answer
stringlengths 17
10.2M
|
|---|
package org.voltdb;
import static com.google_voltpatches.common.base.Preconditions.checkNotNull;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.zookeeper_voltpatches.KeeperException;
import org.apache.zookeeper_voltpatches.KeeperException.NodeExistsException;
import org.apache.zookeeper_voltpatches.ZooKeeper;
import org.apache.zookeeper_voltpatches.data.Stat;
import org.json_voltpatches.JSONException;
import org.json_voltpatches.JSONObject;
import org.json_voltpatches.JSONStringer;
import org.voltcore.logging.Level;
import org.voltcore.logging.VoltLogger;
import org.voltcore.messaging.ForeignHost;
import org.voltcore.messaging.HostMessenger;
import org.voltcore.messaging.Mailbox;
import org.voltcore.network.Connection;
import org.voltcore.utils.CoreUtils;
import org.voltcore.utils.EstTime;
import org.voltcore.utils.RateLimitedLogger;
import org.voltcore.zk.ZKUtil;
import org.voltdb.AuthSystem.AuthUser;
import org.voltdb.SystemProcedureCatalog.Config;
import org.voltdb.catalog.CatalogMap;
import org.voltdb.catalog.Column;
import org.voltdb.catalog.Procedure;
import org.voltdb.catalog.Table;
import org.voltdb.client.BatchTimeoutOverrideType;
import org.voltdb.client.ClientResponse;
import org.voltdb.common.Permission;
import org.voltdb.iv2.Cartographer;
import org.voltdb.iv2.Iv2Trace;
import org.voltdb.iv2.MpInitiator;
import org.voltdb.jni.ExecutionEngine;
import org.voltdb.messaging.Iv2InitiateTaskMessage;
import org.voltdb.messaging.MigratePartitionLeaderMessage;
import org.voltdb.messaging.MultiPartitionParticipantMessage;
import org.voltdb.settings.NodeSettings;
import org.voltdb.sysprocs.saverestore.SnapshotPathType;
import org.voltdb.sysprocs.saverestore.SnapshotUtil;
import org.voltdb.utils.MiscUtils;
import org.voltdb.utils.VoltFile;
import org.voltdb.utils.VoltTrace;
import com.google_voltpatches.common.base.Throwables;
import com.google_voltpatches.common.collect.ImmutableList;
import com.google_voltpatches.common.collect.ImmutableMap;
import com.google_voltpatches.common.util.concurrent.ListenableFuture;
public final class InvocationDispatcher {
private static final VoltLogger log = new VoltLogger(InvocationDispatcher.class.getName());
private static final VoltLogger authLog = new VoltLogger("AUTH");
private static final VoltLogger hostLog = new VoltLogger("HOST");
private static final VoltLogger consoleLog = new VoltLogger("CONSOLE");
public enum OverrideCheck {
NONE(false, false, false),
INVOCATION(false, false, true)
;
final boolean skipAdmimCheck;
final boolean skipPermissionCheck;
final boolean skipInvocationCheck;
OverrideCheck(boolean skipAdminCheck, boolean skipPermissionCheck, boolean skipInvocationCheck) {
this.skipAdmimCheck = skipAdminCheck;
this.skipPermissionCheck = skipPermissionCheck;
this.skipInvocationCheck = skipInvocationCheck;
}
}
/**
* This reference is shared with the one in {@link ClientInterface}
*/
private final AtomicReference<CatalogContext> m_catalogContext;
private final long m_siteId;
private final Mailbox m_mailbox;
//This validator will verify params or per procedure invocation validation.
private final InvocationValidator m_invocationValidator;
private final PermissionValidator m_permissionValidator = new PermissionValidator();
private final Cartographer m_cartographer;
private final ConcurrentMap<Long, ClientInterfaceHandleManager> m_cihm;
private final AtomicReference<Map<Integer,Long>> m_localReplicas = new AtomicReference<>(ImmutableMap.of());
private final SnapshotDaemon m_snapshotDaemon;
private final AtomicBoolean m_isInitialRestore = new AtomicBoolean(true);
private final VoltTable statusTable = new VoltTable(new VoltTable.ColumnInfo("STATUS", VoltType.BIGINT));
private final NTProcedureService m_NTProcedureService;
// Next partition to service adhoc replicated table reads
private static final AtomicInteger m_nextPartition = new AtomicInteger();
// the partition id list, which does not assume starting from 0
private static volatile List<Integer> m_partitionIds;
public final static class Builder {
ClientInterface m_clientInterface;
Cartographer m_cartographer;
AtomicReference<CatalogContext> m_catalogContext;
ConcurrentMap<Long, ClientInterfaceHandleManager> m_cihm;
Mailbox m_mailbox;
ReplicationRole m_replicationRole;
SnapshotDaemon m_snapshotDaemon;
long m_siteId;
public Builder clientInterface(ClientInterface clientInterface) {
m_clientInterface = checkNotNull(clientInterface, "given client interface is null");
return this;
}
public Builder cartographer(Cartographer cartographer) {
m_cartographer = checkNotNull(cartographer, "given cartographer is null");
return this;
}
public Builder catalogContext(AtomicReference<CatalogContext> catalogContext) {
m_catalogContext = checkNotNull(catalogContext, "given catalog context is null");
return this;
}
public Builder clientInterfaceHandleManagerMap(ConcurrentMap<Long, ClientInterfaceHandleManager> cihm) {
m_cihm = checkNotNull(cihm, "given client interface handler manager lookup map is null");
return this;
}
public Builder mailbox(Mailbox mailbox) {
m_mailbox = checkNotNull(mailbox, "given mailbox is null");
return this;
}
public Builder replicationRole(ReplicationRole replicationRole) {
m_replicationRole = checkNotNull(replicationRole, "given replication role is null");
return this;
}
public Builder snapshotDaemon(SnapshotDaemon snapshotDaemon) {
m_snapshotDaemon = checkNotNull(snapshotDaemon,"given snapshot daemon is null");
return this;
}
public Builder siteId(long siteId) {
m_siteId = siteId;
return this;
}
public InvocationDispatcher build() {
return new InvocationDispatcher(
m_clientInterface,
m_cartographer,
m_catalogContext,
m_cihm,
m_mailbox,
m_snapshotDaemon,
m_replicationRole,
m_siteId
);
}
}
public static final Builder builder() {
return new Builder();
}
private InvocationDispatcher(
ClientInterface clientInterface,
Cartographer cartographer,
AtomicReference<CatalogContext> catalogContext,
ConcurrentMap<Long, ClientInterfaceHandleManager> cihm,
Mailbox mailbox,
SnapshotDaemon snapshotDaemon,
ReplicationRole replicationRole,
long siteId)
{
m_siteId = siteId;
m_mailbox = checkNotNull(mailbox, "given mailbox is null");
m_catalogContext = checkNotNull(catalogContext, "given catalog context is null");
m_cihm = checkNotNull(cihm, "given client interface handler manager lookup map is null");
m_invocationValidator = new InvocationValidator(
checkNotNull(replicationRole, "given replication role is null")
);
m_cartographer = checkNotNull(cartographer, "given cartographer is null");
m_snapshotDaemon = checkNotNull(snapshotDaemon,"given snapshot daemon is null");
m_NTProcedureService = new NTProcedureService(clientInterface, this, m_mailbox);
statusTable.addRow(0);
// this kicks off the initial NT procedures being loaded
notifyNTProcedureServiceOfCatalogUpdate();
// update the partition count and partition keys for routing purpose
updatePartitionInformation();
}
/**
* Tells NTProcedureService to pause before stats get smashed during UAC
*/
void notifyNTProcedureServiceOfPreCatalogUpdate() {
m_NTProcedureService.preUpdate();
}
/**
* Tells NTProcedureService to reload NT procedures
*/
void notifyNTProcedureServiceOfCatalogUpdate() {
m_NTProcedureService.update(m_catalogContext.get());
}
public LightweightNTClientResponseAdapter getInternelAdapterNT () {
return m_NTProcedureService.m_internalNTClientAdapter;
}
public static void updatePartitionInformation() {
m_partitionIds = ImmutableList.copyOf(TheHashinator.getCurrentHashinator().getPartitions());
}
/*
* This does a ZK lookup which apparently is full of fail
* if you run TestRejoinEndToEnd. Kind of lame, but initializing this data
* immediately is not critical, request routing works without it.
*
* Populate the map in the background and it will be used to route
* requests to local replicas once the info is available
*/
public Future<?> asynchronouslyDetermineLocalReplicas() {
return VoltDB.instance().getSES(false).submit(new Runnable() {
@Override
public void run() {
/*
* Assemble a map of all local replicas that will be used to determine
* if single part reads can be delivered and executed at local replicas
*/
final int thisHostId = CoreUtils.getHostIdFromHSId(m_mailbox.getHSId());
ImmutableMap.Builder<Integer, Long> localReplicas = ImmutableMap.builder();
for (int partition : m_cartographer.getPartitions()) {
for (Long replica : m_cartographer.getReplicasForPartition(partition)) {
if (CoreUtils.getHostIdFromHSId(replica) == thisHostId) {
localReplicas.put(partition, replica);
}
}
}
m_localReplicas.set(localReplicas.build());
}
});
}
public final ClientResponseImpl dispatch(
StoredProcedureInvocation task,
InvocationClientHandler handler,
Connection ccxn,
AuthUser user,
OverrideCheck bypass,
boolean ntPriority)
{
final long nowNanos = System.nanoTime();
// Deserialize the client's request and map to a catalog stored procedure
final CatalogContext catalogContext = m_catalogContext.get();
String clientInfo = ccxn.getHostnameAndIPAndPort(); // Storing the client's ip information
final String procName = task.getProcName();
final String threadName = Thread.currentThread().getName(); // Thread name has to be materialized here
final StoredProcedureInvocation finalTask = task;
final VoltTrace.TraceEventBatch traceLog = VoltTrace.log(VoltTrace.Category.CI);
if (traceLog != null) {
traceLog.add(() -> VoltTrace.meta("process_name", "name", CoreUtils.getHostnameOrAddress()))
.add(() -> VoltTrace.meta("thread_name", "name", threadName))
.add(() -> VoltTrace.meta("thread_sort_index", "sort_index", Integer.toString(1)))
.add(() -> VoltTrace.beginAsync("recvtxn", finalTask.getClientHandle(),
"name", procName,
"clientHandle", Long.toString(finalTask.getClientHandle())));
}
Procedure catProc = getProcedureFromName(task.getProcName(), catalogContext);
if (catProc == null) {
String errorMessage = "Procedure " + procName + " was not found";
RateLimitedLogger.tryLogForMessage(EstTime.currentTimeMillis(),
60, TimeUnit.SECONDS, authLog, Level.WARN,
errorMessage + ". This message is rate limited to once every 60 seconds."
);
return unexpectedFailureResponse(errorMessage, task.clientHandle);
}
ClientResponseImpl error = null;
// Check for pause mode restrictions before proceeding any further
if ((error = allowPauseModeExecution(handler, catProc, task)) != null) {
if (bypass == null || !bypass.skipAdmimCheck) {
return error;
}
}
if ((error = m_permissionValidator.shouldAccept(procName, user, task, catProc)) != null) {
if (bypass == null || !bypass.skipPermissionCheck) {
return error;
}
}
//Check param deserialization policy for sysprocs
if ((error = m_invocationValidator.shouldAccept(procName, user, task, catProc)) != null) {
if (bypass == null || !bypass.skipInvocationCheck) {
return error;
}
}
//Check individual query timeout value settings with privilege
int batchTimeout = task.getBatchTimeout();
if (BatchTimeoutOverrideType.isUserSetTimeout(batchTimeout)) {
if (! user.hasPermission(Permission.ADMIN)) {
int systemTimeout = catalogContext.cluster.getDeployment().
get("deployment").getSystemsettings().get("systemsettings").getQuerytimeout();
if (systemTimeout != ExecutionEngine.NO_BATCH_TIMEOUT_VALUE &&
(batchTimeout > systemTimeout || batchTimeout == ExecutionEngine.NO_BATCH_TIMEOUT_VALUE)) {
String errorMessage = "The attempted individual query timeout value " + batchTimeout +
" milliseconds override was ignored because the connection lacks ADMIN privileges.";
RateLimitedLogger.tryLogForMessage(EstTime.currentTimeMillis(),
60, TimeUnit.SECONDS,
log, Level.INFO,
errorMessage + " This message is rate limited to once every 60 seconds.");
task.setBatchTimeout(systemTimeout);
}
}
}
// handle non-transactional procedures (INCLUDING NT SYSPROCS)
// note that we also need to check for java for now as transactional flag is
// only 100% when we're talking Java
if ((catProc.getTransactional() == false) && catProc.getHasjava()) {
return dispatchNTProcedure(handler, task, user, ccxn, nowNanos, ntPriority);
}
// check for allPartition invocation and provide a nice error if it's misused
if (task.getAllPartition()) {
// must be single partition and must be partitioned on parameter 0
if (!catProc.getSinglepartition() || (catProc.getPartitionparameter() != 0) || catProc.getSystemproc()) {
return new ClientResponseImpl(ClientResponseImpl.GRACEFUL_FAILURE,
new VoltTable[0], "Invalid procedure for all-partition execution. " +
"Targeted procedure must be partitioned, must be partitioned on the first parameter, " +
"and must not be a system procedure.",
task.clientHandle);
}
}
if (catProc.getSystemproc()) {
// COMMUNITY SYSPROC SPECIAL HANDLING
// ping just responds as fast as possible to show the connection is alive
// nb: ping is not a real procedure, so this is checked before other "sysprocs"
if ("@Ping".equals(procName)) {
return new ClientResponseImpl(ClientResponseImpl.SUCCESS, new VoltTable[]{statusTable}, "SUCCESS", task.clientHandle);
}
else if ("@GetPartitionKeys".equals(procName)) {
return dispatchGetPartitionKeys(task);
}
else if ("@Subscribe".equals(procName)) {
return dispatchSubscribe( handler, task);
}
else if ("@Statistics".equals(procName)) {
return dispatchStatistics(OpsSelector.STATISTICS, task, ccxn);
}
else if ("@SystemCatalog".equals(procName)) {
return dispatchStatistics(OpsSelector.SYSTEMCATALOG, task, ccxn);
}
else if ("@SystemInformation".equals(procName)) {
return dispatchStatistics(OpsSelector.SYSTEMINFORMATION, task, ccxn);
}
else if ("@Trace".equals(procName)) {
return dispatchStatistics(OpsSelector.TRACE, task, ccxn);
}
else if ("@StopNode".equals(procName)) {
CoreUtils.logProcedureInvocation(hostLog, user.m_name, clientInfo, procName);
return dispatchStopNode(task);
}
else if ("@PrepareStopNode".equals(procName)) {
CoreUtils.logProcedureInvocation(hostLog, user.m_name, clientInfo, procName);
return dispatchPrepareStopNode(task);
}
else if ("@LoadSinglepartitionTable".equals(procName)) {
// FUTURE: When we get rid of the legacy hashinator, this should go away
return dispatchLoadSinglepartitionTable(catProc, task, handler, ccxn);
}
else if ("@SnapshotSave".equals(procName)) {
m_snapshotDaemon.requestUserSnapshot(task, ccxn);
return null;
}
else if ("@SnapshotStatus".equals(procName)) {
// SnapshotStatus is really through @Statistics now, but preserve the
// legacy calling mechanism
Object[] params = new Object[] { "SNAPSHOTSTATUS" };
task.setParams(params);
return dispatchStatistics(OpsSelector.STATISTICS, task, ccxn);
}
else if ("@SnapshotScan".equals(procName)) {
return dispatchStatistics(OpsSelector.SNAPSHOTSCAN, task, ccxn);
}
else if ("@SnapshotDelete".equals(procName)) {
return dispatchStatistics(OpsSelector.SNAPSHOTDELETE, task, ccxn);
}
else if ("@SnapshotRestore".equals(procName)) {
ClientResponseImpl retval = SnapshotUtil.transformRestoreParamsToJSON(task);
if (retval != null) {
return retval;
}
if (m_isInitialRestore.compareAndSet(true, false) && shouldLoadSchemaFromSnapshot()) {
m_NTProcedureService.isRestoring = true;
return useSnapshotCatalogToRestoreSnapshotSchema(task, handler, ccxn, user, bypass);
}
}
else if ("@Shutdown".equals(procName)) {
if (task.getParams().size() == 1) {
return takeShutdownSaveSnapshot(task, handler, ccxn, user, bypass);
}
}
else if ("@UpdateLogging".equals(procName)) {
task = appendAuditParams(task, ccxn, user);
}
else if ("@JStack".equals(procName)) {
return dispatchJstack(task);
}
// ERROR MESSAGE FOR PRO SYSPROC USE IN COMMUNITY
if (!MiscUtils.isPro()) {
SystemProcedureCatalog.Config sysProcConfig = SystemProcedureCatalog.listing.get(procName);
if ((sysProcConfig != null) && (sysProcConfig.commercial)) {
return new ClientResponseImpl(ClientResponseImpl.GRACEFUL_FAILURE,
new VoltTable[0],
procName + " is available in the Enterprise Edition of VoltDB only.",
task.clientHandle);
}
}
// Verify that admin mode sysprocs are called from a client on the
// admin port, otherwise return a failure
if ( "@Pause".equals(procName)
|| "@Resume".equals(procName)
|| "@PrepareShutdown".equals(procName)
|| "@CancelShutdown".equals(procName))
{
if (handler.isAdmin() == false) {
return unexpectedFailureResponse(
procName + " is not available to this client",
task.clientHandle);
}
// Log the invocation with user name and ip information
CoreUtils.logProcedureInvocation(hostLog, user.m_name, clientInfo, procName);
}
}
// If you're going to copy and paste something, CnP the pattern
// up above. -rtb.
int[] partitions = null;
do {
try {
partitions = getPartitionsForProcedure(catProc, task);
} catch (Exception e) {
// unable to hash to a site, return an error
return getMispartitionedErrorResponse(task, catProc, e);
}
CreateTransactionResult result = createTransaction(handler.connectionId(), task, catProc.getReadonly(),
catProc.getSinglepartition(), catProc.getEverysite(), partitions, task.getSerializedSize(),
nowNanos);
switch (result) {
case SUCCESS:
return null;
case NO_CLIENT_HANDLER:
/*
* when VoltDB.crash... is called, we close off the client interface and it might not be possible to
* create new transactions. Return an error. Another case is when elastic shrink, the target partition
* may be removed in between the transaction is created
*/
return new ClientResponseImpl(ClientResponseImpl.SERVER_UNAVAILABLE, new VoltTable[0],
"VoltDB failed to create the transaction internally. It is possible this "
+ "was caused by a node failure or intentional shutdown. If the cluster recovers, "
+ "it should be safe to resend the work, as the work was never started.",
task.clientHandle);
case PARTITION_REMOVED:
// Loop back around and try to figure out the partitions again
Thread.yield();
}
} while (true);
}
private final boolean shouldLoadSchemaFromSnapshot() {
CatalogMap<Table> tables = m_catalogContext.get().database.getTables();
if(tables.size() == 0) {
return true;
}
for(Table t : tables) {
if(!t.getSignature().startsWith("VOLTDB_AUTOGEN_XDCR")) {
return false;
}
}
return true;
}
public final static Procedure getProcedureFromName(String procName, CatalogContext catalogContext) {
Procedure catProc = catalogContext.procedures.get(procName);
if (catProc == null) {
catProc = catalogContext.m_defaultProcs.checkForDefaultProcedure(procName);
}
if (catProc == null) {
Config sysProc = SystemProcedureCatalog.listing.get(procName);
if (sysProc != null) {
catProc = sysProc.asCatalogProcedure();
}
}
return catProc;
}
public final static String SHUTDOWN_MSG = "Server is shutting down.";
private final static ClientResponseImpl allowPauseModeExecution(
InvocationClientHandler handler,
Procedure procedure,
StoredProcedureInvocation task)
{
final VoltDBInterface voltdb = VoltDB.instance();
if (voltdb.getMode() == OperationMode.SHUTTINGDOWN) {
return serverUnavailableResponse(
SHUTDOWN_MSG,
task.clientHandle);
}
if (voltdb.isPreparingShuttingdown()) {
if (procedure.getAllowedinshutdown()) {
return null;
}
return serverUnavailableResponse(
SHUTDOWN_MSG,
task.clientHandle);
}
if (voltdb.getMode() != OperationMode.PAUSED || handler.isAdmin()) {
return null;
}
// If we got here, instance is paused and handler is not admin.
final String procName = task.getProcName();
if (procedure.getSystemproc() &&
("@AdHoc".equals(procName) || "@AdHocSpForTest".equals(procName))) {
// AdHoc is handled after it is planned and we figure out if it is read-only or not.
return null;
} else if (!procedure.getReadonly()) {
return serverUnavailableResponse(
"Server is paused and is available in read-only mode - please try again later.",
task.clientHandle);
}
return null;
}
private final static ClientResponseImpl dispatchGetPartitionKeys(StoredProcedureInvocation task) {
Object params[] = task.getParams().toArray();
String typeString = "the type of partition key to return and can be one of " +
"INTEGER, STRING or VARCHAR (equivalent), or VARBINARY";
if (params.length != 1 || params[0] == null) {
return gracefulFailureResponse(
"GetPartitionKeys must have one string parameter specifying " + typeString,
task.clientHandle);
}
if (!(params[0] instanceof String)) {
return gracefulFailureResponse(
"GetPartitionKeys must have one string parameter specifying " + typeString +
" provided type was " + params[0].getClass().getName(), task.clientHandle);
}
VoltType voltType = null;
String typeStr = ((String)params[0]).trim().toUpperCase();
if ("INTEGER".equals(typeStr)) {
voltType = VoltType.INTEGER;
} else if ("STRING".equals(typeStr) || "VARCHAR".equals(typeStr)) {
voltType = VoltType.STRING;
} else if ("VARBINARY".equals(typeStr)) {
voltType = VoltType.VARBINARY;
} else {
return gracefulFailureResponse(
"Type " + typeStr + " is not a supported type of partition key, " + typeString,
task.clientHandle);
}
VoltTable partitionKeys = TheHashinator.getPartitionKeys(voltType);
if (partitionKeys == null) {
return gracefulFailureResponse(
"Type " + typeStr + " is not a supported type of partition key, " + typeString,
task.clientHandle);
}
return new ClientResponseImpl(ClientResponse.SUCCESS, new VoltTable[] { partitionKeys }, null, task.clientHandle);
}
private static ClientResponseImpl dispatchJstack(StoredProcedureInvocation task) {
Object params[] = task.getParams().toArray();
if (params.length != 1 || params[0] == null) {
return gracefulFailureResponse(
"@JStack must provide hostId",
task.clientHandle);
}
if (!(params[0] instanceof Integer)) {
return gracefulFailureResponse(
"@JStack must have one Integer parameter specified. Provided type was " + params[0].getClass().getName(),
task.clientHandle);
}
int ihid = (Integer) params[0];
final HostMessenger hostMessenger = VoltDB.instance().getHostMessenger();
Set<Integer> liveHids = hostMessenger.getLiveHostIds();
if (ihid >=0 && !liveHids.contains(ihid)) {
return gracefulFailureResponse(
"Invalid Host Id or Host Id not member of cluster: " + ihid,
task.clientHandle);
}
boolean success = true;
if (ihid < 0) { // all hosts
//collect thread dumps
String dumpDir = new File(VoltDB.instance().getVoltDBRootPath(), "thread_dumps").getAbsolutePath();
String fileName = hostMessenger.getHostname() + "_host-" + hostMessenger.getHostId() + "_" + System.currentTimeMillis()+".jstack";
success = VoltDB.dumpThreadTraceToFile(dumpDir, fileName );
liveHids.remove(hostMessenger.getHostId());
hostMessenger.sendPoisonPill(liveHids, "@Jstack called", ForeignHost.PRINT_STACKTRACE);
} else if (ihid == hostMessenger.getHostId()) { // only local
//collect thread dumps
String dumpDir = new File(VoltDB.instance().getVoltDBRootPath(), "thread_dumps").getAbsolutePath();
String fileName = hostMessenger.getHostname() + "_host-" + hostMessenger.getHostId() + "_" + System.currentTimeMillis()+".jstack";
success = VoltDB.dumpThreadTraceToFile(dumpDir, fileName );
} else { // only remote
hostMessenger.sendPoisonPill(ihid, "@Jstack called", ForeignHost.PRINT_STACKTRACE);
}
if (success) {
return new ClientResponseImpl(ClientResponse.SUCCESS, new VoltTable[0], "SUCCESS", task.clientHandle);
}
return gracefulFailureResponse(
"Failed to create the thread dump of " + ((ihid < 0) ? "all hosts." : "Host Id " + ihid + "."),
task.clientHandle);
}
private final ClientResponseImpl dispatchSubscribe(InvocationClientHandler handler, StoredProcedureInvocation task) {
final ParameterSet ps = task.getParams();
final Object params[] = ps.toArray();
String err = null;
final ClientInterfaceHandleManager cihm = m_cihm.get(handler.connectionId());
//Not sure if it can actually be null, not really important if it is
if (cihm == null) {
return null;
}
for (int ii = 0; ii < params.length; ii++) {
final Object param = params[ii];
if (param == null) {
err = "Parameter index " + ii + " was null"; break;
}
if (!(param instanceof String)) {
err = "Parameter index " + ii + " was not a String"; break;
}
if ("TOPOLOGY".equals(param)) {
cihm.setWantsTopologyUpdates(true);
} else {
err = "Parameter \"" + param + "\" is not recognized/supported"; break;
}
}
return new ClientResponseImpl(
err == null ? ClientResponse.SUCCESS : ClientResponse.GRACEFUL_FAILURE,
new VoltTable[] { },
err,
task.clientHandle);
}
final static ClientResponseImpl dispatchStatistics(OpsSelector selector, StoredProcedureInvocation task, Connection ccxn) {
try {
OpsAgent agent = VoltDB.instance().getOpsAgent(selector);
if (agent != null) {
agent.performOpsAction(ccxn, task.clientHandle, selector, task.getParams());
}
else {
return errorResponse(ccxn, task.clientHandle, ClientResponse.GRACEFUL_FAILURE,
"Unknown OPS selector", null, true);
}
return null;
} catch (Exception e) {
return errorResponse( ccxn, task.clientHandle, ClientResponse.UNEXPECTED_FAILURE, null, e, true);
}
}
private ClientResponseImpl dispatchStopNode(StoredProcedureInvocation task) {
Object params[] = task.getParams().toArray();
if (params.length != 1 || params[0] == null) {
return gracefulFailureResponse(
"@StopNode must provide hostId",
task.clientHandle);
}
if (!(params[0] instanceof Integer)) {
return gracefulFailureResponse(
"@StopNode must have one Integer parameter specified. Provided type was " + params[0].getClass().getName(),
task.clientHandle);
}
int ihid = (Integer) params[0];
final HostMessenger hostMessenger = VoltDB.instance().getHostMessenger();
Set<Integer> liveHids = hostMessenger.getLiveHostIds();
if (!liveHids.contains(ihid)) {
return gracefulFailureResponse(
"Invalid Host Id or Host Id not member of cluster: " + ihid,
task.clientHandle);
}
String reason = m_cartographer.stopNodeIfClusterIsSafe(liveHids, ihid);
if (reason != null) {
hostLog.info("It's unsafe to shutdown node " + ihid
+ ". Cannot stop the requested node. " + reason
+ ". Use shutdown to stop the cluster.");
return gracefulFailureResponse(
"It's unsafe to shutdown node " + ihid
+ ". Cannot stop the requested node. " + reason
+ ". Use shutdown to stop the cluster.", task.clientHandle);
}
return new ClientResponseImpl(ClientResponse.SUCCESS, new VoltTable[0], "SUCCESS", task.clientHandle);
}
private ClientResponseImpl dispatchPrepareStopNode(StoredProcedureInvocation task) {
Object params[] = task.getParams().toArray();
if (params.length != 1 || params[0] == null) {
return gracefulFailureResponse(
"@PrepareStopNode must provide hostId",
task.clientHandle);
}
if (!(params[0] instanceof Integer)) {
return gracefulFailureResponse(
"@PrepareStopNode must have one Integer parameter specified. Provided type was " + params[0].getClass().getName(),
task.clientHandle);
}
int ihid = (Integer) params[0];
final HostMessenger hostMessenger = VoltDB.instance().getHostMessenger();
Set<Integer> liveHids = hostMessenger.getLiveHostIds();
if (!liveHids.contains(ihid)) {
return gracefulFailureResponse("@PrepareStopNode: " + ihid + " is not valid.", task.clientHandle);
}
String reason = m_cartographer.verifyPartitonLeaderMigrationForStopNode(ihid);
if (reason != null) {
return gracefulFailureResponse(
"@PrepareStopNode:" + reason, task.clientHandle);
}
// The host has partition masters, go ahead to move them
if (m_cartographer.getMasterCount(ihid) > 0) {
// shutdown partition leader migration
MigratePartitionLeaderMessage message = new MigratePartitionLeaderMessage(ihid, Integer.MIN_VALUE);
for (Integer integer : liveHids) {
m_mailbox.send(CoreUtils.getHSIdFromHostAndSite(integer,
HostMessenger.CLIENT_INTERFACE_SITE_ID), message);
}
// start leader migration on this node
message = new MigratePartitionLeaderMessage(ihid, Integer.MIN_VALUE);
message.setStartTask();
message.setStopNodeService();
m_mailbox.send(CoreUtils.getHSIdFromHostAndSite(ihid, HostMessenger.CLIENT_INTERFACE_SITE_ID), message);
}
return new ClientResponseImpl(ClientResponse.SUCCESS, new VoltTable[0], "SUCCESS", task.clientHandle);
}
public final ClientResponseImpl dispatchNTProcedure(InvocationClientHandler handler,
StoredProcedureInvocation task,
AuthUser user,
Connection ccxn,
long nowNanos,
boolean ntPriority)
{
// get the CIHM
long connectionId = handler.connectionId();
final ClientInterfaceHandleManager cihm = m_cihm.get(connectionId);
if (cihm == null) {
hostLog.rateLimitedLog(60, Level.WARN, null,
"Dispatch Non-Transactional Procedure request rejected. "
+ "This is likely due to VoltDB ceasing client communication as it "
+ "shuts down.");
// when VoltDB.crash... is called, we close off the client interface
// and it might not be possible to create new transactions.
// Return an error.
return new ClientResponseImpl(ClientResponseImpl.SERVER_UNAVAILABLE,
new VoltTable[0],
"VoltDB failed to create the transaction internally. It is possible this "
+ "was caused by a node failure or intentional shutdown. If the cluster recovers, "
+ "it should be safe to resend the work, as the work was never started.",
task.clientHandle);
}
// This handle is needed for backpressure. It identifies this transaction to the ACG and
// increments backpressure. When the response is sent (by sending an InitiateResponseMessage
// to the CI mailbox, the backpressure associated with this handle will go away.
// Sadly, many of the value's here are junk.
long handle = cihm.getHandle(true,
ClientInterface.NTPROC_JUNK_ID,
task.clientHandle,
task.getSerializedSize(),
nowNanos,
task.getProcName(),
ClientInterface.NTPROC_JUNK_ID,
false);
// note, once we get the handle above, any response to the client MUST be done
// by sending an InitiateResponseMessage to the CI mailbox. Writing bytes to the wire, like we
// do at the top of this method won't release any backpressure accounting.
// actually kick off the NT proc
m_NTProcedureService.callProcedureNT(handle,
user,
ccxn,
handler.isAdmin(),
ntPriority,
task);
return null;
}
private StoredProcedureInvocation appendAuditParams(StoredProcedureInvocation task,
Connection ccxn, AuthSystem.AuthUser user) {
String username = user.m_name;
if (username == null) {
username = "An anonymous user";
}
String remoteHost = ccxn.getRemoteSocketAddress().toString();
String xml = (String)task.getParams().toArray()[0];
StoredProcedureInvocation spi = new StoredProcedureInvocation();
spi.setProcName(task.getProcName());
spi.setParams(username, remoteHost, xml);
spi.setClientHandle(task.getClientHandle());
spi.setBatchTimeout(task.getBatchTimeout());
spi.type = task.getType();
spi.setAllPartition(task.getAllPartition());
return spi;
}
/**
* Send a command log replay sentinel to the given partition.
* @param txnId
* @param partitionId
*/
public final void sendSentinel(long txnId, int partitionId) {
final Long initiatorHSId = m_cartographer.getHSIdForSinglePartitionMaster(partitionId);
if (initiatorHSId == null) {
log.error("InvocationDispatcher.sendSentinel: Master does not exist for partition: " + partitionId);
} else {
sendSentinel(txnId, initiatorHSId, -1, -1, true);
}
}
private final void sendSentinel(long txnId, long initiatorHSId, long ciHandle,
long connectionId, boolean forReplay) {
//The only field that is relevant is txnid, and forReplay.
MultiPartitionParticipantMessage mppm =
new MultiPartitionParticipantMessage(
m_siteId,
initiatorHSId,
txnId,
ciHandle,
connectionId,
false, // isReadOnly
forReplay); // isForReplay
m_mailbox.send(initiatorHSId, mppm);
}
/**
* Coward way out of the legacy hashinator hell. LoadSinglepartitionTable gets the
* partitioning parameter as a byte array. Legacy hashinator hashes numbers and byte arrays
* differently, so have to convert it back to long if it's a number. UGLY!!!
*/
private final ClientResponseImpl dispatchLoadSinglepartitionTable(Procedure catProc,
StoredProcedureInvocation task,
InvocationClientHandler handler,
Connection ccxn)
{
int partition = -1;
try {
CatalogMap<Table> tables = m_catalogContext.get().database.getTables();
int partitionParamType = getLoadSinglePartitionTablePartitionParamType(tables, task);
byte[] valueToHash = (byte[])task.getParameterAtIndex(0);
partition = TheHashinator.getPartitionForParameter(partitionParamType, valueToHash);
}
catch (Exception e) {
authLog.warn(e.getMessage());
return new ClientResponseImpl(ClientResponseImpl.UNEXPECTED_FAILURE,
new VoltTable[0], e.getMessage(), task.clientHandle);
}
assert(partition != -1);
createTransaction(handler.connectionId(),
task,
catProc.getReadonly(),
catProc.getSinglepartition(),
catProc.getEverysite(),
new int[] { partition },
task.getSerializedSize(),
System.nanoTime());
return null;
}
/**
* XXX: This should go away when we get rid of the legacy hashinator.
*/
private final static int getLoadSinglePartitionTablePartitionParamType(CatalogMap<Table> tables,
StoredProcedureInvocation spi)
throws Exception
{
String tableName = (String) spi.getParameterAtIndex(1);
// get the table from the catalog
Table catTable = tables.getIgnoreCase(tableName);
if (catTable == null) {
throw new Exception(String .format("Unable to find target table \"%s\" for LoadSinglepartitionTable.",
tableName));
}
Column pCol = catTable.getPartitioncolumn();
return pCol.getType();
}
public void setReplicationRole(ReplicationRole role) {
m_invocationValidator.setReplicationRole(role);
}
private final static void transmitResponseMessage(ClientResponse r, Connection ccxn, long handle) {
ClientResponseImpl response = ClientResponseImpl.class.cast(r);
response.setClientHandle(handle);
ByteBuffer buf = ByteBuffer.allocate(response.getSerializedSize() + 4);
buf.putInt(buf.capacity() - 4);
response.flattenToBuffer(buf).flip();
ccxn.writeStream().enqueue(buf);
}
private final ClientResponseImpl takeShutdownSaveSnapshot(
final StoredProcedureInvocation task,
final InvocationClientHandler handler, final Connection ccxn,
final AuthUser user, OverrideCheck bypass
)
{
Object p0 = task.getParams().getParam(0);
final long zkTxnId;
if (p0 instanceof Long) {
zkTxnId = ((Long)p0).longValue();
} else if (p0 instanceof String) {
try {
zkTxnId = Long.parseLong((String)p0);
} catch (NumberFormatException e) {
return gracefulFailureResponse(
"Incorrect argument type",
task.clientHandle);
}
} else {
return gracefulFailureResponse(
"Incorrect argument type",
task.clientHandle);
}
VoltDBInterface voltdb = VoltDB.instance();
if (!voltdb.isPreparingShuttingdown()) {
log.warn("Ignoring shutdown save snapshot request as VoltDB is not shutting down");
return unexpectedFailureResponse(
"Ignoring shutdown save snapshot request as VoltDB is not shutting down",
task.clientHandle);
}
final ZooKeeper zk = voltdb.getHostMessenger().getZK();
// network threads are blocked from making zookeeper calls
Future<Long> fut = voltdb.getSES(true).submit(new Callable<Long>() {
@Override
public Long call() {
try {
Stat stat = zk.exists(VoltZK.operationMode, false);
if (stat == null) {
VoltDB.crashLocalVoltDB("cluster operation mode zookeeper node does not exist");
return Long.MIN_VALUE;
}
return stat.getMzxid();
} catch (KeeperException | InterruptedException e) {
VoltDB.crashLocalVoltDB("Failed to stat the cluster operation zookeeper node", true, e);
return Long.MIN_VALUE;
}
}
});
try {
if (fut.get().longValue() != zkTxnId) {
return unexpectedFailureResponse(
"Internal error: cannot write a startup snapshot because the " +
"current system state is not consistent with an orderly shutdown. " +
"Please try \"voltadmin shutdown --save\" again.",
task.clientHandle);
}
} catch (InterruptedException | ExecutionException e1) {
VoltDB.crashLocalVoltDB("Failed to stat the cluster operation zookeeper node", true, e1);
return null;
}
NodeSettings paths = m_catalogContext.get().getNodeSettings();
String data;
try {
data = new JSONStringer()
.object()
.keySymbolValuePair(SnapshotUtil.JSON_TERMINUS, zkTxnId)
.endObject()
.toString();
} catch (JSONException e) {
VoltDB.crashLocalVoltDB("Failed to create startup snapshot save command", true, e);
return null;
}
log.info("Saving startup snapshot");
consoleLog.info("Taking snapshot to save database contents");
final SimpleClientResponseAdapter alternateAdapter = new SimpleClientResponseAdapter(
ClientInterface.SHUTDONW_SAVE_CID, "Blocking Startup Snapshot Save"
);
final InvocationClientHandler alternateHandler = new InvocationClientHandler() {
@Override
public boolean isAdmin() {
return handler.isAdmin();
}
@Override
public long connectionId() {
return ClientInterface.SHUTDONW_SAVE_CID;
}
};
final long sourceHandle = task.clientHandle;
task.setClientHandle(alternateAdapter.registerCallback(SimpleClientResponseAdapter.NULL_CALLBACK));
SnapshotUtil.SnapshotResponseHandler savCallback = new SnapshotUtil.SnapshotResponseHandler() {
@Override
public void handleResponse(ClientResponse r) {
if (r == null) {
String msg = "Snapshot save failed. The database is paused and the shutdown has been cancelled";
transmitResponseMessage(gracefulFailureResponse(msg, sourceHandle), ccxn, sourceHandle);
}
if (r.getStatus() != ClientResponse.SUCCESS) {
String msg = "Snapshot save failed: "
+ r.getStatusString()
+ ". The database is paused and the shutdown has been cancelled";
ClientResponseImpl resp = new ClientResponseImpl(
ClientResponse.GRACEFUL_FAILURE,
r.getResults(),
msg,
sourceHandle);
transmitResponseMessage(resp, ccxn, sourceHandle);
}
consoleLog.info("Snapshot taken successfully");
task.setParams();
dispatch(task, alternateHandler, alternateAdapter, user, bypass, false);
}
};
// network threads are blocked from making zookeeper calls
final byte [] guardContent = data.getBytes(StandardCharsets.UTF_8);
Future<Boolean> guardFuture = voltdb.getSES(true).submit(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
try {
ZKUtil.asyncMkdirs(zk, VoltZK.shutdown_save_guard, guardContent).get();
} catch (NodeExistsException itIsOk) {
return false;
} catch (InterruptedException | KeeperException e) {
VoltDB.crashLocalVoltDB("Failed to create shutdown save guard zookeeper node", true, e);
return false;
}
return true;
}
});
boolean created;
try {
created = guardFuture.get().booleanValue();
} catch (InterruptedException | ExecutionException e) {
VoltDB.crashLocalVoltDB("Failed to create shutdown save guard zookeeper node", true, e);
return null;
}
if (!created) {
return unexpectedFailureResponse(
"Internal error: detected concurrent invocations of \"voltadmin shutdown --save\"",
task.clientHandle);
}
voltdb.getClientInterface().bindAdapter(alternateAdapter, null);
SnapshotUtil.requestSnapshot(
sourceHandle,
paths.resolveToAbsolutePath(paths.getSnapshoth()).toPath().toUri().toString(),
SnapshotUtil.getShutdownSaveNonce(zkTxnId),
true,
SnapshotFormat.NATIVE,
SnapshotPathType.SNAP_AUTO,
data,
savCallback,
true
);
return null;
}
private final File getSnapshotCatalogFile(JSONObject snapJo) throws JSONException {
NodeSettings paths = m_catalogContext.get().getNodeSettings();
String catFN = snapJo.getString(SnapshotUtil.JSON_NONCE) + ".jar";
SnapshotPathType pathType = SnapshotPathType.valueOf(
snapJo.optString(SnapshotUtil.JSON_PATH_TYPE, SnapshotPathType.SNAP_PATH.name()));
switch(pathType) {
case SNAP_AUTO:
return new File(paths.resolveToAbsolutePath(paths.getSnapshoth()), catFN);
case SNAP_CL:
return new File(paths.resolveToAbsolutePath(paths.getCommandLogSnapshot()), catFN);
default:
File snapDH = new VoltFile(snapJo.getString(SnapshotUtil.JSON_PATH));
return new File(snapDH, catFN);
}
}
private final ClientResponseImpl useSnapshotCatalogToRestoreSnapshotSchema(
final StoredProcedureInvocation task,
final InvocationClientHandler handler, final Connection ccxn,
final AuthUser user, OverrideCheck bypass
)
{
CatalogContext catalogContext = m_catalogContext.get();
if (!catalogContext.cluster.getUseddlschema()) {
return gracefulFailureResponse(
"Cannot restore catalog from snapshot when schema is set to catalog in the deployment.",
task.clientHandle);
}
log.info("No schema found. Restoring schema and procedures from snapshot.");
try {
JSONObject jsObj = new JSONObject(task.getParams().getParam(0).toString());
final File catalogFH = getSnapshotCatalogFile(jsObj);
final byte[] catalog;
try {
catalog = MiscUtils.fileToBytes(catalogFH);
} catch (IOException e) {
log.warn("Unable to access file " + catalogFH, e);
return unexpectedFailureResponse(
"Unable to access file " + catalogFH,
task.clientHandle);
}
final String dep = new String(catalogContext.getDeploymentBytes(), StandardCharsets.UTF_8);
final StoredProcedureInvocation catalogUpdateTask = new StoredProcedureInvocation();
catalogUpdateTask.setProcName("@UpdateApplicationCatalog");
catalogUpdateTask.setParams(catalog,dep);
//A connection with positive id will be thrown into live client statistics. The connection does not support stats.
//Thus make the connection id as a negative constant to skip the stats collection.
final SimpleClientResponseAdapter alternateAdapter = new SimpleClientResponseAdapter(
ClientInterface.RESTORE_SCHEMAS_CID, "Empty database snapshot restore catalog update"
);
final InvocationClientHandler alternateHandler = new InvocationClientHandler() {
@Override
public boolean isAdmin() {
return handler.isAdmin();
}
@Override
public long connectionId() {
return ClientInterface.RESTORE_SCHEMAS_CID;
}
};
final long sourceHandle = task.clientHandle;
SimpleClientResponseAdapter.SyncCallback restoreCallback =
new SimpleClientResponseAdapter.SyncCallback()
;
final ListenableFuture<ClientResponse> onRestoreComplete =
restoreCallback.getResponseFuture()
;
onRestoreComplete.addListener(new Runnable() {
@Override
public void run() {
ClientResponse r;
try {
r = onRestoreComplete.get();
} catch (ExecutionException|InterruptedException e) {
VoltDB.crashLocalVoltDB("Should never happen", true, e);
return;
}
transmitResponseMessage(r, ccxn, sourceHandle);
}
},
CoreUtils.SAMETHREADEXECUTOR);
task.setClientHandle(alternateAdapter.registerCallback(restoreCallback));
SimpleClientResponseAdapter.SyncCallback catalogUpdateCallback =
new SimpleClientResponseAdapter.SyncCallback()
;
final ListenableFuture<ClientResponse> onCatalogUpdateComplete =
catalogUpdateCallback.getResponseFuture()
;
onCatalogUpdateComplete.addListener(new Runnable() {
@Override
public void run() {
ClientResponse r;
try {
r = onCatalogUpdateComplete.get();
} catch (ExecutionException|InterruptedException e) {
VoltDB.crashLocalVoltDB("Should never happen", true, e);
return;
}
if (r.getStatus() != ClientResponse.SUCCESS) {
transmitResponseMessage(r, ccxn, sourceHandle);
log.error("Received error response for updating catalog " + r.getStatusString());
return;
}
m_catalogContext.set(VoltDB.instance().getCatalogContext());
dispatch(task, alternateHandler, alternateAdapter, user, bypass, false);
}
},
CoreUtils.SAMETHREADEXECUTOR);
catalogUpdateTask.setClientHandle(alternateAdapter.registerCallback(catalogUpdateCallback));
VoltDB.instance().getClientInterface().bindAdapter(alternateAdapter, null);
// dispatch the catalog update
dispatchNTProcedure(alternateHandler, catalogUpdateTask, user, alternateAdapter, System.nanoTime(), false);
}
catch (JSONException e) {
return unexpectedFailureResponse("Unable to parse parameters.", task.clientHandle);
}
return null;
}
// Wrap API to SimpleDtxnInitiator - mostly for the future
public CreateTransactionResult createTransaction(
final long connectionId,
final StoredProcedureInvocation invocation,
final boolean isReadOnly,
final boolean isSinglePartition,
final boolean isEveryPartition,
final int[] partitions,
final int messageSize,
final long nowNanos)
{
return createTransaction(
connectionId,
Iv2InitiateTaskMessage.UNUSED_MP_TXNID,
0, //unused timestammp
invocation,
isReadOnly,
isSinglePartition,
isEveryPartition,
partitions,
messageSize,
nowNanos,
false); // is for replay.
}
// Wrap API to SimpleDtxnInitiator - mostly for the future
public CreateTransactionResult createTransaction(
final long connectionId,
final long txnId,
final long uniqueId,
final StoredProcedureInvocation invocation,
final boolean isReadOnly,
final boolean isSinglePartition,
final boolean isEveryPartition,
final int[] partitions,
final int messageSize,
long nowNanos,
final boolean isForReplay)
{
assert(!isSinglePartition || (partitions.length == 1));
final ClientInterfaceHandleManager cihm = m_cihm.get(connectionId);
if (cihm == null) {
hostLog.rateLimitedLog(60, Level.WARN, null,
"InvocationDispatcher.createTransaction request rejected. "
+ "This is likely due to VoltDB ceasing client communication as it "
+ "shuts down.");
return CreateTransactionResult.NO_CLIENT_HANDLER;
}
Long initiatorHSId = null;
boolean isShortCircuitRead = false;
/*
* Send the read to the partition leader only
* @MigratePartitionLeader always goes to partition leader
*/
if (isSinglePartition && !isEveryPartition) {
initiatorHSId = m_cartographer.getHSIdForSinglePartitionMaster(partitions[0]);
} else {
// Multi-part transactions go to the multi-part coordinator
initiatorHSId = m_cartographer.getHSIdForMultiPartitionInitiator();
// Treat all MP reads as short-circuit since they can run out-of-order
// from their arrival order due to the MP Read-only execution pool
if (isReadOnly) {
isShortCircuitRead = true;
}
}
if (initiatorHSId == null) {
hostLog.rateLimitedLog(60, Level.INFO, null,
String.format(
"InvocationDispatcher.createTransaction request rejected for partition %d invocation %s."
+ " isReadOnly=%s isSinglePartition=%s, isEveryPartition=%s isForReplay=%s."
+ " This is likely due to partition leader being removed during elastic shrink.",
(isSinglePartition && !isEveryPartition) ? partitions[0] : 16383, invocation, isReadOnly,
isSinglePartition, isEveryPartition, isForReplay));
return CreateTransactionResult.PARTITION_REMOVED;
}
long handle = cihm.getHandle(isSinglePartition, isSinglePartition ? partitions[0] : -1, invocation.getClientHandle(),
messageSize, nowNanos, invocation.getProcName(), initiatorHSId, isShortCircuitRead);
Iv2InitiateTaskMessage workRequest =
new Iv2InitiateTaskMessage(m_siteId,
initiatorHSId,
Iv2InitiateTaskMessage.UNUSED_TRUNC_HANDLE,
txnId,
uniqueId,
isReadOnly,
isSinglePartition,
(partitions == null) || (partitions.length < 2) ? null : partitions,
invocation,
handle,
connectionId,
isForReplay);
Long finalInitiatorHSId = initiatorHSId;
final VoltTrace.TraceEventBatch traceLog = VoltTrace.log(VoltTrace.Category.CI);
if (traceLog != null) {
traceLog.add(() -> VoltTrace.instantAsync("inittxn",
invocation.getClientHandle(),
"clientHandle", Long.toString(invocation.getClientHandle()),
"ciHandle", Long.toString(handle),
"partitions", partitions.toString(),
"dest", CoreUtils.hsIdToString(finalInitiatorHSId)));
}
Iv2Trace.logCreateTransaction(workRequest);
m_mailbox.send(initiatorHSId, workRequest);
return CreateTransactionResult.SUCCESS;
}
final static int[] getPartitionsForProcedure(Procedure procedure, StoredProcedureInvocation task) {
final CatalogContext.ProcedurePartitionInfo ppi =
(CatalogContext.ProcedurePartitionInfo) procedure.getAttachment();
if (procedure.getSinglepartition()) {
// break out the Hashinator and calculate the appropriate partition
Object invocationParameter = task.getParameterAtIndex(ppi.index);
if (invocationParameter == null && procedure.getReadonly()) {
// AdHoc replicated table reads are optimized as single partition,
// but without partition params, since replicated table reads can
// be done on any partition, round-robin the procedure to local
// partitions to spread the traffic.
assert (task.getProcName().equals("@AdHoc_RO_SP")): task.getProcName();
List<Integer> partitionIds = m_partitionIds;
int partitionIdIndex = Math.abs(m_nextPartition.getAndIncrement()) % partitionIds.size();
int partitionId = partitionIds.get(partitionIdIndex);
return new int[] {partitionId};
}
return new int[] { TheHashinator.getPartitionForParameter(ppi.type, invocationParameter) };
} else if (procedure.getPartitioncolumn2() != null) {
// two-partition procedure
VoltType partitionParamType1 = VoltType.get((byte)procedure.getPartitioncolumn().getType());
VoltType partitionParamType2 = VoltType.get((byte)procedure.getPartitioncolumn2().getType());
Object invocationParameter1 = task.getParameterAtIndex(procedure.getPartitionparameter());
Object invocationParameter2 = task.getParameterAtIndex(procedure.getPartitionparameter2());
int p1 = TheHashinator.getPartitionForParameter(partitionParamType1, invocationParameter1);
int p2 = TheHashinator.getPartitionForParameter(partitionParamType2, invocationParameter2);
return new int[] { p1, p2 };
} else {
// multi-partition procedure
return new int[] { MpInitiator.MP_INIT_PID };
}
}
//Generate a mispartitioned response also log the message.
private final static ClientResponseImpl getMispartitionedErrorResponse(StoredProcedureInvocation task,
Procedure catProc, Exception ex) {
Object invocationParameter = null;
try {
invocationParameter = task.getParameterAtIndex(catProc.getPartitionparameter());
} catch (Exception ex2) {
}
String exMsg = "Unknown";
if (ex != null) {
exMsg = ex.getMessage();
}
String errorMessage = "Error sending procedure " + task.getProcName()
+ " to the correct partition. Make sure parameter values are correct."
+ " Parameter value " + invocationParameter
+ ", partition column " + catProc.getPartitioncolumn().getName()
+ " type " + catProc.getPartitioncolumn().getType()
+ " Message: " + exMsg;
authLog.warn(errorMessage);
ClientResponseImpl clientResponse = new ClientResponseImpl(ClientResponse.UNEXPECTED_FAILURE,
new VoltTable[0], errorMessage, task.clientHandle);
return clientResponse;
}
private final static ClientResponseImpl errorResponse(Connection c, long handle, byte status, String reason, Exception e, boolean log) {
String realReason = reason;
if (e != null) {
realReason = Throwables.getStackTraceAsString(e);
}
if (log) {
hostLog.warn(realReason);
}
return new ClientResponseImpl(status, new VoltTable[0], realReason, handle);
}
private final static ClientResponseImpl unexpectedFailureResponse(String msg, long handle) {
return new ClientResponseImpl(ClientResponseImpl.UNEXPECTED_FAILURE, new VoltTable[0], msg, handle);
}
private final static ClientResponseImpl gracefulFailureResponse(String msg, long handle) {
return new ClientResponseImpl(ClientResponseImpl.GRACEFUL_FAILURE, new VoltTable[0], msg, handle);
}
private final static ClientResponseImpl serverUnavailableResponse(String msg, long handle) {
return new ClientResponseImpl(ClientResponseImpl.SERVER_UNAVAILABLE, new VoltTable[0], msg, handle);
}
/**
* Currently passes failure notices to NTProcedureService
*/
void handleFailedHosts(Set<Integer> failedHosts) {
m_NTProcedureService.handleCallbacksForFailedHosts(failedHosts);
}
/**
* Passes responses to NTProcedureService
*/
public void handleAllHostNTProcedureResponse(ClientResponseImpl clientResponseData) {
long handle = clientResponseData.getClientHandle();
ProcedureRunnerNT runner = m_NTProcedureService.m_outstanding.get(handle);
if (runner == null) {
hostLog.info("Run everywhere NTProcedure early returned, probably gets timed out.");
return;
}
runner.allHostNTProcedureCallback(clientResponseData);
}
/** test only */
long countNTWaitingProcs() {
return m_NTProcedureService.m_outstanding.size();
}
}
|
package edu.kit.iti.formal.pse.worthwhile.prover;
import java.util.Map;
import edu.kit.iti.formal.pse.worthwhile.interpreter.Value;
import edu.kit.iti.formal.pse.worthwhile.model.ast.Expression;
import edu.kit.iti.formal.pse.worthwhile.model.ast.Program;
/**
* Facade class for the {@link prover} package.
*/
public class SpecificationChecker {
/**
* Time delta in seconds after which a prover call times out.
*/
private Integer timeout = 0;
/**
* @return the timeout
*/
public Integer getTimeout() {
// begin-user-code
return this.timeout;
// end-user-code
}
/**
* @param timeout
* the timeout to set
*/
public void setTimeout(Integer timeout) {
// begin-user-code
this.timeout = timeout;
// end-user-code
}
/**
* The {@link ProverCaller} that is called for checking the satisfiability of formulae.
*/
private ProverCaller prover;
/**
* @return the prover
*/
public ProverCaller getProver() {
// begin-user-code
return this.prover;
// end-user-code
}
/**
* @param prover
* the prover to set
*/
public void setProver(ProverCaller prover) {
// begin-user-code
this.prover = prover;
// end-user-code
}
/**
* The {@link FormulaGenerator} that is called for generating a formula from a {@link Program}.
*/
private FormulaGenerator transformer;
/**
* @return the transformer
*/
public FormulaGenerator getTransformer() {
// begin-user-code
return this.transformer;
// end-user-code
}
/**
* @param transformer
* the transformer to set
*/
public void setTransformer(FormulaGenerator transformer) {
// begin-user-code
this.transformer = transformer;
// end-user-code
}
/**
* The result of the last call to {@link prover}.
*/
private ProverResult checkResult;
/**
* @return the checkResult
*/
public ProverResult getCheckResult() {
// begin-user-code
return this.checkResult;
// end-user-code
}
/**
* @param checkResult
* the checkResult to set
*/
public void setCheckResult(ProverResult checkResult) {
// begin-user-code
this.checkResult = checkResult;
// end-user-code
}
/**
* Uses {@link WPStrategy} as {@link transformer}.
*/
public SpecificationChecker() {
// begin-user-code
// TODO Auto-generated constructor stub
// end-user-code
}
/**
* @param transformer
* Is called to transform {@link Program}s into formulae.
*/
public SpecificationChecker(FormulaGenerator transformer) {
// begin-user-code
// TODO Auto-generated constructor stub
// end-user-code
}
/**
* @param formula
* the {@link Expression} to check
* @param environment
* a list of variable values and axioms
* @return the {@link Validity} of <code>formula</code> when <code>environment</code> is applied
*/
public Validity checkFormula(Expression formula, Map<String, Value> environment) {
// begin-user-code
// TODO Auto-generated method stub
return null;
// end-user-code
}
/**
* @param program
* the {@link Program} to check
* @return the {@link Validity} of <code>program</code>
*/
public Validity checkProgram(Program program) {
// begin-user-code
// TODO Auto-generated method stub
return null;
// end-user-code
}
}
|
package net.somethingdreadful.MAL;
import android.content.res.Configuration;
import org.holoeverywhere.ThemeManager;
import org.holoeverywhere.app.Application;
import java.util.Locale;
public class Theme extends Application {
Locale locale;
@Override
public void onCreate() {
super.onCreate();
PrefManager Prefs = new PrefManager(getApplicationContext());
locale = Prefs.getLocale();
// apply it until the app remains cached
Locale.setDefault(locale);
Configuration newConfig = new Configuration();
newConfig.locale = locale;
getBaseContext().getResources().updateConfiguration(newConfig, getBaseContext().getResources().getDisplayMetrics());
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// apply it until the app remains cached
Locale.setDefault(locale);
Configuration Config = new Configuration();
Config.locale = locale;
getBaseContext().getResources().updateConfiguration(Config, getBaseContext().getResources().getDisplayMetrics());
}
static {
ThemeManager.setDefaultTheme(ThemeManager.MIXED);
}
}
|
package gov.nih.nci.calab.domain;
import java.util.Collection;
import java.util.HashSet;
/**
* @author zengje
*
*/
public class DerivedDataFile extends LabFile {
private Collection<Keyword> keywordCollection = new HashSet<Keyword>();
public DerivedDataFile() {
super();
// TODO Auto-generated constructor stub
}
public Collection<Keyword> getKeywordCollection() {
return keywordCollection;
}
public void setKeywordCollection(Collection<Keyword> keywordCollection) {
this.keywordCollection = keywordCollection;
}
}
|
package io.core9.proxy;
import io.core9.firewall.rules.FirewallRequestRulesEngine;
import io.core9.rules.RuleException;
import io.core9.rules.Status;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.HttpObject;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import java.net.InetSocketAddress;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.xeoh.plugins.base.annotations.PluginImplementation;
import net.xeoh.plugins.base.annotations.injections.InjectPlugin;
import org.littleshoot.proxy.HttpFilters;
import org.littleshoot.proxy.HttpFiltersAdapter;
import org.littleshoot.proxy.HttpFiltersSourceAdapter;
import org.littleshoot.proxy.impl.DefaultHttpProxyServer;
@PluginImplementation
public class ProxyServerImpl implements ProxyServer {
private final Core9HostResolver resolver = new Core9HostResolver();
private final Map<String, Proxy> hostnameProxies = new HashMap<>();
@InjectPlugin
private FirewallRequestRulesEngine rules;
@Override
public ProxyServer addProxy(Proxy proxy) {
resolver.addHost(proxy);
hostnameProxies.put(proxy.getHostname(), proxy);
return this;
}
@Override
public Collection<Proxy> getProxies() {
return hostnameProxies.values();
}
@Override
public ProxyServer removeAllProxies() {
resolver.removeAllHosts();
return this;
}
@Override
public ProxyServer start() {
String port = System.getenv("PORT");
port = System.getProperty("PORT", port);
if(port == null) {
port = "8080";
}
DefaultHttpProxyServer.bootstrap()
.withPort(Integer.parseInt(port))
.withAllowLocalOnly(false)
.withListenOnAllAddresses(true)
.withServerResolver(resolver)
.withFiltersSource(new HttpFiltersSourceAdapter() {
@Override
public HttpFilters filterRequest(HttpRequest originalRequest, ChannelHandlerContext context) {
return new HttpFiltersAdapter(originalRequest) {
private ProxyRequest proxyRequest;
@Override
public HttpResponse requestPre(HttpObject httpObject) {
HttpResponse response = null;
if(httpObject instanceof HttpRequest) {
proxyRequest = new ProxyRequest((HttpRequest) httpObject, context);
proxyRequest.setProxy(hostnameProxies.get(((HttpRequest) httpObject).headers().get("Host")));
response = handleRequestPre(proxyRequest);
}
return response;
}
@Override
public HttpResponse requestPost(HttpObject httpObject) {
if(httpObject instanceof HttpRequest) {
setRequestHeaders(new ProxyRequest((HttpRequest) httpObject, context));
}
return null;
}
@Override
public HttpObject responsePre(HttpObject httpObject) {
return httpObject;
}
@Override
public HttpObject responsePost(HttpObject httpObject) {
proxyRequest.setHttpObject(httpObject);
handleResponsePost(proxyRequest);
return proxyRequest.getHttpObject();
}
};
}
}).start();
return this;
}
private HttpResponse handleRequestPre(ProxyRequest request) {
List<String> ruleSets = request.getProxy().getRuleSets().getPreRequest();
if(ruleSets == null) {
return null;
} else {
try {
handleRuleResponse(rules.handle(ruleSets, request), request);
} catch (RuleException e) {
return new DefaultFullHttpResponse(
HttpVersion.HTTP_1_1,
HttpResponseStatus.INTERNAL_SERVER_ERROR);
}
}
HttpObject result = request.getHttpObject();
if(result instanceof HttpResponse) {
return (HttpResponse) result;
} else {
return null;
}
}
private void handleResponsePost(ProxyRequest request) {
List<String> ruleSets = request.getProxy().getRuleSets().getPostResponse();
if(ruleSets == null) {
return;
} else {
try {
handleRuleResponse(rules.handle(ruleSets, request), request);
} catch (RuleException e) {
e.printStackTrace();
request.setHttpObject(new DefaultFullHttpResponse(
HttpVersion.HTTP_1_1,
HttpResponseStatus.INTERNAL_SERVER_ERROR));
}
}
}
private void setRequestHeaders(ProxyRequest request) {
request.getRequest().headers().remove("Accept-Encoding");
request.getRequest().headers().add("Accept-Encoding", "chunked");
String virtualhost = hostnameProxies.get(request.getRequest().headers().get("Host")).getVirtualHostname();
if(virtualhost != null) {
request.getRequest().headers().remove("Host");
request.getRequest().headers().add("Host", virtualhost);
}
}
private void handleRuleResponse(Status status, ProxyRequest request) throws RuleException {
switch (status.getType()) {
case ALLOW:
case PROCESS:
//request.setHttpObject(null);
return;
case DENY:
request.setHttpObject(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.FORBIDDEN));
return;
case PROCESSED:
case INITIALIZED:
return;
default:
throw new RuleException();
}
}
}
|
package Scrayble;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
|
package io.tetrapod.core;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.ssl.SslHandler;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import javax.net.ssl.*;
import io.tetrapod.protocol.core.Core;
import org.slf4j.*;
/**
* A server that speaks the tetrapod wire protocol
*/
public class Server extends ChannelInitializer<SocketChannel> implements Session.Listener {
public static final Logger logger = LoggerFactory.getLogger(Server.class);
private Map<Integer, Session> sessions = new ConcurrentHashMap<>();
private EventLoopGroup bossGroup;
private int port;
private final Dispatcher dispatcher;
private final SessionFactory sessionFactory;
private SSLContext sslContext;
private boolean clientAuth;
private ChannelFuture channel;
public Server(int port, SessionFactory sessionFactory, Dispatcher dispatcher) {
this.sessionFactory = sessionFactory;
this.dispatcher = dispatcher;
this.port = port;
}
public Server(int port, SessionFactory sessionFactory, Dispatcher dispatcher, SSLContext ctx, boolean clientAuth) {
this(port, sessionFactory, dispatcher);
enableTLS(ctx, clientAuth);
}
public void enableTLS(SSLContext ctx, boolean clientAuth) {
this.sslContext = ctx;
this.clientAuth = clientAuth;
}
public synchronized ChannelFuture start(int port) {
this.port = port;
return start();
}
public synchronized ChannelFuture start() {
bossGroup = dispatcher.getBossGroup();
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, dispatcher.getWorkerGroup()).channel(NioServerSocketChannel.class);
b.childHandler(this);
setOptions(b);
logger.info("Starting Server Listening on Port {}", port);
channel = b.bind(port);
return channel;
}
public void initChannel(SocketChannel ch) throws Exception {
startSession(ch);
}
protected void setOptions(ServerBootstrap sb) {
sb.option(ChannelOption.SO_BACKLOG, 128);
sb.childOption(ChannelOption.SO_KEEPALIVE, true);
}
public void close() {
if (channel != null) {
Channel c = channel.channel();
try {
c.close();
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
logger.debug("Stopped server on port {}", port);
}
}
public void stop() {
logger.debug("Stopping server on port {}...", port);
try {
if (bossGroup != null) {
bossGroup.shutdownGracefully().sync();
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
logger.debug("Stopped server on port {}", port);
}
public void purge() {
for (Session session : sessions.values()) {
if (session.getTheirEntityType() != Core.TYPE_ADMIN) {
session.close();
}
}
}
private static final Set<String> WEAK_CIPHERS = new HashSet<>();
static {
WEAK_CIPHERS.add("SSL_RSA_WITH_RC4_128_MD5");
WEAK_CIPHERS.add("SSL_RSA_WITH_RC4_128_SHA");
WEAK_CIPHERS.add("SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA");
WEAK_CIPHERS.add("TLS_ECDHE_RSA_WITH_RC4_128_SHA");
WEAK_CIPHERS.add("TLS_DHE_RSA_WITH_AES_128_CBC_SHA");
WEAK_CIPHERS.add("TLS_DHE_RSA_WITH_AES_128_CBC_SHA256");
WEAK_CIPHERS.add("TLS_DHE_RSA_WITH_AES_256_CBC_SHA");
WEAK_CIPHERS.add("TLS_DHE_RSA_WITH_AES_256_CBC_SHA256");
}
private void startSession(final SocketChannel ch) throws Exception {
logger.info("Connection from {}", ch);
if (sslContext != null) {
SSLEngine engine = sslContext.createSSLEngine();
engine.setUseClientMode(false);
engine.setWantClientAuth(clientAuth);
// Explicitly removes "SSLv3" from supported protocols to prevent the 'POODLE' exploit
final List<String> protocols = new ArrayList<>();
for (String p : engine.getEnabledProtocols()) {
if (!p.equals("SSLv3")) {
protocols.add(p);
}
}
engine.setEnabledProtocols(protocols.toArray(new String[protocols.size()]));
// remove weak cipher suites from the enabled list
final List<String> ciphers = new ArrayList<>();
for (String p : engine.getEnabledCipherSuites()) {
if (!WEAK_CIPHERS.contains(p)) {
ciphers.add(p);
} else {
logger.trace("removing weak cipher suit {}", p);
}
}
engine.setEnabledCipherSuites(ciphers.toArray(new String[ciphers.size()]));
SslHandler handler = new SslHandler(engine);
ch.pipeline().addLast("ssl", handler);
}
Session session = sessionFactory.makeSession(ch);
session.addSessionListener(this);
}
@Override
public void onSessionStart(Session ses) {
sessions.put(ses.getSessionNum(), ses);
}
@Override
public void onSessionStop(Session ses) {
sessions.remove(ses.getSessionNum());
}
public synchronized int getPort() {
return port;
}
public int getNumSessions() {
return sessions.size();
}
}
|
package graphics.nim.volterra;
import java.util.HashMap;
import graphics.nim.volterra.util.Matrix4f;
import static org.lwjgl.opengl.GL20.*;
public class Shader {
private int handle;
private HashMap<String, Integer> locationMap = new HashMap<String, Integer>();
public Shader(int handle) {
this.handle = handle;
}
public void bind() {
glUseProgram(handle);
}
public void unbind() {
glUseProgram(0);
}
public int location(String name) {
Integer location = locationMap.get(name);
if (location == null) {
location = glGetUniformLocation(handle, name);
locationMap.put(name, location);
}
return location;
}
public void uniform1i(String name, int value) {
glUniform1i(location(name), value);
}
public void uniform1f(String name, float value) {
glUniform1f(location(name), value);
}
public void uniform3f(String name, float v0, float v1, float v2) {
glUniform3f(location(name), v0, v1, v2);
}
public void uniformMatrix4f(String name, Matrix4f m) {
glUniformMatrix4fv(location(name), false, m.getBuffer());
}
}
|
package jolie.net;
import java.io.ByteArrayOutputStream;
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.Map.Entry;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import jolie.runtime.FaultException;
import jolie.runtime.Value;
import jolie.runtime.ValueVector;
import jolie.runtime.VariablePath;
public class SodepProtocol extends CommProtocol
{
private Charset stringCharset = Charset.forName( "UTF8" );
private String readString( DataInput in )
throws IOException
{
int len = in.readInt();
if ( len > 0 ) {
byte[] bb = new byte[ len ];
in.readFully( bb );
return new String( bb, stringCharset );
}
return "";
}
private void writeString( DataOutput out, String str )
throws IOException
{
if ( str.isEmpty() ) {
out.writeInt( 0 );
} else {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
Writer writer = new OutputStreamWriter( bos, stringCharset );
writer.write( str );
writer.close();
byte[] bb = bos.toByteArray();
out.writeInt( bb.length );
out.write( bb );
}
}
private void writeFault( DataOutput out, FaultException fault )
throws IOException
{
writeString( out, fault.faultName() );
writeValue( out, fault.value() );
}
private void writeValue( DataOutput out, Value value )
throws IOException
{
Object valueObject = value.valueObject();
if ( valueObject == null ) {
out.writeByte( 0 );
} else if ( valueObject instanceof String ) {
out.writeByte( 1 );
writeString( out, (String)valueObject );
} else if ( valueObject instanceof Integer ) {
out.writeByte( 2 );
out.writeInt( ((Integer)valueObject).intValue() );
} else if ( valueObject instanceof Double ) {
out.writeByte( 3 );
out.writeDouble( ((Double)valueObject).doubleValue() );
} else {
out.writeByte( 0 );
}
Map< String, ValueVector > children = value.children();
out.writeInt( children.size() );
for( Entry< String, ValueVector > entry : children.entrySet() ) {
writeString( out, entry.getKey() );
out.writeInt( entry.getValue().size() );
for( Value v : entry.getValue() )
writeValue( out, v );
}
}
private void writeMessage( DataOutput out, CommMessage message )
throws IOException
{
writeString( out, message.resourcePath() );
writeString( out, message.operationName() );
FaultException fault = message.fault();
if ( fault == null ) {
out.writeBoolean( false );
} else {
out.writeBoolean( true );
writeFault( out, fault );
}
writeValue( out, message.value() );
}
private Value readValue( DataInput in )
throws IOException
{
Value value = Value.create();
Object valueObject = null;
byte b = in.readByte();
if ( b == 1 ) { // String
valueObject = readString( in );
} else if ( b == 2 ) { // Integer
valueObject = new Integer( in.readInt() );
} else if ( b == 3 ) { // Double
valueObject = new Double( in.readInt() );
}
value.setValue( valueObject );
Map< String, ValueVector > children = value.children();
String s;
int n, i, size, k;
n = in.readInt(); // How many children?
ValueVector vec;
for( i = 0; i < n; i++ ) {
s = readString( in );
vec = ValueVector.create();
size = in.readInt();
for( k = 0; k < size; k++ ) {
vec.add( readValue( in ) );
}
children.put( s, vec );
}
return value;
}
private FaultException readFault( DataInput in )
throws IOException
{
String faultName = readString( in );
Value value = readValue( in );
return new FaultException( faultName, value );
}
private CommMessage readMessage( DataInput in )
throws IOException
{
String resourcePath = readString( in );
String operationName = readString( in );
FaultException fault = null;
if ( in.readBoolean() == true ) {
fault = readFault( in );
}
Value value = readValue( in );
return new CommMessage( operationName, resourcePath, value, fault );
}
public SodepProtocol( VariablePath configurationPath )
{
super( configurationPath );
}
public SodepProtocol clone()
{
return new SodepProtocol( configurationPath() );
}
public void send( OutputStream ostream, CommMessage message )
throws IOException
{
if ( getParameterVector( "keepAlive" ).first().intValue() == 0 ) {
channel.setToBeClosed( true );
} else {
channel.setToBeClosed( false );
}
String charset = getParameterVector( "charset" ).first().strValue();
if ( !charset.isEmpty() ) {
stringCharset = Charset.forName( charset );
}
GZIPOutputStream gzip = null;
String compression = getParameterVector( "compression" ).first().strValue();
if ( "gzip".equals( compression ) ) {
gzip = new GZIPOutputStream( ostream );
ostream = gzip;
}
DataOutputStream oos = new DataOutputStream( ostream );
writeMessage( oos, message );
oos.flush();
if ( gzip != null )
gzip.finish();
}
public CommMessage recv( InputStream istream )
throws IOException
{
if ( getParameterVector( "keepAlive" ).first().intValue() == 0 ) {
channel.setToBeClosed( true );
} else {
channel.setToBeClosed( false );
}
String charset = getParameterVector( "charset" ).first().strValue();
if ( !charset.isEmpty() ) {
stringCharset = Charset.forName( charset );
}
String compression = getParameterVector( "compression" ).first().strValue();
if ( "gzip".equals( compression ) ) {
istream = new GZIPInputStream( istream );
}
DataInputStream ios = new DataInputStream( istream );
return readMessage( ios );
}
}
|
package org.jboss.as.protocol.mgmt;
import static org.jboss.as.protocol.old.ProtocolUtils.expectHeader;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import org.jboss.as.protocol.ProtocolChannel;
import org.jboss.marshalling.Marshalling;
import org.jboss.marshalling.SimpleDataInput;
import org.jboss.remoting3.Channel;
import org.jboss.remoting3.MessageInputStream;
import org.xnio.IoUtils;
/**
*
* @author <a href="kabir.khan@jboss.com">Kabir Khan</a>
* @version $Revision: 1.1 $
*/
public class ManagementChannel extends ProtocolChannel implements ManagementRequestExecutionCallback {
private final CountDownLatch completedActiveRequestsLatch = new CountDownLatch(1);
private final RequestReceiver requestReceiver = new RequestReceiver();
private final ResponseReceiver responseReceiver = new ResponseReceiver();
//GuardedBy(this)
private final Set<Integer> outgoingExecutions = new HashSet<Integer>();
ManagementChannel(String name, Channel channel) {
super(name, channel);
}
public void setOperationHandler(final ManagementOperationHandler handler) {
requestReceiver.setOperationHandler(handler);
}
@Override
protected void doHandle(final Channel channel, final MessageInputStream message) {
final SimpleDataInput input = new SimpleDataInput(Marshalling.createByteInput(message));
try {
ManagementProtocolHeader header = ManagementProtocolHeader.parse(input);
if (header.isRequest()) {
requestReceiver.handleRequest((ManagementRequestHeader)header, input);
} else {
responseReceiver.handleResponse((ManagementResponseHeader)header, input);
}
} catch (IOException e) {
//TODO handle properly
e.printStackTrace();
} finally {
IoUtils.safeClose(input);
IoUtils.safeClose(message);
}
}
void executeRequest(ManagementRequest<?> request, ManagementResponseHandler<?> responseHandler) throws IOException {
responseReceiver.registerResponseHandler(request.getCurrentRequestId(), responseHandler);
FlushableDataOutputImpl output = FlushableDataOutputImpl.create(this.writeMessage());
try {
request.writeRequest(this, output);
} finally {
IoUtils.safeClose(output);
}
}
@Override
public synchronized void registerOutgoingExecution(int executionId) {
outgoingExecutions.add(executionId);
}
@Override
public synchronized void completeOutgoingExecution(int executionId) {
outgoingExecutions.remove(executionId);
if ((getClosed() || getWritesShutdown()) && outgoingExecutions.size() == 0) {
completedActiveRequestsLatch.countDown();
}
}
protected void waitUntilClosable() throws InterruptedException {
boolean wait = false;
synchronized (this) {
wait = outgoingExecutions.size() > 0;
}
if (wait) {
completedActiveRequestsLatch.await();
}
}
synchronized FlushableDataOutputImpl writeMessage(int executionId) throws IOException {
if (getClosed() || getWritesShutdown()) {
if (!outgoingExecutions.contains(executionId)) {
throw new IOException("Can't accept new requests in a closed channel");
}
}
return FlushableDataOutputImpl.create(writeMessage());
}
private class RequestReceiver {
private volatile ManagementOperationHandler operationHandler;
private void handleRequest(final ManagementRequestHeader header, final DataInput input) throws IOException {
final FlushableDataOutputImpl output = writeMessage(header.getExecutionId());
try {
final ManagementRequestHandler requestHandler;
try {
final ManagementOperationHandler operationHandler = getOperationHandler(header);
//Read request
expectHeader(input, ManagementProtocol.REQUEST_OPERATION);
requestHandler = getRequestHandler(operationHandler, input);
expectHeader(input, ManagementProtocol.REQUEST_START);
expectHeader(input, ManagementProtocol.REQUEST_BODY);
requestHandler.setContext(new ManagementRequestContext(ManagementChannel.this, header));
requestHandler.readRequest(input);
expectHeader(input, ManagementProtocol.REQUEST_END);
} catch (Exception e) {
throw e;
} finally {
writeResponseHeader(header, output);
output.writeByte(ManagementProtocol.RESPONSE_START);
output.writeByte(ManagementProtocol.RESPONSE_BODY);
}
requestHandler.writeResponse(output);
output.writeByte(ManagementProtocol.RESPONSE_END);
} catch (Exception e) {
e.printStackTrace();
if (e instanceof IOException) {
throw (IOException)e;
}
throw new IOException(e);
} finally {
IoUtils.safeClose(output);
}
}
private ManagementOperationHandler getOperationHandler(final ManagementRequestHeader header) throws IOException {
try {
if (operationHandler == null) {
throw new IOException("No operation handler set");
}
return operationHandler;
} catch (IOException e) {
throw e;
} catch (Exception e) {
throw new IOException(e);
}
}
private ManagementRequestHandler getRequestHandler(final ManagementOperationHandler operationHandler, final DataInput input) throws IOException {
try {
final byte requestHandlerId = input.readByte();
ManagementRequestHandler requestHandler = operationHandler.getRequestHandler(requestHandlerId);
if (requestHandler == null) {
throw new IOException("No request handler found with id " + requestHandlerId + " in operation handler " + operationHandler);
}
return requestHandler;
} catch (IOException e) {
e.printStackTrace();//TODO remove
throw e;
} catch (Exception e) {
throw new IOException(e);
}
}
private void writeResponseHeader(final ManagementRequestHeader header, DataOutput output) throws IOException {
final int workingVersion = Math.min(ManagementProtocol.VERSION, header.getVersion());
try {
// Now write the response header
final ManagementResponseHeader responseHeader = new ManagementResponseHeader(workingVersion, header.getRequestId());
responseHeader.write(output);
} catch (IOException e) {
throw e;
} catch (Throwable t) {
throw new IOException("Failed to write management response headers", t);
}
}
private void setOperationHandler(final ManagementOperationHandler operationHandler) {
this.operationHandler = operationHandler;
}
}
private class ResponseReceiver {
private final Map<Integer, ManagementResponseHandler<?>> responseHandlers = Collections.synchronizedMap(new HashMap<Integer, ManagementResponseHandler<?>>());
private void registerResponseHandler(final int requestId, final ManagementResponseHandler<?> handler) throws IOException {
if (responseHandlers.put(requestId, handler) != null) {
throw new IOException("Response handler already registered for request");
}
}
private void handleResponse(ManagementResponseHeader header, DataInput input) throws IOException {
ManagementResponseHandler<?> responseHandler = responseHandlers.get(header.getResponseId());
if (responseHandler == null) {
throw new IOException("No response handler for request " + header.getResponseId());
}
try {
expectHeader(input, ManagementProtocol.RESPONSE_START);
expectHeader(input, ManagementProtocol.RESPONSE_BODY);
responseHandler.readResponse(input);
expectHeader(input, ManagementProtocol.RESPONSE_END);
} catch (Exception e) {
if (e instanceof IOException) {
throw (IOException)e;
}
if (e instanceof RuntimeException) {
throw (RuntimeException)e;
}
throw new IOException(e);
}
}
}
}
|
package com.relayrides.pushy.apns;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.relayrides.pushy.apns.auth.ApnsVerificationKey;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http2.*;
import io.netty.util.AsciiString;
import io.netty.util.concurrent.PromiseCombiner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class MockApnsServerHandler extends Http2ConnectionHandler implements Http2FrameListener {
private final boolean emulateInternalErrors;
private final Http2Connection.PropertyKey apnsIdPropertyKey;
private final Map<String, Map<String, Date>> deviceTokenExpirationsByTopic;
private final Map<String, ApnsVerificationKey> verificationKeysByKeyId;
private final Map<ApnsVerificationKey, Set<String>> topicsByVerificationKey;
private String expectedTeamId;
private static final Http2Headers SUCCESS_HEADERS = new DefaultHttp2Headers().status(HttpResponseStatus.OK.codeAsText());
private static final String APNS_PATH_PREFIX = "/3/device/";
private static final AsciiString APNS_TOPIC_HEADER = new AsciiString("apns-topic");
private static final AsciiString APNS_PRIORITY_HEADER = new AsciiString("apns-priority");
private static final AsciiString APNS_ID_HEADER = new AsciiString("apns-id");
private static final AsciiString APNS_AUTHORIZATION_HEADER = new AsciiString("authorization");
private static final int MAX_CONTENT_LENGTH = 4096;
private static final Pattern TOKEN_PATTERN = Pattern.compile("[0-9a-fA-F]{64}");
private static final Gson GSON = new GsonBuilder()
.registerTypeAdapter(Date.class, new DateAsTimeSinceEpochTypeAdapter(TimeUnit.MILLISECONDS))
.create();
private static final Logger log = LoggerFactory.getLogger(MockApnsServerHandler.class);
private enum ErrorReason {
BAD_COLLAPSE_ID("BadCollapseId", HttpResponseStatus.BAD_REQUEST),
BAD_DEVICE_TOKEN("BadDeviceToken", HttpResponseStatus.BAD_REQUEST),
BAD_EXPIRATION_DATE("BadExpirationDate", HttpResponseStatus.BAD_REQUEST),
BAD_MESSAGE_ID("BadMessageId", HttpResponseStatus.BAD_REQUEST),
BAD_PRIORITY("BadPriority", HttpResponseStatus.BAD_REQUEST),
BAD_TOPIC("BadTopic", HttpResponseStatus.BAD_REQUEST),
DEVICE_TOKEN_NOT_FOR_TOPIC("DeviceTokenNotForTopic", HttpResponseStatus.BAD_REQUEST),
DUPLICATE_HEADERS("DuplicateHeaders", HttpResponseStatus.BAD_REQUEST),
IDLE_TIMEOUT("IdleTimeout", HttpResponseStatus.BAD_REQUEST),
MISSING_DEVICE_TOKEN("MissingDeviceToken", HttpResponseStatus.BAD_REQUEST),
MISSING_TOPIC("MissingTopic", HttpResponseStatus.BAD_REQUEST),
PAYLOAD_EMPTY("PayloadEmpty", HttpResponseStatus.BAD_REQUEST),
TOPIC_DISALLOWED("TopicDisallowed", HttpResponseStatus.BAD_REQUEST),
BAD_CERTIFICATE("BadCertificate", HttpResponseStatus.FORBIDDEN),
BAD_CERTIFICATE_ENVIRONMENT("BadCertificateEnvironment", HttpResponseStatus.FORBIDDEN),
EXPIRED_PROVIDER_TOKEN("ExpiredProviderToken", HttpResponseStatus.FORBIDDEN),
FORBIDDEN("Forbidden", HttpResponseStatus.FORBIDDEN),
INVALID_PROVIDER_TOKEN("InvalidProviderToken", HttpResponseStatus.FORBIDDEN),
MISSING_PROVIDER_TOKEN("MissingProviderToken", HttpResponseStatus.FORBIDDEN),
BAD_PATH("BadPath", HttpResponseStatus.NOT_FOUND),
METHOD_NOT_ALLOWED("MethodNotAllowed", HttpResponseStatus.METHOD_NOT_ALLOWED),
UNREGISTERED("Unregistered", HttpResponseStatus.GONE),
PAYLOAD_TOO_LARGE("PayloadTooLarge", HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE),
TOO_MANY_PROVIDER_TOKEN_UPDATES("TooManyProviderTokenUpdates", HttpResponseStatus.TOO_MANY_REQUESTS),
TOO_MANY_REQUESTS("TooManyRequests", HttpResponseStatus.TOO_MANY_REQUESTS),
INTERNAL_SERVER_ERROR("InternalServerError", HttpResponseStatus.INTERNAL_SERVER_ERROR),
SERVICE_UNAVAILABLE("ServiceUnavailable", HttpResponseStatus.SERVICE_UNAVAILABLE),
SHUTDOWN("Shutdown", HttpResponseStatus.SERVICE_UNAVAILABLE);
private final String reasonText;
private final HttpResponseStatus httpResponseStatus;
private ErrorReason(final String reasonText, final HttpResponseStatus httpResponseStatus) {
this.reasonText = reasonText;
this.httpResponseStatus = httpResponseStatus;
}
public String getReasonText() {
return this.reasonText;
}
public HttpResponseStatus getHttpResponseStatus() {
return this.httpResponseStatus;
}
}
protected static class RejectedNotificationException extends Exception {
private final ErrorReason errorReason;
private final Date deviceTokenExpirationTimestamp;
public RejectedNotificationException(final ErrorReason errorReason) {
this(errorReason, null);
}
public RejectedNotificationException(final ErrorReason errorReason, final Date deviceTokenExpirationTimestamp) {
Objects.requireNonNull(errorReason, "Error reason must not be null.");
this.errorReason = errorReason;
this.deviceTokenExpirationTimestamp = deviceTokenExpirationTimestamp;
}
public ErrorReason getErrorReason() {
return errorReason;
}
public Date getDeviceTokenExpirationTimestamp() {
return deviceTokenExpirationTimestamp;
}
}
private static class ExpiredAuthenticationTokenException extends Exception {
private static final long serialVersionUID = 1L;
}
private static class InvalidAuthenticationTokenException extends Exception {
private static final long serialVersionUID = 1L;
public InvalidAuthenticationTokenException() {
super();
}
public InvalidAuthenticationTokenException(final Throwable cause) {
super(cause);
}
}
public static final class MockApnsServerHandlerBuilder extends AbstractHttp2ConnectionHandlerBuilder<MockApnsServerHandler, MockApnsServerHandlerBuilder> {
private boolean emulateInternalErrors;
private Map<String, Map<String, Date>> deviceTokenExpirationsByTopic;
private Map<String, ApnsVerificationKey> verificationKeysByKeyId;
private Map<ApnsVerificationKey, Set<String>> topicsByVerificationKey;
@Override
public MockApnsServerHandlerBuilder initialSettings(final Http2Settings initialSettings) {
return super.initialSettings(initialSettings);
}
public MockApnsServerHandlerBuilder emulateInternalErrors(final boolean emulateInternalErrors) {
this.emulateInternalErrors = emulateInternalErrors;
return this;
}
public MockApnsServerHandlerBuilder deviceTokenExpirationsByTopic(final Map<String, Map<String, Date>> deviceTokenExpirationsByTopic) {
this.deviceTokenExpirationsByTopic = deviceTokenExpirationsByTopic;
return this;
}
public Map<String, Map<String, Date>> deviceTokenExpirationsByTopic() {
return this.deviceTokenExpirationsByTopic;
}
public MockApnsServerHandlerBuilder verificationKeysByKeyId(final Map<String, ApnsVerificationKey> verificationKeysByKeyId) {
this.verificationKeysByKeyId = verificationKeysByKeyId;
return this;
}
public Map<String, ApnsVerificationKey> verificationKeysByKeyId() {
return this.verificationKeysByKeyId;
}
public MockApnsServerHandlerBuilder topicsByVerificationKey(final Map<ApnsVerificationKey, Set<String>> topicsByVerificationKey) {
this.topicsByVerificationKey = topicsByVerificationKey;
return this;
}
public Map<ApnsVerificationKey, Set<String>> topicsByVerificationKey() {
return this.topicsByVerificationKey;
}
@Override
public MockApnsServerHandler build(final Http2ConnectionDecoder decoder, final Http2ConnectionEncoder encoder, final Http2Settings initialSettings) {
final MockApnsServerHandler handler = new MockApnsServerHandler(decoder, encoder, initialSettings, emulateInternalErrors, deviceTokenExpirationsByTopic, verificationKeysByKeyId, topicsByVerificationKey);
this.frameListener(handler);
return handler;
}
@Override
public MockApnsServerHandler build() {
return super.build();
}
}
private static class AcceptNotificationResponse {
private final int streamId;
public AcceptNotificationResponse(final int streamId) {
this.streamId = streamId;
}
public int getStreamId() {
return this.streamId;
}
}
private static class RejectNotificationResponse {
private final int streamId;
private final UUID apnsId;
private final ErrorReason errorReason;
private final Date timestamp;
public RejectNotificationResponse(final int streamId, final UUID apnsId, final ErrorReason errorReason, final Date timestamp) {
this.streamId = streamId;
this.apnsId = apnsId;
this.errorReason = errorReason;
this.timestamp = timestamp;
}
public int getStreamId() {
return this.streamId;
}
public UUID getApnsId() {
return this.apnsId;
}
public ErrorReason getErrorReason() {
return this.errorReason;
}
public Date getTimestamp() {
return this.timestamp;
}
}
private static class InternalServerErrorResponse {
private final int streamId;
public InternalServerErrorResponse(final int streamId) {
this.streamId = streamId;
}
public int getStreamId() {
return this.streamId;
}
}
protected MockApnsServerHandler(final Http2ConnectionDecoder decoder,
final Http2ConnectionEncoder encoder,
final Http2Settings initialSettings,
final boolean emulateInternalErrors,
final Map<String, Map<String, Date>> deviceTokenExpirationsByTopic,
final Map<String, ApnsVerificationKey> verificationKeysByKeyId,
final Map<ApnsVerificationKey, Set<String>> topicsByVerificationKey) {
super(decoder, encoder, initialSettings);
this.apnsIdPropertyKey = this.connection().newKey();
this.emulateInternalErrors = emulateInternalErrors;
this.deviceTokenExpirationsByTopic = deviceTokenExpirationsByTopic;
this.verificationKeysByKeyId = verificationKeysByKeyId;
this.topicsByVerificationKey = topicsByVerificationKey;
}
@Override
public int onDataRead(final ChannelHandlerContext context, final int streamId, final ByteBuf data, final int padding, final boolean endOfStream) throws Http2Exception {
final int bytesProcessed = data.readableBytes() + padding;
if (endOfStream) {
final Http2Stream stream = this.connection().stream(streamId);
// Presumably, we spotted an error earlier and sent a response immediately if the stream is closed on our
// side.
if (stream.state() == Http2Stream.State.OPEN) {
final UUID apnsId = stream.getProperty(this.apnsIdPropertyKey);
if (data.readableBytes() <= MAX_CONTENT_LENGTH) {
context.channel().writeAndFlush(new AcceptNotificationResponse(streamId));
} else {
context.channel().writeAndFlush(new RejectNotificationResponse(streamId, apnsId, ErrorReason.PAYLOAD_TOO_LARGE, null));
}
}
}
return bytesProcessed;
}
@Override
public void onHeadersRead(final ChannelHandlerContext context, final int streamId, final Http2Headers headers, final int padding, final boolean endOfStream) throws Http2Exception {
if (this.emulateInternalErrors) {
context.channel().writeAndFlush(new InternalServerErrorResponse(streamId));
} else {
final Http2Stream stream = this.connection().stream(streamId);
UUID apnsId = null;
try {
{
final CharSequence apnsIdSequence = headers.get(APNS_ID_HEADER);
if (apnsIdSequence != null) {
try {
apnsId = UUID.fromString(apnsIdSequence.toString());
} catch (final IllegalArgumentException e) {
throw new RejectedNotificationException(ErrorReason.BAD_MESSAGE_ID);
}
} else {
// If the client didn't send us a UUID, make one up (for now)
apnsId = UUID.randomUUID();
}
}
if (!HttpMethod.POST.asciiName().contentEquals(headers.get(Http2Headers.PseudoHeaderName.METHOD.value()))) {
throw new RejectedNotificationException(ErrorReason.METHOD_NOT_ALLOWED);
}
if (endOfStream) {
throw new RejectedNotificationException(ErrorReason.PAYLOAD_EMPTY);
}
this.verifyHeaders(headers);
// At this point, we've made it through all of the headers without an exception and know we're waiting
// for a data frame. The data frame handler will want the APNs ID in case it needs to send an error
// response.
stream.setProperty(this.apnsIdPropertyKey, apnsId);
} catch (final RejectedNotificationException e) {
context.channel().writeAndFlush(new RejectNotificationResponse(streamId, apnsId, e.getErrorReason(), e.getDeviceTokenExpirationTimestamp()));
}
}
}
protected void verifyHeaders(final Http2Headers headers) throws RejectedNotificationException {
final String base64EncodedAuthenticationToken;
{
final CharSequence authorizationSequence = headers.get(APNS_AUTHORIZATION_HEADER);
if (authorizationSequence != null) {
final String authorizationString = authorizationSequence.toString();
if (authorizationString.startsWith("bearer")) {
base64EncodedAuthenticationToken = authorizationString.substring("bearer".length()).trim();
} else {
base64EncodedAuthenticationToken = null;
}
} else {
base64EncodedAuthenticationToken = null;
}
}
final String topic;
{
final CharSequence topicSequence = headers.get(APNS_TOPIC_HEADER);
topic = (topicSequence != null) ? topicSequence.toString() : null;
}
if (topic == null) {
throw new RejectedNotificationException(ErrorReason.MISSING_TOPIC);
}
// TODO Restore caching
final AuthenticationToken authenticationToken = new AuthenticationToken(base64EncodedAuthenticationToken);
final ApnsVerificationKey verificationKey = this.verificationKeysByKeyId.get(authenticationToken.getKeyId());
// Have we ever heard of the key in question?
if (verificationKey == null) {
throw new RejectedNotificationException(ErrorReason.INVALID_PROVIDER_TOKEN);
}
try {
if (!authenticationToken.verifySignature(verificationKey)) {
throw new RejectedNotificationException(ErrorReason.INVALID_PROVIDER_TOKEN);
}
} catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException e) {
// This should never happen (here, at least) because we check keys at construction time. If something's
// going to go wrong, it will go wrong before we ever get here.
log.error("Failed to verify signature.", e);
throw new RuntimeException(e);
}
// At this point, we've verified that the token is signed by somebody with the named team's private key. The
// real APNs server only allows one team per connection, so if this is our first notification, we want to keep
// track of the team that sent it so we can reject notifications from other teams, even if they're signed
// correctly.
if (this.expectedTeamId == null) {
this.expectedTeamId = authenticationToken.getTeamId();
}
if (!this.expectedTeamId.equals(authenticationToken.getTeamId())) {
throw new RejectedNotificationException(ErrorReason.INVALID_PROVIDER_TOKEN);
}
if (authenticationToken.getIssuedAt().getTime() + MockApnsServer.AUTHENTICATION_TOKEN_EXPIRATION_MILLIS < System.currentTimeMillis()) {
throw new RejectedNotificationException(ErrorReason.EXPIRED_PROVIDER_TOKEN);
}
final Set<String> topics = this.topicsByVerificationKey.get(verificationKey);
if (topics == null || !topics.contains(topic)) {
throw new RejectedNotificationException(ErrorReason.DEVICE_TOKEN_NOT_FOR_TOPIC);
}
{
final Integer priorityCode = headers.getInt(APNS_PRIORITY_HEADER);
if (priorityCode != null) {
try {
DeliveryPriority.getFromCode(priorityCode);
} catch (final IllegalArgumentException e) {
throw new RejectedNotificationException(ErrorReason.BAD_PRIORITY);
}
}
}
{
final CharSequence pathSequence = headers.get(Http2Headers.PseudoHeaderName.PATH.value());
if (pathSequence != null) {
final String pathString = pathSequence.toString();
if (pathString.startsWith(APNS_PATH_PREFIX)) {
final String tokenString = pathString.substring(APNS_PATH_PREFIX.length());
final Matcher tokenMatcher = TOKEN_PATTERN.matcher(tokenString);
if (!tokenMatcher.matches()) {
throw new RejectedNotificationException(ErrorReason.BAD_DEVICE_TOKEN);
}
final boolean deviceTokenRegisteredForTopic;
final Date expirationTimestamp;
{
final Map<String, Date> expirationTimestampsByDeviceToken = this.deviceTokenExpirationsByTopic.get(topic);
expirationTimestamp = expirationTimestampsByDeviceToken != null ? expirationTimestampsByDeviceToken.get(tokenString) : null;
deviceTokenRegisteredForTopic = expirationTimestampsByDeviceToken != null && expirationTimestampsByDeviceToken.containsKey(tokenString);
}
if (expirationTimestamp != null) {
throw new RejectedNotificationException(ErrorReason.UNREGISTERED, expirationTimestamp);
}
if (!deviceTokenRegisteredForTopic) {
throw new RejectedNotificationException(ErrorReason.DEVICE_TOKEN_NOT_FOR_TOPIC);
}
}
} else {
throw new RejectedNotificationException(ErrorReason.BAD_PATH);
}
}
}
@Override
public void onHeadersRead(final ChannelHandlerContext ctx, final int streamId, final Http2Headers headers, final int streamDependency,
final short weight, final boolean exclusive, final int padding, final boolean endOfStream) throws Http2Exception {
this.onHeadersRead(ctx, streamId, headers, padding, endOfStream);
}
@Override
public void onPriorityRead(final ChannelHandlerContext ctx, final int streamId, final int streamDependency, final short weight, final boolean exclusive) throws Http2Exception {
}
@Override
public void onRstStreamRead(final ChannelHandlerContext ctx, final int streamId, final long errorCode) throws Http2Exception {
}
@Override
public void onSettingsAckRead(final ChannelHandlerContext ctx) throws Http2Exception {
}
@Override
public void onSettingsRead(final ChannelHandlerContext ctx, final Http2Settings settings) throws Http2Exception {
}
@Override
public void onPingRead(final ChannelHandlerContext ctx, final ByteBuf data) throws Http2Exception {
}
@Override
public void onPingAckRead(final ChannelHandlerContext ctx, final ByteBuf data) throws Http2Exception {
}
@Override
public void onPushPromiseRead(final ChannelHandlerContext ctx, final int streamId, final int promisedStreamId, final Http2Headers headers, final int padding) throws Http2Exception {
}
@Override
public void onGoAwayRead(final ChannelHandlerContext ctx, final int lastStreamId, final long errorCode, final ByteBuf debugData) throws Http2Exception {
}
@Override
public void onWindowUpdateRead(final ChannelHandlerContext ctx, final int streamId, final int windowSizeIncrement) throws Http2Exception {
}
@Override
public void onUnknownFrame(final ChannelHandlerContext ctx, final byte frameType, final int streamId, final Http2Flags flags, final ByteBuf payload) throws Http2Exception {
}
@Override
public void write(final ChannelHandlerContext context, final Object message, final ChannelPromise writePromise) throws Exception {
if (message instanceof AcceptNotificationResponse) {
final AcceptNotificationResponse acceptNotificationResponse = (AcceptNotificationResponse) message;
this.encoder().writeHeaders(context, acceptNotificationResponse.getStreamId(), SUCCESS_HEADERS, 0, true, writePromise);
} else if (message instanceof RejectNotificationResponse) {
final RejectNotificationResponse rejectNotificationResponse = (RejectNotificationResponse) message;
final Http2Headers headers = new DefaultHttp2Headers();
headers.status(rejectNotificationResponse.getErrorReason().getHttpResponseStatus().codeAsText());
headers.add(HttpHeaderNames.CONTENT_TYPE, "application/json");
if (rejectNotificationResponse.getApnsId() != null) {
headers.add(APNS_ID_HEADER, rejectNotificationResponse.getApnsId().toString());
}
final byte[] payloadBytes;
{
final ErrorResponse errorResponse =
new ErrorResponse(rejectNotificationResponse.getErrorReason().getReasonText(),
rejectNotificationResponse.getTimestamp());
payloadBytes = GSON.toJson(errorResponse).getBytes();
}
final ChannelPromise headersPromise = context.newPromise();
this.encoder().writeHeaders(context, rejectNotificationResponse.getStreamId(), headers, 0, false, headersPromise);
final ChannelPromise dataPromise = context.newPromise();
this.encoder().writeData(context, rejectNotificationResponse.getStreamId(), Unpooled.wrappedBuffer(payloadBytes), 0, true, dataPromise);
final PromiseCombiner promiseCombiner = new PromiseCombiner();
promiseCombiner.addAll((ChannelFuture) headersPromise, dataPromise);
promiseCombiner.finish(writePromise);
} else if (message instanceof InternalServerErrorResponse) {
final InternalServerErrorResponse internalServerErrorResponse = (InternalServerErrorResponse) message;
final Http2Headers headers = new DefaultHttp2Headers();
headers.status(HttpResponseStatus.INTERNAL_SERVER_ERROR.codeAsText());
this.encoder().writeHeaders(context, internalServerErrorResponse.getStreamId(), headers, 0, true, writePromise);
} else {
context.write(message, writePromise);
}
}
}
|
package com.jetbrains.python.actions;
import com.intellij.codeInspection.LocalQuickFix;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiElement;
import com.jetbrains.python.PyBundle;
import com.jetbrains.python.psi.*;
import com.jetbrains.python.psi.impl.PyAugAssignmentStatementImpl;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
/**
* User: catherine
*
* QuickFix to replace assignment that can be replaced with augmented assignment.
* for instance, i = i + 1 --> i +=1
*/
public class AugmentedAssignmentQuickFix implements LocalQuickFix {
public AugmentedAssignmentQuickFix() {
}
@NotNull
public String getName() {
return PyBundle.message("QFIX.augment.assignment");
}
@NotNull
public String getFamilyName() {
return PyBundle.message("INSP.GROUP.python");
}
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
PsiElement element = descriptor.getPsiElement();
if (element != null && element instanceof PyAssignmentStatement && element.isWritable()) {
PyAssignmentStatement statement = (PyAssignmentStatement)element;
PyTargetExpression target = ((PyTargetExpression)statement.getLeftHandSideExpression());
PyBinaryExpression expression = (PyBinaryExpression)statement.getAssignedValue();
PyExpression leftExpression = expression.getLeftExpression();
PyExpression rightExpression = expression.getRightExpression();
if (leftExpression != null && leftExpression instanceof PyReferenceExpression) {
if (leftExpression.getName().equals(target.getName())) {
if (rightExpression instanceof PyNumericLiteralExpression ||
rightExpression instanceof PyStringLiteralExpression
|| rightExpression instanceof PyReferenceExpression) {
PyElementGenerator elementGenerator = PyElementGenerator.getInstance(project);
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(target.getText()).append(" ").
append(expression.getPsiOperator().getText()).append("= ").append(rightExpression.getText());
PyAugAssignmentStatementImpl augAssignment = elementGenerator.createFromText(LanguageLevel.getDefault(),
PyAugAssignmentStatementImpl.class, stringBuilder.toString());
statement.replace(augAssignment);
}
}
}
}
}
}
|
package com.podio.sdk.volley;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import com.android.volley.AuthFailureError;
import com.android.volley.Cache.Entry;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.RequestFuture;
import com.podio.sdk.JsonParser;
import com.podio.sdk.PodioError;
import com.podio.sdk.Session;
import com.podio.sdk.internal.Utils;
public class VolleyRequest<T> extends Request<T> implements com.podio.sdk.Request<T> {
public static ErrorListener addGlobalErrorListener(ErrorListener errorListener) {
return VolleyCallbackManager.addGlobalErrorListener(errorListener);
}
public static SessionListener addGlobalSessionListener(SessionListener sessionListener) {
return VolleyCallbackManager.addGlobalSessionListener(sessionListener);
}
public static ErrorListener removeGlobalErrorListener(ErrorListener errorListener) {
return VolleyCallbackManager.addGlobalErrorListener(errorListener);
}
public static SessionListener removeGlobalSessionListener(SessionListener sessionListener) {
return VolleyCallbackManager.removeGlobalSessionListener(sessionListener);
}
static <E> VolleyRequest<E> newRequest(com.podio.sdk.Request.Method method, String url, String body, Class<E> classOfResult) {
RequestFuture<E> volleyRequestFuture = RequestFuture.newFuture();
int volleyMethod = parseMethod(method);
VolleyRequest<E> request = new VolleyRequest<E>(volleyMethod, url, classOfResult, volleyRequestFuture, false);
request.contentType = "application/json; charset=UTF-8";
if (Utils.notEmpty(Session.accessToken())) {
request.headers.put("Authorization", "Bearer " + Session.accessToken());
}
request.body = body;
return request;
}
static VolleyRequest<Void> newAuthRequest(String url, Map<String, String> params) {
RequestFuture<Void> volleyRequestFuture = RequestFuture.newFuture();
int volleyMethod = parseMethod(com.podio.sdk.Request.Method.POST);
VolleyRequest<Void> request = new VolleyRequest<Void>(volleyMethod, url, null, volleyRequestFuture, true);
request.contentType = "application/x-www-form-urlencoded; charset=UTF-8";
request.params.putAll(params);
return request;
}
protected static int parseMethod(com.podio.sdk.Request.Method method) {
switch (method) {
case DELETE:
return com.android.volley.Request.Method.DELETE;
case GET:
return com.android.volley.Request.Method.GET;
case POST:
return com.android.volley.Request.Method.POST;
case PUT:
return com.android.volley.Request.Method.PUT;
default:
return com.android.volley.Request.Method.GET;
}
}
private final VolleyCallbackManager<T> callbackManager;
private final RequestFuture<T> volleyRequestFuture;
private final Class<T> classOfResult;
protected HashMap<String, String> headers;
protected HashMap<String, String> params;
protected String contentType;
protected String body;
private T result;
private Throwable error;
private boolean isAuthRequest;
private boolean hasSessionChanged;
protected VolleyRequest(int method, String url, Class<T> resultType, RequestFuture<T> volleyRequestFuture, boolean isAuthRequest) {
super(method, url, volleyRequestFuture);
setShouldCache(false);
this.callbackManager = new VolleyCallbackManager<T>();
this.volleyRequestFuture = volleyRequestFuture;
this.volleyRequestFuture.setRequest(this);
this.classOfResult = resultType;
this.headers = new HashMap<String, String>();
this.params = new HashMap<String, String>();
this.body = null;
this.hasSessionChanged = false;
this.isAuthRequest = isAuthRequest;
}
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
return volleyRequestFuture.cancel(mayInterruptIfRunning);
}
@Override
public T get() throws InterruptedException, ExecutionException {
return volleyRequestFuture.get();
}
@Override
public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
return volleyRequestFuture.get(timeout, unit);
}
@Override
public boolean isCancelled() {
return volleyRequestFuture.isCancelled();
}
@Override
public boolean isDone() {
return volleyRequestFuture.isDone();
}
@Override
public VolleyRequest<T> withResultListener(ResultListener<T> resultListener) {
callbackManager.addResultListener(resultListener, isDone(), result);
return this;
}
@Override
public VolleyRequest<T> withErrorListener(ErrorListener errorListener) {
callbackManager.addErrorListener(errorListener, isDone() && error != null, error);
return this;
}
@Override
public VolleyRequest<T> withSessionListener(SessionListener sessionListener) {
callbackManager.addSessionListener(sessionListener, isDone() && hasSessionChanged);
return this;
}
@Override
public byte[] getBody() throws AuthFailureError {
return body != null ? body.getBytes() : super.getBody();
}
@Override
public String getBodyContentType() {
return contentType;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
String accessToken = Session.accessToken();
if (!isAuthRequest && Utils.notEmpty(accessToken)) {
headers.put("Authorization", "Bearer " + accessToken);
} else {
headers.remove("Authorization");
}
return headers;
}
@Override
protected Map<String, String> getParams() throws AuthFailureError {
if (params.containsKey("refresh_token")) {
String refreshToken = Session.refreshToken();
params.put("refresh_token", refreshToken);
}
return params;
}
@Override
public void deliverError(VolleyError error) {
// This method is executed on the main thread. Extra care should be
// taken on what is done here.
if (isExpiredError(this.error)) {
callbackManager.deliverAuthError(this);
}
callbackManager.deliverError(this.error);
}
@Override
protected void deliverResponse(T result) {
// This method is executed on the main thread. Extra care should be
// taken on what is done here.
this.result = result;
if (hasSessionChanged) {
callbackManager.deliverSession();
}
callbackManager.deliverResult(result);
}
@Override
protected VolleyError parseNetworkError(VolleyError volleyError) {
// This method is executed on the worker thread. It's "safe" to perform
// JSON parsing here.
try {
String charSet = HttpHeaderParser.parseCharset(volleyError.networkResponse.headers);
String errorJson = new String(volleyError.networkResponse.data, charSet);
error = PodioError.fromJson(errorJson, volleyError.networkResponse.statusCode, error);
} catch (UnsupportedEncodingException e) {
// The provided error JSON is provided with an unknown char-set.
error = volleyError;
} catch (NullPointerException e) {
// For some reason the VollyError didn't provide a networkResponse.
error = volleyError;
}
return super.parseNetworkError(volleyError);
}
@Override
protected Response<T> parseNetworkResponse(NetworkResponse response) {
// This method is executed on the worker thread. It's "safe" to perform
// JSON parsing here.
try {
Entry cacheHeaders = HttpHeaderParser.parseCacheHeaders(response);
String charSet = HttpHeaderParser.parseCharset(response.headers);
String json = new String(response.data, charSet);
if (isAuthRequest) {
Session.set(json);
hasSessionChanged = true;
return Response.success(null, cacheHeaders);
} else if (classOfResult == null || classOfResult == Void.class) {
return Response.success(null, cacheHeaders);
} else {
T result = JsonParser.fromJson(json, classOfResult);
return Response.success(result, cacheHeaders);
}
} catch (UnsupportedEncodingException e) {
// The provided response JSON is provided with an unknown char-set.
return Response.error(new ParseError(e));
}
}
public ErrorListener removeErrorListener(ErrorListener errorListener) {
return callbackManager.removeErrorListener(errorListener);
}
public ResultListener<T> removeResultListener(ResultListener<T> resultListener) {
return callbackManager.removeResultListener(resultListener);
}
public SessionListener removeSessionListener(SessionListener sessionListener) {
return callbackManager.removeSessionListener(sessionListener);
}
AuthErrorListener<T> removeAuthErrorListener(AuthErrorListener<T> authErrorListener) {
return callbackManager.removeAuthErrorListener(authErrorListener);
}
VolleyRequest<T> withAuthErrorListener(AuthErrorListener<T> authErrorListener) {
callbackManager.addAuthErrorListener(authErrorListener, isDone() && isExpiredError(error), this);
return this;
}
private boolean isExpiredError(Throwable error) {
if (error instanceof PodioError) {
PodioError e = (PodioError) error;
return e.isExpiredError();
} else if (error instanceof VolleyError) {
VolleyError e = (VolleyError) error;
return e.networkResponse != null && e.networkResponse.statusCode == 401;
} else {
return false;
}
}
}
|
package org.codehaus.modello.plugin.java;
import org.codehaus.modello.ModelloException;
import org.codehaus.modello.ModelloRuntimeException;
import org.codehaus.modello.model.CodeSegment;
import org.codehaus.modello.model.Model;
import org.codehaus.modello.model.ModelAssociation;
import org.codehaus.modello.model.ModelClass;
import org.codehaus.modello.model.ModelDefault;
import org.codehaus.modello.model.ModelField;
import org.codehaus.modello.model.ModelInterface;
import org.codehaus.modello.plugin.java.javasource.JArrayType;
import org.codehaus.modello.plugin.java.javasource.JClass;
import org.codehaus.modello.plugin.java.javasource.JCollectionType;
import org.codehaus.modello.plugin.java.javasource.JConstructor;
import org.codehaus.modello.plugin.java.javasource.JField;
import org.codehaus.modello.plugin.java.javasource.JInterface;
import org.codehaus.modello.plugin.java.javasource.JMethod;
import org.codehaus.modello.plugin.java.javasource.JParameter;
import org.codehaus.modello.plugin.java.javasource.JSourceCode;
import org.codehaus.modello.plugin.java.javasource.JSourceWriter;
import org.codehaus.modello.plugin.java.javasource.JType;
import org.codehaus.modello.plugin.java.metadata.JavaAssociationMetadata;
import org.codehaus.modello.plugin.java.metadata.JavaClassMetadata;
import org.codehaus.modello.plugin.java.metadata.JavaFieldMetadata;
import org.codehaus.modello.plugin.model.ModelClassMetadata;
import org.codehaus.plexus.util.StringUtils;
import java.io.IOException;
import java.io.Serializable;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
/**
* @author <a href="mailto:jason@modello.org">Jason van Zyl </a>
* @version $Id$
*/
public class JavaModelloGenerator
extends AbstractJavaModelloGenerator
{
public void generate( Model model, Properties parameters )
throws ModelloException
{
initialize( model, parameters );
try
{
generateJava();
}
catch ( IOException ex )
{
throw new ModelloException( "Exception while generating Java.", ex );
}
}
private void generateJava()
throws ModelloException, IOException
{
Model objectModel = getModel();
// Generate the interfaces.
for ( Iterator i = objectModel.getInterfaces( getGeneratedVersion() ).iterator(); i.hasNext(); )
{
ModelInterface modelInterface = (ModelInterface) i.next();
String packageName = modelInterface.getPackageName( isPackageWithVersion(), getGeneratedVersion() );
JSourceWriter sourceWriter = newJSourceWriter( packageName, modelInterface.getName() );
JInterface jInterface = new JInterface( packageName + '.' + modelInterface.getName() );
if ( modelInterface.getSuperInterface() != null )
{
// check if we need an import: if it is a generated superInterface in another package
try
{
ModelInterface superInterface = objectModel.getInterface( modelInterface.getSuperInterface(),
getGeneratedVersion() );
String superPackageName = superInterface.getPackageName( isPackageWithVersion(),
getGeneratedVersion() );
if ( ! packageName.equals( superPackageName ) )
{
jInterface.addImport( superPackageName + '.' + superInterface.getName() );
}
}
catch ( ModelloRuntimeException mre )
{
// no problem if the interface does not exist in the model, it can be in the jdk
}
jInterface.addInterface( modelInterface.getSuperInterface() );
}
if ( modelInterface.getCodeSegments( getGeneratedVersion() ) != null )
{
for ( Iterator iterator = modelInterface.getCodeSegments( getGeneratedVersion() ).iterator(); iterator.hasNext(); )
{
CodeSegment codeSegment = (CodeSegment) iterator.next();
jInterface.addSourceCode( codeSegment.getCode() );
}
}
jInterface.print( sourceWriter );
sourceWriter.close();
}
// Generate the classes.
for ( Iterator i = objectModel.getClasses( getGeneratedVersion() ).iterator(); i.hasNext(); )
{
ModelClass modelClass = (ModelClass) i.next();
JavaClassMetadata javaClassMetadata = (JavaClassMetadata) modelClass.getMetadata( JavaClassMetadata.ID );
if ( !javaClassMetadata.isEnabled() )
{
// Skip generation of those classes that are not enabled for the java plugin.
continue;
}
String packageName = modelClass.getPackageName( isPackageWithVersion(), getGeneratedVersion() );
JSourceWriter sourceWriter = newJSourceWriter( packageName, modelClass.getName() );
JClass jClass = new JClass( packageName + '.' + modelClass.getName() );
if ( StringUtils.isNotEmpty( modelClass.getDescription() ) )
{
jClass.getJDocComment().setComment( appendPeriod( modelClass.getDescription() ) );
}
addModelImports( jClass, modelClass );
jClass.getModifiers().setAbstract( javaClassMetadata.isAbstract() );
if ( modelClass.getSuperClass() != null )
{
jClass.setSuperClass( modelClass.getSuperClass() );
}
for ( Iterator j = modelClass.getInterfaces().iterator(); j.hasNext(); )
{
String implementedInterface = (String) j.next();
jClass.addInterface( implementedInterface );
}
jClass.addInterface( Serializable.class.getName() );
JSourceCode jConstructorSource = new JSourceCode();
for ( Iterator j = modelClass.getFields( getGeneratedVersion() ).iterator(); j.hasNext(); )
{
ModelField modelField = (ModelField) j.next();
if ( modelField instanceof ModelAssociation )
{
createAssociation( jClass, (ModelAssociation) modelField, jConstructorSource );
}
else
{
createField( jClass, modelField );
}
}
if ( !jConstructorSource.isEmpty() )
{
// Ironic that we are doing lazy init huh?
JConstructor jConstructor = jClass.createConstructor();
jConstructor.setSourceCode( jConstructorSource );
jClass.addConstructor( jConstructor );
}
// equals() / hashCode() / toString()
List identifierFields = modelClass.getIdentifierFields( getGeneratedVersion() );
if ( identifierFields.size() != 0 )
{
JMethod equals = generateEquals( modelClass );
jClass.addMethod( equals );
JMethod hashCode = generateHashCode( modelClass );
jClass.addMethod( hashCode );
JMethod toString = generateToString( modelClass );
jClass.addMethod( toString );
}
if ( modelClass.getCodeSegments( getGeneratedVersion() ) != null )
{
for ( Iterator iterator = modelClass.getCodeSegments( getGeneratedVersion() ).iterator();
iterator.hasNext(); )
{
CodeSegment codeSegment = (CodeSegment) iterator.next();
jClass.addSourceCode( codeSegment.getCode() );
}
}
ModelClassMetadata metadata = (ModelClassMetadata) modelClass.getMetadata( ModelClassMetadata.ID );
if ( ( metadata != null ) && metadata.isRootElement() )
{
JField modelEncoding = new JField( new JType( "String" ), "modelEncoding" );
modelEncoding.setInitString( "\"UTF-8\"" );
jClass.addField( modelEncoding );
// setModelEncoding(String) method
JMethod setModelEncoding = new JMethod( "setModelEncoding" );
setModelEncoding.addParameter( new JParameter( new JClass( "String" ), "modelEncoding" ) );
setModelEncoding.getSourceCode().add( "this.modelEncoding = modelEncoding;" );
setModelEncoding.getJDocComment().setComment( "Set an encoding used for reading/writing the model." );
jClass.addMethod( setModelEncoding );
// getModelEncoding() method
JMethod getModelEncoding = new JMethod( "getModelEncoding", new JType( "String" ),
"the current encoding used when reading/writing this model" );
getModelEncoding.getSourceCode().add( "return modelEncoding;" );
jClass.addMethod( getModelEncoding );
}
jClass.print( sourceWriter );
sourceWriter.close();
}
}
private JMethod generateEquals( ModelClass modelClass )
{
JMethod equals = new JMethod( "equals", JType.BOOLEAN, null );
equals.addParameter( new JParameter( new JClass( "Object" ), "other" ) );
JSourceCode sc = equals.getSourceCode();
sc.add( "if ( this == other )" );
sc.add( "{" );
sc.addIndented( "return true;" );
sc.add( "}" );
sc.add( "" );
sc.add( "if ( !( other instanceof " + modelClass.getName() + " ) )" );
sc.add( "{" );
sc.addIndented( "return false;" );
sc.add( "}" );
sc.add( "" );
sc.add( modelClass.getName() + " that = (" + modelClass.getName() + ") other;" );
sc.add( "boolean result = true;" );
sc.add( "" );
for ( Iterator j = modelClass.getIdentifierFields( getGeneratedVersion() ).iterator(); j.hasNext(); )
{
ModelField identifier = (ModelField) j.next();
String name = identifier.getName();
if ( "boolean".equals( identifier.getType() ) || "byte".equals( identifier.getType() )
|| "char".equals( identifier.getType() ) || "double".equals( identifier.getType() )
|| "float".equals( identifier.getType() ) || "int".equals( identifier.getType() )
|| "short".equals( identifier.getType() ) || "long".equals( identifier.getType() ) )
{
sc.add( "result = result && " + name + " == that." + name + ";" );
}
else
{
name = "get" + capitalise( name ) + "()";
sc.add( "result = result && ( " + name + " == null ? that." + name + " == null : " + name
+ ".equals( that." + name + " ) );" );
}
}
if ( modelClass.getSuperClass() != null )
{
sc.add( "result = result && ( super.equals( other ) );" );
}
sc.add( "" );
sc.add( "return result;" );
return equals;
}
private JMethod generateToString( ModelClass modelClass )
{
JMethod toString = new JMethod( "toString", new JType( String.class.getName() ), null );
List identifierFields = modelClass.getIdentifierFields( getGeneratedVersion() );
JSourceCode sc = toString.getSourceCode();
if ( identifierFields.size() == 0 )
{
sc.add( "return super.toString();" );
return toString;
}
sc.add( "StringBuffer buf = new StringBuffer();" );
sc.add( "" );
for ( Iterator j = identifierFields.iterator(); j.hasNext(); )
{
ModelField identifier = (ModelField) j.next();
String getter = "boolean".equals( identifier.getType() ) ? "is" : "get";
sc.add( "buf.append( \"" + identifier.getName() + " = '\" );" );
sc.add( "buf.append( " + getter + capitalise( identifier.getName() ) + "() );" );
sc.add( "buf.append( \"'\" );" );
if ( j.hasNext() )
{
sc.add( "buf.append( \"\\n\" ); " );
}
}
if ( modelClass.getSuperClass() != null )
{
sc.add( "buf.append( \"\\n\" );" );
sc.add( "buf.append( super.toString() );" );
}
sc.add( "" );
sc.add( "return buf.toString();" );
return toString;
}
private JMethod generateHashCode( ModelClass modelClass )
{
JMethod hashCode = new JMethod( "hashCode", JType.INT, null );
List identifierFields = modelClass.getIdentifierFields( getGeneratedVersion() );
JSourceCode sc = hashCode.getSourceCode();
if ( identifierFields.size() == 0 )
{
sc.add( "return super.hashCode();" );
return hashCode;
}
sc.add( "int result = 17;" );
sc.add( "" );
for ( Iterator j = identifierFields.iterator(); j.hasNext(); )
{
ModelField identifier = (ModelField) j.next();
sc.add( "result = 37 * result + " + createHashCodeForField( identifier ) + ";" );
}
if ( modelClass.getSuperClass() != null )
{
sc.add( "result = 37 * result + super.hashCode();" );
}
sc.add( "" );
sc.add( "return result;" );
return hashCode;
}
/**
* Utility method that adds a period to the end of a string, if the last
* non-whitespace character of the string is not a punctuation mark or an
* end-tag.
*
* @param string The string to work with
* @return The string that came in but with a period at the end
*/
private String appendPeriod( String string )
{
if ( string == null )
{
return string;
}
String trimmedString = string.trim();
if ( trimmedString.endsWith( "." ) || trimmedString.endsWith( "!" ) || trimmedString.endsWith( "?" )
|| trimmedString.endsWith( ">" ) )
{
return string;
}
else
{
return string + ".";
}
}
private String createHashCodeForField( ModelField identifier )
{
String name = identifier.getName();
String type = identifier.getType();
if ( "boolean".equals( type ) )
{
return "( " + name + " ? 0 : 1 )";
}
else if ( "byte".equals( type ) || "char".equals( type ) || "short".equals( type ) || "int".equals( type ) )
{
return "(int) " + name;
}
else if ( "long".equals( type ) )
{
return "(int) ( " + name + " ^ ( " + name + " >>> 32 ) )";
}
else if ( "float".equals( type ) )
{
return "Float.floatToIntBits( " + name + " )";
}
else if ( "double".equals( type ) )
{
return "(int) ( Double.doubleToLongBits( " + identifier.getName() + " ) ^ ( Double.doubleToLongBits( " + identifier.getName() + " ) >>> 32 ) )";
}
else
{
return "( " + name + " != null ? " + name + ".hashCode() : 0 )";
}
}
private JField createField( ModelField modelField )
throws ModelloException
{
JType type;
String baseType = modelField.getType();
if ( modelField.isArray() )
{
// remove [] at the end of the type
baseType = baseType.substring( 0, baseType.length() - 2 );
}
if ( baseType.equals( "boolean" ) )
{
type = JType.BOOLEAN;
}
else if ( baseType.equals( "byte" ) )
{
type = JType.BYTE;
}
else if ( baseType.equals( "char" ) )
{
type = JType.CHAR;
}
else if ( baseType.equals( "double" ) )
{
type = JType.DOUBLE;
}
else if ( baseType.equals( "float" ) )
{
type = JType.FLOAT;
}
else if ( baseType.equals( "int" ) )
{
type = JType.INT;
}
else if ( baseType.equals( "short" ) )
{
type = JType.SHORT;
}
else if ( baseType.equals( "long" ) )
{
type = JType.LONG;
}
else if ( baseType.equals( "Date" ) )
{
type = new JClass( "java.util.Date" );
}
else if ( baseType.equals( "DOM" ) )
{
// TODO: maybe DOM is not how to specify it in the model, but just Object and markup Xpp3Dom for the Xpp3Reader?
// not sure how we'll treat it for the other sources, eg sql.
type = new JClass( "Object" );
}
else if ( baseType.equals( "Content" ) )
{
type = new JClass( "String" );
}
else
{
type = new JClass( baseType );
}
if ( modelField.isArray() )
{
type = new JArrayType( type, useJava5 );
}
JField field = new JField( type, modelField.getName() );
if ( modelField.isModelVersionField() )
{
field.setInitString( "\"" + getGeneratedVersion() + "\"" );
}
if ( modelField.getDefaultValue() != null )
{
field.setInitString( getJavaDefaultValue( modelField ) );
}
if ( StringUtils.isNotEmpty( modelField.getDescription() ) )
{
field.setComment( appendPeriod( modelField.getDescription() ) );
}
return field;
}
private void createField( JClass jClass, ModelField modelField )
throws ModelloException
{
JavaFieldMetadata javaFieldMetadata = (JavaFieldMetadata) modelField.getMetadata( JavaFieldMetadata.ID );
JField field = createField( modelField );
jClass.addField( field );
if ( javaFieldMetadata.isGetter() )
{
jClass.addMethod( createGetter( field, modelField ) );
}
if ( javaFieldMetadata.isSetter() )
{
jClass.addMethod( createSetter( field, modelField ) );
}
}
private JMethod createGetter( JField field, ModelField modelField )
{
String propertyName = capitalise( field.getName() );
JavaFieldMetadata javaFieldMetadata = (JavaFieldMetadata) modelField.getMetadata( JavaFieldMetadata.ID );
String prefix = javaFieldMetadata.isBooleanGetter() ? "is" : "get";
JType returnType = field.getType();
String interfaceCast = "";
if ( modelField instanceof ModelAssociation )
{
ModelAssociation modelAssociation = (ModelAssociation) modelField;
JavaAssociationMetadata javaAssociationMetadata = (JavaAssociationMetadata) modelAssociation
.getAssociationMetadata( JavaAssociationMetadata.ID );
if ( StringUtils.isNotEmpty( javaAssociationMetadata.getInterfaceName() )
&& !javaFieldMetadata.isBooleanGetter() )
{
returnType = new JClass( javaAssociationMetadata.getInterfaceName() );
interfaceCast = "(" + javaAssociationMetadata.getInterfaceName() + ") ";
}
}
JMethod getter = new JMethod( prefix + propertyName, returnType, null );
StringBuffer comment = new StringBuffer( "Get " );
if ( StringUtils.isEmpty( modelField.getDescription() ) )
{
comment.append( "the " );
comment.append( field.getName() );
comment.append( " field" );
}
else
{
comment.append( StringUtils.lowercaseFirstLetter( modelField.getDescription().trim() ) );
}
getter.getJDocComment().setComment( appendPeriod( comment.toString() ) );
getter.getSourceCode().add( "return " + interfaceCast + "this." + field.getName() + ";" );
return getter;
}
private JMethod createSetter( JField field, ModelField modelField )
throws ModelloException
{
String propertyName = capitalise( field.getName() );
JMethod setter = new JMethod( "set" + propertyName );
StringBuffer comment = new StringBuffer( "Set " );
if ( StringUtils.isEmpty( modelField.getDescription() ) )
{
comment.append( "the " );
comment.append( field.getName() );
comment.append( " field" );
}
else
{
comment.append( StringUtils.lowercaseFirstLetter( modelField.getDescription().trim() ) );
}
setter.getJDocComment().setComment( appendPeriod( comment.toString() ) );
JType parameterType = getDesiredType( modelField, false );
setter.addParameter( new JParameter( parameterType, field.getName() ) );
JSourceCode sc = setter.getSourceCode();
if ( modelField instanceof ModelAssociation )
{
ModelAssociation modelAssociation = (ModelAssociation) modelField;
JavaAssociationMetadata javaAssociationMetadata = (JavaAssociationMetadata) modelAssociation
.getAssociationMetadata( JavaAssociationMetadata.ID );
boolean isOneMultiplicity = isBidirectionalAssociation( modelAssociation )
&& modelAssociation.isOneMultiplicity();
if ( isOneMultiplicity && javaAssociationMetadata.isBidi() )
{
sc.add( "if ( this." + field.getName() + " != null )" );
sc.add( "{" );
sc.indent();
sc.add( "this." + field.getName() + ".break" + modelAssociation.getModelClass().getName() +
"Association( this );" );
sc.unindent();
sc.add( "}" );
sc.add( "" );
}
String interfaceCast = "";
if ( StringUtils.isNotEmpty( javaAssociationMetadata.getInterfaceName() )
&& modelAssociation.isOneMultiplicity() )
{
interfaceCast = "(" + field.getType().getName() + ") ";
createClassCastAssertion( sc, modelField, "set" );
}
sc.add( "this." + field.getName() + " = " + interfaceCast + field.getName() + ";" );
if ( isOneMultiplicity && javaAssociationMetadata.isBidi() )
{
sc.add( "" );
sc.add( "if ( " + field.getName() + " != null )" );
sc.add( "{" );
sc.indent();
sc.add( "this." + field.getName() + ".create" + modelAssociation.getModelClass().getName() +
"Association( this );" );
sc.unindent();
sc.add( "}" );
}
}
else
{
sc.add( "this." + field.getName() + " = " + field.getName() + ";" );
}
return setter;
}
private void createClassCastAssertion( JSourceCode sc, ModelField modelField, String crudModifier )
throws ModelloException
{
String propertyName = capitalise( modelField.getName() );
JField field = createField( modelField );
String fieldName = field.getName();
JType type = field.getType();
if ( modelField instanceof ModelAssociation )
{
ModelAssociation modelAssociation = (ModelAssociation) modelField;
JavaAssociationMetadata javaAssociationMetadata = (JavaAssociationMetadata) modelAssociation
.getAssociationMetadata( JavaAssociationMetadata.ID );
if ( StringUtils.isNotEmpty( javaAssociationMetadata.getInterfaceName() )
&& modelAssociation.isOneMultiplicity() )
{
type = new JClass( javaAssociationMetadata.getInterfaceName() );
}
else
{
fieldName = uncapitalise( modelAssociation.getTo() );
type = new JClass( modelAssociation.getTo() );
}
}
String instanceName = type.getName();
// Add sane class cast exception message
// When will sun ever fix this?
sc.add( "if ( !(" + fieldName + " instanceof " + instanceName + ") )" );
sc.add( "{" );
sc.indent();
sc.add( "throw new ClassCastException( \"" + modelField.getModelClass().getName() + "." + crudModifier
+ propertyName + "(" + fieldName + ") parameter must be instanceof \" + " + instanceName +
".class.getName() );" );
sc.unindent();
sc.add( "}" );
}
private void createAssociation( JClass jClass, ModelAssociation modelAssociation, JSourceCode jConstructorSource )
throws ModelloException
{
JavaFieldMetadata javaFieldMetadata = (JavaFieldMetadata) modelAssociation.getMetadata( JavaFieldMetadata.ID );
JavaAssociationMetadata javaAssociationMetadata =
(JavaAssociationMetadata) modelAssociation.getAssociationMetadata( JavaAssociationMetadata.ID );
if ( !JavaAssociationMetadata.INIT_TYPES.contains( javaAssociationMetadata.getInitializationMode() ) )
{
throw new ModelloException( "The Java Modello Generator cannot use '"
+ javaAssociationMetadata.getInitializationMode() + "' as a <association java.init=\""
+ javaAssociationMetadata.getInitializationMode() + "\"> "
+ "value, the only the following are acceptable " + JavaAssociationMetadata.INIT_TYPES );
}
if ( modelAssociation.isManyMultiplicity() )
{
JType type;
if ( modelAssociation.isGenericType() )
{
type = new JCollectionType( modelAssociation.getType(), new JClass( modelAssociation.getTo() ),
useJava5 );
}
else
{
type = new JClass( modelAssociation.getType() );
}
JField jField = new JField( type, modelAssociation.getName() );
if ( !isEmpty( modelAssociation.getComment() ) )
{
jField.setComment( modelAssociation.getComment() );
}
if ( StringUtils.equals( javaAssociationMetadata.getInitializationMode(),
JavaAssociationMetadata.FIELD_INIT ) )
{
jField.setInitString( getDefaultValue ( modelAssociation ) );
}
if ( StringUtils.equals( javaAssociationMetadata.getInitializationMode(),
JavaAssociationMetadata.CONSTRUCTOR_INIT ) )
{
jConstructorSource.add( "this." + jField.getName() + " = " + getDefaultValue ( modelAssociation ) + ";" );
}
jClass.addField( jField );
if ( javaFieldMetadata.isGetter() )
{
String propertyName = capitalise( jField.getName() );
JMethod getter = new JMethod( "get" + propertyName, jField.getType(), null );
JSourceCode sc = getter.getSourceCode();
if ( StringUtils.equals( javaAssociationMetadata.getInitializationMode(),
JavaAssociationMetadata.LAZY_INIT ) )
{
sc.add( "if ( this." + jField.getName() + " == null )" );
sc.add( "{" );
sc.indent();
sc.add( "this." + jField.getName() + " = " + getDefaultValue ( modelAssociation ) + ";" );
sc.unindent();
sc.add( "}" );
sc.add( "" );
}
sc.add( "return this." + jField.getName() + ";" );
jClass.addMethod( getter );
}
if ( javaFieldMetadata.isSetter() )
{
jClass.addMethod( createSetter( jField, modelAssociation ) );
}
if ( javaAssociationMetadata.isAdder() )
{
createAdder( modelAssociation, jClass );
}
}
else
{
createField( jClass, modelAssociation );
}
if ( isBidirectionalAssociation( modelAssociation ) )
{
if ( javaAssociationMetadata.isBidi() )
{
createCreateAssociation( jClass, modelAssociation );
}
if ( javaAssociationMetadata.isBidi() )
{
createBreakAssociation( jClass, modelAssociation );
}
}
}
private void createCreateAssociation( JClass jClass, ModelAssociation modelAssociation )
{
JMethod createMethod = new JMethod( "create" + modelAssociation.getTo() + "Association" );
JavaAssociationMetadata javaAssociationMetadata =
(JavaAssociationMetadata) modelAssociation.getAssociationMetadata( JavaAssociationMetadata.ID );
createMethod.addParameter(
new JParameter( new JClass( modelAssociation.getTo() ), uncapitalise( modelAssociation.getTo() ) ) );
// TODO: remove after tested
// createMethod.addException( new JClass( "Exception" ) );
JSourceCode sc = createMethod.getSourceCode();
if ( modelAssociation.isOneMultiplicity() )
{
if ( javaAssociationMetadata.isBidi() )
{
sc.add( "if ( this." + modelAssociation.getName() + " != null )" );
sc.add( "{" );
sc.indent();
sc.add(
"break" + modelAssociation.getTo() + "Association( this." + modelAssociation.getName() + " );" );
sc.unindent();
sc.add( "}" );
sc.add( "" );
}
sc.add( "this." + modelAssociation.getName() + " = " + uncapitalise( modelAssociation.getTo() ) + ";" );
}
else
{
jClass.addImport( "java.util.Collection" );
sc.add( "Collection " + modelAssociation.getName() + " = get" + capitalise( modelAssociation.getName() )
+ "();" );
sc.add( "" );
sc.add( "if ( " + modelAssociation.getName() + ".contains( "
+ uncapitalise( modelAssociation.getTo() ) + " ) )" );
sc.add( "{" );
sc.indent();
sc.add( "throw new IllegalStateException( \"" + uncapitalise( modelAssociation.getTo() )
+ " is already assigned.\" );" );
sc.unindent();
sc.add( "}" );
sc.add( "" );
sc.add( modelAssociation.getName() + ".add( " + uncapitalise( modelAssociation.getTo() ) + " );" );
}
jClass.addMethod( createMethod );
}
private void createBreakAssociation( JClass jClass, ModelAssociation modelAssociation )
{
JSourceCode sc;
JMethod breakMethod = new JMethod( "break" + modelAssociation.getTo() + "Association" );
breakMethod.addParameter(
new JParameter( new JClass( modelAssociation.getTo() ), uncapitalise( modelAssociation.getTo() ) ) );
// TODO: remove after tested
// breakMethod.addException( new JClass( "Exception" ) );
sc = breakMethod.getSourceCode();
if ( modelAssociation.isOneMultiplicity() )
{
sc.add(
"if ( this." + modelAssociation.getName() + " != " + uncapitalise( modelAssociation.getTo() ) + " )" );
sc.add( "{" );
sc.indent();
sc.add( "throw new IllegalStateException( \"" + uncapitalise( modelAssociation.getTo() )
+ " isn't associated.\" );" );
sc.unindent();
sc.add( "}" );
sc.add( "" );
sc.add( "this." + modelAssociation.getName() + " = null;" );
}
else
{
sc.add( "if ( ! get" + capitalise( modelAssociation.getName() ) + "().contains( "
+ uncapitalise( modelAssociation.getTo() ) + " ) )" );
sc.add( "{" );
sc.indent();
sc.add( "throw new IllegalStateException( \"" + uncapitalise( modelAssociation.getTo() )
+ " isn't associated.\" );" );
sc.unindent();
sc.add( "}" );
sc.add( "" );
sc.add( "get" + capitalise( modelAssociation.getName() ) + "().remove( "
+ uncapitalise( modelAssociation.getTo() ) + " );" );
}
jClass.addMethod( breakMethod );
}
private void createAdder( ModelAssociation modelAssociation, JClass jClass )
throws ModelloException
{
String fieldName = modelAssociation.getName();
JavaAssociationMetadata javaAssociationMetadata =
(JavaAssociationMetadata) modelAssociation.getAssociationMetadata( JavaAssociationMetadata.ID );
String parameterName = uncapitalise( modelAssociation.getTo() );
String implementationParameterName = parameterName;
boolean bidirectionalAssociation = isBidirectionalAssociation( modelAssociation );
JType addType;
if ( StringUtils.isNotEmpty( javaAssociationMetadata.getInterfaceName() ) )
{
addType = new JClass( javaAssociationMetadata.getInterfaceName() );
implementationParameterName = "( (" + modelAssociation.getTo() + ") " + parameterName + " )";
}
else if ( modelAssociation.getToClass() != null )
{
addType = new JClass( modelAssociation.getToClass().getName() );
}
else
{
addType = new JClass( "String" );
}
if ( modelAssociation.getType().equals( ModelDefault.PROPERTIES )
|| modelAssociation.getType().equals( ModelDefault.MAP ) )
{
JMethod adder = new JMethod( "add" + capitalise( singular( fieldName ) ) );
if ( modelAssociation.getType().equals( ModelDefault.MAP ) )
{
adder.addParameter( new JParameter( new JClass( "Object" ), "key" ) );
}
else
{
adder.addParameter( new JParameter( new JClass( "String" ), "key" ) );
}
adder.addParameter( new JParameter( new JClass( modelAssociation.getTo() ), "value" ) );
adder.getSourceCode().add( "get" + capitalise( fieldName ) + "().put( key, value );" );
jClass.addMethod( adder );
}
else
{
JMethod adder = new JMethod( "add" + singular( capitalise( fieldName ) ) );
adder.addParameter( new JParameter( addType, parameterName ) );
createClassCastAssertion( adder.getSourceCode(), modelAssociation, "add" );
adder.getSourceCode().add(
"get" + capitalise( fieldName ) + "().add( " + implementationParameterName + " );" );
if ( bidirectionalAssociation && javaAssociationMetadata.isBidi() )
{
// TODO: remove after tested
// adder.addException( new JClass( "Exception" ) );
adder.getSourceCode().add( implementationParameterName + ".create"
+ modelAssociation.getModelClass().getName() + "Association( this );" );
}
jClass.addMethod( adder );
JMethod remover = new JMethod( "remove" + singular( capitalise( fieldName ) ) );
remover.addParameter( new JParameter( addType, parameterName ) );
createClassCastAssertion( remover.getSourceCode(), modelAssociation, "remove" );
if ( bidirectionalAssociation && javaAssociationMetadata.isBidi() )
{
// TODO: remove after tested
// remover.addException( new JClass( "Exception" ) );
remover.getSourceCode().add(
parameterName + ".break" + modelAssociation.getModelClass().getName() + "Association( this );" );
}
remover.getSourceCode().add(
"get" + capitalise( fieldName ) + "().remove( " + implementationParameterName + " );" );
jClass.addMethod( remover );
}
}
private boolean isBidirectionalAssociation( ModelAssociation association )
{
Model model = association.getModelClass().getModel();
if ( !isClassInModel( association.getTo(), model ) )
{
return false;
}
ModelClass toClass = association.getToClass();
for ( Iterator j = toClass.getFields( getGeneratedVersion() ).iterator(); j.hasNext(); )
{
ModelField modelField = (ModelField) j.next();
if ( !( modelField instanceof ModelAssociation ) )
{
continue;
}
ModelAssociation modelAssociation = (ModelAssociation) modelField;
if ( !isClassInModel( modelAssociation.getTo(), model ) )
{
continue;
}
ModelClass totoClass = modelAssociation.getToClass();
if ( association.getModelClass().equals( totoClass ) )
{
return true;
}
}
return false;
}
private JType getDesiredType( ModelField modelField, boolean useTo )
throws ModelloException
{
JField field = createField( modelField );
JType type = field.getType();
if ( modelField instanceof ModelAssociation )
{
ModelAssociation modelAssociation = (ModelAssociation) modelField;
JavaAssociationMetadata javaAssociationMetadata = (JavaAssociationMetadata) modelAssociation
.getAssociationMetadata( JavaAssociationMetadata.ID );
if ( StringUtils.isNotEmpty( javaAssociationMetadata.getInterfaceName() )
&& ! modelAssociation.isManyMultiplicity() )
{
type = new JClass( javaAssociationMetadata.getInterfaceName() );
}
else if ( modelAssociation.isManyMultiplicity() && modelAssociation.isGenericType() )
{
type = new JCollectionType( modelAssociation.getType(), new JClass( modelAssociation.getTo() ),
useJava5 );
}
else if ( useTo )
{
type = new JClass( modelAssociation.getTo() );
}
}
return type;
}
}
|
package jade.core.sam;
/**
* A default ready-made implementation of the AverageMeasureProvider interface that offers
* methods to add measure samples and automatically computes an <code>AverageMeasure</code>
* when the <code>getValue()</code> method is called.
*/
public class AverageMeasureProviderImpl implements AverageMeasureProvider {
private double sum = 0.0;
private int nSamples = 0;
public synchronized void addSample(Number value) {
if (value != null) {
addSample(value.doubleValue());
}
}
public synchronized void addSample(int value) {
nSamples++;
sum += value;
}
public synchronized void addSample(long value) {
nSamples++;
sum += value;
}
public synchronized void addSample(float value) {
nSamples++;
sum += value;
}
public synchronized void addSample(double value) {
nSamples++;
sum += value;
}
public synchronized AverageMeasure getValue() {
double avg = (nSamples != 0 ? sum / nSamples : 0);
AverageMeasure result = new AverageMeasure(avg, nSamples);
nSamples = 0;
sum = 0.0;
return result;
}
}
|
package org.activiti.cycle.impl.connector.signavio.provider;
import org.activiti.cycle.Content;
import org.activiti.cycle.RepositoryArtifact;
import org.activiti.cycle.impl.connector.signavio.SignavioConnector;
import org.activiti.cycle.impl.connector.signavio.util.SignavioSvgApiBuilder;
public class SvgApiProvider extends SignavioContentRepresentationProvider {
@Override
public void addValueToContent(Content content, SignavioConnector connector, RepositoryArtifact artifact) {
String text = new SignavioSvgApiBuilder(connector, artifact).buildHtml();
content.setValue(text);
}
}
|
package org.xins.types.standard;
import org.xins.types.Type;
import org.xins.types.TypeValueException;
import org.xins.util.MandatoryArgumentChecker;
import org.xins.util.text.FastStringBuffer;
/**
* Standard type <em>_date</em>.
*
* @version $Revision$ $Date$
* @author Ernst de Haan (<a href="mailto:znerd@FreeBSD.org">znerd@FreeBSD.org</a>)
*
* @since XINS 0.166
*/
public class Date extends Type {
// Class fields
/**
* The only instance of this class. This field is never <code>null</code>.
*/
public final static Date SINGLETON = new Date();
// Class functions
public static Value fromStringForRequired(String string)
throws IllegalArgumentException, TypeValueException {
// Check preconditions
MandatoryArgumentChecker.check("string", string);
return (Value) SINGLETON.fromString(string);
}
/**
* Constructs a <code>Date.Value</code> from the specified string.
*
* @param string
* the string to convert, can be <code>null</code>.
*
* @return
* the {@link Value}, or <code>null</code> if
* <code>string == null</code>.
*
* @throws TypeValueException
* if the specified string does not represent a valid value for this
* type.
*/
public static Value fromStringForOptional(String string)
throws TypeValueException {
return (Value) SINGLETON.fromString(string);
}
/**
* Converts the specified <code>Date.Value</code> to a string.
*
* @param value
* the value to convert, can be <code>null</code>.
*
* @return
* the textual representation of the value, or <code>null</code> if and
* only if <code>value == null</code>.
*/
public static String toString(Value value) {
// Short-circuit if the argument is null
if (value == null) {
return null;
}
return toString(value.getYear(),
value.getMonthOfYear(),
value.getDayOfMonth());
}
/**
* Converts the specified combination of a year, month and day to a string.
*
* @param year
* the year, must be >=0 and <= 9999.
*
* @param month
* the month of the year, must be >= 1 and <= 12.
*
* @param day
* the day of the month, must be >= 1 and <= 31.
*
* @return
* the textual representation of the value, never <code>null</code>.
*/
private static String toString(int year, int month, int day) {
// Short-circuit if the argument is null
if (value == null) {
return null;
}
// Use a buffer to create the string
FastStringBuffer buffer = new FastStringBuffer(8);
// Append the year
if (year < 10) {
buffer.append("000");
} else if (year < 100) {
buffer.append("00");
} else if (year < 1000) {
buffer.append('0');
}
buffer.append(year);
// Append the month
if (month < 10) {
buffer.append('0');
}
buffer.append(month);
// Append the day
if (day < 10) {
buffer.append('0');
}
buffer.append(day);
return buffer.toString();
}
// Constructors
/**
* Constructs a new <code>Date</code> instance.
* This constructor is private, the field {@link #SINGLETON} should be
* used.
*/
private Date() {
super("date", Value.class);
}
// Fields
// Methods
protected final boolean isValidValueImpl(String value) {
// First check the length
if (value.length() != 8) {
return false;
}
// Convert all 3 components of the string to integers
int y, m, d;
try {
y = Integer.parseInt(value.substring(0, 4));
m = Integer.parseInt(value.substring(4, 2));
d = Integer.parseInt(value.substring(6, 2));
} catch (NumberFormatException nfe) {
return false;
}
// Check that the values are in the correct range
return (y >= 0) && (m >= 1) && (m <= 12) && (d >= 1) && (d <= 31);
}
protected final Object fromStringImpl(String string)
throws TypeValueException {
// Convert all 3 components of the string to integers
int y, m, d;
try {
y = Integer.parseInt(string.substring(0, 4));
m = Integer.parseInt(string.substring(4, 2));
d = Integer.parseInt(string.substring(6, 2));
} catch (NumberFormatException nfe) {
// Should never happen, since isValidValueImpl(String) will have been
// called
throw new TypeValueException(this, string);
}
// Check that the values are in the correct range
return new Value(y, m, d);
}
public final String toString(Object value)
throws IllegalArgumentException, ClassCastException, TypeValueException {
// Check preconditions
MandatoryArgumentChecker.check("value", value);
// The argument must be a PropertyReader
return toString((Value) value);
}
// Inner classes
/**
* Date value, composed of a year, month and a day.
*
* @version $Revision$ $Date$
* @author Ernst de Haan (<a href="mailto:znerd@FreeBSD.org">znerd@FreeBSD.org</a>)
*
* @since XINS 0.166
*/
public static final class Value {
// Constructors
/**
* Constructs a new date value. The values will not be checked.
*
* @param year
* the year, e.g. <code>2004</code>.
*
* @param month
* the month of the year, e.g. <code>11</code> for November.
*
* @param day
* the day of the month, e.g. <code>1</code> for the first day of the
* month.
*/
Value(int year, int month, int day) {
_year = year;
_month = month;
_day = day;
_asString = toString(year, month, day);
}
// Fields
/**
* The year. E.g. <code>2004</code>.
*/
private final int _year;
/**
* The month of the year. E.g. <code>11</code> for November.
*/
private final int _month;
/**
* The day of the month. E.g. <code>1</code> for the first day of the
* month.
*/
private final int _day;
/**
* Textual representation of this date. Composed of the year (YYYY),
* month (MM) and day (DD) in the format: <em>YYYYMMDD</em>.
*/
private final String _asString;
// Methods
/**
* Returns the year.
*
* @return
* the year, between 0 and 9999 (inclusive).
*/
public int getYear() {
return _year;
}
/**
* Returns the month of the year.
*
* @return
* the month of the year, between 1 and 12 (inclusive).
*/
public int getMonthOfYear() {
return _month;
}
/**
* Returns the day of the month.
*
* @return
* the day of the month, between 1 and 31 (inclusive).
*/
public int getDayOfMonth() {
return _day;
}
public String toString() {
return _asString;
}
}
}
|
package org.xins.util.io;
import java.io.File;
import org.xins.util.MandatoryArgumentChecker;
/**
* File watcher thread. This thread checks if a file changed and if it has, it
* notifies the listener. The check is performed every <em>n</em> seconds,
* where <em>n</em> can be configured.
*
* @version $Revision$ $Date$
* @author Ernst de Haan (<a href="mailto:znerd@FreeBSD.org">znerd@FreeBSD.org</a>)
*
* @since XINS 0.121
*/
public final class FileWatcher extends Thread {
// Class fields
// Class functions
// Constructors
public FileWatcher(String file, int delay, Listener listener)
throws IllegalArgumentException {
// Check preconditions
MandatoryArgumentChecker.check("file", file, "listener", listener);
if (delay < 1) {
throw new IllegalArgumentException("delay (" + delay + ") < 1");
}
// Store the information
_file = new File(file);
_delay = 1000 * (long) delay;
_listener = listener;
_stopped = false;
// Configure thread as daemon
setDaemon(true);
// Immediately check if the file exists
try {
if (_file.exists()) {
_lastModified = _file.lastModified();
}
} catch (SecurityException exception) {
// ignore
}
}
// Fields
/**
* The file to watch. Not <code>null</code>.
*/
private final File _file;
/**
* Delay in seconds, at least 1.
*/
private final long _delay;
/**
* The listener. Not <code>null</code>
*/
private final Listener _listener;
/**
* Timestamp of the last modification of the file. Initially this field is
* <code>0L</code>.
*/
private long _lastModified;
/**
* Flag that indicates if this thread has been stopped.
*/
private boolean _stopped;
// Methods
public void run() throws IllegalStateException {
// Check preconditions
if (Thread.currentThread() != this) {
throw new IllegalStateException("Thread.currentThread() != this");
}
while (! _stopped) {
try {
while(! _stopped) {
// Wait for the designated amount of time
sleep(_delay);
// Check if the file changed
check();
}
} catch (InterruptedException exception) {
// Fall through
}
}
}
/**
* Stops this thread.
*/
public void end() {
_stopped = true;
this.interrupt();
}
/**
* Checks if the file changed. The following algorithm is used:
*
* <ul>
* <li>if the file does not exist, then {@link Listener#fileNotFound()} is called;
* <li>if the file was modified, then {@link Listener#fileModified()} is called;
* <li>if {@link File#exists()} or {@link File#lastModified()} throws a {@link SecurityException}, then {@link Listener#securityException(SecurityException)} is called;
* <li>if the file was not modified and no {@link SecurityException}, then {@link Listener#fileNotModified()} is called.
* </ul>
*/
private void check() {
long lastModified;
try {
// If the file exists, then check when it was last modified...
if (_file.exists()) {
lastModified = _file.lastModified();
// ...otherwise notify the listener and return.
} else {
_lastModified = 0;
_listener.fileNotFound();
return;
}
// If there was an authorisation error, notify the listener.
} catch (SecurityException exception) {
_lastModified = 0;
_listener.securityException(exception);
return;
}
// No authorisation error, check if the file was modified.
if (lastModified != _lastModified) {
_listener.fileModified();
} else {
_listener.fileNotModified();
}
_lastModified = lastModified;
}
// Inner classes
/**
* Interface for file watcher listeners.
*
* @version $Revision$ $Date$
* @author Ernst de Haan (<a href="mailto:znerd@FreeBSD.org">znerd@FreeBSD.org</a>)
*
* @since XINS 0.121
*/
public interface Listener {
/**
* Callback method, called if the file is checked but cannot be found.
*/
void fileNotFound();
/**
* Callback method, called if an authorisation error prevents that the
* file is checked for existence and last modification date.
*
* @param exception
* the caught exception, not <code>null</code>.
*/
void securityException(SecurityException exception);
/**
* Callback method, called if the file was checked and found to be
* modified.
*/
void fileModified();
/**
* Callback method, called if the file was checked but found not to be
* modified.
*/
void fileNotModified();
}
}
|
package com.sun.facelets;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Writer;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.FacesException;
import javax.faces.application.StateManager;
import javax.faces.application.ViewHandler;
import javax.faces.component.UIComponent;
import javax.faces.component.UIViewRoot;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import javax.faces.render.RenderKit;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import com.sun.facelets.compiler.Compiler;
import com.sun.facelets.compiler.SAXCompiler;
import com.sun.facelets.compiler.TagLibraryConfig;
import com.sun.facelets.spi.RefreshableFaceletFactory;
import com.sun.facelets.tag.TagLibrary;
import com.sun.facelets.util.FacesAPI;
/**
* ViewHandler implementation for Facelets
*
* @author Jacob Hookom
* @version $Id: FaceletViewHandler.java,v 1.9 2005/07/13 04:46:06 jhook Exp $
*/
public class FaceletViewHandler extends ViewHandler {
protected final static Logger log = Logger
.getLogger("facelets.viewHandler");
public final static long DEFAULT_REFRESH_PERIOD = 2;
public final static String REFRESH_PERIOD_PARAM_NAME = "facelet.REFRESH_PERIOD";
public final static String LIBRARIES_PARAM_NAME = "facelet.LIBRARIES";
protected final static String STATE_KEY = "com.sun.facelets.VIEW_STATE";
private final ViewHandler parent;
private boolean initialized = false;
private String defaultSuffix;
protected static void removeTransient(UIComponent c) {
UIComponent d, e;
if (c.getChildCount() > 0) {
for (Iterator itr = c.getChildren().iterator(); itr.hasNext();) {
d = (UIComponent) itr.next();
if (d.getFacets().size() > 0) {
for (Iterator jtr = d.getFacets().values().iterator(); jtr
.hasNext();) {
e = (UIComponent) jtr.next();
if (e.isTransient()) {
jtr.remove();
} else {
removeTransient(e);
}
}
}
if (d.isTransient()) {
itr.remove();
} else {
removeTransient(d);
}
}
}
if (c.getFacets().size() > 0) {
for (Iterator itr = c.getFacets().values().iterator(); itr
.hasNext();) {
d = (UIComponent) itr.next();
if (d.isTransient()) {
itr.remove();
} else {
removeTransient(d);
}
}
}
}
public FaceletViewHandler(ViewHandler parent) {
this.parent = parent;
}
protected void initialize() {
synchronized (this) {
if (!this.initialized) {
log.fine("Initializing");
Compiler c = this.createCompiler();
this.initializeCompiler(c);
FaceletFactory f = this.createFaceletFactory(c);
FaceletFactory.setInstance(f);
this.initialized = true;
log.fine("Initialization Successful");
}
}
}
protected FaceletFactory createFaceletFactory(Compiler c) {
long refreshPeriod = DEFAULT_REFRESH_PERIOD;
FacesContext ctx = FacesContext.getCurrentInstance();
String userPeriod = ctx.getExternalContext().getInitParameter(
REFRESH_PERIOD_PARAM_NAME);
if (userPeriod != null && userPeriod.length() > 0) {
refreshPeriod = Long.parseLong(userPeriod);
}
log.fine("Using Refresh Period: " + refreshPeriod + " sec");
try {
return new RefreshableFaceletFactory(c, ctx.getExternalContext()
.getResource("/"), refreshPeriod);
} catch (MalformedURLException e) {
throw new FaceletException("Error Creating FaceletFactory", e);
}
}
protected Compiler createCompiler() {
return new SAXCompiler();
}
protected void initializeCompiler(Compiler c) {
FacesContext ctx = FacesContext.getCurrentInstance();
ExternalContext ext = ctx.getExternalContext();
String libParam = ext.getInitParameter(LIBRARIES_PARAM_NAME);
if (libParam != null) {
libParam = libParam.trim();
String[] libs = libParam.split(";");
URL src;
TagLibrary libObj;
for (int i = 0; i < libs.length; i++) {
try {
src = ext.getResource(libs[i]);
if (src == null) {
throw new FileNotFoundException(libs[i]);
}
libObj = TagLibraryConfig.create(src);
c.addTagLibrary(libObj);
log.fine("Successfully Loaded Library: " + libs[i]);
} catch (IOException e) {
log.log(Level.SEVERE, "Error Loading Library: " + libs[i],
e);
}
}
}
}
public UIViewRoot restoreView(FacesContext context, String viewId) {
UIViewRoot root = null;
try {
root = this.parent.restoreView(context, viewId);
} catch (Exception e) {
log.log(Level.WARNING, "Error Restoring View: " + viewId, e);
}
if (root != null) {
log.fine("View Restored: " + root.getViewId());
} else {
log.fine("Unable to restore View");
}
return root;
}
/*
* (non-Javadoc)
*
* @see javax.faces.application.ViewHandlerWrapper#getWrapped()
*/
protected ViewHandler getWrapped() {
return this.parent;
}
protected ResponseWriter createResponseWriter(FacesContext context)
throws IOException, FacesException {
ExternalContext extContext = context.getExternalContext();
RenderKit renderKit = context.getRenderKit();
ServletRequest request = (ServletRequest) extContext.getRequest();
ServletResponse response = (ServletResponse) extContext.getResponse();
String encoding = request.getCharacterEncoding();
// Create a dummy ResponseWriter with a bogus writer,
// so we can figure out what content type the ReponseWriter
// is really going to ask for
ResponseWriter writer = renderKit.createResponseWriter(
new NullWriter(), "text/html", encoding);
response.setContentType(writer.getContentType() + "; charset = "
+ encoding);
// Now, clone with the real writer
writer = writer.cloneWithWriter(response.getWriter());
return writer;
}
protected void buildView(FacesContext context, UIViewRoot viewToRender)
throws IOException, FacesException {
// setup our viewId
String renderedViewId = this.getRenderedViewId(context, viewToRender
.getViewId());
viewToRender.setViewId(renderedViewId);
if (log.isLoggable(Level.FINE)) {
log.fine("Building View: " + renderedViewId);
}
// grab our FaceletFactory and create a Facelet
FaceletFactory factory = FaceletFactory.getInstance();
Facelet f = factory.getFacelet(viewToRender.getViewId());
// populate UIViewRoot
f.apply(context, viewToRender);
}
public void renderView(FacesContext context, UIViewRoot viewToRender)
throws IOException, FacesException {
if (!this.initialized) {
this.initialize();
}
// exit if the view is not to be rendered
if (!viewToRender.isRendered()) {
return;
}
if (log.isLoggable(Level.FINE)) {
log.fine("Rendering View: " + viewToRender.getViewId());
}
// build view
this.buildView(context, viewToRender);
// setup writer and assign it to the context
ResponseWriter writer = this.createResponseWriter(context);
context.setResponseWriter(writer);
// render the view to the response
writer.startDocument();
if (FacesAPI.getVersion() >= 12) {
viewToRender.encodeAll(context);
} else {
encodeRecursive(context, viewToRender);
}
writer.endDocument();
writer.close();
// finally clean up transients if viewState = true
ExternalContext extContext = context.getExternalContext();
if (extContext.getRequestMap().containsKey(STATE_KEY)) {
removeTransient(viewToRender);
}
}
protected final static void encodeRecursive(FacesContext context,
UIComponent viewToRender) throws IOException, FacesException {
if (viewToRender.isRendered()) {
viewToRender.encodeBegin(context);
if (viewToRender.getRendersChildren()) {
viewToRender.encodeChildren(context);
} else if (viewToRender.getChildCount() > 0) {
Iterator kids = viewToRender.getChildren().iterator();
while (kids.hasNext()) {
UIComponent kid = (UIComponent) kids.next();
encodeRecursive(context, kid);
}
}
viewToRender.encodeEnd(context);
}
}
public String getDefaultSuffix(FacesContext context) throws FacesException {
if (this.defaultSuffix == null) {
ExternalContext extCtx = context.getExternalContext();
String viewSuffix = extCtx
.getInitParameter(ViewHandler.DEFAULT_SUFFIX_PARAM_NAME);
this.defaultSuffix = (viewSuffix != null) ? viewSuffix
: ViewHandler.DEFAULT_SUFFIX;
}
return this.defaultSuffix;
}
protected String getRenderedViewId(FacesContext context, String actionId) {
ExternalContext extCtx = context.getExternalContext();
String viewId = extCtx.getRequestPathInfo();
if (extCtx.getRequestPathInfo() == null) {
String facesSuffix = actionId.substring(actionId.lastIndexOf('.'));
String viewSuffix = this.getDefaultSuffix(context);
viewId = actionId.replaceFirst(facesSuffix, viewSuffix);
}
if (log.isLoggable(Level.FINE)) {
log.fine("ActionId -> ViewId: " + actionId + " -> " + viewId);
}
return viewId;
}
public void writeState(FacesContext context) throws IOException {
StateManager stateMgr = context.getApplication().getStateManager();
ExternalContext extContext = context.getExternalContext();
Object state = extContext.getRequestMap().get(STATE_KEY);
if (state == null) {
state = stateMgr.saveSerializedView(context);
extContext.getRequestMap().put(STATE_KEY, state);
}
stateMgr.writeState(context, (StateManager.SerializedView) state);
}
public Locale calculateLocale(FacesContext context) {
return this.parent.calculateLocale(context);
}
public String calculateRenderKitId(FacesContext context) {
return this.parent.calculateRenderKitId(context);
}
public UIViewRoot createView(FacesContext context, String viewId) {
return this.parent.createView(context, viewId);
}
public String getActionURL(FacesContext context, String viewId) {
return this.parent.getActionURL(context, viewId);
}
public String getResourceURL(FacesContext context, String path) {
return this.parent.getResourceURL(context, path);
}
static private class NullWriter extends Writer {
public void write(char[] buffer) {
}
public void write(char[] buffer, int off, int len) {
}
public void write(String str) {
}
public void write(int c) {
}
public void write(String str, int off, int len) {
}
public void close() {
}
public void flush() {
}
}
}
|
package nginx.clojure.logger;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
/**
* This tiny log service is mainly for debug use
*/
public class TinyLogService implements LoggerService {
public static final String NGINX_CLOJURE_LOG_LEVEL = "nginx.clojure.logger.level";
public enum MsgType{ trace, debug,info, warn, error, fatal };
public static final Set<String> LOG_METHODS = new HashSet<String>();
static {
for (MsgType t : MsgType.values()) {
LOG_METHODS.add(t.name());
}
}
protected MsgType level = MsgType.info;
protected PrintStream out;
protected PrintStream err;
protected boolean showMethod = false;
public static TinyLogService createDefaultTinyLogService() {
return new TinyLogService(TinyLogService.getSystemPropertyOrDefaultLevel(), System.err, System.err);
}
public static MsgType getSystemPropertyOrDefaultLevel(String p, MsgType t) {
String l = System.getProperty(p);
if (l != null){
try{
return MsgType.valueOf(l);
}catch (Exception e) {
e.printStackTrace();
}
}
return t == null ? MsgType.info : t;
}
public static MsgType getSystemPropertyOrDefaultLevel() {
String l = System.getProperty(NGINX_CLOJURE_LOG_LEVEL);
if (l != null){
try{
return MsgType.valueOf(l);
}catch (Exception e) {
e.printStackTrace();
}
}
return MsgType.info;
}
public TinyLogService(){
String l = System.getProperty(NGINX_CLOJURE_LOG_LEVEL);
if (l != null){
try{
level = MsgType.valueOf(l);
}catch (Exception e) {
e.printStackTrace();
}
}
out = System.out;
err = System.err;
}
public TinyLogService(MsgType level, PrintStream out, PrintStream err) {
this.level = level;
this.out = out;
this.err = err;
}
public void debug(Object message) {
if (message instanceof Throwable) {
((Throwable)message).printStackTrace(message(((Throwable)message).getMessage(), MsgType.debug));
}else {
message(message, MsgType.debug);
}
}
public void debug(Object message, Throwable t) {
if (isDebugEnabled()){
t.printStackTrace(message(message, MsgType.debug));
}
}
public void debug(String format, Object ... objects){
message(format, MsgType.debug, objects);
}
public void error(Object message) {
if (message instanceof Throwable) {
((Throwable)message).printStackTrace(message(((Throwable)message).getMessage(), MsgType.error));
}else {
message(message, MsgType.error);
}
}
public void error(Object message, Throwable t) {
t.printStackTrace(message(message, MsgType.error));
}
public void error(String format, Object ... objects){
message(format, MsgType.error, objects);
}
public void fatal(Object message) {
if (message instanceof Throwable) {
((Throwable)message).printStackTrace(message(((Throwable)message).getMessage(), MsgType.fatal));
}else {
message(message, MsgType.fatal);
}
}
public void fatal(Object message, Throwable t) {
t.printStackTrace(message(message, MsgType.fatal));
}
public void fatal(String format, Object ... objects){
message(format, MsgType.fatal, objects);
}
public PrintStream message(String format, MsgType type, Object ...objects){
if (type.compareTo(level) < 0){
return out;
}
return message(String.format(format, objects), type);
}
public PrintStream message(Object message, MsgType type){
if (type.compareTo(level) < 0){
return this.out;
}
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
StringBuffer s = new StringBuffer();
s.append(sf.format(new Date())).append("[").append(type).append("]:");
if (showMethod) {
StackTraceElement se = null;
boolean meetCurrentMethod = false;
for (StackTraceElement si : Thread.currentThread().getStackTrace()){
if (si.getClassName().equals(TinyLogService.class.getName()) || LOG_METHODS.contains(si.getMethodName())){
meetCurrentMethod = true;
continue;
}
if (meetCurrentMethod){
se = si;
break;
}
}
s.append("[").append(se.getClassName()).append(".").append(se.getMethodName()).append("]:");
}
s.append(message);
PrintStream out = this.out;
if (type != MsgType.debug && type != MsgType.info){
out = this.err;
}
out.println(s);
return out;
}
public void info(Object message) {
if (message instanceof Throwable) {
((Throwable)message).printStackTrace(message(((Throwable)message).getMessage(), MsgType.info));
}else {
message(message, MsgType.info);
}
}
public void info(Object message, Throwable t) {
message(message, MsgType.info);
t.printStackTrace(out);
}
public void info(String format, Object ... objects){
message(format, MsgType.info, objects);
}
public boolean isDebugEnabled() {
return level.compareTo(MsgType.debug) <= 0;
}
public boolean isErrorEnabled() {
return level.compareTo(MsgType.error) <= 0;
}
public boolean isFatalEnabled() {
return level.compareTo(MsgType.fatal) <= 0;
}
public boolean isInfoEnabled() {
return level.compareTo(MsgType.info) <= 0;
}
public boolean isTraceEnabled() {
return level.compareTo(MsgType.trace) <= 0;
}
public boolean isWarnEnabled() {
return level.compareTo(MsgType.warn) <= 0;
}
public void trace(Object message) {
message(message, MsgType.trace);
}
public void trace(Object message, Throwable t) {
t.printStackTrace(message(message, MsgType.trace));
}
public void trace(String format, Object ... objects){
message(format, MsgType.trace, objects);
}
public void warn(Object message) {
if (message instanceof Throwable) {
((Throwable)message).printStackTrace(message(((Throwable)message).getMessage(), MsgType.warn));
}else {
message(message, MsgType.warn);
}
}
public void warn(Object message, Throwable t) {
t.printStackTrace(message(message, MsgType.warn));
}
public void warn(String format, Object ... objects){
message(format, MsgType.warn, objects);
}
public MsgType getLevel() {
return level;
}
public void setLevel(MsgType level) {
this.level = level;
}
public PrintStream getOut() {
return out;
}
public void setOut(PrintStream out) {
this.out = out;
}
public PrintStream getErr() {
return err;
}
public void setErr(PrintStream err) {
this.err = err;
}
public void setShowMethod(boolean showMethod) {
this.showMethod = showMethod;
}
public boolean isShowMethod() {
return showMethod;
}
}
|
package org.eclipse.mylyn.internal.tasks.ui.views;
import java.util.Arrays;
import org.eclipse.mylyn.context.core.ContextCorePlugin;
import org.eclipse.mylyn.internal.tasks.ui.TasksUiImages;
import org.eclipse.mylyn.internal.tasks.ui.TasksUiPreferenceConstants;
import org.eclipse.mylyn.tasks.core.AbstractTask;
import org.eclipse.mylyn.tasks.core.AbstractTaskContainer;
import org.eclipse.mylyn.tasks.core.AbstractTask.RepositoryTaskSyncState;
import org.eclipse.mylyn.tasks.ui.TasksUiPlugin;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
/**
* @author Mik Kersten
*/
class CustomTaskListDecorationDrawer implements Listener {
private final TaskListView taskListView;
private int activationImageOffset;
private Image taskActive = TasksUiImages.getImage(TasksUiImages.TASK_ACTIVE);
private Image taskInactive = TasksUiImages.getImage(TasksUiImages.TASK_INACTIVE);
private Image taskInactiveContext = TasksUiImages.getImage(TasksUiImages.TASK_INACTIVE_CONTEXT);
// see bug 185004
private int platformSpecificSquish = 0;
CustomTaskListDecorationDrawer(TaskListView taskListView, int activationImageOffset) {
this.taskListView = taskListView;
this.activationImageOffset = activationImageOffset;
this.taskListView.synchronizationOverlaid = TasksUiPlugin.getDefault().getPluginPreferences().getBoolean(
TasksUiPreferenceConstants.OVERLAYS_INCOMING_TIGHT);
if (SWT.getPlatform().equals("gtk")) {
platformSpecificSquish = 8;
} else if (SWT.getPlatform().equals("carbon")) {
platformSpecificSquish = 3;
}
}
/*
* NOTE: MeasureItem, PaintItem and EraseItem are called repeatedly.
* Therefore, it is critical for performance that these methods be as
* efficient as possible.
*/
public void handleEvent(Event event) {
Object data = event.item.getData();
AbstractTask task = null;
Image activationImage = null;
if (data instanceof AbstractTask) {
task = (AbstractTask) data;
}
if (task != null) {
if (task.isActive()) {
activationImage = taskActive;
} else if (ContextCorePlugin.getContextManager().hasContext(task.getHandleIdentifier())) {
activationImage = taskInactiveContext;
} else {
activationImage = taskInactive;
}
}
if (data instanceof AbstractTaskContainer) {
switch (event.type) {
case SWT.EraseItem: {
if (activationImage != null) {
drawActivationImage(activationImageOffset, event, activationImage);
}
if (!this.taskListView.synchronizationOverlaid) {
if (data instanceof AbstractTaskContainer) {
drawSyncronizationImage((AbstractTaskContainer) data, event);
}
}
// TODO: would be nice not to do this on each item's painting
// String text = tree.getFilterControl().getText();
// System.err.println(">>>>>> " + tree.getViewer().getExpandedElements().length);
// if (text != null && !text.equals("") && tree.getViewer().getExpandedElements().length <= 12) {
// int offsetY = tree.getViewer().getExpandedElements().length * tree.getViewer().getTree().getItemHeight();
// event.gc.drawText("Open search dialog...", 20, offsetY - 10);
break;
}
case SWT.PaintItem: {
if (activationImage != null) {
drawActivationImage(activationImageOffset, event, activationImage);
}
if (data instanceof AbstractTaskContainer) {
drawSyncronizationImage((AbstractTaskContainer) data, event);
}
break;
}
}
}
}
private void drawSyncronizationImage(AbstractTaskContainer element, Event event) {
Image image = null;
int offsetX = 6;
int offsetY = (event.height / 2) - 5;
if (taskListView.synchronizationOverlaid) {
offsetX = event.x + 18 - platformSpecificSquish;
offsetY += 2;
}
if (element != null && !(element instanceof AbstractTask)) {
if (!hideDecorationOnContainer(element) && hasIncoming(element)) {
int additionalSquish = 0;
if (platformSpecificSquish > 0 && taskListView.synchronizationOverlaid) {
additionalSquish = platformSpecificSquish + 3;
} else if (platformSpecificSquish > 0) {
additionalSquish = platformSpecificSquish / 2;
}
if (taskListView.synchronizationOverlaid) {
image = TasksUiImages.getImage(TasksUiImages.OVERLAY_SYNCH_INCOMMING);
offsetX = 42 - additionalSquish;
} else {
image = TasksUiImages.getImage(TasksUiImages.OVERLAY_INCOMMING);
offsetX = 24 - additionalSquish;
}
}
} else {
image = TasksUiImages.getImage(TaskElementLabelProvider.getSynchronizationImageDescriptor(element,
taskListView.synchronizationOverlaid));
}
if (image != null) {
event.gc.drawImage(image, offsetX, event.y + offsetY);
}
}
private boolean hideDecorationOnContainer(AbstractTaskContainer element) {
return taskListView.isFocusedMode()
&& Arrays.asList(this.taskListView.getViewer().getExpandedElements()).contains(element);
}
private boolean hasIncoming(AbstractTaskContainer container) {
for (AbstractTask task : container.getChildren()) {
if (task != null) {
AbstractTask containedRepositoryTask = task;
if (containedRepositoryTask.getSynchronizationState() == RepositoryTaskSyncState.INCOMING) {
return true;
} else if (task.getChildren() != null && task.getChildren().size() > 0 && hasIncoming(task)) {
return true;
}
}
}
return false;
}
private void drawActivationImage(final int activationImageOffset, Event event, Image image) {
Rectangle rect = image.getBounds();
int offset = Math.max(0, (event.height - rect.height) / 2);
event.gc.drawImage(image, activationImageOffset, event.y + offset);
}
}
|
package jycessing.mode.run;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.RMIClientSocketFactory;
import java.rmi.server.RMIServerSocketFactory;
import java.rmi.server.UnicastRemoteObject;
import jycessing.mode.PythonMode;
public class RMIUtils {
private static final boolean EXTREMELY_VERBOSE = false;
static final int RMI_PORT = 8220;
private static final RMIClientSocketFactory clientFactory =
new RMIClientSocketFactory() {
@Override
public Socket createSocket(final String host, final int port) throws IOException {
return new Socket(host, port);
}
};
private static final RMIServerSocketFactory serverFactory =
new RMIServerSocketFactory() {
@Override
public ServerSocket createServerSocket(final int port) throws IOException {
return new ServerSocket(port, 50, InetAddress.getLoopbackAddress());
}
};
static {
System.setProperty("sun.rmi.transport.tcp.localHostNameTimeOut", "1000");
System.setProperty("java.rmi.server.hostname", "127.0.0.1");
// Timeout RMI calls after 1.5 seconds. Good for detecting a hanging sketch runner.
System.setProperty("sun.rmi.transport.tcp.responseTimeout", "1500");
if (EXTREMELY_VERBOSE) {
System.setProperty("java.rmi.server.logCalls", "true");
System.setProperty("sun.rmi.server.logLevel", "VERBOSE");
System.setProperty("sun.rmi.client.logCalls", "true");
System.setProperty("sun.rmi.transport.tcp.logLevel", "VERBOSE");
}
}
private static void log(final String msg) {
if (PythonMode.VERBOSE) {
System.err.println(RMIUtils.class.getSimpleName() + ": " + msg);
}
}
public static class RMIProblem extends Exception {
RMIProblem(final Exception e) {
super(e);
}
}
private RMIUtils() {}
private static Registry registry;
public static Registry registry() throws RemoteException {
if (registry == null) {
try {
registry = LocateRegistry.createRegistry(RMI_PORT, clientFactory, serverFactory);
System.err.println("created registry at port " + RMI_PORT);
} catch (final RemoteException e) {
System.err.println("could not create registry; assume it's already created");
registry = LocateRegistry.getRegistry("127.0.0.1", RMI_PORT, clientFactory);
}
}
return registry;
}
public static void bind(final Remote remote, final Class<? extends Remote> remoteInterface)
throws RMIProblem {
final String registryKey = remoteInterface.getSimpleName();
try {
final Remote stub = export(remote);
log(
"Attempting to bind instance of "
+ remote.getClass().getName()
+ " to registry as "
+ registryKey);
registry().bind(registryKey, stub);
log("Bound.");
Runtime.getRuntime()
.addShutdownHook(
new Thread(
new Runnable() {
@Override
public void run() {
try {
log("Unbinding " + registryKey + " from registry.");
registry().unbind(registryKey);
} catch (final Exception e) {
}
}
}));
} catch (final Exception e) {
throw new RMIProblem(e);
}
}
public static Remote export(final Remote remote) throws RMIProblem {
try {
return UnicastRemoteObject.exportObject(remote, 0);
} catch (final RemoteException e) {
throw new RMIProblem(e);
}
}
@SuppressWarnings("unchecked")
public static <T extends Remote> T lookup(final Class<T> klass) throws RMIProblem {
try {
log("Looking up ModeService in registry.");
return (T) registry().lookup(klass.getSimpleName());
} catch (final Exception e) {
throw new RMIProblem(e);
}
}
}
|
package org.jdesktop.swingx;
import java.awt.Container;
import java.awt.Rectangle;
import javax.swing.JComponent;
import javax.swing.RepaintManager;
/**
* <p>An implementation of {@link RepaintManager} which adds support for transparency
* in {@link JXPanel}s. <code>JXPanel</code> (which supports translucency) will
* replace the current RepaintManager with an instance of RepaintManagerX
* <em>unless</em> the current RepaintManager is tagged by the {@link TranslucentRepaintManager}
* annotation.</p>
*
* @author zixle
* @author rbair
*/
@TranslucentRepaintManager
public class RepaintManagerX extends RepaintManager {
public void addDirtyRegion(JComponent c, int x, int y, int w, int h) {
Rectangle dirtyRegion = getDirtyRegion(c);
if (dirtyRegion.width == 0 && dirtyRegion.height == 0) {
int lastDeltaX = c.getX();
int lastDeltaY = c.getY();
Container parent = c.getParent();
while (parent instanceof JComponent) {
if (!parent.isVisible() || !parent.isDisplayable()) {
return;
}
if (parent instanceof JXPanel && (((JXPanel)parent).getAlpha() < 1f ||
!parent.isOpaque())) {
x += lastDeltaX;
y += lastDeltaY;
lastDeltaX = lastDeltaY = 0;
c = (JComponent)parent;
}
lastDeltaX += parent.getX();
lastDeltaY += parent.getY();
parent = parent.getParent();
}
}
super.addDirtyRegion(c, x, y, w, h);
}
}
|
package org.mwg.experiments.smartgridprofiling.gmm;
//import org.graphstream.graph.implementations.SingleGraph;
//import org.graphstream.ui.swingViewer.View;
//import org.graphstream.ui.swingViewer.Viewer;
import org.math.plot.Plot3DPanel;
import org.mwg.Callback;
import org.mwg.Graph;
import org.mwg.GraphBuilder;
import org.mwg.LevelDBStorage;
import org.mwg.core.scheduler.NoopScheduler;
import org.mwg.ml.algorithm.profiling.GaussianGmmNode;
import org.mwg.ml.algorithm.profiling.ProbaDistribution;
import org.mwg.ml.algorithm.profiling.ProgressReporter;
import org.mwg.ml.common.matrix.Matrix;
import org.mwg.ml.common.matrix.operation.MultivariateNormalDistribution;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.concurrent.CountDownLatch;
public class Graph3D extends JFrame implements PropertyChangeListener {
// Graph related fields
private JSplitPane spUp; //split panel for GUI
private ProgressMonitor progressMonitor;
// private org.graphstream.graph.Graph visualGraph; //Graph of MWDB
// private Viewer visualGraphViewer; //Graph Viewer of MWDB
// private View visualGraphView;
private static Graph graph; //MWDB graph
public GaussianGmmNode profiler;
private int MAXLEVEL;
private int selectedCalcLevel = 0;
private JComboBox<Integer> levelSelector;
private JLabel graphinfo;
private JLabel processinginfo;
private JTextField textX;
private JTextField textY;
private JButton updateField;
private double[] err;
private int[] xConfig={0,24,48};
private int[] yConfig={0,1000,100};
private boolean automatic=false;
//Data set related fields
private ArrayList<ElectricMeasure> data; //Data loaded from the csv file
private int loc = 0; //Location in the data set reading
private boolean lock = true;
private Calculate operation;
private Graph3D() {
initUI();
}
class Calculate extends SwingWorker<Plot3DPanel, String> implements ProgressReporter {
private final int num;
private long starttime;
private long endtime;
private double[] temp;
public Calculate(int num, double[] temp) {
lock = false;
this.num = Math.min(num, data.size() - loc);
this.temp = temp;
}
@Override
public Plot3DPanel doInBackground() {
starttime = System.nanoTime();
if ((loc < data.size() && num > 0) || temp != null) {
publish("Processing " + num + " values started...");
if (temp != null) {
profiler.learnVector(temp, result -> {
});
} else {
for (int i = 0; i < num; i++) {
this.setProgress(i * 50 / num);
if (isCancelled()) {
return null;
}
if (loc < data.size()) {
profiler.learnVector(data.get(loc).getVector(), new Callback<Boolean>() {
@Override
public void on(Boolean result) {
}
});
loc++;
} else {
break;
}
}
}
yConfig[1]=(int)Math.max(profiler.getMax()[1],1000);
textY.setText("0,"+yConfig[1]+",100");
processinginfo.setText("Learning done in " + getTime() + ", generating 3D plot...");
publish("Learning done in " + getTime() + ", generating 3D plot...");
return generatePlot();
}
return generatePlot();
}
private Plot3DPanel generatePlot() {
/*
* Plot the distribution estimated by the sample model
*/
double[][] zArray;
// first create a 100x100 grid
double[] xArray = new double[xConfig[2] + 1];
double[] yArray = new double[yConfig[2] + 1];
double zmax = Double.MIN_VALUE;
if(automatic) {
if (profiler.getMax() != null) {
yConfig[1] = (int) (profiler.getMax()[1] * 1.1);
}
}
double yrange;
yrange=(yConfig[1]-yConfig[0]);
yrange=yrange/yConfig[2];
double xrange;
xrange=(xConfig[1]-xConfig[0]);
xrange=xrange/xConfig[2];
for (int i = 0; i < yArray.length; i++) {
yArray[i] = i * yrange+yConfig[0];
}
for (int i = 0; i < xArray.length; i++) {
xArray[i] = i * xrange+xConfig[0];
}
double[][] featArray = new double[(xArray.length * yArray.length)][2];
int count = 0;
for (int i = 0; i < xArray.length; i++) {
for (int j = 0; j < yArray.length; j++) {
double[] point = {xArray[i], yArray[j]};
featArray[count] = point;
count++;
}
}
double[] min={xConfig[0],yConfig[0]};
double[] max={xConfig[1],yConfig[1]};
starttime = System.nanoTime();
double[] z;
if(selectedCalcLevel!=-1) {
z = calculateArray(featArray, min, max);
}
else {
z =calculateArrayDataset(featArray);
}
if (isCancelled() || z == null) {
return null;
}
zArray = new double[yArray.length][xArray.length];
count = 0;
for (int i = 0; i < xArray.length; i++) {
for (int j = 0; j < yArray.length; j++) {
zArray[j][i] = z[count];
if (zArray[j][i] > zmax) {
zmax = zArray[j][i];
}
count++;
}
}
if (zmax == 0) {
zmax = 1;
}
processinginfo.setText("Calculating probabilities done in " + getTime());
publish("Calculating probabilities done in " + getTime());
Plot3DPanel plot = emptyPlot();
// add grid plot to the PlotPanel
plot.addGridPlot("Electric consumption probability distribution", xArray, yArray,
zArray);
plot.setFixedBounds(0, xConfig[0], xConfig[1]);
plot.setFixedBounds(1, yConfig[0], yConfig[1]);
plot.setFixedBounds(2, 0, zmax);
lock=true;
return plot;
}
private double[] calculateArrayDataset(double[][] features) {
int[] total = new int[data.size()];
MultivariateNormalDistribution[] distributions = new MultivariateNormalDistribution[data.size()];
int global = data.size();
Matrix covBackup = new Matrix(null, 2, 2);
for (int i = 0; i < 2; i++) {
covBackup.set(i, i, err[i]);
}
MultivariateNormalDistribution mvnBackup = new MultivariateNormalDistribution(null, covBackup,false);
for (int i = 0; i < data.size(); i++) {
total[i] = 1;
distributions[i] = mvnBackup.clone(data.get(i).getVector());
}
ProbaDistribution probabilities = new ProbaDistribution(total, distributions, global);
return probabilities.calculateArray(features,this);
}
//ToDo need optimization
private double[] calculateArray(double[][] features, double[] min, double[] max) {
double[][] res = new double[1][];
CountDownLatch countDownLatch = new CountDownLatch(1);
profiler.query(selectedCalcLevel, min, max, probabilities -> {
if(probabilities!=null) {
res[0] = probabilities.calculateArray(features, this);
updateProgress(100);
countDownLatch.countDown();
}
});
try {
countDownLatch.await();
} catch (InterruptedException e) {
return null;
}
return res[0];
}
@Override
protected void process(java.util.List<String> chunks) {
if (isCancelled()) {
return;
}
for (String s : chunks) {
progressMonitor.setNote(s);
}
}
private String getTime() {
endtime = System.nanoTime();
double v = endtime - starttime;
String s;
NumberFormat formatter = new DecimalFormat("#0.00");
if (v > 1000000000) {
v = v / 1000000000;
s = formatter.format(v) + " s";
} else if (v > 1000000) {
v = v / 1000000;
s = formatter.format(v) + " ms";
} else {
s = v + " ns";
}
return s;
}
@Override
public void done() {
lock = true;
try {
if (!this.isCancelled()) {
publish("Processing done in " + getTime());
Plot3DPanel pd = get();
if (pd == null) {
clearplot();
} else {
spUp.setLeftComponent(pd);
spUp.setDividerLocation(getWidth() - 300);
progressMonitor.close();
}
// visualGraphViewer.close();
// org.mwg.experiments.smartgridprofiling.gmm.GraphBuilder.graphFrom(graph, visualGraph, profiler, selectedCalcLevel, GaussianGmmNode.INTERNAL_SUBGAUSSIAN_KEY, result -> visualGraphViewer = result.display());
}
//ToDo set the display back here
//elecStat.setText("Electrical Values loaded: " + ((int) mm.getWeight()));
// compStat.setText("Number of components: "+mm.totalComponents());
//topStat.setText("Top level components: " + mm.getTopLevelComp());
} catch (Exception ex) {
ex.printStackTrace();
}
}
@Override
public void updateProgress(int value) {
this.setProgress(value);
}
public void updateGraphInfo(String info) {
graphinfo.setText(info);
}
}
// executes in event dispatch thread
public void propertyChange(PropertyChangeEvent event) {
// if the operation is finished or has been canceled by
// the user, take appropriate action
if (progressMonitor.isCanceled()) {
operation.cancel(true);
} else if (event.getPropertyName().equals("progress")) {
// get the % complete from the progress event
// and set it on the progress monitor
int progress = (Integer) event.getNewValue();
progressMonitor.setProgress(progress);
}
}
private static Plot3DPanel emptyPlot() {
Plot3DPanel plot = new Plot3DPanel("SOUTH");
plot.setAxisLabel(0, "Time");
plot.setAxisLabel(1, "Electric load");
plot.setAxisLabel(2, "Probability");
return plot;
}
private void initUI() {
resetProfile();
data = new ArrayList<>();
// some configuration for plotting
setTitle("Smart Grid consumption");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel board = new JPanel(new FlowLayout(FlowLayout.LEFT));
// board.setPreferredSize(new Dimension(300, 1000));
// board.setMaximumSize(new Dimension(350, 1000));
spUp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, new JPanel(), board);
// spUp.setPreferredSize(new Dimension(1200, 1000));
spUp.setContinuousLayout(true);
spUp.setDividerLocation(this.getWidth() - 300);
GridLayout experimentLayout = new GridLayout(8, 1, 0, 0);
board.setLayout(experimentLayout);
Integer[] items = new Integer[MAXLEVEL + 2];
for (int i = 0; i <= MAXLEVEL+1; i++) {
items[i] = i-1;
}
levelSelector = new JComboBox<>(items);
levelSelector.setSelectedItem(levelSelector.getItemAt(MAXLEVEL+1));
selectedCalcLevel = MAXLEVEL;
levelSelector.addActionListener(event -> {
JComboBox comboBox = (JComboBox) event.getSource();
selectedCalcLevel = (int) comboBox.getSelectedItem();
feed(0, null); //update the graph
});
JLabel comboLabel = new JLabel("Calculation Level (0: most precise):");
board.add(comboLabel);
board.add(levelSelector);
JLabel temp=new JLabel("X,Y bounds (min,max,numStep)");
board.add(temp);
textX=new JTextField(xConfig[0]+","+xConfig[1]+","+xConfig[2]);
textY=new JTextField(yConfig[0]+","+yConfig[1]+","+yConfig[2]);
board.add(textX);
board.add(textY);
updateField=new JButton("Update Space");
updateField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
updateFieldPressed();
}
} );
board.add(updateField);
graphinfo=new JLabel("");
board.add(graphinfo);
processinginfo=new JLabel("");
board.add(processinginfo);
getContentPane().add(spUp, BorderLayout.CENTER);
setSize(1600, 1000);
setLocationRelativeTo(null);
// visualGraph = new SingleGraph("Model");
// visualGraphViewer = new Viewer(visualGraph, Viewer.ThreadingModel.GRAPH_IN_ANOTHER_THREAD);
// visualGraphView = visualGraphViewer.addDefaultView(true); // false indicates "no JFrame".
clearplot();
menu();
}
private void updateFieldPressed() {
String xs=textX.getText();
String ys=textY.getText();
int[] xres=new int[3];
int[] yres=new int[3];
try{
String[] split=xs.split(",");
xres[0] =Integer.parseInt(split[0]);
xres[1] =Integer.parseInt(split[1]);
xres[2] =Integer.parseInt(split[2]);
split=ys.split(",");
yres[0] =Integer.parseInt(split[0]);
yres[1] =Integer.parseInt(split[1]);
yres[2] =Integer.parseInt(split[2]);
if(xres[2]<=0||yres[2]<=0){
throw new Exception("Third input should not be negative");
}
if(xres[1]<=xres[0]||yres[1]<=yres[0]){
throw new Exception("max should be > min");
}
xConfig=xres;
yConfig=yres;
}
catch (Exception ex){
JOptionPane.showMessageDialog(null, "X and Y selection should 3 integers each: min, max, (numberOfStep>0). "+ex.getMessage(), "Incorrect input", JOptionPane.ERROR_MESSAGE);
return;
}
feed(0, null); //update the proba
}
private void clearplot() {
Plot3DPanel pp = emptyPlot();
pp.addGridPlot("Electric consumption probability distribution", new double[]{0, 24}, new double[]{0, 1000}, new double[][]{{0, 0}, {0, 0}});
pp.setFixedBounds(0, 0, 24);
pp.setFixedBounds(1, 0, 1000);
pp.setFixedBounds(2, 0, 1);
spUp.setLeftComponent(pp);
spUp.setDividerLocation(getWidth() - 300);
graphinfo.setText("");
processinginfo.setText("");
}
private void feed(final int num, double[] temp) {
if (data != null) {
if (lock) {
lock = false;
progressMonitor = new ProgressMonitor(this, "Loading values...", "", 0, 100);
operation = new Calculate(num, temp);
operation.addPropertyChangeListener(this);
operation.execute();
lock=true;
} else {
JOptionPane.showMessageDialog(null, "Please wait till the first process is done", "Process not finished yet", JOptionPane.ERROR_MESSAGE);
}
} else {
JOptionPane.showMessageDialog(null, "Please open a user csv file first", "No user data loaded", JOptionPane.ERROR_MESSAGE);
}
}
private void dataInit() {
//Create a file chooser
final JFileChooser fc = new JFileChooser();
int returnVal = fc.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
try {
File file = fc.getSelectedFile();
loc = 0;
data = CsvLoader.loadFile(file.getAbsolutePath());
JOptionPane.showMessageDialog(null, "Loaded " + data.size() + " measures", "Loading successful", JOptionPane.INFORMATION_MESSAGE);
resetProfile();
clearplot();
} catch (Exception ex) {
loc = 0;
data = null;
JOptionPane.showMessageDialog(null, "Could not load the file ", "Loading failed", JOptionPane.ERROR_MESSAGE);
}
}
}
private void dataDirInit() {
//Create a file chooser
final JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
// disable the "All files" option.
fc.setAcceptAllFileFilterUsed(false);
if (fc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
System.out.println("getCurrentDirectory(): "
+ fc.getCurrentDirectory());
System.out.println("getSelectedFile() : "
+ fc.getSelectedFile());
} else {
System.out.println("No Selection ");
}
}
private void menu() {
//Where the GUI is created:
JMenuBar menuBar;
JMenu menu, filemenu;
JMenuItem menuItem;
//Create the menu bar.
menuBar = new JMenuBar();
//Build the first menu.
filemenu = new JMenu("File");
filemenu.setMnemonic(KeyEvent.VK_I);
filemenu.getAccessibleContext().setAccessibleDescription(
"File");
menuBar.add(filemenu);
menuItem = new JMenuItem("Open a file",
KeyEvent.VK_O);
menuItem.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_O, ActionEvent.ALT_MASK));
menuItem.getAccessibleContext().setAccessibleDescription(
"Open user Csv file");
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
dataInit();
}
});
filemenu.add(menuItem);
/* menuItem = new JMenuItem("Open a directory",
KeyEvent.VK_O);
menuItem.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_O, ActionEvent.ALT_MASK));
menuItem.getAccessibleContext().setAccessibleDescription(
"Open many files");
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
dataDirInit();
}
});
filemenu.add(menuItem);*/
//Build the first menu.
menu = new JMenu("Electric Load");
menu.setMnemonic(KeyEvent.VK_A);
menu.getAccessibleContext().setAccessibleDescription(
"Electric load menu");
menuBar.add(menu);
//a group of JMenuItems
menuItem = new JMenuItem("Load One Value",
KeyEvent.VK_T);
menuItem.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_1, ActionEvent.ALT_MASK));
menuItem.getAccessibleContext().setAccessibleDescription(
"Load next electric consumption");
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
feed(1, null);
}
});
menu.add(menuItem);
menuItem = new JMenuItem("Load 10 Values",
KeyEvent.VK_T);
menuItem.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_2, ActionEvent.ALT_MASK));
menuItem.getAccessibleContext().setAccessibleDescription(
"Load 10 electric consumptions values");
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
feed(10, null);
}
});
menu.add(menuItem);
menuItem = new JMenuItem("Load 100 Values",
KeyEvent.VK_T);
menuItem.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_3, ActionEvent.ALT_MASK));
menuItem.getAccessibleContext().setAccessibleDescription(
"Load 1000 electric consumptions values");
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
feed(100, null);
}
});
menu.add(menuItem);
menuItem = new JMenuItem("Load 1000 Values",
KeyEvent.VK_T);
menuItem.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_4, ActionEvent.ALT_MASK));
menuItem.getAccessibleContext().setAccessibleDescription(
"Load 1000 electric consumptions values");
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
feed(1000, null);
}
});
menu.add(menuItem);
menuItem = new JMenuItem("Load all Values",
KeyEvent.VK_T);
menuItem.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_5, ActionEvent.ALT_MASK));
menuItem.getAccessibleContext().setAccessibleDescription(
"Load all electric consumptions values of this client");
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
feed(data.size(), null);
}
});
menu.add(menuItem);
menu.addSeparator();
menuItem = new JMenuItem("Load Custom Value",
KeyEvent.VK_T);
menuItem.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_6, ActionEvent.ALT_MASK));
menuItem.getAccessibleContext().setAccessibleDescription(
"Load Custom Value");
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFrame frame = new JFrame("InputDialog Example
String s = (String) JOptionPane.showInputDialog(frame, "Enter the features separated by space",
"Enter your custom features",
JOptionPane.INFORMATION_MESSAGE);
if ((s != null) && (s.length() > 0)) {
try {
String[] splits = s.split(" ");
double[] data = new double[2];
data[0] = Double.parseDouble(splits[0]);
data[1] = Double.parseDouble(splits[1]);
feed(1, data);
} catch (Exception ex) {
JOptionPane.showMessageDialog(frame, ex.getMessage());
}
}
}
});
menu.add(menuItem);
setJMenuBar(menuBar);
}
public void resetProfile() {
if (profiler != null) {
profiler.free();
}
profiler = (GaussianGmmNode) graph.newTypedNode(0, 0, "GaussianGmm");
MAXLEVEL = 4;
profiler.set(GaussianGmmNode.LEVEL_KEY, MAXLEVEL); //max levels allowed
profiler.set(GaussianGmmNode.WIDTH_KEY, 100); //each level can have 24 components
profiler.set(GaussianGmmNode.COMPRESSION_FACTOR_KEY, 4); //Factor of times before compressing, so at 24x10=240, compressions executes
profiler.set(GaussianGmmNode.COMPRESSION_ITER_KEY, 5); //iteration in the compression function, keep default
profiler.set(GaussianGmmNode.THRESHOLD_KEY, 1.0); //At the lower level, at higher level will be: threashold + level/2 -> number of variance tolerated to insert in the same node
err = new double[]{0.25 * 0.25, 10 * 10};
profiler.set(GaussianGmmNode.PRECISION_KEY, err); //Minimum covariance in both axis
}
public static void main(String[] args) {
graph = GraphBuilder
.builder()
.withMemorySize(300000)
.withAutoSave(10000)
// .withOffHeapMemory()
.withStorage(new LevelDBStorage("./"))
.withFactory(new GaussianGmmNode.Factory())
.withScheduler(new NoopScheduler())
.build();
graph.connect(result -> {
SwingUtilities.invokeLater(() -> {
Graph3D ps = new Graph3D();
ps.setVisible(true);
});
});
}
}
|
package edu.umd.cs.findbugs;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import edu.umd.cs.findbugs.ba.AnalysisContext;
import edu.umd.cs.findbugs.classfile.IAnalysisEngineRegistrar;
import edu.umd.cs.findbugs.cloud.CloudPlugin;
import edu.umd.cs.findbugs.plan.DetectorOrderingConstraint;
import edu.umd.cs.findbugs.util.DualKeyHashMap;
/**
* A FindBugs plugin. A plugin contains executable Detector classes, as well as
* meta information describing those detectors (such as human-readable detector
* and bug descriptions).
*
* @see PluginLoader
* @author David Hovemeyer
*/
public class Plugin {
private static final String USE_FINDBUGS_VERSION = "USE_FINDBUGS_VERSION";
private final String pluginId;
private final String version;
private Date releaseDate;
private String provider;
private URI website;
private @CheckForNull URI updateUrl;
private String shortDescription;
private String detailedDescription;
private final ArrayList<DetectorFactory> detectorFactoryList;
private final Map<String, FindBugsMain> mainPlugins;
private final LinkedHashSet<BugPattern> bugPatterns;
private final LinkedHashSet<BugCode> bugCodeList;
private final LinkedHashMap<String, BugCategory> bugCategories;
private final LinkedHashSet<CloudPlugin> cloudList;
private final HashMap<String,String> myGlobalOptions = new HashMap<String, String>();
private final DualKeyHashMap<Class<?>, String, ComponentPlugin<?>> componentPlugins;
private BugRanker bugRanker;
// Ordering constraints
private final ArrayList<DetectorOrderingConstraint> interPassConstraintList;
private final ArrayList<DetectorOrderingConstraint> intraPassConstraintList;
// Optional: engine registrar class
private Class<? extends IAnalysisEngineRegistrar> engineRegistrarClass;
// PluginLoader that loaded this plugin
private final PluginLoader pluginLoader;
private final boolean enabledByDefault;
private final boolean cannotDisable;
static Map<URI, Plugin> allPlugins = new LinkedHashMap<URI, Plugin>();
enum EnabledState { PLUGIN_DEFAULT, ENABLED, DISABLED};
private EnabledState enabled;
/**
* Constructor. Creates an empty plugin object.
*
* @param pluginId
* the plugin's unique identifier
* @param version TODO
* @param enabled TODO
* @param cannotDisable TODO
*/
public Plugin(String pluginId, String version, Date releaseDate, @Nonnull PluginLoader pluginLoader, boolean enabled, boolean cannotDisable) {
this.pluginId = pluginId;
if (version == null) {
version = "";
} else if (version.equals(USE_FINDBUGS_VERSION)) {
version = Version.COMPUTED_RELEASE;
releaseDate = Version.getReleaseDate();
}
assert enabled || !cannotDisable;
cloudList = new LinkedHashSet<CloudPlugin>();
componentPlugins = new DualKeyHashMap<Class<?>, String, ComponentPlugin<?>> ();
this.version = version;
this.releaseDate = releaseDate;
this.detectorFactoryList = new ArrayList<DetectorFactory>();
this.bugPatterns = new LinkedHashSet<BugPattern>();
this.bugCodeList = new LinkedHashSet<BugCode>();
this.bugCategories = new LinkedHashMap<String,BugCategory>();
this.interPassConstraintList = new ArrayList<DetectorOrderingConstraint>();
this.intraPassConstraintList = new ArrayList<DetectorOrderingConstraint>();
this.mainPlugins = new HashMap<String, FindBugsMain>();
this.pluginLoader = pluginLoader;
this.enabledByDefault = enabled;
this.cannotDisable = cannotDisable;
this.enabled = EnabledState.PLUGIN_DEFAULT;
}
@Override
public String toString() {
return this.getClass().getSimpleName() + ":" + pluginId;
}
/**
* Return whether or not the Plugin is enabled.
*
* @return true if the Plugin is enabled, false if not
*/
public boolean isEnabledByDefault() {
return enabledByDefault;
}
/**
* Set plugin provider.
*
* @param provider
* the plugin provider
*/
public void setProvider(String provider) {
this.provider = provider;
}
/**
* Get the plugin provider.
*
* @return the provider, or null if the provider was not specified
*/
public @CheckForNull String getProvider() {
return provider;
}
public void setUpdateUrl(String url) throws URISyntaxException {
this.updateUrl = new URI(url);
}
public @CheckForNull URI getUpdateUrl() {
return updateUrl;
}
public void setMyGlobalOption(String key, String value) {
myGlobalOptions.put(key, value);
}
Map<String,String> getMyGlobalOptions() {
return Collections.unmodifiableMap(myGlobalOptions);
}
/**
* Set plugin website.
*
* @param website
* the plugin website
* @throws URISyntaxException
*/
public void setWebsite(String website) throws URISyntaxException {
this.website = new URI(website);
}
/**
* Get the plugin website.
*
* @return the website, or null if the was not specified
*/
public @CheckForNull String getWebsite() {
if (website == null)
return null;
return website.toASCIIString();
}
public @CheckForNull URI getWebsiteURI() {
return website;
}
public String getVersion() {
return version;
}
public Date getReleaseDate() {
return releaseDate;
}
public void setShortDescription(String shortDescription) {
this.shortDescription = shortDescription;
}
public String getShortDescription() {
return shortDescription;
}
public String getDetailedDescription() {
return detailedDescription;
}
public void setDetailedDescription(String detailedDescription) {
this.detailedDescription = detailedDescription;
}
/**
* Add a DetectorFactory for a Detector implemented by the Plugin.
*
* @param factory
* the DetectorFactory
*/
public void addDetectorFactory(DetectorFactory factory) {
detectorFactoryList.add(factory);
}
public void addCloudPlugin(CloudPlugin cloudPlugin) {
cloudList.add(cloudPlugin);
}
/**
* Add a BugPattern reported by the Plugin.
*
* @param bugPattern
*/
public void addBugPattern(BugPattern bugPattern) {
bugPatterns.add(bugPattern);
}
/**
* Add a BugCode reported by the Plugin.
*
* @param bugCode
*/
public void addBugCode(BugCode bugCode) {
bugCodeList.add(bugCode);
}
/**
* Add a BugCategory reported by the Plugin.
*
* @param bugCode
*/
public void addBugCategory(BugCategory bugCategory) {
BugCategory old = bugCategories.get(bugCategory.getCategory());
if (old != null)
throw new IllegalArgumentException("Category already exists");
bugCategories.put(bugCategory.getCategory(), bugCategory);
}
public BugCategory addOrCreateBugCategory(String id) {
BugCategory c = bugCategories.get(id);
if (c != null)
return c;
c = new BugCategory(id);
bugCategories.put(id, c);
return c;
}
/**
* Add an inter-pass Detector ordering constraint.
*
* @param constraint
* the inter-pass Detector ordering constraint
*/
public void addInterPassOrderingConstraint(DetectorOrderingConstraint constraint) {
interPassConstraintList.add(constraint);
}
/**
* Add an intra-pass Detector ordering constraint.
*
* @param constraint
* the intra-pass Detector ordering constraint
*/
public void addIntraPassOrderingConstraint(DetectorOrderingConstraint constraint) {
intraPassConstraintList.add(constraint);
}
/**
* Look up a DetectorFactory by short name.
*
* @param shortName
* the short name
* @return the DetectorFactory
*/
public DetectorFactory getFactoryByShortName(final String shortName) {
return findFirstMatchingFactory(new FactoryChooser() {
public boolean choose(DetectorFactory factory) {
return factory.getShortName().equals(shortName);
}
});
}
/**
* Look up a DetectorFactory by full name.
*
* @param fullName
* the full name
* @return the DetectorFactory
*/
public DetectorFactory getFactoryByFullName(final String fullName) {
return findFirstMatchingFactory(new FactoryChooser() {
public boolean choose(DetectorFactory factory) {
return factory.getFullName().equals(fullName);
}
});
}
/**
* Get Iterator over DetectorFactory objects in the Plugin.
*
* @return Iterator over DetectorFactory objects
*/
public Collection<DetectorFactory> getDetectorFactories() {
return detectorFactoryList;
}
/**
* Get the set of BugPatterns
*
*/
public Set<BugPattern> getBugPatterns() {
return bugPatterns;
}
/**
* Get Iterator over BugCode objects in the Plugin.
*
* @return Iterator over BugCode objects
*/
public Set<BugCode> getBugCodes() {
return bugCodeList;
}
/**
* Get Iterator over BugCategories objects in the Plugin.
*
* @return Iterator over BugCategory objects
*/
public Collection<BugCategory> getBugCategories() {
return bugCategories.values();
}
/**
* @param id may be null
* @return return bug category with given id, may return null if the bug category is unknown
*/
@CheckForNull
public BugCategory getBugCategory(String id) {
return bugCategories.get(id);
}
public Set<CloudPlugin> getCloudPlugins() {
return cloudList;
}
/**
* Return an Iterator over the inter-pass Detector ordering constraints.
*/
public Iterator<DetectorOrderingConstraint> interPassConstraintIterator() {
return interPassConstraintList.iterator();
}
/**
* Return an Iterator over the intra-pass Detector ordering constraints.
*/
public Iterator<DetectorOrderingConstraint> intraPassConstraintIterator() {
return intraPassConstraintList.iterator();
}
/**
* @return Returns the pluginId.
*/
public String getPluginId() {
return pluginId;
}
/**
* @return Returns the short pluginId.
*/
public String getShortPluginId() {
int i = pluginId.lastIndexOf('.');
return pluginId.substring(i+1);
}
/**
* Set the analysis engine registrar class that, when instantiated, can be
* used to register the plugin's analysis engines with the analysis cache.
*
* @param engineRegistrarClass
* The engine registrar class to set.
*/
public void setEngineRegistrarClass(Class<? extends IAnalysisEngineRegistrar> engineRegistrarClass) {
this.engineRegistrarClass = engineRegistrarClass;
}
/**
* Get the analysis engine registrar class that, when instantiated, can be
* used to register the plugin's analysis engines with the analysis cache.
*
* @return Returns the engine registrar class.
*/
public Class<? extends IAnalysisEngineRegistrar> getEngineRegistrarClass() {
return engineRegistrarClass;
}
/**
* @return Returns the pluginLoader.
*/
public PluginLoader getPluginLoader() {
return pluginLoader;
}
private interface FactoryChooser {
public boolean choose(DetectorFactory factory);
}
private @CheckForNull
DetectorFactory findFirstMatchingFactory(FactoryChooser chooser) {
for (DetectorFactory factory : getDetectorFactories()) {
if (chooser.choose(factory))
return factory;
}
return null;
}
/**
* @param ranker
*/
public void setBugRanker(BugRanker ranker) {
this.bugRanker = ranker;
}
public BugRanker getBugRanker() {
return bugRanker;
}
<T> void addFindBugsMain(Class<?> mainClass, String cmd, String description, String kind, boolean analysis)
throws SecurityException, NoSuchMethodException {
FindBugsMain main = new FindBugsMain(mainClass, cmd, description, kind, analysis);
mainPlugins.put(cmd, main);
}
public @CheckForNull FindBugsMain getFindBugsMain(String cmd) {
return mainPlugins.get(cmd);
}
public Collection<FindBugsMain> getAllFindBugsMain() {
return mainPlugins.values();
}
<T> void addComponentPlugin(Class<T> componentKind, ComponentPlugin<T> plugin) {
if (componentKind == null)
throw new NullPointerException("Null component kind");
if (plugin == null)
throw new NullPointerException("Null plugin");
if (!componentKind.isAssignableFrom(plugin.getComponentClass()))
throw new IllegalArgumentException();
componentPlugins.put(componentKind, plugin.getId(), plugin);
}
@SuppressWarnings("unchecked")
public <T> Iterable<ComponentPlugin<T>> getComponentPlugins(Class<T> componentClass) {
@SuppressWarnings("rawtypes")
Collection values = componentPlugins.get(componentClass).values();
return values;
}
@SuppressWarnings("unchecked")
public <T> ComponentPlugin<T> getComponentPlugin(Class<T> componentClass, String name) {
return (ComponentPlugin<T>) componentPlugins.get(componentClass, name);
}
public static synchronized @CheckForNull Plugin getByPluginId(String name) {
if(name == null) {
return null;
}
for(Plugin plugin : allPlugins.values()) {
// the second part is questionable, as this may lead to id collisions
if (name.equals(plugin.getPluginId()) /*|| name.equals(plugin.getShortPluginId())*/)
return plugin;
}
return null;
}
public static synchronized void removePlugin(URI uri) {
allPlugins.remove(uri);
}
/**
* @return a copy of the internal plugins collection
*/
public static synchronized Collection<Plugin> getAllPlugins() {
return new ArrayList<Plugin>(allPlugins.values());
}
public static synchronized Collection<String> getAllPluginIds() {
ArrayList<String> result = new ArrayList<String>();
for(Plugin p : allPlugins.values())
result.add(p.getPluginId());
return result;
}
/**
* @return a copy of the internal plugins collection
*/
public static synchronized Map<URI, Plugin> getAllPluginsMap() {
return new LinkedHashMap<URI, Plugin>(allPlugins);
}
public static synchronized Set<URI> getAllPluginsURIs() {
Collection<Plugin> plugins = getAllPlugins();
Set<URI> uris = new HashSet<URI>();
for (Plugin plugin : plugins) {
try {
URI uri = plugin.getPluginLoader().getURL().toURI();
if(uri != null) {
uris.add(uri);
}
} catch (URISyntaxException e) {
AnalysisContext.logError("Unable to get URI", e);
}
}
return uris;
}
/**
* @return may return null
*/
@CheckForNull
static synchronized Plugin getPlugin(URI uri) {
return allPlugins.get(uri);
}
/**
* @return may return null
*/
@CheckForNull
static synchronized Plugin putPlugin(URI uri, Plugin plugin) {
return allPlugins.put(uri, plugin);
}
public boolean isCorePlugin() {
return pluginLoader.isCorePlugin();
}
public boolean cannotDisable() {
return cannotDisable;
}
public boolean isGloballyEnabled() {
if (isCorePlugin())
return true;
switch (enabled) {
case ENABLED:
return true;
case DISABLED:
return false;
case PLUGIN_DEFAULT:
return isEnabledByDefault();
default:
throw new IllegalStateException("Unknown state : " + enabled);
}
}
/**
* @return
*/
public void setGloballyEnabled(boolean enabled) {
if (isCorePlugin()) {
if (!enabled)
throw new IllegalArgumentException("Can't disable core plugin");
return;
}
if (cannotDisable) {
if (enabled) return;
throw new IllegalArgumentException("Cannot disable " + pluginId);
}
EnabledState oldState = this.enabled;
if (enabled) {
if (isEnabledByDefault())
this.enabled = EnabledState.PLUGIN_DEFAULT;
else
this.enabled = EnabledState.ENABLED;
} else {
if (isEnabledByDefault())
this.enabled = EnabledState.DISABLED;
else
this.enabled = EnabledState.PLUGIN_DEFAULT;
}
if(oldState != this.enabled) {
// TODO update detector factory collection?
}
}
public boolean isInitialPlugin() {
return getPluginLoader().initialPlugin;
}
public URL getResource(String name) {
return getPluginLoader().getResource(name);
}
public ClassLoader getClassLoader() {
return getPluginLoader().getClassLoader();
}
public @CheckForNull Plugin getParentPlugin() {
if (getPluginLoader().hasParent())
return Plugin.getByPluginId(getPluginLoader().parentId);
return null;
}
/**
* Loads the given plugin and enables it for the given project.
*/
public static Plugin loadCustomPlugin(File f, @CheckForNull Project project)
throws PluginException {
URL urlString;
try {
urlString = f.toURI().toURL();
} catch (MalformedURLException e) {
throw new IllegalArgumentException(e);
}
return loadCustomPlugin(urlString, project);
}
/**
* Loads the given plugin and enables it for the given project.
*/
public static Plugin loadCustomPlugin(URL urlString, @CheckForNull Project project) throws PluginException {
Plugin plugin = addCustomPlugin(urlString);
if (project != null) {
project.setPluginStatusTrinary(plugin.getPluginId(), true);
}
return plugin;
}
public static @CheckForNull Plugin addCustomPlugin(URL u) throws PluginException {
return addCustomPlugin(u, PluginLoader.class.getClassLoader());
}
public static @CheckForNull Plugin addCustomPlugin(URI u) throws PluginException {
return addCustomPlugin(u, PluginLoader.class.getClassLoader());
}
public static @CheckForNull Plugin addCustomPlugin(URL u, ClassLoader parent) throws PluginException {
PluginLoader pluginLoader = PluginLoader.getPluginLoader(u, parent, false, true);
Plugin plugin = pluginLoader.loadPlugin();
if (plugin != null)
DetectorFactoryCollection.instance().loadPlugin(plugin);
return plugin;
}
public static @CheckForNull Plugin addCustomPlugin(URI u, ClassLoader parent) throws PluginException {
URL url;
try {
url = u.toURL();
} catch (MalformedURLException e) {
throw new PluginException("Unable to convert uri to url:" + u, e);
}
return addCustomPlugin(url, parent);
}
public static synchronized void removeCustomPlugin(Plugin plugin) {
Set<Entry<URI, Plugin>> entrySet = Plugin.allPlugins.entrySet();
for (Entry<URI, Plugin> entry : entrySet) {
if(entry.getValue() == plugin) {
Plugin.allPlugins.remove(entry.getKey());
PluginLoader.loadedPluginIds.remove(plugin.getPluginId());
break;
}
}
DetectorFactoryCollection.instance().unLoadPlugin(plugin);
}
}
|
package ua.com.fielden.platform.sample.domain;
import ua.com.fielden.platform.dao.CommonEntityDao;
import ua.com.fielden.platform.dao.annotations.SessionRequired;
import ua.com.fielden.platform.entity.AbstractEntity;
import ua.com.fielden.platform.entity.fetch.IFetchProvider;
import ua.com.fielden.platform.entity.query.IFilter;
import ua.com.fielden.platform.sample.domain.mixin.TgFunctionalEntityWithCentreContextMixin;
import ua.com.fielden.platform.swing.review.annotations.EntityType;
import com.google.inject.Inject;
/**
* DAO implementation for companion object {@link ITgFunctionalEntityWithCentreContext}.
*
* @author Developers
*
*/
@EntityType(TgFunctionalEntityWithCentreContext.class)
public class TgFunctionalEntityWithCentreContextDao extends CommonEntityDao<TgFunctionalEntityWithCentreContext> implements ITgFunctionalEntityWithCentreContext {
private final TgFunctionalEntityWithCentreContextMixin mixin;
private final ITgPersistentEntityWithProperties dao;
@Inject
public TgFunctionalEntityWithCentreContextDao(final IFilter filter, final ITgPersistentEntityWithProperties dao) {
super(filter);
this.dao = dao;
mixin = new TgFunctionalEntityWithCentreContextMixin(this);
}
@Override
public IFetchProvider<TgFunctionalEntityWithCentreContext> createFetchProvider() {
return super.createFetchProvider()
.with("key") // this property is "required" (necessary during saving) -- should be declared as fetching property
.with("desc")
.with("valueToInsert", "withBrackets");
}
@Override
@SessionRequired
public TgFunctionalEntityWithCentreContext save(final TgFunctionalEntityWithCentreContext entity) {
for (final AbstractEntity<?> selectedEntity : entity.getContext().getSelectedEntities()) {
final TgPersistentEntityWithProperties selected = dao.findById(selectedEntity.getId()); // (TgPersistentEntityWithProperties) selectedEntity;
final Object user = entity.getContext().getSelectionCrit() != null ? entity.getContext().getSelectionCrit().get("tgPersistentEntityWithProperties_userParam.key") : "UNKNOWN_USER";
selected.set("desc", user + ": " + entity.getValueToInsert() + ": " + selected.get("desc"));
if (entity.getWithBrackets()) {
selected.set("desc", "[" + selected.get("desc") + "]");
}
dao.save(selected);
}
return super.save(entity);
}
}
|
package eu.cloudscaleproject.env.example.common;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.net.URL;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Logger;
import java.util.zip.ZipFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Platform;
import org.eclipse.ui.dialogs.IOverwriteQuery;
import org.eclipse.ui.wizards.datatransfer.ImportOperation;
import org.eclipse.ui.wizards.datatransfer.ZipFileStructureProvider;
import eu.cloudscaleproject.env.common.CloudScaleConstants;
import eu.cloudscaleproject.env.example.common.Example.Resource.Type;
import eu.cloudscaleproject.env.product.wizard.CloudScaleProjectSupport;
public class ExampleService
{
private static final String EP_EXAMPLE = "eu.cloudscaleproject.env.example";
private static ExampleService instance;
private List<Example> examples;
public static ExampleService getInstance()
{
if (instance == null)
{
instance = new ExampleService();
instance.examples = retrieveExamples();
}
return instance;
}
public List<Example> getExamples()
{
return examples;
}
public IProject getProject (Example.Resource r)
{
IProject project;
try
{
project = ResourcesPlugin.getWorkspace().getRoot().getProject(getProjectName(r));
if (project.exists())
{
return project;
}
} catch (IOException e)
{
e.printStackTrace();
}
return null;
}
public void createExampleResourceProject(Example.Resource r) throws Exception
{
// Prepare project
IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(getProjectName(r));
if (!project.exists())
{
project.create(new NullProgressMonitor());
project.open(new NullProgressMonitor());
// Extract archive to newly prepared project
unpackResourceProject(project, r);
CloudScaleProjectSupport.addNature(project, CloudScaleConstants.EXAMPLE_NATURE_ID);
}
else
{
Logger.getLogger(ExampleService.class.getName()).info("Example project already exists : "+project.getName());
}
}
public static IProject unpackResourceProject(IProject project, Example.Resource resource) throws Exception
{
if (resource.getType() == Type.ENVIRONMENT)
CloudScaleProjectSupport.addProjectNature(project);
ZipFile file = new ZipFile(resource.getArchive().getFile());
ZipFileStructureProvider provider = new ZipFileStructureProvider(file);
IPath containerPath = project.getFullPath();
Object source = provider.getRoot();
IOverwriteQuery query = new IOverwriteQuery()
{
@Override
public String queryOverwrite(String path)
{
return IOverwriteQuery.ALL;
};
};
ImportOperation operation = new ImportOperation(containerPath, source, provider, query);
operation.run(null);
return project;
}
private String getProjectName(Example.Resource r) throws IOException
{
URL entryUrl = new URL("jar:" + r.getArchive() + "!/.project");
BufferedReader br = new BufferedReader(new InputStreamReader(entryUrl.openStream()));
StringWriter writer = new StringWriter();
String line = "";
while((line = br.readLine()) != null){
writer.append(line);
}
br.close();
String theString = writer.toString();
int from = theString.indexOf("<name>") + 6;
int to = theString.indexOf("</name>");
return theString.substring(from, to);
}
private static List<Example> retrieveExamples()
{
List<Example> examples = new LinkedList<>();
IConfigurationElement[] elements = Platform.getExtensionRegistry().getConfigurationElementsFor(EP_EXAMPLE);
for (IConfigurationElement el : elements)
{
if (!el.isValid())
{
continue;
}
Example e = new Example(el);
examples.add(e);
}
return examples;
}
}
|
package services.languageProcessor;
import com.fasterxml.jackson.databind.JsonNode;
import play.Configuration;
import play.api.Play;
import play.libs.Json;
import play.libs.ws.WSClient;
import play.libs.ws.WSRequest;
import play.libs.ws.WSResponse;
import services.IntentEntity;
import java.util.concurrent.CompletionStage;
public class LUIS {
private Configuration configuration;
private String query;
private WSClient ws;
public LUIS(String query, WSClient ws) {
configuration = Play.current().injector().instanceOf(Configuration.class);
this.query = query;
this.ws = ws;
}
public JsonNode handleQuery(){
return getLuisResult(query);
}
/**
* This method connects to the LUIS API and sends a query.
* @param query is the question by a user to POET on slack channel.
* @return the result of classification performed by LUSI on the asked query as a JSON object.
*/
public JsonNode getLuisResult(String query) {
CompletionStage<JsonNode> responsePromise = getTask(query);
try{
JsonNode node = responsePromise.toCompletableFuture().get();
return taskMapping(node);
}catch(Exception e){
System.out.println("Exception: " + e.toString());
return null;
}
}
/**
* Connects to LUIS API using HTTPS request.
* LUIS API processes the query and returns intent and entities as JSON object
* @param query
* @return
*/
public CompletionStage<JsonNode> getTask(String query) {
String luisurl = configuration.getString("luis.url");
String appid = configuration.getString("luis.appId");
String key = configuration.getString("luis.subscription-key");
WSRequest request = ws.url(luisurl);
WSRequest complexRequest = request.setQueryParameter("subscription-key",key).setQueryParameter("q",query);
return complexRequest.get().thenApply(WSResponse:: asJson);
}
/**
* This method gets the topScoring intent and identified entities
* from LUIS API and calls methods to perform the required action.
* @param responseBody
* @return
*/
public JsonNode taskMapping(JsonNode responseBody) {
System.out.print((responseBody.toString()));
String topScoringIntent = responseBody.get("topScoringIntent").get("intent").toString().replace("\"", "");
String entity = null;
if(responseBody.get("entities").findValues("entity").size() != 0) {
entity = responseBody.get("entities").findValues("entity").get(0).toString().replaceAll("\"", "").replaceAll("\\s", "");
}
String entityType = null;
if(responseBody.get("entities").findValues("type").size() != 0) {
entityType = responseBody.get("entities").findValues("type").get(0).toString().replace("\"", "").replace(" ", "");
}
IntentEntity intentEntity = new IntentEntity();
intentEntity.intent = topScoringIntent;
intentEntity.entityType = entityType;
intentEntity.entityName = entity;
return Json.toJson((intentEntity));
}
}
|
package org.voovan.tools;
import java.lang.ref.PhantomReference;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.util.Timer;
import java.util.TimerTask;
public class Cleaner extends PhantomReference<Object> {
private static final ReferenceQueue<Object> dummyQueue = new ReferenceQueue();
private static Cleaner first = null;
private Cleaner next = null;
private Cleaner prev = null;
private final Runnable thunk;
private static final Timer timer;
static {
Integer noHeapReleaseInterval = TProperties.getInt("framework", "NoHeapReleaseInterval");
Integer finalNoHeapReleaseInterval = noHeapReleaseInterval ==0 ? 3 : noHeapReleaseInterval;
timer = new Timer();
timer.schedule(new TimerTask() {
int releaseCount = 0;
@Override
public void run() {
while(true) {
Reference cleanerRef= dummyQueue.poll();
if(cleanerRef == null){
if(releaseCount == finalNoHeapReleaseInterval){
System.gc();
}
releaseCount ++;
break;
} else if(cleanerRef instanceof Cleaner){
Cleaner cleaner = (Cleaner) cleanerRef;
cleaner.clean();
releaseCount = 0;
}
}
}
}, 1000, 1000);
}
private static synchronized Cleaner add(Cleaner cleaner) {
if (first != null) {
cleaner.next = first;
first.prev = cleaner;
}
first = cleaner;
return cleaner;
}
private static synchronized boolean remove(Cleaner cleaner) {
if (cleaner.next == cleaner) {
return false;
} else {
if (first == cleaner) {
if (cleaner.next != null) {
first = cleaner.next;
} else {
first = cleaner.prev;
}
}
if (cleaner.next != null) {
cleaner.next.prev = cleaner.prev;
}
if (cleaner.prev != null) {
cleaner.prev.next = cleaner.next;
}
cleaner.next = cleaner;
cleaner.prev = cleaner;
return true;
}
}
private Cleaner(Object obj, Runnable thunk) {
super(obj, dummyQueue);
this.thunk = thunk;
}
public static Cleaner create(Object obj, Runnable thunk) {
return thunk == null ? null : add(new Cleaner(obj, thunk));
}
public void clean() {
if (remove(this)) {
try {
this.thunk.run();
} catch (final Throwable var2) {
System.out.println("Cleaner terminated abnormally");
}
}
}
}
|
package com.evolveum.midpoint.task.quartzimpl;
import static com.evolveum.midpoint.test.IntegrationTestTools.display;
import static org.testng.AssertJUnit.assertEquals;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.xml.bind.JAXBException;
import javax.xml.namespace.QName;
import com.evolveum.midpoint.prism.*;
import com.evolveum.midpoint.prism.delta.ItemDelta;
import com.evolveum.midpoint.prism.delta.PropertyDelta;
import com.evolveum.midpoint.prism.path.ItemPath;
import com.evolveum.midpoint.prism.schema.SchemaRegistry;
import com.evolveum.midpoint.schema.DeltaConvertor;
import com.evolveum.midpoint.schema.result.OperationResultStatus;
import com.evolveum.midpoint.task.quartzimpl.handlers.NoOpTaskHandler;
import com.evolveum.midpoint.test.Checker;
import com.evolveum.midpoint.test.IntegrationTestTools;
import com.evolveum.midpoint.util.exception.SystemException;
import com.evolveum.midpoint.xml.ns._public.common.common_2.*;
import com.evolveum.prism.xml.ns._public.types_2.ItemDeltaType;
import org.opends.server.types.Attribute;
import org.opends.server.types.SearchResultEntry;
import org.quartz.JobKey;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.testng.Assert;
import org.testng.AssertJUnit;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
import com.evolveum.midpoint.prism.util.PrismAsserts;
import com.evolveum.midpoint.prism.util.PrismTestUtil;
import com.evolveum.midpoint.repo.api.RepositoryService;
import com.evolveum.midpoint.schema.MidPointPrismContextFactory;
import com.evolveum.midpoint.schema.constants.MidPointConstants;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.schema.util.ObjectTypeUtil;
import com.evolveum.midpoint.schema.util.ResourceTypeUtil;
import com.evolveum.midpoint.task.api.Task;
import com.evolveum.midpoint.task.api.TaskBinding;
import com.evolveum.midpoint.task.api.TaskExecutionStatus;
import com.evolveum.midpoint.task.api.TaskRecurrence;
import com.evolveum.midpoint.util.DOMUtil;
import com.evolveum.midpoint.util.JAXBUtil;
import com.evolveum.midpoint.util.PrettyPrinter;
import com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException;
import com.evolveum.midpoint.util.exception.ObjectNotFoundException;
import com.evolveum.midpoint.util.exception.SchemaException;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import static com.evolveum.midpoint.test.IntegrationTestTools.*;
import static org.testng.AssertJUnit.assertNotNull;
/**
* @author Radovan Semancik
*/
@ContextConfiguration(locations = {"classpath:application-context-task.xml",
"classpath:application-context-task-test.xml",
"classpath:application-context-repo-cache.xml",
"classpath:application-context-repository.xml",
"classpath:application-context-audit.xml",
"classpath:application-context-configuration-test.xml"})
public class TestQuartzTaskManagerContract extends AbstractTestNGSpringContextTests {
private static final transient Trace LOGGER = TraceManager.getTrace(TestQuartzTaskManagerContract.class);
private static final String TASK_OWNER_FILENAME = "src/test/resources/repo/owner.xml";
private static final String TASK_OWNER2_FILENAME = "src/test/resources/repo/owner2.xml";
private static final String TASK_OWNER2_OID = "c0c010c0-d34d-b33f-f00d-111111111112";
private static final String NS_WHATEVER = "http://myself.me/schemas/whatever";
private static String taskFilename(String test) {
return "src/test/resources/repo/task-" + test + ".xml";
}
private static String taskOid(String test) {
return "91919191-76e0-59e2-86d6-556655660" + test.substring(0, 3);
}
private static OperationResult createResult(String test) {
System.out.println("===[ "+test+" ]===");
LOGGER.info("===[ "+test+" ]===");
return new OperationResult(TestQuartzTaskManagerContract.class.getName() + ".test" + test);
}
private static final String CYCLE_TASK_HANDLER_URI = "http://midpoint.evolveum.com/test/cycle-task-handler";
public static final String SINGLE_TASK_HANDLER_URI = "http://midpoint.evolveum.com/test/single-task-handler";
public static final String SINGLE_TASK_HANDLER_2_URI = "http://midpoint.evolveum.com/test/single-task-handler-2";
public static final String SINGLE_TASK_HANDLER_3_URI = "http://midpoint.evolveum.com/test/single-task-handler-3";
public static final String L1_TASK_HANDLER_URI = "http://midpoint.evolveum.com/test/l1-task-handler";
public static final String L2_TASK_HANDLER_URI = "http://midpoint.evolveum.com/test/l2-task-handler";
public static final String L3_TASK_HANDLER_URI = "http://midpoint.evolveum.com/test/l3-task-handler";
public static final String WAIT_FOR_SUBTASKS_TASK_HANDLER_URI = "http://midpoint.evolveum.com/test/wait-for-subtasks-task-handler";
@Autowired(required = true)
private RepositoryService repositoryService;
private static boolean repoInitialized = false;
@Autowired(required = true)
private TaskManagerQuartzImpl taskManager;
@Autowired(required = true)
private PrismContext prismContext;
@BeforeSuite
public void setup() throws SchemaException, SAXException, IOException {
PrettyPrinter.setDefaultNamespacePrefix(MidPointConstants.NS_MIDPOINT_PUBLIC_PREFIX);
PrismTestUtil.resetPrismContext(MidPointPrismContextFactory.FACTORY);
}
// We need this complicated init as we want to initialize repo only once.
// JUnit will
// create new class instance for every test, so @Before and @PostInit will
// not work
// directly. We also need to init the repo after spring autowire is done, so
// @BeforeClass won't work either.
@BeforeMethod
public void initRepository() throws Exception {
if (!repoInitialized) {
// addObjectFromFile(SYSTEM_CONFIGURATION_FILENAME);
repoInitialized = true;
}
}
MockSingleTaskHandler singleHandler1, singleHandler2, singleHandler3;
MockSingleTaskHandler l1Handler, l2Handler, l3Handler;
MockSingleTaskHandler waitForSubtasksTaskHandler;
@PostConstruct
public void initHandlers() throws Exception {
MockCycleTaskHandler cycleHandler = new MockCycleTaskHandler();
taskManager.registerHandler(CYCLE_TASK_HANDLER_URI, cycleHandler);
singleHandler1 = new MockSingleTaskHandler("1", taskManager);
taskManager.registerHandler(SINGLE_TASK_HANDLER_URI, singleHandler1);
singleHandler2 = new MockSingleTaskHandler("2", taskManager);
taskManager.registerHandler(SINGLE_TASK_HANDLER_2_URI, singleHandler2);
singleHandler3 = new MockSingleTaskHandler("3", taskManager);
taskManager.registerHandler(SINGLE_TASK_HANDLER_3_URI, singleHandler3);
l1Handler = new MockSingleTaskHandler("L1", taskManager);
l2Handler = new MockSingleTaskHandler("L2", taskManager);
l3Handler = new MockSingleTaskHandler("L3", taskManager);
taskManager.registerHandler(L1_TASK_HANDLER_URI, l1Handler);
taskManager.registerHandler(L2_TASK_HANDLER_URI, l2Handler);
taskManager.registerHandler(L3_TASK_HANDLER_URI, l3Handler);
waitForSubtasksTaskHandler = new MockSingleTaskHandler("WFS", taskManager);
taskManager.registerHandler(WAIT_FOR_SUBTASKS_TASK_HANDLER_URI, waitForSubtasksTaskHandler);
addObjectFromFile(TASK_OWNER_FILENAME);
addObjectFromFile(TASK_OWNER2_FILENAME);
}
/**
* Test integrity of the test setup.
*
* @throws SchemaException
* @throws ObjectNotFoundException
*/
@Test(enabled = true)
public void test000Integrity() {
AssertJUnit.assertNotNull(repositoryService);
AssertJUnit.assertNotNull(taskManager);
}
/**
* Here we only test setting various task properties.
*/
@Test(enabled = true)
public void test003GetProgress() throws Exception {
String test = "003GetProgress";
OperationResult result = createResult(test);
addObjectFromFile(taskFilename(test));
logger.trace("Retrieving the task and getting its progress...");
TaskQuartzImpl task = (TaskQuartzImpl) taskManager.getTask(taskOid(test), result);
AssertJUnit.assertEquals("Progress is not 0", 0, task.getProgress());
}
@Test(enabled = false) // this is probably OK to fail, so do not enable it (at least for now)
public void test004aTaskBigProperty() throws Exception {
String test = "004aTaskBigProperty";
OperationResult result = createResult(test);
String string300 = "123456789-123456789-123456789-123456789-123456789-"
+ "123456789-123456789-123456789-123456789-123456789-"
+ "123456789-123456789-123456789-123456789-123456789-"
+ "123456789-123456789-123456789-123456789-123456789-"
+ "123456789-123456789-123456789-123456789-123456789-"
+ "123456789-123456789-123456789-123456789-123456789-";
String string300a = "AAAAAAAAA-123456789-123456789-123456789-123456789-"
+ "123456789-123456789-123456789-123456789-123456789-"
+ "123456789-123456789-123456789-123456789-123456789-"
+ "123456789-123456789-123456789-123456789-123456789-"
+ "123456789-123456789-123456789-123456789-123456789-"
+ "123456789-123456789-123456789-123456789-123456789-";
addObjectFromFile(taskFilename(test));
TaskQuartzImpl task = (TaskQuartzImpl) taskManager.getTask(taskOid(test), result);
// property definition
QName bigStringQName = new QName("http://midpoint.evolveum.com/repo/test", "bigString");
PrismPropertyDefinition bigStringDefinition = new PrismPropertyDefinition(bigStringQName, bigStringQName, DOMUtil.XSD_STRING, taskManager.getPrismContext());
bigStringDefinition.setIndexed(false);
bigStringDefinition.setMinOccurs(0);
bigStringDefinition.setMaxOccurs(1);
System.out.println("bigstring property definition = " + bigStringDefinition);
PrismProperty<String> bigStringProperty = (PrismProperty<String>) bigStringDefinition.instantiate();
bigStringProperty.setRealValue(string300);
task.setExtensionProperty(bigStringProperty);
task.savePendingModifications(result);
System.out.println("1st round: Task = " + task.dump());
logger.trace("Retrieving the task and comparing its properties...");
Task task001 = taskManager.getTask(taskOid(test), result);
System.out.println("1st round: Task from repo: " + task001.dump());
PrismProperty<String> bigString001 = (PrismProperty<String>) task001.getExtension(bigStringQName);
assertEquals("Big string not retrieved correctly (1st round)", bigStringProperty.getRealValue(), bigString001.getRealValue());
// second round
bigStringProperty.setRealValue(string300a);
task001.setExtensionProperty(bigStringProperty);
// brutal hack, because task extension property has no "indexed" flag when retrieved from repo
task001.getExtension(bigStringQName).getDefinition().setIndexed(false);
System.out.println("2nd round: Task before save = " + task001.dump());
task001.savePendingModifications(result); // however, this does not work, because 'modifyObject' in repo first reads object, overwriting any existing definitions ...
Task task002 = taskManager.getTask(taskOid(test), result);
System.out.println("2nd round: Task from repo: " + task002.dump());
PrismProperty<String> bigString002 = (PrismProperty<String>) task002.getExtension(bigStringQName);
assertEquals("Big string not retrieved correctly (2nd round)", bigStringProperty.getRealValue(), bigString002.getRealValue());
}
@Test(enabled = true)
public void test004bTaskBigProperty() throws Exception {
String test = "004aTaskBigProperty";
OperationResult result = createResult(test);
String string300 = "123456789-123456789-123456789-123456789-123456789-"
+ "123456789-123456789-123456789-123456789-123456789-"
+ "123456789-123456789-123456789-123456789-123456789-"
+ "123456789-123456789-123456789-123456789-123456789-"
+ "123456789-123456789-123456789-123456789-123456789-"
+ "123456789-123456789-123456789-123456789-123456789-";
String string300a = "AAAAAAAAA-123456789-123456789-123456789-123456789-"
+ "123456789-123456789-123456789-123456789-123456789-"
+ "123456789-123456789-123456789-123456789-123456789-"
+ "123456789-123456789-123456789-123456789-123456789-"
+ "123456789-123456789-123456789-123456789-123456789-"
+ "123456789-123456789-123456789-123456789-123456789-";
addObjectFromFile(taskFilename(test));
TaskQuartzImpl task = (TaskQuartzImpl) taskManager.getTask(taskOid(test), result);
// property definition
QName shipStateQName = new QName("http://myself.me/schemas/whatever", "shipState");
PrismPropertyDefinition shipStateDefinition = prismContext.getSchemaRegistry().findPropertyDefinitionByElementName(shipStateQName);
assertNotNull("Cannot find property definition for shipState", shipStateDefinition);
PrismProperty<String> shipStateProperty = (PrismProperty<String>) shipStateDefinition.instantiate();
shipStateProperty.setRealValue(string300);
task.setExtensionProperty(shipStateProperty);
task.savePendingModifications(result);
System.out.println("1st round: Task = " + task.dump());
logger.trace("Retrieving the task and comparing its properties...");
Task task001 = taskManager.getTask(taskOid(test), result);
System.out.println("1st round: Task from repo: " + task001.dump());
PrismProperty<String> shipState001 = (PrismProperty<String>) task001.getExtension(shipStateQName);
assertEquals("Big string not retrieved correctly (1st round)", shipStateProperty.getRealValue(), shipState001.getRealValue());
// second round
shipStateProperty.setRealValue(string300a);
task001.setExtensionProperty(shipStateProperty);
System.out.println("2nd round: Task before save = " + task001.dump());
task001.savePendingModifications(result);
Task task002 = taskManager.getTask(taskOid(test), result);
System.out.println("2nd round: Task from repo: " + task002.dump());
PrismProperty<String> bigString002 = (PrismProperty<String>) task002.getExtension(shipStateQName);
assertEquals("Big string not retrieved correctly (2nd round)", shipStateProperty.getRealValue(), bigString002.getRealValue());
}
@Test(enabled = true)
public void test004TaskProperties() throws Exception {
String test = "004TaskProperties";
OperationResult result = createResult(test);
addObjectFromFile(taskFilename(test));
TaskQuartzImpl task = (TaskQuartzImpl) taskManager.getTask(taskOid(test), result);
System.out.println("Task extension = " + task.getExtension());
PrismPropertyDefinition delayDefinition = new PrismPropertyDefinition(NoOpTaskHandler.DELAY_QNAME, NoOpTaskHandler.DELAY_QNAME, DOMUtil.XSD_INT, taskManager.getPrismContext());
System.out.println("property definition = " + delayDefinition);
PrismProperty<Integer> property = (PrismProperty<Integer>) delayDefinition.instantiate();
property.setRealValue(100);
PropertyDelta delta = new PropertyDelta(new ItemPath(TaskType.F_EXTENSION, property.getName()), property.getDefinition());
//delta.addV(property.getValues());
delta.setValuesToReplace(PrismValue.cloneCollection(property.getValues()));
Collection<ItemDelta<?>> modifications = new ArrayList<ItemDelta<?>>(1);
modifications.add(delta);
Collection<ItemDeltaType> idts = DeltaConvertor.toPropertyModificationTypes(delta);
for (ItemDeltaType idt : idts) {
String idtxml = prismContext.getPrismJaxbProcessor().marshalElementToString(idt, new QName("http://a/", "A"));
System.out.println("item delta type = " + idtxml);
ItemDeltaType idt2 = prismContext.getPrismJaxbProcessor().unmarshalObject(idtxml, ItemDeltaType.class);
ItemDelta id2 = DeltaConvertor.createItemDelta(idt2, TaskType.class, prismContext);
System.out.println("unwrapped item delta = " + id2.debugDump());
task.modifyExtension(id2);
}
task.savePendingModifications(result);
System.out.println("Task = " + task.dump());
PrismObject<UserType> owner2 = repositoryService.getObject(UserType.class, TASK_OWNER2_OID, result);
task.setBindingImmediate(TaskBinding.LOOSE, result);
// other properties will be set in batched mode
String newname = "Test task, name changed";
task.setName(PrismTestUtil.createPolyStringType(newname));
task.setProgress(10);
long currentTime = System.currentTimeMillis();
long currentTime1 = currentTime + 10000;
long currentTime2 = currentTime + 25000;
task.setLastRunStartTimestamp(currentTime);
task.setLastRunFinishTimestamp(currentTime1);
task.setExecutionStatus(TaskExecutionStatus.SUSPENDED);
task.setHandlerUri("http://no-handler.org/");
//task.setOwner(owner2);
ScheduleType st0 = task.getSchedule();
ScheduleType st1 = new ScheduleType();
st1.setInterval(1);
st1.setMisfireAction(MisfireActionType.RESCHEDULE);
task.pushHandlerUri("http://no-handler.org/1", st1, TaskBinding.TIGHT, task.createExtensionDelta(delayDefinition, 1));
ScheduleType st2 = new ScheduleType();
st2.setInterval(2);
st2.setMisfireAction(MisfireActionType.EXECUTE_IMMEDIATELY);
task.pushHandlerUri("http://no-handler.org/2", st2, TaskBinding.LOOSE, task.createExtensionDelta(delayDefinition, 2));
task.setRecurrenceStatus(TaskRecurrence.RECURRING);
OperationResultType ort = result.createOperationResultType(); // to be compared with later
task.setResult(result);
logger.trace("Saving modifications...");
task.savePendingModifications(result);
logger.trace("Retrieving the task (second time) and comparing its properties...");
Task task001 = taskManager.getTask(taskOid(test), result);
logger.trace("Task from repo: " + task001.dump());
AssertJUnit.assertEquals(TaskBinding.LOOSE, task001.getBinding());
PrismAsserts.assertEqualsPolyString("Name not", newname, task001.getName());
// AssertJUnit.assertEquals(newname, task001.getName());
AssertJUnit.assertTrue(10 == task001.getProgress());
AssertJUnit.assertNotNull(task001.getLastRunStartTimestamp());
AssertJUnit.assertTrue(currentTime == task001.getLastRunStartTimestamp());
AssertJUnit.assertNotNull(task001.getLastRunFinishTimestamp());
AssertJUnit.assertTrue(currentTime1 == task001.getLastRunFinishTimestamp());
// AssertJUnit.assertEquals(TaskExclusivityStatus.CLAIMED, task001.getExclusivityStatus());
AssertJUnit.assertEquals(TaskExecutionStatus.SUSPENDED, task001.getExecutionStatus());
AssertJUnit.assertEquals("Handler after 2xPUSH is not OK", "http://no-handler.org/2", task001.getHandlerUri());
AssertJUnit.assertEquals("Schedule after 2xPUSH is not OK", st2, task001.getSchedule());
AssertJUnit.assertEquals("Number of handlers is not OK", 3, task.getHandlersCount());
UriStack us = task.getOtherHandlersUriStack();
AssertJUnit.assertEquals("First handler from the handler stack does not match", "http://no-handler.org/", us.getUriStackEntry().get(0).getHandlerUri());
AssertJUnit.assertEquals("First schedule from the handler stack does not match", st0, us.getUriStackEntry().get(0).getSchedule());
AssertJUnit.assertEquals("Second handler from the handler stack does not match", "http://no-handler.org/1", us.getUriStackEntry().get(1).getHandlerUri());
AssertJUnit.assertEquals("Second schedule from the handler stack does not match", st1, us.getUriStackEntry().get(1).getSchedule());
AssertJUnit.assertTrue(task001.isCycle());
OperationResult r001 = task001.getResult();
AssertJUnit.assertNotNull(r001);
//AssertJUnit.assertEquals("Owner OID is not correct", TASK_OWNER2_OID, task001.getOwner().getOid());
PrismProperty<?> d = task001.getExtension(NoOpTaskHandler.DELAY_QNAME);
AssertJUnit.assertNotNull("delay extension property was not found", d);
AssertJUnit.assertEquals("delay extension property has wrong value", (Integer) 100, d.getRealValue(Integer.class));
OperationResultType ort1 = r001.createOperationResultType();
// handling of operation result in tasks is extremely fragile now...
// in case of problems, just uncomment the following line ;)
AssertJUnit.assertEquals(ort, ort1);
// now pop the handlers
((TaskQuartzImpl) task001).finishHandler(result);
task001.refresh(result);
AssertJUnit.assertEquals("Handler URI after first POP is not correct", "http://no-handler.org/1", task001.getHandlerUri());
AssertJUnit.assertEquals("Schedule after first POP is not correct", st1, task001.getSchedule());
AssertJUnit.assertEquals("Binding after first POP is not correct", TaskBinding.TIGHT, task001.getBinding());
AssertJUnit.assertNotSame("Task state after first POP should not be CLOSED", TaskExecutionStatus.CLOSED, task001.getExecutionStatus());
AssertJUnit.assertEquals("Extension element value is not correct after first POP", (Integer) 2, task001.getExtension(NoOpTaskHandler.DELAY_QNAME).getRealValue(Integer.class));
((TaskQuartzImpl) task001).finishHandler(result);
task001.refresh(result);
AssertJUnit.assertEquals("Handler URI after second POP is not correct", "http://no-handler.org/", task001.getHandlerUri());
AssertJUnit.assertEquals("Schedule after second POP is not correct", st0, task001.getSchedule());
AssertJUnit.assertEquals("Binding after second POP is not correct", TaskBinding.LOOSE, task001.getBinding());
AssertJUnit.assertNotSame("Task state after second POP should not be CLOSED", TaskExecutionStatus.CLOSED, task001.getExecutionStatus());
AssertJUnit.assertEquals("Extension element value is not correct after second POP", (Integer) 1, task001.getExtension(NoOpTaskHandler.DELAY_QNAME).getRealValue(Integer.class));
((TaskQuartzImpl) task001).finishHandler(result);
task001.refresh(result);
AssertJUnit.assertNull("Handler URI after third POP is not null", task001.getHandlerUri());
AssertJUnit.assertEquals("Task state after third POP is not CLOSED", TaskExecutionStatus.CLOSED, task001.getExecutionStatus());
}
/*
* Execute a single-run task.
*/
@Test(enabled = true)
public void test005Single() throws Exception {
final String test = "005Single";
final OperationResult result = createResult(test);
// reset 'has run' flag on the handler
singleHandler1.resetHasRun();
// Add single task. This will get picked by task scanner and executed
addObjectFromFile(taskFilename(test));
logger.trace("Retrieving the task...");
TaskQuartzImpl task = (TaskQuartzImpl) taskManager.getTask(taskOid(test), result);
AssertJUnit.assertNotNull(task);
logger.trace("Task retrieval OK.");
// We need to wait for a sync interval, so the task scanner has a chance
// to pick up this
// task
waitFor("Waiting for task manager to execute the task", new Checker() {
public boolean check() throws ObjectNotFoundException, SchemaException {
Task task = taskManager.getTask(taskOid(test), result);
IntegrationTestTools.display("Task while waiting for task manager to execute the task", task);
return task.getExecutionStatus() == TaskExecutionStatus.CLOSED;
}
@Override
public void timeout() {
}
}, 10000, 1000);
logger.info("... done");
// Check task status
Task task1 = taskManager.getTask(taskOid(test), result);
AssertJUnit.assertNotNull(task1);
System.out.println("getTask returned: " + task1.dump());
PrismObject<TaskType> po = repositoryService.getObject(TaskType.class, taskOid(test), result);
System.out.println("getObject returned: " + po.dump());
// .. it should be closed
AssertJUnit.assertEquals(TaskExecutionStatus.CLOSED, task1.getExecutionStatus());
// .. and released
// AssertJUnit.assertEquals(TaskExclusivityStatus.RELEASED, task1.getExclusivityStatus());
// .. and last run should not be zero
AssertJUnit.assertNotNull("LastRunStartTimestamp is null", task1.getLastRunStartTimestamp());
AssertJUnit.assertFalse("LastRunStartTimestamp is 0", task1.getLastRunStartTimestamp().longValue() == 0);
AssertJUnit.assertNotNull("LastRunFinishTimestamp is null", task1.getLastRunFinishTimestamp());
AssertJUnit.assertFalse("LastRunFinishTimestamp is 0", task1.getLastRunFinishTimestamp().longValue() == 0);
// The progress should be more than 0 as the task has run at least once
AssertJUnit.assertTrue("Task reported no progress", task1.getProgress() > 0);
// Test for presence of a result. It should be there and it should
// indicate success
OperationResult taskResult = task1.getResult();
AssertJUnit.assertNotNull("Task result is null", taskResult);
AssertJUnit.assertTrue("Task did not yield 'success' status", taskResult.isSuccess());
// Test for no presence of handlers
AssertJUnit.assertNull("Handler is still present", task1.getHandlerUri());
AssertJUnit.assertTrue("Other handlers are still present",
task1.getOtherHandlersUriStack() == null || task1.getOtherHandlersUriStack().getUriStackEntry().isEmpty());
// Test whether handler has really run
AssertJUnit.assertTrue("Handler1 has not run", singleHandler1.hasRun());
}
/*
* Executes a cyclic task
*/
@Test(enabled = true)
public void test006Cycle() throws Exception {
final String test = "006Cycle";
final OperationResult result = createResult(test);
// But before that check sanity ... a known problem with xsi:type
PrismObject<ObjectType> object = addObjectFromFile(taskFilename(test));
ObjectType objectType = object.asObjectable();
TaskType addedTask = (TaskType) objectType;
System.out.println("Added task");
System.out.println(object.dump());
PrismContainer<?> extensionContainer = object.getExtension();
PrismProperty<Object> deadProperty = extensionContainer.findProperty(new QName(NS_WHATEVER, "dead"));
assertEquals("Bad typed of 'dead' property (add result)", DOMUtil.XSD_INT, deadProperty.getDefinition().getTypeName());
// Read from repo
PrismObject<TaskType> repoTask = repositoryService.getObject(TaskType.class, addedTask.getOid(), result);
TaskType repoTaskType = repoTask.asObjectable();
extensionContainer = repoTask.getExtension();
deadProperty = extensionContainer.findProperty(new QName(NS_WHATEVER, "dead"));
assertEquals("Bad typed of 'dead' property (from repo)", DOMUtil.XSD_INT, deadProperty.getDefinition().getTypeName());
// We need to wait for a sync interval, so the task scanner has a chance
// to pick up this
// task
waitFor("Waiting for task manager to execute the task", new Checker() {
public boolean check() throws ObjectNotFoundException, SchemaException {
Task task = taskManager.getTask(taskOid(test), result);
IntegrationTestTools.display("Task while waiting for task manager to execute the task", task);
return task.getProgress() > 0;
}
@Override
public void timeout() {
}
}, 10000, 2000);
// Check task status
Task task = taskManager.getTask(taskOid(test), result);
AssertJUnit.assertNotNull(task);
System.out.println(task.dump());
PrismObject<TaskType> t = repositoryService.getObject(TaskType.class, taskOid(test), result);
System.out.println(t.dump());
// .. it should be running
AssertJUnit.assertEquals(TaskExecutionStatus.RUNNABLE, task.getExecutionStatus());
// .. and claimed
// AssertJUnit.assertEquals(TaskExclusivityStatus.CLAIMED, task.getExclusivityStatus());
// .. and last run should not be zero
AssertJUnit.assertNotNull("LastRunStartTimestamp is null", task.getLastRunStartTimestamp());
AssertJUnit.assertFalse("LastRunStartTimestamp is 0", task.getLastRunStartTimestamp().longValue() == 0);
AssertJUnit.assertNotNull("LastRunFinishTimestamp is null", task.getLastRunFinishTimestamp());
AssertJUnit.assertFalse("LastRunFinishTimestamp is 0", task.getLastRunFinishTimestamp().longValue() == 0);
// The progress should be more at least 1 - so small because of lazy testing machine ... (wait time before task runs is 2 seconds)
AssertJUnit.assertTrue("Task progress is too small (should be at least 1)", task.getProgress() >= 1);
// Test for presence of a result. It should be there and it should
// indicate success
OperationResult taskResult = task.getResult();
AssertJUnit.assertNotNull("Task result is null", taskResult);
AssertJUnit.assertTrue("Task did not yield 'success' status", taskResult.isSuccess());
// Suspend the task (in order to keep logs clean), without much waiting
taskManager.suspendTask(task, 100, result);
}
/*
* Single-run task with more handlers.
*/
@Test(enabled = true)
public void test008MoreHandlers() throws Exception {
final String test = "008MoreHandlers";
final OperationResult result = createResult(test);
// reset 'has run' flag on handlers
singleHandler1.resetHasRun();
singleHandler2.resetHasRun();
singleHandler3.resetHasRun();
addObjectFromFile(taskFilename(test));
waitFor("Waiting for task manager to execute the task", new Checker() {
public boolean check() throws ObjectNotFoundException, SchemaException {
Task task = taskManager.getTask(taskOid(test), result);
IntegrationTestTools.display("Task while waiting for task manager to execute the task", task);
return task.getExecutionStatus() == TaskExecutionStatus.CLOSED;
}
@Override
public void timeout() {
}
}, 15000, 2000);
// Check task status
Task task = taskManager.getTask(taskOid(test), result);
AssertJUnit.assertNotNull(task);
System.out.println(task.dump());
PrismObject<TaskType> o = repositoryService.getObject(TaskType.class, taskOid(test), result);
System.out.println(ObjectTypeUtil.dump(o.getValue().getValue()));
// .. it should be closed
AssertJUnit.assertEquals(TaskExecutionStatus.CLOSED, task.getExecutionStatus());
// .. and released
// AssertJUnit.assertEquals(TaskExclusivityStatus.RELEASED, task.getExclusivityStatus());
// .. and last run should not be zero
AssertJUnit.assertNotNull(task.getLastRunStartTimestamp());
AssertJUnit.assertFalse(task.getLastRunStartTimestamp().longValue() == 0);
AssertJUnit.assertNotNull("Last run finish timestamp not set", task.getLastRunFinishTimestamp());
AssertJUnit.assertFalse("Last run finish timestamp is 0", task.getLastRunFinishTimestamp().longValue() == 0);
// The progress should be more than 0 as the task has run at least once
AssertJUnit.assertTrue("Task reported no progress", task.getProgress() > 0);
// Test for presence of a result. It should be there and it should
// indicate success
OperationResult taskResult = task.getResult();
AssertJUnit.assertNotNull("Task result is null", taskResult);
AssertJUnit.assertTrue("Task did not yield 'success' status", taskResult.isSuccess());
// Test for no presence of handlers
AssertJUnit.assertNull("Handler is still present", task.getHandlerUri());
AssertJUnit.assertTrue("Other handlers are still present",
task.getOtherHandlersUriStack() == null || task.getOtherHandlersUriStack().getUriStackEntry().isEmpty());
// Test if all three handlers were run
AssertJUnit.assertTrue("Handler1 has not run", singleHandler1.hasRun());
AssertJUnit.assertTrue("Handler2 has not run", singleHandler2.hasRun());
AssertJUnit.assertTrue("Handler3 has not run", singleHandler3.hasRun());
}
@Test(enabled = true)
public void test009CycleLoose() throws Exception {
final String test = "009CycleLoose";
final OperationResult result = createResult(test);
PrismObject<ObjectType> object = addObjectFromFile(taskFilename(test));
// We need to wait for a sync interval, so the task scanner has a chance
// to pick up this task
waitFor("Waiting for task manager to execute the task", new Checker() {
public boolean check() throws ObjectNotFoundException, SchemaException {
Task task = taskManager.getTask(taskOid(test), result);
IntegrationTestTools.display("Task while waiting for task manager to execute the task", task);
return task.getProgress() >= 1;
}
@Override
public void timeout() {
}
}, 15000, 2000);
// Check task status
Task task = taskManager.getTask(taskOid(test), result);
AssertJUnit.assertNotNull(task);
System.out.println(task.dump());
PrismObject<TaskType> t = repositoryService.getObject(TaskType.class, taskOid(test), result);
System.out.println(t.dump());
// .. it should be running
AssertJUnit.assertEquals(TaskExecutionStatus.RUNNABLE, task.getExecutionStatus());
// .. and last run should not be zero
AssertJUnit.assertNotNull(task.getLastRunStartTimestamp());
AssertJUnit.assertFalse(task.getLastRunStartTimestamp().longValue() == 0);
AssertJUnit.assertNotNull(task.getLastRunFinishTimestamp());
AssertJUnit.assertFalse(task.getLastRunFinishTimestamp().longValue() == 0);
// The progress should be more at least 1 - lazy neptunus... (wait time before task runs is 2 seconds)
AssertJUnit.assertTrue("Progress is none or too small", task.getProgress() >= 1);
// The progress should not be too big (indicates fault in scheduling)
AssertJUnit.assertTrue("Progress is too big (fault in scheduling?)", task.getProgress() <= 7);
// Test for presence of a result. It should be there and it should
// indicate success
OperationResult taskResult = task.getResult();
AssertJUnit.assertNotNull("Task result is null", taskResult);
AssertJUnit.assertTrue("Task did not yield 'success' status", taskResult.isSuccess());
// Suspend the task (in order to keep logs clean), without much waiting
taskManager.suspendTask(task, 100, result);
}
@Test(enabled = true)
public void test010CycleCronLoose() throws Exception {
final String test = "010CycleCronLoose";
final OperationResult result = createResult(test);
addObjectFromFile(taskFilename(test));
waitFor("Waiting for task manager to execute the task", new Checker() {
public boolean check() throws ObjectNotFoundException, SchemaException {
Task task = taskManager.getTask(taskOid(test), result);
IntegrationTestTools.display("Task while waiting for task manager to execute the task", task);
return task.getProgress() >= 2;
}
@Override
public void timeout() {
}
}, 15000, 2000);
// Check task status
Task task = taskManager.getTask(taskOid(test), result);
AssertJUnit.assertNotNull(task);
System.out.println(task.dump());
TaskType t = repositoryService.getObject(TaskType.class, taskOid(test), result).getValue().getValue();
System.out.println(ObjectTypeUtil.dump(t));
AssertJUnit.assertEquals(TaskExecutionStatus.RUNNABLE, task.getExecutionStatus());
// .. and last run should not be zero
AssertJUnit.assertNotNull(task.getLastRunStartTimestamp());
AssertJUnit.assertFalse(task.getLastRunStartTimestamp().longValue() == 0);
AssertJUnit.assertNotNull(task.getLastRunFinishTimestamp());
AssertJUnit.assertFalse(task.getLastRunFinishTimestamp().longValue() == 0);
// The progress should be at least 2 as the task has run at least twice
AssertJUnit.assertTrue("Task has not been executed at least twice", task.getProgress() >= 2);
// Test for presence of a result. It should be there and it should
// indicate success
OperationResult taskResult = task.getResult();
AssertJUnit.assertNotNull("Task result is null", taskResult);
AssertJUnit.assertTrue("Task did not yield 'success' status", taskResult.isSuccess());
// Suspend the task (in order to keep logs clean), without much waiting
taskManager.suspendTask(task, 100, result);
}
@Test(enabled = true)
public void test011MoreHandlersAndSchedules() throws Exception {
final String test = "011MoreHandlersAndSchedules";
final OperationResult result = createResult(test);
// reset 'has run' flag on handlers
l1Handler.resetHasRun();
l2Handler.resetHasRun();
l3Handler.resetHasRun();
addObjectFromFile(taskFilename(test));
waitFor("Waiting for task manager to execute the task", new Checker() {
public boolean check() throws ObjectNotFoundException, SchemaException {
Task task = taskManager.getTask(taskOid(test), result);
IntegrationTestTools.display("Task while waiting for task manager to execute the task", task);
return task.getExecutionStatus() == TaskExecutionStatus.CLOSED;
}
@Override
public void timeout() {
}
}, 20000, 2000);
// Check task status
Task task = taskManager.getTask(taskOid(test), result);
AssertJUnit.assertNotNull(task);
System.out.println(task.dump());
PrismObject<TaskType> o = repositoryService.getObject(TaskType.class, taskOid(test), result);
System.out.println(ObjectTypeUtil.dump(o.getValue().getValue()));
// .. it should be closed
AssertJUnit.assertEquals(TaskExecutionStatus.CLOSED, task.getExecutionStatus());
// .. and last run should not be zero
AssertJUnit.assertNotNull(task.getLastRunStartTimestamp());
AssertJUnit.assertFalse(task.getLastRunStartTimestamp().longValue() == 0);
AssertJUnit.assertNotNull("Last run finish timestamp not set", task.getLastRunFinishTimestamp());
AssertJUnit.assertFalse("Last run finish timestamp is 0", task.getLastRunFinishTimestamp().longValue() == 0);
AssertJUnit.assertEquals("Task reported wrong progress", 8, task.getProgress());
// Test for presence of a result. It should be there and it should
// indicate success
OperationResult taskResult = task.getResult();
AssertJUnit.assertNotNull("Task result is null", taskResult);
AssertJUnit.assertTrue("Task did not yield 'success' status", taskResult.isSuccess());
// Test for no presence of handlers
AssertJUnit.assertNull("Handler is still present", task.getHandlerUri());
AssertJUnit.assertTrue("Other handlers are still present",
task.getOtherHandlersUriStack() == null || task.getOtherHandlersUriStack().getUriStackEntry().isEmpty());
// Test if all three handlers were run
AssertJUnit.assertTrue("L1 handler has not run", l1Handler.hasRun());
AssertJUnit.assertTrue("L2 handler has not run", l2Handler.hasRun());
AssertJUnit.assertTrue("L3 handler has not run", l3Handler.hasRun());
}
/*
* Suspends a running task.
*/
@Test(enabled = true)
public void test012Suspend() throws Exception {
final String test = "012Suspend";
final OperationResult result = createResult(test);
addObjectFromFile(taskFilename(test));
// check if we can read the extension (xsi:type issue)
Task taskTemp = taskManager.getTask(taskOid(test), result);
PrismProperty delay = taskTemp.getExtension(NoOpTaskHandler.DELAY_QNAME);
AssertJUnit.assertEquals("Delay was not read correctly", 2000, delay.getRealValue());
waitFor("Waiting for task manager to execute the task", new Checker() {
public boolean check() throws ObjectNotFoundException, SchemaException {
Task task = taskManager.getTask(taskOid(test), result);
IntegrationTestTools.display("Task while waiting for task manager to execute the task", task);
return task.getProgress() >= 1;
}
@Override
public void timeout() {
}
}, 10000, 2000);
// Check task status (task is running 5 iterations where each takes 2000 ms)
Task task = taskManager.getTask(taskOid(test), result);
AssertJUnit.assertNotNull(task);
System.out.println(task.dump());
AssertJUnit.assertEquals("Task is not running", TaskExecutionStatus.RUNNABLE, task.getExecutionStatus());
// Now suspend the task
boolean stopped = taskManager.suspendTask(task, 0, result);
task.refresh(result);
System.out.println("After suspend and refresh: " + task.dump());
AssertJUnit.assertTrue("Task is not stopped", stopped);
AssertJUnit.assertEquals("Task is not suspended", TaskExecutionStatus.SUSPENDED, task.getExecutionStatus());
AssertJUnit.assertNotNull("Task last start time is null", task.getLastRunStartTimestamp());
AssertJUnit.assertFalse("Task last start time is 0", task.getLastRunStartTimestamp().longValue() == 0);
// The progress should be more than 0
AssertJUnit.assertTrue("Task has not reported any progress", task.getProgress() > 0);
// Thread.sleep(200); // give the scheduler a chance to release the task
// task.refresh(result);
// AssertJUnit.assertEquals("Task is not released", TaskExclusivityStatus.RELEASED, task.getExclusivityStatus());
}
@Test(enabled = true)
public void test013ReleaseAndSuspendLooselyBound() throws Exception {
final String test = "013ReleaseAndSuspendLooselyBound";
final OperationResult result = createResult(test);
addObjectFromFile(taskFilename(test));
Task task = taskManager.getTask(taskOid(test), result);
System.out.println("After setup: " + task.dump());
// check if we can read the extension (xsi:type issue)
PrismProperty delay = task.getExtension(NoOpTaskHandler.DELAY_QNAME);
AssertJUnit.assertEquals("Delay was not read correctly", 1000, delay.getRealValue());
// let us resume (i.e. start the task)
taskManager.resumeTask(task, result);
// task is executing for 1000 ms, so we need to wait slightly longer, in order for the execution to be done
waitFor("Waiting for task manager to execute the task", new Checker() {
public boolean check() throws ObjectNotFoundException, SchemaException {
Task task = taskManager.getTask(taskOid(test), result);
IntegrationTestTools.display("Task while waiting for task manager to execute the task", task);
return task.getProgress() >= 1;
}
@Override
public void timeout() {
}
}, 10000, 2000);
task.refresh(result);
System.out.println("After refresh: " + task.dump());
AssertJUnit.assertEquals(TaskExecutionStatus.RUNNABLE, task.getExecutionStatus());
// AssertJUnit.assertEquals(TaskExclusivityStatus.RELEASED, task.getExclusivityStatus()); // task cycle is 1000 ms, so it should be released now
AssertJUnit.assertNotNull("LastRunStartTimestamp is null", task.getLastRunStartTimestamp());
AssertJUnit.assertFalse("LastRunStartTimestamp is 0", task.getLastRunStartTimestamp().longValue() == 0);
AssertJUnit.assertNotNull(task.getLastRunFinishTimestamp());
AssertJUnit.assertFalse(task.getLastRunFinishTimestamp().longValue() == 0);
AssertJUnit.assertTrue(task.getProgress() > 0);
// now let us suspend it (occurs during wait cycle, so we can put short timeout here)
boolean stopped = taskManager.suspendTask(task, 300, result);
task.refresh(result);
AssertJUnit.assertTrue("Task is not stopped", stopped);
AssertJUnit.assertEquals(TaskExecutionStatus.SUSPENDED, task.getExecutionStatus());
// AssertJUnit.assertEquals(TaskExclusivityStatus.RELEASED, task.getExclusivityStatus());
AssertJUnit.assertNotNull(task.getLastRunStartTimestamp());
AssertJUnit.assertFalse(task.getLastRunStartTimestamp().longValue() == 0);
AssertJUnit.assertNotNull(task.getLastRunFinishTimestamp());
AssertJUnit.assertFalse(task.getLastRunFinishTimestamp().longValue() == 0);
AssertJUnit.assertTrue(task.getProgress() > 0);
// Thread.sleep(200); // give the scheduler a chance to release the task
// task.refresh(result);
// AssertJUnit.assertEquals("Task is not released", TaskExclusivityStatus.RELEASED, task.getExclusivityStatus());
}
@Test(enabled = true)
public void test014SuspendLongRunning() throws Exception {
final String test = "014SuspendLongRunning";
final OperationResult result = createResult(test);
addObjectFromFile(taskFilename(test));
Task task = taskManager.getTask(taskOid(test), result);
System.out.println("After setup: " + task.dump());
waitFor("Waiting for task manager to start the task", new Checker() {
public boolean check() throws ObjectNotFoundException, SchemaException {
Task task = taskManager.getTask(taskOid(test), result);
IntegrationTestTools.display("Task while waiting for task manager to start the task", task);
return task.getLastRunStartTimestamp() != null;
}
@Override
public void timeout() {
}
}, 10000, 2000);
task.refresh(result);
System.out.println("After refresh: " + task.dump());
AssertJUnit.assertEquals(TaskExecutionStatus.RUNNABLE, task.getExecutionStatus());
// AssertJUnit.assertEquals(TaskExclusivityStatus.CLAIMED, task.getExclusivityStatus());
AssertJUnit.assertNotNull(task.getLastRunStartTimestamp());
AssertJUnit.assertFalse(task.getLastRunStartTimestamp().longValue() == 0);
// now let us suspend it, without long waiting
boolean stopped = taskManager.suspendTask(task, 1000, result);
task.refresh(result);
AssertJUnit.assertFalse("Task is stopped (it should be running for now)", stopped);
AssertJUnit.assertEquals("Task is not suspended", TaskExecutionStatus.SUSPENDED, task.getExecutionStatus());
// AssertJUnit.assertEquals("Task should be still claimed, as it is not definitely stopped", TaskExclusivityStatus.CLAIMED, task.getExclusivityStatus());
AssertJUnit.assertNotNull(task.getLastRunStartTimestamp());
AssertJUnit.assertFalse(task.getLastRunStartTimestamp().longValue() == 0);
AssertJUnit.assertNull(task.getLastRunFinishTimestamp());
AssertJUnit.assertTrue("There should be no progress reported", task.getProgress() == 0);
// now let us wait for the finish
stopped = taskManager.suspendTask(task, 0, result);
task.refresh(result);
AssertJUnit.assertTrue("Task is not stopped", stopped);
AssertJUnit.assertEquals("Task is not suspended", TaskExecutionStatus.SUSPENDED, task.getExecutionStatus());
AssertJUnit.assertNotNull(task.getLastRunStartTimestamp());
AssertJUnit.assertFalse(task.getLastRunStartTimestamp().longValue() == 0);
AssertJUnit.assertNotNull("Last run finish time is null", task.getLastRunStartTimestamp());
AssertJUnit.assertFalse("Last run finish time is zero", task.getLastRunStartTimestamp().longValue() == 0);
AssertJUnit.assertTrue("Progress is not reported", task.getProgress() > 0);
// Thread.sleep(200); // give the scheduler a chance to release the task
// task.refresh(result);
// AssertJUnit.assertEquals("Task is not released", TaskExclusivityStatus.RELEASED, task.getExclusivityStatus());
}
@Test(enabled = true)
public void test015DeleteTaskFromRepo() throws Exception {
final String test = "015DeleteTaskFromRepo";
final OperationResult result = createResult(test);
PrismObject<ObjectType> object = addObjectFromFile(taskFilename(test));
String oid = taskOid(test);
// is the task in Quartz?
final JobKey key = TaskQuartzImplUtil.createJobKeyForTaskOid(oid);
AssertJUnit.assertTrue("Job in Quartz does not exist", taskManager.getExecutionManager().getQuartzScheduler().checkExists(key));
// Remove task from repo
repositoryService.deleteObject(TaskType.class, taskOid(test), result);
// We need to wait for a sync interval, so the task scanner has a chance
// to pick up this task
waitFor("Waiting for the job to disappear from Quartz Job Store", new Checker() {
public boolean check() throws ObjectNotFoundException, SchemaException {
try {
return !taskManager.getExecutionManager().getQuartzScheduler().checkExists(key);
} catch (SchedulerException e) {
throw new SystemException(e);
}
}
@Override
public void timeout() {
}
}, 10000, 2000);
}
@Test(enabled = true)
public void test016WaitForSubtasks() throws Exception {
final String test = "016WaitForSubtasks";
final OperationResult result = createResult(test);
PrismObject<ObjectType> object = addObjectFromFile(taskFilename(test));
String oid = taskOid(test);
waitFor("Waiting for task manager to execute the task", new Checker() {
public boolean check() throws ObjectNotFoundException, SchemaException {
Task task = taskManager.getTask(taskOid(test), result);
IntegrationTestTools.display("Task while waiting for task manager to execute the task", task);
return task.getExecutionStatus() == TaskExecutionStatus.CLOSED;
}
@Override
public void timeout() {
}
}, 30000, 3000);
Task task = taskManager.getTask(taskOid(test), result);
AssertJUnit.assertTrue("Progress is too low", task.getProgress() >= 2);
}
@Test(enabled = true)
public void test017TaskResult() throws Exception {
final String test = "017RefreshingResult";
final OperationResult result = createResult(test);
Task task = taskManager.createTaskInstance();
PrismObject<UserType> owner2 = repositoryService.getObject(UserType.class, TASK_OWNER2_OID, result);
task.setOwner(owner2);
AssertJUnit.assertEquals("Task result for new task is not correct", OperationResultStatus.UNKNOWN, task.getResult().getStatus());
taskManager.switchToBackground(task, result);
AssertJUnit.assertEquals("Background task result is not correct (in memory)", OperationResultStatus.IN_PROGRESS, task.getResult().getStatus());
PrismObject<TaskType> task1 = repositoryService.getObject(TaskType.class, task.getOid(), result);
AssertJUnit.assertEquals("Background task result is not correct (in repo)", OperationResultStatusType.IN_PROGRESS, task1.asObjectable().getResult().getStatus());
// now change task's result and check the refresh() method w.r.t. result handling
task.getResult().recordFatalError("");
AssertJUnit.assertEquals(OperationResultStatus.FATAL_ERROR, task.getResult().getStatus());
task.refresh(result);
AssertJUnit.assertEquals("Refresh does not update task's result", OperationResultStatus.IN_PROGRESS, task.getResult().getStatus());
}
@Test(enabled = true)
public void test999CheckingLeftovers() throws Exception {
String test = "999CheckingLeftovers";
OperationResult result = createResult(test);
ArrayList<String> leftovers = new ArrayList<String>();
checkLeftover(leftovers, "005", result);
checkLeftover(leftovers, "006", result);
checkLeftover(leftovers, "008", result);
checkLeftover(leftovers, "009", result);
checkLeftover(leftovers, "010", result);
checkLeftover(leftovers, "011", result);
checkLeftover(leftovers, "012", result);
checkLeftover(leftovers, "013", result);
checkLeftover(leftovers, "014", result);
checkLeftover(leftovers, "015", result);
checkLeftover(leftovers, "016", result);
String message = "Leftover task(s) found:";
for (String leftover : leftovers) {
message += " " + leftover;
}
AssertJUnit.assertTrue(message, leftovers.isEmpty());
}
private void checkLeftover(ArrayList<String> leftovers, String testNumber, OperationResult result) throws Exception {
String oid = taskOid(testNumber);
Task t;
try {
t = taskManager.getTask(oid, result);
} catch (ObjectNotFoundException e) {
// this is OK, test probably did not start
LOGGER.info("Check leftovers: Task " + oid + " does not exist.");
return;
}
LOGGER.info("Check leftovers: Task " + oid + " state: " + t.getExecutionStatus());
if (t.getExecutionStatus() == TaskExecutionStatus.RUNNABLE) {
LOGGER.info("Leftover task: {}", t);
leftovers.add(t.getOid());
}
}
// UTILITY METHODS
// TODO: maybe we should move them to a common utility class
private void assertAttribute(AccountShadowType repoShadow, ResourceType resource, String name, String value) {
assertAttribute(repoShadow, new QName(ResourceTypeUtil.getResourceNamespace(resource), name), value);
}
private void assertAttribute(AccountShadowType repoShadow, QName name, String value) {
boolean found = false;
List<Object> xmlAttributes = repoShadow.getAttributes().getAny();
for (Object element : xmlAttributes) {
if (name.equals(JAXBUtil.getElementQName(element))) {
if (found) {
Assert.fail("Multiple values for " + name + " attribute in shadow attributes");
} else {
AssertJUnit.assertEquals(value, ((Element) element).getTextContent());
found = true;
}
}
}
}
protected void assertAttribute(SearchResultEntry response, String name, String value) {
AssertJUnit.assertNotNull(response.getAttribute(name.toLowerCase()));
AssertJUnit.assertEquals(1, response.getAttribute(name.toLowerCase()).size());
Attribute attribute = response.getAttribute(name.toLowerCase()).get(0);
AssertJUnit.assertEquals(value, attribute.iterator().next().getValue().toString());
}
private <T extends ObjectType> PrismObject<T> unmarshallJaxbFromFile(String filePath, Class<T> clazz) throws FileNotFoundException, JAXBException, SchemaException {
File file = new File(filePath);
return PrismTestUtil.parseObject(file);
}
private PrismObject<ObjectType> addObjectFromFile(String filePath) throws Exception {
return addObjectFromFile(filePath, false);
}
private PrismObject<ObjectType> addObjectFromFile(String filePath, boolean deleteIfExists) throws Exception {
PrismObject<ObjectType> object = unmarshallJaxbFromFile(filePath, ObjectType.class);
System.out.println("obj: " + object.getName());
OperationResult result = new OperationResult(TestQuartzTaskManagerContract.class.getName() + ".addObjectFromFile");
try {
add(object, result);
} catch(ObjectAlreadyExistsException e) {
delete(object, result);
add(object, result);
}
logger.trace("Object from " + filePath + " added to repository.");
return object;
}
private void add(PrismObject<ObjectType> object, OperationResult result)
throws ObjectAlreadyExistsException, SchemaException {
if (object.canRepresent(TaskType.class)) {
taskManager.addTask((PrismObject)object, result);
} else {
repositoryService.addObject(object, result);
}
}
private void delete(PrismObject<ObjectType> object, OperationResult result) throws ObjectNotFoundException, SchemaException {
if (object.canRepresent(TaskType.class)) {
taskManager.deleteTask(object.getOid(), result);
} else {
repositoryService.deleteObject(ObjectType.class, object.getOid(), result); // correct?
}
}
// private void display(SearchResultEntry response) {
// // TODO Auto-generated method stub
// System.out.println(response.toLDIFString());
}
|
package org.eclipse.che.selenium.miscellaneous;
import static java.lang.String.valueOf;
import static org.testng.Assert.fail;
import com.google.inject.Inject;
import java.net.URL;
import java.nio.file.Paths;
import org.eclipse.che.commons.lang.NameGenerator;
import org.eclipse.che.selenium.core.client.TestProjectServiceClient;
import org.eclipse.che.selenium.core.constant.TestBuildConstants;
import org.eclipse.che.selenium.core.constant.TestTimeoutsConstants;
import org.eclipse.che.selenium.core.project.ProjectTemplates;
import org.eclipse.che.selenium.core.utils.WaitUtils;
import org.eclipse.che.selenium.core.workspace.TestWorkspace;
import org.eclipse.che.selenium.pageobject.Consoles;
import org.eclipse.che.selenium.pageobject.Ide;
import org.eclipse.che.selenium.pageobject.Loader;
import org.eclipse.che.selenium.pageobject.ProjectExplorer;
import org.eclipse.che.selenium.pageobject.machineperspective.MachineTerminal;
import org.openqa.selenium.Keys;
import org.openqa.selenium.TimeoutException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
/**
* @author Aleksandr Shmaraev
* @author Alexander Andrienko
*/
public class WorkingWithTerminalTest {
private static final String PROJECT_NAME = NameGenerator.generate("SpringWebApp", 4);
private static final Logger LOG = LoggerFactory.getLogger(WorkingWithTerminalTest.class);
private static final String[] CHECK_MC_OPENING = {
"Left", "File", "Command", "Options", "Right", "Name", "bin", "dev", "etc", "home",
"lib", "lib64", "bin", "1Help", "2Menu", "3View", "4Edit", "5Copy", "6RenMov", "7Mkdir",
"8Delete", "9PullDn", "10Quit"
};
private static final String MESS_IN_CONSOLE =
"Installing /projects/" + PROJECT_NAME + "/target/qa-spring-sample-1.0-SNAPSHOT.war";
private static final String WAR_NAME = "qa-spring-sample-1.0-SNAPSHOT.war";
private static final String BASH_SCRIPT =
"for i in `seq 1 10`; do sleep 3; echo \"test=$i\"; done";
private static final String MC_HELP_DIALOG =
"This is the main help screen for GNU Midnight Commander.";
private static final String MC_USER_MENU_DIALOG = "User menu";
private static final String[] VIEW_BIN_FOLDER = {"bash", "chmod", "date"};
@Inject private TestWorkspace workspace;
@Inject private Ide ide;
@Inject private ProjectExplorer projectExplorer;
@Inject private Loader loader;
@Inject private MachineTerminal terminal;
@Inject private Consoles consoles;
@Inject private TestProjectServiceClient testProjectServiceClient;
@BeforeClass
public void setUp() throws Exception {
URL resource = getClass().getResource("/projects/guess-project");
testProjectServiceClient.importProject(
workspace.getId(),
Paths.get(resource.toURI()),
PROJECT_NAME,
ProjectTemplates.MAVEN_SPRING);
ide.open(workspace);
}
@BeforeMethod
private void prepareNewTerminal() {
try {
projectExplorer.waitProjectExplorer();
loader.waitOnClosed();
projectExplorer.waitItem(PROJECT_NAME);
if (terminal.terminalIsPresent()) {
consoles.closeTerminalIntoConsoles();
terminal.waitTerminalIsNotPresent(1);
}
consoles.clickOnPlusMenuButton();
consoles.clickOnTerminalItemInContextMenu();
terminal.selectTerminalTab();
terminal.waitTerminalConsole();
terminal.waitTerminalIsNotEmpty();
} catch (Exception e) {
LOG.error(e.getLocalizedMessage(), e);
}
}
@Test(priority = 0)
public void shouldLaunchCommandWithBigOutput() {
// build the web java application
projectExplorer.waitProjectExplorer();
loader.waitOnClosed();
projectExplorer.waitItem(PROJECT_NAME);
terminal.waitTerminalConsole(1);
terminal.typeIntoTerminal("cd /projects/" + PROJECT_NAME + Keys.ENTER);
terminal.waitExpectedTextIntoTerminal("/projects/" + PROJECT_NAME);
terminal.typeIntoTerminal("mvn clean install" + Keys.ENTER);
terminal.waitExpectedTextIntoTerminal(
TestBuildConstants.BUILD_SUCCESS, TestTimeoutsConstants.EXPECTED_MESS_IN_CONSOLE_SEC);
terminal.waitExpectedTextIntoTerminal(MESS_IN_CONSOLE);
// check the target folder
projectExplorer.openItemByPath(PROJECT_NAME);
projectExplorer.openItemByPath(PROJECT_NAME + "/target");
projectExplorer.waitItem(PROJECT_NAME + "/target/" + WAR_NAME);
}
@Test(priority = 1)
public void shouldAppearMCDialogs() {
terminal.typeIntoTerminal("cd ~ && touch -f testfile.txt" + Keys.ENTER);
openMC("~");
// check F5
terminal.typeIntoTerminal("" + Keys.END + Keys.F5);
terminal.waitExpectedTextIntoTerminal("Copy file \"testfile.txt\" with source mask");
terminal.typeIntoTerminal("" + Keys.ESCAPE + Keys.ESCAPE);
// check F6
terminal.typeIntoTerminal(Keys.F6.toString());
terminal.waitExpectedTextIntoTerminal("Move file \"testfile.txt\" with source mask");
terminal.typeIntoTerminal("" + Keys.ESCAPE + Keys.ESCAPE);
// check F7
terminal.typeIntoTerminal(Keys.F7.toString());
terminal.waitExpectedTextIntoTerminal("Enter directory name:");
terminal.typeIntoTerminal("" + Keys.ESCAPE + Keys.ESCAPE);
// check F8
terminal.typeIntoTerminal(Keys.F8.toString());
terminal.waitExpectedTextIntoTerminal("Delete file");
terminal.waitExpectedTextIntoTerminal("\"testfile.txt\"?");
terminal.typeIntoTerminal("" + Keys.ESCAPE + Keys.ESCAPE);
// check F9 - Select menu in MC
terminal.typeIntoTerminal("" + Keys.F9 + Keys.ENTER);
terminal.waitExpectedTextIntoTerminal("File listing");
terminal.typeIntoTerminal("" + Keys.ESCAPE + Keys.ESCAPE);
}
@Test(priority = 2)
public void shouldScrollIntoTerminal() throws InterruptedException {
openMC("/");
try {
// check scrolling of the terminal
terminal.movePageDownListTerminal("opt");
} catch (TimeoutException ex) {
// remove try-catch block after issue has been resolved
fail("Known issue https://github.com/eclipse/che-lib/issues/57", ex);
}
terminal.moveDownListTerminal(".dockerenv");
terminal.waitExpectedTextIntoTerminal(".dockerenv");
terminal.movePageUpListTerminal("projects");
terminal.moveUpListTerminal("bin");
terminal.waitExpectedTextIntoTerminal("bin");
}
@Test(priority = 3)
public void shouldResizeTerminal() {
openMC("/");
try {
// check the root content of the midnight commander
for (String partOfContent : CHECK_MC_OPENING) {
terminal.waitExpectedTextIntoTerminal(partOfContent);
}
} catch (TimeoutException ex) {
// remove try-catch block after issue has been resolved
fail("Known issue https://github.com/eclipse/che-lib/issues/57", ex);
}
terminal.waitExpectedTextNotPresentTerminal(".dockerenv");
consoles.clickOnMaximizePanelIcon();
loader.waitOnClosed();
// check resize of the terminal
for (String partOfContent : CHECK_MC_OPENING) {
terminal.waitExpectedTextIntoTerminal(partOfContent);
}
terminal.waitExpectedTextIntoTerminal(".dockerenv");
consoles.clickOnMaximizePanelIcon();
loader.waitOnClosed();
for (String partOfContent : CHECK_MC_OPENING) {
terminal.waitExpectedTextIntoTerminal(partOfContent);
}
terminal.waitExpectedTextNotPresentTerminal(".dockerenv");
}
@Test(priority = 4)
public void shouldNavigateToMC() {
openMC("/");
// navigate to midnight commander tree
consoles.selectProcessByTabName("Terminal");
terminal.typeIntoTerminal(Keys.ARROW_DOWN.toString());
terminal.typeIntoTerminal(Keys.ARROW_DOWN.toString());
terminal.typeIntoTerminal(Keys.ARROW_DOWN.toString());
terminal.typeIntoTerminal(Keys.ARROW_DOWN.toString());
terminal.typeIntoTerminal(Keys.ENTER.toString());
terminal.typeIntoTerminal(Keys.ARROW_DOWN.toString());
terminal.typeIntoTerminal(Keys.ENTER.toString());
try {
// check the home content of the midnight commander
for (String partOfContent : CHECK_MC_OPENING) {
terminal.waitExpectedTextIntoTerminal(partOfContent);
}
} catch (TimeoutException ex) {
// remove try-catch block after issue has been resolved
fail("Known issue https://github.com/eclipse/che-lib/issues/57", ex);
}
terminal.typeIntoTerminal(Keys.F10.toString());
}
@Test(priority = 5)
public void shouldCreateFileTest() {
terminal.typeIntoTerminal("cd ~" + Keys.ENTER);
terminal.typeIntoTerminal("ls" + Keys.ENTER);
terminal.waitTerminalIsNotEmpty();
terminal.waitExpectedTextIntoTerminal("che");
terminal.typeIntoTerminal("touch testfile0.txt" + Keys.ENTER);
terminal.typeIntoTerminal("ls" + Keys.ENTER);
terminal.waitExpectedTextIntoTerminal("che");
terminal.waitExpectedTextIntoTerminal("che");
terminal.waitExpectedTextIntoTerminal("testfile0.txt");
terminal.waitExpectedTextIntoTerminal("tomcat8");
}
@Test(priority = 6)
public void shouldCancelProcessByCtrlC() throws InterruptedException {
terminal.typeIntoTerminal("cd /" + Keys.ENTER);
// launch bash script
terminal.typeIntoTerminal(BASH_SCRIPT + Keys.ENTER);
terminal.waitExpectedTextIntoTerminal("test=1");
// cancel script
terminal.typeIntoTerminal(Keys.CONTROL + "c");
// wait 3 sec. If process was really stopped we should not get text "test=2"
WaitUtils.sleepQuietly(3);
try {
terminal.waitExpectedTextNotPresentTerminal("test=2");
} catch (TimeoutException ex) {
// remove try-catch block after issue has been resolved
fail("Known issue https://github.com/eclipse/che/issues/8390");
}
}
@Test(priority = 7)
public void shouldBeClear() {
terminal.typeIntoTerminal("cd / && ls -l" + Keys.ENTER);
// clear terminal
terminal.typeIntoTerminal("clear" + Keys.ENTER);
terminal.waitExpectedTextNotPresentTerminal("clear");
terminal.waitTerminalIsNotEmpty();
terminal.waitExpectedTextIntoTerminal("user@");
}
@Test(priority = 8)
public void shouldBeReset() {
terminal.typeIntoTerminal("cd / && ls -l" + Keys.ENTER);
// clear terminal
terminal.typeIntoTerminal("reset" + Keys.ENTER.toString());
terminal.waitExpectedTextNotPresentTerminal("reset");
terminal.waitTerminalIsNotEmpty();
terminal.waitExpectedTextIntoTerminal("user@");
}
@Test(priority = 9)
public void shouldTurnToNormalModeFromAlternativeScreenModeAndOtherwise() {
// open MC - terminal will switch off from normal mode to alternative screen with text user
// interface (pseudo user graphics).
openMC("/");
// turn back to "normal" mode
terminal.typeIntoTerminal(Keys.CONTROL + "o");
for (String partOfContent : CHECK_MC_OPENING) {
terminal.waitExpectedTextNotPresentTerminal(partOfContent);
}
terminal.typeIntoTerminal(Keys.CONTROL + "o" + Keys.ENTER);
for (String partOfContent : CHECK_MC_OPENING) {
terminal.waitExpectedTextIntoTerminal(partOfContent);
}
}
@Test(priority = 10)
public void shouldOpenMCHelpDialogAndUserMenuDialog() {
openMC("/");
// check "F1"
terminal.typeIntoTerminal(Keys.F1.toString());
terminal.waitTerminalIsNotEmpty();
terminal.waitExpectedTextIntoTerminal(MC_HELP_DIALOG);
terminal.typeIntoTerminal(Keys.F10.toString());
terminal.waitExpectedTextNotPresentTerminal(MC_HELP_DIALOG);
// check "F2" key
terminal.typeIntoTerminal(Keys.F2.toString());
terminal.waitExpectedTextIntoTerminal(MC_USER_MENU_DIALOG);
terminal.typeIntoTerminal(Keys.F10.toString());
terminal.waitExpectedTextNotPresentTerminal(MC_USER_MENU_DIALOG);
}
@Test(priority = 11)
public void shouldViewFolderIntoMC() {
terminal.waitTerminalTab();
consoles.clickOnMaximizePanelIcon();
openMC("/");
// select bin folder and view this folder by "F3" key
terminal.waitExpectedTextIntoTerminal("bin");
terminal.typeIntoTerminal(Keys.HOME.toString() + Keys.F3.toString());
for (String partOfContent : VIEW_BIN_FOLDER) {
terminal.waitExpectedTextIntoTerminal(partOfContent);
}
terminal.typeIntoTerminal("cd ~" + Keys.ENTER);
terminal.waitExpectedTextIntoTerminal(".cache");
consoles.clickOnMaximizePanelIcon();
}
@Test(priority = 12)
public void closeTerminalByExitCommand() {
terminal.waitTerminalConsole();
terminal.typeIntoTerminal("exit" + Keys.ENTER);
terminal.waitTerminalIsNotPresent(1);
}
@Test(priority = 13)
public void shouldEditFileIntoMCEdit() {
openMC("/projects/" + PROJECT_NAME);
// check End, Home, F4, Delete keys
terminal.typeIntoTerminal("" + Keys.END + Keys.ENTER + Keys.END + Keys.ARROW_UP + Keys.F4);
// select editor
terminal.typeIntoTerminal(valueOf(1) + Keys.ENTER);
terminal.waitExpectedTextIntoTerminal("README.md");
terminal.typeIntoTerminal("<!-some comment->");
terminal.typeIntoTerminal(
"" + Keys.HOME + Keys.ARROW_RIGHT + Keys.ARROW_RIGHT + Keys.ARROW_RIGHT + Keys.DELETE);
terminal.waitExpectedTextIntoTerminal("<!-ome comment->");
}
@Test(priority = 14)
public void checkDeleteAction() throws InterruptedException {
// if the bug exists -> the dialog appears and the terminal lose focus
terminal.typeIntoTerminal(Keys.DELETE.toString());
terminal.typeIntoTerminal("pwd");
}
private void openMC(String currentLocation) {
// launch mc from root directory
loader.waitOnClosed();
consoles.selectProcessByTabName("Terminal");
terminal.typeIntoTerminal("cd " + currentLocation);
terminal.typeIntoTerminal(Keys.ENTER.toString());
terminal.typeIntoTerminal("mc");
terminal.typeIntoTerminal(Keys.ENTER.toString());
terminal.waitTerminalIsNotEmpty();
}
}
|
package magpie.models.regression;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import magpie.data.Dataset;
import magpie.user.CommandHandler;
import magpie.utility.MathUtils;
import org.apache.commons.math3.stat.StatUtils;
import org.apache.commons.math3.stat.correlation.PearsonsCorrelation;
import org.apache.commons.math3.stat.regression.SimpleRegression;
public class LASSORegression extends BaseRegression {
/** Maximum number of features allowed in model (-1 is unlimited) */
protected int MaxNumberTerms = -1;
/** Terms used in the model */
protected List<Integer> Terms = new LinkedList<>();
/** Names of terms used in the model */
protected List<String> TermNames = new LinkedList<>();
/** Coefficients for linear model */
protected List<Double> Coefficients = new LinkedList<>();
/** Intercept of the linear model */
protected double Intercept;
@Override
@SuppressWarnings("CloneDeclaresCloneNotSupported")
public BaseRegression clone() {
LASSORegression x = (LASSORegression) super.clone();
x.Coefficients = new LinkedList<>(Coefficients);
x.Terms = new LinkedList<>(Terms);
x.TermNames = new LinkedList<>(TermNames);
return x;
}
@Override
public void setOptions(List OptionsObj) throws Exception {
String[] Options = CommandHandler.convertCommandToString(OptionsObj);
try {
int count = 0;
while (count < Options.length) {
switch (Options[count].toLowerCase()) {
case "-maxterms":
count++;
int maxterms = Integer.parseInt(Options[count]);
setMaxNumberTerms(maxterms);
break;
default:
throw new Exception();
}
count++;
}
} catch (Exception e) {
throw new Exception(printUsage());
}
}
@Override
public String printUsage() {
return "Usage: -maxterms <maximum # terms>";
}
public void setMaxNumberTerms(int MaxNumberTerms) {
this.MaxNumberTerms = MaxNumberTerms;
}
@Override
protected void train_protected(Dataset TrainData) {
/* Reset the coefficient vector */
Coefficients.clear(); TermNames.clear(); Terms.clear();
/* Gather and normalize data (NOT CURRENTLY USED)
double [][] features = MathUtils.transpose(TrainData.getAttributeArray());
FeatureMean = new double[features.length];
FeatureDev = new double[features.length];
for (int i=0; i<features.length; i++) {
FeatureMean[i] = StatUtils.mean(features[i]);
double temp = StatUtils.variance(features[i], FeatureMean[i]);
FeatureDev[i] = temp == 0 || temp == Double.NaN ?
1.0 : Math.sqrt(temp);
for (int j=0; j<features[i].length; j++)
features[i][j] = (features[i][j] - FeatureMean[i]) / FeatureDev[i];
}
*/
double [][] observations = TrainData.getAttributeArray();
double [][] features = MathUtils.transpose(observations);
/* Retrieve the class */
double[] targetClass = TrainData.getMeasuredClassArray();
/* Do a LASSO fit. Algorithm:
* 1) Select the parameter that correlates best with class variable
* 2) Add that parameter to the model
* 3) Determine the coefficient and intercept that minimizes error (L2 norm)
* 4) Fit the parameter that correlates best with residual
* 5) Determine parameter that has the best correlation with residual and
* is not already in the model
* 6) Find the coefficient that minimizes error with residual
* 7) Repeat from 4 until maximum number of terms is reached or error
* passes below a threshold
*/
// 1-3) Fit first term and intercept
boolean[] includable = new boolean[features.length];
Arrays.fill(includable, true);
int toAdd = findMaxCorrelation(features, targetClass, includable);
includable[toAdd] = false; // Remove from selection pool
double[] results = linearFit(features[toAdd], targetClass, true);
Intercept = results[0];
Coefficients.add(results[1]);
Terms.add(toAdd);
TermNames.add(TrainData.getAttributeName(toAdd));
// Find the residuals
double[] residual = getResidual(observations, targetClass);
double MAE = getMAE(residual);
int termCount = 1;
// 4-7) Add new terms to model
while (termCount != MaxNumberTerms) {
toAdd = findMaxCorrelation(features, residual, includable);
if (toAdd == -1) {
break;
}
results = linearFit(features[toAdd], residual, true);
Coefficients.add(results[1]);
Terms.add(toAdd);
TermNames.add(TrainData.getAttributeName(toAdd));
Intercept += results[0];
includable[toAdd] = false;
residual = getResidual(observations, targetClass);
MAE = getMAE(residual);
termCount++;
}
}
@Override
public int getNFittingParameters() {
return Coefficients.size() + 1;
}
@Override
public void run_protected(Dataset TrainData) {
double[] predictedClass = runModel(TrainData.getAttributeArray());
TrainData.setPredictedClasses(predictedClass);
}
/**
* Finds the feature with the maximum correlation out of all possible candidates
* @param features Features for each measurement
* @param objective Objective function for each measurement
* @param isSearchable List of which features are searchable
* @return Index of feature that is searchable and has the highest correlation coefficient.
* Return -1 if no features are left to add.
*/
protected int findMaxCorrelation(double[][] features, double[] objective,
boolean[] isSearchable) {
int best = -1;
double corr_best = -15, corr;
for (int i=0; i<features.length; i++){
if (!isSearchable[i]) continue;
corr = new PearsonsCorrelation().correlation(features[i], objective);
if (Double.isNaN(corr)) corr = 0.0;
else corr = Math.abs(corr);
if (corr > corr_best) {
corr_best = corr; best = i;
}
}
return best;
}
/**
* Find the best linear fit
* @param x Independent variable
* @param y Dependent variable
* @param intercept Whether to fit an intercept
* @return Optimal fit: [0] is the intercept, [1] is the slope
*/
static public double[] linearFit(double[] x, double[] y, boolean intercept) {
SimpleRegression Fit = new SimpleRegression(intercept);
for (int i=0; i<x.length; i++)
Fit.addData(x[i], y[i]);
double[] output = new double[2];
if (intercept) output[0] = Fit.getIntercept();
output[1] = Fit.getSlope();
return output;
}
/**
* Determines the residuals from a model
* @param x Observation matrix
* @param y Data to compare against model
* @return <code>y - runModel(x)</code>
*/
public double[] getResidual(double[][] x, double[] y) {
double[] yhat = runModel(x);
double[] residuals = new double[y.length];
for (int i=0; i<y.length; i++)
residuals[i] = y[i] - yhat[i];
return residuals;
}
/**
* Runs the model contained within object
* @param x Observation matrix
* @return
*/
public double[] runModel(double[][] x){
double[] y = new double[x.length];
Arrays.fill(y, Intercept);
for (int i=0; i<x.length; i++) {
for (int j=0; j<Coefficients.size(); j++)
y[i] += Coefficients.get(j) * x[i][Terms.get(j)];
}
return y;
}
/**
* Get Mean Absolute Error (MAE) given residuals
* @param residuals Error between model and reality for each entry
* @return Mean absolute error
*/
static public double getMAE(double[] residuals) {
double[] copy = new double[residuals.length];
for (int i=0; i<residuals.length; i++) copy[i] = Math.abs(residuals[i]);
return StatUtils.mean(copy);
}
@Override
protected String printModel_protected() {
String output = "Class = " + String.format("%.5e", Intercept);
for (int i=0; i < Terms.size(); i++)
output += " + " + String.format("%.5e * %s", Coefficients.get(i), TermNames.get(i));
return output + "\n";
}
@Override
public List<String> printModelDescriptionDetails(boolean htmlFormat) {
List<String> output = super.printModelDescriptionDetails(htmlFormat);
output.add("Maximum number of terms: "
+ (MaxNumberTerms == -1 ? "Unlimited" : MaxNumberTerms));
return output;
}
}
|
package org.collectionspace.services.client.test;
import java.util.List;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.collectionspace.services.client.VocabularyClient;
import org.collectionspace.services.vocabulary.VocabulariesCommon;
import org.collectionspace.services.vocabulary.VocabulariesCommonList;
import org.collectionspace.services.vocabulary.VocabularyitemsCommon;
import org.collectionspace.services.vocabulary.VocabularyitemsCommonList;
import org.jboss.resteasy.client.ClientResponse;
import org.jboss.resteasy.plugins.providers.multipart.MultipartInput;
import org.jboss.resteasy.plugins.providers.multipart.MultipartOutput;
import org.jboss.resteasy.plugins.providers.multipart.OutputPart;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.annotations.Test;
public class VocabularyServiceTest extends AbstractServiceTest {
private final Logger logger =
LoggerFactory.getLogger(VocabularyServiceTest.class);
// Instance variables specific to this test.
private VocabularyClient client = new VocabularyClient();
final String SERVICE_PATH_COMPONENT = "vocabularies";
final String ITEM_SERVICE_PATH_COMPONENT = "items";
private String knownResourceId = null;
private String knownItemResourceId = null;
// CRUD tests : CREATE tests
// Success outcomes
@Override
@Test
public void create() {
// Perform setup, such as initializing the type of service request
// (e.g. CREATE, DELETE), its valid and expected status codes, and
// its associated HTTP method name (e.g. POST, DELETE).
setupCreate();
// Submit the request to the service and store the response.
String identifier = createIdentifier();
MultipartOutput multipart = createVocabularyInstance(identifier);
ClientResponse<Response> res = client.create(multipart);
int statusCode = res.getStatus();
// Check the status code of the response: does it match
// the expected response(s)?
// Specifically:
// Does it fall within the set of valid status codes?
// Does it exactly match the expected status code?
verbose("create: status = " + statusCode);
Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
// Store the ID returned from this create operation
// for additional tests below.
knownResourceId = extractId(res);
verbose("create: knownResourceId=" + knownResourceId);
}
@Test(dependsOnMethods = {"create"})
public void createItem() {
setupCreate("Create Item");
knownItemResourceId = createItemInVocab(knownResourceId);
verbose("createItem: knownItemResourceId=" + knownItemResourceId);
}
private String createItemInVocab(String vcsid) {
// Submit the request to the service and store the response.
String identifier = createIdentifier();
verbose("createItem:...");
MultipartOutput multipart = createVocabularyItemInstance(vcsid, identifier);
ClientResponse<Response> res = client.createItem(vcsid, multipart);
int statusCode = res.getStatus();
// Check the status code of the response: does it match
// the expected response(s)?
// Specifically:
// Does it fall within the set of valid status codes?
// Does it exactly match the expected status code?
verbose("createItem: status = " + statusCode);
Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
return extractId(res);
}
@Override
@Test(dependsOnMethods = {"create", "createItem"})
public void createList() {
for (int i = 0; i < 3; i++) {
create();
// Add 3 items to each vocab
for (int j = 0; j < 3; j++) {
createItem();
}
}
}
// Failure outcomes
// Placeholders until the three tests below can be uncommented.
// See Issue CSPACE-401.
public void createWithEmptyEntityBody() {
}
public void createWithMalformedXml() {
}
public void createWithWrongXmlSchema() {
}
/*
@Override
@Test(dependsOnMethods = {"create", "testSubmitRequest"})
public void createWithEmptyEntityBody() {
// Perform setup.
setupCreateWithEmptyEntityBody();
// Submit the request to the service and store the response.
String method = REQUEST_TYPE.httpMethodName();
String url = getServiceRootURL();
String mediaType = MediaType.APPLICATION_XML;
final String entity = "";
int statusCode = submitRequest(method, url, mediaType, entity);
// Check the status code of the response: does it match
// the expected response(s)?
verbose("createWithEmptyEntityBody url=" + url + " status=" + statusCode);
Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
}
@Override
@Test(dependsOnMethods = {"create", "testSubmitRequest"})
public void createWithMalformedXml() {
// Perform setup.
setupCreateWithMalformedXml();
// Submit the request to the service and store the response.
String method = REQUEST_TYPE.httpMethodName();
String url = getServiceRootURL();
String mediaType = MediaType.APPLICATION_XML;
final String entity = MALFORMED_XML_DATA; // Constant from base class.
int statusCode = submitRequest(method, url, mediaType, entity);
// Check the status code of the response: does it match
// the expected response(s)?
verbose("createWithMalformedXml url=" + url + " status=" + statusCode);
Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
}
@Override
@Test(dependsOnMethods = {"create", "testSubmitRequest"})
public void createWithWrongXmlSchema() {
// Perform setup.
setupCreateWithWrongXmlSchema();
// Submit the request to the service and store the response.
String method = REQUEST_TYPE.httpMethodName();
String url = getServiceRootURL();
String mediaType = MediaType.APPLICATION_XML;
final String entity = WRONG_XML_SCHEMA_DATA;
int statusCode = submitRequest(method, url, mediaType, entity);
// Check the status code of the response: does it match
// the expected response(s)?
verbose("createWithWrongSchema url=" + url + " status=" + statusCode);
Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
}
*/
// CRUD tests : READ tests
// Success outcomes
@Override
@Test(dependsOnMethods = {"create"})
public void read() {
// Perform setup.
setupRead();
// Submit the request to the service and store the response.
ClientResponse<MultipartInput> res = client.read(knownResourceId);
int statusCode = res.getStatus();
// Check the status code of the response: does it match
// the expected response(s)?
verbose("read: status = " + statusCode);
Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
//FIXME: remove the following try catch once Aron fixes signatures
try {
MultipartInput input = (MultipartInput) res.getEntity();
VocabulariesCommon vocabulary = (VocabulariesCommon) extractPart(input,
client.getCommonPartName(), VocabulariesCommon.class);
Assert.assertNotNull(vocabulary);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Test(dependsOnMethods = {"createItem", "read"})
public void readItem() {
// Perform setup.
setupRead("Read Item");
// Submit the request to the service and store the response.
ClientResponse<MultipartInput> res = client.readItem(knownResourceId, knownItemResourceId);
int statusCode = res.getStatus();
// Check the status code of the response: does it match
// the expected response(s)?
verbose("readItem: status = " + statusCode);
Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
//FIXME: remove the following try catch once Aron fixes signatures
try {
MultipartInput input = (MultipartInput) res.getEntity();
VocabularyitemsCommon vocabularyItem = (VocabularyitemsCommon) extractPart(input,
client.getItemCommonPartName(), VocabularyitemsCommon.class);
Assert.assertNotNull(vocabularyItem);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
// Failure outcomes
@Override
@Test(dependsOnMethods = {"read"})
public void readNonExistent() {
// Perform setup.
setupReadNonExistent();
// Submit the request to the service and store the response.
ClientResponse<MultipartInput> res = client.read(NON_EXISTENT_ID);
int statusCode = res.getStatus();
// Check the status code of the response: does it match
// the expected response(s)?
verbose("readNonExistent: status = " + res.getStatus());
Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
}
@Test(dependsOnMethods = {"readItem", "readNonExistent"})
public void readItemNonExistent() {
// Perform setup.
setupReadNonExistent("Read Non-Existent Item");
// Submit the request to the service and store the response.
ClientResponse<MultipartInput> res = client.readItem(knownResourceId, NON_EXISTENT_ID);
int statusCode = res.getStatus();
// Check the status code of the response: does it match
// the expected response(s)?
verbose("readItemNonExistent: status = " + res.getStatus());
Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
}
// CRUD tests : READ_LIST tests
// Success outcomes
@Override
@Test(dependsOnMethods = {"read"})
public void readList() {
// Perform setup.
setupReadList();
// Submit the request to the service and store the response.
ClientResponse<VocabulariesCommonList> res = client.readList();
VocabulariesCommonList list = res.getEntity();
int statusCode = res.getStatus();
// Check the status code of the response: does it match
// the expected response(s)?
verbose("readList: status = " + res.getStatus());
Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
// Optionally output additional data about list members for debugging.
boolean iterateThroughList = false;
if (iterateThroughList && logger.isDebugEnabled()) {
List<VocabulariesCommonList.VocabularyListItem> items =
list.getVocabularyListItem();
int i = 0;
for (VocabulariesCommonList.VocabularyListItem item : items) {
String csid = item.getCsid();
verbose("readList: list-item[" + i + "] csid=" +
csid);
verbose("readList: list-item[" + i + "] displayName=" +
item.getDisplayName());
verbose("readList: list-item[" + i + "] URI=" +
item.getUri());
readItemList(csid);
i++;
}
}
}
@Test(dependsOnMethods = {"readItem"})
public void readItemList() {
readItemList(knownResourceId);
}
private void readItemList(String vcsid) {
// Perform setup.
setupReadList("Read Item List");
// Submit the request to the service and store the response.
ClientResponse<VocabularyitemsCommonList> res =
client.readItemList(vcsid);
VocabularyitemsCommonList list = res.getEntity();
int statusCode = res.getStatus();
// Check the status code of the response: does it match
// the expected response(s)?
verbose(" readItemList: status = " + res.getStatus());
Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
// Optionally output additional data about list members for debugging.
boolean iterateThroughList = false;
if (iterateThroughList && logger.isDebugEnabled()) {
List<VocabularyitemsCommonList.VocabularyitemListItem> items =
list.getVocabularyitemListItem();
int i = 0;
for (VocabularyitemsCommonList.VocabularyitemListItem item : items) {
verbose(" readItemList: list-item[" + i + "] csid=" +
item.getCsid());
verbose(" readItemList: list-item[" + i + "] displayName=" +
item.getDisplayName());
verbose(" readItemList: list-item[" + i + "] URI=" +
item.getUri());
i++;
}
}
}
// Failure outcomes
// None at present.
// CRUD tests : UPDATE tests
// Success outcomes
@Override
@Test(dependsOnMethods = {"read"})
public void update() {
// Perform setup.
setupUpdate();
try { //ideally, just remove try-catch and let the exception bubble up
// Retrieve an existing resource that we can update.
ClientResponse<MultipartInput> res =
client.read(knownResourceId);
verbose("update: read status = " + res.getStatus());
Assert.assertEquals(res.getStatus(), EXPECTED_STATUS_CODE);
verbose("got Vocabulary to update with ID: " + knownResourceId);
MultipartInput input = (MultipartInput) res.getEntity();
VocabulariesCommon vocabulary = (VocabulariesCommon) extractPart(input,
client.getCommonPartName(), VocabulariesCommon.class);
Assert.assertNotNull(vocabulary);
// Update the content of this resource.
vocabulary.setDisplayName("updated-" + vocabulary.getDisplayName());
vocabulary.setVocabType("updated-" + vocabulary.getVocabType());
verbose("to be updated Vocabulary", vocabulary, VocabulariesCommon.class);
// Submit the request to the service and store the response.
MultipartOutput output = new MultipartOutput();
OutputPart commonPart = output.addPart(vocabulary, MediaType.APPLICATION_XML_TYPE);
commonPart.getHeaders().add("label", client.getCommonPartName());
res = client.update(knownResourceId, output);
int statusCode = res.getStatus();
// Check the status code of the response: does it match the expected response(s)?
verbose("update: status = " + res.getStatus());
Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
input = (MultipartInput) res.getEntity();
VocabulariesCommon updatedVocabulary =
(VocabulariesCommon) extractPart(input,
client.getCommonPartName(), VocabulariesCommon.class);
Assert.assertNotNull(updatedVocabulary);
Assert.assertEquals(updatedVocabulary.getDisplayName(),
vocabulary.getDisplayName(),
"Data in updated object did not match submitted data.");
} catch (Exception e) {
e.printStackTrace();
}
}
@Test(dependsOnMethods = {"readItem", "update"})
public void updateItem() {
// Perform setup.
setupUpdate("Update Item");
try { //ideally, just remove try-catch and let the exception bubble up
// Retrieve an existing resource that we can update.
ClientResponse<MultipartInput> res =
client.readItem(knownResourceId, knownItemResourceId);
verbose("updateItem: read status = " + res.getStatus());
Assert.assertEquals(res.getStatus(), EXPECTED_STATUS_CODE);
verbose("got VocabularyItem to update with ID: " + knownItemResourceId + " in Vocab: " + knownResourceId);
MultipartInput input = (MultipartInput) res.getEntity();
VocabularyitemsCommon vocabularyItem = (VocabularyitemsCommon) extractPart(input,
client.getItemCommonPartName(), VocabularyitemsCommon.class);
Assert.assertNotNull(vocabularyItem);
// Update the content of this resource.
vocabularyItem.setDisplayName("updated-" + vocabularyItem.getDisplayName());
verbose("to be updated VocabularyItem", vocabularyItem, VocabularyitemsCommon.class);
// Submit the request to the service and store the response.
MultipartOutput output = new MultipartOutput();
OutputPart commonPart = output.addPart(vocabularyItem, MediaType.APPLICATION_XML_TYPE);
commonPart.getHeaders().add("label", client.getItemCommonPartName());
res = client.updateItem(knownResourceId, knownItemResourceId, output);
int statusCode = res.getStatus();
// Check the status code of the response: does it match the expected response(s)?
verbose("updateItem: status = " + res.getStatus());
Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
input = (MultipartInput) res.getEntity();
VocabularyitemsCommon updatedVocabularyItem =
(VocabularyitemsCommon) extractPart(input,
client.getItemCommonPartName(), VocabularyitemsCommon.class);
Assert.assertNotNull(updatedVocabularyItem);
Assert.assertEquals(updatedVocabularyItem.getDisplayName(),
vocabularyItem.getDisplayName(),
"Data in updated VocabularyItem did not match submitted data.");
} catch (Exception e) {
e.printStackTrace();
}
}
// Failure outcomes
// Placeholders until the three tests below can be uncommented.
// See Issue CSPACE-401.
public void updateWithEmptyEntityBody() {
}
public void updateWithMalformedXml() {
}
public void updateWithWrongXmlSchema() {
}
/*
@Override
@Test(dependsOnMethods = {"create", "update", "testSubmitRequest"})
public void updateWithEmptyEntityBody() {
// Perform setup.
setupUpdateWithEmptyEntityBody();
// Submit the request to the service and store the response.
String method = REQUEST_TYPE.httpMethodName();
String url = getResourceURL(knownResourceId);
String mediaType = MediaType.APPLICATION_XML;
final String entity = "";
int statusCode = submitRequest(method, url, mediaType, entity);
// Check the status code of the response: does it match
// the expected response(s)?
verbose("updateWithEmptyEntityBody url=" + url + " status=" + statusCode);
Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
}
@Override
@Test(dependsOnMethods = {"create", "update", "testSubmitRequest"})
public void updateWithMalformedXml() {
// Perform setup.
setupUpdateWithMalformedXml();
// Submit the request to the service and store the response.
String method = REQUEST_TYPE.httpMethodName();
String url = getResourceURL(knownResourceId);
String mediaType = MediaType.APPLICATION_XML;
final String entity = MALFORMED_XML_DATA;
int statusCode = submitRequest(method, url, mediaType, entity);
// Check the status code of the response: does it match
// the expected response(s)?
verbose("updateWithMalformedXml: url=" + url + " status=" + statusCode);
Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
}
@Override
@Test(dependsOnMethods = {"create", "update", "testSubmitRequest"})
public void updateWithWrongXmlSchema() {
// Perform setup.
setupUpdateWithWrongXmlSchema();
// Submit the request to the service and store the response.
String method = REQUEST_TYPE.httpMethodName();
String url = getResourceURL(knownResourceId);
String mediaType = MediaType.APPLICATION_XML;
final String entity = WRONG_XML_SCHEMA_DATA;
int statusCode = submitRequest(method, url, mediaType, entity);
// Check the status code of the response: does it match
// the expected response(s)?
verbose("updateWithWrongSchema: url=" + url + " status=" + statusCode);
Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
}
*/
@Override
@Test(dependsOnMethods = {"update", "testSubmitRequest"})
public void updateNonExistent() {
// Perform setup.
setupUpdateNonExistent();
// Submit the request to the service and store the response.
// Note: The ID used in this 'create' call may be arbitrary.
// The only relevant ID may be the one used in update(), below.
// The only relevant ID may be the one used in update(), below.
MultipartOutput multipart = createVocabularyInstance(NON_EXISTENT_ID);
ClientResponse<MultipartInput> res =
client.update(NON_EXISTENT_ID, multipart);
int statusCode = res.getStatus();
// Check the status code of the response: does it match
// the expected response(s)?
verbose("updateNonExistent: status = " + res.getStatus());
Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
}
@Test(dependsOnMethods = {"updateItem", "testItemSubmitRequest"})
public void updateNonExistentItem() {
// Perform setup.
setupUpdateNonExistent("Update Non-Existent Item");
// Submit the request to the service and store the response.
// Note: The ID used in this 'create' call may be arbitrary.
// The only relevant ID may be the one used in update(), below.
// The only relevant ID may be the one used in update(), below.
MultipartOutput multipart = createVocabularyItemInstance(knownResourceId, NON_EXISTENT_ID);
ClientResponse<MultipartInput> res =
client.updateItem(knownResourceId, NON_EXISTENT_ID, multipart);
int statusCode = res.getStatus();
// Check the status code of the response: does it match
// the expected response(s)?
verbose("updateNonExistentItem: status = " + res.getStatus());
Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
}
// CRUD tests : DELETE tests
// Success outcomes
@Override
@Test(dependsOnMethods = {"create", "readList", "testSubmitRequest", "update"})
public void delete() {
// Perform setup.
setupDelete();
// Submit the request to the service and store the response.
ClientResponse<Response> res = client.delete(knownResourceId);
int statusCode = res.getStatus();
// Check the status code of the response: does it match
// the expected response(s)?
verbose("delete: status = " + res.getStatus());
Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
}
@Test(dependsOnMethods = {"createItem", "readItemList", "testItemSubmitRequest", "updateItem"})
public void deleteItem() {
// Perform setup.
setupDelete("Delete Item");
// Submit the request to the service and store the response.
ClientResponse<Response> res = client.deleteItem(knownResourceId, knownItemResourceId);
int statusCode = res.getStatus();
// Check the status code of the response: does it match
// the expected response(s)?
verbose("delete: status = " + res.getStatus());
Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
}
// Failure outcomes
@Override
@Test(dependsOnMethods = {"delete"})
public void deleteNonExistent() {
// Perform setup.
setupDeleteNonExistent();
// Submit the request to the service and store the response.
ClientResponse<Response> res = client.delete(NON_EXISTENT_ID);
int statusCode = res.getStatus();
// Check the status code of the response: does it match
// the expected response(s)?
verbose("deleteNonExistent: status = " + res.getStatus());
Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
}
@Test(dependsOnMethods = {"deleteItem"})
public void deleteNonExistentItem() {
// Perform setup.
setupDeleteNonExistent("Delete Non-Existent Item");
// Submit the request to the service and store the response.
ClientResponse<Response> res = client.deleteItem(knownResourceId, NON_EXISTENT_ID);
int statusCode = res.getStatus();
// Check the status code of the response: does it match
// the expected response(s)?
verbose("deleteNonExistent: status = " + res.getStatus());
Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
}
// Utility tests : tests of code used in tests above
/**
* Tests the code for manually submitting data that is used by several
* of the methods above.
*/
@Test(dependsOnMethods = {"create", "read"})
public void testSubmitRequest() {
// Expected status code: 200 OK
final int EXPECTED_STATUS_CODE = Response.Status.OK.getStatusCode();
// Submit the request to the service and store the response.
String method = ServiceRequestType.READ.httpMethodName();
String url = getResourceURL(knownResourceId);
int statusCode = submitRequest(method, url);
// Check the status code of the response: does it match
// the expected response(s)?
verbose("testSubmitRequest: url=" + url + " status=" + statusCode);
Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
}
@Test(dependsOnMethods = {"createItem", "readItem", "testSubmitRequest"})
public void testItemSubmitRequest() {
// Expected status code: 200 OK
final int EXPECTED_STATUS_CODE = Response.Status.OK.getStatusCode();
// Submit the request to the service and store the response.
String method = ServiceRequestType.READ.httpMethodName();
String url = getItemResourceURL(knownResourceId, knownItemResourceId);
int statusCode = submitRequest(method, url);
// Check the status code of the response: does it match
// the expected response(s)?
verbose("testItemSubmitRequest: url=" + url + " status=" + statusCode);
Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
}
// Utility methods used by tests above
@Override
public String getServicePathComponent() {
return SERVICE_PATH_COMPONENT;
}
public String getItemServicePathComponent() {
return ITEM_SERVICE_PATH_COMPONENT;
}
/**
* Returns the root URL for a service.
*
* This URL consists of a base URL for all services, followed by
* a path component for the owning vocabulary, followed by the
* path component for the items.
*
* @return The root URL for a service.
*/
protected String getItemServiceRootURL(String parentResourceIdentifier) {
return getResourceURL(parentResourceIdentifier) + "/" + getItemServicePathComponent();
}
/**
* Returns the URL of a specific resource managed by a service, and
* designated by an identifier (such as a universally unique ID, or UUID).
*
* @param resourceIdentifier An identifier (such as a UUID) for a resource.
*
* @return The URL of a specific resource managed by a service.
*/
protected String getItemResourceURL(String parentResourceIdentifier, String resourceIdentifier) {
return getItemServiceRootURL(parentResourceIdentifier) + "/" + resourceIdentifier;
}
private MultipartOutput createVocabularyInstance(String identifier) {
return createVocabularyInstance(
"displayName-" + identifier,
"vocabType-" + identifier);
}
private MultipartOutput createVocabularyInstance(String displayName, String vocabType) {
VocabulariesCommon vocabulary = new VocabulariesCommon();
vocabulary.setDisplayName(displayName);
vocabulary.setVocabType(vocabType);
MultipartOutput multipart = new MultipartOutput();
OutputPart commonPart = multipart.addPart(vocabulary, MediaType.APPLICATION_XML_TYPE);
commonPart.getHeaders().add("label", client.getCommonPartName());
verbose("to be created, vocabulary common ", vocabulary, VocabulariesCommon.class);
return multipart;
}
private MultipartOutput createVocabularyItemInstance(String inVocabulary, String displayName) {
VocabularyitemsCommon vocabularyItem = new VocabularyitemsCommon();
vocabularyItem.setInVocabulary(inVocabulary);
vocabularyItem.setDisplayName(displayName);
MultipartOutput multipart = new MultipartOutput();
OutputPart commonPart = multipart.addPart(vocabularyItem, MediaType.APPLICATION_XML_TYPE);
commonPart.getHeaders().add("label", client.getItemCommonPartName());
verbose("to be created, vocabularyitem common ", vocabularyItem, VocabularyitemsCommon.class);
return multipart;
}
}
|
package magpie.utility.tools;
import java.util.*;
import magpie.data.BaseEntry;
import magpie.data.materials.CompositionDataset;
import magpie.data.materials.CompositionEntry;
import magpie.data.utilities.generators.PhaseDiagramCompositionEntryGenerator;
import magpie.utility.interfaces.Commandable;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
/**
* Given a nominal composition, find nearby compositions that can be charge neutral.
*
* <p>Works by finding all combinations of elements in the supplied composition
* that are within a certain distance of the target composition with less than
* a certain number of atoms per unit cell.
*
* <p>Distance is computed as the L<sub>1</sub> distance of the composition vector
* for N - 1 elements (N is the number of compounds). Example: Fe3Al and FeAl
* are 0.25 apart.
*
* <p><b><u>Implemented Command</u></b>
*
* <command><p><b>run <composition> <distance> <size></b> -
* Find all neutral compounds within a certain distance of a target
* <br><pr><i>composition</i>: Target composition
* <br><pr><i>distance</i>: Maximum allowed distance
* <br><pr><i>size</i>: Maximum number of atoms in formula unit.</command>
*
* @author Logan Ward
*/
public class IonicCompoundFinder implements Commandable {
/** Nominal composition */
private CompositionEntry NominalComposition;
/** Maximum acceptable distance from nominal composition */
private double MaximumDistance = 0.1;
/** Maximum number of atoms in formula unit */
private int MaxFormulaUnitSize = 5;
/**
* Set the target composition of the ionic compound.
* @param comp Desired nominal composition
* @throws java.lang.Exception
*/
public void setNominalComposition(CompositionEntry comp) throws Exception {
if (comp.getElements().length < 2) {
throw new Exception("Must be at least a binary compound");
}
this.NominalComposition = comp;
}
/**
* Set the maximum allowed distance from the target value. Note, distance
* is computed as the L<sub>1</sub> norm of the composition vector assuming
* one of the elements is a balance (i.e., only sum the difference for N-1 elements).
* @param dist Maximum allowed distance
*/
public void setMaximumDistance(double dist) {
this.MaximumDistance = dist;
}
/**
* Set maximum number of atoms in formula unit. Example: NaCl has 2
* @param size Maximum allowed size
*/
public void setMaxFormulaUnitSize(int size) {
this.MaxFormulaUnitSize = size;
}
/**
* Locate all ionic compounds within a certain distance of the target composition.
* Subject to the constraints set by {@linkplain #setMaximumDistance(double) }
* and {@linkplain #setMaxFormulaUnitSize(int) }.
* @return List of possible compositions
* @throws java.lang.Exception
*/
public List<CompositionEntry> findAllCompounds() throws Exception {
// Get elements in nominal compound
Set<Integer> elemSet = new TreeSet<>();
for (int i : NominalComposition.getElements()) {
elemSet.add(i);
}
// Get list of all possible compositions
PhaseDiagramCompositionEntryGenerator gen = new PhaseDiagramCompositionEntryGenerator();
gen.setElementsByIndex(elemSet);
gen.setEvenSpacing(false);
gen.setOrder(1, elemSet.size());
gen.setSize(MaxFormulaUnitSize);
List<BaseEntry> allPossibilities = gen.generateEntries();
// Find which ones fit the desired tolerance
CompositionDataset dataset = new CompositionDataset();
List<Pair<CompositionEntry, Double>> hits = new LinkedList<>();
int[] elems = NominalComposition.getElements();
double[] fracs = NominalComposition.getFractions();
for (BaseEntry ptr : allPossibilities) {
CompositionEntry cand = (CompositionEntry) ptr;
// See if it is is close enough in composition
double dist = 0.0;
for (int e=0; e<elems.length; e++) {
dist += Math.abs(fracs[e] - cand.getElementFraction(elems[e]));
}
if (dist > MaximumDistance) {
continue;
}
// See if it is ionically neutral
if (dataset.compositionCanFormIonic(cand)) {
hits.add(new ImmutablePair<>(cand, dist));
}
}
// Sort such that closest is first
Collections.sort(hits, new Comparator<Pair<CompositionEntry, Double>> () {
@Override
public int compare(Pair<CompositionEntry, Double> o1, Pair<CompositionEntry, Double> o2) {
return Double.compare(o1.getRight(), o2.getRight());
}
});
// Get only the compositions
List<CompositionEntry> accepted = new LinkedList<>();
for (Pair<CompositionEntry, Double> hit : hits) {
accepted.add(hit.getKey());
}
return accepted;
}
@Override
public Object runCommand(List<Object> Command) throws Exception {
if (Command.isEmpty()) {
throw new Exception("Only runs one command: find");
}
String action = Command.get(0).toString();
if (! action.equalsIgnoreCase("run")) {
throw new Exception("Only runs one command: find");
}
// Parse user request
String comp;
double dist;
int size;
try {
comp = Command.get(1).toString();
dist = Double.parseDouble(Command.get(2).toString());
size = Integer.parseInt(Command.get(3).toString());
} catch (Exception e) {
throw new Exception("Usage: run <comp> <max dist> <max size>");
}
// Set finder
setNominalComposition(new CompositionEntry(comp));
setMaximumDistance(dist);
setMaxFormulaUnitSize(size);
// Run finder
List<CompositionEntry> findings = findAllCompounds();
// Print results
System.out.format("\tFound %d compositions:\n", findings.size());
for (int f=0; f<findings.size(); f++) {
System.out.format("%20s", findings.get(f).toString());
if ((f % 3) == 2) {
System.out.println();
}
}
System.out.println();
// Format output
CompositionDataset output = new CompositionDataset();
output.addEntries(findings);
return output;
}
}
|
package de.qaware.oss.cloud.nativ.wjax2016;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.social.TwitterAutoConfiguration;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
@SpringBootApplication
@EnableCircuitBreaker
@EnableAutoConfiguration(exclude = {TwitterAutoConfiguration.class})
public class ZwitscherServiceApplication {
public static void main(String[] args) {
SpringApplication.run(ZwitscherServiceApplication.class, args);
}
}
|
package bdv.export;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.CountDownLatch;
import bdv.export.WriteSequenceToHdf5.AfterEachPlane;
import bdv.export.WriteSequenceToHdf5.LoopbackHeuristic;
import bdv.img.hdf5.Hdf5ImageLoader;
import bdv.img.hdf5.Partition;
import bdv.img.hdf5.Util;
import bdv.spimdata.SequenceDescriptionMinimal;
import ch.systemsx.cisd.hdf5.HDF5Factory;
import ch.systemsx.cisd.hdf5.HDF5IntStorageFeatures;
import ch.systemsx.cisd.hdf5.IHDF5Reader;
import ch.systemsx.cisd.hdf5.IHDF5Writer;
import mpicbg.spim.data.XmlHelpers;
import mpicbg.spim.data.generic.sequence.AbstractSequenceDescription;
import mpicbg.spim.data.generic.sequence.BasicImgLoader;
import mpicbg.spim.data.generic.sequence.BasicSetupImgLoader;
import mpicbg.spim.data.generic.sequence.BasicViewSetup;
import mpicbg.spim.data.sequence.TimePoint;
import mpicbg.spim.data.sequence.TimePoints;
import mpicbg.spim.data.sequence.ViewId;
import net.imglib2.Cursor;
import net.imglib2.Dimensions;
import net.imglib2.FinalInterval;
import net.imglib2.RandomAccess;
import net.imglib2.RandomAccessibleInterval;
import net.imglib2.img.array.ArrayImg;
import net.imglib2.img.array.ArrayImgs;
import net.imglib2.img.basictypeaccess.array.ShortArray;
import net.imglib2.img.cell.CellImg;
import net.imglib2.iterator.LocalizingIntervalIterator;
import net.imglib2.type.numeric.RealType;
import net.imglib2.type.numeric.integer.UnsignedShortType;
import net.imglib2.view.Views;
/**
* Create a hdf5 files containing image data from all views and all timepoints
* in a chunked, mipmaped representation.
*
* <p>
* Every image is stored in multiple resolutions. The resolutions are described
* as int[] arrays defining multiple of original pixel size in every dimension.
* For example {1,1,1} is the original resolution, {4,4,2} is downsampled by
* factor 4 in X and Y and factor 2 in Z. Each resolution of the image is stored
* as a chunked three-dimensional array (each chunk corresponds to one cell of a
* {@link CellImg} when the data is loaded). The chunk sizes are defined by the
* subdivisions parameter which is an array of int[], one per resolution. Each
* int[] array describes the X,Y,Z chunk size for one resolution. For instance
* {32,32,8} says that the (downsampled) image is divided into 32x32x8 pixel
* blocks.
*
* <p>
* For every mipmap level we have a (3D) int[] resolution array, so the full
* mipmap pyramid is specified by a nested int[][] array. Likewise, we have a
* (3D) int[] subdivions array for every mipmap level, so the full chunking of
* the full pyramid is specfied by a nested int[][] array.
*
* <p>
* A data-set can be stored in a single hdf5 file or split across several hdf5
* "partitions" with one master hdf5 linking into the partitions.
*
* @author Tobias Pietzsch <tobias.pietzsch@gmail.com>
*/
public class WriteSequenceToHdf5
{
/**
* Create a hdf5 file containing image data from all views and all
* timepoints in a chunked, mipmaped representation.
*
* @param seq
* description of the sequence to be stored as hdf5. (The
* {@link AbstractSequenceDescription} contains the number of
* setups and timepoints as well as an {@link BasicImgLoader}
* that provides the image data, Registration information is not
* needed here, that will go into the accompanying xml).
* @param perSetupMipmapInfo
* this maps from setup {@link BasicViewSetup#getId() id} to
* {@link ExportMipmapInfo} for that setup. The
* {@link ExportMipmapInfo} contains for each mipmap level, the
* subsampling factors and subdivision block sizes.
* @param deflate
* whether to compress the data with the HDF5 DEFLATE filter.
* @param hdf5File
* hdf5 file to which the image data is written.
* @param loopbackHeuristic
* heuristic to decide whether to create each resolution level by
* reading pixels from the original image or by reading back a
* finer resolution level already written to the hdf5. may be
* null (in this case always use the original image).
* @param afterEachPlane
* this is called after each "plane of chunks" is written, giving
* the opportunity to clear caches, etc.
* @param numCellCreatorThreads
* The number of threads that will be instantiated to generate
* cell data. Must be at least 1. (In addition the cell creator
* threads there is one writer thread that saves the generated
* data to HDF5.)
* @param progressWriter
* completion ratio and status output will be directed here.
*/
public static void writeHdf5File(
final AbstractSequenceDescription< ?, ?, ? > seq,
final Map< Integer, ExportMipmapInfo > perSetupMipmapInfo,
final boolean deflate,
final File hdf5File,
final LoopbackHeuristic loopbackHeuristic,
final AfterEachPlane afterEachPlane,
final int numCellCreatorThreads,
final ProgressWriter progressWriter )
{
final HashMap< Integer, Integer > timepointIdSequenceToPartition = new HashMap<>();
for ( final TimePoint timepoint : seq.getTimePoints().getTimePointsOrdered() )
timepointIdSequenceToPartition.put( timepoint.getId(), timepoint.getId() );
final HashMap< Integer, Integer > setupIdSequenceToPartition = new HashMap<>();
for ( final BasicViewSetup setup : seq.getViewSetupsOrdered() )
setupIdSequenceToPartition.put( setup.getId(), setup.getId() );
final Partition partition = new Partition( hdf5File.getPath(), timepointIdSequenceToPartition, setupIdSequenceToPartition );
writeHdf5PartitionFile( seq, perSetupMipmapInfo, deflate, partition, loopbackHeuristic, afterEachPlane, numCellCreatorThreads, progressWriter );
}
/**
* Create a hdf5 file containing image data from all views and all
* timepoints in a chunked, mipmaped representation. This is the same as
* {@link WriteSequenceToHdf5#writeHdf5File(AbstractSequenceDescription, Map, boolean, File, LoopbackHeuristic, AfterEachPlane, int, ProgressWriter)}
* except that only one set of supsampling factors and and subdivision
* blocksizes is given, which is used for all {@link BasicViewSetup views}.
*
* @param seq
* description of the sequence to be stored as hdf5. (The
* {@link AbstractSequenceDescription} contains the number of
* setups and timepoints as well as an {@link BasicImgLoader}
* that provides the image data, Registration information is not
* needed here, that will go into the accompanying xml).
* @param resolutions
* this nested arrays contains per mipmap level, the subsampling
* factors.
* @param subdivisions
* this nested arrays contains per mipmap level, the subdivision
* block sizes.
* @param deflate
* whether to compress the data with the HDF5 DEFLATE filter.
* @param hdf5File
* hdf5 file to which the image data is written.
* @param loopbackHeuristic
* heuristic to decide whether to create each resolution level by
* reading pixels from the original image or by reading back a
* finer resolution level already written to the hdf5. may be
* null (in this case always use the original image).
* @param afterEachPlane
* this is called after each "plane of chunks" is written, giving
* the opportunity to clear caches, etc.
* @param numCellCreatorThreads
* The number of threads that will be instantiated to generate
* cell data. Must be at least 1. (In addition the cell creator
* threads there is one writer thread that saves the generated
* data to HDF5.)
* @param progressWriter
* completion ratio and status output will be directed here.
*/
public static void writeHdf5File(
final AbstractSequenceDescription< ?, ?, ? > seq,
final int[][] resolutions,
final int[][] subdivisions,
final boolean deflate,
final File hdf5File,
final LoopbackHeuristic loopbackHeuristic,
final AfterEachPlane afterEachPlane,
final int numCellCreatorThreads,
final ProgressWriter progressWriter )
{
final HashMap< Integer, ExportMipmapInfo > perSetupMipmapInfo = new HashMap<>();
final ExportMipmapInfo mipmapInfo = new ExportMipmapInfo( resolutions, subdivisions );
for ( final BasicViewSetup setup : seq.getViewSetupsOrdered() )
perSetupMipmapInfo.put( setup.getId(), mipmapInfo );
writeHdf5File( seq, perSetupMipmapInfo, deflate, hdf5File, loopbackHeuristic, afterEachPlane, numCellCreatorThreads, progressWriter );
}
/**
* Create a hdf5 master file linking to image data from all views and all
* timepoints. This is the same as
* {@link #writeHdf5PartitionLinkFile(AbstractSequenceDescription, Map, ArrayList, File)},
* except that the information about the partition files as well as the
* path of the master file to be written is obtained from the
* {@link BasicImgLoader} of the sequence, which must be a
* {@link Hdf5ImageLoader}.
*
* @param seq
* description of the sequence to be stored as hdf5. (The
* {@link AbstractSequenceDescription} contains the number of
* setups and timepoints as well as an {@link BasicImgLoader}
* that provides the image data, Registration information is not
* needed here, that will go into the accompanying xml).
* @param perSetupMipmapInfo
* this maps from setup {@link BasicViewSetup#getId() id} to
* {@link ExportMipmapInfo} for that setup. The
* {@link ExportMipmapInfo} contains for each mipmap level, the
* subsampling factors and subdivision block sizes.
*/
public static void writeHdf5PartitionLinkFile( final AbstractSequenceDescription< ?, ?, ? > seq, final Map< Integer, ExportMipmapInfo > perSetupMipmapInfo )
{
if ( !( seq.getImgLoader() instanceof Hdf5ImageLoader ) )
throw new IllegalArgumentException( "sequence has " + seq.getImgLoader().getClass() + " imgloader. Hdf5ImageLoader required." );
final Hdf5ImageLoader loader = ( Hdf5ImageLoader ) seq.getImgLoader();
writeHdf5PartitionLinkFile( seq, perSetupMipmapInfo, loader.getPartitions(), loader.getHdf5File() );
}
/**
* Create a hdf5 master file linking to image data from all views and all
* timepoints. Which hdf5 files contain which part of the image data is
* specified in the {@code portitions} parameter.
*
* Note that this method only writes the master file containing links. The
* individual partitions need to be written with
* {@link #writeHdf5PartitionFile(AbstractSequenceDescription, Map, boolean, Partition, LoopbackHeuristic, AfterEachPlane, int, ProgressWriter)}.
*
* @param seq
* description of the sequence to be stored as hdf5. (The
* {@link AbstractSequenceDescription} contains the number of
* setups and timepoints as well as an {@link BasicImgLoader}
* that provides the image data, Registration information is not
* needed here, that will go into the accompanying xml).
* @param perSetupMipmapInfo
* this maps from setup {@link BasicViewSetup#getId() id} to
* {@link ExportMipmapInfo} for that setup. The
* {@link ExportMipmapInfo} contains for each mipmap level, the
* subsampling factors and subdivision block sizes.
* @param partitions
* which parts of the dataset are stored in which files.
* @param hdf5File
* hdf5 master file to which the image data from the partition
* files is linked.
*/
public static void writeHdf5PartitionLinkFile( final AbstractSequenceDescription< ?, ?, ? > seq, final Map< Integer, ExportMipmapInfo > perSetupMipmapInfo, final ArrayList< Partition > partitions, final File hdf5File )
{
// open HDF5 output file
if ( hdf5File.exists() )
hdf5File.delete();
final IHDF5Writer hdf5Writer = HDF5Factory.open( hdf5File );
// write Mipmap descriptions
for ( final BasicViewSetup setup : seq.getViewSetupsOrdered() )
{
final int setupId = setup.getId();
final ExportMipmapInfo mipmapInfo = perSetupMipmapInfo.get( setupId );
hdf5Writer.writeDoubleMatrix( Util.getResolutionsPath( setupId ), mipmapInfo.getResolutions() );
hdf5Writer.writeIntMatrix( Util.getSubdivisionsPath( setupId ), mipmapInfo.getSubdivisions() );
}
// link Cells for all views in the partition
final File basePath = hdf5File.getParentFile();
for ( final Partition partition : partitions )
{
final Map< Integer, Integer > timepointIdSequenceToPartition = partition.getTimepointIdSequenceToPartition();
final Map< Integer, Integer > setupIdSequenceToPartition = partition.getSetupIdSequenceToPartition();
for ( final Entry< Integer, Integer > tEntry : timepointIdSequenceToPartition.entrySet() )
{
final int tSequence = tEntry.getKey();
final int tPartition = tEntry.getValue();
for ( final Entry< Integer, Integer > sEntry : setupIdSequenceToPartition.entrySet() )
{
final int sSequence = sEntry.getKey();
final int sPartition = sEntry.getValue();
final ViewId idSequence = new ViewId( tSequence, sSequence );
final ViewId idPartition = new ViewId( tPartition, sPartition );
final int numLevels = perSetupMipmapInfo.get( sSequence ).getNumLevels();
for ( int level = 0; level < numLevels; ++level )
{
final String relativePath = XmlHelpers.getRelativePath( new File( partition.getPath() ), basePath ).getPath();
hdf5Writer.object().createOrUpdateExternalLink( relativePath, Util.getCellsPath( idPartition, level ), Util.getCellsPath( idSequence, level ) );
}
}
}
}
hdf5Writer.close();
}
/**
* Create a hdf5 partition file containing image data for a subset of views
* and timepoints in a chunked, mipmaped representation.
*
* Please note that the description of the <em>full</em> dataset must be
* given in the <code>seq</code>, <code>perSetupResolutions</code>, and
* <code>perSetupSubdivisions</code> parameters. Then only the part
* described by <code>partition</code> will be written.
*
* @param seq
* description of the sequence to be stored as hdf5. (The
* {@link AbstractSequenceDescription} contains the number of
* setups and timepoints as well as an {@link BasicImgLoader}
* that provides the image data, Registration information is not
* needed here, that will go into the accompanying xml).
* @param perSetupMipmapInfo
* this maps from setup {@link BasicViewSetup#getId() id} to
* {@link ExportMipmapInfo} for that setup. The
* {@link ExportMipmapInfo} contains for each mipmap level, the
* subsampling factors and subdivision block sizes.
* @param deflate
* whether to compress the data with the HDF5 DEFLATE filter.
* @param partition
* which part of the dataset to write, and to which file.
* @param loopbackHeuristic
* heuristic to decide whether to create each resolution level by
* reading pixels from the original image or by reading back a
* finer resolution level already written to the hdf5. may be
* null (in this case always use the original image).
* @param afterEachPlane
* this is called after each "plane of chunks" is written, giving
* the opportunity to clear caches, etc.
* @param numCellCreatorThreads
* The number of threads that will be instantiated to generate
* cell data. Must be at least 1. (In addition the cell creator
* threads there is one writer thread that saves the generated
* data to HDF5.)
* @param progressWriter
* completion ratio and status output will be directed here.
*/
public static void writeHdf5PartitionFile(
final AbstractSequenceDescription< ?, ?, ? > seq,
final Map< Integer, ExportMipmapInfo > perSetupMipmapInfo,
final boolean deflate,
final Partition partition,
final LoopbackHeuristic loopbackHeuristic,
final AfterEachPlane afterEachPlane,
final int numCellCreatorThreads,
ProgressWriter progressWriter )
{
final int blockWriterQueueLength = 100;
if ( progressWriter == null )
progressWriter = new ProgressWriterConsole();
progressWriter.setProgress( 0 );
// get sequence timepointIds for the timepoints contained in this partition
final ArrayList< Integer > timepointIdsSequence = new ArrayList<>( partition.getTimepointIdSequenceToPartition().keySet() );
Collections.sort( timepointIdsSequence );
final int numTimepoints = timepointIdsSequence.size();
final ArrayList< Integer > setupIdsSequence = new ArrayList<>( partition.getSetupIdSequenceToPartition().keySet() );
Collections.sort( setupIdsSequence );
// get the BasicImgLoader that supplies the images
final BasicImgLoader imgLoader = seq.getImgLoader();
for ( final BasicViewSetup setup : seq.getViewSetupsOrdered() ) {
final Object type = imgLoader.getSetupImgLoader( setup.getId() ).getImageType();
if ( !( type instanceof UnsignedShortType ) )
throw new IllegalArgumentException( "Expected BasicImgLoader<UnsignedShortTyp> but your dataset has BasicImgLoader<"
+ type.getClass().getSimpleName() + ">.\nCurrently writing to HDF5 is only supported for UnsignedShortType." );
}
// open HDF5 partition output file
final File hdf5File = new File( partition.getPath() );
if ( hdf5File.exists() )
hdf5File.delete();
final Hdf5BlockWriterThread writerQueue = new Hdf5BlockWriterThread( hdf5File, blockWriterQueueLength );
writerQueue.start();
// start CellCreatorThreads
final CellCreatorThread[] cellCreatorThreads = createAndStartCellCreatorThreads( numCellCreatorThreads );
// calculate number of tasks for progressWriter
int numTasks = 1; // first task is for writing mipmap descriptions etc...
for ( final int timepointIdSequence : timepointIdsSequence )
for ( final int setupIdSequence : setupIdsSequence )
if ( seq.getViewDescriptions().get( new ViewId( timepointIdSequence, setupIdSequence ) ).isPresent() )
numTasks++;
int numCompletedTasks = 0;
// write Mipmap descriptions
for ( final Entry< Integer, Integer > entry : partition.getSetupIdSequenceToPartition().entrySet() )
{
final int setupIdSequence = entry.getKey();
final int setupIdPartition = entry.getValue();
final ExportMipmapInfo mipmapInfo = perSetupMipmapInfo.get( setupIdSequence );
writerQueue.writeMipmapDescription( setupIdPartition, mipmapInfo );
}
progressWriter.setProgress( ( double ) ++numCompletedTasks / numTasks );
// write image data for all views to the HDF5 file
int timepointIndex = 0;
for ( final int timepointIdSequence : timepointIdsSequence )
{
final int timepointIdPartition = partition.getTimepointIdSequenceToPartition().get( timepointIdSequence );
progressWriter.out().printf( "proccessing timepoint %d / %d\n", ++timepointIndex, numTimepoints );
// assemble the viewsetups that are present in this timepoint
final ArrayList< Integer > setupsTimePoint = new ArrayList<>();
for ( final int setupIdSequence : setupIdsSequence )
if ( seq.getViewDescriptions().get( new ViewId( timepointIdSequence, setupIdSequence ) ).isPresent() )
setupsTimePoint.add( setupIdSequence );
final int numSetups = setupsTimePoint.size();
int setupIndex = 0;
for ( final int setupIdSequence : setupsTimePoint )
{
final int setupIdPartition = partition.getSetupIdSequenceToPartition().get( setupIdSequence );
progressWriter.out().printf( "proccessing setup %d / %d\n", ++setupIndex, numSetups );
@SuppressWarnings( "unchecked" )
final RandomAccessibleInterval< UnsignedShortType > img = ( ( BasicSetupImgLoader< UnsignedShortType > ) imgLoader.getSetupImgLoader( setupIdSequence ) ).getImage( timepointIdSequence );
final ExportMipmapInfo mipmapInfo = perSetupMipmapInfo.get( setupIdSequence );
final double startCompletionRatio = ( double ) numCompletedTasks++ / numTasks;
final double endCompletionRatio = ( double ) numCompletedTasks / numTasks;
final ProgressWriter subProgressWriter = new SubTaskProgressWriter( progressWriter, startCompletionRatio, endCompletionRatio );
writeViewToHdf5PartitionFile(
img, timepointIdPartition, setupIdPartition, mipmapInfo, false,
deflate, writerQueue, cellCreatorThreads, loopbackHeuristic, afterEachPlane, subProgressWriter );
}
}
// shutdown and close file
stopCellCreatorThreads( cellCreatorThreads );
writerQueue.close();
progressWriter.setProgress( 1.0 );
}
/**
* Write a single view to a hdf5 partition file, in a chunked, mipmaped
* representation. Note that the specified view must not already exist in
* the partition file!
*
* @param img
* the view to be written.
* @param partition
* describes which part of the full sequence is contained in this
* partition, and to which file this partition is written.
* @param timepointIdPartition
* the timepoint id wrt the partition of the view to be written.
* The information in {@code partition} relates this to timepoint
* id in the full sequence.
* @param setupIdPartition
* the setup id wrt the partition of the view to be written. The
* information in {@code partition} relates this to setup id in
* the full sequence.
* @param mipmapInfo
* contains for each mipmap level of the setup, the subsampling
* factors and subdivision block sizes.
* @param writeMipmapInfo
* whether to write mipmap description for the setup. must be
* done (at least) once for each setup in the partition.
* @param deflate
* whether to compress the data with the HDF5 DEFLATE filter.
* @param loopbackHeuristic
* heuristic to decide whether to create each resolution level by
* reading pixels from the original image or by reading back a
* finer resolution level already written to the hdf5. may be
* null (in this case always use the original image).
* @param afterEachPlane
* this is called after each "plane of chunks" is written, giving
* the opportunity to clear caches, etc.
* @param numCellCreatorThreads
* The number of threads that will be instantiated to generate
* cell data. Must be at least 1. (In addition the cell creator
* threads there is one writer thread that saves the generated
* data to HDF5.)
* @param progressWriter
* completion ratio and status output will be directed here. may
* be null.
*/
public static void writeViewToHdf5PartitionFile(
final RandomAccessibleInterval< UnsignedShortType > img,
final Partition partition,
final int timepointIdPartition,
final int setupIdPartition,
final ExportMipmapInfo mipmapInfo,
final boolean writeMipmapInfo,
final boolean deflate,
final LoopbackHeuristic loopbackHeuristic,
final AfterEachPlane afterEachPlane,
final int numCellCreatorThreads,
final ProgressWriter progressWriter )
{
final int blockWriterQueueLength = 100;
// create and start Hdf5BlockWriterThread
final Hdf5BlockWriterThread writerQueue = new Hdf5BlockWriterThread( partition.getPath(), blockWriterQueueLength );
writerQueue.start();
final CellCreatorThread[] cellCreatorThreads = createAndStartCellCreatorThreads( numCellCreatorThreads );
// write the image
writeViewToHdf5PartitionFile( img, timepointIdPartition, setupIdPartition, mipmapInfo, writeMipmapInfo, deflate, writerQueue, cellCreatorThreads, loopbackHeuristic, afterEachPlane, progressWriter );
stopCellCreatorThreads( cellCreatorThreads );
writerQueue.close();
}
static class LoopBackImageLoader extends Hdf5ImageLoader
{
private LoopBackImageLoader( final IHDF5Reader existingHdf5Reader, final AbstractSequenceDescription< ?, ?, ? > sequenceDescription )
{
super( null, existingHdf5Reader, null, sequenceDescription, false );
}
static LoopBackImageLoader create( final IHDF5Reader existingHdf5Reader, final int timepointIdPartition, final int setupIdPartition, final Dimensions imageDimensions )
{
final HashMap< Integer, TimePoint > timepoints = new HashMap<>();
timepoints.put( timepointIdPartition, new TimePoint( timepointIdPartition ) );
final HashMap< Integer, BasicViewSetup > setups = new HashMap<>();
setups.put( setupIdPartition, new BasicViewSetup( setupIdPartition, null, imageDimensions, null ) );
final SequenceDescriptionMinimal seq = new SequenceDescriptionMinimal( new TimePoints( timepoints ), setups, null, null );
return new LoopBackImageLoader( existingHdf5Reader, seq );
}
}
/**
* Write a single view to a hdf5 partition file, in a chunked, mipmaped
* representation. Note that the specified view must not already exist in
* the partition file!
*
* @param img
* the view to be written.
* @param timepointIdPartition
* the timepoint id wrt the partition of the view to be written.
* The information in {@code partition} relates this to timepoint
* id in the full sequence.
* @param setupIdPartition
* the setup id wrt the partition of the view to be written. The
* information in {@code partition} relates this to setup id in
* the full sequence.
* @param mipmapInfo
* contains for each mipmap level of the setup, the subsampling
* factors and subdivision block sizes.
* @param writeMipmapInfo
* whether to write mipmap description for the setup. must be
* done (at least) once for each setup in the partition.
* @param deflate
* whether to compress the data with the HDF5 DEFLATE filter.
* @param writerQueue
* block writing tasks are enqueued here.
* @param cellCreatorThreads
* threads used for creating (possibly down-sampled) blocks of
* the view to be written.
* @param loopbackHeuristic
* heuristic to decide whether to create each resolution level by
* reading pixels from the original image or by reading back a
* finer resolution level already written to the hdf5. may be
* null (in this case always use the original image).
* @param afterEachPlane
* this is called after each "plane of chunks" is written, giving
* the opportunity to clear caches, etc.
* @param progressWriter
* completion ratio and status output will be directed here. may
* be null.
*/
public static void writeViewToHdf5PartitionFile(
final RandomAccessibleInterval< UnsignedShortType > img,
final int timepointIdPartition,
final int setupIdPartition,
final ExportMipmapInfo mipmapInfo,
final boolean writeMipmapInfo,
final boolean deflate,
final Hdf5BlockWriterThread writerQueue,
final CellCreatorThread[] cellCreatorThreads,
final LoopbackHeuristic loopbackHeuristic,
final AfterEachPlane afterEachPlane,
ProgressWriter progressWriter )
{
final HDF5IntStorageFeatures storage = deflate ? HDF5IntStorageFeatures.INT_AUTO_SCALING_DEFLATE : HDF5IntStorageFeatures.INT_AUTO_SCALING;
if ( progressWriter == null )
progressWriter = new ProgressWriterConsole();
// for progressWriter
final int numTasks = mipmapInfo.getNumLevels();
int numCompletedTasks = 0;
progressWriter.setProgress( ( double ) numCompletedTasks++ / numTasks );
// write Mipmap descriptions
if ( writeMipmapInfo )
writerQueue.writeMipmapDescription( setupIdPartition, mipmapInfo );
// create loopback image-loader to read already written chunks from the
// h5 for generating low-resolution versions.
final LoopBackImageLoader loopback = ( loopbackHeuristic == null ) ? null : LoopBackImageLoader.create( writerQueue.getIHDF5Writer(), timepointIdPartition, setupIdPartition, img );
// write image data for all views to the HDF5 file
final int n = 3;
final long[] dimensions = new long[ n ];
final int[][] resolutions = mipmapInfo.getExportResolutions();
final int[][] subdivisions = mipmapInfo.getSubdivisions();
final int numLevels = mipmapInfo.getNumLevels();
for ( int level = 0; level < numLevels; ++level )
{
progressWriter.out().println( "writing level " + level );
final RandomAccessibleInterval< UnsignedShortType > sourceImg;
final int[] factor;
final boolean useLoopBack;
if ( loopbackHeuristic == null )
{
sourceImg = img;
factor = resolutions[ level ];
useLoopBack = false;
}
else
{
// Are downsampling factors a multiple of a level that we have
// already written?
int[] factorsToPreviousLevel = null;
int previousLevel = -1;
A: for ( int l = level - 1; l >= 0; --l )
{
final int[] f = new int[ n ];
for ( int d = 0; d < n; ++d )
{
f[ d ] = resolutions[ level ][ d ] / resolutions[ l ][ d ];
if ( f[ d ] * resolutions[ l ][ d ] != resolutions[ level ][ d ] )
continue A;
}
factorsToPreviousLevel = f;
previousLevel = l;
break;
}
// Now, if previousLevel >= 0 we can use loopback ImgLoader on
// previousLevel and downsample with factorsToPreviousLevel.
// whether it makes sense to actually do so is determined by a
// heuristic based on the following considerations:
// * if downsampling a lot over original image, the cost of
// reading images back from hdf5 outweighs the cost of
// accessing and averaging original pixels.
// * original image may already be cached (for example when
// exporting an ImageJ virtual stack. To compute blocks
// that downsample a lot in Z, many planes of the virtual
// stack need to be accessed leading to cache thrashing if
// individual planes are very large.
useLoopBack = loopbackHeuristic.decide( img, resolutions[ level ], previousLevel, factorsToPreviousLevel, subdivisions[ level ] );
if ( useLoopBack )
{
sourceImg = loopback.getSetupImgLoader( setupIdPartition ).getImage( timepointIdPartition, previousLevel );
factor = factorsToPreviousLevel;
}
else
{
sourceImg = img;
factor = resolutions[ level ];
}
}
sourceImg.dimensions( dimensions );
final boolean fullResolution = ( factor[ 0 ] == 1 && factor[ 1 ] == 1 && factor[ 2 ] == 1 );
long size = 1;
if ( !fullResolution )
{
for ( int d = 0; d < n; ++d )
{
dimensions[ d ] = Math.max( dimensions[ d ] / factor[ d ], 1 );
size *= factor[ d ];
}
}
final double scale = 1.0 / size;
final long[] minRequiredInput = new long[ n ];
final long[] maxRequiredInput = new long[ n ];
sourceImg.min( minRequiredInput );
for ( int d = 0; d < n; ++d )
maxRequiredInput[ d ] = minRequiredInput[ d ] + dimensions[ d ] * factor[ d ] - 1;
final RandomAccessibleInterval< UnsignedShortType > extendedImg = Views.interval( Views.extendBorder( sourceImg ), new FinalInterval( minRequiredInput, maxRequiredInput ) );
final int[] cellDimensions = subdivisions[ level ];
final ViewId viewIdPartition = new ViewId( timepointIdPartition, setupIdPartition );
final String path = Util.getCellsPath( viewIdPartition, level );
writerQueue.createAndOpenDataset( path, dimensions.clone(), cellDimensions.clone(), storage );
final long[] numCells = new long[ n ];
final int[] borderSize = new int[ n ];
final long[] minCell = new long[ n ];
final long[] maxCell = new long[ n ];
for ( int d = 0; d < n; ++d )
{
numCells[ d ] = ( dimensions[ d ] - 1 ) / cellDimensions[ d ] + 1;
maxCell[ d ] = numCells[ d ] - 1;
borderSize[ d ] = ( int ) ( dimensions[ d ] - ( numCells[ d ] - 1 ) * cellDimensions[ d ] );
}
// generate one "plane" of cells after the other to avoid cache thrashing when exporting from virtual stacks
for ( int lastDimCell = 0; lastDimCell < numCells[ n - 1 ]; ++lastDimCell )
{
minCell[ n - 1 ] = lastDimCell;
maxCell[ n - 1 ] = lastDimCell;
final LocalizingIntervalIterator i = new LocalizingIntervalIterator( minCell, maxCell );
final int numThreads = cellCreatorThreads.length;
final CountDownLatch doneSignal = new CountDownLatch( numThreads );
for ( int threadNum = 0; threadNum < numThreads; ++threadNum )
{
cellCreatorThreads[ threadNum ].run( new Runnable()
{
@Override
public void run()
{
final double[] accumulator = fullResolution ? null : new double[ cellDimensions[ 0 ] * cellDimensions[ 1 ] * cellDimensions[ 2 ] ];
final long[] currentCellMin = new long[ n ];
final long[] currentCellMax = new long[ n ];
final long[] currentCellDim = new long[ n ];
final long[] currentCellPos = new long[ n ];
final long[] blockMin = new long[ n ];
final RandomAccess< UnsignedShortType > in = extendedImg.randomAccess();
while ( true )
{
synchronized ( i )
{
if ( !i.hasNext() )
break;
i.fwd();
i.localize( currentCellPos );
}
for ( int d = 0; d < n; ++d )
{
currentCellMin[ d ] = currentCellPos[ d ] * cellDimensions[ d ];
blockMin[ d ] = currentCellMin[ d ] * factor[ d ];
final boolean isBorderCellInThisDim = ( currentCellPos[ d ] + 1 == numCells[ d ] );
currentCellDim[ d ] = isBorderCellInThisDim ? borderSize[ d ] : cellDimensions[ d ];
currentCellMax[ d ] = currentCellMin[ d ] + currentCellDim[ d ] - 1;
}
final ArrayImg< UnsignedShortType, ? > cell = ArrayImgs.unsignedShorts( currentCellDim );
if ( fullResolution )
copyBlock( cell.randomAccess(), currentCellDim, in, blockMin );
else
downsampleBlock( cell.cursor(), accumulator, currentCellDim, in, blockMin, factor, scale );
writerQueue.writeBlockWithOffset( ( ( ShortArray ) cell.update( null ) ).getCurrentStorageArray(), currentCellDim.clone(), currentCellMin.clone() );
}
doneSignal.countDown();
}
} );
}
try
{
doneSignal.await();
}
catch ( final InterruptedException e )
{
e.printStackTrace();
}
if ( afterEachPlane != null )
afterEachPlane.afterEachPlane( useLoopBack );
}
writerQueue.closeDataset();
progressWriter.setProgress( ( double ) numCompletedTasks++ / numTasks );
}
if ( loopback != null )
loopback.close();
}
/**
* A heuristic to decide for a given resolution level whether the source
* pixels should be taken from the original image or read from a previously
* written resolution level in the hdf5 file.
*/
public interface LoopbackHeuristic
{
public boolean decide(
final RandomAccessibleInterval< ? > originalImg,
final int[] factorsToOriginalImg,
final int previousLevel,
final int[] factorsToPreviousLevel,
final int[] chunkSize );
}
public interface AfterEachPlane
{
public void afterEachPlane( final boolean usedLoopBack );
}
/**
* Simple heuristic: use loopback image loader if saving 8 times or more on
* number of pixel access with respect to the original image.
*
* @author Tobias Pietzsch <tobias.pietzsch@gmail.com>
*/
public static class DefaultLoopbackHeuristic implements LoopbackHeuristic
{
@Override
public boolean decide( final RandomAccessibleInterval< ? > originalImg, final int[] factorsToOriginalImg, final int previousLevel, final int[] factorsToPreviousLevel, final int[] chunkSize )
{
if ( previousLevel < 0 )
return false;
if ( numElements( factorsToOriginalImg ) / numElements( factorsToPreviousLevel ) >= 8 )
return true;
return false;
}
}
public static int numElements( final int[] size )
{
int numElements = size[ 0 ];
for ( int d = 1; d < size.length; ++d )
numElements *= size[ d ];
return numElements;
}
public static CellCreatorThread[] createAndStartCellCreatorThreads( final int numThreads )
{
final CellCreatorThread[] cellCreatorThreads = new CellCreatorThread[ numThreads ];
for ( int threadNum = 0; threadNum < numThreads; ++threadNum )
{
cellCreatorThreads[ threadNum ] = new CellCreatorThread();
cellCreatorThreads[ threadNum ].setName( "CellCreatorThread " + threadNum );
cellCreatorThreads[ threadNum ].start();
}
return cellCreatorThreads;
}
public static void stopCellCreatorThreads( final CellCreatorThread[] cellCreatorThreads )
{
for ( final CellCreatorThread thread : cellCreatorThreads )
thread.interrupt();
}
public static class CellCreatorThread extends Thread
{
private Runnable currentTask = null;
public synchronized void run( final Runnable task )
{
currentTask = task;
notify();
}
@Override
public void run()
{
while ( !isInterrupted() )
{
synchronized ( this )
{
try
{
if ( currentTask == null )
wait();
else
{
currentTask.run();
currentTask = null;
}
}
catch ( final InterruptedException e )
{
break;
}
}
}
}
}
private static < T extends RealType< T > > void copyBlock( final RandomAccess< T > out, final long[] outDim, final RandomAccess< T > in, final long[] blockMin )
{
in.setPosition( blockMin );
for ( out.setPosition( 0, 2 ); out.getLongPosition( 2 ) < outDim[ 2 ]; out.fwd( 2 ) )
{
for ( out.setPosition( 0, 1 ); out.getLongPosition( 1 ) < outDim[ 1 ]; out.fwd( 1 ) )
{
for ( out.setPosition( 0, 0 ); out.getLongPosition( 0 ) < outDim[ 0 ]; out.fwd( 0 ), in.fwd( 0 ) )
{
out.get().set( in.get() );
}
in.setPosition( blockMin[ 0 ], 0 );
in.fwd( 1 );
}
in.setPosition( blockMin[ 1 ], 1 );
in.fwd( 2 );
}
}
private static < T extends RealType< T > > void downsampleBlock( final Cursor< T > out, final double[] accumulator, final long[] outDim, final RandomAccess< UnsignedShortType > randomAccess, final long[] blockMin, final int[] blockSize, final double scale )
{
final int numBlockPixels = ( int ) ( outDim[ 0 ] * outDim[ 1 ] * outDim[ 2 ] );
Arrays.fill( accumulator, 0, numBlockPixels, 0 );
randomAccess.setPosition( blockMin );
final int ox = ( int ) outDim[ 0 ];
final int oy = ( int ) outDim[ 1 ];
final int oz = ( int ) outDim[ 2 ];
final int sx = ox * blockSize[ 0 ];
final int sy = oy * blockSize[ 1 ];
final int sz = oz * blockSize[ 2 ];
int i = 0;
for ( int z = 0, bz = 0; z < sz; ++z )
{
for ( int y = 0, by = 0; y < sy; ++y )
{
for ( int x = 0, bx = 0; x < sx; ++x )
{
accumulator[ i ] += randomAccess.get().getRealDouble();
randomAccess.fwd( 0 );
if ( ++bx == blockSize[ 0 ] )
{
bx = 0;
++i;
}
}
randomAccess.move( -sx, 0 );
randomAccess.fwd( 1 );
if ( ++by == blockSize[ 1 ] )
by = 0;
else
i -= ox;
}
randomAccess.move( -sy, 1 );
randomAccess.fwd( 2 );
if ( ++bz == blockSize[ 2 ] )
bz = 0;
else
i -= ox * oy;
}
for ( int j = 0; j < numBlockPixels; ++j )
out.next().setReal( accumulator[ j ] * scale );
}
}
|
package boilerplate.common;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.EventHandler;
import cpw.mods.fml.common.Mod.Instance;
import cpw.mods.fml.common.SidedProxy;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.event.FMLServerStartingEvent;
import net.minecraftforge.common.config.Configuration;
/**
* @author Surseance
*
*/
@Mod(modid = "boilerplate", name = "Boilerplate", version = "4.2.0", dependencies = "after:BuildCraft|Core; after:TConstruct; after:ForgeMultipart; after:MineFactoryReloaded")
public class Boilerplate
{
public static String[] donors = { "ClockwerkKaiser" };
public static String[] devs = { "warlordjones", "decebaldecebal", "Snurly" };
public static int trailParticles;
@SidedProxy(clientSide = "boilerplate.client.ClientProxy", serverSide = "boilerplate.common.CommonProxy")
public static CommonProxy proxy;
@Instance("boilerplate")
public static Boilerplate instance;
@EventHandler
public void preInit(FMLPreInitializationEvent event)
{
Configuration config = new Configuration(event.getSuggestedConfigurationFile());
config.load();
// TODO: particles config option on client only
trailParticles = config.get("general", "numberOfParticlesInDonorTrails", 0, "0 to disable").getInt();
config.save();
}
@EventHandler
public void init(FMLInitializationEvent event)
{
FMLCommonHandler.instance().bus().register(new ForgeEventHandler());
proxy.registerRenderHandlers();
}
@EventHandler
public void postInit(FMLPostInitializationEvent event)
{
/*
* FMLLog.getLogger().info("GNU Terry Prachett"); NBTTagCompound tag =
* new NBTTagCompound(); NBTTagCompound item1 = new NBTTagCompound();
* new ItemStack(Items.cake).writeToNBT(item1); item1.setTag("input1",
* tag); NBTTagCompound item2 = new NBTTagCompound(); new
* ItemStack(Items.apple).writeToNBT(item2); item2.setTag("input2",
* tag); NBTTagCompound item3 = new NBTTagCompound(); new
* ItemStack(Items.baked_potato).writeToNBT(item3);
* item3.setTag("result", tag);
* FMLInterModComms.sendMessage("steamcraft2", "addBloomeryRecipe",
* tag);
*/
}
@EventHandler
public void serverStarting(FMLServerStartingEvent event)
{
}
}
|
package br.uff.ic.utility.graph;
import br.uff.ic.provviewer.VariableNames;
import br.uff.ic.utility.GraphAttribute;
import br.uff.ic.utility.Utils;
import static br.uff.ic.utility.Utils.isItTime;
import java.awt.BasicStroke;
import java.awt.Paint;
import java.awt.Stroke;
import java.util.HashMap;
import java.util.Map;
/**
* Abstract (Generic) vertex type for the provenance graph
*
* Time format must be either a Number or DayNumber:DayName (for the weekend display mode)
* @author Kohwalter
*/
public abstract class Vertex extends GraphObject {
private String id; // prov:id
private double normalizedTime;
// private String time; // prov:startTime
// Refactor for datetime type
private String timeFormat;
private String timeScale;
private String timeLabel = "Timestamp";
/**
* Constructor without attributes
* Using this constructor, attributes must be added later
*
* @param id vertex unique ID
* @param label HUman readable name
* @param time Time-related value. Used for temporal layouts
*/
public Vertex(String id, String label, String time) {
this.id = id;
// this.time = time;
GraphAttribute t = new GraphAttribute(timeLabel, time, "");
this.attributes = new HashMap<>();
this.attributes.put(t.getName(), t);
setLabel(label);
timeFormat = "nanoseconds";
timeScale = "nanoseconds";
}
/**
* Constructor with attributes
* @param id
* @param label
* @param time
* @param attributes
*/
public Vertex(String id, String label, String time, Map<String, GraphAttribute> attributes) {
this.id = id;
this.attributes = new HashMap<>();
this.attributes.putAll(attributes);
GraphAttribute t = new GraphAttribute(timeLabel, time, "");
this.attributes.put(t.getName(), t);
setLabel(label);
timeFormat = "nanoseconds";
timeScale = "nanoseconds";
}
/**
* Return the vertex ID
*
* @return (String) id
*/
public String getID() {
return id;
}
/**
* Set vertex ID
* @param t is the new ID
*/
public void setID(String t) {
id = t;
}
public void setNormalizedTime(double t) {
this.normalizedTime = t;
}
public double getNormalizedTime() {
return this.normalizedTime;
}
/**
* Method for returning the vertex name (not type) from the sub-classes.
* i.e. Agent Vertex name = Kohwalter
*
* @return (String) name
*/
/**
* Method for returning the vertex day (if any)
*
* @return (int) date
*/
public double getTime() {
// String[] day = this.time.split(":");
String time = this.attributes.get(timeLabel).getAverageValue();
if(Utils.tryParseFloat(time))
return (Double.parseDouble(time));
else if(Utils.tryParseDate(time))
{
double milliseconds = Utils.convertStringDateToFloat(time);
return milliseconds;
}
else
return -1;
}
public long getMinTime() {
String time = this.attributes.get(timeLabel).getMin();
if(Utils.tryParseFloat(time))
return (long) ((Float.parseFloat(time))*1000);
else if(Utils.tryParseDate(time))
{
long milliseconds = Utils.convertStringDateToFloat(time);
return milliseconds;
}
else
return -1;
}
/**
* Method to get the value of the variable time
* @return time
*/
public String getTimeString() {
return this.attributes.get(timeLabel).getAverageValue();
}
/**
* Method to set the value of the variable time
* @param t is the new value
*/
public void setTime(String t){
GraphAttribute time = new GraphAttribute(timeLabel, t, "Normalized");
this.attributes.put(timeLabel, time);
}
/**
* (Optional) Method for returning the day of the week instead of the day's
* number.
*
* @return (String) the day of the week (mon, tue, wed, ...)
*/
public String getDayName() {
String[] day = this.attributes.get(timeLabel).getAverageValue().split(":");
return day[1];
}
/**
* This overrides the default JUNG method for displaying information
*
* @return (String) id
*/
@Override
public String toString() {
return this.getNodeType() + "<br> "
+ "<br>ID: " + this.id + "<br>"
+ "<b>Label: " + getLabel() + "</b>"
+ " <br>" + printTime()
+ " <br>"
+ " <br>" + printAttributes();
}
public String getTooltip(int nGraphs) {
return this.getNodeType() + "<br> "
+ "<br>ID: " + this.id + "<br>"
+ "<b>Label: " + getLabel() + "</b>"
+ " <br>" + printTime()
+ "<br>Frequency: " + getFrequency(nGraphs)
+ " <br>"
+ " <br>" + printAttributes();
}
public String printTime()
{
double nt = this.getTime();
return "Timestamp: " + Utils.convertTime(timeFormat, nt, timeScale) + " (" + timeScale + ")";
}
public void setTimeScalePrint(String timeFormat, String timeScale) {
this.timeFormat = timeFormat;
this.timeScale = timeScale;
}
/**
* Method to return the attribute value (not necessarily a number)
* If the attribute does not exist, returns "Unknown"
* @param attribute
* @return
*/
@Override
public String getAttributeValue(String attribute) {
if(attribute.equalsIgnoreCase("Label")) {
return getLabel();
}
GraphAttribute aux = attributes.get(attribute);
if(aux != null) {
return aux.getAverageValue();
}
else {
return deltaAttributeValue(attribute);
// return "Unknown";
}
}
/**
* Method to return the values in an attribute that were separated by a comma
* @param attribute is the attribute that we want to get the values
* @return an array with the values
*/
@Override
public String[] getAttributeValues(String attribute) {
String values = this.getAttributeValue(attribute);
return values.split(", ");
}
/**
* Method to return the attribute value as float
* @param attribute
* @return
*/
public float getAttributeValueFloat(String attribute) {
if(isItTime(attribute)) {
return (float)getNormalizedTime();
}
if(attributes.get(attribute) == null) {
return deltaAttributeFloatValue(attribute);
}
return getAttFloatValue(attribute);
}
/**
* Method that gets both attributes in the string and subtracts them. I.e.: First_Attribute - Second_Attribute
* @param attribute must be a string with both atributes separared by " - ". Example: "First_Attribute - Second_Attribute"
* @return the delta
*/
private float deltaAttributeFloatValue(String attribute) {
String[] atts = attribute.split(" - ");
if(atts.length == 2)
return getAttFloatValue(atts[0]) - getAttFloatValue(atts[1]);
else
return Float.NaN;
}
/**
* Method that returns the delta from the two attributes or Unknown if any attribute is invalid
* @param attribute must be a string with both atributes separared by " - ". Example: "First_Attribute - Second_Attribute"
* @return the delta as a String
*/
private String deltaAttributeValue(String attribute) {
if(attribute.equalsIgnoreCase("Label")) {
return getLabel();
}
if(isItTime(attribute)) {
return String.valueOf(getTime());
}
String[] atts = attribute.split(" - ");
if(atts.length == 2) {
if(VariableNames.UnknownValue.equals(getAttributeValue(atts[0])) || VariableNames.UnknownValue.equals(getAttributeValue(atts[1]))) return VariableNames.UnknownValue;
else {
String delta = Float.toString(getAttFloatValue(atts[0]) - getAttFloatValue(atts[1]));
return delta;
}
}
else
return VariableNames.UnknownValue;
}
/**
* Method that returns the float value of the attribute. If it is not convertable, then it returns Float.NaN
* @param attribute the attribute that we want to get the value from
* @return the float value or Float.NaN if it is not possible to convert to float
*/
private float getAttFloatValue(String attribute) {
if(isItTime(attribute)) {
return (float)getNormalizedTime();
}
if(attributes.get(attribute) != null) {
if(Utils.tryParseFloat(attributes.get(attribute).getAverageValue())) {
return Utils.convertFloat(attributes.get(attribute).getAverageValue());
}
else {
return Float.NaN;
}
}
else {
return Float.NaN;
}
}
/**
* Method for getting the vertex border size
*
* @deprecated use VertexStroke class instead
* @param width Define the border width
* @return (Stroke) returns the new vertex border width
*/
public Stroke getStroke(float width) {
float dash[] = null;
final Stroke nodeStroke = new BasicStroke(width, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, dash, 0.0f);
return nodeStroke;
}
/**
* Method for defining the vertex color
*
* @return (Paint) vertex color
*/
public abstract Paint getColor();
/**
* Method used to identify the vertex type
*
*
* @return (String) vertex type
*/
public abstract String getNodeType();
}
|
package ciir.umass.edu.learning;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import ciir.umass.edu.learning.RankList;
import ciir.umass.edu.metric.MetricScorer;
import ciir.umass.edu.utilities.FileUtils;
import ciir.umass.edu.utilities.MergeSorter;
/**
* @author vdang
*
* This class implements the generic Ranker interface. Each ranking algorithm implemented has to extend this class.
*/
abstract public class Ranker {
public static boolean verbose = true;
protected List<RankList> samples = new ArrayList<RankList>();//training samples
protected int[] features = null;
protected MetricScorer scorer = null;
protected double scoreOnTrainingData = 0.0;
protected double bestScoreOnValidationData = 0.0;
protected List<RankList> validationSamples = null;
protected Ranker()
{
}
protected Ranker(List<RankList> samples, int[] features, MetricScorer scorer)
{
this.samples = samples;
this.features = features;
this.scorer = scorer;
}
//Utility functions
public void setTrainingSet(List<RankList> samples)
{
this.samples = samples;
}
public void setFeatures(int[] features)
{
this.features = features;
}
public void setValidationSet(List<RankList> samples)
{
this.validationSamples = samples;
}
public void setMetricScorer(MetricScorer scorer)
{
this.scorer = scorer;
}
public double getScoreOnTrainingData()
{
return scoreOnTrainingData;
}
public double getScoreOnValidationData()
{
return bestScoreOnValidationData;
}
public int[] getFeatures()
{
return features;
}
public RankList rank(RankList rl)
{
double[] scores = new double[rl.size()];
for(int i=0;i<rl.size();i++)
scores[i] = eval(rl.get(i));
int[] idx = MergeSorter.sort(scores, false);
return new RankList(rl, idx);
}
public List<RankList> rank(List<RankList> l)
{
List<RankList> ll = new ArrayList<RankList>();
for(int i=0;i<l.size();i++)
ll.add(rank(l.get(i)));
return ll;
}
public void save(String modelFile)
{
FileUtils.write(modelFile, "ASCII", model());
}
protected void PRINT(String msg)
{
if(verbose)
System.out.print(msg);
}
protected void PRINTLN(String msg)
{
if(verbose)
System.out.println(msg);
}
protected void PRINT(int[] len, String[] msgs)
{
if(verbose)
{
for(int i=0;i<msgs.length;i++)
{
String msg = msgs[i];
if(msg.length() > len[i])
msg = msg.substring(0, len[i]);
else
while(msg.length() < len[i])
msg += " ";
System.out.print(msg + " | ");
}
}
}
protected void PRINTLN(int[] len, String[] msgs)
{
PRINT(len, msgs);
PRINTLN("");
}
protected void PRINTTIME()
{
DateFormat dateFormat = new SimpleDateFormat("MM/dd HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date));
}
protected void PRINT_MEMORY_USAGE()
{
System.out.println("***** " + Runtime.getRuntime().freeMemory() + " / " + Runtime.getRuntime().maxMemory());
}
protected void copy(double[] source, double[] target)
{
System.arraycopy(source, 0, target, 0, source.length);
}
/**
* HAVE TO BE OVER-RIDDEN IN SUB-CLASSES
* LD 2013/10/09: ...therefore I made them abstract.
*/
abstract public void init();
abstract public void learn();
abstract public double eval(DataPoint p);
abstract public Ranker clone();
abstract public String toString();
abstract public String model();
abstract public void load(String fn);
abstract public void printParameters();
abstract public String name();
}
|
package com.akiban.server.types;
public enum AkType {
LONG {
@Override
void notNullDispatch(ConversionSource source, ConversionTarget target) {
target.setLong(source.getLong());
}
},
DATE {
@Override
void notNullDispatch(ConversionSource source, ConversionTarget target) {
target.setDate(source.getDate());
}
},
STRING {
@Override
void notNullDispatch(ConversionSource source, ConversionTarget target) {
target.setString(source.getString());
}
},
NULL {
@Override
void notNullDispatch(ConversionSource source, ConversionTarget target) {
throw new AssertionError("invoking notNullDispatch on NULL");
}
},
UNSUPPORTED {
@Override
void notNullDispatch(ConversionSource source, ConversionTarget target) {
throw new UnsupportedOperationException();
}
}
;
public void dispatch(ConversionSource source, ConversionTarget target) {
if (source.isNull()) {
target.setNull();
}
else {
notNullDispatch(source, target);
}
}
abstract void notNullDispatch(ConversionSource source, ConversionTarget target);
}
|
package com.altamiracorp.miniweb;
import com.altamiracorp.miniweb.utils.UrlUtils;
import javax.servlet.http.HttpServletRequest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Route {
public static enum Method {GET, POST, PUT, DELETE}
;
private Method method;
private String path;
private Handler[] handlers;
private Pattern componentPattern = Pattern.compile("\\{([_a-zA-Z]+)\\}");
private String[] routePathComponents;
public Route(Method method, String path, Handler... handlers) {
this.method = method;
this.path = path;
this.handlers = handlers;
routePathComponents = splitPathComponents(path);
}
public boolean isMatch(HttpServletRequest request) {
Method requestMethod = Method.valueOf(request.getMethod().toUpperCase());
if (!requestMethod.equals(method)) {
return false;
}
String[] requestPathComponents = splitPathComponents(request.getRequestURI());
if (requestPathComponents.length != routePathComponents.length) {
return false;
}
for (int i = 0; i < routePathComponents.length; i++) {
String routeComponent = routePathComponents[i];
String requestComponent = UrlUtils.urlDecode(requestPathComponents[i]);
Matcher matcher = componentPattern.matcher(routeComponent);
if (matcher.matches()) {
request.setAttribute(matcher.group(1), requestComponent);
} else if (!routeComponent.equals(requestComponent)) {
return false;
}
}
return true;
}
public Handler[] getHandlers() {
return handlers;
}
public Method getMethod() {
return method;
}
public String getPath() {
return path;
}
private String[] splitPathComponents(String path) {
String[] components = path.split("/");
if (components.length > 0){
String[] lastComponents = components[components.length - 1].split("\\.");
if (lastComponents.length > 1) {
String[] allComponents = new String[components.length - 1 + lastComponents.length];
for (int i = 0; i < components.length - 1; i++) {
allComponents[i] = components[i];
}
for (int i = 0; i < lastComponents.length; i++) {
allComponents[components.length + i - 1] = lastComponents[i];
}
return allComponents;
} else {
return components;
}
}
return new String[0];
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.areen.jlib.gui.weber;
import javax.swing.event.*;
import javax.swing.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.text.Document;
/**
A simple Web Weber with minimal functionality.
@author Jose M. Vidal
*/
public class Weber {
JPanel panel;
String title;
String currentUrl;
JEditorPane jep;
LinkFollower linkFollower;
private boolean addressBarEnabled = false;
/** Set the page.
@param jep the pane on which to display the url
@param url the url to display */
protected static void setPage(JEditorPane jep, String argUrl) {
try {
jep.setPage(argUrl);
} catch (IOException e) {
System.err.println(argUrl);
System.err.println(e);
//System.exit(-1);
}
}
/** An inner class which listens for keypresses on the Back button. */
class BackButtonListener implements ActionListener {
protected JEditorPane jep;
protected JLabel label;
protected JButton backButton;
protected Vector history;
public BackButtonListener(JEditorPane jep, JButton backButton, Vector history, JLabel label) {
this.jep = jep;
this.backButton = backButton;
this.history = history;
this.label = label;
}
/** The action is to show the last url in the history.
@param e the event*/
public void actionPerformed(ActionEvent e) {
try {
//the current page is the last, remove it
String curl = (String) history.lastElement();
history.removeElement(curl);
curl = (String) history.lastElement();
System.out.println("Back to " + curl);
setPage(jep, curl);
label.setText("<html><b>URL:</b> " + curl);
if (history.size() == 1) {
backButton.setEnabled(false);
}
} catch (Exception ex) {
System.out.println("Exception " + ex);
}
}
}
/** An inner class that listens for hyperlinkEvent.*/
class LinkFollower implements HyperlinkListener {
protected JEditorPane jep;
protected JLabel label;
protected JButton backButton;
protected Vector history;
private String currentUrl;
public LinkFollower(JEditorPane jep, JButton backButton, Vector history, JLabel label) {
this.jep = jep;
this.backButton = backButton;
this.history = history;
this.label = label;
}
public String getCurrentUrl() {
return currentUrl;
}
/** The action is to show the page of the URL the user clicked on.
@param evt the event. We only care when its type is ACTIVATED. */
public void hyperlinkUpdate(HyperlinkEvent evt) {
if (evt.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
try {
currentUrl = evt.getURL().toString();
history.add(currentUrl);
backButton.setEnabled(true);
System.out.println("Going to " + currentUrl);
setPage(jep, currentUrl);
Object ojb = jep.getDocument().getProperty("title");
if (ojb != null) {
title = (String) ojb;
}
label.setText("<html><b>URL:</b> " + currentUrl + " <b>TITLE:</b>" + title);
} catch (Exception e) {
System.out.println("ERROR: Trouble fetching url");
} // catch
}
} // hyperlinkUpdate() method
} // LinkFollower class (nested)
/** The contructor runs the browser. It displays the main frame with the
fetched initialPage
@param initialPage the first page to show */
public Weber(Container argContainer, String initialPage) {
title = "N/A";
/** A vector of String containing the past urls */
final Vector history = new Vector();
history.add(initialPage);
// set up the editor pane
jep = new JEditorPane();
jep.setEditable(false);
setPage(jep, initialPage);
Object ojb = jep.getDocument().getProperty("title");
if (ojb != null) {
title = (String) ojb;
}
// set up the window
JScrollPane scrollPane = new JScrollPane(jep);
//Label where we show the url
JLabel label = new JLabel("<html><b>URL:</b> " + initialPage);
JButton backButton = new JButton("Back");
backButton.setActionCommand("back");
backButton.setToolTipText("Go to previous page");
backButton.setEnabled(false);
backButton.addActionListener(new BackButtonListener(jep, backButton, history, label));
JButton refreshButton = new JButton("Reload");
refreshButton.setActionCommand("reload");
refreshButton.setToolTipText("Reload the page");
refreshButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Document doc = jep.getDocument();
doc.putProperty(Document.StreamDescriptionProperty, null);
setPage(jep, history.lastElement().toString());
}
});
// A toolbar to hold all our buttons
JToolBar toolBar = new JToolBar();
toolBar.add(backButton);
toolBar.add(refreshButton);
linkFollower = new LinkFollower(jep, backButton, history, label);
jep.addHyperlinkListener(linkFollower);
//Set up the toolbar and scrollbar in the contentpane of the frame
panel = (JPanel) argContainer;
panel.setLayout(new BorderLayout());
panel.setPreferredSize(new Dimension(500, 400));
panel.add(toolBar, BorderLayout.NORTH);
panel.add(scrollPane, BorderLayout.CENTER);
panel.add(label, BorderLayout.SOUTH);
if (!addressBarEnabled) {
label.setVisible(false);
}
} // Weber constructor
public JPanel getPanel() {
return panel;
}
public String getTitle() {
return title;
}
/** Create a Weber object. Use the command-line url if given */
public static void main(String[] args) {
String initialPage = new String("http:
if (args.length > 0) {
initialPage = args[0];
}
JFrame f = new JFrame("Simple Web Browser");
f.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
//Exit the program when user closes window.
f.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}); // WindowListener
Weber b = new Weber(f.getContentPane(), initialPage);
f.pack();
f.setSize(640, 360);
f.setVisible(true);
}
} // Weber class
|
package com.axelby.podax;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.ContentObserver;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.widget.Toast;
import com.axelby.podax.PlayerStatus.PlayerStates;
import com.axelby.podax.ui.MainActivity;
public class PlayerService extends Service {
protected PodcastPlayer _player;
private ContentObserver _podcastChangeObserver = new ContentObserver(new Handler()) {
@Override
public boolean deliverSelfNotifications() {
return false;
}
@Override
public void onChange(boolean selfChange) {
onChange(selfChange, null);
}
@Override
public void onChange(boolean selfChange, Uri uri) {
refreshPodcast();
}
};
private void refreshPodcast() {
if (_player == null)
return;
PlayerStatus status = PlayerStatus.getCurrentState(this);
if (!status.hasActivePodcast()) {
_player.stop();
return;
}
if (status.getPodcastId() != _currentPodcastId) {
_currentPodcastId = status.getPodcastId();
if (!_player.changePodcast(status.getFilename(), status.getPosition() / 1000.0f)) {
_player.stop();
String toastMessage = getResources().getString(R.string.cannot_play_podcast, status.getTitle());
Toast.makeText(this, toastMessage, Toast.LENGTH_LONG).show();
} else {
_player.play();
QueueManager.changeActivePodcast(this, status.getPodcastId());
_lockscreenManager.setupLockscreenControls(this, status);
showNotification();
}
} else {
_player.seekTo(status.getPosition() / 1000.0f);
}
}
private BroadcastReceiver _stopReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
PodaxLog.log(PlayerService.this, "stopping for intent " + intent.getAction());
PlayerService.stop(PlayerService.this);
}
};
private LockscreenManager _lockscreenManager = null;
private long _currentPodcastId;
// static functions for easier controls
public static void play(Context context) {
PlayerService.sendCommand(context, Constants.PLAYER_COMMAND_PLAY);
}
public static void play(Context context, long podcastId) {
QueueManager.changeActivePodcast(context, podcastId);
PlayerService.sendCommand(context, Constants.PLAYER_COMMAND_PLAY);
}
public static void pause(Context context, int pause_reason) {
PlayerService.sendCommand(context, Constants.PLAYER_COMMAND_PAUSE, pause_reason);
}
public static void stop(Context context) {
PlayerService.sendCommand(context, Constants.PLAYER_COMMAND_STOP);
}
public static void playpause(Context context, int pause_reason) {
PlayerService.sendCommand(context, Constants.PLAYER_COMMAND_PLAYPAUSE, pause_reason);
}
public static void playstop(Context context) {
PlayerService.sendCommand(context, Constants.PLAYER_COMMAND_PLAYSTOP);
}
private static void sendCommand(Context context, int command) {
Intent intent = new Intent(context, PlayerService.class);
intent.putExtra(Constants.EXTRA_PLAYER_COMMAND, command);
context.startService(intent);
}
private static void sendCommand(Context context, int command, int arg) {
Intent intent = new Intent(context, PlayerService.class);
intent.putExtra(Constants.EXTRA_PLAYER_COMMAND, command);
intent.putExtra(Constants.EXTRA_PLAYER_COMMAND_ARG, arg);
context.startService(intent);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
registerReceiver(_stopReceiver, new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY));
}
@Override
public void onDestroy() {
unregisterReceiver(_stopReceiver);
}
private void createPlayer() {
if (_player == null) {
_player = new PodcastPlayer(this);
prepareNextPodcast();
// handle errors so the onCompletionListener doens't get called
/*
_player.setOnErrorListener(new OnErrorListener() {
@Override
public boolean onError(MediaPlayer player, int what, int extra) {
String message = String.format(Locale.US, "mediaplayer error - what: %d, extra: %d", what, extra);
PodaxLog.log(PlayerService.this, message);
return true;
}
});
*/
_player.setOnCompletionListener(new PodcastPlayer.OnCompletionListener() {
@Override
public void onCompletion() {
QueueManager.moveToNextInQueue(PlayerService.this);
prepareNextPodcast();
}
});
_player.setOnPlayListener(new PodcastPlayer.OnPlayListener() {
@Override
public void onPlay(float durationInSeconds) {
// set this podcast as active
ContentValues values = new ContentValues(1);
if (durationInSeconds > 0 && durationInSeconds < 60 * 60 * 6)
values.put(PodcastProvider.COLUMN_DURATION, (int)(durationInSeconds * 1000));
values.put(PodcastProvider.COLUMN_ID, _currentPodcastId);
getContentResolver().update(PodcastProvider.ACTIVE_PODCAST_URI, values, null, null);
// listen for changes to the podcast
getContentResolver().registerContentObserver(PodcastProvider.PLAYER_UPDATE_URI, false, _podcastChangeObserver);
// grab the media button
AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
ComponentName eventReceiver = new ComponentName(PlayerService.this, MediaButtonIntentReceiver.class);
audioManager.registerMediaButtonEventReceiver(eventReceiver);
showNotification();
PlayerStatus.updateState(PlayerService.this, PlayerStates.PLAYING);
_lockscreenManager.setLockscreenPlaying();
}
});
_player.setOnPauseListener(new PodcastPlayer.OnPauseListener() {
@Override
public void onPause(float positionInSeconds) {
updateActivePodcastPosition(positionInSeconds);
PlayerStatus.updateState(PlayerService.this, PlayerStatus.PlayerStates.PAUSED);
_lockscreenManager.setLockscreenPaused();
showNotification();
}
});
_player.setOnStopListener(new PodcastPlayer.OnStopListener() {
@Override
public void onStop(float positionInSeconds) {
updateActivePodcastPosition(positionInSeconds);
removeNotification();
if (_lockscreenManager != null)
_lockscreenManager.removeLockscreenControls();
getContentResolver().unregisterContentObserver(_podcastChangeObserver);
PlayerStatus.updateState(PlayerService.this, PlayerStatus.PlayerStates.STOPPED);
stopSelf();
}
});
_player.setOnSeekListener(new PodcastPlayer.OnSeekListener() {
@Override
public void onSeek(float positionInSeconds) {
updateActivePodcastPosition(positionInSeconds);
}
});
}
if (_lockscreenManager == null)
_lockscreenManager = new LockscreenManager();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent == null || intent.getExtras() == null)
return START_NOT_STICKY;
if (!intent.getExtras().containsKey(Constants.EXTRA_PLAYER_COMMAND))
return START_NOT_STICKY;
int pauseReason = intent.getIntExtra(Constants.EXTRA_PLAYER_COMMAND_ARG, -1);
if (_player == null && intent.getExtras().containsKey(Constants.EXTRA_PLAYER_COMMAND))
createPlayer();
switch (intent.getIntExtra(Constants.EXTRA_PLAYER_COMMAND, -1)) {
case -1:
break;
case Constants.PLAYER_COMMAND_PLAYPAUSE:
_player.playPause(pauseReason);
break;
case Constants.PLAYER_COMMAND_PLAYSTOP:
_player.playStop();
break;
case Constants.PLAYER_COMMAND_PLAY:
_player.play();
break;
case Constants.PLAYER_COMMAND_PAUSE:
_player.pause(pauseReason);
break;
case Constants.PLAYER_COMMAND_RESUME:
_player.unpause(pauseReason);
break;
case Constants.PLAYER_COMMAND_STOP:
_player.stop();
break;
case Constants.PLAYER_COMMAND_REFRESHPODCAST:
refreshPodcast();
break;
}
return START_NOT_STICKY;
}
private void prepareNextPodcast() {
PlayerStatus currentState = PlayerStatus.getCurrentState(this);
if (!currentState.hasActivePodcast()) {
_player.stop();
} else {
_player.changePodcast(currentState.getFilename(), currentState.getPosition() / 1000.0f);
_currentPodcastId = currentState.getPodcastId();
}
}
private void showNotification() {
String[] projection = new String[]{
PodcastProvider.COLUMN_ID,
PodcastProvider.COLUMN_TITLE,
PodcastProvider.COLUMN_SUBSCRIPTION_ID,
PodcastProvider.COLUMN_SUBSCRIPTION_TITLE,
PodcastProvider.COLUMN_SUBSCRIPTION_THUMBNAIL,
};
Cursor c = getContentResolver().query(PodcastProvider.ACTIVE_PODCAST_URI, projection, null, null, null);
if (c == null)
return;
if (c.isAfterLast()) {
c.close();
return;
}
PodcastCursor podcast = new PodcastCursor(c);
// both paths use the pendingintent
Intent showIntent = new Intent(this, MainActivity.class);
PendingIntent showPendingIntent = PendingIntent.getActivity(this, 0, showIntent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.icon)
.setWhen(0)
.setContentTitle(podcast.getTitle())
.setContentText(podcast.getSubscriptionTitle())
.setContentIntent(showPendingIntent)
.setOngoing(true)
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
// set up pause intent
Intent pauseIntent = new Intent(this, PlayerService.class);
// use data to make intent unique
pauseIntent.setData(Uri.parse("podax://playercommand/playpause"));
pauseIntent.putExtra(Constants.EXTRA_PLAYER_COMMAND, Constants.PLAYER_COMMAND_PLAYPAUSE);
pauseIntent.putExtra(Constants.EXTRA_PLAYER_COMMAND_ARG, Constants.PAUSE_MEDIABUTTON);
PendingIntent pausePendingIntent = PendingIntent.getService(this, 0, pauseIntent, 0);
// set up forward intent
Intent forwardIntent = new Intent(this, ActivePodcastReceiver.class);
forwardIntent.setData(Constants.ACTIVE_PODCAST_DATA_FORWARD);
PendingIntent forwardPendingIntent = PendingIntent.getService(this, 0, forwardIntent, 0);
Bitmap subscriptionBitmap = Helper.getCachedImage(this, podcast.getSubscriptionThumbnailUrl(), 128, 128);
if (subscriptionBitmap != null)
builder.setLargeIcon(subscriptionBitmap);
if (PlayerStatus.getPlayerState(this) == PlayerStates.PLAYING)
builder.addAction(R.drawable.ic_media_pause_normal, getString(R.string.pause), pausePendingIntent);
else
builder.addAction(R.drawable.ic_media_play_normal, getString(R.string.play), pausePendingIntent);
builder.addAction(R.drawable.ic_media_ff_normal, getString(R.string.fast_forward), forwardPendingIntent);
Notification notification = builder.build();
startForeground(Constants.NOTIFICATION_PLAYING, notification);
c.close();
}
private void removeNotification() {
stopForeground(true);
}
private void updateActivePodcastPosition(float positionInSeconds) {
ContentValues values = new ContentValues();
values.put(PodcastProvider.COLUMN_LAST_POSITION, (int)(positionInSeconds * 1000));
getContentResolver().update(PodcastProvider.PLAYER_UPDATE_URI, values, null, null);
}
}
|
package com.ct.ks.bsc.qte.db;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ct.ks.bsc.qte.core.Constants;
public class SqlRunner {
/**
* log writer for this class
*/
private final Logger log = LoggerFactory.getLogger(SqlRunner.class);
/**
* singleton instance of SqlRunner
*/
private static Map<String, SqlRunner> insts = new HashMap<String, SqlRunner>();
/**
* queryRunner stub
*/
final private QueryRunner queryRunner;
final private String dsName;
/**
* default constructor is made private for singleton call only
*
* @throws Exception
*/
private SqlRunner(String dsName) throws Exception {
this.dsName = dsName;
queryRunner = new QueryRunner(DataSourcePool.getDataSource(dsName));
}
/**
* static method to get an instance of {@link CpdAccess}
*
* @return a singleton instance of {@link CpdAccess}
* @throws Exception
*/
public static SqlRunner getInstance(String dsName) throws Exception {
SqlRunner ret = insts.get(dsName);
if (null == ret) {
ret = new SqlRunner(dsName);
insts.put(dsName, ret);
}
return ret;
}
public static SqlRunner getMasterInstance() throws Exception {
return getInstance(Constants.MASTER_DATASOURCE_NAME);
}
/**
* Call a single prepared insert/update/delete sql statement or procedure/function to database. The connection used
* during call is retrieved from {@link Cpds}.
*
* @param sql
* a prepared sql statement
* @param params
* variable parameters for the prepared sql statement
* @return row count affected
* @throws Exception
*/
public int exec(String sql, Object... params) throws Exception {
Connection conn = DataSourcePool.getConnection(this.dsName);
try {
int ret = 0;
// log.info("SQL=[" + sql + "],PARAM=["
// + StringUtils.join(params, ',') + "]");
ret = queryRunner.update(conn, sql, params);
conn.commit();
return ret;
} catch (SQLException e) {
conn.rollback();
log.error(e.getMessage());
throw new SQLException(e);
} finally {
DbUtils.closeQuietly(conn);
}
}
/**
* Call a single prepared insert/update/delete sql statement or procedure/function to database.
*
* @param conn
* the specified database connection to use for the query execution
* @param sql
* a prepared sql statement
* @param params
* variable parameters for the prepared sql statement
* @return row count affected
* @throws SQLException
*/
public int exec(Connection conn, String sql, Object... params)
throws SQLException {
if (null != conn) {
try {
// log.info("SQL=[" + sql + "],PARAM=["
// + StringUtils.join(params, ',') + "]");
return queryRunner.update(conn, sql, params);
} catch (SQLException e) {
log.error(e.getMessage());
throw new SQLException(e);
}
}
return -1;
}
/**
* Call multiple prepared insert/update/delete sql statements or procedures/functions to database. The connection
* used during call is retrieved from {@link Cpds}.
*
* @param sql
* a prepared sql statement template for multiple iteration of parameters array
* @param params
* an array of variable parameters for the prepared sql statement template
* @return row count affected
* @throws SQLException
*/
public int execBatch(String sql, Object[]... params) throws Exception {
Connection conn = DataSourcePool.getConnection(this.dsName);
try {
// log.info("SQL=[" + sql + "],PARAM=["
// + StringUtils.join(params, ',') + "]");
int[] cs = queryRunner.batch(conn, sql, params);
int ret = 0;
for (int c : cs) {
ret += c;
}
conn.commit();
return ret;
} catch (SQLException e) {
conn.rollback();
log.error(e.getMessage());
throw new SQLException(e);
} finally {
DbUtils.closeQuietly(conn);
}
}
/**
* Call multiple prepared insert/update/delete sql statements or procedures/functions to database.
*
* @param conn
* the specified database connection to use for the query execution
* @param sql
* a prepared sql statement template for multiple iteration of parameters array
* @param params
* an array of variable parameters for the prepared sql statement template
* @return row count affected
* @throws SQLException
*/
public int execBatch(Connection conn, String sql, Object[]... params)
throws SQLException {
if (null != conn) {
try {
// log.info("SQL=[" + sql + "],PARAM=["
// + StringUtils.join(params, ',') + "]");
int[] cs = queryRunner.batch(conn, sql, params);
int ret = 0;
for (int c : cs) {
ret += c;
}
return ret;
} catch (SQLException e) {
log.error(e.getMessage());
throw new SQLException(e);
}
}
return -1;
}
/**
* Call multiple insert/update/delete normal sql statements to database. The connection used during call is
* retrieved from {@link Cpds}.
*
* @param sqls
* list of normal sql statements
* @return row count affected
* @throws SQLException
*/
public int execBatch(List<String> sqls) throws Exception {
Connection conn = null;
try {
conn = DataSourcePool.getConnection(this.dsName);
conn.setAutoCommit(false);
int ret = 0;
if (null != sqls) {
final int sqlCnt = sqls.size();
for (int i = 0; i < sqlCnt; i++) {
// log.info("SQL=[" + sqls.get(i) + "]");
ret += queryRunner.update(conn, sqls.get(i));
}
}
conn.commit();
return ret;
} catch (SQLException e) {
conn.rollback();
log.error(e.getMessage());
throw new SQLException(e);
} finally {
DbUtils.closeQuietly(conn);
}
}
/**
* Query a bean object of specified type from a record of query result. The connection used during call is retrieved
* from {@link Cpds}.
*
* @param <T>
* type of bean
* @param clazz
* the class of type T
* @param sql
* a prepared "select ... from" statement, while ... are field names matching all the member names
* defined in class T
* @param params
* variable parameters for the prepared sql statement
* @return an object of the type T as first record in resultset, or null if no records found
* @throws SQLException
*/
public <T> T queryObj(Class<T> clazz, String sql, Object... params)
throws Exception {
Connection conn = null;
try {
conn = DataSourcePool.getConnection(this.dsName);
// log.info("SQL=[" + sql + "],PARAM=["
// + StringUtils.join(params, ',') + "]");
return queryRunner.query(conn, sql, new BeanHandler<T>(clazz),
params);
} catch (SQLException e) {
log.error(e.getMessage());
throw new SQLException(e);
} finally {
DbUtils.closeQuietly(conn);
}
}
/**
* Query a bean object of specified type from a record of query result.
*
* @param <T>
* type of bean
* @param conn
* the specified database connection to use for the query execution
* @param clazz
* the class of type T
* @param sql
* a prepared "select ... from" statement, while ... are field names matching all the member names
* defined in class T
* @param params
* variable parameters for the prepared sql statement
* @return an object of the type T as first record in resultset, or null if no records found
* @throws SQLException
*/
public <T> T queryObj(Connection conn, Class<T> clazz, String sql,
Object... params) throws SQLException {
try {
// log.info("SQL=[" + sql + "],PARAM=["
// + StringUtils.join(params, ',') + "]");
return queryRunner.query(conn, sql, new BeanHandler<T>(clazz),
params);
} catch (SQLException e) {
log.error(e.getMessage());
throw new SQLException(e);
}
}
/**
* Query a list of bean objects of specified type from records of query result. The connection used during call is
* retrieved from {@link Cpds}.
*
* @param <T>
* type of bean
* @param clazz
* the class of type T
* @param sql
* a prepared "select ... from" statement, while ... are field names matching all the member names
* defined in class T
* @param params
* variable parameters for the prepared sql statement
* @return a list of objects of the type T, if no records found, the list is empty
* @throws SQLException
*/
public <T> List<T> queryObjs(Class<T> clazz, String sql, Object... params)
throws Exception {
Connection conn = null;
try {
conn = DataSourcePool.getConnection(this.dsName);
// log.info("SQL=[" + sql + "],PARAM=["
// + StringUtils.join(params, ',') + "]");
return queryRunner.query(conn, sql, new BeanListHandler<T>(clazz),
params);
} catch (SQLException e) {
log.error(e.getMessage());
throw new SQLException(e);
} finally {
DbUtils.closeQuietly(conn);
}
}
/**
* Query a list of bean objects of specified type from records of query result.
*
* @param <T>
* type of bean
* @param conn
* the specified database connection to use for the query execution
* @param clazz
* the class of type T
* @param sql
* a prepared "select ... from" statement, while ... are field names matching all the member names
* defined in class T
* @param params
* variable parameters for the prepared sql statement
* @return a list of objects of the type T, if no records found, the list is empty
* @throws SQLException
*/
public <T> List<T> queryObjs(Connection conn, Class<T> clazz, String sql,
Object... params) throws SQLException {
try {
// log.info("SQL=[" + sql + "],PARAM=["
// + StringUtils.join(params, ',') + "]");
return queryRunner.query(conn, sql, new BeanListHandler<T>(clazz),
params);
} catch (SQLException e) {
log.error(e.getMessage());
throw new SQLException(e);
}
}
/**
* Query a prepared sql statement and return a SqlResultSet. The connection used during call is retrieved from
* {@link Cpds}.
*
* @param sql
* a prepared sql statement
* @param params
* variable parameters for the prepared sql statement
* @return a custom wrapped result set
* @throws SQLException
*/
public SqlResultSet query(String sql, Object... params) throws Exception {
ResultSetHandler<SqlResultSet> h = new ResultSetHandler<SqlResultSet>() {
@Override
public SqlResultSet handle(ResultSet rs) throws SQLException {
ResultSetMetaData meta = rs.getMetaData();
final int cols = meta.getColumnCount();
String[] colNames = new String[cols];
for (int i = 0; i < cols; i++) {
colNames[i] = meta.getColumnName(i + 1);
}
List<Object[]> result = new ArrayList<Object[]>();
Object[] arow = null;
while (rs.next()) {
arow = new Object[cols];
for (int i = 0; i < cols; i++) {
arow[i] = rs.getObject(i + 1);
}
result.add(arow);
}
rs.close();
return new SqlResultSet(colNames, result);
}
};
Connection conn = null;
try {
conn = DataSourcePool.getConnection(this.dsName);
// log.info("SQL=[" + sql + "],PARAM=["
// + StringUtils.join(params, ',') + "]");
return queryRunner.query(conn, sql, h, params);
} catch (SQLException e) {
log.error(e.getMessage());
throw new SQLException(e);
} finally {
DbUtils.closeQuietly(conn);
}
}
/**
* Query a prepared sql statement and return a SqlResultSet.
*
* @param conn
* the specified database connection to use for the query execution
*
* @param sql
* a prepared sql statement
* @param params
* variable parameters for the prepared sql statement
* @return a custom wrapped result set
* @throws SQLException
*/
@SuppressWarnings("unchecked")
public SqlResultSet query(Connection conn, String sql, Object... params)
throws SQLException {
@SuppressWarnings("rawtypes")
ResultSetHandler h = new ResultSetHandler() {
@Override
public SqlResultSet handle(ResultSet rs) throws SQLException {
ResultSetMetaData meta = rs.getMetaData();
final int cols = meta.getColumnCount();
String[] colNames = new String[cols];
for (int i = 0; i < cols; i++) {
colNames[i] = meta.getColumnName(i + 1);
}
List<Object[]> result = new ArrayList<Object[]>();
Object[] arow = null;
while (rs.next()) {
arow = new Object[cols];
for (int i = 0; i < cols; i++) {
arow[i] = rs.getObject(i + 1);
}
result.add(arow);
}
rs.close();
return new SqlResultSet(colNames, result);
}
};
try {
// log.info("SQL=[" + sql + "],PARAM=["
// + StringUtils.join(params, ',') + "]");
return (SqlResultSet) queryRunner.query(conn, sql, h, params);
} catch (SQLException e) {
log.error(e.getMessage());
throw new SQLException(e);
}
}
/**
* Get a list of objects of specified simple type from first column in records of query result. The connection used
* during call is retrieved from {@link Cpds}.
*
* @param <T>
* simple type (Integer/Long/Double/Number/String/Timestamp...)
* @param clazz
* the class of type T
* @param sql
* a prepared "select field from table" statement
* @param params
* variable parameters for the prepared sql statement
* @return a list of objects of the simple type T as first column from query result, if no records found, the list
* is empty
* @throws SQLException
*/
@SuppressWarnings("unchecked")
public <T> List<T> query1stCol(Class<T> clazz, String sql, Object... params)
throws Exception {
List<T> ret = new ArrayList<T>();
SqlResultSet rs = null;
Connection conn = null;
try {
conn = DataSourcePool.getConnection(this.dsName);
// log.info("SQL=[" + sql + "],PARAM=[" + StringUtils.join(params,
rs = query(conn, sql, params);
} catch (SQLException e) {
log.error(e.getMessage());
throw new SQLException(e);
} finally {
DbUtils.closeQuietly(conn);
}
if (null != rs) {
final int rowCnt = rs.getRowCount();
for (int i = 0; i < rowCnt; i++) {
ret.add((T) rs.getCell(i, 0));
}
}
return ret;
}
/**
* Get a list of objects of specified simple type from first column in records of query result.
*
* @param <T>
* simple type (Integer/Long/Double/Number/String/Timestamp...)
* @param conn
* the specified database connection to use for the query execution
*
* @param clazz
* the class of type T
* @param sql
* a prepared "select field from table" statement
* @param params
* variable parameters for the prepared sql statement
* @return a list of objects of the simple type T as first column from query result, if no records found, the list
* is empty
* @throws SQLException
*/
@SuppressWarnings("unchecked")
public <T> List<T> query1stCol(Connection conn, Class<T> clazz, String sql,
Object... params) throws SQLException {
List<T> ret = new ArrayList<T>();
SqlResultSet rs = null;
try {
// log.info("SQL=[" + sql + "],PARAM=[" + StringUtils.join(params,
rs = query(conn, sql, params);
} catch (SQLException e) {
log.error(e.getMessage());
throw new SQLException(e);
}
if (null != rs) {
final int rowCnt = rs.getRowCount();
for (int i = 0; i < rowCnt; i++) {
ret.add((T) rs.getCell(i, 0));
}
}
return ret;
}
@SuppressWarnings("unchecked")
public <V> Map<Long, V> query1st2ColsAsMap(Class<V> valClazz, String sql,
Object... params) throws Exception {
Map<Long, V> ret = new LinkedHashMap<Long, V>();
SqlResultSet rs = null;
try {
// log.info("SQL=[" + sql + "],PARAM=[" + StringUtils.join(params,
rs = query(sql, params);
} catch (SQLException e) {
log.error(e.getMessage());
throw new SQLException(e);
}
if (null != rs) {
final int rowCnt = rs.getRowCount();
for (int i = 0; i < rowCnt; i++) {
ret.put(((BigDecimal) rs.getCell(i, 0)).longValue(),
(V) rs.getCell(i, 1));
}
}
return ret;
}
@SuppressWarnings("unchecked")
public <V> Map<Long, V> query1st2ColsAsMap(Connection conn,
Class<V> valClazz, String sql, Object... params)
throws SQLException {
Map<Long, V> ret = new LinkedHashMap<Long, V>();
SqlResultSet rs = null;
try {
// log.info("SQL=[" + sql + "],PARAM=[" + StringUtils.join(params,
rs = query(conn, sql, params);
} catch (SQLException e) {
log.error(e.getMessage());
throw new SQLException(e);
}
if (null != rs) {
final int rowCnt = rs.getRowCount();
for (int i = 0; i < rowCnt; i++) {
ret.put(((BigDecimal) rs.getCell(i, 0)).longValue(),
(V) rs.getCell(i, 1));
}
}
return ret;
}
@SuppressWarnings("unchecked")
public <V> Map<Integer, V> query1st2ColsAsMapInt(Class<V> valClazz,
String sql, Object... params) throws Exception {
Map<Integer, V> ret = new LinkedHashMap<Integer, V>();
SqlResultSet rs = null;
try {
// log.info("SQL=[" + sql + "],PARAM=[" + StringUtils.join(params,
rs = query(sql, params);
} catch (SQLException e) {
log.error(e.getMessage());
throw new SQLException(e);
}
if (null != rs) {
final int rowCnt = rs.getRowCount();
for (int i = 0; i < rowCnt; i++) {
ret.put(((BigDecimal) rs.getCell(i, 0)).intValue(),
(V) rs.getCell(i, 1));
}
}
return ret;
}
@SuppressWarnings("unchecked")
public <V> Map<Integer, V> query1st2ColsAsMapInt(Connection conn,
Class<V> valClazz, String sql, Object... params)
throws SQLException {
Map<Integer, V> ret = new LinkedHashMap<Integer, V>();
SqlResultSet rs = null;
try {
// log.info("SQL=[" + sql + "],PARAM=[" + StringUtils.join(params,
rs = query(conn, sql, params);
} catch (SQLException e) {
log.error(e.getMessage());
throw new SQLException(e);
}
if (null != rs) {
final int rowCnt = rs.getRowCount();
for (int i = 0; i < rowCnt; i++) {
ret.put(((BigDecimal) rs.getCell(i, 0)).intValue(),
(V) rs.getCell(i, 1));
}
}
return ret;
}
/**
* Get a map of specified simple types as <Key,Value> from first and second column in records of query result. The
* connection used during call is retrieved from {@link Cpds}.
*
* @param <K>
* simple types as key (Integer/Long/Double/Number/String...)
* @param <V>
* simple types as value (Integer/Long/Double/Number/String...)
* @param kClazz
* the class of type K
* @param valClazz
* the class of type V
* @param sql
* a prepared "select ... from" statement
* @param params
* variable parameters for the prepared sql statement
* @return a map of <K,V> entries of the type K as first column as key and type V as secound column as V from query
* result, if no records found, the map is empty
* @throws SQLException
*/
@SuppressWarnings("unchecked")
public <K, V> Map<K, V> query1st2ColsAsMap(Class<K> kClazz,
Class<V> valClazz, String sql, Object... params)
throws Exception {
Map<K, V> ret = new LinkedHashMap<K, V>();
SqlResultSet rs = null;
Connection conn = null;
try {
conn = DataSourcePool.getConnection(this.dsName);
// log.info("SQL=[" + sql + "],PARAM=[" + StringUtils.join(params,
rs = query(conn, sql, params);
} catch (SQLException e) {
log.error(e.getMessage());
throw new SQLException(e);
} finally {
DbUtils.closeQuietly(conn);
}
if (null != rs) {
final int rowCnt = rs.getRowCount();
for (int i = 0; i < rowCnt; i++) {
ret.put((K) rs.getCell(i, 0), (V) rs.getCell(i, 1));
}
}
return ret;
}
/**
* Get a map of specified simple types as <Key,Value> from first and second column in records of query result.
*
* @param <K>
* simple types as key (Integer/Long/Double/Number/String...)
* @param <V>
* simple types as value (Integer/Long/Double/Number/String...)
* @param conn
* the specified database connection to use for the query execution
*
* @param kClazz
* the class of type K
* @param valClazz
* the class of type V
* @param sql
* a prepared "select ... from" statement
* @param params
* variable parameters for the prepared sql statement
* @return a map of <K,V> entries of the type K as first column as key and type V as secound column as V from query
* result, if no records found, the map is empty
* @throws SQLException
*/
@SuppressWarnings("unchecked")
public <K, V> Map<K, V> query1st2ColsAsMap(Connection conn,
Class<K> kClazz, Class<V> valClazz, String sql, Object... params)
throws SQLException {
Map<K, V> ret = new LinkedHashMap<K, V>();
SqlResultSet rs = null;
try {
// log.info("SQL=[" + sql + "],PARAM=[" + StringUtils.join(params,
rs = query(conn, sql, params);
} catch (SQLException e) {
log.error(e.getMessage());
throw new SQLException(e);
}
if (null != rs) {
final int rowCnt = rs.getRowCount();
for (int i = 0; i < rowCnt; i++) {
ret.put((K) rs.getCell(i, 0), (V) rs.getCell(i, 1));
}
}
return ret;
}
/**
* Get an object from first cell (1st column 1st row) in query result. The connection used during call is retrieved
* from {@link Cpds}.
*
* @param sql
* a prepared "select ... from" statement
* @param params
* variable parameters for the prepared sql statement
* @return the value of first cell from query result as an object(could be casted to String/Number/Timestamp...), if
* no records found, this object is null
* @throws SQLException
*/
public Object query1stCell(String sql, Object... params)
throws Exception {
SqlResultSet rs = null;
Connection conn = null;
try {
conn = DataSourcePool.getConnection(this.dsName);
// log.info("SQL=[" + sql + "],PARAM=[" + StringUtils.join(params,
rs = query(conn, sql, params);
} catch (SQLException e) {
log.error(e.getMessage());
throw new SQLException(e);
} finally {
DbUtils.closeQuietly(conn);
}
if (null != rs && rs.getRowCount() > 0) {
return rs.getCell(0, 0);
}
return null;
}
/**
* Get an object from first cell (1st column 1st row) in query result.
*
* @param conn
* the specified database connection to use for the query execution
* @param sql
* a prepared "select ... from" statement
* @param params
* variable parameters for the prepared sql statement
* @return the value of first cell from query result as an object(could be casted to String/Number/Timestamp...), if
* no records found, this object is null
* @throws SQLException
*/
public Object query1stCell(Connection conn, String sql, Object... params)
throws SQLException {
SqlResultSet rs = null;
try {
// log.info("SQL=[" + sql + "],PARAM=[" + StringUtils.join(params,
rs = query(conn, sql, params);
} catch (SQLException e) {
log.error(e.getMessage());
throw new SQLException(e);
}
if (null != rs && rs.getRowCount() > 0) {
return rs.getCell(0, 0);
}
return null;
}
}
|
package com.cx.plugin;
import com.cx.client.*;
import com.cx.client.dto.*;
import com.cx.client.exception.CxClientException;
import com.cx.client.rest.dto.CreateOSAScanResponse;
import com.cx.client.rest.dto.OSASummaryResults;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.model.Resource;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.archiver.Archiver;
import org.codehaus.plexus.archiver.zip.ZipArchiver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.impl.MavenLoggerAdapter;
import java.io.*;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Set;
public abstract class CxAbstractPlugin extends AbstractMojo {
public static final String SOURCES_ZIP_NAME = "sources";
public static final String OSA_ZIP_NAME = "OSAScan";
public static final String PDF_REPORT_NAME = "CxReport";
public static final String OSA_REPORT_NAME = "OSA_Report";
private static Logger log = LoggerFactory.getLogger(CxAbstractPlugin.class);
/**
* The username of the user running the scan.
*/
@Parameter(required = true, property = "cx.username")
protected String username;
/**
* The password of the user running the scan.
*/
@Parameter(required = true, property = "cx.password")
protected String password;
/**
* Host name of the Checkmarx application.
*/
@Parameter(defaultValue = "http://localhost", property = "cx.url")
protected URL url;
/**
* The name of the project being scanned.
*/
@Parameter(defaultValue = "${project.name}", property = "cx.projectName")
protected String projectName;
/**
* The full path describing the team the scan belongs to.
*/
@Parameter(property = "cx.fullTeamPath", defaultValue = "CxServer")
protected String fullTeamPath;
/**
* Configure this field to scan the project with one of the predefined scan presets, or one of your custom presets.
*/
@Parameter(defaultValue = "Checkmarx Default", property = "cx.preset")
protected String preset;
/**
* If true, an incremental scan will be performed, meaning - only modified files will be scanned.
*/
@Parameter(defaultValue = "true", property = "cx.isIncrementalScan")
protected boolean isIncrementalScan;
/**
* Configure this field if you want the scan to skip certain folders.
*/
@Parameter(property = "cx.folderExclusions")
protected String[] folderExclusions = new String[0];
/**
* Configure this field if you want the scan to skip certain files.
*/
@Parameter(property = "cx.fileExclusions")
protected String[] fileExclusions = new String[0];
/**
* If true, a synchronous scan will be performed - the scan will run until finished, and produce a results page.
* If false, the scan will be asynchronous - the scan will run in the background,
* and the results will appear, when finished, on the Checkmarx application.
*/
@Parameter(defaultValue = "true", property = "cx.isSynchronous")
protected boolean isSynchronous;
/**
* If true, a PDF results page will be generated.
*/
@Parameter(defaultValue = "true", property = "cx.generatePDFReport")
protected boolean generatePDFReport;
/**
* Configure a threshold for the High Severity Vulnerabilities.
* The scan will not fail if lower sum of High Severity Vulnerabilities is found.
* Set to -1 to ignore threshold.
*/
@Parameter(defaultValue = "-1", property = "cx.highSeveritiesThreshold")
protected int highSeveritiesThreshold;
/**
* Configure a threshold for the Medium Severity Vulnerabilities.
* The scan will not fail if lower sum of Medium Severity Vulnerabilities is found.
* Set to -1 to ignore threshold.
*/
@Parameter(defaultValue = "-1", property = "cx.mediumSeveritiesThreshold")
protected int mediumSeveritiesThreshold;
/**
* Configure a threshold for the Low Severity Vulnerabilities.
* The scan will not fail if lower sum of Low Severity Vulnerabilities is found.
* Set to -1 to ignore threshold.
*/
@Parameter(defaultValue = "-1", property = "cx.lowSeveritiesThreshold")
protected int lowSeveritiesThreshold;
/**
* Define a timeout (in minutes) for the scan. If the specified time has passed, the build is failed.
* Set to 0 to run the scan with no time limit.
*/
@Parameter(defaultValue = "0", property = "cx.scanTimeoutInMinuets")
protected int scanTimeoutInMinuets;
@Parameter(defaultValue = "false", property = "cx.osaEnabled")
protected boolean osaEnabled;
@Parameter(property = "cx.osaExclusions")
protected String[] osaExclusions = new String[0];
@Parameter(defaultValue = "-1", property = "cx.osaHighSeveritiesThreshold")
protected int osaHighSeveritiesThreshold;
@Parameter(defaultValue = "-1", property = "cx.osaMediumSeveritiesThreshold")
protected int osaMediumSeveritiesThreshold;
@Parameter(defaultValue = "-1", property = "cx.osaLowSeveritiesThreshold")
protected int osaLowSeveritiesThreshold;
@Parameter(defaultValue = "true", property = "cx.osaGeneratePDFReport")
protected boolean osaGeneratePDFReport;
@Parameter(defaultValue = "true", property = "cx.osaGenerateHTMLReport")
protected boolean osaGenerateHTMLReport;
/**
* Define an output directory for the scan results.
*/
@Parameter(defaultValue = "${project.build.directory}\\checkmarx", property = "cx.outputDirectory")
protected File outputDirectory;
@Parameter(defaultValue = "${project}", readonly = true, required = true)
protected MavenProject project;
@Parameter(defaultValue = "${reactorProjects}", readonly = true)
protected List<MavenProject> reactorProjects;
@Component(role = Archiver.class, hint = "zip")
protected ZipArchiver zipArchiver;
protected CxClientService cxClientService;
protected String scanResultsUrl;
protected String projectStateLink;
public void execute() throws MojoExecutionException, MojoFailureException {
MavenLoggerAdapter.setLogger(getLog());
ScanResults scanResults = null;
OSASummaryResults osaSummaryResults = null;
Exception osaCreateException = null;
Exception scanWaitException = null;
if (shouldSkip()) {
log.info("Project Has No Sources (Reactor), Skipping");
return;
}
try {
printConfiguration();
//initialize cx client
log.debug("Initializing Cx Client");
cxClientService = new CxClientServiceImpl(url, username, password);
//perform login to server
log.info("Logging In to Checkmarx Service.");
cxClientService.loginToServer();
//prepare sources to scan (zip them)
log.info("Zipping Sources");
zipSources();
//send sources to scan
byte[] zippedSources = getBytesFromZippedSources();
LocalScanConfiguration conf = generateScanConfiguration(zippedSources);
log.info("Creating Scan");
CreateScanResponse createScanResponse = cxClientService.createLocalScanResolveFields(conf);
projectStateLink = CxPluginHelper.composeProjectStateLink(url.toString(), createScanResponse.getProjectId());
log.info("Scan Created Successfully. Link to Project State: " + projectStateLink);
CreateOSAScanResponse osaScan = null;
if (osaEnabled) {
try {
log.info("creating OSA scan");
log.info("zipping dependencies");
File zipForOSA = createZipForOSA();
log.info("sending OSA scan request");
osaScan = cxClientService.createOSAScan(createScanResponse.getProjectId(), zipForOSA);
log.info("OSA scan created successfully");
} catch (Exception e) {
osaCreateException = e;
}
}
if (!isSynchronous) {
if(osaCreateException != null) {
throw osaCreateException;
}
log.info("Running in Asynchronous Mode. Not Waiting for Scan to Finish");
return;
}
//wait for sast scan to finish
try {
log.info("Waiting For Scan To Finish.");
cxClientService.waitForScanToFinish(createScanResponse.getRunId(), scanTimeoutInMinuets, new ConsoleScanWaitHandler());
log.info("Scan Finished. Retrieving Scan Results");
scanResults = cxClientService.retrieveScanResults(createScanResponse.getProjectId());
scanResultsUrl = CxPluginHelper.composeScanLink(url.toString(), scanResults);
printResultsToConsole(scanResults);
/* log.info("Generating HTML Report");
generateHTMLReport(scanResults.getScanID());*/
//create scan report
if (generatePDFReport) {
createPDFReport(scanResults.getScanID());
}
} catch (Exception e) {
log.error("fail to perform scan: " + e.getMessage());
log.debug("", e);
scanWaitException = e;
}
if (osaEnabled) {
if(osaCreateException != null) {
throw osaCreateException;
}
log.info("Waiting for OSA Scan to Finish");
cxClientService.waitForOSAScanToFinish(osaScan.getScanId(), -1, new OSAConsoleScanWaitHandler());
log.info("OSA Scan Finished Successfully");
log.info("Creating OSA Reports");
osaSummaryResults = cxClientService.retrieveOSAScanSummaryResults(createScanResponse.getProjectId());
printOSAResultsToConsole(osaSummaryResults);
String now = DateFormatUtils.format(new Date(), "dd_MM_yyyy-HH_mm_ss");
if (osaGeneratePDFReport) {
byte[] osaPDF = cxClientService.retrieveOSAScanPDFResults(createScanResponse.getProjectId());
String pdfFileName = OSA_REPORT_NAME + "_" + now + ".pdf";
FileUtils.writeByteArrayToFile(new File(outputDirectory, pdfFileName), osaPDF);
log.info("OSA PDF Report Can Be Found in: " + outputDirectory + "\\" + pdfFileName);
}
if (osaGenerateHTMLReport) {
String osaHtml = cxClientService.retrieveOSAScanHtmlResults(createScanResponse.getProjectId());
String htmlFileName = OSA_REPORT_NAME + "_" + now + ".html";
FileUtils.writeStringToFile(new File(outputDirectory, htmlFileName), osaHtml, Charset.defaultCharset());
log.info("OSA HTML Report Can Be Found in: " + outputDirectory + "\\" + htmlFileName);
}
}
if(scanWaitException != null) {
throw scanWaitException;
}
} catch (CxClientException e) {
log.debug("Caught Exception: ", e);
throw new MojoExecutionException(e.getMessage());
} catch (Exception e) {
log.debug("Unexpected Exception:", e);
throw new MojoExecutionException(e.getMessage());
}
//assert vulnerabilities under threshold
assertVulnerabilities(scanResults, osaSummaryResults);
}
private void printConfiguration() {
log.info("
log.info("username: " + username);
log.info("url: " + url);
log.info("projectName: " + projectName);
log.info("fullTeamPath: " + fullTeamPath);
log.info("preset: " + preset);
log.info("isIncrementalScan: " + isIncrementalScan);
log.info("folderExclusions: " + Arrays.toString(folderExclusions));
log.info("fileExclusions: " + Arrays.toString(fileExclusions));
log.info("isSynchronous: " + isSynchronous);
log.info("generatePDFReport: " + generatePDFReport);
log.info("highSeveritiesThreshold: " + (highSeveritiesThreshold < 0 ? "[No Threshold]" : highSeveritiesThreshold));
log.info("mediumSeveritiesThreshold: " + (mediumSeveritiesThreshold < 0 ? "[No Threshold]" : mediumSeveritiesThreshold));
log.info("lowSeveritiesThreshold: " + (lowSeveritiesThreshold < 0 ? "[No Threshold]" : lowSeveritiesThreshold));
log.info("scanTimeoutInMinuets: " + scanTimeoutInMinuets);
log.info("outputDirectory: " + outputDirectory);
log.info("osaEnabled: " + osaEnabled);
if (osaEnabled) {
log.info("osaExclusions: " + Arrays.toString(osaExclusions));
log.info("osaHighSeveritiesThreshold: " + (osaHighSeveritiesThreshold < 0 ? "[No Threshold]" : osaHighSeveritiesThreshold));
log.info("osaMediumSeveritiesThreshold: " + (osaMediumSeveritiesThreshold < 0 ? "[No Threshold]" : osaMediumSeveritiesThreshold));
log.info("osaLowSeveritiesThreshold: " + (osaLowSeveritiesThreshold < 0 ? "[No Threshold]" : osaLowSeveritiesThreshold));
log.info("osaGeneratePDFReport: " + osaGeneratePDFReport);
log.info("osaGenerateHTMLReport: " + osaGenerateHTMLReport);
}
log.info("
}
private void printResultsToConsole(ScanResults scanResults) {
log.info("
log.info("High Severity Results: " + scanResults.getHighSeverityResults());
log.info("Medium Severity Results: " + scanResults.getMediumSeverityResults());
log.info("Low Severity Results: " + scanResults.getLowSeverityResults());
log.info("Info Severity Results: " + scanResults.getInfoSeverityResults());
log.info("Scan Results Can Be Found at: " + scanResultsUrl);
log.info("
}
private void printOSAResultsToConsole(OSASummaryResults osaSummaryResults) {
log.info("
log.info("");
log.info("
log.info("Vulnerabilities Summary:");
log.info("
log.info("OSA High Severity Results: " + osaSummaryResults.getHighVulnerabilities());
log.info("OSA Medium Severity Results: " + osaSummaryResults.getMediumVulnerabilities());
log.info("OSA Low Severity Results: " + osaSummaryResults.getLowVulnerabilities());
log.info("Vulnerability Score: " + osaSummaryResults.getVulnerabilityScore());
log.info("");
log.info("
log.info("Libraries Scan Results:");
log.info("
log.info("Open Source Libraries: " + osaSummaryResults.getTotalLibraries());
log.info("Vulnerable And Outdated: " + osaSummaryResults.getVulnerableAndOutdated());
log.info("Vulnerable And Updated: " + osaSummaryResults.getVulnerableAndUpdated());
log.info("Non Vulnerable Libraries: " + osaSummaryResults.getNonVulnerableLibraries());
log.info("");
log.info("OSA Scan Results Can Be Found at: " + projectStateLink.replace("Summary", "OSA"));
log.info("
}
protected void generateHTMLReport(long scanId) {
try {
byte[] scanReport = cxClientService.getScanReport(scanId, ReportType.CSV);
String csv = new String(scanReport);
String now = DateFormatUtils.format(new Date(), "dd_MM_yyyy-HH_mm_ss");
String htmlFileName = "report" + "_" + now + ".html";
File htmlReportFile = new File(outputDirectory + "\\" + htmlFileName);
String html = CxPluginHelper.compileHtmlReport(csv, highSeveritiesThreshold, mediumSeveritiesThreshold, lowSeveritiesThreshold);
if (html != null) {
FileUtils.writeStringToFile(htmlReportFile, html, Charset.defaultCharset());
log.info("HTML Report Can Be Found in: " + outputDirectory + "\\" + htmlFileName);
} else {
log.warn("Fail To Generate HTML Report");
}
} catch (Exception e) {
log.warn("Fail To Generate HTML Report");
log.debug("Fail To Generate HTML Report: ", e);
}
}
private LocalScanConfiguration generateScanConfiguration(byte[] zippedSources) {
LocalScanConfiguration ret = new LocalScanConfiguration();
ret.setProjectName(projectName);
ret.setClientOrigin(ClientOrigin.MAVEN);
ret.setFileExclusions(CxPluginHelper.convertArrayToString(fileExclusions));
ret.setFolderExclusions(CxPluginHelper.convertArrayToString(folderExclusions));
ret.setFullTeamPath(fullTeamPath);
ret.setIncrementalScan(isIncrementalScan);
ret.setPreset(preset);
ret.setZippedSources(zippedSources);
ret.setFileName(projectName);
return ret;
}
private void assertVulnerabilities(ScanResults scanResults, OSASummaryResults osaSummaryResults) throws MojoFailureException {
StringBuilder res = new StringBuilder("\n");
boolean fail = false;
if (highSeveritiesThreshold >= 0 && scanResults.getHighSeverityResults() > highSeveritiesThreshold) {
res.append("High Severity Results are Above Threshold. Results: ").append(scanResults.getHighSeverityResults()).append(". Threshold: ").append(highSeveritiesThreshold).append("\n");
fail = true;
}
if (mediumSeveritiesThreshold >= 0 && scanResults.getMediumSeverityResults() > mediumSeveritiesThreshold) {
res.append("Medium Severity Results are Above Threshold. Results: ").append(scanResults.getMediumSeverityResults()).append(". Threshold: ").append(mediumSeveritiesThreshold).append("\n");
fail = true;
}
if (lowSeveritiesThreshold >= 0 && scanResults.getLowSeverityResults() > lowSeveritiesThreshold) {
res.append("Low Severity Results are Above Threshold. Results: ").append(scanResults.getLowSeverityResults()).append(". Threshold: ").append(lowSeveritiesThreshold).append("\n");
fail = true;
}
if (osaEnabled && osaSummaryResults != null) {
if (osaHighSeveritiesThreshold >= 0 && osaSummaryResults.getHighVulnerabilities() > osaHighSeveritiesThreshold) {
res.append("OSA High Severity Results are Above Threshold. Results: ").append(osaSummaryResults.getHighVulnerabilities()).append(". Threshold: ").append(osaHighSeveritiesThreshold).append("\n");
fail = true;
}
if (osaMediumSeveritiesThreshold >= 0 && osaSummaryResults.getMediumVulnerabilities() > osaMediumSeveritiesThreshold) {
res.append("OSA Medium Severity Results are Above Threshold. Results: ").append(osaSummaryResults.getMediumVulnerabilities()).append(". Threshold: ").append(osaMediumSeveritiesThreshold).append("\n");
fail = true;
}
if (osaLowSeveritiesThreshold >= 0 && osaSummaryResults.getLowVulnerabilities() > osaLowSeveritiesThreshold) {
res.append("OSA Low Severity Results are Above Threshold. Results: ").append(osaSummaryResults.getLowVulnerabilities()).append(". Threshold: ").append(osaLowSeveritiesThreshold).append("\n");
fail = true;
}
}
if (fail) {
throw new MojoFailureException(res.toString());
}
}
protected byte[] getBytesFromZippedSources() throws MojoExecutionException {
log.debug("Converting Zipped Sources to Byte Array");
byte[] zipFileByte;
try {
InputStream fileStream = new FileInputStream(new File(outputDirectory, SOURCES_ZIP_NAME + ".zip"));
zipFileByte = IOUtils.toByteArray(fileStream);
} catch (Exception e) {
throw new MojoExecutionException("Fail to Set Zipped File Into Project: " + e.getMessage(), e);
}
return zipFileByte;
}
protected void createPDFReport(long scanId) {
log.info("Generating PDF Report");
byte[] scanReport;
try {
scanReport = cxClientService.getScanReport(scanId, ReportType.PDF);
String now = DateFormatUtils.format(new Date(), "dd_MM_yyyy-HH_mm_ss");
String pdfFileName = PDF_REPORT_NAME + "_" + now + ".pdf";
FileUtils.writeByteArrayToFile(new File(outputDirectory, pdfFileName), scanReport);
log.info("PDF Report Can Be Found in: " + outputDirectory + "\\" + pdfFileName);
} catch (Exception e) {
log.warn("Fail to Generate PDF Report");
log.debug("Fail to Generate PDF Report", e);
}
}
protected abstract boolean shouldSkip();
protected abstract void zipSources() throws MojoExecutionException;
protected void zipSourcesHelper(List<MavenProject> projects) throws MojoExecutionException {
for (MavenProject p : projects) {
MavenProject subProject = getProject(p);
if ("pom".equals(subProject.getPackaging())) {
continue;
}
String prefix = subProject.getName() + "\\";
//add sources
List compileSourceRoots = subProject.getCompileSourceRoots();
for (Object c : compileSourceRoots) {
File sourceDir = new File((String) c);
if (sourceDir.exists()) {
zipArchiver.addDirectory(sourceDir, prefix);
}
}
//add resources
List reSourceRoots = subProject.getResources();
for (Object c : reSourceRoots) {
Resource resource = (Resource) c;
File resourceDir = new File(resource.getDirectory());
if (resourceDir.exists()) {
zipArchiver.addDirectory(resourceDir, prefix);
}
}
}
zipArchiver.setDestFile(new File(outputDirectory, SOURCES_ZIP_NAME + ".zip"));
try {
zipArchiver.createArchive();
log.info("Sources Zipped at: " + outputDirectory + "\\" + SOURCES_ZIP_NAME + ".zip");
} catch (IOException e) {
throw new MojoExecutionException("Fail to Create Zip Sources: ", e);
}
}
protected MavenProject getProject(MavenProject p) {
if (p.getExecutionProject() != null) {
return p.getExecutionProject();
}
return p;
}
private File createZipForOSA() throws MojoExecutionException {
Set artifacts = project.getArtifacts();
for (Object arti : artifacts) {
Artifact a = (Artifact) arti;
if (!isExcludedFromOSA(a)) {
zipArchiver.addFile(a.getFile(), a.getGroupId() + "." + a.getFile().getName());
}
}
File ret = new File(outputDirectory, OSA_ZIP_NAME + ".zip");
zipArchiver.setDestFile(ret);
try {
if(zipArchiver.getFiles().isEmpty()) {
log.info("no dependencies found to zip.");
CxPluginHelper.createEmptyZip(ret);
} else {
zipArchiver.createArchive();
log.info("Files for OSA scan zipped at: " + outputDirectory + "\\" + OSA_ZIP_NAME + ".zip");
}
} catch (Exception e) {
throw new MojoExecutionException("Fail to zip files for OSA scan: " + e.getMessage(), e);
}
return ret;
}
private boolean isExcludedFromOSA(Artifact a) {
for (String exclusion : osaExclusions) {
if ((a.getGroupId() + '.' + a.getArtifactId()).equals(exclusion)) {
return true;
}
}
return false;
}
}
|
package com.dev9.mvnwatcher;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
class MvnMonitor implements Runnable {
private List<ProcessBuilder> config;
private Process watchedProcess;
public boolean dirty = true;
public boolean shutdown = false;
private MvnSystemNotifications notifier;
public MvnMonitor(List<ProcessBuilder> config) {
this.config = config;
}
/**
* Returns true if sync builds are successful
*/
private boolean execSyncBuilds() {
for (int i = 0; i < config.size() - 1; i++) {
ProcessBuilder pb = config.get(i);
notifier.update("Directory for build step " + i + " : " + pb.directory().getAbsolutePath() + "...",
MvnSystemNotifications.Status.WORKING);
String commands = pb.command().stream()
.map(s -> s.toString())
.collect(Collectors.joining(" "));
notifier.update("Starting " + commands + "...",
MvnSystemNotifications.Status.WORKING);
Process p;
try {
p = pb.start();
} catch (IOException e1) {
notifier.update(e1.getLocalizedMessage(), MvnSystemNotifications.Status.FAIL, e1);
return false;
}
try {
// This waits for UP TO 10 seconds.
p.waitFor(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
// For now, swallow interruption exceptions..?
} finally {
if (p.isAlive()) {
notifier.update("Destroying Forcibly " + pb.command().get(0), MvnSystemNotifications.Status.FAIL);
p.destroyForcibly();
return false;
}
}
// Doh, failed build!
if (p.exitValue() != 0) {
notifier.update("Prep build failed with exit code " + p.exitValue(), MvnSystemNotifications.Status.FAIL);
return false;
}
}
return true;
}
private void execMainBuild() {
ProcessBuilder finalConfig = config.get((config.size() - 1));
notifier.update("Directory for monitored build : " + finalConfig.directory().getAbsolutePath() + "...",
MvnSystemNotifications.Status.WORKING);
String commands = finalConfig.command().stream()
.map(s -> s.toString())
.collect(Collectors.joining(" "));
try {
if (watchedProcess == null) {
notifier.update("Starting process " + commands + "...",
MvnSystemNotifications.Status.WORKING);
watchedProcess = finalConfig.start();
notifier.update("Ready",
MvnSystemNotifications.Status.OK);
} else if (!watchedProcess.isAlive()) {
notifier.update("Restarting process " + commands + "...",
MvnSystemNotifications.Status.WORKING);
watchedProcess = finalConfig.start();
notifier.update("Ready",
MvnSystemNotifications.Status.OK);
}
} catch (IOException e1) {
notifier.update(e1.getLocalizedMessage(),
MvnSystemNotifications.Status.FAIL, e1);
}
}
@Override
public void run() {
notifier = new MvnSystemNotifications(this);
notifier.init(true);
while (!shutdown) {
if (dirty) {
dirty = false;
kill();
if (execSyncBuilds()) {
execMainBuild();
}
}
if (watchedProcess != null)
if (watchedProcess.isAlive()) {
{
try {
watchedProcess.waitFor(500, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
// Swallowing interruption exceptions for now.
}
}
} else {
if (watchedProcess.exitValue() != 0)
notifier.update("Monitored build no longer running.", MvnSystemNotifications.Status.FAIL);
}
}
kill();
}
public void kill() {
if (watchedProcess != null)
if (watchedProcess.isAlive()) {
notifier.update("Terminating existing build...",
MvnSystemNotifications.Status.WORKING);
watchedProcess.destroyForcibly();
System.out.println("Killed " + watchedProcess.toString());
}
}
public String status() {
if(notifier == null)
return "Initializing monitor...";
return notifier.status();
}
}
|
package com.fishercoder.solutions;
import com.fishercoder.common.classes.TreeNode;
public class _250 {
public static class Solution1 {
public int countUnivalSubtrees(TreeNode root) {
int[] count = new int[1];
helper(root, count);
return count[0];
}
private boolean helper(TreeNode node, int[] count) {
if (node == null) {
return true;
}
boolean left = helper(node.left, count);
boolean right = helper(node.right, count);
if (left && right) {
if (node.left != null && node.val != node.left.val) {
return false;
}
if (node.right != null && node.val != node.right.val) {
return false;
}
count[0]++;
return true;
}
return false;
}
}
}
|
package com.fishercoder.solutions;
public class _351 {
public static class Solution1 {
private int[][] jumps;
private boolean[] visited;
public int numberOfPatterns(int m, int n) {
jumps = new int[10][10];
jumps[1][3] = jumps[3][1] = 2;
jumps[4][6] = jumps[6][4] = 5;
jumps[7][9] = jumps[9][7] = 8;
jumps[1][7] = jumps[7][1] = 4;
jumps[2][8] = jumps[8][2] = jumps[1][9] = jumps[9][1] = 5;
jumps[9][3] = jumps[3][9] = 6;
jumps[3][7] = jumps[7][3] = 5;
visited = new boolean[10];
int count = 0;
count += dfs(1, 1, 0, m, n)
* 4;//1,3,7,9 are symmetric, so we only need to use 1 to do it once and then multiply the result by 4
count += dfs(2, 1, 0, m, n)
* 4;//2,4,6,8 are symmetric, so we only need to use 1 to do it once and then multiply the result by 4
count += dfs(5, 1, 0, m, n);
return count;
}
private int dfs(int num, int len, int count, int m, int n) {
if (len >= m) {
count++;
}
len++;
if (len > n) {
return count;
}
visited[num] = true;
for (int next = 1; next <= 9; next++) {
int jump = jumps[num][next];
if (!visited[next] && (jump == 0 || visited[jump])) {
count = dfs(next, len, count, m, n);
}
}
visited[num] = false;//backtracking
return count;
}
}
}
|
package com.fishercoder.solutions;
public class _488 {
public static class Solution1 {
int maxcount = 6; // the max balls you need will not exceed 6 since "The number of balls in your hand won't exceed 5"
public int findMinStep(String board, String hand) {
int[] handCount = new int[26];
for (int i = 0; i < hand.length(); ++i) {
++handCount[hand.charAt(i) - 'A'];
}
int result = dfs(board + "#", handCount); // append a "#" to avoid special process while j==board.length, make the code shorter.
return result == maxcount ? -1 : result;
}
private int dfs(String s, int[] handCount) {
s = removeConsecutive(s);
if (s.equals("
return 0;
}
int result = maxcount;
int need = 0;
for (int i = 0, j = 0; j < s.length(); ++j) {
if (s.charAt(j) == s.charAt(i)) {
continue;
}
need = 3 - (j - i); //balls need to remove current consecutive balls.
if (handCount[s.charAt(i) - 'A'] >= need) {
handCount[s.charAt(i) - 'A'] -= need;
result = Math.min(result, need + dfs(s.substring(0, i) + s.substring(j), handCount));
handCount[s.charAt(i) - 'A'] += need;
}
i = j;
}
return result;
}
//remove consecutive balls longer than 3
private String removeConsecutive(String board) {
for (int i = 0, j = 0; j < board.length(); ++j) {
if (board.charAt(j) == board.charAt(i)) {
continue;
}
if (j - i >= 3) {
return removeConsecutive(board.substring(0, i) + board.substring(j));
} else {
i = j;
}
}
return board;
}
}
}
|
package com.fishercoder.solutions;
public class _498 {
public static class Solutoin1 {
public int[] findDiagonalOrder(int[][] matrix) {
if (matrix == null || matrix.length == 0) {
return new int[0];
}
int m = matrix.length;
int n = matrix[0].length;
int[] result = new int[m * n];
int d = 1;
int i = 0;
int j = 0;
for (int k = 0; k < m * n; ) {
result[k++] = matrix[i][j];
i -= d;
j += d;
if (i >= m) {
i = m - 1;
j += 2;
d = -d;
}
if (j >= n) {
j = n - 1;
i += 2;
d = -d;
}
if (i < 0) {
i = 0;
d = -d;
}
if (j < 0) {
j = 0;
d = -d;
}
}
return result;
}
}
}
|
package com.fishercoder.solutions;
public class _556 {
public static class Solution1 {
public int nextGreaterElement(int n) {
char[] digits = String.valueOf(n).toCharArray();
int i = digits.length - 2;
while (i >= 0 && digits[i + 1] <= digits[i]) {
i
}
if (i < 0) {
return -1;
}
int j = digits.length - 1;
while (j >= 0 && digits[j] <= digits[i]) {
j
}
swap(digits, i, j);
reverse(digits, i + 1);
try {
return Integer.parseInt(new String(digits));
} catch (Exception e) {
return -1;
}
}
private void reverse(char[] a, int start) {
int i = start;
int j = a.length - 1;
while (i < j) {
swap(a, i, j);
i++;
j
}
}
private void swap(char[] a, int i, int j) {
char temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
|
package com.fishercoder.solutions;
public class _673 {
public static class Solution1 {
public int findNumberOfLIS(int[] nums) {
int n = nums.length;
int[] cnt = new int[n];
int[] len = new int[n];
int max = 0;
int count = 0;
for (int i = 0; i < n; i++) {
len[i] = cnt[i] = 1;
for (int j = 0; j < i; j++) {
if (nums[i] > nums[j]) {
if (len[i] == len[j] + 1) {
cnt[i] += cnt[j];
}
if (len[i] < len[j] + 1) {
len[i] = len[j] + 1;
cnt[i] = cnt[j];
}
}
}
if (max == len[i]) {
count += cnt[i];
}
if (len[i] > max) {
max = len[i];
count = cnt[i];
}
}
return count;
}
}
}
|
package com.jaamsim.input;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import com.jaamsim.basicsim.ErrorException;
import com.jaamsim.units.Unit;
import com.sandwell.JavaSimulation.Entity;
/**
* OutputHandle is a class that represents all the useful runtime information for an output,
* specifically a reference to the runtime annotation and the method it points to
* @author matt.chudleigh
*
*/
public class OutputHandle {
public Entity ent;
public OutputStaticInfo outputInfo;
public Class<? extends Unit> unitType;
private static final HashMap<Class<? extends Entity>, ArrayList<OutputStaticInfo>> outputInfoCache;
static {
outputInfoCache = new HashMap<Class<? extends Entity>, ArrayList<OutputStaticInfo>>();
}
public OutputHandle(Entity e, String outputName) {
ent = e;
outputInfo = OutputHandle.getOutputInfo(e.getClass(), outputName);
unitType = outputInfo.unitType;
}
/**
* A custom constructor for an interned string parameter
* @param e
* @param outputName
* @param dummy
*/
public OutputHandle(Entity e, String outputName, int dummy) {
ent = e;
outputInfo = OutputHandle.getOutputInfoInterned(e.getClass(), outputName);
unitType = outputInfo.unitType;
}
protected OutputHandle(Entity e) {
ent = e;
}
/**
* A data class containing the 'static' (ie: class derived) information for a single output
*/
private static final class OutputStaticInfo {
public Method method;
public final String name;
public final String desc;
public final boolean reportable;
public final Class<? extends Unit> unitType;
public OutputStaticInfo(Method m, Output a) {
method = m;
desc = a.description();
reportable = a.reportable();
name = a.name().intern();
unitType = a.unitType();
}
}
// Note: this method will not include attributes in the list. For a complete list use
// Entity.hasOutput()
public static Boolean hasOutput(Class<? extends Entity> klass, String outputName) {
return OutputHandle.getOutputInfo(klass, outputName) != null;
}
public static Boolean hasOutputInterned(Class<? extends Entity> klass, String outputName) {
return OutputHandle.getOutputInfoInterned(klass, outputName) != null;
}
private static OutputStaticInfo getOutputInfo(Class<? extends Entity> klass, String outputName) {
for (OutputStaticInfo p : getOutputInfoImp(klass)) {
if( p.name.equals(outputName) )
return p;
}
return null;
}
private static OutputStaticInfo getOutputInfoInterned(Class<? extends Entity> klass, String outputName) {
for (OutputStaticInfo p : getOutputInfoImp(klass)) {
if( p.name == outputName )
return p;
}
return null;
}
private static ArrayList<OutputStaticInfo> getOutputInfoImp(Class<? extends Entity> klass) {
ArrayList<OutputStaticInfo> ret = outputInfoCache.get(klass);
if (ret != null)
return ret;
// klass has not been cached yet, generate info
ret = new ArrayList<OutputStaticInfo>();
for (Method m : klass.getMethods()) {
Output a = m.getAnnotation(Output.class);
if (a == null)
continue;
// Check that this method only takes a single double (simTime) parameter
Class<?>[] paramTypes = m.getParameterTypes();
if (paramTypes.length != 1 ||
paramTypes[0] != double.class) {
continue;
}
ret.add(new OutputStaticInfo(m, a));
}
outputInfoCache.put(klass, ret);
return ret;
}
/**
* Return a list of the OuputHandles for the given entity.
* @param e = the entity whose OutputHandles are to be returned.
* @return = ArrayList of OutputHandles.
*/
public static ArrayList<OutputHandle> getOutputHandleList(Entity e) {
Class<? extends Entity> klass = e.getClass();
ArrayList<OutputStaticInfo> list = getOutputInfoImp(klass);
ArrayList<OutputHandle> ret = new ArrayList<OutputHandle>(list.size());
for( OutputStaticInfo p : list ) {
//ret.add( new OutputHandle(e, p) );
ret.add( e.getOutputHandle(p.name) ); // required to get the correct unit type for the output
}
// And the attributes
for (String attribName : e.getAttributeNames()) {
ret.add(e.getOutputHandle(attribName));
}
Collections.sort(ret, new OutputHandleComparator());
return ret;
}
private static class OutputHandleComparator implements Comparator<OutputHandle> {
@Override
public int compare(OutputHandle hand0, OutputHandle hand1) {
Class<?> class0 = hand0.getDeclaringClass();
Class<?> class1 = hand1.getDeclaringClass();
if (class0 == class1)
return 0;
if (class0.isAssignableFrom(class1))
return -1;
else
return 1;
}
}
@SuppressWarnings("unchecked") // This suppresses the warning on the cast, which is effectively checked
public <T> T getValue(double simTime, Class<T> klass) {
if( outputInfo.method == null )
return null;
T ret = null;
try {
if (!klass.isAssignableFrom(outputInfo.method.getReturnType()))
return null;
ret = (T)outputInfo.method.invoke(ent, simTime);
}
catch (InvocationTargetException ex) {}
catch (IllegalAccessException ex) {}
catch (ClassCastException ex) {}
return ret;
}
public boolean isNumericValue() {
Class<?> rtype = this.getReturnType();
if (rtype == Double.class) return true;
if (rtype == double.class) return true;
if (rtype == Float.class) return true;
if (rtype == float.class) return true;
if (rtype == Long.class) return true;
if (rtype == long.class) return true;
if (rtype == Integer.class) return true;
if (rtype == int.class) return true;
if (rtype == Short.class) return true;
if (rtype == short.class) return true;
if (rtype == Character.class) return true;
if (rtype == char.class) return true;
return false;
}
/**
* Checks the output for all possible numerical types and returns a double representing the value
* @param simTime
* @param def - the default value if the return is null or not a number value
* @return
*/
public double getValueAsDouble(double simTime, double def, Unit u) {
double ret = getValueAsDouble(simTime, def);
Class<? extends Unit> ut = this.getUnitType();
if (u == null)
return ret;
if (u.getClass() != ut)
throw new ErrorException("Unit Mismatch");
ret /= u.getConversionFactorToSI();
return ret;
}
/**
* Checks the output for all possible numerical types and returns a double representing the value
* @param simTime
* @param def - the default value if the return is null or not a number value
* @return
*/
public double getValueAsDouble(double simTime, double def) {
Class<?> retType = this.getReturnType();
if (retType == double.class)
return this.getValue(simTime, double.class);
if (retType == Double.class) {
Double val = getValue(simTime, Double.class);
if (val == null) return def;
return val.doubleValue();
}
if (retType == Float.class) {
Float val = getValue(simTime, Float.class);
if (val == null) return def;
return val.doubleValue();
}
if (retType == Long.class) {
Long val = getValue(simTime, Long.class);
if (val == null) return def;
return val.doubleValue();
}
if (retType == Integer.class) {
Integer val = getValue(simTime, Integer.class);
if (val == null) return def;
return val.doubleValue();
}
if (retType == Short.class) {
Short val = getValue(simTime, Short.class);
if (val == null) return def;
return val.doubleValue();
}
if (retType == Character.class) {
Character val = getValue(simTime, Character.class);
if (val == null) return def;
return val.charValue();
}
if (retType == Boolean.class) {
Boolean val = getValue(simTime, Boolean.class);
if (val == null) return def;
return val.booleanValue() ? 1.0d : 0.0d;
}
if (retType == float.class)
return this.getValue(simTime, float.class);
if (retType == int.class)
return this.getValue(simTime, int.class);
if (retType == long.class)
return this.getValue(simTime, long.class);
if (retType == short.class)
return this.getValue(simTime, short.class);
if (retType == char.class)
return this.getValue(simTime, char.class);
if (retType == boolean.class)
return this.getValue(simTime, boolean.class) ? 1.0d : 0.0d;
return def;
}
public Class<?> getReturnType() {
assert (outputInfo.method != null);
return outputInfo.method.getReturnType();
}
public Class<?> getDeclaringClass() {
assert (outputInfo.method != null);
return outputInfo.method.getDeclaringClass();
}
public void setUnitType(Class<? extends Unit> ut) {
unitType = ut;
}
public Class<? extends Unit> getUnitType() {
return unitType;
}
public String getDescription() {
return outputInfo.desc;
}
public String getName() {
return outputInfo.name;
}
public boolean isReportable() {
return outputInfo.reportable;
}
}
|
package com.johnnywey.flipside.box;
public interface Box<T> {
T get();
T getOrElse(T alternateIn);
Boolean isEmpty();
/**
* If the box is full, invoke the specified consumer with the value of {@link #get()}, otherwise do nothing.
* Works similarly to {@code Optional#ifPresent} in JDK 8+.
*
* @param consumer the consumer to invoke if this Box is full
*/
void ifPresent(BoxConsumer<? super T> consumer);
boolean asBoolean();
}
|
package com.lsnare.film.util;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.lsnare.film.dao.FilmDAO;
import com.lsnare.film.model.Actor;
import com.lsnare.film.model.Director;
import com.lsnare.film.model.Film;
import com.lsnare.film.service.HTTPService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class FilmUtils {
static Log log = LogFactory.getLog(FilmUtils.class);
static String myAPIFilmsURL = "http:
+ "&lang=en-us&uniqueName=0";
/** Search Utils **/
public static Film[] searchMyAPIFilmsByTitle(String filmTitle){
//Add title search-specific filters onto URL
String url = myAPIFilmsURL + "&filter=M&limit=10&title=" + filmTitle;
log.info("Search URL: " + url);
Film[] films = new Film[0];
try{
String res = HTTPService.sendGet(url);
log.info("JSON: " + res);
Gson gson = new GsonBuilder().create();
films = gson.fromJson(res, Film[].class);
} catch(Exception e){
log.error("Error searching MyAPIFilms by title: " + e.getMessage());
}
return films;
}
public static Film searchMyAPIFilmsByIMDBId(String IMDBId){
//Add IMDB Id search-specific filters onto URL
String url = myAPIFilmsURL + "&actors=S&idIMDB=" + IMDBId;
log.info("Search URL: " + url);
Film film = new Film();
try{
String res = HTTPService.sendGet(url);
log.info("JSON returned: " + res);
Gson gson = new GsonBuilder().create();
//Film JSON come back as an array, but will only have one result
film = gson.fromJson(res, Film.class);
} catch(Exception e){
log.error("Error searching MyAPIFilms by IMDB Id: " + e.getMessage());
}
return film;
}
public static List<Film> searchDatabaseForFilmsByTitle(String filmTitle){
List<Film> films = new ArrayList<>();
try{
ApplicationContext context =
new ClassPathXmlApplicationContext("Spring-Module.xml");
FilmDAO filmDAO = (FilmDAO) context.getBean("filmDAO");
films = filmDAO.selectFilmsByTitle(filmTitle);
log.info("Found " + films.size() + " films when searching");
} catch(Exception e){
log.error("Error searching database by title: " + e);
}
return films;
}
public static Map<String, String> searchDatabaseForActorRoles(String actorName){
Map<String, String> rolesForActor = new HashMap();
try{
ApplicationContext context =
new ClassPathXmlApplicationContext("Spring-Module.xml");
FilmDAO filmDAO = (FilmDAO) context.getBean("filmDAO");
rolesForActor = filmDAO.selectRolesForActor(actorName);
log.info("Found " + rolesForActor.size() + " roles when searching");
} catch(Exception e){
log.error("Error searching atabase for roles: " + e);
}
return rolesForActor;
}
/** Page Builders **/
public static Map<String, Object> buildMyAPIFilmsSearchResults(Film[] films){
Map<String, Object> attributes = new HashMap();
String filmData = "";
if (films.length > 0){
filmData += "<fieldset>";
//Create a list of radio inputs with values set to each film's IMDB Id
for (Film film : films){
filmData += "<input type=\"radio\" name=\"film\" value=\"" + film.getIdIMDB() + "\">"
+ film.getTitle() + " " + film.getYear() + "<br>";
}
filmData += "<input type=\"submit\" name=\"insertFilm\" value=\"Insert Film\" form=\"searchResultsTable\"/>";
filmData += "</fieldset>";
}
attributes.put("filmData", filmData);
return attributes;
}
public static Map<String, Object> buildDatabaseFilmSearchResults(List<Film> films){
String filmData = "";
Map<String, Object> attributes = new HashMap();
attributes.put("searchResultsHeader", "<h3>Search Results</h3>");
if(films.size() > 0) {
String shortPlot = "";
String longPlot = "";
int count = 0;
filmData += "<table border=1> <col width=\"80\"> <col width=\"100\"> <col width=\"50\"> <col width=\"500\"> <col width=\"250\">"
+ "<tr>"
+ "<th>IMDB ID</th> <th>Title</th> <th>Year</th> <th>Plot</th> <th>Actors</th> <th>Director</th> </tr>";
for (Film film : films) {
//Get the first full sentence for the short plot
shortPlot = film.getPlot().split("\\.", 25)[0] + "...";
longPlot = film.getPlot();
//HTML TR id field
String rowId = "row_" + count;
filmData += "<tr id = \"" + rowId + "\"><td>" + film.getIdIMDB() + "</td>"
+ "<td>" + film.getTitle() + "</td>"
+ "<td>" + film.getYear() + "</td>"
//Short plot
+ "<td>" + shortPlot
+ "<a href =\"#\" onclick=\"showLongPlot(\'" + rowId + "\')\"> More </a>"
+ "</td>"
//Create hidden td tag to hold the longer plot description
+ "<td style=\"display: none;\">" + longPlot
+ "<a href=\"#\" onclick=\"showShortPlot(\'" + rowId + "\')\"> Less </a>"
+ "</td>"
//Fill in actor list
+ "<td>";
for (Actor actor : film.getActors()){
filmData += actor.getActorName() + "<br>";
}
//Fill in director list
filmData += "</td><td>";
for (Director director : film.getDirectors()){
filmData += director.getName() + "<br>";
}
filmData += "</td></tr>";
count ++;
}
filmData += "</table>";
} else {
filmData = "<b>No results found!</b>";
}
attributes.put("filmData", filmData);
return attributes;
}
public static Map<String, Object> buildDatabaseActorRolesSearchResults(String actorName, Map<String, String> roles){
String actorData = "";
Map<String, Object> attributes = new HashMap();
attributes.put("searchResultsHeader", "<h3>Search Results</h3>");
actorData += "<ul><li>" + actorName + "</li>";
for (String role : roles.keySet()){
actorData += "<ul><li>" + role + "  <i>" + roles.get(role) + "</i></li>";
}
actorData += "</ul>";
attributes.put("actorData", actorData);
return attributes;
}
}
|
package com.matt.forgehax.mods;
import com.google.common.collect.Sets;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
import com.matt.forgehax.events.ChatMessageEvent;
import com.matt.forgehax.events.LocalPlayerUpdateEvent;
import com.matt.forgehax.events.PlayerConnectEvent;
import com.matt.forgehax.mods.services.SpamService;
import com.matt.forgehax.util.ArrayHelper;
import com.matt.forgehax.util.SafeConverter;
import com.matt.forgehax.util.command.Options;
import com.matt.forgehax.util.command.Setting;
import com.matt.forgehax.util.common.PriorityEnum;
import com.matt.forgehax.util.mod.ToggleMod;
import com.matt.forgehax.util.mod.loader.RegisterMod;
import com.matt.forgehax.util.serialization.GsonConstant;
import com.matt.forgehax.util.spam.SpamEntry;
import com.matt.forgehax.util.spam.SpamMessage;
import com.matt.forgehax.util.spam.SpamTokens;
import com.matt.forgehax.util.spam.SpamTrigger;
import joptsimple.internal.Strings;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import java.io.File;
import java.nio.file.Files;
import java.util.Iterator;
import java.util.Scanner;
import static com.matt.forgehax.Helper.getFileManager;
import static com.matt.forgehax.Helper.getLocalPlayer;
@RegisterMod
public class ChatBot extends ToggleMod {
public final Options<SpamEntry> spams = getCommandStub().builders().<SpamEntry>newOptionsBuilder()
.name("spam")
.description("Contents to spam")
.factory(SpamEntry::new)
.supplier(Sets::newConcurrentHashSet)
.build();
public final Setting<Integer> max_message_length = getCommandStub().builders().<Integer>newSettingBuilder()
.name("max_message_length")
.description("Maximum length allowed for a message")
.defaultTo(256)
.min(0)
.max(256)
.build();
public final Setting<Integer> max_input_length = getCommandStub().builders().<Integer>newSettingBuilder()
.name("max_input_length")
.description("Maximum chat input length allowed")
.defaultTo(16)
.min(0)
.max(256)
.build();
public ChatBot() {
super("ChatBot", false, "Spam chat");
}
@Override
protected void onLoad() {
getCommandStub().builders().newCommandBuilder()
.name("add")
.description("Add new spam list")
.options(parser -> {
parser.accepts("keyword", "Message activation keyword").withRequiredArg();
parser.accepts("type", "Spam type (random, sequential)").withRequiredArg();
parser.accepts("trigger", "How the spam will be triggered (spam, reply, reply_with_input, player_connect, player_disconnect)").withRequiredArg();
parser.accepts("enabled", "Enabled").withRequiredArg();
parser.accepts("delay", "Custom delay between messages of the same type").withRequiredArg();
})
.processor(data -> {
data.requiredArguments(1);
String name = data.getArgumentAsString(0);
boolean givenInput = data.hasOption("keyword")
|| data.hasOption("type")
|| data.hasOption("trigger")
|| data.hasOption("enabled")
|| data.hasOption("delay");
SpamEntry entry = spams.get(name);
if (entry == null) {
entry = new SpamEntry(name);
spams.add(entry);
data.write("Added new entry \"" + name + "\"");
}
if (data.hasOption("keyword")) entry.setKeyword(data.getOptionAsString("keyword"));
if (data.hasOption("type")) entry.setType(data.getOptionAsString("type"));
if (data.hasOption("trigger")) entry.setTrigger(data.getOptionAsString("trigger"));
if (data.hasOption("enabled"))
entry.setEnabled(SafeConverter.toBoolean(data.getOptionAsString("enabled")));
if (data.hasOption("delay"))
entry.setDelay(SafeConverter.toLong(data.getOptionAsString("delay")));
if (data.getArgumentCount() == 2) {
String msg = data.getArgumentAsString(1);
entry.add(msg);
data.write("Added message \"" + msg + "\"");
}
if(givenInput) {
data.write("keyword=" + entry.getKeyword());
data.write("type=" + entry.getType().name());
data.write("trigger=" + entry.getTrigger().name());
data.write("enabled=" + Boolean.toString(entry.isEnabled()));
data.write("delay=" + Long.toString(entry.getDelay()));
}
data.markSuccess();
})
.success(e -> spams.serialize())
.build();
getCommandStub().builders().newCommandBuilder()
.name("import")
.description("Import a txt or json file")
.processor(data -> {
data.requiredArguments(2);
String name = data.getArgumentAsString(0);
String fileN = data.getArgumentAsString(1);
SpamEntry entry = spams.get(name);
if (entry == null) {
entry = new SpamEntry(name);
spams.add(entry);
data.write("Added new entry \"" + name + "\"");
}
File file = getFileManager().getFileInBaseDirectory(fileN);
if(file.exists()) {
if(fileN.endsWith(".json")) {
try {
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(new String(Files.readAllBytes(file.toPath())));
if(element.isJsonArray()) {
JsonArray head = (JsonArray) element;
int count = 0;
for(JsonElement e : head) {
if(e.isJsonPrimitive()) {
String str = e.getAsString();
entry.add(str);
++count;
}
}
data.write("Successfully imported " + count + " messages");
} else {
data.write("Json head must be a JsonArray");
}
} catch (Throwable t) {
data.write("Failed parsing json: " + t.getMessage());
}
} else if(fileN.endsWith(".txt")) {
try {
Scanner scanner = new Scanner(file);
int count = 0;
while(scanner.hasNextLine()) {
String next = scanner.nextLine();
if(!Strings.isNullOrEmpty(next)) {
entry.add(next);
++count;
}
}
data.write("Successfully imported " + count + " messages");
} catch (Throwable t) {
data.write("Failed parsing text: " + t.getMessage());
}
} else {
data.write("Invalid file extension for \"" + fileN + "\" (requires .txt or .json)");
}
} else {
data.write("Could not find file \"" + fileN + "\" in base directory");
}
})
.success(e -> spams.serialize())
.build();
getCommandStub().builders().newCommandBuilder()
.name("export")
.description("Export all the contents of an entry")
.processor(data -> {
data.requiredArguments(2);
String name = data.getArgumentAsString(0);
String fileN = data.getArgumentAsString(1);
SpamEntry entry = spams.get(name);
if (entry == null) {
data.write("No such entry: " + name);
return;
}
if(!fileN.endsWith(".json") && !fileN.endsWith(".txt")) fileN += ".txt";
File file = getFileManager().getFileInBaseDirectory(fileN);
try {
if(file.getParentFile() != null) file.getParentFile().mkdirs();
if(name.endsWith(".json")) {
final JsonArray head = new JsonArray();
entry.getMessages().forEach(str -> head.add(new JsonPrimitive(str)));
Files.write(file.toPath(), GsonConstant.GSON_PRETTY.toJson(head).getBytes());
} else {
final StringBuilder builder = new StringBuilder();
entry.getMessages().forEach(str -> {
builder.append(str);
builder.append('\n');
});
Files.write(file.toPath(), builder.toString().getBytes());
}
data.markSuccess();
} catch (Throwable t) {
data.write("Failed exporting file: " + t.getMessage());
}
})
.build();
getCommandStub().builders().newCommandBuilder()
.name("remove")
.description("Remove spam entry")
.processor(data -> {
data.requiredArguments(1);
String name = data.getArgumentAsString(0);
SpamEntry entry = spams.get(name);
if(entry != null) {
spams.remove(entry);
data.write("Removed entry \"" + name + "\"");
data.markSuccess();
} else {
data.write("Invalid entry \"" + name + "\"");
data.markFailed();
}
})
.success(e -> spams.serialize())
.build();
getCommandStub().builders().newCommandBuilder()
.name("list")
.description("List all current entries")
.processor(data -> {
final StringBuilder builder = new StringBuilder();
Iterator<SpamEntry> it = spams.iterator();
while (it.hasNext()) {
SpamEntry next = it.next();
builder.append(next.getName());
if(it.hasNext()) builder.append(", ");
}
data.write(builder.toString());
data.markSuccess();
})
.build();
}
@SubscribeEvent
public void onTick(LocalPlayerUpdateEvent event) {
if(SpamService.isEmpty() && !spams.isEmpty()) for(SpamEntry e : spams) {
if (e.isEnabled()
&& !e.isEmpty()
&& e.getTrigger().equals(SpamTrigger.SPAM)) {
SpamService.send(new SpamMessage(
e.next(),
"SPAM" + e.getName(),
e.getDelay(),
"self" + e.getName().toLowerCase(),
PriorityEnum.DEFAULT
));
return;
}
}
}
@SubscribeEvent
public void onChat(ChatMessageEvent event) {
if(event.getProfile() == null || event.getProfile().getId().equals(getLocalPlayer().getGameProfile().getId())) return;
String[] args = event.getMessage().split(" ");
final String sender = event.getProfile().getId().toString();
final String keyword = ArrayHelper.getOrDefault(args, 0, Strings.EMPTY);
final String arg = ArrayHelper.getOrDefault(args, 1, Strings.EMPTY);
spams.stream()
.filter(SpamEntry::isEnabled)
.filter(e -> e.getKeyword().equalsIgnoreCase(keyword))
.forEach(e -> {
switch (e.getTrigger()) {
case REPLY: {
SpamService.send(new SpamMessage(
e.next(),
"REPLY" + e.getName(),
e.getDelay(),
sender,
PriorityEnum.HIGH
));
break;
}
case REPLY_WITH_INPUT: {
if(!Strings.isNullOrEmpty(arg)
&& arg.length() <= max_input_length.get())
SpamService.send(new SpamMessage(
SpamTokens.PLAYER_NAME.fill(e.next(), arg),
"REPLY_WITH_INPUT" + e.getName(),
e.getDelay(),
sender,
PriorityEnum.HIGH
));
break;
}
default: break;
}
});
}
@SubscribeEvent
public void onPlayerConnect(PlayerConnectEvent.Join event) {
final String player = event.getProfile() != null ? event.getProfile().getName() : "null";
spams.stream()
.filter(SpamEntry::isEnabled)
.forEach(e -> {
switch (e.getTrigger()) {
case PLAYER_CONNECT:
{
SpamService.send(new SpamMessage(
SpamTokens.PLAYER_NAME.fill(e.next(), player),
"PLAYER_CONNECT" + e.getName(),
e.getDelay(),
null,
PriorityEnum.HIGH
));
break;
}
default: break;
}
});
}
@SubscribeEvent
public void onPlayerDisconnect(PlayerConnectEvent.Leave event) {
final String player = event.getProfile() != null ? event.getProfile().getName() : "null";
spams.stream()
.filter(SpamEntry::isEnabled)
.forEach(e -> {
switch (e.getTrigger()) {
case PLAYER_DISCONNECT:
{
SpamService.send(new SpamMessage(
SpamTokens.PLAYER_NAME.fill(e.next(), player),
"PLAYER_DISCONNECT" + e.getName(),
e.getDelay(),
null,
PriorityEnum.HIGH
));
break;
}
default:
break;
}
});
}
}
|
package com.matt.forgehax.mods;
import com.matt.forgehax.events.Render2DEvent;
import com.matt.forgehax.util.color.Color;
import com.matt.forgehax.util.color.Colors;
import com.matt.forgehax.util.command.Setting;
import com.matt.forgehax.util.draw.SurfaceBuilder;
import com.matt.forgehax.util.draw.SurfaceHelper;
import com.matt.forgehax.util.entity.EntityUtils;
import com.matt.forgehax.util.entity.mobtypes.MobTypeEnum;
import com.matt.forgehax.util.math.AngleHelper;
import com.matt.forgehax.util.math.Plane;
import com.matt.forgehax.util.math.VectorUtils;
import com.matt.forgehax.util.mod.Category;
import com.matt.forgehax.util.mod.ToggleMod;
import com.matt.forgehax.util.mod.loader.RegisterMod;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.util.math.Vec3d;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import org.lwjgl.opengl.GL11;
import java.util.Objects;
import static com.matt.forgehax.Helper.getLocalPlayer;
import static com.matt.forgehax.Helper.getWorld;
@RegisterMod
public class Tracers extends ToggleMod implements Colors {
public Tracers() {
super(Category.RENDER, "Tracers", false, "See where other players are");
}
public final Setting<Boolean> drawArrows = getCommandStub().builders().<Boolean>newSettingBuilder()
.name("drawArrows").description("draw arrows to off-screen entities")
.defaultTo(true).build();
public final Setting<Boolean> drawLines = getCommandStub().builders().<Boolean>newSettingBuilder()
.name("drawLines").description("draw lines to entities")
.defaultTo(false).build();
public final Setting<Double> opacity = getCommandStub().builders().<Double>newSettingBuilder()
.name("opacity").description("transparency of the tracers")
.defaultTo(1D)
.min(0D)
.max(1D)
.build();
public final Setting<Boolean> players = getCommandStub().builders().<Boolean>newSettingBuilder()
.name("players").description("trace players")
.defaultTo(true).build();
public final Setting<Boolean> hostile = getCommandStub().builders().<Boolean>newSettingBuilder()
.name("hostile").description("trace hostile mobs")
.defaultTo(true).build();
public final Setting<Boolean> neutral = getCommandStub().builders().<Boolean>newSettingBuilder()
.name("neutral").description("trace neutral mobs")
.defaultTo(true).build();
public final Setting<Boolean> friendly = getCommandStub().builders().<Boolean>newSettingBuilder()
.name("friendly").description("trace friendly mobs")
.defaultTo(true).build();
@SubscribeEvent
public void onDrawScreen(Render2DEvent event) {
getWorld().loadedEntityList.stream()
.filter(entity -> !Objects.equals(entity, getLocalPlayer()))
.filter(entity -> entity instanceof EntityLivingBase)
.map(EntityRelations::new)
.filter(w -> w.getRelationship().equals(MobTypeEnum.INVALID))
.filter(EntityRelations::isOptionEnabled)
.sorted()
.forEach(w -> {
if (drawArrows.getAsBoolean()) drawArrow(event, w);
if (drawLines.getAsBoolean()) drawLine(event, w);
});
}
private void drawArrow(Render2DEvent event, EntityRelations w) {
final Entity entity = w.getEntity();
final MobTypeEnum relationship = w.getRelationship();
final double cx = MC.displayWidth / 4.f;
final double cy = MC.displayHeight / 4.f;
Vec3d pos3d = EntityUtils.getInterpolatedEyePos(entity, MC.getRenderPartialTicks());
Plane pos = VectorUtils.toScreen(pos3d);
if(!pos.isVisible()) {
// get position on ellipse
// dimensions of the ellipse
final double dx = cx - 2;
final double dy = cy - 20;
// ellipse = x^2/a^2 + y^2/b^2 = 1
// e = (pos - C) / d
// C = center vector
// d = dimensions
double ex = (pos.getX() - cx) / dx;
double ey = (pos.getY() - cy) / dy;
// normalize
// n = u/|u|
double m = Math.abs(Math.sqrt(ex*ex + ey*ey));
double nx = ex / m;
double ny = ey / m;
// scale
// p = C + dot(n,d)
double x = cx + nx * dx;
double y = cy + ny * dy;
// now rotate triangle
// point - center
// w = <px - cx, py - cy>
double wx = x - cx;
double wy = y - cy;
// u = <w, 0>
double ux = MC.displayWidth / 2.f;
double uy = 0.D;
double mu = Math.sqrt(ux*ux + uy*uy);
double mw = Math.sqrt(wx*wx + wy*wy);
// theta = dot(u,w)/(|u|*|w|)
double ang = Math.toDegrees(Math.acos((ux*wx + uy*wy)/(mu*mw)));
// don't allow NaN angles
if(ang == Float.NaN) ang = 0;
// invert
if(y < cy) ang *= -1;
// normalize
ang = (float) AngleHelper.normalizeInDegrees(ang);
int size = 5;
if (relationship == MobTypeEnum.PLAYER) {
size = 8;
}
event.getSurfaceBuilder().reset()
.push()
.task(SurfaceBuilder::enableBlend)
.task(SurfaceBuilder::disableTexture2D)
.task(() -> GL11.glEnable(GL11.GL_POLYGON_SMOOTH))
.color(w.getColor().setAlpha((int)(255 * opacity.get())).toBuffer())
.translate(x, y, 0.D)
.rotate(ang, 0.D, 0.D, size / 2.D)
.begin(GL11.GL_TRIANGLES)
.vertex(0, 0)
.vertex(-size, -size)
.vertex(-size, size)
.end()
.task(SurfaceBuilder::disableBlend)
.task(SurfaceBuilder::enableTexture2D)
.task(() -> GL11.glDisable(GL11.GL_POLYGON_SMOOTH))
.pop();
/*
if (EntityUtils.isPlayer(entity)) {
ResourceLocation resourceLocation = AbstractClientPlayer.getLocationSkin(entity.getName());
AbstractClientPlayer.getDownloadImageSkin(resourceLocation, entity.getName());
SurfaceHelper.drawHead(resourceLocation, (int)x - 6, (int)y - 6, 1);
}
else {
SurfaceHelper.drawTriangle((int) x, (int) y, size, (float) ang, color);
}*/
}
}
private void drawLine(Render2DEvent event, EntityRelations w) {
final Entity entity = w.getEntity();
final MobTypeEnum relation = w.getRelationship();
final double cx = MC.displayWidth / 4.f;
final double cy = MC.displayHeight / 4.f;
Vec3d pos3d = EntityUtils.getInterpolatedEyePos(entity, MC.getRenderPartialTicks());
Plane pos = VectorUtils.toScreen(pos3d);
int size = 1;
if (relation == MobTypeEnum.PLAYER) {
size = 2;
}
SurfaceHelper.drawLine((int)cx, (int)cy, (int)pos.getX(), (int)pos.getY(), w.getColor().setAlpha((int)(255 * opacity.get())).toBuffer(), size);
}
private class EntityRelations implements Comparable<EntityRelations> {
private final Entity entity;
private final MobTypeEnum relationship;
public EntityRelations(Entity entity) {
Objects.requireNonNull(entity);
this.entity = entity;
this.relationship = EntityUtils.getRelationship(entity);
}
public Entity getEntity() {
return entity;
}
public MobTypeEnum getRelationship() {
return relationship;
}
public Color getColor() {
switch (relationship) {
case PLAYER:
return YELLOW;
case HOSTILE:
return RED;
case NEUTRAL:
return BLUE;
default:
return GREEN;
}
}
public boolean isOptionEnabled() {
switch (relationship) {
case PLAYER:
return players.get();
case HOSTILE:
return hostile.get();
case NEUTRAL:
return neutral.get();
default:
return friendly.get();
}
}
@Override
public int compareTo(EntityRelations o) {
return getRelationship().compareTo(o.getRelationship());
}
}
}
|
package com.nerodesk.takes.doc;
import com.jcabi.log.Logger;
import com.nerodesk.om.Base;
import com.nerodesk.om.Doc;
import com.nerodesk.takes.RqDisposition;
import com.nerodesk.takes.RqUser;
import java.io.IOException;
import java.io.InputStream;
import org.takes.Request;
import org.takes.Response;
import org.takes.Take;
import org.takes.facets.flash.RsFlash;
import org.takes.facets.forward.RsForward;
import org.takes.rq.RqLengthAware;
import org.takes.rq.RqMultipart;
/**
* Write file content.
*
* @author Yegor Bugayenko (yegor@teamed.io)
* @version $Id$
* @since 0.2
* @todo #151:30min This class should work with a batch of documents, not just
* with a single document. Use the new interface Batch in place of the current
* Doc interface.
*/
final class TkWrite implements Take {
/**
* Base.
*/
private final transient Base base;
/**
* Ctor.
* @param bse Base
*/
TkWrite(final Base bse) {
this.base = bse;
}
@Override
public Response act(final Request req) throws IOException {
Logger.info(
this, "%d bytes incoming",
new RqLengthAware(req).body().available()
);
final RqMultipart multi = new RqMultipart.Base(req);
final Request part = multi.part("file").iterator().next();
final Doc doc = new RqUser(req, this.base).user().docs().doc(
new RqDisposition(part).filename()
);
final InputStream body = part.body();
doc.write(body, body.available());
return new RsForward(new RsFlash("file uploaded"));
}
}
|
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// 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:
// in all copies or substantial portions of the Software.
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package com.pocketsoap;
import hudson.Extension;
import hudson.Launcher;
import hudson.model.Action;
import hudson.model.BuildListener;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.Hudson;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.BuildStepMonitor;
import hudson.tasks.Notifier;
import hudson.tasks.Publisher;
import hudson.tasks.junit.CaseResult;
import hudson.tasks.test.AbstractTestResultAction;
import hudson.util.FormValidation;
import java.io.IOException;
import java.io.PrintStream;
import java.net.MalformedURLException;
import java.net.URL;
import javax.servlet.ServletException;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import com.pocketsoap.salesforce.soap.ChatterClient;
/**
* @author superfell
*
*/
public class ChatterNotifier extends Notifier {
private final String username, password, recordId, server;
@DataBoundConstructor
public ChatterNotifier(String username, String password, String recordId, String server) {
this.username = username;
this.password = password;
this.recordId = recordId;
this.server = server;
}
/**
* We'll use this from the <tt>config.jelly</tt>.
*/
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public String getRecordId() {
return recordId;
}
public String getServer() {
return server;
}
// we'll run after being finalized, and not look at previous results
// so we don't need any locking here, this'll let us be used safely
// from a concurrent build.
public BuildStepMonitor getRequiredMonitorService() {
return BuildStepMonitor.NONE;
}
@Override
public boolean needsToRunAfterFinalized() {
return true;
}
/**
* This method should have the logic of the plugin. Access the configuration
* and execute the the actions.
*/
@Override
public boolean perform(AbstractBuild<?,?> build, Launcher launcher, BuildListener listener) {
PrintStream ps = listener.getLogger();
String title = "Build: " + build.getProject().getName() + " " + build.getDisplayName() + " is " + build.getResult().toString();
String rootUrl = Hudson.getInstance().getRootUrl();
String url = rootUrl == null ? null : rootUrl + build.getUrl();
String testHealth = null;
AbstractTestResultAction<?> tr = build.getTestResultAction();
if (tr != null) {
StringBuilder th = new StringBuilder(tr.getBuildHealth().getDescription());
if (tr.getFailedTests().size() > 0) {
th.append("\nFailures");
for(CaseResult cr : tr.getFailedTests())
th.append("\n").append(cr.getFullName());
}
testHealth = th.toString();
}
try {
new ChatterClient(username, password, server).postBuild(recordId, title, url, testHealth);
} catch (Exception ex) {
ps.print("error posting to chatter : " + ex.getMessage());
}
return true;
}
public Action getProjectAction(AbstractProject<?, ?> project) {
return null;
}
/**
* Descriptor for {@link ChatterNotifier}. Used as a singleton. The class is
* marked as public so that it can be accessed from views.
*
* <p>
* See <tt>global.jelly</tt> for the actual HTML fragment for the
* configuration screen.
*/
@Extension
public static final class DescriptorImpl extends BuildStepDescriptor<Publisher> {
@Override
public boolean isApplicable(Class<? extends AbstractProject> aClass) {
// indicates that this builder can be used with all kinds of project types
return true;
}
/** This human readable name is used in the configuration screen. */
@Override
public String getDisplayName() {
return "Chatter Results";
}
public FormValidation doCheckUsername(@QueryParameter String value) {
if(value.length()==0)
return FormValidation.error("Please enter a username");
if(value.indexOf('@') == -1)
return FormValidation.warning("Username's usually have an @ in them, e.g. hudson@example.org");
return FormValidation.ok();
}
public FormValidation doCheckPassword(@QueryParameter String value) {
if(value.length()==0)
return FormValidation.error("Please enter a password");
return FormValidation.ok();
}
public FormValidation doCheckRecordId(@QueryParameter String value) {
int l = value.length();
if (l == 0 || l == 15 || l == 18)
return FormValidation.ok();
return FormValidation.error("recordId should be blank, or should be a valid Salesforce.com recordId, e.g. 0F930000000PCJP");
}
public FormValidation doCheckServer(@QueryParameter String value) {
if (value.length() == 0)
return FormValidation.ok();
try {
URL u = new URL(value);
String h = u.getHost().toLowerCase();
if (!(h.endsWith(".salesforce.com") || h.endsWith(".force.com")))
return FormValidation.warning("Are you sure this is the correct URL, this doesn't appear to be a Salesforce.com server");
if (u.getProtocol().equalsIgnoreCase("http"))
return FormValidation.warning("Are you sure you want to use HTTP, its recommended to use HTTPS");
} catch (MalformedURLException e) {
return FormValidation.error("please enter a valid URL, e.g. https://test.salesforce.com");
}
return FormValidation.ok();
}
}
}
|
package com.sdl.selenium.web.table;
import com.sdl.selenium.web.SearchType;
import com.sdl.selenium.web.WebLocator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Row extends AbstractRow {
private static final Logger LOGGER = LoggerFactory.getLogger(Row.class);
public Row() {
setRenderMillis(200);
setClassName("Row");
setTag("tr");
getPathBuilder().defaultSearchTextType.add(SearchType.DEEP_CHILD_NODE_OR_SELF);
}
public Row(WebLocator container) {
this();
setContainer(container);
}
public Row(WebLocator container, int indexRow) {
this(container);
setPosition(indexRow);
}
public Row(WebLocator table, String searchElement, SearchType... searchTypes) {
this(table);
setText(searchElement, searchTypes);
}
public Row(WebLocator table, AbstractCell... cells) {
this(table);
List<AbstractCell> collect = Stream.of(cells).filter(t -> t.getPathBuilder().getText() != null).collect((Collectors.toList()));
setChildNodes(collect.toArray(new AbstractCell[collect.size()]));
}
public Row(WebLocator table, int indexRow, AbstractCell... cells) {
this(table, cells);
setPosition(indexRow);
}
public Cell getCell(int columnIndex) {
return new Cell(this, columnIndex);
}
public List<String> getCellsText() {
WebLocator columnsEl = new WebLocator(this).setTag("td");
int columns = columnsEl.size() + 1;
List<String> list = new ArrayList<>();
for (int j = 1; j < columns; j++) {
Cell cell = new Cell(this, j);
list.add(cell.getText().trim());
}
return list;
}
}
|
package com.sendgrid;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.SerializationFeature;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Class Mail builds an object that sends an email through SendGrid.
* Note that this object is not thread safe.
*/
@JsonInclude(Include.NON_DEFAULT)
public class Mail {
/** The email's from field. */
@JsonProperty("from") public Email from;
@JsonProperty("subject") public String subject;
/**
* The email's personalization. Each object within
* personalizations can be thought of as an envelope
* - it defines who should receive an individual message
* and how that message should be handled.
*/
@JsonProperty("personalizations") public List<Personalization> personalization;
/** The email's content. */
@JsonProperty("content") public List<Content> content;
/** The email's attachments. */
@JsonProperty("attachments") public List<Attachments> attachments;
/** The email's template ID. */
@JsonProperty("template_id") public String templateId;
/**
* The email's sections. An object of key/value pairs that
* define block sections of code to be used as substitutions.
*/
@JsonProperty("sections") public Map<String,String> sections;
/** The email's headers. */
@JsonProperty("headers") public Map<String,String> headers;
/** The email's categories. */
@JsonProperty("categories") public List<String> categories;
/**
* The email's custom arguments. Values that are specific to
* the entire send that will be carried along with the email
* and its activity data. Substitutions will not be made on
* custom arguments, so any string that is entered into this
* parameter will be assumed to be the custom argument that
* you would like to be used. This parameter is overridden by
* personalizations[x].custom_args if that parameter has been
* defined. Total custom args size may not exceed 10,000 bytes.
*/
@JsonProperty("custom_args") public Map<String,String> customArgs;
/**
* A unix timestamp allowing you to specify when you want
* your email to be delivered. This may be overridden by
* the personalizations[x].send_at parameter. Scheduling
* more than 72 hours in advance is forbidden.
*/
@JsonProperty("send_at") public long sendAt;
@JsonProperty("batch_id") public String batchId;
/** The email's unsubscribe handling object. */
@JsonProperty("asm") public ASM asm;
/** The email's IP pool name. */
@JsonProperty("ip_pool_name") public String ipPoolId;
/** The email's mail settings. */
@JsonProperty("mail_settings") public MailSettings mailSettings;
/** The email's tracking settings. */
@JsonProperty("tracking_settings") public TrackingSettings trackingSettings;
/** The email's reply to address. */
@JsonProperty("reply_to") public Email replyTo;
private static final ObjectMapper SORTED_MAPPER = new ObjectMapper();
static {
SORTED_MAPPER.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
}
/** Construct a new Mail object. */
public Mail() {
return;
}
/**
* Construct a new Mail object.
* @param from the email's from address.
* @param subject the email's subject line.
* @param to the email's recipient.
* @param content the email's content.
*/
public Mail(Email from, String subject, Email to, Content content)
{
this.setFrom(from);
this.setSubject(subject);
Personalization personalization = new Personalization();
personalization.addTo(to);
this.addPersonalization(personalization);
this.addContent(content);
}
/**
* Get the email's from address.
* @return the email's from address.
*/
@JsonProperty("from")
public Email getFrom() {
return this.from;
}
/**
* Set the email's from address.
* @param from the email's from address.
*/
public void setFrom(Email from) {
this.from = from;
}
/**
* Get the email's subject line.
* @return the email's subject line.
*/
@JsonProperty("subject")
public String getSubject() {
return subject;
}
/**
* Set the email's subject line.
* @param subject the email's subject line.
*/
public void setSubject(String subject) {
this.subject = subject;
}
/**
* Get the email's unsubscribe handling object (ASM).
* @return the email's ASM.
*/
@JsonProperty("asm")
public ASM getASM() {
return asm;
}
/**
* Set the email's unsubscribe handling object (ASM).
* @param asm the email's ASM.
*/
public void setASM(ASM asm) {
this.asm = asm;
}
/**
* Get the email's personalizations. Content added to the returned
* list will be included when sent.
* @return the email's personalizations.
*/
@JsonProperty("personalizations")
public List<Personalization> getPersonalization() {
return personalization;
}
/**
* Add a personalizaton to the email.
* @param personalization a personalization.
*/
public void addPersonalization(Personalization personalization) {
this.personalization = addToList(personalization, this.personalization);
}
/**
* Get the email's content. Content added to the returned list
* will be included when sent.
* @return the email's content.
*/
@JsonProperty("content")
public List<Content> getContent() {
return content;
}
/**
* Add content to this email.
* @param content content to add to this email.
*/
public void addContent(Content content) {
Content newContent = new Content();
newContent.setType(content.getType());
newContent.setValue(content.getValue());
this.content = addToList(newContent, this.content);
}
/**
* Get the email's attachments. Attachments added to the returned
* list will be included when sent.
* @return the email's attachments.
*/
@JsonProperty("attachments")
public List<Attachments> getAttachments() {
return attachments;
}
/**
* Add attachments to the email.
* @param attachments attachments to add.
*/
public void addAttachments(Attachments attachments) {
Attachments newAttachment = new Attachments();
newAttachment.setContent(attachments.getContent());
newAttachment.setType(attachments.getType());
newAttachment.setFilename(attachments.getFilename());
newAttachment.setDisposition(attachments.getDisposition());
newAttachment.setContentId(attachments.getContentId());
this.attachments = addToList(newAttachment, this.attachments);
}
/**
* Get the email's template ID.
* @return the email's template ID.
*/
@JsonProperty("template_id")
public String getTemplateId() {
return this.templateId;
}
/**
* Set the email's template ID.
* @param templateId the email's template ID.
*/
public void setTemplateId(String templateId) {
this.templateId = templateId;
}
/**
* Get the email's sections. Sections added to the returned list
* will be included when sent.
* @return the email's sections.
*/
@JsonProperty("sections")
public Map<String,String> getSections() {
return sections;
}
/**
* Add a section to the email.
* @param key the section's key.
* @param value the section's value.
*/
public void addSection(String key, String value) {
this.sections = addToMap(key, value, this.sections);
}
/**
* Get the email's headers. Headers added to the returned list
* will be included when sent.
* @return the email's headers.
*/
@JsonProperty("headers")
public Map<String,String> getHeaders() {
return headers;
}
/**
* Add a header to the email.
* @param key the header's key.
* @param value the header's value.
*/
public void addHeader(String key, String value) {
this.headers = addToMap(key, value, this.headers);
}
/**
* Get the email's categories. Categories added to the returned list
* will be included when sent.
* @return the email's categories.
*/
@JsonProperty("categories")
public List<String> getCategories() {
return categories;
}
/**
* Add a category to the email.
* @param category the category.
*/
public void addCategory(String category) {
this.categories = addToList(category, this.categories);
}
/**
* Get the email's custom arguments. Custom arguments added to the returned list
* will be included when sent.
* @return the email's custom arguments.
*/
@JsonProperty("custom_args")
public Map<String,String> getCustomArgs() {
return customArgs;
}
/**
* Add a custom argument to the email.
* @param key argument's key.
* @param value the argument's value.
*/
public void addCustomArg(String key, String value) {
this.customArgs = addToMap(key, value, this.customArgs);
}
/**
* Get the email's send at time (Unix timestamp).
* @return the email's send at time.
*/
@JsonProperty("send_at")
public long sendAt() {
return sendAt;
}
/**
* Set the email's send at time (Unix timestamp).
* @param sendAt the send at time.
*/
public void setSendAt(long sendAt) {
this.sendAt = sendAt;
}
/**
* Get the email's batch ID.
* @return the batch ID.
*/
@JsonProperty("batch_id")
public String getBatchId() {
return batchId;
}
/**
* Set the email's batch ID.
* @param batchId the batch ID.
*/
public void setBatchId(String batchId) {
this.batchId = batchId;
}
/**
* Get the email's IP pool ID.
* @return the IP pool ID.
*/
@JsonProperty("ip_pool_name")
public String getIpPoolId() {
return ipPoolId;
}
/**
* Set the email's IP pool ID.
* @param ipPoolId the IP pool ID.
*/
public void setIpPoolId(String ipPoolId) {
this.ipPoolId = ipPoolId;
}
/**
* Get the email's settings.
* @return the settings.
*/
@JsonProperty("mail_settings")
public MailSettings getMailSettings() {
return mailSettings;
}
/**
* Set the email's settings.
* @param mailSettings the settings.
*/
public void setMailSettings(MailSettings mailSettings) {
this.mailSettings = mailSettings;
}
/**
* Get the email's tracking settings.
* @return the tracking settings.
*/
@JsonProperty("tracking_settings")
public TrackingSettings getTrackingSettings() {
return trackingSettings;
}
/**
* Set the email's tracking settings.
* @param trackingSettings the tracking settings.
*/
public void setTrackingSettings(TrackingSettings trackingSettings) {
this.trackingSettings = trackingSettings;
}
/**
* Get the email's reply to address.
* @return the reply to address.
*/
@JsonProperty("reply_to")
public Email getReplyto() {
return replyTo;
}
/**
* Set the email's reply to address.
* @param replyTo the reply to address.
*/
public void setReplyTo(Email replyTo) {
this.replyTo = replyTo;
}
/**
* Create a string represenation of the Mail object JSON.
* @return a JSON string.
* @throws IOException in case of a JSON marshal error.
*/
public String build() throws IOException {
try {
//ObjectMapper mapper = new ObjectMapper();
return SORTED_MAPPER.writeValueAsString(this);
} catch (IOException ex) {
throw ex;
}
}
/**
* Create a string represenation of the Mail object JSON and pretty print it.
* @return a pretty JSON string.
* @throws IOException in case of a JSON marshal error.
*/
public String buildPretty() throws IOException {
try {
ObjectMapper mapper = new ObjectMapper();
return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(this);
} catch (IOException ex) {
throw ex;
}
}
private <T> List<T> addToList(T element, List<T> defaultList) {
if (defaultList != null) {
defaultList.add(element);
return defaultList;
} else {
List<T> list = new ArrayList<T>();
list.add(element);
return list;
}
}
private <K,V> Map<T,V> addToMap(K key, V value, Map<K,V> defaultMap) {
if (defaultMap != null) {
defaultMap.put(key, value);
return defaultMap;
} else {
Map<T,V> map = new HashMap<K,V>();
map.put(key, value);
return map;
}
}
}
|
package com.shawn.dev;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SmoothExpression {
public SmoothExpression(final Pattern pattern) {
this.pattern = pattern;
}
public String getRegularExpression() {
return this.pattern.pattern();
}
public boolean matches(String target) {
return pattern.matcher(target).matches();
}
public List<String> getTextGroups(final String toTest, final int group) {
List<String> groups = new ArrayList<String>();
Matcher m = pattern.matcher(toTest);
while (m.find()) {
groups.add(m.group(group));
}
return groups;
}
private final Pattern pattern;
public static ExpressionBuilder regex() {
return new ExpressionBuilder();
}
public static class ExpressionBuilder {
private StringBuilder prefix = new StringBuilder();
private StringBuilder patternContent = new StringBuilder();
private StringBuilder suffix = new StringBuilder();
private int modifiers = Pattern.MULTILINE;
ExpressionBuilder() {
}
private ExpressionBuilder add(String content) {
patternContent.append("(?:" + content + ")");
return this;
}
public ExpressionBuilder anything() {
this.add("[\\s\\S]*");
return this;
}
public ExpressionBuilder anythingBut(String content) {
this.add("[^" + content + "]*");
return this;
}
public ExpressionBuilder startOfLine() {
this.add("^");
return this;
}
public ExpressionBuilder endOfLine() {
this.add("$");
return this;
}
public ExpressionBuilder singleDigit() {
this.add("\\d");
return this;
}
public ExpressionBuilder integerNumber() {
this.add("\\d+");
return this;
}
public ExpressionBuilder floatNumber() {
this.add("-?([1-9]\\d*\\.\\d*|0\\.\\d*[1-9]\\d*|0?\\.0+|0)");
return this;
}
public ExpressionBuilder wordChar() {
return this;
}
public ExpressionBuilder nonWordChar() {
return this;
}
public ExpressionBuilder then(final String content) {
this.add(content);
return this;
}
public ExpressionBuilder capture() {
patternContent.append("(");
return this;
}
public ExpressionBuilder endCapture() {
patternContent.append(")");
return this;
}
public ExpressionBuilder oneOrMore() {
return this;
}
public ExpressionBuilder zeroOrMore() {
return this;
}
public ExpressionBuilder maybe(final String content) {
return this;
}
public ExpressionBuilder addModifier(final char pModifier) {
switch (pModifier) {
case 'd':
modifiers |= Pattern.UNIX_LINES;
break;
case 'i':
modifiers |= Pattern.CASE_INSENSITIVE;
break;
case 'x':
modifiers |= Pattern.COMMENTS;
break;
case 'm':
modifiers |= Pattern.MULTILINE;
break;
case 's':
modifiers |= Pattern.DOTALL;
break;
case 'u':
modifiers |= Pattern.UNICODE_CASE;
break;
case 'U':
modifiers |= Pattern.UNICODE_CHARACTER_CLASS;
break;
default:
break;
}
return this;
}
public ExpressionBuilder removeModifier(final char pModifier) {
switch (pModifier) {
case 'd':
modifiers &= ~Pattern.UNIX_LINES;
break;
case 'i':
modifiers &= ~Pattern.CASE_INSENSITIVE;
break;
case 'x':
modifiers &= ~Pattern.COMMENTS;
break;
case 'm':
modifiers &= ~Pattern.MULTILINE;
break;
case 's':
modifiers &= ~Pattern.DOTALL;
break;
case 'u':
modifiers &= ~Pattern.UNICODE_CASE;
break;
case 'U':
modifiers &= ~Pattern.UNICODE_CHARACTER_CLASS;
break;
default:
break;
}
return this;
}
public SmoothExpression build() {
Pattern pattern = Pattern.compile(
this.prefix.toString() +
this.patternContent.toString() +
this.suffix.toString(),
modifiers);
return new SmoothExpression(pattern);
}
}
public static void main(String[] args) {
SmoothExpression exp = SmoothExpression.regex().capture().integerNumber().endCapture().then("aa").build();
System.out.println(exp.getRegularExpression());
System.out.println(exp.matches("11 12 11"));
List<String> list = exp.getTextGroups("11aa12aa", 0);
for (String s : list) {
System.out.println(s);
}
}
}
|
package com.sjl.dsl4xml;
import org.xmlpull.v1.*;
import com.sjl.dsl4xml.support.*;
public interface ReadingContext {
public abstract void registerConverters(Converter<?>... aConverters);
public abstract <T> T peek();
public abstract void push(Object aContext);
public abstract <T> T pop();
public abstract XmlPullParser getParser();
public abstract boolean hasMoreTags();
public abstract int next();
public abstract boolean isTagNamed(String aTagName);
public abstract boolean isNotEndTag(String aTagName);
public abstract boolean isStartTag();
public abstract String getAttributeValue(String anAttributeName);
public abstract String getAttributeValue(int anIndex);
public abstract boolean isTextNode();
public abstract boolean isStartTagNamed(String aTagName);
public abstract <T> Converter<T> getConverter(Class<T> aArgType);
}
|
package com.slickqa.client;
import com.slickqa.client.apiparts.ProjectApi;
import com.slickqa.client.apiparts.QueryApi;
import com.slickqa.client.model.Project;
import java.util.Map;
public interface SlickClient
{
/**
* No filtering, retrieve all projects.
*/
public QueryApi<Project> projects();
/**
* Filter based on properties of a project. Dotted sub properties are allowed.
* @param properties A map of properties and their values to filter the projects by.
*/
public QueryApi<Project> projects(Map<String, String> properties);
/**
* Filter the results based of a standard slick query.
* @param query The query to perform, using slick's generic query language.
*/
public QueryApi<Project> projects(String query);
/**
* Filter the results based of a standard slick query, setting a property to order the results by.
*
* @param query The query to perform, using slick's generic query language.
* @param orderBy The name of the property to order the results by. Prefix with a '-' for descending order.
*/
public QueryApi<Project> projects(String query, String orderBy);
/**
* Filter the results based of a standard slick query, setting a property to order the results by. Also you can
* specify a limit to the number of results and set a number of results to skip (for paging purposes).
*
* @param query The query to perform, using slick's generic query language.
* @param orderBy The name of the property to order the results by. Prefix with a '-' for descending order.
* @param limit The maximum number of results to return, or null for no limit.
* @param skip The number of results to skip (maintaining order), or null for no skip.
*/
public QueryApi<Project> projects(String query, String orderBy, Integer limit, Integer skip);
/**
* Perform operations against a specific project. You must use this form for create, getOrCreate, or update
* operations of a project.
*
* @param project The project to perform operations on.
*/
public ProjectApi project(Project project);
/**
* Perform operations against a specific project. You can use this form if you are using get or delete operations.
* This form allows you to specify the name or the id of the project to get or delete.
*
* @param idOrName The id (string representation of the BSON Object Id) or the name of the project.
*/
public ProjectApi project(String idOrName);
}
|
package com.stuonline;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Base64;
import android.view.View;
import android.widget.Toast;
import com.alibaba.fastjson.TypeReference;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.stuonline.entity.Muser;
import com.stuonline.entity.Result;
import com.stuonline.https.MyCallBack;
import com.stuonline.https.XUtils;
import com.stuonline.utils.DialogUtil;
import com.stuonline.utils.JsonUtil;
import com.stuonline.utils.SharedUtil;
import com.stuonline.views.CustomerEditText;
import com.stuonline.views.TitleView;
public class RegisterActivity extends BaseActivity {
@ViewInject(R.id.register_title)
private TitleView mTitle;
@ViewInject(R.id.register_email)
private CustomerEditText mEmail;
@ViewInject(R.id.register_pwd)
private CustomerEditText mPassword;
@ViewInject(R.id.register_repeatepwd)
private CustomerEditText mRepeatPassword;
private String account;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
init();
}
private void init() {
setContentView(R.layout.activity_register);
ViewUtils.inject(this);
account = getIntent().getStringExtra("account");
}
@OnClick({R.id.title_left, R.id.title_right})
public void onClick(View v) {
switch (v.getId()) {
case R.id.title_left:
finish();
break;
case R.id.title_right:
getRegisterEditText();
break;
}
}
public void getRegisterEditText() {
String email = mEmail.getText();
String password = mPassword.getText();
String repeatPassword = mRepeatPassword.getText();
if (TextUtils.isEmpty(email) && TextUtils.isEmpty(password) && TextUtils.isEmpty(repeatPassword)) {
if (TextUtils.isEmpty(email))
XUtils.showToast("!");
if (TextUtils.isEmpty(password))
XUtils.showToast("!");
if (TextUtils.isEmpty(repeatPassword))
XUtils.showToast("!");
} else {
if (!email.matches("^[a-z0-9]+([._\\\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$")) {
XUtils.showToast("");
} else {
if (!password.equals(repeatPassword)) {
XUtils.showToast("");
} else {
RequestParams params = new RequestParams();
params.addBodyParameter("u.account", account);
params.addBodyParameter("u.pwd", password);
params.addBodyParameter("u.email", email);
DialogUtil.showWaitting(this);
XUtils.send(XUtils.REG, params, new MyCallBack<String>() {
@Override
public void onSuccess(ResponseInfo<String> responseInfo) {
DialogUtil.hiddenWaitting();
if (responseInfo != null) {
JsonUtil<Result<Boolean>> jsonUtil = new JsonUtil<Result<Boolean>>(new TypeReference<Result<Boolean>>() {
});
Result<Boolean> result = jsonUtil.parse(responseInfo.result);
XUtils.showToast(result.desc);
if (result.data){
finish();
}
}
}
});
}
}
}
}
@Override
protected void onResume() {
super.onResume();
boolean isNight= SharedUtil.getModel(this);
if (isNight){
setTheme(R.style.night);
} else {
setTheme(R.style.def);
}
init();
}
}
|
package com.wizzardo.jrt;
import com.wizzardo.http.framework.Controller;
import com.wizzardo.http.framework.ControllerUrlMapping;
import com.wizzardo.http.framework.di.DependencyFactory;
import com.wizzardo.http.framework.template.Renderer;
import com.wizzardo.tools.collections.CollectionTools;
import com.wizzardo.tools.io.FileTools;
import com.wizzardo.tools.json.JsonTools;
import com.wizzardo.tools.security.MD5;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class AppController extends Controller {
RTorrentService rtorrentService;
ControllerUrlMapping mapping = DependencyFactory.get(ControllerUrlMapping.class);
public Renderer index() {
List<TorrentInfo> torrents = rtorrentService.list();
model().append("torrents", torrents);
Map<String, Collection<TorrentEntry>> entries = new HashMap<>();
model().append("entries", entries);
for (TorrentInfo torrent : torrents) {
entries.put(torrent.getHash(), rtorrentService.entries(torrent));
}
return renderView("index__");
}
public Renderer riotIndex() {
model().append("config", JsonTools.serialize(new CollectionTools.MapBuilder<>()
.add("ws", mapping.getUrlTemplate("ws").getRelativeUrl())
.add("addTorrent", mapping.getUrlTemplate(AppController.class, "addTorrent").getRelativeUrl())
.get()
));
return renderView("index");
}
public Renderer addTorrent() throws IOException {
if (request.isMultipart()) {
request.prepareMultiPart();
String link = request.entry("url").asString();
byte[] file = request.entry("file").asBytes();
// System.out.println("link: " + link);
// System.out.println("file: " + file.length + " " + MD5.create().update(file).asString());
if (file.length != 0) {
File tempFile = File.createTempFile("jrt", "torrent");
tempFile.deleteOnExit();
FileTools.bytes(tempFile, file);
rtorrentService.load(tempFile.getAbsolutePath());
} else if (!link.isEmpty()) {
rtorrentService.load(link);
} else {
throw new IllegalArgumentException("link and file are empty");
}
}
return renderString("ok");
}
}
|
package crazypants.enderio;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Random;
import crazypants.enderio.capacitor.LootSelector;
import crazypants.enderio.config.Config;
import crazypants.enderio.item.darksteel.DarkSteelItems;
import crazypants.enderio.material.Alloy;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.world.storage.loot.LootContext;
import net.minecraft.world.storage.loot.LootEntry;
import net.minecraft.world.storage.loot.LootPool;
import net.minecraft.world.storage.loot.LootTable;
import net.minecraft.world.storage.loot.LootTableList;
import net.minecraft.world.storage.loot.RandomValueRange;
import net.minecraft.world.storage.loot.conditions.LootCondition;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.LootTableLoadEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
public class LootManager {
private static LootManager INSTANCE = new LootManager();
public static void register() {
MinecraftForge.EVENT_BUS.register(INSTANCE);
}
private LootManager() {
}
@SubscribeEvent
public void onLootTableLoad(LootTableLoadEvent evt) {
LootTable table = evt.getTable();
InnerPool lp = new InnerPool();
if (evt.getName().equals(LootTableList.CHESTS_SIMPLE_DUNGEON)) {
if (Config.lootDarkSteel) {
lp.addItem(createLootEntry(EnderIO.itemAlloy, Alloy.DARK_STEEL.ordinal(), 1, 3, 0.25));
}
if (Config.lootItemConduitProbe) {
lp.addItem(createLootEntry(EnderIO.itemConduitProbe, 0.10));
}
if (Config.lootQuartz) {
lp.addItem(createLootEntry(Items.QUARTZ, 3, 16, 0.25));
}
if (Config.lootNetherWart) {
lp.addItem(createLootEntry(Items.NETHER_WART, 1, 4, 0.20));
}
if (Config.lootEnderPearl) {
lp.addItem(createLootEntry(Items.ENDER_PEARL, 1, 2, 0.30));
}
if (Config.lootTheEnder) {
lp.addItem(createLootEntry(DarkSteelItems.itemDarkSteelSword, 0.1));
}
if (Config.lootDarkSteelBoots) {
lp.addItem(createLootEntry(DarkSteelItems.itemDarkSteelBoots, 0.1));
}
lp.addItem(createLootCapacitor(0.15));
lp.addItem(createLootCapacitor(0.15));
lp.addItem(createLootCapacitor(0.15));
} else if (evt.getName().equals(LootTableList.CHESTS_VILLAGE_BLACKSMITH)) {
if (Config.lootElectricSteel) {
lp.addItem(createLootEntry(EnderIO.itemAlloy, Alloy.ELECTRICAL_STEEL.ordinal(), 2, 6, 0.20));
}
if (Config.lootRedstoneAlloy) {
lp.addItem(createLootEntry(EnderIO.itemAlloy, Alloy.REDSTONE_ALLOY.ordinal(), 3, 6, 0.35));
}
if (Config.lootDarkSteel) {
lp.addItem(createLootEntry(EnderIO.itemAlloy, Alloy.DARK_STEEL.ordinal(), 3, 6, 0.35));
}
if (Config.lootPhasedIron) {
lp.addItem(createLootEntry(EnderIO.itemAlloy, Alloy.PULSATING_IRON.ordinal(), 1, 2, 0.3));
}
if (Config.lootPhasedGold) {
lp.addItem(createLootEntry(EnderIO.itemAlloy, Alloy.VIBRANT_ALLOY.ordinal(), 1, 2, 0.2));
}
if (Config.lootTheEnder) {
lp.addItem(createLootEntry(DarkSteelItems.itemDarkSteelSword, 1, 1, 0.25));
}
if (Config.lootDarkSteelBoots) {
lp.addItem(createLootEntry(DarkSteelItems.itemDarkSteelBoots, 1, 1, 0.25));
}
lp.addItem(createLootCapacitor(0.1));
} else if (evt.getName().equals(LootTableList.CHESTS_DESERT_PYRAMID)) {
if (Config.lootTheEnder) {
lp.addItem(createLootEntry(DarkSteelItems.itemDarkSteelSword, 0.2));
}
if (Config.lootTravelStaff) {
lp.addItem(createLootEntry(EnderIO.itemTravelStaff, 0.1));
}
lp.addItem(createLootCapacitor(25));
} else if (evt.getName().equals(LootTableList.CHESTS_JUNGLE_TEMPLE)) {
if (Config.lootTheEnder) {
lp.addItem(createLootEntry(DarkSteelItems.itemDarkSteelSword, 1, 1, 0.25));
}
if (Config.lootTravelStaff) {
lp.addItem(createLootEntry(EnderIO.itemTravelStaff, 1, 1, 0.1));
}
lp.addItem(createLootCapacitor(0.25));
lp.addItem(createLootCapacitor(0.25));
}
if (!lp.isEmpty()) {
table.addPool(lp);
}
}
private LootItem createLootEntry(Item item, double chance) {
return new LootItem(new ItemStack(item), chance, 1, 1);
}
private LootItem createLootEntry(Item item, int minSize, int maxSize, double chance) {
return new LootItem(new ItemStack(item), chance, minSize, maxSize);
}
private LootItem createLootEntry(Item item, int ordinal, int minStackSize, int maxStackSize, double chance) {
return new LootItem(new ItemStack(item, 1, ordinal), chance, minStackSize, maxStackSize);
}
private LootItem createLootCapacitor(double weight) {
return new CapItem(weight);
}
private static LootSelector ls = new LootSelector(new LootCondition[0]);
private static class CapItem extends LootItem {
public CapItem(double chance) {
super(new ItemStack(EnderIO.itemBasicCapacitor), chance);
}
public ItemStack createStack(Random rnd) {
ItemStack res = item.copy();
ls.apply(res, rnd, null);
return res;
}
}
private static class LootItem {
ItemStack item;
double chance;
int minSize;
int maxSize;
public LootItem(ItemStack item, double chance) {
this(item, chance, 1, 1);
}
public LootItem(ItemStack item, double chance, int minSize, int maxSize) {
this.item = item;
this.chance = chance;
this.minSize = minSize;
this.maxSize = maxSize;
}
public ItemStack createStack(Random rnd) {
int size = minSize;
if (maxSize > minSize) {
size += rnd.nextInt(maxSize - minSize + 1);
}
ItemStack result = item.copy();
result.stackSize = size;
return result;
}
}
private static class InnerPool extends LootPool {
private final List<LootItem> items = new ArrayList<LootItem>();
public InnerPool() {
super(new LootEntry[0], new LootCondition[0], new RandomValueRange(0, 0), new RandomValueRange(0, 0), EnderIO.MOD_NAME);
}
public boolean isEmpty() {
return items.isEmpty();
}
public void addItem(LootItem entry) {
if (entry != null) {
items.add(entry);
}
}
public void generateLoot(Collection<ItemStack> stacks, Random rand, LootContext context) {
for (LootItem entry : items) {
if (rand.nextDouble() < entry.chance) {
ItemStack stack = entry.createStack(rand);
if (stack != null) {
// System.out.println("LootManager.InnerPool.generateLoot: Added " + stack.getDisplayName() + " " + stack);
stacks.add(stack);
}
}
}
}
}
}
|
package de.jeha.s3pt;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.Protocol;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import de.jeha.s3pt.operations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
/**
* @author jenshadlich@googlemail.com
*/
public class S3PerformanceTest implements Runnable {
private static final Logger LOG = LoggerFactory.getLogger(S3PerformanceTest.class);
private final String accessKey;
private final String secretKey;
private final String endpointUrl;
private final String bucketName;
private final Operation operation;
private final int threads;
private final int n;
private final int size;
private final boolean useHttp;
/**
* @param accessKey access key
* @param secretKey secret key
* @param endpointUrl endpoint url
* @param bucketName bucket name
* @param n number of operations
* @param size size for upload operations
*/
public S3PerformanceTest(String accessKey, String secretKey, String endpointUrl, String bucketName,
Operation operation, int threads, int n, int size, boolean useHttp) {
this.accessKey = accessKey;
this.secretKey = secretKey;
this.endpointUrl = endpointUrl;
this.bucketName = bucketName;
this.operation = operation;
this.threads = threads;
this.n = n;
this.size = size;
this.useHttp = useHttp;
}
@Override
public void run() {
AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
ClientConfiguration clientConfig = new ClientConfiguration();
clientConfig.setProtocol(useHttp ? Protocol.HTTP : Protocol.HTTPS);
AmazonS3 s3Client = new AmazonS3Client(credentials, clientConfig);
s3Client.setEndpoint(endpointUrl);
ExecutorService executorService = Executors.newFixedThreadPool(threads);
List<Callable<OperationResult>> operations = new ArrayList<>();
if (operation.isMultiThreaded()) {
for (int i = 0; i < threads; i++) {
operations.add(createOperation(operation, s3Client));
}
} else {
if (threads > 1) {
LOG.warn("operation {} does not support multiple threads, use single thread", operation);
}
operations.add(createOperation(operation, s3Client));
}
try {
List<Future<OperationResult>> futureResults = executorService.invokeAll(operations);
List<OperationResult> results = new ArrayList<>();
for (Future<OperationResult> result : futureResults) {
results.add(result.get());
}
printResults(results);
} catch (InterruptedException | ExecutionException e) {
LOG.error("An error occurred", e);
}
executorService.shutdown();
LOG.info("Done");
}
private AbstractOperation createOperation(Operation operation, AmazonS3 s3Client) {
switch (operation) {
case UPLOAD:
return new Upload(s3Client, bucketName, n, size);
case CREATE_BUCKET:
return new CreateBucket(s3Client, bucketName);
case CLEAR_BUCKET:
return new ClearBucket(s3Client, bucketName, n);
case RANDOM_READ:
return new RandomRead(s3Client, bucketName, n);
default:
throw new UnsupportedOperationException("Unknown operation: " + operation);
}
}
private void printResults(List<OperationResult> results) {
int min = (int) results.stream().mapToDouble(x -> x.getStats().getMin()).average().orElse(0.0);
int max = (int) results.stream().mapToDouble(x -> x.getStats().getMax()).average().orElse(0.0);
int avg = (int) results.stream().mapToDouble(x -> x.getStats().getGeometricMean()).average().orElse(0.0);
int p50 = (int) results.stream().mapToDouble(x -> x.getStats().getPercentile(50)).average().orElse(0.0);
int p75 = (int) results.stream().mapToDouble(x -> x.getStats().getPercentile(75)).average().orElse(0.0);
int p95 = (int) results.stream().mapToDouble(x -> x.getStats().getPercentile(95)).average().orElse(0.0);
int p98 = (int) results.stream().mapToDouble(x -> x.getStats().getPercentile(98)).average().orElse(0.0);
int p99 = (int) results.stream().mapToDouble(x -> x.getStats().getPercentile(99)).average().orElse(0.0);
double throughputPerSecond =
results.stream().mapToDouble(x -> x.getStats().getN() / x.getStats().getSum() * 1000).sum();
LOG.info("Request statistics:");
LOG.info("min = {} ms", min);
LOG.info("max = {} ms", max);
LOG.info("avg = {} ms", avg);
LOG.info("p50 = {} ms", p50);
LOG.info("p75 = {} ms", p75);
LOG.info("p95 = {} ms", p95);
LOG.info("p98 = {} ms", p98);
LOG.info("p99 = {} ms", p99);
LOG.info("throughput = {} requests/s ({} threads)", (int) throughputPerSecond, threads);
}
}
|
package de.tilosp.chess.lib;
public final class ChessPiece {
public final ChessPieceType chessPieceType;
public final PlayerColor playerColor;
private final int movements;
private final int movedInTurn;
private final boolean enPassant;
ChessPiece(ChessPieceType chessPieceType, PlayerColor playerColor) {
this(chessPieceType, playerColor, 0, 0, false);
}
private ChessPiece(ChessPieceType chessPieceType, PlayerColor playerColor, int movements, int movedInTurn, boolean enPassant) {
this.chessPieceType = chessPieceType;
this.playerColor = playerColor;
this.movements = movements;
this.movedInTurn = movedInTurn;
this.enPassant = enPassant;
}
int[][] getMove() {
return chessPieceType.getMove(notMoved());
}
int[][] getCapture() {
return chessPieceType.capture;
}
ChessPiece moved(int turn, boolean enPassant) {
return new ChessPiece(chessPieceType, playerColor, movements + 1, turn, enPassant);
}
ChessPiece promotion(ChessPieceType chessPieceType) {
return new ChessPiece(chessPieceType, playerColor, movements, movedInTurn, false);
}
boolean notMoved() {
return movements == 0;
}
boolean checkEnPassant(int turn) {
return turn == movedInTurn + 1 && enPassant;
}
boolean checkPromotion(int y) {
return chessPieceType == ChessPieceType.PAWN && (playerColor == PlayerColor.WHITE ? 0 : 7) == y;
}
@Override
public String toString() {
return chessPieceType.toString() + playerColor.toString();
}
}
|
package dk.itu.kelvin.util;
// General utilities
import java.util.Arrays;
import java.util.Comparator;
/**
* Collections class.
*/
public final class Collections {
private Collections() {
super();
}
/**
* Sort a list of comparable elements.
*
* <p>
* The list will be sorted in-place.
*
* @param <T> The type of elements to sort.
* @param list The list of comparable elements to sort.
*/
@SuppressWarnings("unchecked")
public static <T extends Comparable<? super T>> void sort(
final List<T> list
) {
T[] elements = (T[]) list.toArray();
Arrays.sort(elements);
for (int i = 0; i < elements.length; i++) {
list.set(i, elements[i]);
}
}
/**
* Sort a list of elements using the specified comparator.
*
* <p>
* The list will be sorted in-place.
*
* @param <T> The type of elements to sort.
* @param list The list of elements to sort.
* @param comparator The comparator to use for sorting the list.
*/
@SuppressWarnings("unchecked")
public static <T> void sort(
final List<T> list,
final Comparator<? super T> comparator
) {
T[] elements = (T[]) list.toArray();
Arrays.sort(elements, comparator);
for (int i = 0; i < elements.length; i++) {
list.set(i, elements[i]);
}
}
}
|
package dmillerw.bling;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.registry.EntityRegistry;
import cpw.mods.fml.common.registry.GameRegistry;
import dmillerw.bling.client.render.PotionEffectRenderer;
import dmillerw.bling.entity.EntityBaublePotion;
import dmillerw.bling.entity.EntitySplashPotion;
import dmillerw.bling.handler.BlacklistHandler;
import dmillerw.bling.handler.BrewingHandler;
import dmillerw.bling.handler.EntityEventHandler;
import dmillerw.bling.handler.EventHelper;
import dmillerw.bling.item.ItemBrewableBottle;
import dmillerw.bling.item.ItemSilverIngot;
import dmillerw.bling.item.bauble.BaublePotion;
import dmillerw.bling.recipe.RecipeIronBottle;
import dmillerw.bling.recipe.RecipeSilver;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.potion.Potion;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.oredict.OreDictionary;
import net.minecraftforge.oredict.ShapedOreRecipe;
import java.io.File;
/**
* @author dmillerw
*/
@Mod(modid = AlchemicalBling.ID, name= AlchemicalBling.NAME, version="%VERSION%", dependencies="required-after:Forge@[%FORGE_VERSION%,);required-after:Baubles")
public class AlchemicalBling {
public static final String ID = "AlchBling";
public static final String NAME = "Alchemical Bling";
@Mod.Instance(AlchemicalBling.ID)
public static AlchemicalBling instance;
public static File configFile;
public static Item baublePotion;
public static Item ingotSilver;
//TODO Broken amulet?
/* Ugly, but unfortunately necessary */
public static Item bottleIron;
public static Item bottleMoltenIron;
public static Item bottleSilver;
/* End the ugliness! */
public static boolean registerSilverWithOreDictionary = true;
public static boolean allowOreDictionarySilver = true;
@Mod.EventHandler
public void preInit(FMLPreInitializationEvent event) {
AlchemicalBling.configFile = event.getSuggestedConfigurationFile();
/* CONFIG */
Configuration configuration = new Configuration(configFile);
try {
registerSilverWithOreDictionary = configuration.get(Configuration.CATEGORY_GENERAL, "_registerSilverWithOreDictionary", true).getBoolean(true);
allowOreDictionarySilver = configuration.get(Configuration.CATEGORY_GENERAL, "_allowOreDictionarySilver", true).getBoolean(true);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (configuration.hasChanged()) {
configuration.save();
}
}
/* REGISTRATION */
baublePotion = new BaublePotion().setUnlocalizedName("bauble.potion");
ingotSilver = new ItemSilverIngot().setUnlocalizedName("ingot.silver");
bottleIron = new ItemBrewableBottle(ItemBrewableBottle.IRON.getRGB()).setUnlocalizedName("bottle.iron");
bottleMoltenIron = new ItemBrewableBottle(ItemBrewableBottle.MOLTEN_IRON.getRGB()).setUnlocalizedName("bottle.molten_iron");
bottleSilver = new ItemBrewableBottle(ItemBrewableBottle.SILVER.getRGB()).setUnlocalizedName("bottle.silver");
GameRegistry.registerItem(baublePotion, baublePotion.getUnlocalizedName());
GameRegistry.registerItem(ingotSilver, ingotSilver.getUnlocalizedName());
GameRegistry.registerItem(bottleIron, bottleIron.getUnlocalizedName());
GameRegistry.registerItem(bottleMoltenIron, bottleMoltenIron.getUnlocalizedName());
GameRegistry.registerItem(bottleSilver, bottleSilver.getUnlocalizedName());
/* FILL STATIC REFERENCES */
if (registerSilverWithOreDictionary) {
OreDictionary.registerOre("ingotSilver", ingotSilver);
}
if (event.getSide().isClient()) {
MinecraftForge.EVENT_BUS.register(new PotionEffectRenderer());
}
EventHelper.batchRegister(new EntityEventHandler(), new BrewingHandler());
EntityRegistry.registerModEntity(EntitySplashPotion.class, "splashPotion", 1, AlchemicalBling.instance, 64, 64, true);
EntityRegistry.registerModEntity(EntityBaublePotion.class, "potionAmulet", 2, AlchemicalBling.instance, 64, 64, true);
/* RECIPES */
GameRegistry.addRecipe(new RecipeIronBottle());
GameRegistry.addSmelting(
new ItemStack(bottleIron),
new ItemStack(bottleMoltenIron),
0F
);
GameRegistry.addRecipe(new RecipeSilver());
/* AMULET */
GameRegistry.addShapedRecipe(
new ItemStack(baublePotion, 1, 0),
" I ",
"IBI",
" D ",
'I', ingotSilver,
'B', new ItemStack(Items.potionitem, 1, OreDictionary.WILDCARD_VALUE),
'D', Items.diamond
);
/* RING */
GameRegistry.addShapedRecipe(
new ItemStack(baublePotion, 1, 1),
"DI ",
"IBI",
" I ",
'I', ingotSilver,
'B', new ItemStack(Items.potionitem, 1, OreDictionary.WILDCARD_VALUE),
'D', Items.diamond
);
if (allowOreDictionarySilver) {
/* AMULET */
GameRegistry.addRecipe(new ShapedOreRecipe(
new ItemStack(baublePotion, 1, 0),
" I ",
"IBI",
" D ",
'I', "ingotSilver",
'B', new ItemStack(Items.potionitem, 1, OreDictionary.WILDCARD_VALUE),
'D', Items.diamond
));
/* RING */
GameRegistry.addRecipe(new ShapedOreRecipe(
new ItemStack(baublePotion, 1, 1),
"DI ",
"IBI",
" I ",
'I', "ingotSilver",
'B', new ItemStack(Items.potionitem, 1, OreDictionary.WILDCARD_VALUE),
'D', Items.diamond
));
}
}
@Mod.EventHandler
public void postInit(FMLPostInitializationEvent event) {
Configuration configuration = new Configuration(configFile);
try {
for (Potion potion : Potion.potionTypes) {
if (potion != null) {
if (!configuration.get(Configuration.CATEGORY_GENERAL, potion.getName(), true).getBoolean(true)) {
BlacklistHandler.blacklist(potion.getId());
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (configuration.hasChanged()) {
configuration.save();
}
}
}
}
|
package edu.rice.seclab.dso;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.RandomAccessFile;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.lang3.StringUtils;
import com.google.common.primitives.UnsignedLong;
@SuppressWarnings("deprecation")
public class Ffastrings {
@SuppressWarnings("deprecation")
ArrayList<File> myTargetFiles = null;
public static final String MIN_STRING_LEN = "minStringLen";
public static final String BINARY_FILE = "binaryFile";
public static final String LIVE_UPDATE = "liveUpdate";
public static final String BASIC_OUTPUT = "basicOutput";
public static final String OUTPUT_WITH_BYTE_LENGTH = "outputWithByteLength";
private static final String START_OFFSET = "startOffset";
public static final String NUM_THREADS = "numThreads";
public static final String HELP_ME = "help";
static Option myHelpOption = new Option(HELP_ME, "print the help message");
static Option myLiveUpdateOption = new Option(LIVE_UPDATE,
"produce a live update on each hit");
@SuppressWarnings("static-access")
static Option myNumThreadsOption = OptionBuilder
.withArgName("num_threads")
.hasArg()
.withDescription(
"number of threads for scanning (specified in hex), 1 is the default")
.create(NUM_THREADS);
@SuppressWarnings("static-access")
static Option myMinStringLenOption = OptionBuilder
.withArgName("num_chars")
.hasArg()
.withDescription(
"number (in hex) of characters required for recognitions, default 4")
.create(MIN_STRING_LEN);
@SuppressWarnings("static-access")
static Option myMemDumpFileOption = OptionBuilder.withArgName("file")
.hasArg().withDescription("binary memory dump file")
.create(BINARY_FILE);
@SuppressWarnings("static-access")
static Option myOffsetOption = OptionBuilder
.withArgName("offset")
.hasArg()
.withDescription(
"start at given offset (specified in hex), 0 is Default")
.create(START_OFFSET);
@SuppressWarnings("static-access")
static Option myBasicOutput = OptionBuilder.withArgName("file")
.hasArg()
.withDescription("print output the format: filename: hex_offset data_string")
.create(BASIC_OUTPUT);
@SuppressWarnings("static-access")
static Option myOutputWithByteLengthOption = OptionBuilder.withArgName("file")
.hasArg()
.withDescription("print output the format: filename: hex_offset hex_strlen_in_bytes data_string")
.create(OUTPUT_WITH_BYTE_LENGTH);
public static Options myOptions = new Options()
.addOption(myNumThreadsOption)
.addOption(myOffsetOption).addOption(myMemDumpFileOption)
.addOption(myHelpOption).addOption(myLiveUpdateOption)
.addOption(myBasicOutput)
.addOption(myMinStringLenOption).addOption(myOutputWithByteLengthOption);
// Hash Table mapping hash values to key bytes
HashMap<String, HashMap<Long, StringInfo>> myStringInfoMap = new HashMap<String, HashMap<Long, StringInfo>>();
HashMap<String, ArrayList<StringInfo>> msToKeys = new HashMap<String, ArrayList<StringInfo>>();
HashMap<String, ArrayList<String>> keysToFileOffset = new HashMap<String, ArrayList<String>>();
Integer myNumThreads = 1;
Long myStartOffset;
private String myMemDump;
ExecutorService myExecutor = null;
HashMap<String, ArrayList<Future<?>>> myThreadFutures = new HashMap<String, ArrayList<Future<?>>>();
private boolean myLiveUpdate = false;
private int myNumExecutors;
private Long myMinStrLen;
Writer OutputFileWithLength = null;
Writer BasicOutputFile = null;
void closeDownWriters() {
if (OutputFileWithLength != null) {
try {
OutputFileWithLength.flush();
OutputFileWithLength.close();
} catch (Exception ex) {/*ignore*/}
}
if (BasicOutputFile != null) {
try {
BasicOutputFile.flush();
BasicOutputFile.close();
} catch (Exception ex) {/*ignore*/}
}
}
private void setOutputFileWithLength(File file) {
try {
OutputFileWithLength = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(file), "utf-8"));
//writer.write(greppableOutput);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
//try {writer.close();} catch (Exception ex) {/*ignore*/}
}
}
private void writeBasicOutput(String output) {
if (BasicOutputFile!=null) {
try {
BasicOutputFile.write(output);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private void writeBasicOutput(ArrayList<String> output) {
for (String o : output)
writeBasicOutput(o+"\n");
}
private void writeOutputWithLength(ArrayList<String> output) {
for (String o : output)
writeOutputWithLength(o+"\n");
}
private void writeOutputWithLength(String output) {
if (OutputFileWithLength!=null) {
try {
OutputFileWithLength.write(output);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private void setBasicOutputFile(File file) {
try {
BasicOutputFile = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(file), "utf-8"));
//writer.write(greppableOutput);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
//try {writer.close();} catch (Exception ex) {/*ignore*/}
}
}
public Ffastrings(String memory_dump_file, Long offset,
Integer numThreads, boolean liveUpdate, Long minStrLen) {
myNumExecutors = numThreads * (Utils.allStringTypes().size());
myMemDump = memory_dump_file;
myNumThreads = numThreads;
myStartOffset = offset;
myMinStrLen = minStrLen;
for (IStringInterpreter si : Utils.allStringTypes()){
si.setLiveUpdate(liveUpdate);
si.setMinLen(myMinStrLen);
}
myExecutor = Executors.newFixedThreadPool(myNumExecutors);
myTargetFiles = Utils.readDirectoryFilenames(myMemDump);
myLiveUpdate = liveUpdate;
for (File file : myTargetFiles)
myStringInfoMap.put(file.getAbsolutePath(),
new HashMap<Long, StringInfo>());
}
static void liveUpdate(String filename, long offset, String key) {
String offset_str = UnsignedLong.valueOf(offset).toString(16);
System.out
.println(String.format("%s %s %s", key, offset_str, filename));
}
void addStringInfo(String filename, Long offset, byte[] value,
IStringInterpreter stringMethods) {
long checkValue = offset + value.length;
synchronized (myStringInfoMap) {
HashMap<Long, StringInfo> si_hm = myStringInfoMap
.containsKey(filename) ? myStringInfoMap.get(filename)
: null;
if (si_hm == null) {
si_hm = new HashMap<Long, StringInfo>();
myStringInfoMap.put(filename, si_hm);
}
synchronized (si_hm) {
StringInfo sr;
try {
sr = new StringInfo(filename, offset, value, stringMethods);
si_hm.put(offset, sr);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
void performMergeOnFileKey (String filename_key) {
HashMap<Long, StringInfo> si_hm = myStringInfoMap.get(filename_key);
ArrayList<Long> locations = new ArrayList<Long>();
locations.addAll(si_hm.keySet());
Collections.sort(locations);
for (int i = 0; i < locations.size(); i++) {
Long offset = locations.get(i);
StringInfo si = si_hm.containsKey(offset) ? si_hm.get(offset)
: null;
if (si == null)
continue; // chances are it was removed and merged
StringInfo last_si = null, next_si = si_hm.get(offset + si.length());
while (si_hm.containsKey(offset + si.length()) && (last_si != next_si)) {
next_si = si_hm.get(offset + si.length());
if (si.getStringType() != next_si.getStringType())
break;
//System.out.println(String.format("%s @ %08x and %s @%08x overlap", si, si.getLocation(), next_si, next_si.getLocation()));
byte[] newValue = new byte[(int) si.length()
+ (int) next_si.length()];
System.arraycopy(si.getBytes(), 0, newValue, 0,
(int) si.length());
System.arraycopy(next_si.getBytes(), 0, newValue,
(int) si.length(), (int) next_si.length());
try {
si = new StringInfo(si.getFilename(), offset, newValue,
si.getStringType());
si_hm.put(offset, si);
si_hm.remove(next_si.getLocation());
} catch (Exception e) {
e.printStackTrace();
}
last_si = next_si;
}
}
}
void executeFileScans() {
System.out.println("Starting the binary string search");
for (File file : myTargetFiles) {
try {
performFileScan(file);
} catch (FileNotFoundException e) {
// this should not happen but if it does, oh well.
e.printStackTrace();
}
}
boolean exit = myThreadFutures.isEmpty();
while (!exit) {
Set<String> filename_keys = new HashSet<String>();
synchronized (myThreadFutures) {
for (String key : myThreadFutures.keySet())
filename_keys.add(key);
}
for (String filename_key : filename_keys) {
ArrayList<Future<?>> value = myThreadFutures.get(filename_key);
int idx = 0;
ArrayList<Future<?>> new_value = new ArrayList<Future<?>>();
for (Future<?> p : value) {
if (!p.isDone()) new_value.add(p);
}
if (new_value.size() == 0) {
synchronized (myThreadFutures) {
myThreadFutures.remove(filename_key);
// dump strings to file
// perform string merge
}
performMergeOnFileKey(filename_key);
performDumpOnFileKey(filename_key);
} else if (value.size() != new_value.size()){
synchronized (myThreadFutures) {
myThreadFutures.put(filename_key, new_value);
}
//System.out.println(String.format("Waiting on %d threads to complete for %s",
// new_value.size(), filename_key));
}
}
if (myThreadFutures.size() == 1) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// Dont know if i care about this
e.printStackTrace();
}
}
//System.out.println(String.format("Waiting on %d files to complete",
// myThreadFutures.size()));
exit = myThreadFutures.isEmpty();
}
myExecutor.shutdown();
while (!myExecutor.isTerminated()) {
}
closeDownWriters();
int totalHits = 0, uniqueKeys = 0;
HashSet<String> containedFiles = new HashSet<String>();
for (HashMap<Long, StringInfo> si_hm : myStringInfoMap.values()) {
for (StringInfo bsi : si_hm.values()) {
totalHits++;
uniqueKeys++;
//if (t > 0)
// uniqueKeys++;
//totalHits += bsi.numLocationsHits();
}
}
long totalFileHits = myStringInfoMap.size();
//System.out.println(String.format(
// "File contains %d hits in %d files and %d unique keys",
// totalHits, totalFileHits, uniqueKeys));
}
private void performDumpOnFileKey(String filename_key) {
ArrayList<String> output = getBasicOutput(filename_key);
writeBasicOutput(output);
output = getOutputWithLength(filename_key);
writeOutputWithLength(output);
}
public String getGreppableOutput() {
ArrayList<String> output = new ArrayList<String>();
for (HashMap<Long, StringInfo> si_hm : myStringInfoMap.values()) {
for (StringInfo bsi : si_hm.values()) {
String s = bsi.toGreppableString();
if (s.length() > 0)
output.add(s);
}
}
Collections.sort(output);
return StringUtils.join(output, "\n") + "\n";
}
public ArrayList<String> getBasicOutput() {
ArrayList<String> list = new ArrayList<String>();
for (String key : myStringInfoMap.keySet()) {
for (String r : getBasicOutput(key))
list.add(r);
}
return list;
}
public ArrayList<String> getBasicOutput(String key) {
HashMap<Long, StringInfo> si_hm = myStringInfoMap.get(key);
ArrayList<String> output = new ArrayList<String>();
for (StringInfo bsi : si_hm.values()) {
String s = bsi.toBasicOutput();
if (s.length() > 0)
output.add(s);
}
Collections.sort(output);
return output;
}
public ArrayList<String> getOutputWithLength() {
ArrayList<String> list = new ArrayList<String>();
for (String key : myStringInfoMap.keySet()) {
for (String i : getOutputWithLength(key)){
list.add(i);
}
}
return list;
}
public ArrayList<String> getOutputWithLength(String key) {
HashMap<Long, StringInfo> si_hm = myStringInfoMap.get(key);
ArrayList<String> output = new ArrayList<String>();
for (StringInfo bsi : si_hm.values()) {
String s = bsi.toOutputStringWithLength();
if (s.length() > 0)
output.add(s);
}
Collections.sort(output);
return output;
}
// public String getByCountsOutput() {
// ArrayList<String> output = new ArrayList<String>();
// for (HashMap<Long, StringInfo> si_hm : myStringInfoMap.values()) {
// for (StringInfo bsi : si_hm.values()) {
// int numHits = bsi.numLocationsHits();
// if (numHits == 0)
// continue;
// String s = String.format("%s %x", bsi.getHash(), numHits);
// if (s.length() > 0)
// output.add(s);
// return StringUtils.join(output, "\n") + "\n";
void performFileScan(File file) throws FileNotFoundException {
if (myStringInfoMap.isEmpty() || !file.exists() || !file.isFile()) {
// nothing to do there there are no patterns
// or this is not a valid file
return;
}
ArrayList<IStringInterpreter> stringTypes = Utils.allStringTypes();
long fileSize = file.length();
long chunkSz = fileSize / myNumThreads;
RandomAccessFile fhandle = new RandomAccessFile(file, "r");
String key = file.getAbsolutePath();
for (long offset = myStartOffset; offset < fileSize; offset += chunkSz) {
chunkSz = offset + chunkSz >= fileSize ? fileSize - offset : chunkSz;
byte[] res = null;
try {
fhandle.seek(offset);
res = new byte[(int) chunkSz];
long a_sz = fhandle.read(res);
if (a_sz != chunkSz) {
System.err.println(String.format(
"Warning: attempted to read %d bytes but got %d",
chunkSz, a_sz));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
break;
}
for (IStringInterpreter stype : stringTypes) {
Runnable cp = null;
cp = new ChunkProcessor(file, offset, res,
myStringInfoMap.get(file.getAbsolutePath()), stype,
myLiveUpdate);
Future<?> p = myExecutor.submit(cp);
if (!myThreadFutures.containsKey(key))
myThreadFutures.put(key, new ArrayList<Future<?>>());
ArrayList<Future<?>> value = myThreadFutures.get(key);
value.add(p);
}
}
}
public static Options getOptions() {
return myOptions;
}
public static void main(String[] args) throws FileNotFoundException {
Ffastrings fbs = null;
CommandLineParser parser = new DefaultParser();
CommandLine cli;
String binary_strings_file = null, memory_dump_file = null, num_scanning_threads = "1", offset_start = "0", min_str_len = "4";
boolean liveUpdate = false;
try {
cli = parser.parse(Ffastrings.getOptions(), args);
memory_dump_file = cli.hasOption(BINARY_FILE) ? cli
.getOptionValue(BINARY_FILE) : null;
if (cli.hasOption(NUM_THREADS))
num_scanning_threads = cli.getOptionValue(NUM_THREADS);
if (cli.hasOption(START_OFFSET))
offset_start = cli.getOptionValue(START_OFFSET);
if (cli.hasOption(MIN_STRING_LEN))
min_str_len = cli.getOptionValue(MIN_STRING_LEN);
if (cli.hasOption(LIVE_UPDATE))
liveUpdate = true;
} catch (ParseException e) {
e.printStackTrace();
return;
}
if (cli.hasOption(HELP_ME)) {
HelpFormatter hf = new HelpFormatter();
hf.printHelp("ffastrings", Ffastrings.getOptions());
return;
} else if (!cli.hasOption(BINARY_FILE)) {
System.err.println(String.format(
"ERROR: %s parameter is required to run jbgrep.",
BINARY_FILE));
return;
}
Integer numThreads = Utils.tryParseHexNumber(num_scanning_threads);
Long offset = Utils.tryParseHexLongNumber(offset_start);
Long minStrLen = Utils.tryParseHexLongNumber(min_str_len);
fbs = new Ffastrings(memory_dump_file, offset, numThreads,
liveUpdate, minStrLen);
if (fbs != null) {
if (cli.hasOption(BASIC_OUTPUT)) {
fbs.setBasicOutputFile(new File(cli.getOptionValue(BASIC_OUTPUT)));
}
if (cli.hasOption(OUTPUT_WITH_BYTE_LENGTH)) {
fbs.setOutputFileWithLength(new File(cli.getOptionValue(OUTPUT_WITH_BYTE_LENGTH)));
}
fbs.executeFileScans();
// if (cli.hasOption(KEY_COUNT_OUTPUT)) {
// File f = new File(cli.getOptionValue(KEY_COUNT_OUTPUT));
// Utils.writeOutputFile(f, fbs.getByCountsOutput());
}
}
}
|
package emufog.container;
import static emufog.util.StringUtils.nullOrEmpty;
/**
* Abstract object of a container image placeable in the graph.
* Container images can be specified with a memory and CPU limit.
*/
public abstract class ContainerType {
/* name of the container image */
public final String name;
/* version of the container image */
public final String version;
/* upper memory limit in Bytes for the container image */
public final int memoryLimit;
/* maximum share of the underlying CPUs */
public final float cpuShare;
ContainerType(String name, int memoryLimit, float cpuShare) throws IllegalArgumentException {
this(name, "latest", memoryLimit, cpuShare);
}
ContainerType(String name, String version, int memoryLimit, float cpuShare) throws IllegalArgumentException {
if (nullOrEmpty(name)) {
throw new IllegalArgumentException("The given container name is not set.");
}
if (nullOrEmpty(version)) {
throw new IllegalArgumentException("The given container version is not set.");
}
this.name = name;
this.version = version;
this.memoryLimit = memoryLimit;
this.cpuShare = cpuShare;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof ContainerType)) {
return false;
}
ContainerType other = (ContainerType) obj;
return name.equals(other.name) && version.equals(other.version) && memoryLimit == other.memoryLimit && cpuShare == other.cpuShare;
}
@Override
public String toString() {
return name + ':' + version;
}
}
|
package http.execution;
import lombok.NonNull;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import http.data.*;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.fluent.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
/**
* A daily consumer of data from an HTTP source.
*
* @author Jacob Rachiele
* Feb. 23, 2017
*/
public final class HttpDailyRunner implements HttpRunner<File> {
private static final Logger logger = LoggerFactory.getLogger(HttpDailyRunner.class);
private static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern("HH-mm-ss-SSS");
private static final DateTimeFormatter DAY_FORMATTER = DateTimeFormatter.ofPattern("YYYY-MM-dd");
private static final int OK = 200;
private static final int NOT_MODIFIED = 304;
private final String uri;
private final Map<String, String> requestProperties;
private final PathProperties pathProperties;
private boolean firstRun = true;
private String etag = "";
public HttpDailyRunner(String uri, Map<String, String> requestProperties, PathProperties pathProperties) {
this.uri = uri;
this.requestProperties = new HashMap<>(requestProperties);
this.pathProperties = pathProperties;
}
@Override
public Request createRequest() {
return Request.Get(uri);
}
@Override
public int getStatusCode(@NonNull HttpResponse response) {
return response.getStatusLine().getStatusCode();
}
@Override
public Response getResponse(@NonNull Request request) {
for (String s : requestProperties.keySet()) {
request.addHeader(s, requestProperties.get(s));
}
request.addHeader("If-None-Match", this.etag);
try {
return request.execute();
} catch (IOException e) {
logger.error("Error executing the request.", e);
throw new RuntimeException(e);
}
}
@Override
public Destination<File> createDestination() {
String time = LocalTime.now().format(TIME_FORMATTER);
String day = LocalDate.now().format(DAY_FORMATTER);
String dirName = pathProperties.getDirectory() + "/" + day;
String prefix = pathProperties.getPrefix();
String suffix = pathProperties.getSuffix();
return new FileDestination(dirName, prefix, time, suffix);
}
@Override
public void write(@NonNull HttpResponse response, @NonNull Destination<File> destination) {
if (firstRun) {
throw new IllegalStateException("Cannot write to file on the first run.");
}
File file = destination.get();
HttpEntity entity;
try (BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(file))){
entity = response.getEntity();
entity.writeTo(outputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
private String getETag(@NonNull HttpResponse response) {
Header header = response.getFirstHeader("ETag");
if (header == null) {
return "";
}
return header.getValue();
}
@Override
public void run() {
final Request request;
if (firstRun) {
request = createRequest();
firstRun = false;
} else {
request = createRequest();
}
Response response = getResponse(request);
HttpResponse httpResponse;
try {
httpResponse = response.returnResponse();
} catch (IOException e) {
logger.error("Error retrieving http response.", e);
throw new RuntimeException(e);
}
int statusCode = getStatusCode(httpResponse);
this.etag = getETag(httpResponse);
if (statusCode == OK) {
Destination<File> destination = createDestination();
write(httpResponse, destination);
} else if (statusCode != NOT_MODIFIED) {
throw new RuntimeException("Unexpected status code " + statusCode +
". Should be equivalent to OK (200) or NOT_MODIFIED (304).");
}
}
}
|
package i5.las2peer.p2p;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Serializable;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.UnknownHostException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Collection;
import java.util.Hashtable;
import java.util.List;
import java.util.Properties;
import java.util.Vector;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import i5.las2peer.api.StorageCollisionHandler;
import i5.las2peer.api.StorageEnvelopeHandler;
import i5.las2peer.api.StorageExceptionHandler;
import i5.las2peer.api.StorageStoreResultHandler;
import i5.las2peer.api.exceptions.ArtifactNotFoundException;
import i5.las2peer.api.exceptions.StorageException;
import i5.las2peer.classLoaders.L2pClassManager;
import i5.las2peer.classLoaders.libraries.SharedStorageRepository;
import i5.las2peer.communication.Message;
import i5.las2peer.communication.MessageException;
import i5.las2peer.logging.L2pLogger;
import i5.las2peer.logging.NodeObserver.Event;
import i5.las2peer.p2p.pastry.MessageEnvelope;
import i5.las2peer.p2p.pastry.NodeApplication;
import i5.las2peer.persistency.Envelope;
import i5.las2peer.persistency.MalformedXMLException;
import i5.las2peer.persistency.SharedStorage;
import i5.las2peer.persistency.SharedStorage.STORAGE_MODE;
import i5.las2peer.security.Agent;
import i5.las2peer.security.AgentContext;
import i5.las2peer.security.AgentException;
import i5.las2peer.security.L2pSecurityException;
import i5.las2peer.security.MessageReceiver;
import i5.las2peer.security.UserAgent;
import i5.las2peer.tools.CryptoException;
import i5.las2peer.tools.SerializationException;
import rice.environment.Environment;
import rice.p2p.commonapi.NodeHandle;
import rice.pastry.NodeIdFactory;
import rice.pastry.PastryNode;
import rice.pastry.socket.internet.InternetPastryNodeFactory;
import rice.pastry.standard.RandomNodeIdFactory;
public class PastryNodeImpl extends Node {
private static final L2pLogger logger = L2pLogger.getInstance(PastryNodeImpl.class);
private static final int AGENT_GET_TIMEOUT = 10000;
private static final int AGENT_STORE_TIMEOUT = 10000;
private static final int ARTIFACT_GET_TIMEOUT = 10000;
private static final int ARTIFACT_STORE_TIMEOUT = 10000;
private InetAddress pastryBindAddress = null; // null = detect Internet address
public static final int STANDARD_PORT = 9901;
private int pastryPort = STANDARD_PORT;
public static final String STANDARD_BOOTSTRAP = "localhost:9900,localhost:9999";
private String bootStrap = STANDARD_BOOTSTRAP;
private ExecutorService threadpool; // gather all threads in node object to minimize idle threads
private Environment pastryEnvironment;
private PastryNode pastryNode;
private NodeApplication application;
private SharedStorage pastStorage;
private STORAGE_MODE mode = STORAGE_MODE.FILESYSTEM;
private String storageDir; // null = default choosen by SharedStorage
private Long nodeIdSeed;
/**
* This is the regular constructor used by the {@link i5.las2peer.tools.L2pNodeLauncher}. Its parameters can be set
* to start a new network or join an existing Pastry ring.
*
* @param classLoader A class loader that is used by the node.
* @param useMonitoringObserver If true, the node sends monitoring information to the monitoring service.
* @param port A port number the PastryNode should listen to for network communication.
* @param bootstrap A bootstrap address that should be used, like hostname:port or <code>null</code> to start a new
* network.
* @param storageMode A storage mode to be used by this node, see
* {@link i5.las2peer.persistency.SharedStorage.STORAGE_MODE}.
* @param nodeIdSeed A node id (random) seed to enforce a specific node id. If <code>null</code>, the node id will
* be random.
*/
public PastryNodeImpl(L2pClassManager classLoader, boolean useMonitoringObserver, int port, String bootstrap,
STORAGE_MODE storageMode, Long nodeIdSeed) {
super(classLoader, true, useMonitoringObserver);
pastryPort = port;
this.bootStrap = bootstrap;
this.mode = storageMode;
this.storageDir = null; // null = SharedStorage chooses directory
this.nodeIdSeed = nodeIdSeed;
this.setStatus(NodeStatus.CONFIGURED);
}
/**
* This constructor is mainly used by the {@link i5.las2peer.testing.TestSuite} and sets all parameters for
* debugging and testing operation mode.
*
* @param bootstrap A bootstrap address that should be used, like hostname:port or <code>null</code> to start a new
* network.
* @param storageMode A storage mode to be used by this node, see
* {@link i5.las2peer.persistency.SharedStorage.STORAGE_MODE}.
* @param storageDir A directory to persist data to. Only considered in persistent storage mode, but overwrites
* {@link SharedStorage} configurations.
* @param nodeIdSeed A node id (random) seed to enforce a specific node id. If <code>null</code>, the node id will
* be random.
*/
public PastryNodeImpl(String bootstrap, STORAGE_MODE storageMode, String storageDir, Long nodeIdSeed) {
this(null, null, bootstrap, storageMode, storageDir, nodeIdSeed);
}
public PastryNodeImpl(L2pClassManager classManager, Integer port, String bootstrap, STORAGE_MODE storageMode,
String storageDir, Long nodeIdSeed) {
super(classManager, true, false);
pastryBindAddress = InetAddress.getLoopbackAddress();
if (port == null) {
// use system defined port
try {
ServerSocket tmpSocket = new ServerSocket(0);
tmpSocket.close();
pastryPort = tmpSocket.getLocalPort();
} catch (IOException e) {
throw new RuntimeException(e);
}
} else {
pastryPort = port;
}
this.bootStrap = bootstrap;
this.mode = storageMode;
this.storageDir = storageDir;
this.nodeIdSeed = nodeIdSeed;
this.setStatus(NodeStatus.CONFIGURED);
}
/**
* access to the underlying pastry node
*
* @return the pastry node representing this las2peer node
*/
public PastryNode getPastryNode() {
return pastryNode;
}
/**
* generate a collection of InetSocketAddresses from the given bootstrap string
*
* @return collection of InetSocketAddresses from the given bootstrap string
*/
private Collection<InetSocketAddress> getBootstrapAddresses() {
Vector<InetSocketAddress> result = new Vector<>();
if (bootStrap == null || bootStrap.isEmpty()) {
return result;
}
String[] addresses = bootStrap.split(",");
for (String address : addresses) {
String[] hostAndPort = address.split(":");
int port = STANDARD_PORT;
if (hostAndPort.length == 2) {
port = Integer.parseInt(hostAndPort[1]);
}
try {
result.add(new InetSocketAddress(InetAddress.getByName(hostAndPort[0]), port));
} catch (UnknownHostException e) {
// TODO this should be handled earlier
if (address.equals("-")) {
System.out.println("Starting new network..");
} else {
System.err.println("Cannot resolve address for: " + address + "\n Starting new network..");
}
}
}
return result;
}
/**
* Setup all pastry applications to run on this node.
*
* This will be
* <ul>
* <li>the application for message passing {@link NodeApplication}</li>
* <li>a Past DHT storage from Freepastry</li>
* </ul>
*
* For the past DHT either a memory mode or a disk persistence mode are selected based on {@link STORAGE_MODE}
*
* @throws StorageException
*/
private void setupPastryApplications() throws StorageException {
threadpool = Executors.newCachedThreadPool();
application = new NodeApplication(this);
pastStorage = new SharedStorage(pastryNode, mode, threadpool, storageDir);
// add past storage as network repository
getBaseClassLoader().addRepository(new SharedStorageRepository(this));
}
/**
* start this node
*/
@Override
protected void launchSub() throws NodeException {
try {
setStatus(NodeStatus.STARTING);
setupPastryEnvironment();
NodeIdFactory nidFactory = null;
if (nodeIdSeed == null) {
nidFactory = new RandomNodeIdFactory(pastryEnvironment);
} else {
nidFactory = new NodeIdFactory() {
@Override
public rice.pastry.Id generateNodeId() {
// same method as in rice.pastry.standard.RandomNodeIdFactory but except using nodeIdSeed
byte raw[] = new byte[8];
long tmp = ++nodeIdSeed;
for (int i = 0; i < 8; i++) {
raw[i] = (byte) (tmp & 0xff);
tmp >>= 8;
}
MessageDigest md = null;
try {
md = MessageDigest.getInstance("SHA");
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("No SHA support!", e);
}
md.update(raw);
byte[] digest = md.digest();
rice.pastry.Id nodeId = rice.pastry.Id.build(digest);
return nodeId;
}
};
}
InternetPastryNodeFactory factory = new InternetPastryNodeFactory(nidFactory, pastryBindAddress, pastryPort,
pastryEnvironment, null, null, null);
pastryNode = factory.newNode();
setupPastryApplications();
pastryNode.boot(getBootstrapAddresses());
synchronized (pastryNode) {
while (!pastryNode.isReady() && !pastryNode.joinFailed()) {
// delay so we don't busy-wait
pastryNode.wait(500);
// abort if can't join
if (pastryNode.joinFailed()) {
throw new NodeException(
"Could not join the FreePastry ring. Reason:" + pastryNode.joinFailedReason());
}
}
}
setStatus(NodeStatus.RUNNING);
registerShutdownMethod();
} catch (IOException e) {
throw new NodeException("IOException while joining pastry ring", e);
} catch (StorageException e) {
throw new NodeException("Shared storage exception while joining pastry ring", e);
} catch (InterruptedException e) {
throw new NodeException("Interrupted while joining pastry ring!", e);
} catch (IllegalStateException e) {
throw new NodeException("Unable to open Netwock socket - is the port already in use?", e);
}
}
/**
* setup pastry environment settings
*/
private void setupPastryEnvironment() {
pastryEnvironment = new Environment();
String[] configFiles = new String[] { "etc/pastry.properties", "config/pastry.properties",
"properties/pastry.properties" };
String found = null;
for (String filename : configFiles) {
try {
if (new File(filename).exists()) {
found = filename;
break;
}
} catch (Exception e) {
logger.log(Level.FINER, "Exception while checking for config file '" + filename + "'", e);
}
}
Hashtable<String, String> properties = new Hashtable<>();
if (found != null) {
System.out.println("Using pastry property file " + found);
try {
Properties props = new Properties();
props.load(new FileInputStream(found));
for (Object propname : props.keySet()) {
properties.put((String) propname, (String) props.get(propname));
}
} catch (FileNotFoundException e) {
System.err.println("Unable to open property file " + found);
} catch (IOException e) {
System.err.println("Error opening property file " + found + ": " + e.getMessage());
}
} else {
logger.fine("No pastry property file found - using default values");
}
if (!properties.containsKey("nat_search_policy")) {
properties.put("nat_search_policy", "never");
}
if (!properties.containsKey("firewall_test_policy")) {
properties.put("firewall_test_policy", "never");
}
if (!properties.containsKey("nat_network_prefixes")) {
properties.put("nat_network_prefixes", "127.0.0.1;10.;192.168.;");
}
if (pastryBindAddress != null && pastryBindAddress.isLoopbackAddress()) {
properties.put("allow_loopback_address", "1");
}
if (!properties.containsKey("p2p_past_messageTimeout")) {
properties.put("p2p_past_messageTimeout", "120000");
}
if (!properties.containsKey("pastry_socket_known_network_address")) {
if (!properties.containsKey("pastry_socket_known_network_address_port")) {
properties.put("pastry_socket_known_network_address_port", "80");
}
}
if (!properties.containsKey("nat_search_policy")) {
properties.put("nat_search_policy", "never");
}
for (String prop : properties.keySet()) {
pastryEnvironment.getParameters().setString(prop, properties.get(prop));
logger.fine("setting: " + prop + ": '" + properties.get(prop) + "'");
}
}
/**
* register node shutdown as JVM shutdown method
*/
private void registerShutdownMethod() {
final PastryNodeImpl self = this;
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
self.shutDown();
}
});
}
@Override
public synchronized void shutDown() {
this.setStatus(NodeStatus.CLOSING);
super.shutDown();
if (threadpool != null) {
// destroy pending jobs first, because they miss the node the most
threadpool.shutdownNow();
}
if (pastryNode != null) {
pastryNode.destroy();
pastryNode = null;
}
if (pastryEnvironment != null) {
pastryEnvironment.destroy();
pastryEnvironment = null;
}
this.setStatus(NodeStatus.CLOSED);
}
@Override
public void registerReceiver(MessageReceiver receiver)
throws AgentAlreadyRegisteredException, L2pSecurityException, AgentException {
synchronized (this) {
super.registerReceiver(receiver);
application.registerAgentTopic(receiver);
// Observer is called in superclass!
}
}
@Override
public void unregisterReceiver(MessageReceiver receiver) throws AgentNotKnownException, NodeException {
synchronized (this) {
application.unregisterAgentTopic(receiver.getResponsibleForAgentId());
super.unregisterReceiver(receiver);
}
}
@Override
public void registerReceiverToTopic(MessageReceiver receiver, long topic) throws AgentNotKnownException {
synchronized (this) {
super.registerReceiverToTopic(receiver, topic);
application.registerTopic(topic);
}
}
@Override
public void unregisterReceiverFromTopic(MessageReceiver receiver, long topic) throws NodeException {
synchronized (this) {
super.unregisterReceiverFromTopic(receiver, topic);
if (!super.hasTopic(topic)) {
application.unregisterTopic(topic);
}
}
}
/**
* @deprecated Use {@link PastryNodeImpl#unregisterReceiver(MessageReceiver)} instead!
*/
@Deprecated
@Override
public void unregisterAgent(long id) throws AgentNotKnownException {
synchronized (this) {
application.unregisterAgentTopic(id);
super.unregisterAgent(id);
}
}
@Override
public void sendMessage(Message message, MessageResultListener listener, SendMode mode) {
// TODO: use mode?!?!
observerNotice(Event.MESSAGE_SENDING, pastryNode, message.getSenderId(), null, message.getRecipientId(),
"broadcasting");
registerAnswerListener(message.getId(), listener);
application.sendMessage(message);
}
@Override
public void sendMessage(Message message, Object atNodeId, MessageResultListener listener)
throws AgentNotKnownException, NodeNotFoundException, L2pSecurityException {
if (!(atNodeId instanceof NodeHandle)) {
String addition = "(null)";
if (atNodeId != null) {
addition = atNodeId.getClass().toString();
}
IllegalArgumentException e = new IllegalArgumentException(
"node id in pastry nets has to be a NodeHandle instance but is " + addition);
e.printStackTrace();
throw e;
}
observerNotice(Event.MESSAGE_SENDING, pastryNode, message.getSenderId(), atNodeId, message.getRecipientId(),
"");
registerAnswerListener(message.getId(), listener);
try {
application.sendMessage(new MessageEnvelope(pastryNode.getLocalHandle(), message), (NodeHandle) atNodeId);
} catch (MalformedXMLException e) {
logger.log(Level.SEVERE, "Can't read message XML", e);
observerNotice(Event.MESSAGE_FAILED, pastryNode, message.getSenderId(), atNodeId, message.getRecipientId(),
"XML exception!");
} catch (MessageException e) {
logger.log(Level.SEVERE, "Could not send message", e);
observerNotice(Event.MESSAGE_FAILED, pastryNode, message.getSenderId(), atNodeId, message.getRecipientId(),
"Message exception!");
}
}
/**
* @deprecated Use {@link #fetchEnvelope(String)} instead
*/
@Deprecated
@Override
public Envelope fetchArtifact(long id) throws ArtifactNotFoundException, StorageException {
return fetchEnvelope(Long.toString(id));
}
/**
* @deprecated Use {@link #fetchEnvelope(String)} instead
*/
@Deprecated
@Override
public Envelope fetchArtifact(String identifier) throws ArtifactNotFoundException, StorageException {
return fetchEnvelope(identifier);
}
/**
* @deprecated Use {@link #storeEnvelope(Envelope, Agent)} instead
*/
@Deprecated
@Override
public void storeArtifact(Envelope envelope) throws StorageException {
storeEnvelope(envelope, AgentContext.getCurrent().getMainAgent());
}
/**
* @deprecated Use {@link #removeEnvelope(String)} instead
*/
@Deprecated
@Override
public void removeArtifact(long id, byte[] signature) throws ArtifactNotFoundException, StorageException {
removeEnvelope(Long.toString(id));
}
@Override
public Object[] findRegisteredAgent(long agentId, int hintOfExpectedCount) throws AgentNotKnownException {
observerNotice(Event.AGENT_SEARCH_STARTED, pastryNode, agentId, null, (Long) null, "");
return application.searchAgent(agentId, hintOfExpectedCount).toArray();
}
/**
* provides access to the underlying pastry application mostly for testing purposes
*
* @return the pastry node application of this pastry node
*/
public NodeApplication getApplication() {
return application;
}
@Override
public Agent getAgent(long id) throws AgentNotKnownException {
// no caching here, because agents may have changed in the network
observerNotice(Event.AGENT_GET_STARTED, pastryNode, id, null, (Long) null, "");
try {
Agent agentFromNet = null;
Agent anonymous = getAnonymous();
if (id == anonymous.getId()) { // TODO use isAnonymous, special ID or Classing for identification
agentFromNet = anonymous;
} else {
Envelope agentEnvelope = pastStorage.fetchEnvelope(Envelope.getAgentIdentifier(id), AGENT_GET_TIMEOUT);
agentFromNet = Agent.createFromXml((String) agentEnvelope.getContent());
}
observerNotice(Event.AGENT_GET_SUCCESS, pastryNode, id, null, (Long) null, "");
return agentFromNet;
} catch (Exception e) {
observerNotice(Event.AGENT_GET_FAILED, pastryNode, id, null, (Long) null, "");
throw new AgentNotKnownException("Unable to retrieve Agent " + id + " from past storage", e);
}
}
@Override
public void storeAgent(Agent agent) throws L2pSecurityException, AgentException {
if (agent.isLocked()) {
throw new L2pSecurityException("You have to unlock the agent before storage!");
// because the agent has to sign itself
}
// TODO check if anonymous should be stored and deny
observerNotice(Event.AGENT_UPLOAD_STARTED, pastryNode, agent, "");
try {
Envelope agentEnvelope = null;
try {
agentEnvelope = pastStorage.fetchEnvelope(Envelope.getAgentIdentifier(agent.getId()),
AGENT_GET_TIMEOUT);
agentEnvelope = pastStorage.createUnencryptedEnvelope(agentEnvelope, agent.toXmlString());
} catch (ArtifactNotFoundException e) {
agentEnvelope = pastStorage.createUnencryptedEnvelope(Envelope.getAgentIdentifier(agent.getId()),
agent.toXmlString());
}
pastStorage.storeEnvelope(agentEnvelope, agent, AGENT_STORE_TIMEOUT);
if (agent instanceof UserAgent) {
getUserManager().registerUserAgent((UserAgent) agent);
}
observerNotice(Event.AGENT_UPLOAD_SUCCESS, pastryNode, agent, "");
} catch (CryptoException | SerializationException | StorageException e) {
observerNotice(Event.AGENT_UPLOAD_FAILED, pastryNode, agent, "Got interrupted!");
throw new AgentException("Storage has been interrupted", e);
}
}
/**
* @deprecated Use {@link #storeAgent(Agent)} instead
*/
@Deprecated
@Override
public void updateAgent(Agent agent) throws AgentException, L2pSecurityException, StorageException {
storeAgent(agent);
}
/**
* get the identifier of this node (string representation of the pastry node)
*
* @return complete identifier of this pastry node as String
*/
@Override
public Serializable getNodeId() {
if (pastryNode == null) {
return null;
} else {
return pastryNode.getLocalNodeHandle();
}
}
public int getPort() {
return pastryPort;
}
@Override
public Object[] getOtherKnownNodes() {
return pastryNode.getLeafSet().getUniqueSet().toArray();
}
@Override
public NodeInformation getNodeInformation(Object nodeId) throws NodeNotFoundException {
if (!(nodeId instanceof NodeHandle)) {
throw new NodeNotFoundException("Given node id is not a pastry Node Handle!");
}
return application.getNodeInformation((NodeHandle) nodeId);
}
@Override
public void storeEnvelope(Envelope envelope, Agent author) throws StorageException {
storeEnvelope(envelope, author, ARTIFACT_STORE_TIMEOUT);
}
@Override
public Envelope fetchEnvelope(String identifier) throws ArtifactNotFoundException, StorageException {
return fetchEnvelope(identifier, ARTIFACT_GET_TIMEOUT);
}
@Override
public Envelope createEnvelope(String identifier, Serializable content, Agent... reader)
throws IllegalArgumentException, SerializationException, CryptoException {
return pastStorage.createEnvelope(identifier, content, reader);
}
@Override
public Envelope createEnvelope(String identifier, Serializable content, List<Agent> readers)
throws IllegalArgumentException, SerializationException, CryptoException {
return pastStorage.createEnvelope(identifier, content, readers);
}
@Override
public Envelope createEnvelope(Envelope previousVersion, Serializable content)
throws IllegalArgumentException, SerializationException, CryptoException {
return pastStorage.createEnvelope(previousVersion, content);
}
@Override
public Envelope createEnvelope(Envelope previousVersion, Serializable content, Agent... reader)
throws IllegalArgumentException, SerializationException, CryptoException {
return pastStorage.createEnvelope(previousVersion, content, reader);
}
@Override
public Envelope createEnvelope(Envelope previousVersion, Serializable content, List<Agent> readers)
throws IllegalArgumentException, SerializationException, CryptoException {
return pastStorage.createEnvelope(previousVersion, content, readers);
}
@Override
public Envelope createUnencryptedEnvelope(String identifier, Serializable content)
throws IllegalArgumentException, SerializationException, CryptoException {
return pastStorage.createUnencryptedEnvelope(identifier, content);
}
@Override
public Envelope createUnencryptedEnvelope(Envelope previousVersion, Serializable content)
throws IllegalArgumentException, SerializationException, CryptoException {
return pastStorage.createUnencryptedEnvelope(previousVersion, content);
}
@Override
public void storeEnvelope(Envelope envelope, Agent author, long timeoutMs) throws StorageException {
try {
pastStorage.storeEnvelope(envelope, author, timeoutMs);
} catch (StorageException e) {
observerNotice(Event.ARTIFACT_UPLOAD_FAILED, pastryNode,
"Storage error for Artifact " + envelope.getIdentifier());
throw e; // transparent exception forwarding
}
observerNotice(Event.ARTIFACT_ADDED, pastryNode, envelope.getIdentifier());
}
@Override
public void storeEnvelopeAsync(Envelope envelope, Agent author, StorageStoreResultHandler resultHandler,
StorageCollisionHandler collisionHandler, StorageExceptionHandler exceptionHandler) {
pastStorage.storeEnvelopeAsync(envelope, author, new StorageStoreResultHandler() {
@Override
public void onResult(Serializable serializable, int successfulOperations) {
observerNotice(Event.ARTIFACT_ADDED, pastryNode, envelope.getIdentifier());
if (resultHandler != null) {
resultHandler.onResult(serializable, successfulOperations);
}
}
}, collisionHandler, new StorageExceptionHandler() {
@Override
public void onException(Exception e) {
observerNotice(Event.ARTIFACT_UPLOAD_FAILED, pastryNode,
"Storage error for Artifact " + envelope.getIdentifier());
if (exceptionHandler != null) {
exceptionHandler.onException(e);
}
}
});
}
@Override
public Envelope fetchEnvelope(String identifier, long timeoutMs)
throws ArtifactNotFoundException, StorageException {
if (pastStorage == null) {
throw new IllegalStateException(
"Past storage not initialized! You can fetch artifacts only from running nodes!");
}
observerNotice(Event.ARTIFACT_FETCH_STARTED, pastryNode, identifier);
try {
Envelope contentFromNet = pastStorage.fetchEnvelope(identifier, timeoutMs);
observerNotice(Event.ARTIFACT_RECEIVED, pastryNode, identifier);
return contentFromNet;
} catch (ArtifactNotFoundException e) {
observerNotice(Event.ARTIFACT_FETCH_FAILED, pastryNode, identifier);
throw e; // transparent exception forwarding
} catch (Exception e) {
observerNotice(Event.ARTIFACT_FETCH_FAILED, pastryNode, identifier);
throw new StorageException("Unable to retrieve Artifact from past storage", e);
}
}
@Override
public void fetchEnvelopeAsync(String identifier, StorageEnvelopeHandler envelopeHandler,
StorageExceptionHandler exceptionHandler) {
if (getStatus() != NodeStatus.RUNNING) {
throw new IllegalStateException("You can fetch artifacts only from running nodes!");
}
observerNotice(Event.ARTIFACT_FETCH_STARTED, pastryNode, identifier);
pastStorage.fetchEnvelopeAsync(identifier, new StorageEnvelopeHandler() {
@Override
public void onEnvelopeReceived(Envelope result) {
observerNotice(Event.ARTIFACT_RECEIVED, pastryNode, identifier);
if (envelopeHandler != null) {
envelopeHandler.onEnvelopeReceived(result);
}
}
}, new StorageExceptionHandler() {
@Override
public void onException(Exception e) {
observerNotice(Event.ARTIFACT_FETCH_FAILED, pastryNode, identifier);
if (exceptionHandler != null) {
exceptionHandler.onException(e);
}
}
});
}
@Override
public void removeEnvelope(String identifier) throws ArtifactNotFoundException, StorageException {
pastStorage.removeEnvelope(identifier);
}
}
|
// -*- mode:java; encoding:utf-8 -*-
// vim:set fileencoding=utf-8:
// @homepage@
package example;
import java.awt.*;
import java.awt.event.InputEvent;
import java.beans.PropertyChangeEvent;
import javax.swing.*;
import javax.swing.plaf.LayerUI;
public final class MainPanel extends JPanel {
private final JTextArea logger = new JTextArea();
private final JButton cancel = new JButton("cancel");
private final DisableInputLayerUI<JComponent> layerUI = new DisableInputLayerUI<>();
private transient Thread worker;
private MainPanel() {
super(new BorderLayout());
cancel.setEnabled(false);
cancel.addActionListener(e -> {
if (worker != null) {
worker.interrupt();
}
});
JButton button = new JButton("Stop 5sec");
button.addActionListener(e -> {
setInputBlock(true);
SecondaryLoop loop = Toolkit.getDefaultToolkit().getSystemEventQueue().createSecondaryLoop();
worker = new Thread(() -> {
String msg = "Done";
try {
Thread.sleep(5000);
} catch (InterruptedException ex) {
msg = "Interrupted";
Thread.currentThread().interrupt();
}
append(msg);
setInputBlock(false);
loop.exit();
});
worker.start();
if (!loop.enter()) {
append("Error");
}
});
JPanel p = new JPanel();
p.add(new JCheckBox());
p.add(new JTextField(10));
p.add(button);
add(new JLayer<>(p, layerUI), BorderLayout.NORTH);
add(new JScrollPane(logger));
add(cancel, BorderLayout.SOUTH);
setPreferredSize(new Dimension(320, 240));
}
public void setInputBlock(boolean flg) {
layerUI.setInputBlock(flg);
cancel.setEnabled(flg);
}
public void append(String str) {
logger.append(str + "\n");
}
public static void main(String[] args) {
EventQueue.invokeLater(MainPanel::createAndShowGui);
}
private static void createAndShowGui() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
Toolkit.getDefaultToolkit().beep();
}
JFrame frame = new JFrame("@title@");
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
// frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new MainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class DisableInputLayerUI<V extends JComponent> extends LayerUI<V> {
private static final String CMD_REPAINT = "repaint";
private boolean running;
public void setInputBlock(boolean block) {
firePropertyChange(CMD_REPAINT, running, block);
running = block;
}
@Override public void paint(Graphics g, JComponent c) {
super.paint(g, c);
if (!running) {
return;
}
Graphics2D g2 = (Graphics2D) g.create();
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, .5f));
g2.setPaint(Color.GRAY.brighter());
g2.fillRect(0, 0, c.getWidth(), c.getHeight());
g2.dispose();
}
@Override public void installUI(JComponent c) {
super.installUI(c);
if (c instanceof JLayer) {
JLayer<?> jlayer = (JLayer<?>) c;
jlayer.getGlassPane().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
jlayer.setLayerEventMask(
AWTEvent.MOUSE_EVENT_MASK | AWTEvent.MOUSE_MOTION_EVENT_MASK
| AWTEvent.MOUSE_WHEEL_EVENT_MASK | AWTEvent.KEY_EVENT_MASK
| AWTEvent.FOCUS_EVENT_MASK | AWTEvent.COMPONENT_EVENT_MASK);
}
}
@Override public void uninstallUI(JComponent c) {
if (c instanceof JLayer) {
((JLayer<?>) c).setLayerEventMask(0);
}
super.uninstallUI(c);
}
@Override public void eventDispatched(AWTEvent e, JLayer<? extends V> l) {
if (running && e instanceof InputEvent) {
((InputEvent) e).consume();
}
}
@Override public void applyPropertyChange(PropertyChangeEvent e, JLayer<? extends V> l) {
if (CMD_REPAINT.equals(e.getPropertyName())) {
l.getGlassPane().setVisible((Boolean) e.getNewValue());
l.repaint();
}
}
}
|
package me.exz.wailanbt.util;
import net.minecraft.nbt.NBTBase;
import net.minecraft.nbt.NBTTagCompound;
import org.apache.commons.lang3.StringUtils;
public class NBTHelper {
public static String NBTTypeToString(NBTTagCompound n, String id) {
if (n.hasKey(id)) {
NBTBase tag = n.getTag(id);
switch (tag.getId()) {
case 0:
case 3:
case 7:
case 9:
case 10:
case 11:
return tag.toString();
case 1:
case 2:
case 4:
case 5:
case 6:
return StringUtils.substring(tag.toString(), 0, -1);
case 8:
return StringUtils.substring(tag.toString(), 1, -1);
default:
return "__ERROR__";
}
} else {
return "__ERROR__";
}
}
@SuppressWarnings({"UnusedDeclaration", "deprecation"})
@Deprecated
public static String NBTTypeToString_old(NBTTagCompound n, String id, String type) {
try {
switch (NBTTypeName.TypeNameToID("TAG_" + type)) {
case TAG_End:
return "TAG_End";
case TAG_Byte:
return String.valueOf(n.getByte(id));
case TAG_Short:
return String.valueOf(n.getShort(id));
case TAG_Integer:
return String.valueOf(n.getInteger(id));
case TAG_Long:
return String.valueOf(n.getLong(id));
case TAG_Float:
return String.valueOf(n.getFloat(id));
case TAG_Double:
return String.valueOf(n.getDouble(id));
case TAG_ByteArray:
return "TAG_ByteArray";
case TAG_String:
return n.getString(id);
case TAG_List:
return "TAG_List";
case TAG_Compound:
return "TAG_Compound";
case TAG_IntArray:
return "TAG_IntArray";
default:
return "Bad Type";
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
@Deprecated
public static enum NBTTypeName {
TAG_End, TAG_Byte, TAG_Short, TAG_Integer, TAG_Long, TAG_Float, TAG_Double, TAG_ByteArray, TAG_String, TAG_List, TAG_Compound, TAG_IntArray, ERROR_VALUE;
@SuppressWarnings("deprecation")
public static NBTTypeName TypeNameToID(String name) {
try {
return valueOf(name);
} catch (Exception e) {
e.printStackTrace();
return ERROR_VALUE;
}
}
}
}
|
package mytown.handlers;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.TickEvent;
import cpw.mods.fml.relauncher.Side;
import mytown.MyTown;
import myessentials.utils.WorldUtils;
import mytown.api.container.TownBlocksContainer;
import mytown.entities.Plot;
import mytown.entities.TownBlock;
import net.minecraft.block.Block;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.init.Blocks;
import net.minecraft.network.play.server.S23PacketBlockChange;
import net.minecraft.server.MinecraftServer;
import org.apache.commons.lang3.exception.ExceptionUtils;
import java.util.*;
public class VisualsHandler {
public static final VisualsHandler instance = new VisualsHandler();
private final List<VisualObject> markedBlocks = new ArrayList<VisualObject>();
@SubscribeEvent
public void tick(TickEvent.ServerTickEvent ev) {
if (ev.side != Side.SERVER || ev.phase != TickEvent.Phase.START)
return;
if (!markedBlocks.isEmpty()) {
for(Iterator<VisualObject> visualObjectIterator = markedBlocks.iterator(); visualObjectIterator.hasNext(); ) {
VisualObject visualObject = visualObjectIterator.next();
for (Iterator<BlockCoords> blockCoordsIterator = visualObject.blockCoords.iterator(); blockCoordsIterator.hasNext(); ) {
BlockCoords coord = blockCoordsIterator.next();
if (!coord.packetSent) {
S23PacketBlockChange packet = new S23PacketBlockChange(coord.x, coord.y, coord.z, MinecraftServer.getServer().worldServerForDimension(coord.dim));
packet.field_148883_d = coord.block;
visualObject.player.playerNetServerHandler.sendPacket(packet);
coord.packetSent = true;
}
if (coord.deleted) {
S23PacketBlockChange packet = new S23PacketBlockChange(coord.x, coord.y, coord.z, MinecraftServer.getServer().worldServerForDimension(coord.dim));
packet.field_148883_d = MinecraftServer.getServer().worldServerForDimension(coord.dim).getBlock(coord.x, coord.y, coord.z);
packet.field_148884_e = MinecraftServer.getServer().worldServerForDimension(coord.dim).getBlockMetadata(coord.x, coord.y, coord.z);
visualObject.player.playerNetServerHandler.sendPacket(packet);
blockCoordsIterator.remove();
}
}
if (visualObject.blockCoords.isEmpty())
visualObjectIterator.remove();
}
}
}
public void markBlock(int x, int y, int z, int dim, Block block, EntityPlayerMP caller, Object key) {
BlockCoords singleCoord = new BlockCoords(x, y, z, dim, block);
for(VisualObject visualObject : markedBlocks) {
if(visualObject.player == caller && visualObject.object == key) {
visualObject.blockCoords.add(singleCoord);
return;
}
}
List<BlockCoords> blockCoords = new ArrayList<BlockCoords>();
blockCoords.add(singleCoord);
markedBlocks.add(new VisualObject(caller, key, blockCoords));
}
public void markBlocks(EntityPlayerMP caller, Object key, List<BlockCoords> blockList) {
for(VisualObject visualObject : markedBlocks) {
if(visualObject.player == caller && visualObject.object == key) {
visualObject.blockCoords.addAll(blockList);
return;
}
}
markedBlocks.add(new VisualObject(caller, key, blockList));
}
public void markCorners(int selectionX1, int selectionY1, int selectionZ1, int selectionX2, int selectionY2, int selectionZ2, int dim, EntityPlayerMP caller) {
List<BlockCoords> blockList = new ArrayList<BlockCoords>();
blockList.add(new BlockCoords(selectionX1, selectionY1, selectionZ1, dim, Blocks.redstone_block));
blockList.add(new BlockCoords(selectionX2, selectionY2, selectionZ2, dim, Blocks.redstone_block));
// On the X
blockList.add(new BlockCoords(selectionX1 + (selectionX1 > selectionX2 ? -1 : 1), selectionY1, selectionZ1, dim, Blocks.redstone_block));
blockList.add(new BlockCoords(selectionX2 + (selectionX1 > selectionX2 ? 1 : -1), selectionY2, selectionZ2, dim, Blocks.redstone_block));
blockList.add(new BlockCoords(selectionX1 + (selectionX1 > selectionX2 ? -2 : 2), selectionY1, selectionZ1, dim, Blocks.redstone_block));
blockList.add(new BlockCoords(selectionX2 + (selectionX1 > selectionX2 ? 2 : -2), selectionY2, selectionZ2, dim, Blocks.redstone_block));
// On the Z
blockList.add(new BlockCoords(selectionX2, selectionY2, selectionZ2 + (selectionZ1 > selectionZ2 ? 1 : -1), dim, Blocks.redstone_block));
blockList.add(new BlockCoords(selectionX1, selectionY1, selectionZ1 + (selectionZ1 > selectionZ2 ? -1 : 1), dim, Blocks.redstone_block));
blockList.add(new BlockCoords(selectionX2, selectionY2, selectionZ2 + (selectionZ1 > selectionZ2 ? 2 : -2), dim, Blocks.redstone_block));
blockList.add(new BlockCoords(selectionX1, selectionY1, selectionZ1 + (selectionZ1 > selectionZ2 ? -2 : 2), dim, Blocks.redstone_block));
if (selectionY1 != selectionY2) {
// On the Y
blockList.add(new BlockCoords(selectionX1, selectionY1 + (selectionY1 > selectionY2 ? -1 : 1), selectionZ1, dim, Blocks.redstone_block));
blockList.add(new BlockCoords(selectionX2, selectionY2 + (selectionY1 > selectionY2 ? 1 : -1), selectionZ2, dim, Blocks.redstone_block));
blockList.add(new BlockCoords(selectionX1, selectionY1 + (selectionY1 > selectionY2 ? -2 : 2), selectionZ1, dim, Blocks.redstone_block));
blockList.add(new BlockCoords(selectionX2, selectionY2 + (selectionY1 > selectionY2 ? 2 : -2), selectionZ2, dim, Blocks.redstone_block));
}
// Marking it to itself since null would not be possible
markBlocks(caller, caller, blockList);
}
public void markPlotBorders(Plot plot, EntityPlayerMP caller) {
markPlotBorders(plot.getStartX(), plot.getStartY(), plot.getStartZ(), plot.getEndX(), plot.getEndY(), plot.getEndZ(), plot.getDim(), caller, plot);
}
public void markPlotBorders(int x1, int y1, int z1, int x2, int y2, int z2, int dim, EntityPlayerMP caller, Object key) {
// assuming x1 < x2, y1 < y2, z1 < z2
List<BlockCoords> blockList = new ArrayList<BlockCoords>();
for (int i = x1; i <= x2; i++) {
blockList.add(new BlockCoords(i, y1, z1, dim, Blocks.redstone_block));
blockList.add(new BlockCoords(i, y2, z1, dim, Blocks.redstone_block));
blockList.add(new BlockCoords(i, y1, z2, dim, Blocks.redstone_block));
blockList.add(new BlockCoords(i, y2, z2, dim, Blocks.redstone_block));
}
for (int i = y1; i <= y2; i++) {
blockList.add(new BlockCoords(x1, i, z1, dim, Blocks.redstone_block));
blockList.add(new BlockCoords(x2, i, z1, dim, Blocks.redstone_block));
blockList.add(new BlockCoords(x1, i, z2, dim, Blocks.redstone_block));
blockList.add(new BlockCoords(x2, i, z2, dim, Blocks.redstone_block));
}
for (int i = z1; i <= z2; i++) {
blockList.add(new BlockCoords(x1, y1, i, dim, Blocks.redstone_block));
blockList.add(new BlockCoords(x2, y1, i, dim, Blocks.redstone_block));
blockList.add(new BlockCoords(x1, y2, i, dim, Blocks.redstone_block));
blockList.add(new BlockCoords(x2, y2, i, dim, Blocks.redstone_block));
}
addMarkedBlocks(caller, key, blockList);
}
public void markTownBorders(TownBlocksContainer townBlocksContainer, EntityPlayerMP caller) {
int[] dx = {-1, -1, 0, 1, 1, 1, 0, -1};
int[] dz = {0, 1, 1, 1, 0, -1, -1, -1};
int x, y, z;
List<BlockCoords> blockList = new ArrayList<BlockCoords>();
for (TownBlock block : townBlocksContainer) {
// Showing lines in borders
for (int i = 0; i < 8; i += 2) {
if (townBlocksContainer.get(block.getDim(), block.getX() + dx[i], block.getZ() + dz[i]) == null) {
if (dx[i] == 0) {
z = dz[i] == -1 ? block.getZ() << 4 : (block.getZ() << 4) + 15;
x = block.getX() << 4;
for (int k = x + 1; k <= x + 14; k++) {
y = WorldUtils.getMaxHeightWithSolid(block.getDim(), k, z);
BlockCoords blockCoord = new BlockCoords(k, y, z, block.getDim(), Blocks.lapis_block);
blockList.add(blockCoord);
}
} else {
x = dx[i] == -1 ? block.getX() << 4 : (block.getX() << 4) + 15;
z = block.getZ() << 4;
for (int k = z + 1; k <= z + 14; k++) {
y = WorldUtils.getMaxHeightWithSolid(block.getDim(), x, k);
BlockCoords blockCoord = new BlockCoords(x, y, k, block.getDim(), Blocks.lapis_block);
blockList.add(blockCoord);
}
}
}
}
// Showing corners in borders
for (int i = 1; i < 8; i += 2) {
x = dx[i] == 1 ? block.getX() << 4 : (block.getX() << 4) + 15;
z = dz[i] == 1 ? block.getZ() << 4 : (block.getZ() << 4) + 15;
y = WorldUtils.getMaxHeightWithSolid(block.getDim(), x, z);
BlockCoords blockCoord = new BlockCoords(x, y, z, block.getDim(), Blocks.lapis_block);
blockList.add(blockCoord);
}
}
addMarkedBlocks(caller, townBlocksContainer, blockList);
}
/**
* This method is gonna wait until the tick function clears the spot.
*/
public void addMarkedBlocks(final EntityPlayerMP caller, final Object key, final List<BlockCoords> blockCoords) {
// Waits 5 milliseconds if there are still blocks to be deleted.
Thread t = new Thread() {
@Override
public void run() {
VisualObject visualObject = null;
for(VisualObject marked : markedBlocks) {
if(marked.player == caller && marked.object == key)
visualObject = marked;
}
if (visualObject != null) {
boolean blocksNotDeleted = true;
while (blocksNotDeleted && markedBlocks.contains(visualObject)) {
blocksNotDeleted = false;
for (BlockCoords coords : visualObject.blockCoords) {
if (coords.deleted)
blocksNotDeleted = true;
}
try {
Thread.sleep(5);
} catch (Exception ex) {
MyTown.instance.LOG.error(ExceptionUtils.getStackTrace(ex));
}
}
visualObject.blockCoords.addAll(blockCoords);
} else {
visualObject = new VisualObject(caller, key, blockCoords);
markedBlocks.add(visualObject);
}
}
};
t.start();
}
public void updatePlotBorders(Plot plot) {
List<EntityPlayerMP> callers = new ArrayList<EntityPlayerMP>();
for(VisualObject visualObject : markedBlocks) {
if(visualObject.isPlot() && visualObject.object.equals(plot)) {
for(BlockCoords coords : visualObject.blockCoords) {
coords.deleted = true;
}
callers.add(visualObject.player);
}
}
for(EntityPlayerMP player : callers) {
markPlotBorders(plot, player);
}
}
public void updateTownBorders(TownBlocksContainer townBlocksContainer) {
List<EntityPlayerMP> callers = new ArrayList<EntityPlayerMP>();
for(VisualObject visualObject : markedBlocks) {
if(visualObject.isTown() && visualObject.object.equals(townBlocksContainer)) {
for(BlockCoords coords : visualObject.blockCoords) {
coords.deleted = true;
}
callers.add(visualObject.player);
}
}
for(EntityPlayerMP player : callers) {
markTownBorders(townBlocksContainer, player);
}
}
/**
* Unmarks all the blocks that are linked to the player and object key.
*/
public synchronized void unmarkBlocks(EntityPlayerMP caller, Object key) {
for(VisualObject visualObject : markedBlocks) {
if(visualObject.player == caller && visualObject.object == key) {
for(BlockCoords blockCoords : visualObject.blockCoords)
blockCoords.deleted = true;
}
}
}
public synchronized void unmarkBlocks(Object key) {
for(VisualObject visualObject : markedBlocks) {
if(visualObject.object == key) {
for(BlockCoords blockCoords : visualObject.blockCoords)
blockCoords.deleted = true;
}
}
}
public void unmarkTowns(EntityPlayerMP caller) {
for(VisualObject visualObject : markedBlocks) {
if(visualObject.player == caller && visualObject.isTown()) {
for(BlockCoords blockCoords : visualObject.blockCoords)
blockCoords.deleted = true;
}
}
}
public void unmarkPlots(EntityPlayerMP caller) {
for(VisualObject visualObject : markedBlocks) {
if(visualObject.player == caller && visualObject.isPlot()) {
for(BlockCoords blockCoords : visualObject.blockCoords)
blockCoords.deleted = true;
}
}
}
public boolean isBlockMarked(int x, int y, int z, int dim, EntityPlayerMP player) {
for(VisualObject visualObject : markedBlocks) {
if(visualObject.player == player) {
for (BlockCoords coord : visualObject.blockCoords) {
if (coord.x == x && coord.y == y && coord.z == z && coord.dim == dim) {
coord.packetSent = false;
return true;
}
}
}
}
return false;
}
/**
* Class used to store all the blocks that are marked.
*/
private class BlockCoords {
private final int x;
private final int y;
private final int z;
private final int dim;
private boolean deleted = false;
private boolean packetSent = false;
/**
* The block to which the sistem should change
*/
private final Block block;
public BlockCoords(int x, int y, int z, int dim, Block block) {
this.x = x;
this.y = y;
this.z = z;
this.dim = dim;
this.block = block;
}
}
private class VisualObject {
private EntityPlayerMP player;
private Object object;
private List<BlockCoords> blockCoords;
public VisualObject(EntityPlayerMP player, Object object, List<BlockCoords> blockCoords) {
this.player = player;
this.object = object;
this.blockCoords = blockCoords;
}
public boolean isTown() {
return object != null && object instanceof TownBlocksContainer;
}
public boolean isPlot() {
return object != null && object instanceof Plot;
}
}
}
|
package net.darkhax.orestages;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.logging.log4j.Logger;
import net.darkhax.bookshelf.util.RenderUtils;
import net.darkhax.orestages.api.OreTiersAPI;
import net.darkhax.orestages.client.renderer.block.model.BakedModelTiered;
import net.minecraft.block.state.IBlockState;
import net.minecraft.util.Tuple;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.event.FMLInterModComms;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
@Mod(modid = "orestages", name = "Ore Stages", version = "@VERSION@", dependencies = "required-after:bookshelf@[2.1.428,);required-after:gamestages@[1.0.52,);required-after:crafttweaker@[3.0.25.,)")
public class OreTiers {
public static Logger log;
@Mod.EventHandler
public void preInit (FMLPreInitializationEvent ev) {
log = ev.getModLog();
MinecraftForge.EVENT_BUS.register(new OreTiersEventHandler());
if (Loader.isModLoaded("waila")) {
FMLInterModComms.sendMessage("waila", "register", "com.jarhax.oretiers.compat.waila.OreTiersProvider.register");
}
}
@Mod.EventHandler
@SideOnly(Side.CLIENT)
public void postInit (FMLPostInitializationEvent ev) {
log.info("Loaded {} block replacements!", OreTiersAPI.STATE_MAP.size());
log.info("Starting model wrapping for replacements.");
final Map<IBlockState, Tuple<String, IBlockState>> differences = OreTiersAPI.STATE_MAP;
if (!OreTiersAPI.STATE_MAP.isEmpty()) {
for (final Entry<IBlockState, Tuple<String, IBlockState>> entry : differences.entrySet()) {
log.debug("Adding a wrapper model for {}", entry.getKey().toString());
RenderUtils.setModelForState(entry.getKey(), new BakedModelTiered(entry.getValue().getFirst(), entry.getKey(), entry.getValue().getSecond()));
}
}
else {
log.info("There are no replacements. Have you added them in a CrT script?");
}
log.info("Model wrapping finished!");
}
}
|
package net.fortuna.ical4j.vcard;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import net.fortuna.ical4j.util.Strings;
import net.fortuna.ical4j.vcard.Property.Name;
/**
* @author Ben
*
*/
public final class VCard implements Serializable {
private static final long serialVersionUID = -4784034340843199392L;
private List<Property> properties;
/**
* Default constructor.
*/
public VCard() {
this(new ArrayList<Property>());
}
/**
* @param properties
*/
public VCard(List<Property> properties) {
this.properties = properties;
}
/**
* Returns a reference to the list of properties for the VCard instance. Note that
* any changes to this list are reflected in the VCard object list.
* @return the properties
*/
public List<Property> getProperties() {
return properties;
}
/**
* Returns a list of properties for the VCard instance with a matching name. Any modifications
* to this list will not effect the list referenced by the VCard instance.
* @param name
* @return
*/
public List<Property> getProperties(Name name) {
List<Property> matches = new ArrayList<Property>();
for (Property p : properties) {
if (p.name.equals(name)) {
matches.add(p);
}
}
return matches;
}
/**
* Returns the first property found matching the specified name.
* @param name
* @return the first matching property, or null if no properties match
*/
public Property getProperty(Name name) {
for (Property p : properties) {
if (p.name.equals(name)) {
return p;
}
}
return null;
}
/**
* Returns a list of non-standard properties for the VCard instance with a matching name. Any modifications
* to this list will not effect the list referenced by the VCard instance.
* @param name
* @return
*/
public List<Property> getExtendedProperties(String name) {
List<Property> matches = new ArrayList<Property>();
for (Property p : properties) {
if (p.name.equals(Name.EXTENDED) && p.extendedName.equals(name)) {
matches.add(p);
}
}
return matches;
}
/**
* Returns the first non-standard property found matching the specified name.
* @param name
* @return the first matching property, or null if no properties match
*/
public Property getExtendedProperty(String name) {
for (Property p : properties) {
if (p.name.equals(Name.EXTENDED) && p.extendedName.equals(name)) {
return p;
}
}
return null;
}
@Override
public String toString() {
StringBuilder b = new StringBuilder();
b.append("BEGIN:VCARD");
b.append(Strings.LINE_SEPARATOR);
for (Property prop : properties) {
b.append(prop);
}
b.append("END:VCARD");
b.append(Strings.LINE_SEPARATOR);
return b.toString();
}
}
|
package net.jforum.search;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import net.jforum.entities.Post;
import net.jforum.exceptions.SearchException;
import net.jforum.util.preferences.ConfigKeys;
import net.jforum.util.preferences.SystemGlobals;
import org.apache.log4j.Logger;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.Filter;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.Sort;
import org.apache.lucene.search.SortField;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.TopFieldDocs;
/**
* @author Rafael Steil
* @version $Id$
*/
public class LuceneSearch implements NewDocumentAdded
{
private static final Logger LOGGER = Logger.getLogger(LuceneSearch.class);
private final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
private final Lock read = rwl.readLock();
private final Lock write = rwl.writeLock();
private IndexSearcher searcher;
private LuceneSettings settings;
private LuceneContentCollector collector;
public LuceneSearch(LuceneSettings settings, LuceneContentCollector collector)
{
this.settings = settings;
this.collector = collector;
this.openSearch();
}
public void newDocumentAdded() {
try {
write.lock();
if (searcher != null) {
searcher.close();
}
// re-open a new searcher
openSearch();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
write.unlock();
}
}
/**
* @return the search result
*/
public SearchResult<Post> search(SearchArgs args, int userId)
{
return this.performSearch(args, this.collector, null, userId);
}
public Document findDocumentByPostId (int postId) {
Document doc = null;
try {
read.lock();
TopDocs results = searcher.search(new TermQuery(
new Term(SearchFields.Keyword.POST_ID, String.valueOf(postId))), null, 1);
ScoreDoc[] hits = results.scoreDocs;
for (ScoreDoc hit : hits) {
doc = this.searcher.doc(hit.doc);
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
read.unlock();
}
return doc;
}
private SearchResult<Post> performSearch(SearchArgs args, LuceneContentCollector resultCollector, Filter filter, int userId)
{
SearchResult<Post> result;
try {
read.lock();
StringBuilder criteria = new StringBuilder(256);
this.filterByForum(args, criteria);
this.filterByUser(args, criteria, userId);
this.filterByKeywords(args, criteria);
this.filterByDateRange(args, criteria);
LOGGER.info("criteria=["+criteria.toString()+"]");
if (criteria.length() == 0) {
result = new SearchResult<Post>(new ArrayList<Post>(), 0);
} else {
Query query = new QueryParser(LuceneSettings.version, SearchFields.Indexed.CONTENTS, this.settings.analyzer()).parse(criteria.toString());
final int limit = SystemGlobals.getIntValue(ConfigKeys.SEARCH_RESULT_LIMIT);
TopFieldDocs tfd = searcher.search(query, filter, limit, getSorter(args));
ScoreDoc[] docs = tfd.scoreDocs;
int numDocs = tfd.totalHits;
if (numDocs > 0) {
result = new SearchResult<Post>(resultCollector.collect(args, docs, query), numDocs);
} else {
result = new SearchResult<Post>(new ArrayList<Post>(), 0);
}
LOGGER.info("hits="+numDocs);
}
} catch (Exception e) {
throw new SearchException(e);
} finally {
read.unlock();
}
return result;
}
// only options are relevance and date
private Sort getSorter (SearchArgs args) {
Sort sort;
SortField forumGroupingSortField = new SortField(SearchFields.Keyword.FORUM_ID, SortField.INT, false);
SortField dateSortField = new SortField(SearchFields.Keyword.DATE, SortField.LONG, args.isOrderDirectionDescending());
if ("time".equals(args.getOrderBy())) {
// sort by date
if (args.isGroupByForum()) {
sort = new Sort(new SortField[] { forumGroupingSortField, dateSortField });
} else {
sort = new Sort(new SortField[] { dateSortField });
}
} else {
// sort by relevance
if (args.isGroupByForum()) {
sort = new Sort(new SortField[] { forumGroupingSortField, SortField.FIELD_SCORE });
} else {
sort = new Sort(new SortField[] { SortField.FIELD_SCORE });
}
}
return sort;
}
private void filterByDateRange(SearchArgs args, StringBuilder criteria)
{
if (args.getFromDate() != null) {
if (criteria.length() > 0) {
criteria.append(" AND ");
}
criteria.append('(')
.append(SearchFields.Keyword.DATE)
.append(": [")
.append(this.settings.formatDateTime(args.getFromDate()))
.append(" TO ")
.append(this.settings.formatDateTime(args.getToDate()))
.append("])");
}
}
private void filterByUser (SearchArgs args, StringBuilder criteria, int userID) {
int[] userIds = args.getUserIds();
// if searching by user id (as opposed to solely by keyword)
if (userIds.length > 0) {
// By default, Lucene can't handle boolean queries with more than 1024 clauses.
// Instead of raising the limit, we ask the user to give more information.
if (userIds.length > 1000) {
throw new RuntimeException("This first name/last name combination matches too many users. Please be more specific.");
}
/*
if (args.shouldLimitSearchToTopicStarted()) {
// just looking for topics started by this user
criteria.append("+(").append(SearchFields.Keyword.IS_FIRST_POST).append(":true) ");
} else {
// if searching for all posts by a member, we have
// the option of filtering by those I started
if (args.isTopicsIstarted()) {
criteria.append("+(")
.append(SearchFields.Keyword.TOPIC_STARTER_ID)
.append(':')
.append(userID<0 ? "\\" : "")
.append(userID)
.append(')');
}
}*/
StringBuilder query = new StringBuilder();
for (int i = 0; i < userIds.length; i++) {
if (i > 0) {
query.append(" OR ");
}
query.append(SearchFields.Keyword.USER_ID).append(':').append(userIds[i]);
}
criteria.append("+(").append(query.toString()).append(')');
}
}
private void filterByKeywords(SearchArgs args, StringBuilder criteria)
{
LOGGER.info("searching for: " + args.rawKeywords());
if (args.rawKeywords().length() > 0) {
if (args.isMatchRaw()) {
if (criteria.length() >0) {
criteria.append(" AND ");
}
criteria.append('(');
if (args.shouldLimitSearchToSubject()) {
// subject only
criteria.append(SearchFields.Indexed.SUBJECT).append(':').append(args.rawKeywords());
} else {
// contents and subject
criteria.append(SearchFields.Indexed.CONTENTS).append(':').append(args.rawKeywords());
criteria.append(" OR ").append(SearchFields.Indexed.SUBJECT).append(':').append(args.rawKeywords());
}
criteria.append(')');
} else if (args.isMatchExact()) {
String escapedKeywords = "\"" + QueryParser.escape(args.rawKeywords()) + "\"";
criteria.append("+(");
if (args.shouldLimitSearchToSubject()) {
// subject only
criteria.append(SearchFields.Indexed.SUBJECT).append(':').append(escapedKeywords);
} else {
// contents and subject
criteria.append(SearchFields.Indexed.CONTENTS).append(':').append(escapedKeywords);
criteria.append(" OR ").append(SearchFields.Indexed.SUBJECT).append(':').append(escapedKeywords);
}
criteria.append(')');
} else {
String[] keywords = this.analyzeKeywords(args.rawKeywords());
if (keywords.length != 0) {
if (criteria.length() > 0) {
criteria.append(" AND ");
}
criteria.append("+(");
// for Porter stemming it's problematic to analyze (and potentially alter) the keywords twice
if (settings.analyzer() instanceof PorterStandardAnalyzer)
keywords = args.rawKeywords().split("\\s");
for (int i = 0; i < keywords.length; i++) {
if (keywords[i].trim().length() == 0)
continue;
if (args.isMatchAll()) {
criteria.append("+");
}
String escapedKeywords = QueryParser.escape(keywords[i]);
criteria.append('(');
if (args.shouldLimitSearchToSubject()) {
// subject only
criteria.append(SearchFields.Indexed.SUBJECT).append(':').append(escapedKeywords);
} else {
// contents and subject
criteria.append(SearchFields.Indexed.CONTENTS).append(':').append(escapedKeywords);
criteria.append(" OR ").append(SearchFields.Indexed.SUBJECT).append(':').append(escapedKeywords);
}
criteria.append(')');
}
criteria.append(')');
}
}
}
}
private void filterByForum(SearchArgs args, StringBuilder criteria)
{
if (args.getForumId() > 0) {
criteria.append("+(")
.append(SearchFields.Keyword.FORUM_ID)
.append(':')
.append(args.getForumId())
.append(')');
}
}
private String[] analyzeKeywords(String contents)
{
try {
TokenStream stream = this.settings.analyzer().tokenStream(SearchFields.Indexed.CONTENTS, new StringReader(contents));
stream.addAttribute(CharTermAttribute.class);
List<String> tokens = new ArrayList<String>();
stream.reset();
while (stream.incrementToken()) {
CharTermAttribute token = stream.getAttribute(CharTermAttribute.class);
if (token == null) {
break;
}
tokens.add(token.toString());
}
return tokens.toArray(new String[tokens.size()]);
}
catch (IOException e) {
throw new SearchException(e);
}
}
private void openSearch()
{
try {
this.searcher = new IndexSearcher(IndexReader.open(this.settings.directory()));
}
catch (IOException e) {
throw new SearchException(e.toString(), e);
}
}
}
|
package net.openhft.chronicle.core;
import java.lang.reflect.Field;
import static java.lang.management.ManagementFactory.getRuntimeMXBean;
public enum Jvm {
;
public static final boolean IS_DEBUG = getRuntimeMXBean().getInputArguments().toString().contains("jdwp");
@SuppressWarnings("unchecked")
public static <T extends Throwable> RuntimeException rethrow(Throwable t) throws T {
throw (T) t; // rely on vacuous cast
}
public static void trimStackTrace(StringBuilder sb, StackTraceElement... stes) {
int first = trimFirst(stes);
int last = trimLast(first, stes);
for (int i = first; i <= last; i++)
sb.append("\n\tat ").append(stes[i]);
}
static int trimFirst(StackTraceElement[] stes) {
int first = 0;
for (; first < stes.length; first++)
if (!isInternal(stes[first].getClassName()))
break;
return Math.max(0, first - 2);
}
public static int trimLast(int first, StackTraceElement[] stes) {
int last = stes.length - 1;
for (; first < last; last
if (!isInternal(stes[last].getClassName()))
break;
if (last < stes.length - 1) last++;
return last;
}
static boolean isInternal(String className) {
return className.startsWith("jdk.") || className.startsWith("sun.") || className.startsWith("java.");
}
@SuppressWarnings("SameReturnValue")
public static boolean isDebug() {
return IS_DEBUG || Boolean.getBoolean("debug");
}
public static void pause(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
}
public static Field getField(Class clazz, String name) {
try {
Field field = clazz.getDeclaredField(name);
field.setAccessible(true);
return field;
} catch (NoSuchFieldException e) {
throw new AssertionError(e);
}
}
}
|
package net.simpvp.Events;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.util.Base64;
import java.util.Collection;
import java.util.UUID;
import org.bukkit.ChatColor;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.potion.PotionEffect;
import org.bukkit.scoreboard.Team;
import org.bukkit.util.io.BukkitObjectOutputStream;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.MarkerManager;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.Level;
/** This class is responsible for handling the /event command.
*
* Saves all the player's information.
* Teleports users to the set starting location of the event.
* And prepares them for the event. */
public class EventCommand implements CommandExecutor {
private Logger INVENTORY_LOGGER = LogManager.getLogger("InventoryLog");
private static final Marker INVENTORY_MARKER = MarkerManager.getMarker("INVENTORY");
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
Player player = null;
if (sender instanceof Player) {
player = (Player) sender;
}
/* Command sender must be an ingame player */
if (player == null) {
Events.instance.getLogger().info("You must be a player to use this command.");
return true;
}
/* Event must be active */
if (!Event.getIsActive()) {
player.sendMessage(ChatColor.RED + "Event is currently closed for new contestants.\n"
+ "Please wait until the next event starts.");
return true;
}
/* If the event is not setup yet */
if (!Event.getIsComplete()) {
sender.sendMessage(ChatColor.RED + "Woops. Looks like the event is set to active,\n" +
"but I'm missing some information about the event.\n" +
"Please tell the nice admin that they're missing something :)");
return true;
}
/* If player quit an event less than 4 seconds ago */
if (EventPlayer.playerLastJoinTime.containsKey(player.getUniqueId())) {
if (System.currentTimeMillis() - EventPlayer.playerLastJoinTime.get(player.getUniqueId()) < 4 * 1000) {
sender.sendMessage(ChatColor.RED + "Please wait a few seconds before joining.");
return true;
}
}
if (Events.banned_players.contains(player.getUniqueId())) {
sender.sendMessage(ChatColor.RED + "You are banned from events.");
return true;
}
if (player.isInsideVehicle()) {
sender.sendMessage(ChatColor.RED + "You cannot join events while in a vehicle.");
return true;
}
if (player.getLocation().getY() < -64.0) {
sender.sendMessage(ChatColor.RED + "You cannot join events from your current location.");
return true;
}
if (player.isOp()) {
player.performCommand("rg bypass off");
}
UUID uuid = player.getUniqueId();
/* Everything seems to be in order. Saving all player info for when the event is over */
if (!Event.isPlayerActive(uuid)) {
save_player_data(player);
}
/* Now we reset all their stuff and teleport them off */
player.setFoodLevel(20);
player.setLevel(0);
player.setExp(0);
player.getInventory().clear();
player.getInventory().setArmorContents(null);
player.setHealth(player.getMaxHealth());
for (PotionEffect potionEffect : player.getActivePotionEffects())
player.removePotionEffect(potionEffect.getType());
player.setGameMode(GameMode.SURVIVAL);
player.teleport(Event.getStartLocation());
/* Leave current team. Doesn't save it, but maybe it should? */
Team team = player.getScoreboard().getPlayerTeam(player);
if (team != null) {
team.removePlayer(player);
}
player.sendMessage(ChatColor.AQUA + "Teleporting you to the event arena."
+ "\nWhen you die, you will be teleported back with all your items and XP in order.");
return true;
}
private void save_player_data(Player player) {
String sPlayer = player.getName();
Location playerLocation = player.getLocation();
int playerFoodLevel = player.getFoodLevel();
int playerLevel = player.getLevel();
float playerXP = player.getExp();
ItemStack[] armorContents = player.getInventory().getArmorContents();
ItemStack[] inventoryContents = player.getInventory().getContents();
Double playerHealth = player.getHealth();
Collection<PotionEffect> potionEffects = player.getActivePotionEffects();
GameMode gameMode = player.getGameMode();
/* Save all this data */
EventPlayer eventPlayer = new EventPlayer(player.getUniqueId(), sPlayer, playerLocation, playerFoodLevel, playerLevel, playerXP, armorContents, inventoryContents, playerHealth, potionEffects, gameMode, false);
eventPlayer.save();
/* Log it all, just in case */
if (INVENTORY_LOGGER.isDebugEnabled()) {
try {
ByteArrayOutputStream bytearray = new ByteArrayOutputStream();
OutputStream base64 = Base64.getEncoder().wrap(bytearray);
BukkitObjectOutputStream bukkitstream = new BukkitObjectOutputStream(base64);
int len = 0;
for (ItemStack itemStack : inventoryContents) {
if (itemStack == null) {
continue;
}
len += 1;
}
bukkitstream.writeInt(len);
for (ItemStack itemStack : inventoryContents) {
if (itemStack == null) {
continue;
}
bukkitstream.writeObject(itemStack);
}
bukkitstream.close();
base64.close();
INVENTORY_LOGGER.debug(INVENTORY_MARKER, String.format("%s is participating in event: '%d %d %d %s' %d %s", sPlayer, playerLocation.getBlockX(), playerLocation.getBlockY(), playerLocation.getBlockZ(), playerLocation.getWorld().getName(), playerLevel, bytearray.toString()));
} catch (Exception e) {
Events.instance.getLogger().warning("Failed to log inventory: " + e);
e.printStackTrace();
}
}
Events.instance.getLogger().info(String.format("%s is participating in event", sPlayer));
}
}
|
package no.finn.unleash;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import no.finn.unleash.metric.UnleashMetricService;
import no.finn.unleash.metric.UnleashMetricServiceImpl;
import no.finn.unleash.repository.FeatureToggleRepository;
import no.finn.unleash.repository.ToggleBackupHandlerFile;
import no.finn.unleash.repository.HttpToggleFetcher;
import no.finn.unleash.repository.ToggleRepository;
import no.finn.unleash.strategy.ApplicationHostnameStrategy;
import no.finn.unleash.strategy.DefaultStrategy;
import no.finn.unleash.strategy.GradualRolloutRandomStrategy;
import no.finn.unleash.strategy.GradualRolloutSessionIdStrategy;
import no.finn.unleash.strategy.GradualRolloutUserIdStrategy;
import no.finn.unleash.strategy.RemoteAddressStrategy;
import no.finn.unleash.strategy.Strategy;
import no.finn.unleash.strategy.UnknownStrategy;
import no.finn.unleash.strategy.UserWithIdStrategy;
import no.finn.unleash.util.UnleashConfig;
import no.finn.unleash.util.UnleashScheduledExecutor;
import no.finn.unleash.util.UnleashScheduledExecutorImpl;
public final class DefaultUnleash implements Unleash {
private static final List<Strategy> BUILTIN_STRATEGIES = Arrays.asList(new DefaultStrategy(),
new ApplicationHostnameStrategy(),
new GradualRolloutRandomStrategy(),
new GradualRolloutSessionIdStrategy(),
new GradualRolloutUserIdStrategy(),
new RemoteAddressStrategy(),
new UserWithIdStrategy());
private static final UnknownStrategy UNKNOWN_STRATEGY = new UnknownStrategy();
private static final UnleashScheduledExecutor unleashScheduledExecutor = new UnleashScheduledExecutorImpl();
private final UnleashMetricService metricService;
private final ToggleRepository toggleRepository;
private final Map<String, Strategy> strategyMap;
private final UnleashContextProvider contextProvider;
private static FeatureToggleRepository defaultToggleRepository(UnleashConfig unleashConfig) {
return new FeatureToggleRepository(
unleashConfig,
unleashScheduledExecutor,
new HttpToggleFetcher(unleashConfig),
new ToggleBackupHandlerFile(unleashConfig));
}
public DefaultUnleash(UnleashConfig unleashConfig, Strategy... strategies) {
this(unleashConfig, defaultToggleRepository(unleashConfig), strategies);
}
public DefaultUnleash(UnleashConfig unleashConfig, ToggleRepository toggleRepository, Strategy... strategies) {
this.toggleRepository = toggleRepository;
this.strategyMap = buildStrategyMap(strategies);
this.contextProvider = unleashConfig.getContextProvider();
this.metricService = new UnleashMetricServiceImpl(unleashConfig, unleashScheduledExecutor);
metricService.register(strategyMap.keySet());
}
@Override
public boolean isEnabled(final String toggleName) {
return isEnabled(toggleName, false);
}
@Override
public boolean isEnabled(final String toggleName, final boolean defaultSetting) {
return isEnabled(toggleName, contextProvider.getContext(), defaultSetting);
}
@Override
public boolean isEnabled(final String toggleName, final UnleashContext context ,final boolean defaultSetting) {
boolean enabled = false;
FeatureToggle featureToggle = toggleRepository.getToggle(toggleName);
if (featureToggle == null) {
enabled = defaultSetting;
} else if(!featureToggle.isEnabled()) {
enabled = false;
} else {
enabled = featureToggle.getStrategies().stream()
.filter(as -> getStrategy(as.getName()).isEnabled(as.getParameters(), context))
.findFirst()
.isPresent();
}
metricService.count(toggleName, enabled);
return enabled;
}
private Map<String, Strategy> buildStrategyMap(Strategy[] strategies) {
Map<String, Strategy> map = new HashMap<>();
BUILTIN_STRATEGIES.forEach(strategy -> map.put(strategy.getName(), strategy));
if (strategies != null) {
for (Strategy strategy : strategies) {
map.put(strategy.getName(), strategy);
}
}
return map;
}
private Strategy getStrategy(String strategy) {
return strategyMap.containsKey(strategy) ? strategyMap.get(strategy) : UNKNOWN_STRATEGY;
}
}
|
package no.uis.ux.cipsi.plot;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics;
import com.panayotis.gnuplot.dataset.Point;
import com.panayotis.gnuplot.dataset.PointDataSet;
public class PlotUtils {
public static Map<String, List<Point<Number>>> addDataPoint(String dataSetName, int x, double y, Map<String, List<Point<Number>>> dataPointMap) {
List<Point<Number>> dataPointList = dataPointMap.get(dataSetName);
if (dataPointList == null){
dataPointList = new ArrayList<Point<Number>>();
dataPointMap.put(dataSetName, dataPointList);
}
if (Double.compare(y, Double.NaN) == 0) {
return dataPointMap;
}
Point<Number> mean = new Point<Number>(x, y);
// System.out.println("mean:" + stats.getMean());
dataPointList.add(mean);
return dataPointMap;
}
public static Map<String, List<Point<Number>>> addBoxDataPoint(String dataSetName, int x, double xOffset, double boxWidth, double y, Map<String, List<Point<Number>>> dataPointMap) {
List<Point<Number>> dataPointList = dataPointMap.get(dataSetName);
if (dataPointList == null){
dataPointList = new ArrayList<Point<Number>>();
dataPointMap.put(dataSetName, dataPointList);
}
if (Double.compare(y, Double.NaN) == 0) {
return dataPointMap;
}
Point<Number> mean = new Point<Number>(x + xOffset, y, boxWidth);
// System.out.println("mean:" + stats.getMean());
dataPointList.add(mean);
return dataPointMap;
}
public static Map<String, List<Point<Number>>> addCandleStickDataPoints(String dataSetName, int x, double xOffset, double boxWidth, DescriptiveStatistics stats, Map<String, List<Point<Number>>> dataPointMap) {
List<Point<Number>> dataPointList = dataPointMap.get(dataSetName);
if (dataPointList == null){
dataPointList = new ArrayList<Point<Number>>();
dataPointMap.put(dataSetName, dataPointList);
}
if (Double.compare(stats.getMean(), Double.NaN) == 0) {
return dataPointMap;
}
//x box_min whisker_min whisker_high box_high box_width
Point<Number> mean = new Point<Number>(x + xOffset, stats.getPercentile(25), stats.getMin(), stats.getMax(), stats.getPercentile(75), boxWidth);
// Point<Number> mean = new Point<Number>(x + xOffset, stats.getPercentile(95), stats.getMin(), stats.getMax(), boxWidth);
// System.out.println("mean:" + stats.getMean());
dataPointList.add(mean);
return dataPointMap;
}
public static Map<String, List<Point<Number>>> addDataPointsWithMinMax(String dataSetName, int x, double xOffset, double boxWidth, DescriptiveStatistics stats, Map<String, List<Point<Number>>> dataPointMap) {
List<Point<Number>> dataPointList = dataPointMap.get(dataSetName);
if (dataPointList == null){
dataPointList = new ArrayList<Point<Number>>();
dataPointMap.put(dataSetName, dataPointList);
}
if (Double.compare(stats.getMean(), Double.NaN) == 0) {
return dataPointMap;
}
Point<Number> mean = new Point<Number>(x + xOffset, stats.getMean(), stats.getMin(), stats.getMax(), boxWidth);
// Point<Number> mean = new Point<Number>(x + xOffset, stats.getPercentile(95), stats.getMin(), stats.getMax(), boxWidth);
// System.out.println("mean:" + stats.getMean());
dataPointList.add(mean);
return dataPointMap;
}
public static PointDataSet<Number> getSortedPointDataSetForCandleStick(List<Point<Number>> pointListOrig, boolean inverse) {
PointDataSet<Number> points = new PointDataSet<>();
List<Point<Number>> pointList = new ArrayList<Point<Number>>();
int scale = ((inverse == true) ? -1 : 1);
// Fail-safe behavior
if (pointListOrig == null || pointListOrig.size() == 0) {
points.add(new Point(0));
}
for (Point<Number> point : pointListOrig) {
Number[] dataPoints = new Number[point.getDimensions()];
for (int i = 1; i < point.getDimensions(); i++) {
dataPoints[i] = scale * point.get(i).doubleValue();
}
dataPoints[0] = point.get(0);
Point<Number> newPoint = new Point<Number>(dataPoints);
System.out.println("adding " + newPoint);
pointList.add(newPoint);
}
Collections.sort(pointList, new Comparator<Point<Number>>() {
@Override
public int compare(Point<Number> o1, Point<Number> o2) {
if (o1.get(0).doubleValue() < o2.get(0).doubleValue()){
return -1;
} else if (o1.get(0).doubleValue() == o2.get(0).doubleValue()) {
return 0;
} else {
return 1;
}
}
});
points.addAll(pointList);
return points;
}
public static PointDataSet<Number> getSortedPointDataSetWithMinMaxForBox(List<Point<Number>> pointListOrig, boolean inverse) {
PointDataSet<Number> points = new PointDataSet<>();
List<Point<Number>> pointList = new ArrayList<Point<Number>>();
int scale = ((inverse == true) ? -1 : 1);
// Fail-safe behavior
if (pointListOrig == null || pointListOrig.size() == 0) {
points.add(new Point(0));
}
for (Point<Number> point : pointListOrig) {
pointList.add(new Point<Number>(point.get(0),
(scale * point.get(1).doubleValue())
,
(scale * point.get(2).doubleValue()),
(scale * point.get(3).doubleValue()),
(point.get(4).doubleValue())
));
}
Collections.sort(pointList, new Comparator<Point<Number>>() {
@Override
public int compare(Point<Number> o1, Point<Number> o2) {
if (o1.get(0).doubleValue() < o2.get(0).doubleValue()){
return -1;
} else if (o1.get(0).doubleValue() == o2.get(0).doubleValue()) {
return 0;
} else {
return 1;
}
}
});
points.addAll(pointList);
return points;
}
public static PointDataSet<Number> getSortedPointDataSetForBox(List<Point<Number>> pointListOrig, boolean inverse) {
PointDataSet<Number> points = new PointDataSet<>();
List<Point<Number>> pointList = new ArrayList<Point<Number>>();
int scale = ((inverse == true) ? -1 : 1);
// Fail-safe behavior
if (pointListOrig == null || pointListOrig.size() == 0) {
points.add(new Point(0));
}
for (Point<Number> point : pointListOrig) {
pointList.add(new Point<Number>(point.get(0),
(scale * point.get(1).doubleValue())
,
(scale * point.get(2).doubleValue())
));
}
Collections.sort(pointList, new Comparator<Point<Number>>() {
@Override
public int compare(Point<Number> o1, Point<Number> o2) {
if (o1.get(0).doubleValue() < o2.get(0).doubleValue()){
return -1;
} else if (o1.get(0).doubleValue() == o2.get(0).doubleValue()) {
return 0;
} else {
return 1;
}
}
});
points.addAll(pointList);
return points;
}
public static PointDataSet<Number> getSortedPointDataSet(List<Point<Number>> pointListOrig, boolean inverse) {
PointDataSet<Number> points = new PointDataSet<>();
List<Point<Number>> pointList = new ArrayList<Point<Number>>();
int scale = ((inverse == true) ? -1 : 1);
// Fail-safe behavior
if (pointListOrig == null || pointListOrig.size() == 0) {
points.add(new Point(0));
}
for (Point<Number> point : pointListOrig) {
pointList.add(new Point<Number>(point.get(0),
(scale * point.get(1).doubleValue())
));
}
Collections.sort(pointList, new Comparator<Point<Number>>() {
@Override
public int compare(Point<Number> o1, Point<Number> o2) {
if (o1.get(0).doubleValue() < o2.get(0).doubleValue()){
return -1;
} else if (o1.get(0).doubleValue() == o2.get(0).doubleValue()) {
return 0;
} else {
return 1;
}
}
});
points.addAll(pointList);
return points;
}
}
|
package operias.diff;
import java.io.File;
import java.io.IOException;
import java.security.InvalidParameterException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class FileDiffDirectory {
/**
* Directory name
*/
private String directoryName;
/**
* List of changed files within the directory
*/
private List<FileDiffFile> files;
/**
* List of changed files within the directory
*/
private List<FileDiffDirectory> directories;
/**
* Diff state of the directory
*/
private DiffState state;
/**
* Construct a new direcotyr for in the diff report
* @param directoryName
*/
public FileDiffDirectory(String directoryName, DiffState state) {
this.directoryName = directoryName;
this.state = state;
this.files = new ArrayList<FileDiffFile>();
this.directories = new ArrayList<FileDiffDirectory>();
}
/**
* @return the directoryName
*/
public String getDirectoryName() {
return directoryName;
}
/**
* @return the files
*/
public List<FileDiffFile> getFiles() {
return files;
}
/**
* @return the state
*/
public DiffState getState() {
return state;
}
/**
* @param state the state to set
*/
public void setState(DiffState state) {
this.state = state;
}
/**
* Add a new file to the files within this directory;
* @param file
*/
public void addFile(FileDiffFile file) {
files.add(file);
}
/**
* Add a new directory to this directory
* @param directory
*/
public void addDirectory(FileDiffDirectory directory) {
this.directories.add(directory);
}
/**
*
* @param originalDirectory
* @param newDirectory
* @throws IOException
*/
public static FileDiffDirectory compareDirectory(String originalDirectory, String newDirectory) throws IOException {
// Short cuts
if (originalDirectory == null) {
return fillDirectoryDiff(newDirectory, DiffState.NEW);
} else if (newDirectory == null) {
return fillDirectoryDiff(originalDirectory, DiffState.DELETED);
}
// Both directories should exists, if not, throw exceptions
FileDiffDirectory diffDirectory = new FileDiffDirectory(originalDirectory, DiffState.SAME);
File originalDirectoryFile = new File(originalDirectory);
File newDirectoryFile = new File(newDirectory);
if (!originalDirectoryFile.isDirectory()) {
throw new InvalidParameterException("'" +originalDirectory + "' is not a valid directory");
}
if (!newDirectoryFile.isDirectory()) {
throw new InvalidParameterException("'" +newDirectoryFile + "' is not a valid directory");
}
String[] newFiles = newDirectoryFile.list();
Arrays.sort(newFiles);
String[] originalFiles = originalDirectoryFile.list();
Arrays.sort(originalFiles);
List<String> filesWithinNewDirectory = Arrays.asList(newFiles);
List<String> filesWithinOriginalDirectory = Arrays.asList(originalFiles);
//First cmpare the original dirs with the new one to see changes and deleted file and directories
for(String fileName : filesWithinOriginalDirectory) {
File originalFile = new File(originalDirectoryFile, fileName);
if (originalFile.isHidden()) {
continue;
}
if (originalFile.isDirectory()) {
if (filesWithinNewDirectory.indexOf(fileName) >= 0) {
// Directory exists
File newDir = new File(newDirectoryFile, fileName);
diffDirectory.addDirectory(FileDiffDirectory.compareDirectory(originalFile.getAbsolutePath(), newDir.getAbsolutePath()));
} else {
// Directory was deleted
diffDirectory.addDirectory(FileDiffDirectory.compareDirectory(originalFile.getAbsolutePath(), null));
}
} else {
if (filesWithinNewDirectory.indexOf(fileName) >= 0) {
// File exists
File newFile = new File(newDirectoryFile, fileName);
diffDirectory.addFile(FileDiffFile.compareFile(originalFile.getAbsolutePath(), newFile.getAbsolutePath()));
} else {
// File was deleted
diffDirectory.addFile(FileDiffFile.compareFile(originalFile.getAbsolutePath(), null));
}
}
}
//Secondly check the new directory for any new files or directories
for(String fileName : filesWithinNewDirectory) {
File newFile = new File(newDirectory, fileName);
if (newFile.isHidden()) {
continue;
}
if (filesWithinOriginalDirectory.indexOf(fileName) < 0) {
if (newFile.isDirectory()) {
// directory is new
diffDirectory.addDirectory(FileDiffDirectory.compareDirectory(null, newFile.getAbsolutePath()));
} else {
// file is new
diffDirectory.addFile(FileDiffFile.compareFile(null, newFile.getAbsolutePath()));
}
}
}
//Check if we need to changed this directory status to changed
diffDirectory.setNewStatusIfNeeded();
return diffDirectory;
}
/**
* Set the status to CHANGED if any directory or file within this directory is changed
*/
private void setNewStatusIfNeeded() {
for(FileDiffDirectory dir : directories ) {
if (dir.getState() != DiffState.SAME) {
setState(DiffState.CHANGED);
return;
}
}
for(FileDiffFile file : files ) {
if (file.getState() != DiffState.SAME) {
setState(DiffState.CHANGED);
return;
}
}
}
/**
* File a deleted directory with state deleted, only states DELETED or NEW are accepted
* @param fileDiffDirectory
* @return
* @throws IOException
*/
private static FileDiffDirectory fillDirectoryDiff(String directory, DiffState state) throws IOException {
File dir = new File(directory);
File[] files = dir.listFiles();
Arrays.sort(files);
List<File> filesWithinDirectory = Arrays.asList(files);
FileDiffDirectory diffDirectory = new FileDiffDirectory(directory, state);
for(File file : filesWithinDirectory) {
if (file.isHidden()) {
continue;
}
if (file.isFile()) {
if (state.equals(DiffState.DELETED)) {
diffDirectory.addFile(FileDiffFile.compareFile(file.getAbsolutePath(), null));
} else {
diffDirectory.addFile(FileDiffFile.compareFile(null, file.getAbsolutePath()));
}
} else {
if (state.equals(DiffState.DELETED)) {
diffDirectory.addDirectory(FileDiffDirectory.compareDirectory(file.getAbsolutePath(), null));
} else {
diffDirectory.addDirectory(FileDiffDirectory.compareDirectory(null, file.getAbsolutePath()));
}
}
}
return diffDirectory;
}
/**
* Checks if the directory has no changes
* @return True if no changes were found in this directory, false otherwise
*/
public boolean isEmpty() {
boolean isEmpty = files.size() == 0;
for(FileDiffDirectory dir : directories) {
isEmpty &= dir.isEmpty();
}
return isEmpty;
}
/**
* @return the directories
*/
public List<FileDiffDirectory> getDirectories() {
return directories;
}
}
|
package org.animotron.graph;
import javolution.util.FastMap;
import org.animotron.Executor;
import org.animotron.exception.AnimoException;
import org.animotron.statement.operator.THE;
import org.neo4j.graphdb.*;
import org.neo4j.graphdb.index.IndexHits;
import org.neo4j.graphdb.index.IndexManager;
import org.neo4j.graphdb.index.RelationshipIndex;
import org.neo4j.kernel.EmbeddedGraphDatabase;
import org.xtreemfs.babudb.BabuDBFactory;
import org.xtreemfs.babudb.api.BabuDB;
import org.xtreemfs.babudb.api.exception.BabuDBException;
import org.xtreemfs.babudb.config.BabuDBConfig;
import org.xtreemfs.babudb.log.DiskLogger.SyncMode;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;
import static org.neo4j.graphdb.Direction.OUTGOING;
/**
* @author <a href="mailto:shabanovd@gmail.com">Dmitriy Shabanov</a>
*
*/
public class AnimoGraph {
private static GraphDatabaseService graphDb;
private static BabuDB babuDB;
private static String STORAGE;
private static Node ROOT, TOP; //EMPTY
private static CacheIndex CACHE;
private static OrderIndex ORDER;
public static RelationshipIndex RESULT_INDEX;
private static String RESULT = "RESULT";
public static void startDB(String folder, Map<String, String> config) throws BabuDBException {
STORAGE = folder;
graphDb = new EmbeddedGraphDatabase(STORAGE, config);
initDB();
}
public static void startDB(String folder) throws BabuDBException {
STORAGE = folder;
graphDb = new EmbeddedGraphDatabase(STORAGE);
initDB();
}
public static void initDB() throws BabuDBException {
BabuDBConfig config = new BabuDBConfig(new File(STORAGE, "babudb/databases/").getPath(), new File(STORAGE, "babudb/dblog/").getPath(), 4, 1024 * 1024 * 16, 5 * 60, SyncMode.ASYNC, 50, 0, false, 16, 1024 * 1024 * 512);
babuDB = BabuDBFactory.createBabuDB(config);
ROOT = graphDb.getReferenceNode();
IndexManager INDEX = graphDb.index();
CACHE = new CacheIndex(INDEX);
ORDER = new OrderIndex(INDEX);
RESULT_INDEX = INDEX.forRelationships(RESULT);
execute(
new GraphOperation<Void> () {
@Override
public Void execute() {
TOP = getOrCreateNode(ROOT, RelationshipTypes.TOP);
//EMPTY = getOrCreateNode(ROOT,RelationshipTypes.EMPTY);
return null;
}
}
);
}
public static GraphDatabaseService getDb() {
return graphDb;
}
public static BabuDB getBabuDB() {
return babuDB;
}
public static String getStorage() {
return STORAGE;
}
public static Node getROOT() {
return ROOT;
}
public static Node getTOP() {
return TOP;
}
public static OrderIndex getORDER() {
return ORDER;
}
public static void shutdownDB() {
System.out.println("shotdown");
Executor.shutdown();
while (!activeTx.isEmpty()) {
System.out.println("Active transactions "+countTx);
if (countTx > 0) {
for (Entry<Transaction, Exception> e : activeTx.entrySet()) {
e.getValue().printStackTrace();
}
}
try { Thread.sleep(1000); } catch (InterruptedException e) {}
}
graphDb.shutdown();
THE._.beforeShutdown();
}
private static FastMap<Transaction, Exception> activeTx = new FastMap<Transaction, Exception>();
private static int countTx = 0;
private static synchronized void inc() {
countTx++;
}
private static synchronized void dec() {
countTx
}
public static Transaction beginTx() {
Transaction tx = graphDb.beginTx();
activeTx.put(tx, new IOException());
inc();
return tx;
}
public static void finishTx(Transaction tx) {
tx.finish();
activeTx.remove(tx);
dec();
}
public static boolean isTransactionActive(Transaction tx) {
return activeTx.containsKey(tx);
}
/**
* Execute operation with transaction.
* @param <T>
*
* @param operation
* @return
*/
public static <T> T execute(GraphOperation<T> operation) {
T result = null;
Transaction tx = beginTx();
try {
result = operation.execute();
tx.success();
} finally {
finishTx(tx);
return result;
}
}
public static Node getNode(Node parent, RelationshipType type) {
Relationship r = parent.getSingleRelationship(type, OUTGOING);
return r == null ? null : r.getEndNode();
}
public static Node createNode(){
return graphDb.createNode();
}
public static Node createNode(Node parent, RelationshipType type) {
Node node = createNode();
parent.createRelationshipTo(node, type);
return node;
}
public static Node getOrCreateNode(Node parent, RelationshipType type) {
Relationship r = parent.getSingleRelationship(type, OUTGOING);
if (r != null)
return r.getEndNode();
Node node = createNode(parent, type);
return node;
}
public static void createCache(Node node, byte[] hash) {
CACHE.add(node, hash);
}
public static Node getCache(byte[] hash) throws AnimoException {
try {
return CACHE.get(hash);
} catch (BabuDBException e) {
throw new AnimoException(e);
}
}
public static void order (Relationship r, int order) {
ORDER.add(r, order);
}
public static void unorder (Relationship r) {
ORDER.remove(r);
}
public static void result (Relationship r, long id) {
RESULT_INDEX.add(r, RESULT, id);
}
public static IndexHits<Relationship> getResult(Relationship ref, Node node) {
return RESULT_INDEX.get(RESULT, ref.getId(), node, null);
//return RESULT_INDEX.query(RESULT, ref.getId(), node, null);
}
}
|
package org.gitlab4j.api;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import org.gitlab4j.api.GitLabApi.ApiVersion;
import org.gitlab4j.api.models.Branch;
import org.gitlab4j.api.models.Commit;
import org.gitlab4j.api.models.CompareResults;
import org.gitlab4j.api.models.Contributor;
import org.gitlab4j.api.models.TreeItem;
import org.gitlab4j.api.utils.FileUtils;
public class RepositoryApi extends AbstractApi {
public RepositoryApi(GitLabApi gitLabApi) {
super(gitLabApi);
}
/**
* Get a list of repository branches from a project, sorted by name alphabetically.
*
* <pre><code>GitLab Endpoint: GET /projects/:id/repository/branches</code></pre>
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @return the list of repository branches for the specified project
* @throws GitLabApiException if any exception occurs
*/
public List<Branch> getBranches(Object projectIdOrPath) throws GitLabApiException {
return getBranches(projectIdOrPath, null, getDefaultPerPage()).all();
}
/**
* Get a list of repository branches from a project, sorted by name alphabetically.
*
* <pre><code>GitLab Endpoint: GET /projects/:id/repository/branches</code></pre>
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param page the page to get
* @param perPage the number of Branch instances per page
* @return the list of repository branches for the specified project
* @throws GitLabApiException if any exception occurs
*/
public List<Branch> getBranches(Object projectIdOrPath, int page, int perPage) throws GitLabApiException {
Response response = get(Response.Status.OK, getPageQueryParams(page, perPage), "projects",
getProjectIdOrPath(projectIdOrPath), "repository", "branches");
return (response.readEntity(new GenericType<List<Branch>>() {}));
}
/**
* Get a Pager of repository branches from a project, sorted by name alphabetically.
*
* <pre><code>GitLab Endpoint: GET /projects/:id/repository/branches</code></pre>
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param itemsPerPage the number of Project instances that will be fetched per page
* @return the list of repository branches for the specified project ID
*
* @throws GitLabApiException if any exception occurs
*/
public Pager<Branch> getBranches(Object projectIdOrPath, int itemsPerPage) throws GitLabApiException {
return getBranches(projectIdOrPath, null, itemsPerPage);
}
/**
* Get a Stream of repository branches from a project, sorted by name alphabetically.
*
* <pre><code>GitLab Endpoint: GET /projects/:id/repository/branches</code></pre>
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @return a Stream of repository branches for the specified project
* @throws GitLabApiException if any exception occurs
*/
public Stream<Branch> getBranchesStream(Object projectIdOrPath) throws GitLabApiException {
return getBranches(projectIdOrPath, null, getDefaultPerPage()).stream();
}
/**
* Get a single project repository branch.
*
* <pre><code>GitLab Endpoint: GET /projects/:id/repository/branches/:branch</code></pre>
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param branchName the name of the branch to get
* @return the branch info for the specified project ID/branch name pair
* @throws GitLabApiException if any exception occurs
*/
public Branch getBranch(Object projectIdOrPath, String branchName) throws GitLabApiException {
Response response = get(Response.Status.OK, null, "projects",
getProjectIdOrPath(projectIdOrPath), "repository", "branches", urlEncode(branchName));
return (response.readEntity(Branch.class));
}
/**
* Get a List of repository branches from a project, sorted by name alphabetically, filter by the search term.
*
* <pre><code>GitLab Endpoint: GET /projects/:id/repository/branches?search=:search</code></pre>
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param search the branch name search term
* @return the List of repository branches for the specified project ID and search term
* @throws GitLabApiException if any exception occurs
*/
public List<Branch> getBranches(Object projectIdOrPath, String search) throws GitLabApiException {
return (getBranches(projectIdOrPath, search, getDefaultPerPage()).all());
}
/**
* Get a Pager of repository branches from a project, sorted by name alphabetically, filter by the search term.
*
* <pre><code>GitLab Endpoint: GET /projects/:id/repository/branches?search=:search</code></pre>
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param search the branch name search term
* @param itemsPerPage the number of Project instances that will be fetched per page
* @return the list of repository branches for the specified project ID and search term
*
* @throws GitLabApiException if any exception occurs
*/
public Pager<Branch> getBranches(Object projectIdOrPath, String search, int itemsPerPage) throws GitLabApiException {
MultivaluedMap<String, String> queryParams = ( search == null ? null :
new GitLabApiForm().withParam("search", urlEncode(search)).asMap() );
return (new Pager<Branch>(this, Branch.class, itemsPerPage, queryParams, "projects",
getProjectIdOrPath(projectIdOrPath), "repository", "branches"));
}
/**
* Get a Stream of repository branches from a project, sorted by name alphabetically, filter by the search term.
*
* <pre><code>GitLab Endpoint: GET /projects/:id/repository/branches?search=:search</code></pre>
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param search the branch name search term
* @return the Stream of repository branches for the specified project ID and search term
*
* @throws GitLabApiException if any exception occurs
*/
public Stream<Branch> getBranchesStream(Object projectIdOrPath, String search) throws GitLabApiException {
return (getBranches(projectIdOrPath, search, getDefaultPerPage()).stream());
}
/**
* Get an Optional instance with the value for the specific repository branch.
*
* <pre><code>GitLab Endpoint: GET /projects/:id/repository/branches/:branch</code></pre>
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param branchName the name of the branch to get
* @return an Optional instance with the info for the specified project ID/branch name pair as the value
* @throws GitLabApiException if any exception occurs
*/
public Optional<Branch> getOptionalBranch(Object projectIdOrPath, String branchName) throws GitLabApiException {
try {
return (Optional.ofNullable(getBranch(projectIdOrPath, branchName)));
} catch (GitLabApiException glae) {
return (GitLabApi.createOptionalFromException(glae));
}
}
/**
* Creates a branch for the project. Support as of version 6.8.x
*
* <pre><code>GitLab Endpoint: POST /projects/:id/repository/branches</code></pre>
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param branchName the name of the branch to create
* @param ref Source to create the branch from, can be an existing branch, tag or commit SHA
* @return the branch info for the created branch
* @throws GitLabApiException if any exception occurs
*/
public Branch createBranch(Object projectIdOrPath, String branchName, String ref) throws GitLabApiException {
Form formData = new GitLabApiForm()
.withParam(isApiVersion(ApiVersion.V3) ? "branch_name" : "branch", branchName, true)
.withParam("ref", ref, true);
Response response = post(Response.Status.CREATED, formData.asMap(), "projects",
getProjectIdOrPath(projectIdOrPath), "repository", "branches");
return (response.readEntity(Branch.class));
}
/**
* Delete a single project repository branch.
*
* <pre><code>GitLab Endpoint: DELETE /projects/:id/repository/branches/:branch</code></pre>
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param branchName the name of the branch to delete
* @throws GitLabApiException if any exception occurs
*/
public void deleteBranch(Object projectIdOrPath, String branchName) throws GitLabApiException {
Response.Status expectedStatus = (isApiVersion(ApiVersion.V3) ? Response.Status.OK : Response.Status.NO_CONTENT);
delete(expectedStatus, null, "projects",
getProjectIdOrPath(projectIdOrPath), "repository", "branches", urlEncode(branchName));
}
/**
* Protects a single project repository branch. This is an idempotent function,
* protecting an already protected repository branch will not produce an error.
*
* <pre><code>GitLab Endpoint: PUT /projects/:id/repository/branches/:branch/protect</code></pre>
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param branchName the name of the branch to protect
* @return the branch info for the protected branch
* @throws GitLabApiException if any exception occurs
*/
public Branch protectBranch(Object projectIdOrPath, String branchName) throws GitLabApiException {
Response response = put(Response.Status.OK, null, "projects",
getProjectIdOrPath(projectIdOrPath), "repository", "branches", urlEncode(branchName), "protect");
return (response.readEntity(Branch.class));
}
/**
* Unprotects a single project repository branch. This is an idempotent function, unprotecting an
* already unprotected repository branch will not produce an error.
*
* <pre><code>GitLab Endpoint: PUT /projects/:id/repository/branches/:branch/unprotect</code></pre>
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param branchName the name of the branch to un-protect
* @return the branch info for the unprotected branch
* @throws GitLabApiException if any exception occurs
*/
public Branch unprotectBranch(Object projectIdOrPath, String branchName) throws GitLabApiException {
Response response = put(Response.Status.OK, null, "projects",
getProjectIdOrPath(projectIdOrPath), "repository", "branches", urlEncode(branchName), "unprotect");
return (response.readEntity(Branch.class));
}
/**
* Get a list of repository files and directories in a project.
*
* <pre><code>GitLab Endpoint: GET /projects/:id/repository/tree</code></pre>
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @return a tree with the root directories and files of a project
* @throws GitLabApiException if any exception occurs
*/
public List<TreeItem> getTree(Object projectIdOrPath) throws GitLabApiException {
return (getTree(projectIdOrPath, "/", "master"));
}
/**
* Get a Pager of repository files and directories in a project.
*
* <pre><code>GitLab Endpoint: GET /projects/:id/repository/tree</code></pre>
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param itemsPerPage the number of Project instances that will be fetched per page
* @return a Pager containing a tree with the root directories and files of a project
* @throws GitLabApiException if any exception occurs
*/
public Pager<TreeItem> getTree(Object projectIdOrPath, int itemsPerPage) throws GitLabApiException {
return (getTree(projectIdOrPath, "/", "master", false, itemsPerPage));
}
/**
* Get a Stream of repository files and directories in a project.
*
* <pre><code>GitLab Endpoint: GET /projects/:id/repository/tree</code></pre>
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @return a Stream containing a tree with the root directories and files of a project
* @throws GitLabApiException if any exception occurs
*/
public Stream<TreeItem> getTreeStream(Object projectIdOrPath) throws GitLabApiException {
return (getTreeStream(projectIdOrPath, "/", "master"));
}
/**
* Get a list of repository files and directories in a project.
*
* <pre><code>GitLab Endpoint: GET /projects/:id/repository/tree</code></pre>
*
* id (required) - The ID of a project
* path (optional) - The path inside repository. Used to get content of subdirectories
* ref_name (optional) - The name of a repository branch or tag or if not given the default branch
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param filePath the path inside repository, used to get content of subdirectories
* @param refName the name of a repository branch or tag or if not given the default branch
* @return a tree with the directories and files of a project
* @throws GitLabApiException if any exception occurs
*/
public List<TreeItem> getTree(Object projectIdOrPath, String filePath, String refName) throws GitLabApiException {
return (getTree(projectIdOrPath, filePath, refName, false));
}
/**
* Get a Pager of repository files and directories in a project.
*
* <pre><code>GitLab Endpoint: GET /projects/:id/repository/tree</code></pre>
*
* id (required) - The ID of a project
* path (optional) - The path inside repository. Used to get content of subdirectories
* ref_name (optional) - The name of a repository branch or tag or if not given the default branch
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param filePath the path inside repository, used to get content of subdirectories
* @param refName the name of a repository branch or tag or if not given the default branch
* @param itemsPerPage the number of Project instances that will be fetched per page
* @return a Pager containing a tree with the directories and files of a project
* @throws GitLabApiException if any exception occurs
*/
public Pager<TreeItem> getTree(Object projectIdOrPath, String filePath, String refName, int itemsPerPage) throws GitLabApiException {
return (getTree(projectIdOrPath, filePath, refName, false, itemsPerPage));
}
/**
* Get a Stream of repository files and directories in a project.
*
* <pre><code>GitLab Endpoint: GET /projects/:id/repository/tree</code></pre>
*
* id (required) - The ID of a project
* path (optional) - The path inside repository. Used to get content of subdirectories
* ref_name (optional) - The name of a repository branch or tag or if not given the default branch
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param filePath the path inside repository, used to get content of subdirectories
* @param refName the name of a repository branch or tag or if not given the default branch
* @return a Stream containing a tree with the directories and files of a project
* @throws GitLabApiException if any exception occurs
*/
public Stream<TreeItem> getTreeStream(Object projectIdOrPath, String filePath, String refName) throws GitLabApiException {
return (getTreeStream(projectIdOrPath, filePath, refName, false));
}
/**
* Get a list of repository files and directories in a project.
*
* <pre><code>GitLab Endpoint: GET /projects/:id/repository/tree</code></pre>
*
* id (required) - The ID of a project
* path (optional) - The path inside repository. Used to get contend of subdirectories
* ref_name (optional) - The name of a repository branch or tag or if not given the default branch
* recursive (optional) - Boolean value used to get a recursive tree (false by default)
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param filePath the path inside repository, used to get content of subdirectories
* @param refName the name of a repository branch or tag or if not given the default branch
* @param recursive flag to get a recursive tree or not
* @return a tree with the directories and files of a project
* @throws GitLabApiException if any exception occurs
*/
public List<TreeItem> getTree(Object projectIdOrPath, String filePath, String refName, Boolean recursive) throws GitLabApiException {
return (getTree(projectIdOrPath, filePath, refName, recursive, getDefaultPerPage()).all());
}
/**
* Get a Pager of repository files and directories in a project.
*
* <pre><code>GitLab Endpoint: GET /projects/:id/repository/tree</code></pre>
*
* id (required) - The ID of a project
* path (optional) - The path inside repository. Used to get contend of subdirectories
* ref_name (optional) - The name of a repository branch or tag or if not given the default branch
* recursive (optional) - Boolean value used to get a recursive tree (false by default)
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param filePath the path inside repository, used to get content of subdirectories
* @param refName the name of a repository branch or tag or if not given the default branch
* @param recursive flag to get a recursive tree or not
* @param itemsPerPage the number of Project instances that will be fetched per page
* @return a tree with the directories and files of a project
* @throws GitLabApiException if any exception occurs
*/
public Pager<TreeItem> getTree(Object projectIdOrPath, String filePath, String refName, Boolean recursive, int itemsPerPage) throws GitLabApiException {
Form formData = new GitLabApiForm()
.withParam("id", getProjectIdOrPath(projectIdOrPath), true)
.withParam("path", filePath, false)
.withParam(isApiVersion(ApiVersion.V3) ? "ref_name" : "ref", (refName != null ? urlEncode(refName) : null), false)
.withParam("recursive", recursive, false);
return (new Pager<TreeItem>(this, TreeItem.class, itemsPerPage, formData.asMap(), "projects",
getProjectIdOrPath(projectIdOrPath), "repository", "tree"));
}
/**
* Get a Stream of repository files and directories in a project.
*
* <pre><code>GitLab Endpoint: GET /projects/:id/repository/tree</code></pre>
*
* id (required) - The ID of a project
* path (optional) - The path inside repository. Used to get contend of subdirectories
* ref_name (optional) - The name of a repository branch or tag or if not given the default branch
* recursive (optional) - Boolean value used to get a recursive tree (false by default)
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param filePath the path inside repository, used to get content of subdirectories
* @param refName the name of a repository branch or tag or if not given the default branch
* @param recursive flag to get a recursive tree or not
* @return a Stream containing a tree with the directories and files of a project
* @throws GitLabApiException if any exception occurs
*/
public Stream<TreeItem> getTreeStream(Object projectIdOrPath, String filePath, String refName, Boolean recursive) throws GitLabApiException {
return (getTree(projectIdOrPath, filePath, refName, recursive, getDefaultPerPage()).stream());
}
/**
* Get the raw file contents for a blob by blob SHA.
*
* <pre><code>GitLab Endpoint: GET /projects/:id/repository/raw_blobs/:sha</code></pre>
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param sha the SHA of the file to get the contents for
* @return the raw file contents for the blob on an InputStream
* @throws GitLabApiException if any exception occurs
*/
public InputStream getRawBlobContent(Object projectIdOrPath, String sha) throws GitLabApiException {
Response response = getWithAccepts(Response.Status.OK, null, MediaType.MEDIA_TYPE_WILDCARD,
"projects", getProjectIdOrPath(projectIdOrPath), "repository", "blobs", sha, "raw");
return (response.readEntity(InputStream.class));
}
/**
* Get an archive of the complete repository by SHA (optional).
*
* <pre><code>GitLab Endpoint: GET /projects/:id/repository/archive</code></pre>
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param sha the SHA of the archive to get
* @return an input stream that can be used to save as a file
* or to read the content of the archive
* @throws GitLabApiException if any exception occurs
*/
public InputStream getRepositoryArchive(Object projectIdOrPath, String sha) throws GitLabApiException {
Form formData = new GitLabApiForm().withParam("sha", sha);
Response response = getWithAccepts(Response.Status.OK, formData.asMap(), MediaType.WILDCARD,
"projects", getProjectIdOrPath(projectIdOrPath), "repository", "archive");
return (response.readEntity(InputStream.class));
}
/**
* Get an archive of the complete repository by SHA (optional).
*
* <pre><code>GitLab Endpoint: GET /projects/:id/repository/archive</code></pre>
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param sha the SHA of the archive to get
* @param format The archive format, defaults to "tar.gz" if null
* @return an input stream that can be used to save as a file or to read the content of the archive
* @throws GitLabApiException if format is not a valid archive format or any exception occurs
*/
public InputStream getRepositoryArchive(Object projectIdOrPath, String sha, String format) throws GitLabApiException {
ArchiveFormat archiveFormat = ArchiveFormat.forValue(format);
return (getRepositoryArchive(projectIdOrPath, sha, archiveFormat));
}
/**
* Get an archive of the complete repository by SHA (optional).
*
* <pre><code>GitLab Endpoint: GET /projects/:id/repository/archive</code></pre>
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param sha the SHA of the archive to get
* @param format The archive format, defaults to TAR_GZ if null
* @return an input stream that can be used to save as a file or to read the content of the archive
* @throws GitLabApiException if any exception occurs
*/
public InputStream getRepositoryArchive(Object projectIdOrPath, String sha, ArchiveFormat format) throws GitLabApiException {
if (format == null) {
format = ArchiveFormat.TAR_GZ;
}
Form formData = new GitLabApiForm().withParam("sha", sha);
Response response = getWithAccepts(Response.Status.OK, formData.asMap(), MediaType.WILDCARD,
"projects", getProjectIdOrPath(projectIdOrPath), "repository", "archive" + "." + format.toString());
return (response.readEntity(InputStream.class));
}
/**
* Get an archive of the complete repository by SHA (optional) and saves to the specified directory.
* If the archive already exists in the directory it will be overwritten.
*
* <pre><code>GitLab Endpoint: GET /projects/:id/repository/archive</code></pre>
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param sha the SHA of the archive to get
* @param directory the File instance of the directory to save the archive to, if null will use "java.io.tmpdir"
* @return a File instance pointing to the downloaded instance
* @throws GitLabApiException if any exception occurs
*/
public File getRepositoryArchive(Object projectIdOrPath, String sha, File directory) throws GitLabApiException {
Form formData = new GitLabApiForm().withParam("sha", sha);
Response response = getWithAccepts(Response.Status.OK, formData.asMap(), MediaType.WILDCARD,
"projects", getProjectIdOrPath(projectIdOrPath), "repository", "archive");
try {
if (directory == null)
directory = new File(System.getProperty("java.io.tmpdir"));
String filename = FileUtils.getFilenameFromContentDisposition(response);
File file = new File(directory, filename);
InputStream in = response.readEntity(InputStream.class);
Files.copy(in, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
return (file);
} catch (IOException ioe) {
throw new GitLabApiException(ioe);
}
}
/**
* Get an archive of the complete repository by SHA (optional) and saves to the specified directory.
* If the archive already exists in the directory it will be overwritten.
*
* <pre><code>GitLab Endpoint: GET /projects/:id/repository/archive</code></pre>
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param sha the SHA of the archive to get
* @param directory the File instance of the directory to save the archive to, if null will use "java.io.tmpdir"
* @param format The archive format, defaults to "tar.gz" if null
* @return a File instance pointing to the downloaded instance
* @throws GitLabApiException if format is not a valid archive format or any exception occurs
*/
public File getRepositoryArchive(Object projectIdOrPath, String sha, File directory, String format) throws GitLabApiException {
ArchiveFormat archiveFormat = ArchiveFormat.forValue(format);
return (getRepositoryArchive(projectIdOrPath, sha, directory, archiveFormat));
}
/**
* Get an archive of the complete repository by SHA (optional) and saves to the specified directory.
* If the archive already exists in the directory it will be overwritten.
*
* <pre><code>GitLab Endpoint: GET /projects/:id/repository/archive</code></pre>
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param sha the SHA of the archive to get
* @param directory the File instance of the directory to save the archive to, if null will use "java.io.tmpdir"
* @param format The archive format, defaults to TAR_GZ if null
* @return a File instance pointing to the downloaded instance
* @throws GitLabApiException if any exception occurs
*/
public File getRepositoryArchive(Object projectIdOrPath, String sha, File directory, ArchiveFormat format) throws GitLabApiException {
if (format == null) {
format = ArchiveFormat.TAR_GZ;
}
Form formData = new GitLabApiForm().withParam("sha", sha);
Response response = getWithAccepts(Response.Status.OK, formData.asMap(), MediaType.WILDCARD,
"projects", getProjectIdOrPath(projectIdOrPath), "repository", "archive" + "." + format.toString());
try {
if (directory == null)
directory = new File(System.getProperty("java.io.tmpdir"));
String filename = FileUtils.getFilenameFromContentDisposition(response);
File file = new File(directory, filename);
InputStream in = response.readEntity(InputStream.class);
Files.copy(in, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
return (file);
} catch (IOException ioe) {
throw new GitLabApiException(ioe);
}
}
public CompareResults compare(Object projectIdOrPath, String from, String to, boolean straight) throws GitLabApiException {
Form formData = new GitLabApiForm()
.withParam("from", from, true)
.withParam("to", to, true)
.withParam("straight", straight);
Response response = get(Response.Status.OK, formData.asMap(), "projects",
getProjectIdOrPath(projectIdOrPath), "repository", "compare");
return (response.readEntity(CompareResults.class));
}
/**
* Compare branches, tags or commits. This can be accessed without authentication
* if the repository is publicly accessible.
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param from the commit SHA or branch name
* @param to the commit SHA or branch name
* @return a CompareResults containing the results of the comparison
* @throws GitLabApiException if any exception occurs
*/
public CompareResults compare(Object projectIdOrPath, String from, String to) throws GitLabApiException {
return (compare(projectIdOrPath, from, to, false));
}
/**
* Get a list of contributors from a project.
*
* <pre><code>GitLab Endpoint: GET /projects/:id/repository/contributors</code></pre>
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @return a List containing the contributors for the specified project ID
* @throws GitLabApiException if any exception occurs
*/
public List<Contributor> getContributors(Object projectIdOrPath) throws GitLabApiException {
return (getContributors(projectIdOrPath, getDefaultPerPage()).all());
}
/**
* Get a list of contributors from a project and in the specified page range.
*
* <pre><code>GitLab Endpoint: GET /projects/:id/repository/contributors</code></pre>
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param page the page to get
* @param perPage the number of projects per page
* @return a List containing the contributors for the specified project ID
* @throws GitLabApiException if any exception occurs
*/
public List<Contributor> getContributors(Object projectIdOrPath, int page, int perPage) throws GitLabApiException {
Response response = get(Response.Status.OK, getPageQueryParams(page, perPage),
"projects", getProjectIdOrPath(projectIdOrPath), "repository", "contributors");
return (response.readEntity(new GenericType<List<Contributor>>() { }));
}
/**
* Get a Pager of contributors from a project.
*
* <pre><code>GitLab Endpoint: GET /projects/:id/repository/contributors</code></pre>
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param itemsPerPage the number of Project instances that will be fetched per page
* @return a Pager containing the contributors for the specified project ID
* @throws GitLabApiException if any exception occurs
*/
public Pager<Contributor> getContributors(Object projectIdOrPath, int itemsPerPage) throws GitLabApiException {
return new Pager<Contributor>(this, Contributor.class, itemsPerPage, null, "projects",
getProjectIdOrPath(projectIdOrPath), "repository", "contributors");
}
/**
* Get a list of contributors from a project.
*
* <pre><code>GitLab Endpoint: GET /projects/:id/repository/contributors</code></pre>
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @return a List containing the contributors for the specified project ID
* @throws GitLabApiException if any exception occurs
*/
public Stream<Contributor> getContributorsStream(Object projectIdOrPath) throws GitLabApiException {
return (getContributors(projectIdOrPath, getDefaultPerPage()).stream());
}
/**
* Get the common ancestor for 2 or more refs (commit SHAs, branch names or tags).
*
* <pre><code>GitLab Endpoint: GET /projects/:id/repository/merge_base</code></pre>
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param refs a List of 2 or more refs (commit SHAs, branch names or tags)
* @return the Commit instance containing the common ancestor
* @throws GitLabApiException if any exception occurs
*/
public Commit getMergeBase(Object projectIdOrPath, List<String> refs) throws GitLabApiException {
if (refs == null || refs.size() < 2) {
throw new RuntimeException("refs must conatin at least 2 refs");
}
List<String> encodedRefs = new ArrayList<>(refs.size());
for (String ref : refs) {
encodedRefs.add(urlEncode(ref));
}
GitLabApiForm queryParams = new GitLabApiForm().withParam("refs", encodedRefs, true);
Response response = get(Response.Status.OK, queryParams.asMap(), "projects",
getProjectIdOrPath(projectIdOrPath), "repository", "merge_base");
return (response.readEntity(Commit.class));
}
/**
* Get an Optional instance with the value of the common ancestor
* for 2 or more refs (commit SHAs, branch names or tags).
*
* <pre><code>GitLab Endpoint: GET /projects/:id/repository/merge_base</code></pre>
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param refs a List of 2 or more refs (commit SHAs, branch names or tags)
* @return an Optional instance with the Commit instance containing the common ancestor as the value
* @throws GitLabApiException if any exception occurs
*/
public Optional<Commit> getOptionalMergeBase(Object projectIdOrPath, List<String> refs) throws GitLabApiException {
try {
return (Optional.ofNullable(getMergeBase(projectIdOrPath, refs)));
} catch (GitLabApiException glae) {
return (GitLabApi.createOptionalFromException(glae));
}
}
public void deleteMergedBranches(Object projectIdOrPath) throws GitLabApiException {
delete(Response.Status.NO_CONTENT, null, "projects",
getProjectIdOrPath(projectIdOrPath), "repository", "merged_branches");
}
}
|
package org.jtrfp.trcl;
import java.awt.Color;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.math3.geometry.euclidean.threed.Vector3D;
import org.jtrfp.trcl.core.TR;
import org.jtrfp.trcl.core.TextureDescription;
import org.jtrfp.trcl.file.LVLFile;
import org.jtrfp.trcl.file.TDFFile;
import org.jtrfp.trcl.flow.LoadingProgressReporter;
import org.jtrfp.trcl.img.vq.ColorPaletteVectorList;
import org.jtrfp.trcl.obj.DEFObject;
import org.jtrfp.trcl.obj.EnemyIntro;
import org.jtrfp.trcl.obj.ObjectSystem;
import org.jtrfp.trcl.obj.PositionedRenderable;
public class OverworldSystem extends RenderableSpacePartitioningGrid {
private CloudSystem cloudSystem;
private TextureMesh textureMesh;
private InterpolatingAltitudeMap altitudeMap;
private Color fogColor = Color.black;
private final ArrayList<DEFObject> defList = new ArrayList<DEFObject>();
private RenderableSpacePartitioningGrid terrainMirror = new RenderableSpacePartitioningGrid(
this) {
};
private boolean chamberMode = false;
private boolean tunnelMode = false;
private final TR tr;
private final LoadingProgressReporter terrainReporter, cloudReporter, objectReporter;
private ObjectSystem objectSystem;
public OverworldSystem(World w, final LoadingProgressReporter progressReporter) {
super(w);
this.tr = w.getTr();
final LoadingProgressReporter []reporters = progressReporter.generateSubReporters(256);
terrainReporter = reporters[0];
cloudReporter = reporters[1];
objectReporter = reporters[2];
}
public void loadLevel(final LVLFile lvl, final TDFFile tdf){
try {
final World w = tr.getWorld();
Color[] globalPalette = tr.getResourceManager().getPalette(lvl.getGlobalPaletteFile());
TextureDescription[] texturePalette = tr
.getResourceManager().getTextures(
lvl.getLevelTextureListFile(), new ColorPaletteVectorList(globalPalette),
tr.gpu.get().getGl(),true);
System.out.println("Loading height map...");
altitudeMap = new InterpolatingAltitudeMap(tr.getResourceManager()
.getRAWAltitude(lvl.getHeightMapOrTunnelFile()));
tr.setAltitudeMap(altitudeMap);
System.out.println("... Done");
textureMesh = tr.getResourceManager().getTerrainTextureMesh(
lvl.getTexturePlacementFile(), texturePalette);
// Terrain
System.out.println("Building terrain...");
boolean flatShadedTerrain = lvl.getHeightMapOrTunnelFile()
.toUpperCase().contains("BORG");
TerrainSystem terrainSystem = new TerrainSystem(altitudeMap, textureMesh,
TR.mapSquareSize, this, terrainMirror, tr, tdf,
flatShadedTerrain, terrainReporter);
System.out.println("...Done.");
// Clouds
System.out.println("Setting up sky...");
if (!lvl.getCloudTextureFile().contentEquals("stars.vox")) {
cloudSystem = new CloudSystem(this, tr, this, lvl,
TR.mapSquareSize * 8,
(int) (TR.mapWidth / (TR.mapSquareSize * 8)),
w.sizeY / 3.5, cloudReporter);
}
System.out.println("...Done.");
// Objects
System.out.println("Setting up objects...");
objectSystem = new ObjectSystem(this, w, lvl, defList,
null, Vector3D.ZERO, objectReporter);
objectSystem.activate();
terrainSystem.activate();
System.out.println("...Done.");
// Tunnel activators
} catch (Exception e) {
e.printStackTrace();
}
// terrainMirror.deactivate();//TODO: Uncomment
}// end constructor
@Override
public void activate(){
tr.getWorld().setFogColor(getFogColor());
super.activate();
}
public Color getFogColor() {
return fogColor;
}
public void setFogColor(Color c) {
fogColor = c;
if (fogColor == null)
throw new NullPointerException("Passed color is intolerably null.");
}
public List<DEFObject> getDefList() {
return defList;
}
public SpacePartitioningGrid<PositionedRenderable> getTerrainMirror() {
return terrainMirror;
}
public void setChamberMode(boolean mirrorTerrain) {
tr.getReporter().report("org.jtrfp.OverworldSystem.isInChamber?",
"" + mirrorTerrain);
chamberMode = mirrorTerrain;
final CloudSystem cs = getCloudSystem();
if (mirrorTerrain) {
this.getTerrainMirror().activate();
if (cs != null)
cs.deactivate();
} else {
this.getTerrainMirror().deactivate();
if (cs != null)
cs.activate();
}
}// end chamberMode
private CloudSystem getCloudSystem() {
return cloudSystem;
}
/**
* @return the chamberMode
*/
public boolean isChamberMode() {
return chamberMode;
}
/**
* @return the tunnelMode
*/
public boolean isTunnelMode() {
return tunnelMode;
}
/**
* @param tunnelMode
* the tunnelMode to set
*/
public void setTunnelMode(boolean tunnelMode) {
this.tunnelMode = tunnelMode;
}
/**
* @return the objectSystem
*/
public ObjectSystem getObjectSystem() {
return objectSystem;
}
}// end OverworldSystem
|
package org.jtrfp.trcl.obj;
import java.lang.ref.WeakReference;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.IntBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import org.apache.commons.math3.exception.MathArithmeticException;
import org.apache.commons.math3.geometry.euclidean.threed.Vector3D;
import org.jtrfp.trcl.ObjectDefinitionWindow;
import org.jtrfp.trcl.PrimitiveList;
import org.jtrfp.trcl.SpacePartitioningGrid;
import org.jtrfp.trcl.Submitter;
import org.jtrfp.trcl.beh.Behavior;
import org.jtrfp.trcl.beh.BehaviorNotFoundException;
import org.jtrfp.trcl.beh.CollisionBehavior;
import org.jtrfp.trcl.beh.NullBehavior;
import org.jtrfp.trcl.core.TR;
import org.jtrfp.trcl.gpu.GPU;
import org.jtrfp.trcl.gpu.Model;
import org.jtrfp.trcl.math.Mat4x4;
import org.jtrfp.trcl.math.Vect3D;
public class WorldObject implements PositionedRenderable {
public static final boolean LOOP = true;
private double[] heading = new double[] { 0, 0, 1 };
private double[] top = new double[] { 0, 1, 0 };
protected double[] position = new double[3];
protected double[] modelOffset= new double[3];
private final double[]positionWithOffset
= new double[3];
private boolean needToRecalcMatrix=true;
private final TR tr;
private boolean visible = true;
private Model model;
private List<PositionedRenderable>lastContainingList;
private int[] triangleObjectDefinitions;
private int[] transparentTriangleObjectDefinitions;
protected Integer matrixID;
private ByteBuffer opaqueObjectDefinitionAddressesInVec4 = ByteBuffer
.allocate(0);// defaults to empty
private ByteBuffer transparentObjectDefinitionAddressesInVec4 = ByteBuffer
.allocate(0);// defaults to empty
private WeakReference<SpacePartitioningGrid> containingGrid;
private ArrayList<Behavior> inactiveBehaviors = new ArrayList<Behavior>();
private ArrayList<CollisionBehavior>collisionBehaviors = new ArrayList<CollisionBehavior>();
private ArrayList<Behavior> tickBehaviors = new ArrayList<Behavior>();
private final NullBehavior nullBehavior;
private boolean active = true;
private byte renderFlags=0;
private boolean immuneToOpaqueDepthTest = false;
protected final double[] aX = new double[3];
protected final double[] aY = new double[3];
protected final double[] aZ = new double[3];
protected final double[] rotTransM = new double[16];
protected final double[] camM = new double[16];
protected final double[] rMd = new double[16];
protected final double[] tMd = new double[16];
protected double[] cMd = new double[16];
private boolean respondToTick = true;
public WorldObject(TR tr) {
this.nullBehavior = new NullBehavior(this);
this.tr = tr;
matrixID = tr.matrixWindow.get().create();
// Matrix constants setup
rMd[15] = 1;
tMd[0] = 1;
tMd[5] = 1;
tMd[10] = 1;
tMd[15] = 1;
}
public WorldObject(TR tr, Model m) {
this(tr);
setModel(m);
}// end constructor
void proposeCollision(WorldObject other) {
for (int i = 0; i < collisionBehaviors.size(); i++) {
collisionBehaviors.get(i).proposeCollision(other);
}// end for(collisionBehaviors)
}// end proposeCollision(...)
public boolean isCollideable(){
return !collisionBehaviors.isEmpty();
}
public <T extends Behavior> T addBehavior(T ob) {
if (ob.isEnabled()) {
if (ob instanceof CollisionBehavior)
collisionBehaviors.add((CollisionBehavior) ob);
tickBehaviors.add(ob);
} else {
inactiveBehaviors.add(ob);
}
ob.setParent(this);
return ob;
}
protected boolean recalcMatrixWithEachFrame(){
return false;
}
public <T> T probeForBehavior(Class<T> bC) {
if (bC.isAssignableFrom(CollisionBehavior.class)) {
for (int i = 0; i < collisionBehaviors.size(); i++) {
if (bC.isAssignableFrom(collisionBehaviors.get(i).getClass())) {
return (T) collisionBehaviors.get(i);
}
}// end if(instanceof)
}// emd if(isAssignableFrom(CollisionBehavior.class))
for (int i = 0; i < inactiveBehaviors.size(); i++) {
if (bC.isAssignableFrom(inactiveBehaviors.get(i).getClass())) {
return (T) inactiveBehaviors.get(i);
}
}// end if(instanceof)
for (int i = 0; i < tickBehaviors.size(); i++) {
if (bC.isAssignableFrom(tickBehaviors.get(i).getClass())) {
return (T) tickBehaviors.get(i);
}
}// end if(instanceof)
throw new BehaviorNotFoundException("Cannot find behavior of type "
+ bC.getName() + " in behavior sandwich owned by "
+ this.toString());
}// end probeForBehavior
public <T> void probeForBehaviors(Submitter<T> sub, Class<T> type) {
synchronized(collisionBehaviors){
if (type.isAssignableFrom(CollisionBehavior.class)) {
for (int i = 0; i < collisionBehaviors.size(); i++) {
if (type.isAssignableFrom(collisionBehaviors.get(i).getClass())) {
sub.submit((T) collisionBehaviors.get(i));
}
}// end if(instanceof)
}// end isAssignableFrom(CollisionBehavior.class)
}synchronized(inactiveBehaviors){
for (int i = 0; i < inactiveBehaviors.size(); i++) {
if (type.isAssignableFrom(inactiveBehaviors.get(i).getClass()))
sub.submit((T) inactiveBehaviors.get(i));
}// end if(instanceof)
}synchronized(tickBehaviors){
for (int i = 0; i < tickBehaviors.size(); i++) {
if (type.isAssignableFrom(tickBehaviors.get(i).getClass()))
sub.submit((T) tickBehaviors.get(i));
}// end for (tickBehaviors)
}//end sync(tickBehaviors)
}// end probeForBehaviors(...)
public void tick(long time) {
if(!respondToTick)return;
synchronized(tickBehaviors){
for (int i = 0; i < tickBehaviors.size(); i++)
tickBehaviors.get(i).tick(time);
}//end sync(tickBehaviors)
}// end tick(...)
private final int [] emptyIntArray = new int[0];
public void setModel(Model m) {
if (m == null)
throw new RuntimeException("Passed model cannot be null.");
model = m;
int numObjDefs, sizeInVerts;
if (m.getTriangleList() == null)
triangleObjectDefinitions = emptyIntArray;
else {
sizeInVerts = m.getTriangleList().getTotalSizeInGPUVertices();
numObjDefs = sizeInVerts / GPU.GPU_VERTICES_PER_BLOCK;
if (sizeInVerts % GPU.GPU_VERTICES_PER_BLOCK != 0)
numObjDefs++;
triangleObjectDefinitions = new int[numObjDefs];
for (int i = 0; i < numObjDefs; i++) {
triangleObjectDefinitions[i] = tr.objectDefinitionWindow.get()
.create();
}
}
if (m.getTransparentTriangleList() == null)
transparentTriangleObjectDefinitions = emptyIntArray;
else {
sizeInVerts = m.getTransparentTriangleList()
.getTotalSizeInGPUVertices();
numObjDefs = sizeInVerts / GPU.GPU_VERTICES_PER_BLOCK;
if (sizeInVerts % GPU.GPU_VERTICES_PER_BLOCK != 0)
numObjDefs++;
transparentTriangleObjectDefinitions = new int[numObjDefs];
for (int i = 0; i < numObjDefs; i++) {
transparentTriangleObjectDefinitions[i] = tr
.objectDefinitionWindow.get().create();
}
}
initializeObjectDefinitions();
}// end setModel(...)
public synchronized void setDirection(ObjectDirection dir) {
if (dir.getHeading().getNorm() == 0 || dir.getTop().getNorm() == 0) {
System.err
.println("Warning: Rejecting zero-norm for object direction. "
+ dir);
new Exception().printStackTrace();
return;
}
setHeading(dir.getHeading());
setTop(dir.getTop());
}
@Override
public String toString() {
final String modelDebugName;
if(model!=null)modelDebugName=model.getDebugName();
else modelDebugName="[null model]";
return "WorldObject Model=" + modelDebugName + " pos="
+ this.getPosition() + " class=" + getClass().getName();
}
public final void initializeObjectDefinitions() {
if (model == null)
throw new NullPointerException(
"Model is null. Did you forget to set it?");
final ArrayList<Integer> opaqueIndicesList = new ArrayList<Integer>();
final ArrayList<Integer> transparentIndicesList = new ArrayList<Integer>();
tr.getThreadManager().submitToGPUMemAccess(new Callable<Void>(){
@Override
public Void call() throws Exception {
processPrimitiveList(model.getTriangleList(),
triangleObjectDefinitions, opaqueIndicesList);
processPrimitiveList(model.getTransparentTriangleList(),
transparentTriangleObjectDefinitions, transparentIndicesList);
return null;
}}).get();//TODO: Make non-blocking
ByteOrder order = getTr().gpu.get().getByteOrder();
opaqueObjectDefinitionAddressesInVec4 = ByteBuffer.allocateDirect(
opaqueIndicesList.size() * 4).order(order);// 4 bytes per int
transparentObjectDefinitionAddressesInVec4 = ByteBuffer.allocateDirect(
transparentIndicesList.size() * 4).order(order);
IntBuffer trans = transparentObjectDefinitionAddressesInVec4
.asIntBuffer(), opaque = opaqueObjectDefinitionAddressesInVec4
.asIntBuffer();
for (Integer elm : transparentIndicesList) {
trans.put(elm);
}
for (Integer elm : opaqueIndicesList) {
opaque.put(elm);
}
}// end initializeObjectDefinitions()
private void processPrimitiveList(PrimitiveList<?> primitiveList,
int[] objectDefinitions, ArrayList<Integer> indicesList) {
if (primitiveList == null)
return; // Nothing to do, no primitives here
//int vec4sRemaining = primitiveList.getTotalSizeInVec4s();
final int gpuVerticesPerElement = primitiveList.getGPUVerticesPerElement();
final int elementsPerBlock = GPU.GPU_VERTICES_PER_BLOCK / gpuVerticesPerElement;
int gpuVerticesRemaining = primitiveList.getNumElements()*gpuVerticesPerElement;
// For each of the allocated-but-not-yet-initialized object definitions.
final ObjectDefinitionWindow odw = tr.objectDefinitionWindow.get();
int odCounter=0;
final int memoryWindowIndicesPerElement = primitiveList.getNumMemoryWindowIndicesPerElement();
for (final int index : objectDefinitions) {
final int vertexOffsetVec4s=primitiveList.getMemoryWindow().getPhysicalAddressInBytes(odCounter*elementsPerBlock*memoryWindowIndicesPerElement)
/GPU.BYTES_PER_VEC4;
final int matrixOffsetVec4s=tr.matrixWindow.get()
.getPhysicalAddressInBytes(matrixID)
/ GPU.BYTES_PER_VEC4;
odw.matrixOffset.set(index,matrixOffsetVec4s);
odw.vertexOffset.set(index,vertexOffsetVec4s);
odw.mode.set(index, (byte)(primitiveList.getPrimitiveRenderMode() | (renderFlags << 4)&0xF0));
odw.modelScale.set(index, (byte) primitiveList.getPackedScale());
if (gpuVerticesRemaining >= GPU.GPU_VERTICES_PER_BLOCK) {
odw.numVertices.set(index,
(byte) GPU.GPU_VERTICES_PER_BLOCK);
} else if (gpuVerticesRemaining > 0) {
odw.numVertices.set(index,
(byte) (gpuVerticesRemaining));
} else {
throw new RuntimeException("Ran out of vec4s.");
}
gpuVerticesRemaining -= GPU.GPU_VERTICES_PER_BLOCK;
indicesList.add(odw.getPhysicalAddressInBytes(index)
/ GPU.BYTES_PER_VEC4);
odCounter++;
}// end for(ObjectDefinition)
}// end processPrimitiveList(...)
public synchronized final void updateStateToGPU() {
attemptLoop();
if(needToRecalcMatrix){
recalculateTransRotMBuffer();
needToRecalcMatrix=recalcMatrixWithEachFrame();
}
if(model!=null)model.proposeAnimationUpdate();
}//end updateStateToGPU()
protected void attemptLoop(){
if (LOOP) {
final Vector3D camPos = tr.renderer.get().getCamera().getCameraPosition();
double delta = position[0]
- camPos.getX();
if (delta > TR.mapWidth / 2.) {
position[0] -= TR.mapWidth;
needToRecalcMatrix=true;
} else if (delta < -TR.mapWidth / 2.) {
position[0] += TR.mapWidth;
needToRecalcMatrix=true;
}
delta = position[1]
- camPos.getY();
if (delta > TR.mapWidth / 2.) {
position[1] -= TR.mapWidth;
needToRecalcMatrix=true;
} else if (delta < -TR.mapWidth / 2.) {
position[1] += TR.mapWidth;
needToRecalcMatrix=true;
}
delta = position[2]
- camPos.getZ();
if (delta > TR.mapWidth / 2.) {
position[2] -= TR.mapWidth;
needToRecalcMatrix=true;
} else if (delta < -TR.mapWidth / 2.) {
position[2] += TR.mapWidth;
needToRecalcMatrix=true;
}
}//end if(LOOP)
}//end attemptLoop()
protected void recalculateTransRotMBuffer() {
try {
Vect3D.normalize(heading, aZ);
Vect3D.cross(top, aZ, aX);
Vect3D.cross(aZ, aX, aY);
rMd[0] = aX[0];
rMd[1] = aY[0];
rMd[2] = aZ[0];
rMd[4] = aX[1];
rMd[5] = aY[1];
rMd[6] = aZ[1];
rMd[8] = aX[2];
rMd[9] = aY[2];
rMd[10] = aZ[2];
tMd[3] = position[0]+modelOffset[0];
tMd[7] = position[1]+modelOffset[1];
tMd[11] = position[2]+modelOffset[2];
if (translate()) {
Mat4x4.mul(tMd, rMd, rotTransM);
} else {
System.arraycopy(rMd, 0, rotTransM, 0, 16);
}
tr.matrixWindow.get().setTransposed(rotTransM, matrixID, scratchMatrixArray);//New version
} catch (MathArithmeticException e) {
}// Don't crash.
}// end recalculateTransRotMBuffer()
protected final double [] scratchMatrixArray = new double[16];
protected boolean translate() {
return true;
}
/**
* @return the visible
*/
public boolean isVisible() {
return visible;
}
/**
* @param visible
* the visible to set
*/
public void setVisible(boolean visible) {
if(!this.visible && visible){
this.visible = true;
needToRecalcMatrix=true;
tr.threadManager.submitToGPUMemAccess(new Callable<Void>(){
@Override
public Void call() throws Exception {
WorldObject.this.updateStateToGPU();
return null;
}
});
tr.renderer.get().temporarilyMakeImmediatelyVisible(this);
}else this.visible = visible;
}//end setvisible()
/**
* @return the position
*/
public final double[] getPosition() {
return position;
}
/**
* @param position
* the position to set
*/
public WorldObject setPosition(double[] position) {
this.position[0]=position[0];
this.position[1]=position[1];
this.position[2]=position[2];
notifyPositionChange();
return this;
}// end setPosition()
public synchronized WorldObject notifyPositionChange(){
needToRecalcMatrix=true;
synchronized (position) {
final SpacePartitioningGrid<PositionedRenderable>
containingGrid = getContainingGrid();
if(containingGrid==null){//Not in grid
if(lastContainingList!=null){//Removed from grid
synchronized(lastContainingList){
lastContainingList.remove(this);}
lastContainingList=null;
}//end if(lastContainingList!=null)
return this;
}//end if(not in grid)
//Possibly moved from cube-to-cube
final List<PositionedRenderable> newList =
(this instanceof VisibleEverywhere)?
containingGrid.getAlwaysVisibleList():containingGrid.world2List(position[0],position[1],position[2],true);
if(lastContainingList!=newList){//Definitely moved from cube-to-cube
if(lastContainingList!=null){
synchronized(newList){
synchronized(lastContainingList){
lastContainingList.remove(this);
newList.add(this);
}}//end sync(new and last)
}//end (moved)
else synchronized(newList){
newList.add(this);}
lastContainingList=newList;
}//end if(posChange)
}//end sync(position)
return this;
}//end notifyPositionChange()
/**
* @return the heading
*/
public final Vector3D getLookAt() {
return new Vector3D(heading);
}
/**
* @param heading
* the heading to set
*/
public synchronized void setHeading(Vector3D nHeading) {
heading[0] = nHeading.getX();
heading[1] = nHeading.getY();
heading[2] = nHeading.getZ();
needToRecalcMatrix=true;
}
public Vector3D getHeading() {
return new Vector3D(heading);
}
/**
* @return the top
*/
public final Vector3D getTop() {
return new Vector3D(top);
}
/**
* @param top
* the top to set
*/
public synchronized void setTop(Vector3D nTop) {
top[0] = nTop.getX();
top[1] = nTop.getY();
top[2] = nTop.getZ();
needToRecalcMatrix=true;
}
public final ByteBuffer getOpaqueObjectDefinitionAddresses() {
opaqueObjectDefinitionAddressesInVec4.clear();
return opaqueObjectDefinitionAddressesInVec4;
}
public final ByteBuffer getTransparentObjectDefinitionAddresses() {
transparentObjectDefinitionAddressesInVec4.clear();
return transparentObjectDefinitionAddressesInVec4;
}
/**
* @return the tr
*/
public TR getTr() {
return tr;
}
public void destroy() {
if (containingGrid != null){
SpacePartitioningGrid g = getContainingGrid();
if(g!=null)
if(lastContainingList!=null)
synchronized(lastContainingList){
lastContainingList.remove(this);}
}//end if(grid!=null)
containingGrid=null;
// Send it to the land of wind and ghosts.
final double[] pos = getPosition();
pos[0] = Double.NEGATIVE_INFINITY;
pos[1] = Double.NEGATIVE_INFINITY;
pos[2] = Double.NEGATIVE_INFINITY;
notifyPositionChange();
setActive(false);
}
@Override
public void setContainingGrid(SpacePartitioningGrid grid) {
containingGrid = new WeakReference<SpacePartitioningGrid>(grid);
notifyPositionChange();
}
public SpacePartitioningGrid<PositionedRenderable> getContainingGrid() {
try{return containingGrid.get();}
catch(NullPointerException e){return null;}
}
public Model getModel() {
return model;
}
public Behavior getBehavior() {
return nullBehavior;
}
/**
* @return the active
*/
public boolean isActive() {
return active;
}
/**
* @param active
* the active to set
*/
public void setActive(boolean active) {
if(!this.active && active && isVisible()){
this.active=true;
needToRecalcMatrix=true;
tr.renderer.get().temporarilyMakeImmediatelyVisible(this);
tr.threadManager.submitToGPUMemAccess(new Callable<Void>(){
@Override
public Void call() throws Exception {
WorldObject.this.updateStateToGPU();
return null;
}
});
}
this.active = active;
}//end setActive(...)
public synchronized void movePositionBy(Vector3D delta) {
position[0] += delta.getX();
position[1] += delta.getY();
position[2] += delta.getZ();
notifyPositionChange();
}
public synchronized void setPosition(double x, double y, double z) {
position[0] = x;
position[1] = y;
position[2] = z;
notifyPositionChange();
}
public double[] getHeadingArray() {
return heading;
}
public double[] getTopArray() {
return top;
}
public void enableBehavior(Behavior behavior) {
if (!inactiveBehaviors.contains(behavior)) {
throw new RuntimeException(
"Tried to enabled an unregistered behavior.");
}
if (behavior instanceof CollisionBehavior) {
if (!collisionBehaviors.contains(behavior)
&& behavior instanceof CollisionBehavior) {
collisionBehaviors.add((CollisionBehavior) behavior);
}
}
if (!tickBehaviors.contains(behavior)) {
tickBehaviors.add(behavior);
}
}// end enableBehavior(...)
public void disableBehavior(Behavior behavior) {
if (!inactiveBehaviors.contains(behavior))
synchronized(inactiveBehaviors){
inactiveBehaviors.add(behavior);
}
if (behavior instanceof CollisionBehavior)
synchronized(collisionBehaviors){
collisionBehaviors.remove(behavior);
}
synchronized(tickBehaviors){
tickBehaviors.remove(behavior);
}
}//end disableBehavior(...)
/**
* @return the renderFlags
*/
public int getRenderFlags() {
return renderFlags;
}
/**
* @param renderFlags the renderFlags to set
*/
public void setRenderFlags(byte renderFlags) {
this.renderFlags = renderFlags;
}
/**
* @return the respondToTick
*/
public boolean isRespondToTick() {
return respondToTick;
}
/**
* @param respondToTick the respondToTick to set
*/
public void setRespondToTick(boolean respondToTick) {
this.respondToTick = respondToTick;
}
@Override
public void finalize() throws Throwable{
System.out.println("WorldObject.finalize()");
if(matrixID!=null)
tr.matrixWindow.get().free(matrixID);
if(transparentTriangleObjectDefinitions!=null)
for(int def:transparentTriangleObjectDefinitions)
tr.objectDefinitionWindow.get().free(def);
if(triangleObjectDefinitions!=null)
for(int def:triangleObjectDefinitions)
tr.objectDefinitionWindow.get().free(def);
super.finalize();
}//end finalize()
/**
* @param modelOffset the modelOffset to set
*/
public void setModelOffset(double x, double y, double z) {
modelOffset[0]=x;
modelOffset[1]=y;
modelOffset[2]=z;
}
public double[] getPositionWithOffset() {
positionWithOffset[0]=position[0]+modelOffset[0];
positionWithOffset[1]=position[1]+modelOffset[1];
positionWithOffset[2]=position[2]+modelOffset[2];
return positionWithOffset;
}
public boolean isImmuneToOpaqueDepthTest() {
return immuneToOpaqueDepthTest;
}
/**
* @param immuneToDepthTest the immuneToDepthTest to set
*/
public WorldObject setImmuneToOpaqueDepthTest(boolean immuneToDepthTest) {
this.immuneToOpaqueDepthTest = immuneToDepthTest;
return this;
}
}// end WorldObject
|
package org.lantern;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicReference;
import javax.security.auth.login.CredentialException;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.SystemUtils;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.SmackConfiguration;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.IQTypeFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.packet.Presence.Type;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.lantern.event.ClosedBetaEvent;
import org.lantern.event.Events;
import org.lantern.event.GoogleTalkStateEvent;
import org.lantern.event.ResetEvent;
import org.lantern.event.UpdateEvent;
import org.lantern.event.UpdatePresenceEvent;
import org.lantern.kscope.KscopeAdHandler;
import org.lantern.kscope.LanternKscopeAdvertisement;
import org.lantern.proxy.GiveModeProxy;
import org.lantern.proxy.UdtServerFiveTupleListener;
import org.lantern.state.ClientFriend;
import org.lantern.state.Connectivity;
import org.lantern.state.Friend;
import org.lantern.state.FriendsHandler;
import org.lantern.state.Model;
import org.lantern.state.ModelUtils;
import org.lantern.state.Notification.MessageType;
import org.lantern.state.SyncPath;
import org.lantern.util.Threads;
import org.lastbamboo.common.ice.MappedServerSocket;
import org.lastbamboo.common.p2p.P2PConnectionEvent;
import org.lastbamboo.common.p2p.P2PConnectionListener;
import org.lastbamboo.common.p2p.P2PConstants;
import org.lastbamboo.common.portmapping.NatPmpService;
import org.lastbamboo.common.portmapping.UpnpService;
import org.lastbamboo.common.stun.client.StunServerRepository;
import org.littleshoot.commom.xmpp.XmppCredentials;
import org.littleshoot.commom.xmpp.XmppP2PClient;
import org.littleshoot.commom.xmpp.XmppUtils;
import org.littleshoot.p2p.P2PEndpoints;
import org.littleshoot.util.FiveTuple;
import org.littleshoot.util.SessionSocketListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.eventbus.Subscribe;
import com.google.inject.Inject;
import com.google.inject.Singleton;
/**
* Handles logging in to the XMPP server and processing trusted users through
* the roster.
*/
@Singleton
public class DefaultXmppHandler implements XmppHandler {
private static final Logger LOG =
LoggerFactory.getLogger(DefaultXmppHandler.class);
private final AtomicReference<XmppP2PClient<FiveTuple>> client =
new AtomicReference<XmppP2PClient<FiveTuple>>();
static {
SmackConfiguration.setPacketReplyTimeout(60 * 1000);
}
private volatile long lastInfoMessageScheduled = 0L;
private final MessageListener typedListener = new MessageListener() {
@Override
public void processMessage(final Chat ch, final Message msg) {
// Note the Chat will always be null here. We try to avoid using
// actual Chat instances due to Smack's strange and inconsistent
// behavior with message listeners on chats.
final String from = msg.getFrom();
LOG.debug("Got chat participant: {} with message:\n {}", from,
msg.toXML());
if (msg.getType() == org.jivesoftware.smack.packet.Message.Type.error) {
LOG.warn("Received error message!! {}", msg.toXML());
return;
}
if (LanternUtils.isLanternHub(from)) {
processLanternHubMessage(msg);
}
final Integer type =
(Integer) msg.getProperty(P2PConstants.MESSAGE_TYPE);
if (type != null) {
LOG.debug("Processing typed message");
processTypedMessage(msg, type);
}
}
};
private String lastJson = "";
private GoogleTalkState state;
private final NatPmpService natPmpService;
private final UpnpService upnpService;
private ClosedBetaEvent closedBetaEvent;
private final Object closedBetaLock = new Object();
private MappedServerSocket mappedServer;
private final Timer timer;
private final ClientStats stats;
private final LanternKeyStoreManager keyStoreManager;
private final LanternSocketsUtil socketsUtil;
private final LanternXmppUtil xmppUtil;
private final Model model;
private volatile boolean started;
private final ModelUtils modelUtils;
private final org.lantern.Roster roster;
private final ProxyTracker proxyTracker;
private final KscopeAdHandler kscopeAdHandler;
private TimerTask reconnectIfNoPong;
/**
* The XMPP message id that we are waiting for a pong on
*/
private String waitingForPong;
private long pingTimeout = 15 * 1000;
protected XMPPConnection previousConnection;
private final ExecutorService xmppProcessors =
Threads.newCachedThreadPool("Smack-XMPP-Message-Processing-");
private final UdtServerFiveTupleListener udtFiveTupleListener;
private final FriendsHandler friendsHandler;
private final GiveModeProxy giveModeProxy;
/**
* Creates a new XMPP handler.
*/
@Inject
public DefaultXmppHandler(final Model model,
final Timer updateTimer, final ClientStats stats,
final LanternKeyStoreManager keyStoreManager,
final LanternSocketsUtil socketsUtil,
final LanternXmppUtil xmppUtil,
final ModelUtils modelUtils,
final org.lantern.Roster roster,
final ProxyTracker proxyTracker,
final KscopeAdHandler kscopeAdHandler,
final NatPmpService natPmpService,
final UpnpService upnpService,
final UdtServerFiveTupleListener udtFiveTupleListener,
final FriendsHandler friendsHandler,
final GiveModeProxy giveModeProxy) {
this.model = model;
this.timer = updateTimer;
this.stats = stats;
this.keyStoreManager = keyStoreManager;
this.socketsUtil = socketsUtil;
this.xmppUtil = xmppUtil;
this.modelUtils = modelUtils;
this.roster = roster;
this.proxyTracker = proxyTracker;
this.kscopeAdHandler = kscopeAdHandler;
this.natPmpService = natPmpService;
this.upnpService = upnpService;
this.udtFiveTupleListener = udtFiveTupleListener;
this.friendsHandler = friendsHandler;
this.giveModeProxy = giveModeProxy;
Events.register(this);
//setupJmx();
}
@Override
public MappedServerSocket getMappedServer() {
return mappedServer;
}
@Override
public void start() {
this.modelUtils.loadClientSecrets();
XmppUtils.setGlobalConfig(this.xmppUtil.xmppConfig());
XmppUtils.setGlobalProxyConfig(this.xmppUtil.xmppProxyConfig());
this.mappedServer = new LanternMappedTcpAnswererServer(natPmpService,
upnpService, new InetSocketAddress(this.model.getSettings().getServerPort()));
this.started = true;
}
@Override
public void stop() {
LOG.debug("Stopping XMPP handler...");
disconnect();
if (upnpService != null) {
upnpService.shutdown();
}
if (natPmpService != null) {
natPmpService.shutdown();
}
LOG.debug("Stopped XMPP handler...");
}
@Subscribe
public void onAuthStatus(final GoogleTalkStateEvent ase) {
this.state = ase.getState();
switch (state) {
case connected:
// We wait until we're logged in before creating our roster.
final XmppP2PClient<FiveTuple> cl = client.get();
if (cl == null) {
LOG.error("Null client for instance: "+hashCode());
return;
}
this.roster.onRoster(this);
break;
case notConnected:
this.roster.reset();
break;
case connecting:
break;
case LOGIN_FAILED:
this.roster.reset();
break;
}
}
@Subscribe
public void onConnectivityChanged(final ConnectivityChangedEvent e) {
if (!e.isConnected()) {
// send a ping message to determine if we need to reconnect; failed
// STUN connectivity is not necessarily a death sentence for the
// XMPP connection.
// If the ping fails, then XmppP2PClient will retry that connection
// in a loop.
ping();
return;
}
LOG.info("Connected to internet: {}", e);
LOG.info("Logged in? {}", this.isLoggedIn());
XmppP2PClient<FiveTuple> xmpp = this.client.get();
if (xmpp == null) {
LOG.debug("No client?");
return; //this is probably at startup
}
final XMPPConnection conn = xmpp.getXmppConnection();
if (e.isIpChanged()) {
//definitely need to reconnect here
reconnect();
} else {
if (conn == null || !conn.isConnected()) {
//definitely need to reconnect here
reconnect();
} else {
ping();
}
}
}
private void ping() {
//if we are already pinging, cancel the existing ping
//and retry
if (reconnectIfNoPong != null) {
reconnectIfNoPong.cancel();
}
XmppP2PClient<FiveTuple> client = this.client.get();
if (client == null) {
//no connection yet, so we'll just return; the connection
//will be established when we can
return;
}
XMPPConnection connection = client.getXmppConnection();
IQ ping = new IQ() {
@Override
public String getChildElementXML() {
return "<ping xmlns='urn:xmpp:ping'/>";
}
};
waitingForPong = ping.getPacketID();
//set up timer to reconnect if we don't hear a pong
reconnectIfNoPong = new Reconnector();
timer.schedule(reconnectIfNoPong, getPingTimeout());
//and send the ping
connection.sendPacket(ping);
}
/**
* How long we wait,
* @return
*/
public long getPingTimeout() {
return pingTimeout;
}
public void setPingTimeout(long pingTimeout) {
this.pingTimeout = pingTimeout;
}
/**
* This will be cancelled if a pong is received,
* indicating that we have already successfully
* reconnected
*/
private class Reconnector extends TimerTask {
@Override
public void run() {
reconnect();
}
}
@Override
public synchronized void connect() throws IOException, CredentialException,
NotInClosedBetaException {
if (!this.started) {
LOG.warn("Can't connect when not started!!");
throw new Error("Can't connect when not started!!");
}
if (!this.modelUtils.isConfigured()) {
if (this.model.getSettings().isUiEnabled()) {
LOG.debug("Not connecting when not configured and UI enabled");
return;
}
}
if (isLoggedIn()) {
LOG.warn("Already logged in!! Not connecting");
return;
}
LOG.debug("Connecting to XMPP servers...");
if (this.modelUtils.isOauthConfigured()) {
connectViaOAuth2();
} else {
throw new Error("Oauth not configured properly?");
}
}
private void connectViaOAuth2() throws IOException,
CredentialException, NotInClosedBetaException {
final XmppCredentials credentials =
this.modelUtils.newGoogleOauthCreds(getResource());
LOG.debug("Logging in with credentials: {}", credentials);
connect(credentials);
}
@Override
public void connect(final String email, final String pass)
throws IOException, CredentialException, NotInClosedBetaException {
//connect(new PasswordCredentials(email, pass, getResource()));
}
private String getResource() {
return LanternConstants.UNCENSORED_ID;
}
/** listen to responses for XMPP pings, and if we get any,
cancel pending reconnects
*/
private class PingListener implements PacketListener {
@Override
public void processPacket(Packet packet) {
IQ iq = (IQ) packet;
if (iq.getPacketID().equals(waitingForPong)) {
LOG.debug("Got pong, cancelling pending reconnect");
reconnectIfNoPong.cancel();
}
}
}
private class DefaultP2PConnectionListener implements P2PConnectionListener {
@Override
public void onConnectivityEvent(final P2PConnectionEvent event) {
LOG.debug("Got connectivity event: {}", event);
Events.asyncEventBus().post(event);
XMPPConnection connection = client.get().getXmppConnection();
if (connection == previousConnection) {
//only add packet listener once
return;
}
previousConnection = connection;
connection.addPacketListener(new PingListener(),
new IQTypeFilter(org.jivesoftware.smack.packet.IQ.Type.RESULT));
}
}
/**
* Connect to Google Talk's XMPP servers using the supplied XmppCredentials
*/
private void connect(final XmppCredentials credentials)
throws IOException, CredentialException, NotInClosedBetaException {
LOG.debug("Connecting to XMPP servers with credentials...");
this.closedBetaEvent = null;
// This address doesn't appear to be used anywhere, setting to null
final InetSocketAddress plainTextProxyRelayAddress = null;
if (this.client.get() == null) {
makeClient(plainTextProxyRelayAddress);
} else {
LOG.debug("Using existing client for xmpp handler: "+hashCode());
}
// This is a global, backup listener added to the client. We might
// get notifications of messages twice in some cases, but that's
// better than the alternative of sometimes not being notified
// at all.
LOG.debug("Adding message listener...");
this.client.get().addMessageListener(typedListener);
Events.eventBus().post(
new GoogleTalkStateEvent("", GoogleTalkState.connecting));
login(credentials);
// Note we don't consider ourselves connected in get mode until we
// actually get proxies to work with.
final XMPPConnection connection = this.client.get().getXmppConnection();
getStunServers(connection);
// Make sure all connections between us and the server are stored
// OTR.
modelUtils.syncConnectingStatus("Activating Google Talk pseudo-OTR...");
LanternUtils.activateOtr(connection);
LOG.debug("Connection ID: {}", connection.getConnectionID());
modelUtils.syncConnectingStatus("Waiting for message from Lantern...");
DefaultPacketListener listener = new DefaultPacketListener();
connection.addPacketListener(listener, listener);
gTalkSharedStatus();
updatePresence();
waitForClosedBetaStatus(credentials.getUsername());
modelUtils.syncConnectingStatus("Lantern message received...");
}
private void makeClient(final InetSocketAddress plainTextProxyRelayAddress)
throws IOException {
final SessionSocketListener sessionListener = new SessionSocketListener() {
@Override
public void reconnected() {
// We need to send a new presence message each time we
// reconnect to the XMPP server, as otherwise peers won't
// know we're available and we won't get data from the bot.
updatePresence();
}
@Override
public void onSocket(String arg0, Socket arg1) throws IOException {
}
};
client.set(makeXmppP2PHttpClient(plainTextProxyRelayAddress,
sessionListener));
LOG.debug("Set client for xmpp handler: "+hashCode());
client.get().addConnectionListener(new DefaultP2PConnectionListener());
}
private void getStunServers(final XMPPConnection connection) {
modelUtils.syncConnectingStatus("Gathering servers...");
final Collection<InetSocketAddress> googleStunServers =
XmppUtils.googleStunServers(connection);
StunServerRepository.setStunServers(googleStunServers);
this.model.getSettings().setStunServers(
new HashSet<String>(toStringServers(googleStunServers)));
}
private void login(final XmppCredentials credentials) throws IOException,
CredentialException {
try {
this.client.get().login(credentials);
modelUtils.syncConnectingStatus("Logged in to Google Talk...");
// Preemptively create our key.
this.keyStoreManager.getBase64Cert(getJid());
LOG.debug("Sending connected event");
Events.eventBus().post(
new GoogleTalkStateEvent(getJid(), GoogleTalkState.connected));
} catch (final IOException e) {
// Note that the XMPP library will internally attempt to connect
// to our backup proxy if it can.
handleConnectionFailure();
throw e;
} catch (final IllegalStateException e) {
handleConnectionFailure();
throw e;
} catch (final CredentialException e) {
handleConnectionFailure();
throw e;
}
}
private XmppP2PClient<FiveTuple> makeXmppP2PHttpClient(
final InetSocketAddress plainTextProxyRelayAddress,
final SessionSocketListener sessionListener) throws IOException {
return P2PEndpoints.newXmppP2PHttpClient(
"shoot", natPmpService,
this.upnpService, this.mappedServer,
this.socketsUtil.newTlsSocketFactoryJavaCipherSuites(),
this.socketsUtil.newTlsServerSocketFactory(),
plainTextProxyRelayAddress, sessionListener, false,
udtFiveTupleListener);
}
private void handleConnectionFailure() {
Events.eventBus().post(
new GoogleTalkStateEvent("", GoogleTalkState.LOGIN_FAILED));
}
private void waitForClosedBetaStatus(final String email)
throws NotInClosedBetaException {
if (this.modelUtils.isInClosedBeta(email)) {
LOG.debug("Already in closed beta...");
return;
}
// The following is necessary because the call to login needs to either
// succeed or fail for the UI to work properly, but we don't know if
// a user is able to log in until we get an asynchronous XMPP message
// back from the server.
synchronized (this.closedBetaLock) {
if (this.closedBetaEvent == null) {
try {
this.closedBetaLock.wait(80 * 1000);
} catch (final InterruptedException e) {
LOG.info("Interrupted? Maybe on shutdown?", e);
}
}
}
if (this.closedBetaEvent != null) {
if(!this.closedBetaEvent.isInClosedBeta()) {
LOG.debug("Not in closed beta...");
notInClosedBeta("Not in closed beta");
} else {
LOG.debug("Server notified us we're in the closed beta!");
return;
}
} else {
LOG.warn("No closed beta event -- timed out!!");
notInClosedBeta("No closed beta event!!");
}
}
/** The default packet listener automatically
*
*
*/
private class DefaultPacketListener implements PacketListener, PacketFilter {
@Override
public void processPacket(final Packet pack) {
final Runnable runner = new Runnable() {
@Override
public void run() {
final Presence pres = (Presence) pack;
LOG.debug("Processing packet!! {}", pres.toXML());
final String from = pres.getFrom();
LOG.debug("Responding to presence from '{}' and to '{}'",
from, pack.getTo());
final Type type = pres.getType();
// Allow subscription requests from the lantern bot.
if (LanternUtils.isLanternHub(from)) {
handleHubMessage(pack, pres, from, type);
} else {
handlePeerMessage(pack, pres, from, type);
}
}
};
xmppProcessors.execute(runner);
}
private void handlePeerMessage(final Packet pack,
final Presence pres, final String from, final Type type) {
switch (type) {
case available:
peerAvailable(from, pres);
return;
case error:
LOG.warn("Got error packet!! {}", pack.toXML());
return;
case subscribe:
LOG.debug("Adding subscription request from: {}", from);
// Did we originally invite them and they're
// subscribing back? Auto-allow if so.
if (roster.autoAcceptSubscription(from)) {
subscribed(from);
} else {
LOG.debug("We didn't invite " + from);
}
// XMPP requires says that we MUST reply to this request with
// either 'subscribed' or 'unsubscribed'. But we don't even know
// if this is a Lantern request yet, so we can't reply yet. But
// fortunately, we don't have a timeline to respond. We need to
// mark that we owe this user a reply, so that if we do decide to
// friend the user, we can approve the request.
LOG.debug("Adding subscription request");
friendsHandler.addIncomingSubscriptionRequest(pres.getFrom());
break;
case subscribed:
break;
case unavailable:
peerUnavailable(from, pres);
return;
case unsubscribe:
// The user is unsubscribing from us, so we will no longer be
// able to send them messages. However, we still trust them
// so there is no reason to remove them from the friends list.
// If they later resubscribe to us, we don't need to go
// through the whole friending process again.
return;
case unsubscribed:
break;
}
}
/** Allow the hub to subscribe to messages from us. */
private void handleHubMessage(final Packet pack,
final Presence pres, final String from, final Type type) {
if (type == Type.subscribe) {
final Presence packet =
new Presence(Presence.Type.subscribed);
packet.setTo(from);
packet.setFrom(pack.getTo());
XMPPConnection connection = client.get().getXmppConnection();
connection.sendPacket(packet);
} else {
LOG.debug("Non-subscribe packet from hub? {}",
pres.toXML());
}
}
@Override
public boolean accept(final Packet packet) {
if (packet instanceof Presence) {
return true;
} else {
LOG.debug("Not a presence packet: {}", packet.toXML());
}
return false;
}
};
private void notInClosedBeta(final String msg)
throws NotInClosedBetaException {
LOG.debug("Not in closed beta!");
disconnect();
throw new NotInClosedBetaException(msg);
}
private Set<String> toStringServers(
final Collection<InetSocketAddress> googleStunServers) {
final Set<String> strings = new HashSet<String>();
for (final InetSocketAddress isa : googleStunServers) {
// If we get an unresolved name, isa.getAddress() will return
// null. We don't just call getHostName because that will trigger
// a reverse DNS lookup if it is resolved. Finally, getHostString
// is only available in Java 7.
if (!isa.isUnresolved()) {
strings.add(isa.getAddress().getHostAddress()+":"+isa.getPort());
} else {
strings.add(isa.getHostName()+":"+isa.getPort());
}
}
return strings;
}
@Override
public void disconnect() {
LOG.debug("Disconnecting!!");
lastJson = "";
/*
LanternHub.eventBus().post(
new GoogleTalkStateEvent(GoogleTalkState.LOGGING_OUT));
*/
final XmppP2PClient<FiveTuple> cl = this.client.get();
if (cl != null) {
this.client.get().logout();
//this.client.set(null);
}
Events.eventBus().post(
new GoogleTalkStateEvent("", GoogleTalkState.notConnected));
this.proxyTracker.clearPeerProxySet();
this.closedBetaEvent = null;
// This is mostly logged for debugging thorny shutdown issues...
LOG.debug("Finished disconnecting XMPP...");
}
private void processLanternHubMessage(final Message msg) {
Connectivity connectivity = model.getConnectivity();
if (!connectivity.getLanternController()) {
connectivity.setLanternController(true);
Events.sync(SyncPath.CONNECTIVITY_LANTERN_CONTROLLER, true);
}
LOG.debug("Lantern controlling agent response");
final String to = XmppUtils.jidToUser(msg.getTo());
LOG.debug("Set hub address to: {}", LanternClientConstants.LANTERN_JID);
final String body = msg.getBody();
LOG.debug("Hub message body: {}", body);
final Object obj = JSONValue.parse(body);
final JSONObject json = (JSONObject) obj;
boolean handled = false;
handled |= handleSetDelay(json);
handled |= handleUpdate(json);
final Boolean inClosedBeta =
(Boolean) json.get(LanternConstants.INVITED);
if (inClosedBeta != null) {
Events.asyncEventBus().post(new ClosedBetaEvent(to, inClosedBeta));
} else {
if (!handled) {
// assume closed beta, because server replied with unhandled
// message
Events.asyncEventBus().post(new ClosedBetaEvent(to, false));
}
}
sendOnDemandValuesToControllerIfNecessary(json);
}
@SuppressWarnings("unchecked")
private boolean handleUpdate(final JSONObject json) {
// This is really a JSONObject, but that itself is a map.
final JSONObject update =
(JSONObject) json.get(LanternConstants.UPDATE_KEY);
if (update == null) {
return false;
}
LOG.info("About to propagate update...");
final Map<String, Object> event = new HashMap<String, Object>();
event.putAll(update);
Events.asyncEventBus().post(new UpdateEvent(event));
return false;
}
private boolean handleSetDelay(final JSONObject json) {
final Long delay =
(Long) json.get(LanternConstants.UPDATE_TIME);
LOG.debug("Server sent delay of: "+delay);
if (delay == null) {
return false;
}
final long now = System.currentTimeMillis();
final long elapsed = now - lastInfoMessageScheduled;
if (elapsed > 10000 && delay != 0L) {
lastInfoMessageScheduled = now;
timer.schedule(new TimerTask() {
@Override
public void run() {
updatePresence();
}
}, delay);
LOG.debug("Scheduled next info request in {} milliseconds", delay);
} else {
LOG.debug("Ignoring duplicate info request scheduling- "
+ "scheduled request {} milliseconds ago.", elapsed);
}
return true;
}
@Subscribe
public void onClosedBetaEvent(final ClosedBetaEvent cbe) {
LOG.debug("Got closed beta event!!");
this.closedBetaEvent = cbe;
if (this.closedBetaEvent.isInClosedBeta()) {
this.modelUtils.addToClosedBeta(cbe.getTo());
}
synchronized (this.closedBetaLock) {
// We have to make sure that this event is actually intended for
// the user we're currently logged in as!
final String to = this.closedBetaEvent.getTo();
LOG.debug("Analyzing closed beta event for: {}", to);
if (isLoggedIn()) {
final String user = LanternUtils.toEmail(
this.client.get().getXmppConnection());
if (user.equals(to)) {
LOG.debug("Users match!");
this.closedBetaLock.notifyAll();
} else {
LOG.debug("Users don't match {}, {}", user, to);
}
}
}
}
private void gTalkSharedStatus() {
// This is for Google Talk compatibility. Surprising, all we need to
// do is grab our Google Talk shared status, signifying support for
// their protocol, and then we don't interfere with GChat visibility.
final Packet status = XmppUtils.getSharedStatus(
this.client.get().getXmppConnection());
LOG.info("Status:\n{}", status.toXML());
}
/**
* Updates the user's presence. We also include any stats and friends
* updates in this message. Note that periodic presence updates are also
* used on the server side to verify which clients are actually available.
*
* We in part send presence updates instead of typical chat messages to get
* around these messages showing up in the user's gchat window.
*/
private void updatePresence() {
if (!isLoggedIn()) {
LOG.debug("Not updating presence when we're not connected");
return;
}
final XMPPConnection conn = this.client.get().getXmppConnection();
if (conn == null || !conn.isConnected()) {
return;
}
LOG.debug("Sending presence available");
// OK, this is bizarre. For whatever reason, we **have** to send the
// following packet in order to get presence events from our peers.
// DO NOT REMOVE THIS MESSAGE!! See XMPP spec.
final Presence pres = new Presence(Presence.Type.available);
conn.sendPacket(pres);
final Presence forHub = new Presence(Presence.Type.available);
forHub.setTo(LanternClientConstants.LANTERN_JID);
forHub.setProperty("language", SystemUtils.USER_LANGUAGE);
forHub.setProperty("instanceId", model.getInstanceId());
forHub.setProperty("mode", model.getSettings().getMode().toString());
final String str = JsonUtils.jsonify(stats);
LOG.debug("Reporting data: {}", str);
if (!this.lastJson.equals(str)) {
this.lastJson = str;
forHub.setProperty("stats", str);
stats.resetCumulativeStats();
} else {
LOG.info("No new stats to report");
}
/*
final FriendsHandler friends = model.getFriends();
if (friends.needsSync()) {
String friendsJson = JsonUtils.jsonify(friends);
forHub.setProperty(LanternConstants.FRIENDS, friendsJson);
friends.setNeedsSync(false);
}
*/
conn.sendPacket(forHub);
}
@Subscribe
public void onUpdatePresenceEvent(final UpdatePresenceEvent upe) {
// This was originally added to decouple the roster from this class.
final Presence pres = upe.getPresence();
addOrRemovePeer(pres, pres.getFrom());
}
@Override
public void addOrRemovePeer(final Presence p, final String from) {
LOG.info("Processing peer: {}", from);
final URI uri;
try {
uri = new URI(from);
} catch (final URISyntaxException e) {
LOG.error("Could not create URI from: {}", from);
return;
}
if (p.isAvailable()) {
LOG.info("Processing available peer");
// Only exchange certs with peers based on kscope ads.
// OK, we just request a certificate every time we get a present
// peer. If we get a response, this peer will be added to active
// peer URIs.
//sendAndRequestCert(uri);
}
else {
LOG.info("Removing JID for peer '"+from);
this.proxyTracker.removeNatTraversedProxy(uri);
}
}
private void processTypedMessage(final Message msg, final Integer type) {
final String from = msg.getFrom();
LOG.info("Processing typed message from {}", from);
switch (type) {
case (XmppMessageConstants.INFO_REQUEST_TYPE):
LOG.debug("Handling INFO request from {}", from);
if (!this.friendsHandler.isRejected(from)) {
processInfoData(msg);
} else {
LOG.debug("Not processing message from rejected friend {}",
from);
}
sendInfoResponse(from);
break;
case (XmppMessageConstants.INFO_RESPONSE_TYPE):
LOG.debug("Handling INFO response from {}", from);
if (!this.friendsHandler.isRejected(from)) {
processInfoData(msg);
}
break;
case (LanternConstants.KSCOPE_ADVERTISEMENT):
//only process kscope ads delivered by friends
if (this.friendsHandler.isFriend(from)) {
LOG.debug("Handling KSCOPE ADVERTISEMENT");
final String payload =
(String) msg.getProperty(
LanternConstants.KSCOPE_ADVERTISEMENT_KEY);
if (StringUtils.isNotBlank(payload)) {
processKscopePayload(from, payload);
} else {
LOG.error("kscope ad with no payload? "+msg.toXML());
}
} else {
LOG.warn("kscope ad from non-friend");
}
break;
default:
LOG.warn("Did not understand type: "+type);
break;
}
}
private void processKscopePayload(final String from, final String payload) {
LOG.debug("Processing payload: {}", payload);
final ObjectMapper mapper = new ObjectMapper();
try {
final LanternKscopeAdvertisement ad =
mapper.readValue(payload, LanternKscopeAdvertisement.class);
final String jid = ad.getJid();
if (this.kscopeAdHandler.handleAd(jid, ad)) {
sendAndRequestCert(jid);
} else {
LOG.debug("Not requesting cert -- duplicate kscope ad?");
}
} catch (final JsonParseException e) {
LOG.warn("Could not parse JSON", e);
} catch (final JsonMappingException e) {
LOG.warn("Could not map JSON", e);
} catch (final IOException e) {
LOG.warn("IO error parsing JSON", e);
}
}
private void sendInfoResponse(final String from) {
final Message msg = new Message();
// The from becomes the to when we're responding.
msg.setTo(from);
msg.setProperty(P2PConstants.MESSAGE_TYPE,
XmppMessageConstants.INFO_RESPONSE_TYPE);
//msg.setProperty(P2PConstants.MAC, this.model.getNodeId());
msg.setProperty(P2PConstants.CERT,
this.keyStoreManager.getBase64Cert(getJid()));
this.client.get().getXmppConnection().sendPacket(msg);
}
private void processInfoData(final Message msg) {
LOG.debug("Processing INFO data from request or response.");
// This just makes sure it's a valid URI!!
final URI uri;
try {
uri = new URI(msg.getFrom());
} catch (final URISyntaxException e) {
LOG.error("Could not create URI from: {}", msg.getFrom());
return;
}
//final String mac = (String) msg.getProperty(P2PConstants.MAC);
final String base64Cert = (String) msg.getProperty(P2PConstants.CERT);
LOG.debug("Base 64 cert: {}", base64Cert);
if (StringUtils.isNotBlank(base64Cert)) {
LOG.trace("Got certificate for {}:\n{}", uri,
new String(Base64.decodeBase64(base64Cert),
LanternConstants.UTF8).replaceAll("\u0007", "[bell]")); // don't ring any bells
// Add the peer if we're able to add the cert.
this.kscopeAdHandler.onBase64Cert(uri, base64Cert);
} else {
LOG.error("No cert for peer?");
}
}
@Override
public String getJid() {
// We may have already disconnected on shutdown, for example, so check
// for null.
if (this.client.get() != null &&
this.client.get().getXmppConnection() != null &&
this.client.get().getXmppConnection().getUser() != null) {
return this.client.get().getXmppConnection().getUser().trim();
}
return "";
}
private void sendAndRequestCert(final String peer) {
LOG.debug("Requesting cert from {}", peer);
final Message msg = new Message();
msg.setProperty(P2PConstants.MESSAGE_TYPE,
XmppMessageConstants.INFO_REQUEST_TYPE);
msg.setTo(peer);
// Set our certificate in the request as well -- we want to make
// extra sure these get through!
//msg.setProperty(P2PConstants.MAC, this.model.getNodeId());
msg.setProperty(P2PConstants.CERT,
this.keyStoreManager.getBase64Cert(getJid()));
if (isLoggedIn()) {
this.client.get().getXmppConnection().sendPacket(msg);
} else {
LOG.debug("No longer logged in? Not sending cert");
}
}
@Override
public XmppP2PClient<FiveTuple> getP2PClient() {
return client.get();
}
@Override
public boolean isLoggedIn() {
if (this.client.get() == null) {
return false;
}
final XMPPConnection conn = client.get().getXmppConnection();
if (conn == null) {
return false;
}
return conn.isAuthenticated();
}
@Override
public void sendInvite(final Friend friend, boolean redo,
final boolean addToRoster) {
LOG.debug("Sending invite");
final String email = friend.getEmail();
final Set<String> invited = roster.getInvited();
if ((!redo) && invited.contains(email)) {
LOG.info("Already invited: {}", email);
model.addNotification("You appear to have already sent a Lantern invitation to '"+email+"'",
MessageType.info, 30);
Events.sync(SyncPath.NOTIFICATIONS, model.getNotifications());
return;
}
if (!isLoggedIn()) {
LOG.info("Not logged in!");
model.addNotification("Cannot send invite because we appear to no " +
"longer be logged in to Google Talk. Are you still connected " +
"to the Internet?",
MessageType.error, 30);
Events.sync(SyncPath.NOTIFICATIONS, model.getNotifications());
return;
}
final XMPPConnection conn = this.client.get().getXmppConnection();
final Roster rost = conn.getRoster();
final Presence pres = new Presence(Presence.Type.available);
pres.setTo(LanternClientConstants.LANTERN_JID);
// "emails" of the form xxx@public.talk.google.com aren't really
// e-mail addresses at all, so don't send 'em.
// In theory we might be able to use the Google Plus API to get
// actual e-mail addresses -- see:
if (LanternUtils.isAnonymizedGoogleTalkAddress(email)) {
pres.setProperty(LanternConstants.INVITED_EMAIL, email);
} else {
pres.setProperty(LanternConstants.INVITED_EMAIL, "");
}
final String refresh = this.model.getSettings().getRefreshToken();
LOG.debug("Sending refresh token: {}", refresh);
if (StringUtils.isBlank(refresh)) {
LOG.warn("Refresh token is blank");
}
pres.setProperty(LanternConstants.REFRESH_TOKEN, refresh);
final RosterEntry entry = rost.getEntry(email);
if (entry != null) {
final String name = entry.getName();
if (StringUtils.isNotBlank(name)) {
pres.setProperty(LanternConstants.INVITEE_NAME, name);
}
}
pres.setProperty(LanternConstants.INVITER_NAME,
this.model.getProfile().getName());
invited.add(email);
sendPresence(pres, "Invite-Thread");
addToRoster(email);
}
private void sendPresence(final Presence pres, final String threadName) {
final XMPPConnection conn = this.client.get().getXmppConnection();
final Runnable runner = new Runnable() {
@Override
public void run() {
conn.sendPacket(pres);
}
};
final Thread t = new Thread(runner, threadName);
t.setDaemon(true);
t.start();
}
/** Try to reconnect to the xmpp server */
private void reconnect() {
//this will trigger XmppP2PClient's internal reconnection logic
if (hasConnection()) {
client.get().getXmppConnection().disconnect();
}
// Otherwise the client should already be trying to connect.
}
private boolean hasConnection() {
return client.get() != null && client.get().getXmppConnection() != null;
}
@Override
public void subscribe(final String jid) {
LOG.debug("Sending subscribe message to: {}", jid);
final Presence packet = new Presence(Presence.Type.subscribe);
packet.setTo(jid);
//final String json = JsonUtils.jsonify(this.model.getProfile());
//packet.setProperty(XmppMessageConstants.PROFILE, json);
final XMPPConnection conn = this.client.get().getXmppConnection();
conn.sendPacket(packet);
}
@Override
public void subscribed(final String jid) {
LOG.debug("Sending subscribed message to: {}", jid);
sendTypedPacket(jid, Presence.Type.subscribed);
}
@Override
public void unsubscribe(final String jid) {
LOG.debug("Sending unsubscribe message to: {}", jid);
sendTypedPacket(jid, Presence.Type.unsubscribe);
}
@Override
public void unsubscribed(final String jid) {
LOG.debug("Sending unsubscribed message to: {}", jid);
sendTypedPacket(jid, Presence.Type.unsubscribed);
}
private void sendTypedPacket(final String jid, final Type type) {
final Presence packet = new Presence(type);
packet.setTo(jid);
XmppP2PClient<FiveTuple> xmppP2PClient = this.client.get();
if (xmppP2PClient == null) {
throw new IllegalStateException("Can't send packets without a client");
}
final XMPPConnection conn = xmppP2PClient.getXmppConnection();
if (conn == null) {
throw new IllegalStateException("Can't send packets while offline");
}
conn.sendPacket(packet);
}
@Override
public void addToRoster(final String email) {
// If the user is not already on our roster, we want to make sure to
// send them an invite. If the e-mail address specified does not
// correspond with a Jabber ID, then we're out of luck. If it does,
// then this will send the roster invite.
final XMPPConnection conn = this.client.get().getXmppConnection();
final Roster rost = conn.getRoster();
final RosterEntry entry = rost.getEntry(email);
if (entry == null) {
LOG.debug("Inviting user to join roster: {}", email);
try {
// Note this also sends a subscription request!!
rost.createEntry(email,
StringUtils.substringBefore(email, "@"), new String[]{});
} catch (final XMPPException e) {
LOG.error("Could not create entry?", e);
}
} else {
LOG.debug("User already on roster...");
}
}
@Override
public void removeFromRoster(final String email) {
final XMPPConnection conn = this.client.get().getXmppConnection();
final Roster rost = conn.getRoster();
final RosterEntry entry = rost.getEntry(email);
if (entry != null) {
LOG.debug("Removing user from roster: {}", email);
try {
rost.removeEntry(entry);
} catch (final XMPPException e) {
LOG.error("Could not create entry?", e);
}
}
}
@Subscribe
public void onReset(final ResetEvent event) {
disconnect();
}
@Override
public void sendPacket(final Packet packet) {
this.client.get().getXmppConnection().sendPacket(packet);
}
private void peerUnavailable(final String from, final Presence pres) {
if (!LanternXmppUtils.isLanternJid(from)) {
return;
}
final String email = XmppUtils.jidToUser(from);
final ClientFriend friend = this.friendsHandler.getFriend(email);
if (friend == null) {
// Some error occurred!
return;
}
// We don't track logged in or mode separately on our server since
// XMPP takes care of it - that's why we don't update the server here.
friend.setLoggedIn(false);
friend.setMode(pres.getMode());
this.friendsHandler.syncFriends();
}
private void peerAvailable(final String from, final Presence pres) {
if (!LanternXmppUtils.isLanternJid(from)) {
return;
}
LOG.debug("Got peer available...");
final String email = XmppUtils.jidToUser(from);
this.friendsHandler.peerRunningLantern(email, pres);
}
/**
* Sends one or more properties to the controller based on a request from
* the controller.
*
* @param json
*/
private void sendOnDemandValuesToControllerIfNecessary(JSONObject json) {
final Presence presence = new Presence(Presence.Type.available);
if (Boolean.TRUE.equals(json.get(LanternConstants.NEED_REFRESH_TOKEN))) {
sendToken(presence);
}
if (Boolean.TRUE.equals(json.get(LanternConstants.NEED_ADDRESS))) {
sendAddress(presence);
}
if (Boolean.TRUE.equals(json.get(LanternConstants.NEED_FALLBACK_ADDRESS))) {
sendFallbackAddress(presence);
}
if (presence.getPropertyNames().size() > 0) {
LOG.debug("Sending on-demand properties to controller");
presence.setTo(LanternClientConstants.LANTERN_JID);
sendPresence(presence, "SendOnDemandProperties-Thread");
} else {
LOG.debug("Not sending on-demand properties to controller");
}
}
private void sendToken(Presence presence) {
LOG.info("Sending refresh token to controller.");
presence.setProperty(LanternConstants.REFRESH_TOKEN,
this.model.getSettings().getRefreshToken());
}
private void sendAddress(Presence presence) {
LOG.info("Sending give mode proxy address to controller.");
InetSocketAddress address = giveModeProxy.getServer().getAddress();
String hostAndPort = addressToHostAndPort(address);
presence.setProperty(LanternConstants.ADDRESS, hostAndPort);
}
private void sendFallbackAddress(Presence presence) {
LOG.info("Sending fallback address to controller.");
InetSocketAddress address = proxyTracker.addressForConfiguredFallbackProxy();
String hostAndPort = addressToHostAndPort(address);
presence.setProperty(LanternConstants.FALLBACK_ADDRESS, hostAndPort);
}
private String addressToHostAndPort(InetSocketAddress address) {
if (address == null) {
return null;
} else {
return String.format("%1$s:%2$s",
address.getAddress().getHostAddress(),
address.getPort());
}
}
@Override
public ProxyTracker getProxyTracker() {
return proxyTracker;
}
}
|
package org.narwhal.query;
public abstract class QueryCreator {
/**
* Makes prepared INSERT SQL statement by using the table name.
*
* @param tableName String representation of the table name that maps to the particular entity.
* @return String representation of the INSERT SQL statement.
* */
public String makeInsertQuery(String tableName, String[] columns, String primaryColumnName) {
StringBuilder builder = new StringBuilder("INSERT INTO ");
builder.append(tableName);
builder.append(" VALUES (");
for (int i = 0; i < columns.length; ++i) {
if (i > 0) {
builder.append(',');
}
builder.append('?');
}
builder.append(')');
return builder.toString();
}
/**
* Makes prepared SELECT SQL statement by using the table name.
*
* @param tableName String representation of the table name that maps to the particular entity.
* @return String representation of the SELECT SQL statement.
* */
public String makeSelectQuery(String tableName, String[] columns, String primaryColumnName) {
StringBuilder builder = new StringBuilder("SELECT ");
for (int i = 0; i < columns.length; ++i) {
if (i > 0) {
builder.append(',');
}
builder.append(columns[i]);
}
builder.append(" FROM ");
builder.append(tableName);
builder.append(" WHERE ");
builder.append(primaryColumnName);
builder.append(" = ?");
return builder.toString();
}
/**
* Makes prepared DELETE SQL statement by using the table name.
*
* @param tableName String representation of the table name that maps to the particular entity.
* @return String representation of the DELETE SQL statement.
* */
public String makeDeleteQuery(String tableName, String primaryColumnName) {
StringBuilder builder = new StringBuilder("DELETE FROM ");
builder.append(tableName);
builder.append(" WHERE ");
builder.append(primaryColumnName);
builder.append(" = ?");
return builder.toString();
}
/**
* Makes prepared UPDATE SQL statement by using the table name.
*
* @param tableName String representation of the table name that maps to the particular entity.
* @return String representation of the UPDATE SQL statement.
* */
public String makeUpdateQuery(String tableName, String[] columns, String primaryColumnName) {
StringBuilder builder = new StringBuilder("UPDATE ");
builder.append(tableName);
builder.append(" SET ");
for (int i = 0; i < columns.length; ++i) {
if (i > 0) {
builder.append(',');
}
builder.append(columns[i]);
builder.append(" = ?");
}
builder.append(" WHERE ");
builder.append(primaryColumnName);
builder.append(" = ?");
return builder.toString();
}
}
|
package org.nustaq.offheap;
import org.nustaq.offheap.bytez.ByteSink;
import org.nustaq.offheap.bytez.ByteSource;
import org.nustaq.offheap.bytez.Bytez;
import org.nustaq.offheap.bytez.onheap.HeapBytez;
/**
* an automatically growing byte queue organized as a ringbuffer.
*
* poll* methods don't throw excpetions but return incomplete or no result instead if
* the queue's content is not sufficient.
* read* methods throw excpetions in case the q contains not enough bytes (need to use available() to
* ensure data is present).
*
* add methods add to the queue. If the adding outperforms reading/polling, the queue is growed automatically.
*
*/
public class BinaryQueue {
Bytez storage;
long addIndex = 0;
long pollIndex = 0;
public BinaryQueue() {
this(1024);
}
public BinaryQueue(int qsize) {
storage = new HeapBytez(qsize);
}
/**
* add bytes to the queue. Again by using (reusable) Wrapper classes any kind of memory
* (offheap, byte arrays, nio bytebuffer, memory mapped) can be added.
*
* @param source
*/
public void add(ByteSource source) {
add(source,0, source.length());
}
/**
* add bytes to the queue. Again by using (reusable) Wrapper classes any kind of memory
* (offheap, byte arrays, nio bytebuffer, memory mapped) can be added.
*
* @param source
* @param sourceoff
* @param sourcelen
*/
public void add(ByteSource source, long sourceoff, long sourcelen) {
if ( sourcelen >= remaining() ) {
grow(sourcelen+1); //issue85
add(source,sourceoff,sourcelen);
return;
}
for ( int i=0; i < sourcelen; i++ ) {
storage.put(addIndex++,source.get(i+sourceoff));
if ( addIndex >= storage.length() )
addIndex -= storage.length();
}
}
public void addInt(int written)
{
add((byte) ((written >>> 0) & 0xFF));
add((byte) ((written >>> 8) & 0xFF));
add((byte) ((written >>> 16) & 0xFF));
add((byte) ((written >>> 24) & 0xFF));
}
public void add(byte b) {
long remaining = remaining();
if ( 1 >= remaining) {
grow(1+1); // issue85
add(b);
return;
}
storage.put(addIndex++, b);
if ( addIndex >= storage.length() )
addIndex -= storage.length();
}
protected void grow(long sourcelen) {
HeapBytez newStorage = new HeapBytez((int) Math.max(capacity()*2,capacity()+sourcelen+available()));
long len = poll(newStorage, 0, available());
pollIndex = 0;
addIndex = len;
storage = newStorage;
}
/**
* @return number of bytes free for an add operation
*/
public long remaining() {
return capacity() - available();
}
/**
* read up to destlen bytes (if available).
* Note you can use HeapBytez (implements ByteSink) in order to read to a regular byte array.
* HeapBytez wrapper can be reused to avoid unnecessary allocation.
* Also possible is ByteBufferBasicBytes to read into a ByteBuffer and MallocBytes or MMFBytes to
* read into Unsafe alloc'ed off heap memory or persistent mem mapped memory regions.
*
* @param destination
* @param destoff
* @param destlen
* @return
*/
public long poll(ByteSink destination, long destoff, long destlen) {
long count = 0;
try {
while (pollIndex != addIndex && count < destlen) {
destination.put(destoff + count++, storage.get(pollIndex++));
if (pollIndex >= storage.length()) {
pollIndex = 0;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return count;
}
/**
* convenience method to read len byte array. Throws an excpetion if not enough data is present
*
* @param len
* @return
*/
public byte[] readByteArray(int len) {
if ( available() < len ) {
throw new RuntimeException("not enough data available, check available() > len before calling");
}
byte b[] = new byte[len];
int count = 0;
while ( pollIndex != addIndex && count < len ) {
b[count++] = storage.get(pollIndex++);
if ( pollIndex >= storage.length() ) {
pollIndex = 0;
}
}
return b;
}
/**
* read an int. throws an exception if not enough data is present
* @return
*/
public int readInt() {
if ( available() < 4 ) {
throw new RuntimeException("not enough data available, check available() > 4 before calling");
}
int ch1 = poll();
int ch2 = poll();
int ch3 = poll();
int ch4 = poll();
return (ch4 << 24) + (ch3 << 16) + (ch2 << 8) + (ch1 << 0);
}
/**
* @return -1 or the next byte unsigned value
*/
public int poll() {
int result = -1;
if ( pollIndex != addIndex ) {
result = (storage.get(pollIndex++)+256)&0xff;
if ( pollIndex >= storage.length() ) {
pollIndex = 0;
}
}
return result;
}
/**
* 'unread' len bytes
* @param len
*/
public void back( int len ) {
if ( pollIndex >= len )
pollIndex -= len;
else
pollIndex = pollIndex + capacity() - len;
}
/**
* @return number of readable bytes
*/
public long available() {
return addIndex>=pollIndex ? addIndex-pollIndex : addIndex+capacity()-pollIndex;
}
/**
* @return size of underlying ringbuffer
*/
public long capacity() {
return storage.length();
}
@Override
public String toString() {
return "BinaryQueue{" +
"storage=" + storage +
", addIndex=" + addIndex +
", pollIndex=" + pollIndex +
'}';
}
}
|
package org.pfaa.chemica.model;
import java.awt.Color;
import org.pfaa.chemica.model.ChemicalStateProperties.Gas;
import org.pfaa.chemica.model.ChemicalStateProperties.Liquid;
import org.pfaa.chemica.model.ChemicalStateProperties.Liquid.Yaws;
import org.pfaa.chemica.model.ChemicalStateProperties.Solid;
import org.pfaa.chemica.model.Formula.PartFactory;
import org.pfaa.chemica.model.Hazard.SpecialCode;
import org.pfaa.chemica.model.Vaporization.AntoineCoefficients;
public enum Element implements Chemical, PartFactory, Metal {
/*
H He
Li Be B C N O F Ne
Na Mg Al Si P S Cl Ar
K Ca Sc Ti V Cr Mn Fe Co Ni Cu Zn Ga Ge As Se Br Kr
R Sr Y Zr Nb Mo Tc Rb Rh Pd Ag Cd In Sn Sb Te I Xe
Cs Ba Lu Hf Ta W Re Os Ir Pt Au Hg Tl Pb Bi Po At Rn
Ce La Pr Nd ... Sm ...
.. Th .. U ...
*/
H("hydrogen", Category.DIATOMIC_NONMETAL, null, 1.00, +1), /* See Molecules.H2 for properties */
He("helium", Category.NOBLE_GAS, null, 4.00, 0,
new Solid(0.187,
new Thermo(9.85)), // artificial, He is weird
new Fusion(1),
new Liquid(0.13,
new Thermo(-8.33, 18.4E3, -7.72E6, 1.18E9, 3.89E-6, 0.047, 11.8)),
new Vaporization(4),
new Gas(new Thermo(20.8, 0, 0, 0, 0, -6.2, 151))),
Li("lithium", Category.ALKALI_METAL, Strength.WEAK, 6.94, +1,
new Solid(new Color(240, 240, 240), 0.534,
new Thermo(170, -883, 1977, -1487, -1.61, -31.2, 414),
new Hazard(3, 2, 2, SpecialCode.WATER_REACTIVE)),
new Fusion(454),
new Liquid(0.512,
new Thermo(32.5, -2.64, -6.33, 4.23, 0.00569, -7.12, 74.3)
.addSegment(700, 26.0, 5.63, -4.01, 0.874, 0.344, -4.20, 66.4)),
new Vaporization(1603),
new Gas(new Thermo(23.3, -2.77, 0.767, -0.00360, -0.0352, 152, 166))),
Be("beryllium", Category.ALKALINE_EARTH_METAL, Strength.STRONG, 9.01, +2,
new Solid(new Color(40, 40, 40), 1.85,
new Thermo(21.2, 5.69, 0.968, -0.00175, -0.588, -8.55, 30.1)
.addSegment(1527, 30.0, -0.000396, 0.000169, -0.000026, -0.000105, -6.97, 40.8),
new Hazard(3, 1, 0)),
new Fusion(1560),
new Liquid(1.69,
new Thermo(25.4, 2.16, -0.00257, 0.000287, 0.00396, 5.44, 44.5)),
new Vaporization(3243),
new Gas(new Thermo(28.6, -5.38, 1.04, -0.0121, -426, 308, 164))),
B("boron", Category.METALLOID, Strength.VERY_STRONG, 10.8, +3,
new Solid(new Color(82, 53, 7), 2.37,
new Thermo(10.2, 29.2, -18.0, 4.21, -0.551, -6.04, 7.09)
.addSegment(1800, 25.1, 1.98, 0.338, -0.0400, -2.64, -14.4, 25.6),
new Hazard(3, 3, 2, SpecialCode.WATER_REACTIVE)),
new Fusion(2349),
new Liquid(2.08,
new Thermo(48.9, 26.5, 31.8)),
new Vaporization(4200),
new Gas(new Thermo(20.7, 0.226, -0.112, 0.0169, 0.00871, 554, 178))),
C("carbon", Category.POLYATOMIC_NONMETAL, Strength.WEAK /* graphite */, 12.0, +4,
new Solid(new Color(38, 33, 33), 2.27,
new Thermo(0, 6.0, 9.25).addSegment(300, 10.7),
new Hazard(0, 1, 0)),
null,
null,
new Vaporization(3915),
new Gas(new Thermo(21.2, -0.812, 0.449, -0.0433, -0.0131, 710, 184))),
N("nitrogen", Category.DIATOMIC_NONMETAL, null, 14.0, -3), /* see Compounds.N2 for properties */
O("oxygen", Category.DIATOMIC_NONMETAL, null, 16.0, -2), /* See Compounds.O2 for properties */
F("fluorine", Category.DIATOMIC_NONMETAL, null, 19.0, -1), /* See Compounds.F2 for properties, solid density 1.7 */
Ne("neon", Category.NOBLE_GAS, null, 20.2, 0,
new Solid(1.44,
new Thermo(14.3)),
new Fusion(25),
new Liquid(1.21,
new Thermo(27.9)),
new Vaporization(3.76, 95.6, -1.50),
new Gas(new Thermo(20.8, 0, 0, 0, 0, -6.2, 171))),
Na("sodium", Category.ALKALI_METAL, Strength.WEAK, 23.0, +1,
new Solid(new Color(212, 216, 220), 0.968,
new Thermo(72.6, -9.49, -731, 1415, -1.26, -21.8, 155),
new Hazard(3, 3, 2, SpecialCode.WATER_REACTIVE)),
new Fusion(371),
new Liquid(0.927,
new Thermo(40.3, -28.2, 20.7, -3.64, -0.0799, -8.78, 114)),
new Vaporization(2.46, 1874, -416),
new Gas(new Thermo(20.8, 0.277, -0.392, 0.120, -0.00888, 101, 179))),
Mg("magnesium", Category.ALKALINE_EARTH_METAL, Strength.MEDIUM, 24.3, +2,
new Solid(new Color(157, 157, 157), 1.74,
new Thermo(26.5, -1.53, 8.06, 0.572, -0.174, -8.50, 63.9),
new Hazard(0, 1, 1)),
new Fusion(923),
new Liquid(1.58,
new Thermo(4.79, 34.5, 34.3)),
new Vaporization(1363),
new Gas(new Thermo(20.8, 0.0356, -0.0319, 0.00911, 0.000461, 141)
.addSegment(2200, 47.6, -15.4, 2.88, -0.121, -27.0, 97.4, 177))),
Al("aluminum", Category.POST_TRANSITION_METAL, Strength.MEDIUM, 31.0, +5,
new Solid(new Color(177, 177, 177), 2.70,
new Thermo(28.1, -5.41, 8.56, 3.43, -0.277, -9.15, 61.9),
new Hazard(0, 1, 1)),
new Fusion(933),
new Liquid(2.38,
new Thermo(10.6, 39.6, 31.8)),
new Vaporization(5.74, 13204, -24.3),
new Gas(new Thermo(20.4, 0.661, -0.314, 0.0451, 0.0782, 324, 189))),
Si("silicon", Category.METALLOID, Strength.STRONG, 28.1, +4,
new Solid(new Color(206, 227, 231), 2.33,
new Thermo(22.8, 3.90, -0.0829, 0.0421, -0.354, -8.16, 43.3)),
new Fusion(1687),
new Liquid(2.57, new Thermo(48.5, 44.5, 27.2))),
P("phosphorus", Category.POLYATOMIC_NONMETAL, null, 31.0, +5,
new Solid(Color.white, 1.82,
new Thermo(16.5, 43.3, -58.7, 25.6, -0.0867, -6.66, 50.0),
new Hazard(4, 4, 2)),
new Fusion(317),
new Liquid(1.74,
new Thermo(26.3, 1.04, -6.12, 1.09, 3.00, -7.23, 74.9)),
new Vaporization(553),
new Gas(new Thermo(20.4, 1.05, -1.10, 0.378, 0.011, 310, 188)
.addSegment(2200, -2.11, 9.31, -0.558, -0.020, 29.3, 354, 190))
),
S("sulfur", Category.POLYATOMIC_NONMETAL, null, 32.1, +4,
new Solid(new Color(230, 230, 25), 2,
new Thermo(21.2, 3.87, 22.3, -10.3, -0.0123, -7.09, 55.5),
new Hazard()),
new Fusion(388),
new Liquid(1.82,
new Thermo(4541, 26066, -55521, 42012, 54.6, 788, -10826)
.addSegment(432, -37.9, 133, -95.3, 24.0, 7.65, 29.8, -13.2)),
new Vaporization(718),
new Gas(new Thermo(27.5, -13.3, 10.1, -2.66, -0.00558, 269, 204)
.addSegment(1400, 16.6, 2.40, -0.256, 0.00582, 3.56, 278, 195))
),
Cl("chlorine", Category.DIATOMIC_NONMETAL, null, 34.5, -1), /* See Compounds.Cl2 for properties */
Ar("argon", Category.NOBLE_GAS, null, 39.9, 0,
new Solid(1.62,
new Thermo(38)),
new Fusion(84),
new Liquid(1.21,
new Thermo(128)),
new Vaporization(3.30, 215, -22.3),
new Gas(new Thermo(20.8, 0, 0, 0, 0, -6.2, 180))),
K("potassium", Category.ALKALI_METAL, Strength.WEAK, 39.1, +1,
new Solid(new Color(219, 219, 219), 0.862,
new Thermo(-63.5, -3226, 14644, -16229, 16.3, 120, 534),
new Hazard(3, 3, 2, SpecialCode.WATER_REACTIVE)),
new Fusion(337),
new Liquid(0.828, new Thermo(40.3, -30.5, 26.5, -5.73, -0.0635, -8.81, 128)),
new Vaporization(new AntoineCoefficients(4.46, 4692, 24.2)),
new Gas(new Thermo(20.7, 0.392, -0.417, 0.146, 0.00376, 82.8, 185)
.addSegment(1800, 58.7, -27.4, 6.73, -0.421, -25.9, 32.4, 198))),
Ca("calcium", Category.ALKALINE_EARTH_METAL, Strength.WEAK, 40.1, +2,
new Solid(new Color(228, 237, 237), 1.55,
new Thermo(19.8, 10.1, 14.5, -5.53, 0.178, -5.86, 62.9),
new Hazard(3, 1, 2, SpecialCode.WATER_REACTIVE)),
new Fusion(1115),
new Liquid(1.38, new Thermo(7.79, 45.5, 35.0)),
new Vaporization(new AntoineCoefficients(2.78, 3121, -595)),
new Gas(new Thermo(122, -75, 19.2, -1.40, -64.5, 42.2, 217))),
// Skipped Sc
Ti("titanium", Category.TRANSITION_METAL, Strength.STRONG, 47.9, +4,
new Solid(new Color(230, 230, 230), 4.51,
new Thermo(23.1, 5.54, -2.06, 1.61, -0.0561, -0.433, 64.1),
new Hazard(1, 1, 2)),
new Fusion(1941),
new Liquid(4.11, new Thermo(13.7, 39.2, -22.1)),
new Vaporization(3560),
new Gas(new Thermo(9.27, 6.09, 0.577, -0.110, 6.50, 483, 204))),
V("vanadium", Category.TRANSITION_METAL, Strength.VERY_STRONG, 50.9, +5,
new Solid(new Color(145, 170, 190), 6.0,
new Thermo(26.3, 1.40, 2.21, 0.404, -0.176, -8.52, 59.3),
new Hazard(2, 1, 0)),
new Fusion(2183),
new Liquid(5.5, new Thermo(17.3, 36.1, 46.2)),
new Vaporization(3680),
new Gas(new Thermo(32.0, -9.12, 2.94, -0.190, 1.41, 505, 220))),
Cr("chromium", Category.TRANSITION_METAL, Strength.VERY_STRONG, 52.0, +3,
new Solid(new Color(212, 216, 220), 7.19,
new Thermo(7.49, 71.5, -91.7, 46.0, 0.138, -4.23, 15.8)
.addSegment(600, 18.5, 5.48, 7.90, -1.15, 1.27, -2.68, 48.1),
new Hazard(2, 1, 1)),
new Fusion(2180),
new Liquid(6.3, new Thermo(21.6, 36.2, 39.3)),
new Vaporization(2944),
new Gas(new Thermo(13.7, -3.42, 0.394, -16.7, 383, 183, 397))),
Mn("manganese", Category.TRANSITION_METAL, Strength.STRONG, 54.9, +4,
new Solid(new Color(212, 216, 220), 7.21,
new Thermo(27.2, 5.24, 7.78, -2.12, -0.282, -9.37, 61.5)
.addSegment(980, 52.3, -28.7, 21.5, -4.98, -2.43, -21.2, 90.7)
.addSegment(1361, 19.1, 31.4, -15.0, 3.21, 1.87, -2.76, 48.8)
.addSegment(1412, -534, 679, -296, 46.4, 161, 469, -394)),
new Fusion(1519),
new Liquid(5.95, new Thermo(16.3, 43.5, 46.0)),
new Vaporization(2334),
new Gas(new Thermo(188, -97.8, 20.2, -1.27, -177, 1.55, 220))),
Fe("iron", Category.TRANSITION_METAL, Strength.STRONG, 55.8, +3,
new Solid(Color.lightGray, 7.87,
new Thermo(24.0, 8.37, 0.000277, -8.60E-5, -5.00E-6, 0.268, 62.1),
new Hazard(1, 1, 0)),
new Fusion(1811),
new Liquid(6.98, new Thermo(12, 35, 46.0)),
new Vaporization(3134),
new Gas(new Thermo(11.3, 6.99, -1.11, 0.122, 5.69, 424, 206))),
Co("cobalt", Category.TRANSITION_METAL, Strength.STRONG, 58.9, +2,
new Solid(Color.lightGray, 8.90,
new Thermo(11.0, 54.4, -55.5, 25.8, 0.165, -4.70, 30.3)
.addSegment(700, -205, 516, -422, 130, 18.0, 94.6, -273)
.addSegment(1394, -12418, 15326, -7087, 1167, 3320, 10139, -10473)),
new Fusion(1768),
new Liquid(7.75,
new Thermo(45.6, -3.81, 1.03, -0.0967, -3.33, -8.14, 78.0)),
new Vaporization(3200),
new Gas(new Thermo(40.7, -8.46, 1.54, -0.0652, -11.1, 397, 213))),
Ni("nickel", Category.TRANSITION_METAL, Strength.STRONG, 58.7, +2,
new Solid(new Color(160, 160, 140), 8.91,
new Thermo(13.7, 82.5, -175, 162, -0.0924, -6.83, 27.7)
.addSegment(600, 1248, -1258, 0, 0, -165, -789, 1213)
.addSegment(700, 16.5, 18.7, -6.64, 1.72, 1.87, -0.468, 51.7),
new Hazard(2, 4, 1)),
new Fusion(1728),
new Liquid(7.81, new Thermo(17.5, 41.5, 38.9)),
new Vaporization(3186),
new Gas(new Thermo(27.1, -2.59, 0.295, 0.0152, 0.0418, 421, 214))),
Cu("copper", Category.TRANSITION_METAL, Strength.MEDIUM, 63.5, +2,
new Solid(new Color(208, 147, 29), 8.96,
new Thermo(17.7, 28.1, -31.3, 14.0, 0.0686, -6.06, 47.9),
new Hazard(1, 1, 0)),
new Fusion(1358),
new Liquid(8.02, new Thermo(17.5, 41.5, 32.8)),
new Vaporization(2835),
new Gas(new Thermo(-80.5, 49.4, -7.58, 0.0405, 133, 520, 194))),
Zn("zinc", Category.TRANSITION_METAL, Strength.MEDIUM, 63.5, +2,
new Solid(new Color(230, 230, 230), 7.14,
new Thermo(25.6, -4.41, 20.4, -7.40, -0.0458, -7.56, 72.9),
new Hazard(2, 0, 0)),
new Fusion(673),
new Liquid(6.57, new Thermo(6.52, 50.8, 31.4)),
new Vaporization(1180),
new Gas(new Thermo(18.2, 2.31, -0.737, 0.0800, 1.07, 127, 185))),
Ga("gallium", Category.POST_TRANSITION_METAL, Strength.WEAK, 69.7, +3,
new Solid(new Color(212, 216, 220), 5.91,
new Thermo(102, -348, 603, -361, -1.49, -24.7, 236),
new Hazard(1, 0, 0)),
new Fusion(303),
new Liquid(6.10, new Thermo(24.6, 2.70, -1.27, 0.197, 0.286, -0.909, 89.9)),
new Vaporization(2673),
new Gas(new Thermo(20.3, 0.570, -0.210, 0.0258, 3.05, 273, 201))),
Ge("germanium", Category.METALLOID, Strength.STRONG, 72.6, +4,
new Solid(new Color(212, 216, 220), 5.32,
new Thermo(0, 31.1, 23.7, 3.57, -0.233, -0.125)),
new Fusion(1211),
new Liquid(5.60, new Thermo(60.5, 97.3, 27.6)),
new Vaporization(3106),
new Gas(new Thermo(377, 168, 30.7))),
As("arsenic", Category.METALLOID, Strength.MEDIUM, 74.9, +3,
new Solid(new Color(112, 112, 112), 5.73,
new Thermo(0, 35.1, 21.6, 9.79),
new Hazard(3, 2, 0)),
null, null,
new Vaporization(887),
new Gas(new Thermo(74.3))),
Se("selenium", Category.POLYATOMIC_NONMETAL, null, 79.0, +4,
new Solid(Color.red, 4.39,
new Thermo(0, 42.0, 16.2, 29.4),
new Hazard(2, 0, 0)),
new Fusion(494),
new Liquid(3.99, new Thermo(11.4, 67.8, 35.2)),
new Vaporization(958),
new Gas(new Thermo(227, 177, 20.8))),
Br("bromine", Category.DIATOMIC_NONMETAL, null, 79.9, -1), // see Compounds.Br2
Kr("krypton", Category.NOBLE_GAS, null, 83.8, 0,
new Solid(2.83,
new Thermo(-14.4, 54.9, -0.910, 291, -3844, 17670, 1.39E-6)),
new Fusion(116),
new Liquid(2.41,
new Thermo(-12.8, 69, 10.4)),
new Vaporization(4.21, 539, 8.86),
new Gas(new Thermo(20.8, 0, 0, 0, 0, -6.2, 189))),
Rb("rubidium", Category.ALKALI_METAL, Strength.WEAK, 85.5, +1,
new Solid(new Color(175, 175, 175), 1.53,
new Thermo(9.45, 65.3, 45.5, -26.8, -0.108, -6.43, 66.3),
new Hazard(2, 3, 0, SpecialCode.WATER_REACTIVE)),
new Fusion(312),
new Liquid(1.46, new Thermo(35.5, -12.9, 8.55, -0.00283, -0.000119, -7.90, 130)),
new Vaporization(961),
new Gas(new Thermo(20.6, 0.462, -0.495, 0.174, 0.00439, 74.7, 195)
.addSegment(1800, 74.1, -39.2, 9.91, -0.679, -35.1, 4.97, 214))),
Sr("strontium", Category.ALKALINE_EARTH_METAL, Strength.WEAK, 87.6, +2,
new Solid(new Color(212, 216, 220), 2.64,
new Thermo(23.9, 9.30, 0.920, 0.0352, 0.00493, -7.53, 81.8),
new Hazard(4, 0, 2, SpecialCode.WATER_REACTIVE)),
new Fusion(1050),
new Liquid(2.38, new Thermo(0.91, 50.9, 39.5)),
new Vaporization(1650),
new Gas(new Thermo(19.4, 3.74, -3.19, 0.871, 0.0540, 158, 187)
.addSegment(2700, -39.0, -1.70, 7.99, -0.852, 188, 355, 243))),
Y("yttrium", Category.TRANSITION_METAL, Strength.STRONG, 88.9, +3,
new Solid(new Color(212, 216, 220), 4.47,
new Thermo(0, 44.4, 24.4, 6.99)),
new Fusion(1799),
new Liquid(4.24, new Thermo(50.7)),
new Vaporization(3203),
new Gas(new Thermo(164))),
Zr("zirconium", Category.TRANSITION_METAL, Strength.STRONG, 91.2, +4,
new Solid(new Color(212, 216, 220), 6.52,
new Thermo(29, -12.6, 20.7, -5.91, -0.157, -8.79, 76.0),
new Hazard(1, 1, 0)),
new Fusion(2128),
new Liquid(5.8, new Thermo(17.4, 47.6, 41.8)),
new Vaporization(4650),
new Gas(new Thermo(39.5, -6.52, 2.26, -0.194, -12.5, 578, 212))),
Nb("niobium", Category.TRANSITION_METAL, Strength.STRONG, 92.9, +5,
new Solid(new Color(135, 150, 160), 8.57,
new Thermo(22.0, 9.89, -5.65, 1.76, 0.0218, -6.88, 60.5),
new Hazard(1, 1, 0)),
new Fusion(2750),
new Liquid(Double.NaN, new Thermo(29.7, 47.3, 33.5)),
new Vaporization(5017),
new Gas(new Thermo(-14637, 5142, -675, 31.5, 47657, 42523, 6194))),
Mo("molybdenum", Category.TRANSITION_METAL, Strength.STRONG, 96, +4,
new Solid(new Color(105, 105, 105), 10.3,
new Thermo(24.7, 3.96, -1.27, 1.15, -0.17, -8.11, 56.4)
.addSegment(1900, 1231, -963, 284, -28, -712, -1486, 574),
new Hazard(1, 3, 0)),
new Fusion(2896),
new Liquid(9.33, new Thermo(41.6, 43.1, 37.7)),
new Vaporization(4912),
new Gas(new Thermo(67.9, -40.5, 11.7, -0.819, -22.1, 601, 232))),
// Skipped Tc
Ru("ruthenium", Category.TRANSITION_METAL, Strength.STRONG, 101, +3,
new Solid(new Color(213, 213, 213), 12.5,
new Thermo(0, 28.5, 19.9, 10.4, -2.27, 0.125),
new Hazard(2, 3, 0, SpecialCode.WATER_REACTIVE)),
new Fusion(2607),
new Liquid(10.7, new Thermo(109, 105, 22.7, 5.12)),
new Vaporization(4423),
new Gas(new Thermo(264))),
Rh("rhodium", Category.TRANSITION_METAL, Strength.STRONG, 103, +3,
new Solid(new Color(213, 213, 213), 12.4,
new Thermo(0, 31.5, 22.0, 9.98)),
new Fusion(2237),
new Liquid(10.7, new Thermo(107)),
new Vaporization(3968)),
Pd("palladium", Category.TRANSITION_METAL, Strength.STRONG, 106, +2,
new Solid(new Color(213, 213, 213), 12.0,
new Thermo(0, 37.6, 22.5, 10.0, -2.63, 0.0622)),
new Fusion(1828),
new Liquid(10.4, new Thermo(62.2, 98.9, 37.2)),
new Vaporization(3236),
new Gas(new Thermo(231))),
Ag("silver", Category.TRANSITION_METAL, Strength.MEDIUM, 108, +1,
new Solid(new Color(213, 213, 213), 10.5,
new Thermo(0, 42.6, 23.4, 6.28),
new Hazard(1, 1, 0)),
new Fusion(1235),
new Liquid(9.32, new Thermo(24.7, 52.3, 339, -45)),
new Vaporization(1.95, 2505, -1195),
new Gas(new Thermo(285, 173, Double.NaN))),
Cd("cadmium", Category.TRANSITION_METAL, Strength.WEAK, 112, +2,
new Solid(new Color(190, 190, 210), 8.65,
new Thermo(0, 51.8, 22.8, 10.3),
new Hazard(2, 2, 0)),
new Fusion(594),
new Liquid(8.00, new Thermo(14.4, 62.2, 29.7)),
new Vaporization(1040),
new Gas(new Thermo(112, 168, 20.8))),
In("indium", Category.POST_TRANSITION_METAL, Strength.WEAK, 115, +3,
new Solid(new Color(190, 190, 210), 7.31,
new Thermo(0, 57.8, 21.4, 17.7)),
new Fusion(430),
new Liquid(7.02, new Thermo(6.93, 75.5, 30.1)),
new Vaporization(2345),
new Gas(new Thermo(216))),
Sn("tin", Category.POST_TRANSITION_METAL, Strength.WEAK, 119, +4,
new Solid(new Color(212, 216, 220), 7.28,
new Thermo(0, 51.2, 23.1, 19.6),
new Hazard(1, 3, 3)),
new Fusion(505),
new Liquid(6.97, new Thermo(13.5, 65.1, 28.7)),
new Vaporization(6.60, 16867, 15.5),
new Gas(new Thermo(168))),
Sb("antimony", Category.METALLOID, Strength.MEDIUM, 122, +3,
new Solid(new Color(212, 216, 220), 6.70,
new Thermo(0, 45.7, 23.1, 7.45), // NOTE: heating is extremely dangerous
new Hazard(4, 4, 2)),
new Fusion(904),
new Liquid(6.53, new Thermo(67.6)),
new Vaporization(2.26, 4475, -152),
new Gas(new Thermo(168))),
Te("tellurium", Category.METALLOID, Strength.WEAK, 128, +4,
new Solid(new Color(212, 216, 220), 6.24,
new Thermo(0, 49.7, 19.2, 21.8),
new Hazard(2, 0, 0)),
new Fusion(723),
new Liquid(5.70, new Thermo(12.9, 76.0, 37.7)),
new Vaporization(1261),
new Gas(new Thermo(189))),
I("iodine", Category.DIATOMIC_NONMETAL, null, 127, +4),
Xe("xenon", Category.NOBLE_GAS, null, 131, 0,
new Solid(5.89,
new Thermo(63.6)),
new Fusion(116),
new Liquid(2.41,
new Thermo(-15.4, 81.6, 155)),
new Vaporization(2.84, 327, -49.8),
new Gas(new Thermo(20.8, 0, 0, 0, 0, -6.2, 195))),
Cs("caesium", Category.ALKALI_METAL, Strength.WEAK, 133, +1,
new Solid(new Color(170, 160, 115), 1.93,
new Thermo(57.0, -50.0, 48.6, -16.7, -1.22, -19.3, 160),
new Hazard(4, 3, 3, SpecialCode.WATER_REACTIVE)),
new Fusion(302),
new Liquid(1.84, new Thermo(30.0, 0.506, 0.348, -0.0995, 0.197, -6.23, 129)),
new Vaporization(3.70, 3453, -26.8),
new Gas(new Thermo(76.5, 175, 20.8)
.addSegment(1000, 34.5, -13.8, 4.13, -0.138, -3.95, 58.2, 211)
.addSegment(4000, -181, 80.0, -9.19, 0.330, 374, 518, 242))),
Ba("barium", Category.ALKALINE_EARTH_METAL, Strength.WEAK, 137, +2,
new Solid(new Color(70, 70, 70), 3.51,
new Thermo(83.8, -406, 915, -520, -14.6, 248)
.addSegment(583, 76.7, -188, 296, -114, -4.34, -25.6, 189)
.addSegment(768, 26.2, 28.6, -23.7, 6.95, 1.04, -5.80, 90),
new Hazard(2, 1, 2)),
new Fusion(1000),
new Liquid(3.34, new Thermo(55.0, -18.7, 2.76, 1.28, 3.02, -8.42, 135)),
new Vaporization(4.08, 7599, -45.7),
new Gas(new Thermo(-623, 430, -97.0, 7.47, 488, 1077, 19.0)
.addSegment(4000, 770, -284, 41.4, -2.13, -1693, -1666, -26.3))),
// Skipped Lu and Hf
Ta("tantalum", Category.TRANSITION_METAL, Strength.VERY_STRONG, 181, +5,
new Solid(new Color(185, 190, 200), 16.7,
new Thermo(20.7, 17.3, -15.7, 5.61, 0.0616, -6.60, 62.4)
.addSegment(1300, -43.9, 73.0, -27.4, 4.00, 26.3, 60.2, 25.7),
new Hazard(1, 1, 0)),
new Fusion(3290),
new Liquid(15, new Thermo(30.8, 50.4, 41.8)),
new Vaporization(5731),
new Gas(new Thermo(29.5, 3.42, -0.566, 0.0697, -4.93, 763, 208))),
W("tungsten", Category.TRANSITION_METAL, Strength.VERY_STRONG, 184, +6,
new Solid(new Color(140, 140, 140), 19.3,
new Thermo(24.0, 2.64, 1.26, -0.255, -0.0484, -7.43, 60.5)
.addSegment(1900, -22.6, 90.3, -44.3, 7.18, -24.1, -9.98, -14.2),
new Hazard(1, 2, 1)),
new Fusion(3695),
new Liquid(17.6, new Thermo(46.9, 45.7, 35.6)),
new Vaporization(6203),
new Gas(new Thermo(174))),
Re("rhenium", Category.TRANSITION_METAL, Strength.VERY_STRONG, 186, +7,
new Solid(new Color(212, 216, 220), 21.0,
new Thermo(0, 36.9, 26.4, 2.22)),
new Fusion(3459),
new Liquid(18.9, new Thermo(54.4))),
Os("osmium", Category.TRANSITION_METAL, Strength.VERY_STRONG, 190, +4,
new Solid(new Color(190, 180, 240), 22.6,
new Thermo(0, 32.6, 23.6, 3.88)),
new Fusion(3306),
new Liquid(20, new Thermo(119))),
Ir("iridium", Category.TRANSITION_METAL, Strength.VERY_STRONG, 190, +4,
new Solid(new Color(212, 216, 220), 25.6,
new Thermo(0, 35.5, 25.1)),
new Fusion(2719),
new Liquid(19, new Thermo(106))),
Pt("platinum", Category.TRANSITION_METAL, Strength.MEDIUM, 195, +4,
new Solid(new Color(235, 235, 235), 22.2,
new Thermo(0, 41.6, 24.3, 5.27)),
new Fusion(2041),
new Liquid(19.8, new Thermo(109))),
Au("gold", Category.TRANSITION_METAL, Strength.MEDIUM, 197, +3,
new Solid(new Color(255, 215, 0), 19.3,
new Thermo(0, 47.4, 23.2, 6.16, -0.618, -0.0355),
new Hazard(2, 0, 0)),
new Fusion(1337),
new Liquid(17.3, new Thermo(57.8)), // FIXME: better thermodynamics for liquid gold!
new Vaporization(5.47, 17292, -71),
new Gas(new Thermo(366, 180, 20.8))),
Hg("mercury", Category.TRANSITION_METAL, null, 201, +2,
new Solid(new Color(155, 155, 155), 14.25,
new Thermo(-2.18, 66.1, 21.5, 29.2)),
new Fusion(234),
new Liquid(new Color(188, 188, 188), 13.5,
new Thermo(0, 75.9, 28),
new Hazard(3, 0, 0),
new Yaws(-0.275, 137, 4.18E-6, -1.20E-9)),
new Vaporization(4.86, 3007, -10.0),
new Gas(new Thermo(20.7, 0.179, -0.0801, 0.0105, 0.00701, 55.2, 200))),
// Skipped Tl
Pb("lead", Category.POST_TRANSITION_METAL, Strength.WEAK, 207, +2,
new Solid(new Color(65, 65, 65), 11.3,
new Thermo(25.0, 5.44, 4.06, -1.24, -0.0107, -7.77, 93.2),
new Hazard(2, 0, 0)),
new Fusion(601),
new Liquid(10.7, new Thermo(38.0, -14.6, 7.26, -1.03, -0.331, -7.94, 119)),
new Vaporization(2022),
new Gas(new Thermo(-85.7, 69.3, -13.3, 0.840, 63.1, 333, 170))),
Bi("bismuth", Category.POST_TRANSITION_METAL, Strength.MEDIUM, 209, +3,
new Solid(new Color(213, 213, 213), 9.78,
new Thermo(0, 56.7, 21.1, 14.7)),
new Fusion(545),
new Liquid(10.1, new Thermo(0 /* dummy */, 77.4, 31.8)),
new Vaporization(1837),
new Gas(new Thermo(175))),
// Skipped Po, At, and many others...
Ce("cerium", Category.LANTHANIDE, Strength.MEDIUM, 140, +3,
new Solid(new Color(212, 216, 220), 6.77,
new Thermo(0, 72.0, 24.6, 0.005),
new Hazard(2, 3, 2)),
new Fusion(1068),
new Liquid(6.55, new Thermo(77.1)),
new Vaporization(3716),
new Gas(new Thermo(184))),
La("lanthanum", Category.LANTHANIDE, Strength.MEDIUM, 139, +3,
new Solid(new Color(212, 216, 220), 6.16,
new Thermo(0, 56.9, 24.7, 4),
new Hazard(2, 3, 2)),
new Fusion(1193),
new Liquid(5.94, new Thermo(62.1)),
new Vaporization(3737),
new Gas(new Thermo(169))),
Nd("neodynium", Category.LANTHANIDE, Strength.MEDIUM, 144, +3,
new Solid(new Color(212, 216, 220), 7.01,
new Thermo(0, 71.6, 26.2, 4),
new Hazard(2, 3, 2)),
new Fusion(1297),
new Liquid(6.89, new Thermo(77.1)),
new Vaporization(3347),
new Gas(new Thermo(163))),
Sm("samarium", Category.LANTHANIDE, Strength.MEDIUM, 150, +3,
new Solid(new Color(212, 216, 220), 7.52,
new Thermo(0, 69.6, 25, 24.9, -0.354, -0.256),
new Hazard(1, 1, 1)),
new Fusion(1345),
new Liquid(7.16, new Thermo(76.0)),
new Vaporization(2173),
new Gas(new Thermo(164))),
Pr("praseodynium", Category.LANTHANIDE, Strength.MEDIUM, 141, +3,
new Solid(new Color(212, 216, 220), 6.77,
new Thermo(0, 73.2, 26.0, 4),
new Hazard(2, 3, 2)),
new Fusion(1208),
new Liquid(6.50, new Thermo(78.9)),
new Vaporization(3403),
new Gas(new Thermo(176))),
Th("thorium", Category.ACTINIDE, Strength.MEDIUM, 232, +4,
new Solid(new Color(64, 69, 70), 11.7,
new Thermo(0, 51.8, 24.3, 10.2)),
new Fusion(2115),
new Liquid(Double.NaN, new Thermo(58.3)),
new Vaporization(5061),
new Gas(new Thermo(160))),
U("uranium", Category.ACTINIDE, Strength.STRONG, 238, +6,
new Solid(new Color(95, 95, 95), 19.1,
new Thermo(0, 50.2, 9.68, 41.0, -2.65, 53.7)
.addSegment(672, 41, 2.93)
.addSegment(772, 42, 4.79)),
new Fusion(1405),
new Liquid(17.3, new Thermo(56.7)),
new Vaporization(4404),
new Gas(new Thermo(200)))
;
public static enum Category {
ALKALI_METAL,
ALKALINE_EARTH_METAL,
LANTHANIDE,
ACTINIDE,
TRANSITION_METAL,
POST_TRANSITION_METAL,
METALLOID,
POLYATOMIC_NONMETAL,
DIATOMIC_NONMETAL,
NOBLE_GAS,
UNKNOWN;
public boolean isMetal() {
return this.ordinal() < METALLOID.ordinal();
}
public boolean isMetallic() {
return this.ordinal() <= METALLOID.ordinal();
}
}
private Chemical delegate;
private double atomicWeight;
private int defaultOxidationState;
private Category category;
private Strength strength;
private Element(String name, Category category, Strength strength, double atomicWeight, int defaultOxidationState,
Solid solid, Fusion fusion,
Liquid liquid, Vaporization vaporization,
Gas gas)
{
this.atomicWeight = atomicWeight;
this.defaultOxidationState = defaultOxidationState;
this.category = category;
this.strength = strength;
this.delegate = new SimpleChemical(new Formula(this._(1)), name, solid, fusion, liquid,
vaporization, gas);
}
private Element(String name, Category category, Strength strength, double atomicWeight, int defaultOxidationState,
Solid solid, Fusion fusion,
Liquid liquid, Vaporization vaporization)
{
this(name, category, strength, atomicWeight, defaultOxidationState, solid, fusion, liquid,
vaporization, null);
}
private Element(String name, Category category, Strength strength, double atomicWeight, int defaultOxidationState,
Solid solid, Fusion fusion,
Liquid liquid)
{
this(name, category, strength, atomicWeight, defaultOxidationState, solid, fusion, liquid, null);
}
private Element(String name, Category category, Strength strength, double atomicWeight, int defaultOxidationState,
Solid solid, Fusion fusion)
{
this(name, category, strength, atomicWeight, defaultOxidationState, solid, fusion, null);
}
private Element(String name, Category category, Strength strength, double atomicWeight, int defaultOxidationState,
Solid solid) {
this(name, category, strength, atomicWeight, defaultOxidationState, solid, null);
}
private Element(String name, Category category, Strength strength, double atomicWeight, int defaultOxidationState) {
this(name, category, strength, atomicWeight, defaultOxidationState, null);
}
@Override
public Fusion getFusion() {
return delegate.getFusion();
}
@Override
public Vaporization getVaporization() {
return delegate.getVaporization();
}
@Override
public String getOreDictKey() {
return delegate.getOreDictKey();
}
@Override
public ConditionProperties getProperties(Condition condition) {
return delegate.getProperties(condition);
}
@Override
public ConditionProperties getProperties(Condition condition, State state) {
return delegate.getProperties(condition, state);
}
@Override
public Mixture mix(IndustrialMaterial material, double weight) {
return this.delegate.mix(material, weight);
}
@Override
public Formula getFormula() {
return delegate.getFormula();
}
@Override
public Formula.Part _(int quantity) {
return new Formula.Part(this, quantity);
}
@Override
public Formula.Part getPart() {
return this._(1);
}
public double getAtomicWeight() {
return this.atomicWeight;
}
public int getDefaultOxidationState() {
return this.defaultOxidationState;
}
public Alloy alloy(Element solute, double weight) {
return new SimpleAlloy(this, solute, weight);
}
public Category getCategory() {
return this.category;
}
@Override
public Strength getStrength() {
return this.strength;
}
public boolean isMonatomic() {
return this.getCategory() != Category.DIATOMIC_NONMETAL;
}
}
|
package org.scm4j.releaser;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import org.scm4j.commons.Version;
import org.scm4j.releaser.actions.ActionKind;
import org.scm4j.releaser.actions.ActionNone;
import org.scm4j.releaser.actions.IAction;
import org.scm4j.releaser.branch.DevelopBranch;
import org.scm4j.releaser.branch.ReleaseBranch;
import org.scm4j.releaser.conf.Component;
import org.scm4j.releaser.conf.DelayedTagsFile;
import org.scm4j.releaser.conf.Options;
import org.scm4j.releaser.conf.TagDesc;
import org.scm4j.releaser.scmactions.SCMActionBuild;
import org.scm4j.releaser.scmactions.SCMActionFork;
import org.scm4j.releaser.scmactions.SCMActionTagRelease;
import org.scm4j.vcs.api.IVCS;
import org.scm4j.vcs.api.VCSTag;
public class SCMReleaser {
public static final String MDEPS_FILE_NAME = "mdeps";
public static final String VER_FILE_NAME = "version";
public static final String DELAYED_TAGS_FILE_NAME = "delayed-tags.yml";
public static final File BASE_WORKING_DIR = new File(System.getProperty("user.home"), ".scm4j");
public IAction getActionTree(String coords) {
return getActionTree(new Component(coords));
}
public IAction getActionTree(Component comp) {
Options.setIsPatch(comp.getVersion().isExact());
return getActionTree(comp, ActionKind.AUTO);
}
public IAction getActionTree(String coords, ActionKind actionKind) {
Component comp = new Component(coords);
Options.setIsPatch(comp.getVersion().isExact());
return getActionTree(new Component(coords), actionKind);
}
public IAction getActionTree(Component comp, ActionKind actionKind) {
List<IAction> childActions = new ArrayList<>();
List<Component> mDeps;
ReleaseBranch rb;
if (Options.isPatch()) {
rb = new ReleaseBranch(comp, comp.getCoords().getVersion());
mDeps = rb.getMDeps();
} else {
rb = new ReleaseBranch(comp);
mDeps = new DevelopBranch(comp).getMDeps();
}
for (Component mDep : mDeps) {
childActions.add(getActionTree(mDep, actionKind));
}
Build mb = new Build(rb);
BuildStatus mbs = mb.getStatus();
switch (mbs) {
case FORK:
case FREEZE:
return getForkOrSkipAction(rb, childActions, mbs, actionKind);
case BUILD_MDEPS:
case ACTUALIZE_PATCHES:
case BUILD:
return getBuildOrSkipAction(rb, childActions, mbs, actionKind);
case DONE:
return new ActionNone(rb, childActions, mbs.toString());
default:
throw new IllegalArgumentException("unsupported build status: " + mbs);
}
}
private IAction getBuildOrSkipAction(ReleaseBranch rb, List<IAction> childActions, BuildStatus mbs,
ActionKind actionKind) {
if (actionKind == ActionKind.FORK) {
return new ActionNone(rb, childActions, "nothing to fork");
}
skipAllForks(rb, childActions);
return new SCMActionBuild(rb, childActions, mbs);
}
private IAction getForkOrSkipAction(ReleaseBranch rb, List<IAction> childActions, BuildStatus mbs,
ActionKind actionKind) {
if (actionKind == ActionKind.BUILD) {
return new ActionNone(rb, childActions, "nothing to build");
}
skipAllBuilds(rb, childActions);
return new SCMActionFork(rb, childActions, mbs);
}
public static TagDesc getTagDesc(String verStr) {
String tagMessage = verStr + " release";
return new TagDesc(verStr, tagMessage);
}
private void skipAllForks(ReleaseBranch rb, List<IAction> childActions) {
ListIterator<IAction> li = childActions.listIterator();
IAction action;
while (li.hasNext()) {
action = li.next();
skipAllForks(rb, action.getChildActions());
if (action instanceof SCMActionFork) {
li.set(new ActionNone(((SCMActionFork) action).getReleaseBranch(), action.getChildActions(), "fork skipped because not all parent components built"));
}
}
}
private void skipAllBuilds(ReleaseBranch rb, List<IAction> childActions) {
ListIterator<IAction> li = childActions.listIterator();
IAction action;
while (li.hasNext()) {
action = li.next();
skipAllBuilds(rb, action.getChildActions());
if (action instanceof SCMActionBuild) {
li.set(new ActionNone(((SCMActionBuild) action).getReleaseBranch(), action.getChildActions(), ((SCMActionBuild) action).getVersion() +
" build skipped because not all parent components forked"));
}
}
}
public IAction getTagActionTree(Component comp) {
List<IAction> childActions = new ArrayList<>();
DevelopBranch db = new DevelopBranch(comp);
List<Component> mDeps = db.getMDeps();
for (Component mDep : mDeps) {
childActions.add(getTagActionTree(mDep));
}
return getTagActionTree(comp, childActions);
}
private IAction getTagActionTree(Component comp, List<IAction> childActions) {
DelayedTagsFile cf = new DelayedTagsFile();
IVCS vcs = comp.getVCS();
String delayedRevisionToTag = cf.getRevisitonByUrl(comp.getVcsRepository().getUrl());
if (delayedRevisionToTag == null) {
return new ActionNone(new ReleaseBranch(comp), childActions, "no delayed tags");
}
ReleaseBranch rb = new ReleaseBranch(comp);
List<VCSTag> tagsOnRevision = vcs.getTagsOnRevision(delayedRevisionToTag);
if (tagsOnRevision.isEmpty()) {
return new SCMActionTagRelease(new ReleaseBranch(comp), childActions);
}
Version delayedTagVersion = new Version(vcs.getFileContent(rb.getName(), SCMReleaser.VER_FILE_NAME, delayedRevisionToTag));
for (VCSTag tag : tagsOnRevision) {
if (tag.getTagName().equals(delayedTagVersion.toReleaseString())) {
return new ActionNone(new ReleaseBranch(comp), childActions, "tag " + tag.getTagName() + " already exists");
}
}
return new SCMActionTagRelease(new ReleaseBranch(comp), childActions);
}
}
|
package org.threadly.load;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.threadly.concurrent.future.ListenableFuture;
import org.threadly.util.Clock;
import org.threadly.util.ExceptionHandler;
import org.threadly.util.ExceptionUtils;
import org.threadly.util.StringUtils;
/**
* <p>Class which is designed to invoke a provided {@link ScriptFactory} to build the script. It
* then runs the provided script and informs of any errors which occurred.</p>
*
* @author jent - Mike Jensen
*/
public class ScriptRunner extends AbstractScriptFactoryInitializer {
/**
* Main function, usually executed by the JVM on startup.
*
* @param args Arguments for startup, including which test should run and params for that test
* @throws InterruptedException Thrown if this thread is interrupted while waiting on test to run
*/
public static void main(String[] args) throws InterruptedException {
setupExceptionHandler();
ScriptRunner runner = null;
try {
runner = new ScriptRunner(args);
} catch (Throwable t) {
System.err.println("Unexpected failure when building script: ");
printFailureAndExit(t);
}
System.exit(runner.runScript());
}
/**
* Sets up a default {@link ExceptionHandlerInterface} so that if any uncaught exceptions occur,
* the script will display the exception and exit. There should never be any uncaught
* exceptions, this likely would indicate a bug in Ambush.
*/
protected static void setupExceptionHandler() {
ExceptionUtils.setDefaultExceptionHandler(new ExceptionHandler() {
@Override
public void handleException(Throwable thrown) {
synchronized (this) { // synchronized to prevent terminal corruption from multiple failures
System.err.println("Unexpected uncaught exception: ");
printFailureAndExit(thrown);
}
}
});
}
/**
* Prints the throwable to standard error then exits with a non-zero exit code which matches to
* the throwable's message.
*
* @param t The throwable which caused the failure
*/
protected static void printFailureAndExit(Throwable t) {
t.printStackTrace();
int hashCode = StringUtils.nullToEmpty(t.getMessage()).hashCode();
if (hashCode == 0) {
hashCode = -1;
}
if (hashCode > 0) {
hashCode *= -1;
}
System.exit(hashCode);
}
protected ScriptRunner(String[] args) {
super(args);
}
/**
* Outputs/logs this message/output from the script execution/results. By default this reports
* to {@link System#out}.println(String). This can be overridden to use other loggers.
*
* @param msg String output from runner
*/
protected void out(String msg) {
System.out.println(msg);
}
/**
* Starts the execution of the script. This executes and reports the output to
* {@link #out(String)}. That output includes tracked details during execution like speed and
* success or failures.
*
* @throws InterruptedException Thrown if thread is interrupted during execution
* @return Number of failed steps
*/
protected int runScript() throws InterruptedException {
long start = Clock.accurateForwardProgressingMillis();
List<ListenableFuture<StepResult>> futures = script.startScript();
List<StepResult> fails = StepResultCollectionUtils.getAllFailedResults(futures);
long end = Clock.accurateForwardProgressingMillis();
if (fails.isEmpty()) {
out("All steps passed!");
} else {
Map<String, List<StepResult>> failureCountMap = new HashMap<String, List<StepResult>>();
out(fails.size() + " STEPS FAILED!!" + StringUtils.NEW_LINE);
{
Iterator<StepResult> it = fails.iterator();
while (it.hasNext()) {
StepResult tr = it.next();
String errorMsg = ExceptionUtils.stackToString(tr.getError());
List<StepResult> currentSteps = failureCountMap.get(errorMsg);
if (currentSteps == null) {
currentSteps = new ArrayList<StepResult>(1);
failureCountMap.put(errorMsg, currentSteps);
}
currentSteps.add(tr);
}
}
{
Iterator<Map.Entry<String, List<StepResult>>> it = failureCountMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, List<StepResult>> e = it.next();
if (e.getValue().size() > 1) {
List<String> descriptions = new ArrayList<String>(e.getValue().size());
for (StepResult sr : e.getValue()) {
if (! descriptions.contains(sr.getDescription())) {
descriptions.add(sr.getDescription());
}
}
out("Error occured " + e.getValue().size() + " times for the following steps:");
for (String s : descriptions) {
out('\t' + s);
}
out("All share failure cause:");
} else {
out("Step " + e.getValue().get(0).getDescription() + " failed due to:");
}
out(e.getKey() + StringUtils.NEW_LINE);
}
}
}
int totalExecuted = 0;
for (ListenableFuture<StepResult> f : futures) {
if (! f.isCancelled()) {
totalExecuted++;
}
}
out("Totals steps executed: " + totalExecuted + " / " + futures.size());
out("Test execution time: " + ((end - start) / 1000) + " seconds");
double averageRunMillis = StepResultCollectionUtils.getAverageRuntime(futures, TimeUnit.MILLISECONDS);
out("Average time spent per step: " + averageRunMillis + " milliseconds");
StepResult longestStep = StepResultCollectionUtils.getLongestRuntimeStep(futures);
out("Longest running step: " + longestStep.getDescription() +
", ran for: " + longestStep.getRunTime(TimeUnit.MILLISECONDS) + " milliseconds");
return fails.size();
}
}
|
package rmblworx.tools.timey.gui;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import org.joda.time.LocalDateTime;
public class Alarm implements Comparable<Alarm> {
private final BooleanProperty enabled;
private final ObjectProperty<LocalDateTime> dateTime;
private final StringProperty description;
private final StringProperty sound;
/**
* Initialisiert den Alarm mit der aktuellen Systemzeit.
*/
public Alarm() {
this(LocalDateTime.now().millisOfSecond().setCopy(0), null);
}
public Alarm(final LocalDateTime dateTime, final String description) {
this(dateTime, description, null, true);
}
public Alarm(final LocalDateTime dateTime, final String description, final boolean enabled) {
this(dateTime, description, null, enabled);
}
public Alarm(final LocalDateTime dateTime, final String description, final String sound, final boolean enabled) {
this.enabled = new SimpleBooleanProperty(enabled);
this.dateTime = new SimpleObjectProperty<LocalDateTime>(dateTime);
this.description = new SimpleStringProperty(description);
this.sound = new SimpleStringProperty(sound);
}
public void setEnabled(final boolean enabled) {
this.enabled.set(enabled);
}
public boolean isEnabled() {
return enabled.get();
}
public void setDateTime(final LocalDateTime dateTime) {
this.dateTime.set(dateTime);
}
public LocalDateTime getDateTime() {
return dateTime.get();
}
public void setDescription(final String description) {
this.description.set(description);
}
public String getDescription() {
return description.get();
}
public void setSound(final String sound) {
this.sound.set(sound);
}
public String getSound() {
return sound.get();
}
public int compareTo(final Alarm other) {
return getDateTime().toDateTime().getMillis() > other.getDateTime().toDateTime().getMillis() ? 1 : -1;
}
}
|
//@@author A0147996E-reused
package seedu.address.ui;
import java.util.logging.Logger;
import javafx.application.Platform;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.control.SplitPane;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Region;
import seedu.address.commons.core.LogsCenter;
import seedu.address.commons.events.ui.TaskPanelSelectionChangedEvent;
import seedu.address.commons.util.FxViewUtil;
import seedu.address.model.task.ReadOnlyTask;
/**
* Panel containing the list of tasks.
*/
public class TaskListPanel extends UiPart<Region> {
private final Logger logger = LogsCenter.getLogger(TaskListPanel.class);
private static final String FXML = "TaskListPanel.fxml";
@FXML
private ListView<ReadOnlyTask> taskListView;
public TaskListPanel(AnchorPane taskListPlaceholder, ObservableList<ReadOnlyTask> taskList) {
super(FXML);
setConnections(taskList);
addToPlaceholder(taskListPlaceholder);
}
private void setConnections(ObservableList<ReadOnlyTask> taskList) {
taskListView.setItems(taskList);
taskListView.setCellFactory(listView -> new TaskListViewCell());
setEventHandlerForSelectionChangeEvent();
}
private void addToPlaceholder(AnchorPane placeHolderPane) {
SplitPane.setResizableWithParent(placeHolderPane, false);
FxViewUtil.applyAnchorBoundaryParameters(getRoot(), 0.0, 0.0, 0.0, 0.0);
placeHolderPane.getChildren().add(getRoot());
}
private void setEventHandlerForSelectionChangeEvent() {
taskListView.getSelectionModel().selectedItemProperty()
.addListener((observable, oldValue, newValue) -> {
if (newValue != null) {
logger.fine("Selection in task list panel changed to : '" + newValue + "'");
raise(new TaskPanelSelectionChangedEvent(newValue));
}
});
}
public void scrollTo(int index) {
Platform.runLater(() -> {
taskListView.scrollTo(index);
taskListView.getSelectionModel().clearAndSelect(index);
});
}
class TaskListViewCell extends ListCell<ReadOnlyTask> {
@Override
protected void updateItem(ReadOnlyTask task, boolean empty) {
super.updateItem(task, empty);
if (empty || task == null) {
setGraphic(null);
setText(null);
} else {
taskListView.scrollTo(getIndex() + 1);
setGraphic(new TaskListCard(task, getIndex() + 1).getRoot());
}
}
}
}
|
package edu.northwestern.bioinformatics.studycalendar.utils.accesscontrol;
import edu.northwestern.bioinformatics.studycalendar.StudyCalendarError;
import edu.northwestern.bioinformatics.studycalendar.StudyCalendarSystemException;
import edu.northwestern.bioinformatics.studycalendar.domain.Study;
import edu.northwestern.bioinformatics.studycalendar.domain.StudySite;
import edu.northwestern.bioinformatics.studycalendar.utils.DomainObjectTools;
import gov.nih.nci.security.UserProvisioningManager;
import gov.nih.nci.security.authorization.domainobjects.Group;
import gov.nih.nci.security.authorization.domainobjects.ProtectionElement;
import gov.nih.nci.security.authorization.domainobjects.ProtectionGroup;
import gov.nih.nci.security.authorization.domainobjects.ProtectionGroupRoleContext;
import gov.nih.nci.security.authorization.domainobjects.Role;
import gov.nih.nci.security.authorization.domainobjects.User;
import gov.nih.nci.security.dao.ProtectionGroupSearchCriteria;
import gov.nih.nci.security.dao.RoleSearchCriteria;
import gov.nih.nci.security.dao.SearchCriteria;
import gov.nih.nci.security.dao.UserSearchCriteria;
import gov.nih.nci.security.exceptions.CSObjectNotFoundException;
import gov.nih.nci.security.exceptions.CSTransactionException;
import gov.nih.nci.security.util.ObjectSetUtil;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.LinkedHashSet;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* @author Padmaja Vedula
* @author Rhett Sutphin
*/
// TODO: None of these methods should throw checked exceptions
public class StudyCalendarAuthorizationManager {
public static final String APPLICATION_CONTEXT_NAME = "study_calendar";
public static final String BASE_SITE_PG = "BaseSitePG";
public static final String ASSIGNED_USERS = "ASSIGNED_USERS";
public static final String AVAILABLE_USERS = "AVAILABLE_USERS";
public static final String ASSIGNED_PGS = "ASSIGNED_PGS";
public static final String AVAILABLE_PGS = "AVAILABLE_PGS";
public static final String ASSIGNED_PES = "ASSIGNED_PES";
public static final String AVAILABLE_PES = "AVAILABLE_PES";
public static final String PARTICIPANT_COORDINATOR_GROUP = "PARTICIPANT_COORDINATOR";
public static final String SITE_COORDINATOR_GROUP = "SITE_COORDINATOR";
private static Log log = LogFactory.getLog(StudyCalendarAuthorizationManager.class);
private UserProvisioningManager userProvisioningManager;
public void assignProtectionElementsToUsers(List<String> userIds, String protectionElementObjectId) throws Exception
{
boolean protectionElementPresent = false;
ProtectionElement pElement = new ProtectionElement();
try {
pElement = userProvisioningManager.getProtectionElement(protectionElementObjectId);
protectionElementPresent = true;
} catch (CSObjectNotFoundException ex){
ProtectionElement newProtectionElement = new ProtectionElement();
newProtectionElement.setObjectId(protectionElementObjectId);
newProtectionElement.setProtectionElementName(protectionElementObjectId);
userProvisioningManager.createProtectionElement(newProtectionElement);
pElement = userProvisioningManager.getProtectionElement(protectionElementObjectId);
//userProvisioningManager.setOwnerForProtectionElement(protectionElementObjectId, userIds.toArray(new String[0]));
//userProvisioningManager.assignOwners(protectionElementObjectId, userIds.toArray(new String[0]));
}
userProvisioningManager.assignOwners(pElement.getProtectionElementId().toString(), userIds.toArray(new String[0]));
/*if (protectionElementPresent)
{
if (log.isDebugEnabled()) {
log.debug(" The given Protection Element: " + userProvisioningManager.getProtectionElement(protectionElementObjectId).getProtectionElementName()+ "is present in Database");
}
for (String userId : userIds)
{
String userName = getUserObject(userId).getLoginName();
if (!(userProvisioningManager.checkOwnership((String)userName, protectionElementObjectId)))
{
if (log.isDebugEnabled()) {
log.debug(" Given Protection Element: " + userProvisioningManager.getProtectionElement(protectionElementObjectId).getProtectionElementName()+ "is not owned by " + userName);
}
userProvisioningManager.setOwnerForProtectionElement((String)userName, protectionElementObjectId, userProvisioningManager.getProtectionElement(protectionElementObjectId).getAttribute());
} else {
if (log.isDebugEnabled()) {
log.debug(" Given Protection Element: " + userProvisioningManager.getProtectionElement(protectionElementObjectId).getProtectionElementName()+ "is owned by " + userName);
}
}
}
}*/
}
public void assignMultipleProtectionElements(String userId, List<String> protectionElementObjectIds) throws Exception
{
boolean protectionElementPresent = false;
String userName = getUserObject(userId).getLoginName();
for (String protectionElementObjectId : protectionElementObjectIds) {
try {
userProvisioningManager.getProtectionElement(protectionElementObjectId);
protectionElementPresent = true;
} catch (CSObjectNotFoundException ex){
ProtectionElement newProtectionElement = new ProtectionElement();
newProtectionElement.setObjectId(protectionElementObjectId);
newProtectionElement.setProtectionElementName(protectionElementObjectId);
userProvisioningManager.createProtectionElement(newProtectionElement);
//protection element attribute name is set to be the same as protection element object id
userProvisioningManager.setOwnerForProtectionElement(userName, protectionElementObjectId, protectionElementObjectId);
}
if (protectionElementPresent)
{
if (log.isDebugEnabled()) {
log.debug(" The given Protection Element: " + userProvisioningManager.getProtectionElement(protectionElementObjectId).getProtectionElementName()+ "is present in Database");
}
if (!(userProvisioningManager.checkOwnership(userName, protectionElementObjectId)))
{
if (log.isDebugEnabled()) {
log.debug(" Given Protection Element: " + userProvisioningManager.getProtectionElement(protectionElementObjectId).getProtectionElementName()+ "is not owned by " + userName);
}
userProvisioningManager.setOwnerForProtectionElement(userName, protectionElementObjectId, userProvisioningManager.getProtectionElement(protectionElementObjectId).getAttribute());
} else {
if (log.isDebugEnabled())
log.debug(" Given Protection Element: " + userProvisioningManager.getProtectionElement(protectionElementObjectId).getProtectionElementName()+ "is owned by " + userName);
}
}
}
}
//get users of a group, associated with a protection element, and also those not associated
public Map getUsers(String groupName, String pgId, String pgName) throws Exception {
HashMap<String, List> usersMap = new HashMap<String, List>();
List<User> usersForRequiredGroup = getUsersForGroup(groupName);
usersMap = (HashMap) getUserListsForProtectionElement(usersForRequiredGroup, pgId, pgName);
return usersMap;
}
private Map getUserListsForProtectionElement(List<User> users, String pgpeId, String pgName) throws Exception {
HashMap<String, List> userHashMap = new HashMap<String, List>();
List<User> assignedUsers = new ArrayList<User>();
List<User> availableUsers = new ArrayList<User>();
ProtectionGroup pGroup = getPGByName(pgName);
List<User> usersForSite = new ArrayList<User>();
for (User user : users) {
Set<ProtectionGroupRoleContext> pgRoleContext = getProtectionGroupRoleContexts(user);
for (ProtectionGroupRoleContext pgrc : pgRoleContext) {
if (pgrc.getProtectionGroup().getProtectionGroupName().equals(pgName)) {
usersForSite.add(user);
}
}
}
for (User userSite : usersForSite) {
Set<ProtectionGroupRoleContext> userSiteRoleContext = getProtectionGroupRoleContexts(userSite);
for (ProtectionGroupRoleContext pgrcSite : userSiteRoleContext) {
if (pgrcSite.getProtectionGroup().getProtectionGroupName().equals(pgpeId)) {
assignedUsers.add(userSite);
}
}
}
availableUsers = (List) ObjectSetUtil.minus(usersForSite, assignedUsers);
userHashMap.put(ASSIGNED_USERS, assignedUsers);
userHashMap.put(AVAILABLE_USERS, availableUsers);
return userHashMap;
}
public User getUserObject(String id) throws Exception {
User user = null;
user = userProvisioningManager.getUserById(id);
return user;
}
public void createProtectionGroup(String newProtectionGroup, String parentPG) throws Exception {
if (parentPG != null) {
ProtectionGroup parentGroupSearch = new ProtectionGroup();
parentGroupSearch.setProtectionGroupName(parentPG);
SearchCriteria protectionGroupSearchCriteria = new ProtectionGroupSearchCriteria(parentGroupSearch);
List parentGroupList = userProvisioningManager.getObjects(protectionGroupSearchCriteria);
if (parentGroupList.size() > 0) {
ProtectionGroup parentProtectionGroup = (ProtectionGroup) parentGroupList.get(0);
ProtectionGroup requiredProtectionGroup = new ProtectionGroup();
requiredProtectionGroup.setProtectionGroupName(newProtectionGroup);
requiredProtectionGroup.setParentProtectionGroup(parentProtectionGroup);
userProvisioningManager.createProtectionGroup(requiredProtectionGroup);
if (log.isDebugEnabled()) {
log.debug("new protection group created " + newProtectionGroup);
}
}
}
}
/**
* Method to retrieve all site protection groups
*
*/
public List getSites() throws Exception {
List<ProtectionGroup> siteList = new ArrayList<ProtectionGroup>() ;
ProtectionGroup protectionGroup = new ProtectionGroup();
SearchCriteria pgSearchCriteria = new ProtectionGroupSearchCriteria(protectionGroup);
List<ProtectionGroup> pgList = userProvisioningManager.getObjects(pgSearchCriteria);
if (pgList.size() > 0) {
for (ProtectionGroup requiredProtectionGroup : pgList) {
if ((requiredProtectionGroup.getParentProtectionGroup()!=null) && (isSitePG(requiredProtectionGroup))) {
siteList.add(requiredProtectionGroup);
}
}
}
return siteList;
}
/**
* Method to retrieve a site protection group
* @param name
* @return null or site Protection Group
*
*/
public ProtectionGroup getPGByName(String name) throws Exception {
ProtectionGroup requiredProtectionGroup = null;
ProtectionGroup protectionGroupSearch = new ProtectionGroup();
protectionGroupSearch.setProtectionGroupName(name);
SearchCriteria protectionGroupSearchCriteria = new ProtectionGroupSearchCriteria(protectionGroupSearch);
List<ProtectionGroup> protectionGroupList = userProvisioningManager.getObjects(protectionGroupSearchCriteria);
if (protectionGroupList.size() > 0) {
requiredProtectionGroup = protectionGroupList.get(0);
}
return requiredProtectionGroup;
}
public List<User> getUsersForGroup(String groupName) {
List<User> usersForRequiredGroup = new ArrayList<User>();
User user = new User();
SearchCriteria userSearchCriteria = new UserSearchCriteria(user);
List<User> userList = userProvisioningManager.getObjects(userSearchCriteria);
for (User requiredUser : userList) {
Set<Group> userGroups = getGroups(requiredUser);
for (Group userGroup : userGroups) {
if (userGroup.getGroupName().equals(groupName)) {
usersForRequiredGroup.add(requiredUser);
break;
}
}
}
return usersForRequiredGroup;
}
/**
* Method to retrieve users who have the given protection group assigned to them.
* (can be used for retrieving site coordinators for site protection groups)
* @param group
* @param protectionGroupName
* @return
* @throws Exception
*/
public Map getUserPGLists(String group, String protectionGroupName) throws Exception {
List<User> usersForRequiredGroup = getUsersForGroup(group);
return getUserListsForProtectionGroup(usersForRequiredGroup, protectionGroupName);
}
/**
*
* @param users
* @param protectionGroupName
* @return
* @throws Exception
*/
private Map getUserListsForProtectionGroup(List<User> users, String protectionGroupName) throws Exception {
HashMap<String, List> userHashMap = new HashMap<String, List>();
List<User> assignedUsers = new ArrayList<User>();
List<User> availableUsers = new ArrayList<User>();
for (User user : users)
{
boolean isAssigned = false;
Set<ProtectionGroupRoleContext> pgRoleContext = getProtectionGroupRoleContexts(user);
List<ProtectionGroupRoleContext> pgRoleContextList = new ArrayList(pgRoleContext);
if (pgRoleContextList.size() != 0) {
for (ProtectionGroupRoleContext pgrc : pgRoleContextList) {
if (pgrc.getProtectionGroup().getProtectionGroupName().equals(protectionGroupName)) {
assignedUsers.add(user);
isAssigned = true;
break;
}
}
if (!isAssigned) {
availableUsers.add(user);
}
} else {
availableUsers.add(user);
}
}
userHashMap.put(ASSIGNED_USERS, assignedUsers);
userHashMap.put(AVAILABLE_USERS, availableUsers);
return userHashMap;
}
public void assignProtectionGroupsToUsers(List<String> userIds, ProtectionGroup protectionGroup, String roleName) throws Exception
{
Role role = new Role();
role.setName(roleName);
SearchCriteria roleSearchCriteria = new RoleSearchCriteria(role);
List roleList = userProvisioningManager.getObjects(roleSearchCriteria);
if (roleList.size() > 0) {
Role accessRole = (Role) roleList.get(0);
String[] roleIds = new String[] {accessRole.getId().toString()};
for (String userId : userIds)
{
userProvisioningManager.assignUserRoleToProtectionGroup(userId, roleIds, protectionGroup.getProtectionGroupId().toString());
}
}
}
public void removeProtectionGroupUsers(List<String> userIds, ProtectionGroup protectionGroup) throws Exception
{
if (!((userIds.size() == 1) && (userIds.get(0).equals("")))) {
for (String userId : userIds)
{
userProvisioningManager.removeUserFromProtectionGroup(protectionGroup.getProtectionGroupId().toString(), userId);
}
}
}
public void assignProtectionElementToPGs(List<String> pgIdsList, String protectionElementId) throws Exception {
ProtectionElement requiredPE;
try {
requiredPE = userProvisioningManager.getProtectionElement(protectionElementId);
} catch (CSObjectNotFoundException ex){
ProtectionElement newProtectionElement = new ProtectionElement();
newProtectionElement.setObjectId(protectionElementId);
newProtectionElement.setProtectionElementName(protectionElementId);
userProvisioningManager.createProtectionElement(newProtectionElement);
requiredPE = userProvisioningManager.getProtectionElement(protectionElementId);
}
List<ProtectionGroup> assignedPGs = new ArrayList<ProtectionGroup>();
List<String> pgIds = new ArrayList<String>();
try
{
Long peId = userProvisioningManager.getProtectionElement(protectionElementId).getProtectionElementId();
Set<ProtectionGroup> protectionGroupsForPE = userProvisioningManager.getProtectionGroups(peId.toString());
for (ProtectionGroup protectionGroupForPE : protectionGroupsForPE) {
if (protectionGroupForPE.getParentProtectionGroup() != null) {
if (isSitePG(protectionGroupForPE)) {
assignedPGs.add(protectionGroupForPE);
}
}
}
} catch (CSObjectNotFoundException cse) {
if (log.isDebugEnabled()) {
log.debug("no assigned protectiongroups for this protection element");
}
}
for (ProtectionGroup assignedPG : assignedPGs) {
pgIds.add(assignedPG.getProtectionGroupId().toString());
}
pgIds.addAll(pgIdsList);
userProvisioningManager.assignToProtectionGroups(requiredPE.getProtectionElementId().toString(), pgIds.toArray(new String[0]));
}
public void registerUrl(String url, List<String> protectionGroups) {
if (log.isDebugEnabled()) log.debug("Attempting to register PE for " + url + " in " + protectionGroups);
ProtectionElement element = getOrCreateProtectionElement(url);
syncProtectionGroups(element, protectionGroups);
}
private ProtectionElement getOrCreateProtectionElement(String objectId) {
ProtectionElement element = null;
try {
element = userProvisioningManager.getProtectionElement(objectId);
log.debug("PE for " + objectId + " found");
} catch (CSObjectNotFoundException e) {
log.debug("PE for " + objectId + " not found");
// continue
}
if (element == null) {
element = new ProtectionElement();
element.setObjectId(objectId);
element.setProtectionElementName(objectId);
element.setProtectionElementDescription("Autogenerated PE for " + objectId);
try {
userProvisioningManager.createProtectionElement(element);
} catch (CSTransactionException e) {
throw new StudyCalendarSystemException("Creating PE for " + objectId + " failed", e);
}
try {
element = userProvisioningManager.getProtectionElement(element.getObjectId());
} catch (CSObjectNotFoundException e) {
throw new StudyCalendarSystemException("Reloading just-created PE for " + element.getObjectId() + " failed", e);
}
}
return element;
}
private void syncProtectionGroups(ProtectionElement element, List<String> desiredProtectionGroups) {
Set<ProtectionGroup> existingGroups;
try {
existingGroups = userProvisioningManager.getProtectionGroups(element.getProtectionElementId().toString());
} catch (CSObjectNotFoundException e) {
throw new StudyCalendarError("Could not find groups for just-created/loaded PE", e);
}
// if they're all the same, we don't need to do anything
if (existingGroups.size() == desiredProtectionGroups.size()) {
List<String> existingNames = new ArrayList<String>(existingGroups.size());
for (ProtectionGroup existingGroup : existingGroups) existingNames.add(existingGroup.getProtectionGroupName());
if (log.isDebugEnabled()) log.debug(element.getObjectId() + " currently in " + desiredProtectionGroups);
if (existingNames.containsAll(desiredProtectionGroups)) {
log.debug("Sync requires no changes");
return;
}
}
if (log.isDebugEnabled()) log.debug("Setting groups for " + element.getObjectId() + " to " + desiredProtectionGroups);
// accumulate IDs from names
// Seriously -- there's no way to look them up by name
List<ProtectionGroup> allGroups = userProvisioningManager.getProtectionGroups();
List<String> desiredGroupIds = new ArrayList<String>(desiredProtectionGroups.size());
for (ProtectionGroup group : allGroups) {
if (desiredProtectionGroups.contains(group.getProtectionGroupName())) {
desiredGroupIds.add(group.getProtectionGroupId().toString());
}
}
// warn about missing groups, if any
if (desiredGroupIds.size() != desiredProtectionGroups.size()) {
List<String> missingGroups = new LinkedList<String>(desiredProtectionGroups);
for (ProtectionGroup group : allGroups) {
String name = group.getProtectionGroupName();
if (missingGroups.contains(name)) missingGroups.remove(name);
}
log.warn("Requested protection groups included one or more that don't exist: " + missingGroups + ". These groups were skipped.");
}
try {
userProvisioningManager.assignToProtectionGroups(
element.getProtectionElementId().toString(), desiredGroupIds.toArray(new String[0]));
} catch (CSTransactionException e) {
throw new StudyCalendarSystemException("Assigning PE " + element.getProtectionElementName() + " to groups " + desiredProtectionGroups + " failed", e);
}
}
public Map getProtectionGroups(List<ProtectionGroup> allProtectionGroups, String protectionElementObjectId) throws Exception {
HashMap<String, List> pgHashMap = new HashMap<String, List>();
List<ProtectionGroup> assignedPGs = new ArrayList<ProtectionGroup>();
List<ProtectionGroup> availablePGs = new ArrayList<ProtectionGroup>();
try
{
Long peId = userProvisioningManager.getProtectionElement(protectionElementObjectId).getProtectionElementId();
Set<ProtectionGroup> protectionGroupsForPE = userProvisioningManager.getProtectionGroups(peId.toString());
for (ProtectionGroup protectionGroupForPE : protectionGroupsForPE) {
if (protectionGroupForPE.getParentProtectionGroup() != null) {
if (isSitePG(protectionGroupForPE)) {
assignedPGs.add(protectionGroupForPE);
}
}
}
} catch (CSObjectNotFoundException cse) {
if (log.isDebugEnabled()) {
log.debug("no assigned protectiongroups for this protection element");
}
}
availablePGs = (List) ObjectSetUtil.minus(allProtectionGroups, assignedPGs);
pgHashMap.put(ASSIGNED_PGS, assignedPGs);
pgHashMap.put(AVAILABLE_PGS, availablePGs);
return pgHashMap;
}
public Map getPEForUserProtectionGroup(String pgName, String userId) throws Exception {
HashMap<String, List> peHashMap = new HashMap<String, List>();
List<ProtectionElement> assignedPEs = new ArrayList<ProtectionElement>();
List<ProtectionElement> availablePEs = new ArrayList<ProtectionElement>();
Set<ProtectionElement> allAssignedPEsForPGs = userProvisioningManager.getProtectionElements(getPGByName(pgName).getProtectionGroupId().toString());
for (ProtectionElement userPE : allAssignedPEsForPGs) {
String userName = getUserObject(userId).getLoginName();
if (userProvisioningManager.checkOwnership(userName, userPE.getObjectId()))
{
assignedPEs.add(userPE);
}
}
availablePEs = (List) ObjectSetUtil.minus(allAssignedPEsForPGs, assignedPEs);
peHashMap.put(ASSIGNED_PES, assignedPEs);
peHashMap.put(AVAILABLE_PES, availablePEs);
return peHashMap;
}
public List<ProtectionGroup> getSitePGsForUser(String userName) {
return getSitePGs(userProvisioningManager.getUser(userName));
}
public List<ProtectionGroup> getStudySitePGsForUser(String userName) {
User user = userProvisioningManager.getUser(userName);
List<ProtectionGroup> studySitePGs = new ArrayList<ProtectionGroup>();
for (Group group : getGroups(user)) {
if (group.getGroupName().equals(PARTICIPANT_COORDINATOR_GROUP)) {
Set<ProtectionGroupRoleContext> pgRoleContexts = getProtectionGroupRoleContexts(user);
for (ProtectionGroupRoleContext pgrc : pgRoleContexts) {
if (isStudySitePG(pgrc.getProtectionGroup())) {
studySitePGs.add(pgrc.getProtectionGroup());
}
}
}
}
return studySitePGs;
}
public void removeProtectionElementFromPGs(List<String> removePGs, String protectionElementObjectId) throws Exception {
List<ProtectionGroup> assignedPGs = new ArrayList<ProtectionGroup>();
List<String> pgIds = new ArrayList<String>();
ProtectionElement requiredPE;
try
{
Long peId = userProvisioningManager.getProtectionElement(protectionElementObjectId).getProtectionElementId();
Set<ProtectionGroup> protectionGroupsForPE = userProvisioningManager.getProtectionGroups(peId.toString());
for (ProtectionGroup protectionGroupForPE : protectionGroupsForPE) {
if (protectionGroupForPE.getParentProtectionGroup() != null) {
if (isSitePG(protectionGroupForPE)) {
assignedPGs.add(protectionGroupForPE);
}
}
}
} catch (CSObjectNotFoundException cse) {
if (log.isDebugEnabled()) {
log.debug("no assigned protectiongroups for this protection element");
}
}
for (ProtectionGroup assignedPG : assignedPGs) {
pgIds.add(assignedPG.getProtectionGroupId().toString());
}
List<String> newList = (List) ObjectSetUtil.minus(pgIds, removePGs);
requiredPE = userProvisioningManager.getProtectionElement(protectionElementObjectId);
userProvisioningManager.assignToProtectionGroups(requiredPE.getProtectionElementId().toString(), newList.toArray(new String[0]));
}
public List<Study> checkOwnership(String userName, List<Study> studies) {
Set<Study> assignedStudies = new LinkedHashSet<Study>();
User userTemplate = new User();
userTemplate.setLoginName(userName);
SearchCriteria userSearchCriteria = new UserSearchCriteria(userTemplate);
List<User> userList = userProvisioningManager.getObjects(userSearchCriteria);
if (userList.size() > 0) {
User user = userList.get(0);
Set<Group> userGroups = getGroups(user);
if (userGroups.size() > 0) {
Group requiredGroup = userGroups.iterator().next();
if (requiredGroup.getGroupName().equals(PARTICIPANT_COORDINATOR_GROUP)) {
for (Study study : studies) {
if (checkParticipantCoordinatorOwnership(user, study)) {
assignedStudies.add(study);
}
}
} else if (requiredGroup.getGroupName().equals(SITE_COORDINATOR_GROUP)) {
List<ProtectionGroup> sites = getSitePGs(user);
for (Study study : studies) {
if (checkSiteCoordinatorOwnership(study, sites)) {
assignedStudies.add(study);
}
}
} else {
assignedStudies.addAll(studies);
}
}
}
return new ArrayList<Study>(assignedStudies);
}
public void removeProtectionGroup(String protectionGroupName) throws Exception {
ProtectionGroup pg = new ProtectionGroup();
pg.setProtectionGroupName(protectionGroupName);
SearchCriteria pgSearchCriteria = new ProtectionGroupSearchCriteria(pg);
List<ProtectionGroup> pgList = userProvisioningManager.getObjects(pgSearchCriteria);
if (pgList.size() > 0) {
userProvisioningManager.removeProtectionGroup(pgList.get(0).getProtectionGroupId().toString());
}
}
public void createAndAssignPGToUser(List<String> userIds, String protectionGroupName, String roleName) throws Exception {
ProtectionGroup pg = new ProtectionGroup();
pg.setProtectionGroupName(protectionGroupName);
SearchCriteria pgSearchCriteria = new ProtectionGroupSearchCriteria(pg);
List<ProtectionGroup> pgList = userProvisioningManager.getObjects(pgSearchCriteria);
if (pgList.size() <= 0) {
ProtectionGroup requiredProtectionGroup = new ProtectionGroup();
requiredProtectionGroup.setProtectionGroupName(protectionGroupName);
userProvisioningManager.createProtectionGroup(requiredProtectionGroup);
}
Role role = new Role();
role.setName(roleName);
SearchCriteria roleSearchCriteria = new RoleSearchCriteria(role);
List roleList = userProvisioningManager.getObjects(roleSearchCriteria);
if (roleList.size() > 0) {
Role accessRole = (Role) roleList.get(0);
String[] roleIds = new String[] {accessRole.getId().toString()};
if (!((userIds.size() == 1) && (userIds.get(0).equals("")))) {
for (String userId : userIds)
{
userProvisioningManager.assignUserRoleToProtectionGroup(userId, roleIds, getPGByName(protectionGroupName).getProtectionGroupId().toString());
}
}
}
}
public boolean isUserPGAssigned(String pgName, String userId) throws Exception {
Set<ProtectionGroupRoleContext> pgRoleContext = userProvisioningManager.getProtectionGroupRoleContextForUser(userId);
List<ProtectionGroupRoleContext> pgRoleContextList = new ArrayList<ProtectionGroupRoleContext> (pgRoleContext);
if (pgRoleContextList.size() != 0) {
for (ProtectionGroupRoleContext pgrc : pgRoleContextList) {
if (pgrc.getProtectionGroup().getProtectionGroupName().equals(pgName)) {
return true;
}
}
}
return false;
}
public User getUserForLogin(String userName) {
return userProvisioningManager.getUser(userName);
}
////// INTERNAL HELPERS
private List<ProtectionGroup> getSitePGs(User user) {
List<ProtectionGroup> sites = new ArrayList<ProtectionGroup>();
Set<ProtectionGroupRoleContext> pgRoleContext = getProtectionGroupRoleContexts(user);
if (pgRoleContext.size() != 0) {
for (ProtectionGroupRoleContext pgrc : pgRoleContext) {
if (isSitePG(pgrc.getProtectionGroup())) {
sites.add(pgrc.getProtectionGroup());
}
}
}
return sites;
}
private boolean checkSiteCoordinatorOwnership(Study study, List<ProtectionGroup> sites) {
List<StudySite> studySites = study.getStudySites();
for (StudySite studySite : studySites) {
for (ProtectionGroup site : sites) {
if (studySite.getSite().getName().equals(site.getProtectionGroupName())) {
return true;
}
}
}
return false;
}
private boolean checkParticipantCoordinatorOwnership(User user, Study study) {
String userName = user.getLoginName();
List<StudySite> studySites = study.getStudySites();
for (StudySite studySite : studySites) {
String protectionGroupName = DomainObjectTools.createExternalObjectId(studySite);
Set<ProtectionGroupRoleContext> pgRoleContext = getProtectionGroupRoleContexts(user);
if (pgRoleContext.size() != 0) {
for (ProtectionGroupRoleContext pgrc : pgRoleContext) {
if (pgrc.getProtectionGroup().getProtectionGroupName().equals(protectionGroupName)) {
return true;
}
}
}
}
return userProvisioningManager.checkOwnership(userName, DomainObjectTools.createExternalObjectId(study));
}
private Set<Group> getGroups(User user) {
try {
return userProvisioningManager.getGroups(user.getUserId().toString());
} catch (CSObjectNotFoundException e) {
throw new StudyCalendarSystemException("Could not get groups for " + user.getLoginName(), e);
}
}
private Set<ProtectionGroupRoleContext> getProtectionGroupRoleContexts(User user) {
try {
return userProvisioningManager.getProtectionGroupRoleContextForUser(user.getUserId().toString());
} catch (CSObjectNotFoundException e) {
throw new StudyCalendarSystemException("Could not find PGRCs for " + user.getLoginName(), e);
}
}
private boolean isSitePG(ProtectionGroup protectionGroup) {
ProtectionGroup parentPG = protectionGroup.getParentProtectionGroup();
return parentPG != null && parentPG.getProtectionGroupName().equals(BASE_SITE_PG);
}
private boolean isStudySitePG(ProtectionGroup protectionGroup) {
return protectionGroup.getProtectionGroupName().startsWith(StudySite.class.getName());
}
////// CONFIGURATION
public void setUserProvisioningManager(UserProvisioningManager userProvisioningManager) {
this.userProvisioningManager = userProvisioningManager;
}
}
|
package tigase.server.bosh;
import tigase.server.Command;
import tigase.server.Packet;
import tigase.util.TigaseStringprepException;
import tigase.xml.Element;
import tigase.xmpp.Authorization;
import tigase.xmpp.JID;
import tigase.xmpp.PacketErrorTypeException;
import tigase.xmpp.StanzaType;
import static tigase.server.bosh.Constants.*;
import java.util.Collections;
import java.util.List;
import java.util.Queue;
import java.util.TimerTask;
import java.util.UUID;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
/**
* Describe class BoshSession here.
*
*
* Created: Tue Jun 5 18:07:23 2007
*
* @author <a href="mailto:artur.hefczyc@tigase.org">Artur Hefczyc</a>
* @version $Rev$
*/
public class BoshSession {
/**
* Variable <code>log</code> is a class logger.
*/
private static final Logger log = Logger.getLogger("tigase.server.bosh.BoshSession");
private static final long SECOND = 1000;
private static final String PRESENCE_ELEMENT_NAME = "presence";
private static final String MESSAGE_ELEMENT_NAME = "message";
private static final String IQ_ELEMENT_NAME = "iq";
private BoshSessionCache cache = null;
/**
* <code>current_rid</code> is the table with body rids which are waiting for
* replies.
*/
private long[] currentRids = null;
private JID dataReceiver = null;
private String domain = null;
private BoshSessionTaskHandler handler = null;
private int[] hashCodes = null;
private TimerTask inactivityTimer = null;
private long previous_received_rid = -1;
private String[] replace_with = {
"$1<a href=\"http://$2\" target=\"_blank\">$2</a>",
"$1<a href=\"$2\" target=\"_blank\">$2</a>", };
private int rids_head = 0;
private int rids_tail = 0;
private String sessionId = null;
private UUID sid = null;
// Old connections which might be reused in keep-alive mode.
// Requests have been responded to so in most cases the connection should
// be closed unless it is reused in keep-alive mode.
// Normally there should be no more than max 2 elements in the queue.
private Queue<BoshIOService> old_connections =
new LinkedBlockingQueue<BoshIOService>(4);
// Active connections with pending requests received
private Queue<BoshIOService> connections = new ConcurrentLinkedQueue<BoshIOService>();
// private enum TimedTask { EMPTY_RESP, STOP };
// private Map<TimerTask, TimedTask> task_enum =
// new LinkedHashMap<TimerTask, TimedTask>();
// private EnumMap<TimedTask, TimerTask> enum_task =
// new EnumMap<TimedTask, TimerTask>(TimedTask.class);
private TimerTask waitTimer = null;
private Queue<Element> waiting_packets = new ConcurrentLinkedQueue<Element>();
private boolean terminate = false;
private long min_polling = MIN_POLLING_PROP_VAL;
private long max_wait = MAX_WAIT_DEF_PROP_VAL;
private long max_pause = MAX_PAUSE_PROP_VAL;
private long max_inactivity = MAX_INACTIVITY_PROP_VAL;
private Pattern[] links_regexs = {
Pattern.compile("([^>/\";]|^)(www\\.[^ ]+)", Pattern.CASE_INSENSITIVE),
Pattern.compile("([^\">;]|^)(http://[^ ]+)", Pattern.CASE_INSENSITIVE), };
private int hold_requests = HOLD_REQUESTS_PROP_VAL;
private String content_type = CONTENT_TYPE_DEF;
private int concurrent_requests = CONCURRENT_REQUESTS_PROP_VAL;
private boolean cache_on = false;
/**
* Creates a new <code>BoshSession</code> instance.
*
*
* @param def_domain
* @param dataReceiver
* @param handler
*/
public BoshSession(String def_domain, JID dataReceiver, BoshSessionTaskHandler handler) {
this.sid = UUID.randomUUID();
this.domain = def_domain;
this.dataReceiver = dataReceiver;
this.handler = handler;
}
/**
* Method description
*
*/
public void close() {
terminate = true;
processPacket(null, null);
closeAllConnections();
}
private void closeAllConnections() {
for (BoshIOService conn : old_connections) {
conn.stop();
}
for (BoshIOService conn : connections) {
conn.stop();
}
}
/**
* Method description
*
*
* @param bios
*/
public void disconnected(BoshIOService bios) {
if (log.isLoggable(Level.FINEST)) {
log.finest("Disconnected called for: " + bios.getUniqueId());
}
if (bios != null) {
connections.remove(bios);
}
if (inactivityTimer != null) {
if (log.isLoggable(Level.FINEST)) {
log.finest("Canceling inactivityTimer: " + getSid());
}
handler.cancelTask(inactivityTimer);
}
if (connections.size() == 0) {
if (log.isLoggable(Level.FINEST)) {
log.finest("Setting inactivityTimer for " + max_inactivity + ": " + getSid());
}
inactivityTimer = handler.scheduleTask(this, max_inactivity * SECOND);
}
}
/**
* Method description
*
*
* @return
*/
public JID getDataReceiver() {
return dataReceiver;
}
/**
* Method description
*
*
* @return
*/
public String getDomain() {
return domain;
}
/**
* Method description
*
*
* @return
*/
public String getSessionId() {
return sessionId;
}
/**
* Method description
*
*
* @return
*/
public UUID getSid() {
return sid;
}
/**
* Method description
*
*
* @param packet
* @param service
* @param max_wait
* @param min_polling
* @param max_inactivity
* @param concurrent_requests
* @param hold_requests
* @param max_pause
* @param out_results
*/
public void init(Packet packet, BoshIOService service, long max_wait, long min_polling,
long max_inactivity, int concurrent_requests, int hold_requests, long max_pause,
Queue<Packet> out_results) {
String cache_action = packet.getAttribute(CACHE_ATTR);
if ((cache_action != null) && cache_action.equals(CacheAction.on.toString())) {
cache = new BoshSessionCache();
cache_on = true;
log.fine("BoshSessionCache set to ON");
}
hashCodes = new int[(this.concurrent_requests + 1) * 5];
currentRids = new long[(this.concurrent_requests + 1) * 5];
for (int i = 0; i < currentRids.length; i++) {
currentRids[i] = -1;
hashCodes[i] = -1;
}
long wait_l = max_wait;
String wait_s = packet.getAttribute(WAIT_ATTR);
if (wait_s != null) {
try {
wait_l = Long.parseLong(wait_s);
} catch (NumberFormatException e) {
wait_l = max_wait;
}
}
this.max_wait = Math.min(wait_l, max_wait);
// this.max_wait = wait_l;
int hold_i = hold_requests;
String tmp_str = packet.getAttribute(HOLD_ATTR);
if (tmp_str != null) {
try {
hold_i = Integer.parseInt(tmp_str);
} catch (NumberFormatException e) {
hold_i = hold_requests;
}
}
tmp_str = packet.getAttribute(RID_ATTR);
if (tmp_str != null) {
try {
previous_received_rid = Long.parseLong(tmp_str);
currentRids[rids_head++] = previous_received_rid;
} catch (NumberFormatException e) {
}
}
this.hold_requests = Math.max(hold_i, hold_requests);
if (packet.getAttribute(TO_ATTR) != null) {
this.domain = packet.getAttribute(TO_ATTR);
}
this.min_polling = min_polling;
this.max_inactivity = max_inactivity;
this.concurrent_requests = concurrent_requests;
this.max_pause = max_pause;
if (packet.getAttribute(CONTENT_ATTR) != null) {
content_type = packet.getAttribute(CONTENT_ATTR);
}
String lang = packet.getAttribute(LANG_ATTR);
if (lang == null) {
lang = "en";
}
service.setContentType(content_type);
Element body =
new Element(BODY_EL_NAME, new String[] { WAIT_ATTR, INACTIVITY_ATTR,
POLLING_ATTR, REQUESTS_ATTR, HOLD_ATTR, MAXPAUSE_ATTR, SID_ATTR, VER_ATTR,
FROM_ATTR, SECURE_ATTR, "xmpp:version", "xmlns:xmpp", "xmlns:stream" },
new String[] { Long.valueOf(this.max_wait).toString(),
Long.valueOf(this.max_inactivity).toString(),
Long.valueOf(this.min_polling).toString(),
Integer.valueOf(this.concurrent_requests).toString(),
Integer.valueOf(this.hold_requests).toString(),
Long.valueOf(this.max_pause).toString(), this.sid.toString(),
BOSH_VERSION, this.domain, "true", "1.0", "urn:xmpp:xbosh",
"http://etherx.jabber.org/streams" });
sessionId = UUID.randomUUID().toString();
body.setAttribute(AUTHID_ATTR, sessionId);
if (getCurrentRidTail() > 0) {
body.setAttribute(ACK_ATTR, "" + takeCurrentRidTail());
}
body.setXMLNS(BOSH_XMLNS);
sendBody(service, body);
// service.writeRawData(body.toString());
Packet streamOpen =
Command.STREAM_OPENED.getPacket(null, null, StanzaType.set, UUID.randomUUID()
.toString(), Command.DataType.submit);
Command.addFieldValue(streamOpen, "session-id", sessionId);
Command.addFieldValue(streamOpen, "hostname", domain);
Command.addFieldValue(streamOpen, LANG_ATTR, lang);
handler.addOutStreamOpen(streamOpen, this);
// out_results.offer(streamOpen);
}
/**
* Method description
*
*
* @param packet
* @param out_results
*/
public synchronized void processPacket(Packet packet, Queue<Packet> out_results) {
if (packet != null) {
if (log.isLoggable(Level.FINEST)) {
log.finest("[" + connections.size() + "] Processing packet: " + packet.toString());
}
if (filterInPacket(packet)) {
waiting_packets.offer(packet.getElement());
} else {
if (log.isLoggable(Level.FINEST)) {
log.finest("[" + connections.size() + "] In packet filtered: "
+ packet.toString());
}
}
}
if ((connections.size() > 0) && ((waiting_packets.size() > 0) || terminate)) {
BoshIOService serv = connections.poll();
sendBody(serv, null);
}
}
/**
* Method description
*
*
* @param packet
* @param service
* @param out_results
*/
public synchronized void processSocketPacket(Packet packet, BoshIOService service,
Queue<Packet> out_results) {
if (log.isLoggable(Level.FINEST)) {
log.finest("[" + connections.size() + "] Processing socket packet: "
+ packet.toString());
}
if (waitTimer != null) {
if (log.isLoggable(Level.FINEST)) {
log.finest("Canceling waitTimer: " + getSid());
}
handler.cancelTask(waitTimer);
}
if (inactivityTimer != null) {
if (log.isLoggable(Level.FINEST)) {
log.finest("Canceling inactivityTimer: " + getSid());
}
handler.cancelTask(inactivityTimer);
}
if ((packet.getElemName() == BODY_EL_NAME) && (packet.getXMLNS() == BOSH_XMLNS)) {
List<Element> children = packet.getElemChildren(BODY_EL_NAME);
boolean duplicate = false;
if (packet.getAttribute(RID_ATTR) != null) {
try {
long rid = Long.parseLong(packet.getAttribute(RID_ATTR));
if (isDuplicateRid(rid, children)) {
log.info("Discovered duplicate client connection, trying to close the "
+ "old one with RID: " + rid);
Element body = getBodyElem();
body.setAttribute("type", StanzaType.terminate.toString());
sendBody(service, body);
return;
}
service.setRid(rid);
duplicate = isDuplicateMessage(rid, children);
if (!duplicate) {
processRid(rid, children);
}
} catch (NumberFormatException e) {
log.warning("Incorrect RID value: " + packet.getAttribute(RID_ATTR));
}
}
service.setContentType(content_type);
service.setSid(sid);
connections.offer(service);
if (!duplicate) {
if ((packet.getType() != null) && (packet.getType() == StanzaType.terminate)) {
// We are preparing for session termination.
// Some client send IQ stanzas with private data to store some
// settings so some confirmation stanzas might be sent back
// let's give the client a few secs for session termination
max_inactivity = 2; // Max pause changed to 2 secs
terminate = true;
Packet command =
Command.STREAM_CLOSED.getPacket(null, null, StanzaType.set, UUID
.randomUUID().toString());
handler.addOutStreamClosed(command, this);
// out_results.offer(command);
}
if ((packet.getAttribute(RESTART_ATTR) != null)
&& packet.getAttribute(RESTART_ATTR).equals("true")) {
log.fine("Found stream restart instruction: " + packet.toString());
out_results.offer(Command.GETFEATURES.getPacket(null, null, StanzaType.get,
"restart1", null));
}
if (packet.getAttribute(CACHE_ATTR) != null) {
try {
CacheAction action = CacheAction.valueOf(packet.getAttribute(CACHE_ATTR));
if (cache_on || (action == CacheAction.on)) {
processCache(action, packet);
}
} catch (IllegalArgumentException e) {
log.warning("Incorrect cache action: " + packet.getAttribute(CACHE_ATTR));
}
} else {
if (children != null) {
for (Element el : children) {
try {
if (el.getXMLNS().equals(BOSH_XMLNS)) {
el.setXMLNS(XMLNS_CLIENT_VAL);
}
Packet result = Packet.packetInstance(el);
if (filterOutPacket(result)) {
if (log.isLoggable(Level.FINEST)) {
log.finest("Sending out packet: " + result.toString());
}
out_results.offer(result);
} else {
if (log.isLoggable(Level.FINEST)) {
log.finest("Out packet filtered: " + result.toString());
}
}
} catch (TigaseStringprepException ex) {
log.warning("Packet addressing problem, stringprep processing failed, dropping: "
+ el);
}
}
}
}
} else {
log.info("Duplicated packet: " + packet.toString());
}
} else {
log.warning("[" + connections.size() + "] Unexpected packet from the network: "
+ packet.toString());
String er_msg = "Invalid body element";
if (packet.getElemName() != BODY_EL_NAME) {
er_msg += ", incorrect root element name, use " + BODY_EL_NAME;
}
if (packet.getXMLNS() != BOSH_XMLNS) {
er_msg += ", incorrect xmlns, use " + BOSH_XMLNS;
}
try {
Packet error = Authorization.BAD_REQUEST.getResponseMessage(packet, er_msg, true);
waiting_packets.add(error.getElement());
terminate = true;
Packet command =
Command.STREAM_CLOSED.getPacket(null, null, StanzaType.set, UUID.randomUUID()
.toString());
handler.addOutStreamClosed(command, this);
// out_results.offer(command);
} catch (PacketErrorTypeException e) {
log.info("Error type and incorrect from bosh client? Ignoring...");
}
}
// Send packets waiting in queue...
processPacket(null, out_results);
if (connections.size() > hold_requests) {
BoshIOService serv = connections.poll();
sendBody(serv, null);
}
if ((connections.size() > 0) && (waiting_packets.size() == 0)) {
if (log.isLoggable(Level.FINEST)) {
log.finest("Setting waitTimer for " + max_wait + ": " + getSid());
}
waitTimer = handler.scheduleTask(this, max_wait * SECOND);
}
}
/**
* Method description
*
*
* @param dataReceiver
*/
public void setDataReceiver(JID dataReceiver) {
this.dataReceiver = dataReceiver;
}
/**
* Method description
*
*
* @param out_results
* @param tt
*
* @return
*/
public boolean task(Queue<Packet> out_results, TimerTask tt) {
if (tt == inactivityTimer) {
if (log.isLoggable(Level.FINEST)) {
log.finest("inactivityTimer fired: " + getSid());
}
if (waitTimer != null) {
if (log.isLoggable(Level.FINEST)) {
log.finest("Canceling waitTimer: " + getSid());
}
handler.cancelTask(waitTimer);
}
for (Element packet : waiting_packets) {
try {
// Do not send stream:features back with an error
if (packet.getName() != "stream:features") {
out_results.offer(Authorization.RECIPIENT_UNAVAILABLE.getResponseMessage(
Packet.packetInstance(packet), "Bosh = disconnected", true));
}
} catch (TigaseStringprepException ex) {
log.warning("Packet addressing problem, stringprep processing failed, dropping: "
+ packet);
} catch (PacketErrorTypeException e) {
log.info("Packet processing exception: " + e);
}
}
if (log.isLoggable(Level.FINEST)) {
log.finest("Closing session, inactivity timeout expired: " + getSid());
}
Packet command =
Command.STREAM_CLOSED.getPacket(null, null, StanzaType.set, UUID.randomUUID()
.toString());
handler.addOutStreamClosed(command, this);
closeAllConnections();
// out_results.offer(command);
return true;
}
if (tt == waitTimer) {
if (log.isLoggable(Level.FINEST)) {
log.finest("waitTimer fired: " + getSid());
}
BoshIOService serv = connections.poll();
if (serv != null) {
sendBody(serv, null);
}
}
return false;
}
private Element applyFilters(Element packet) {
Element result = packet.clone();
if (result.getName() == MESSAGE_ELEMENT_NAME) {
String body = result.getCData("/message/body");
if (body != null) {
int count = 0;
// for (Pattern reg: links_regexs) {
// body = reg.matcher(body).replaceAll(replace_with[count++]);
result.getChild("body").setCData(body);
}
}
return result;
}
private boolean filterInPacket(Packet packet) {
if (cache_on) {
processAutomaticCache(packet);
}
return true;
}
private boolean filterOutPacket(Packet packet) {
if (cache_on && (packet.getElemName() == MESSAGE_ELEMENT_NAME)) {
cache.addToMessage(packet.getElement());
}
return true;
}
private Element getBodyElem() {
Element body =
new Element(BODY_EL_NAME, new String[] { FROM_ATTR, SECURE_ATTR, "xmpp:version",
"xmlns:xmpp", "xmlns:stream" }, new String[] { this.domain, "true", "1.0",
"urn:xmpp:xbosh", "http://etherx.jabber.org/streams" });
body.setXMLNS(BOSH_XMLNS);
return body;
}
private long getCurrentRidTail() {
synchronized (currentRids) {
return currentRids[rids_tail];
}
}
private boolean isDuplicateMessage(long rid, List<Element> packets) {
synchronized (currentRids) {
int hashCode = -1;
if ((packets != null) && (packets.size() > 0)) {
StringBuilder sb = new StringBuilder();
for (Element elem : packets) {
sb.append(elem.toString());
}
hashCode = sb.toString().hashCode();
}
if (hashCode == -1) {
return false;
}
for (int i = 0; i < currentRids.length; ++i) {
if (rid == currentRids[i]) {
return hashCode == hashCodes[i];
}
}
}
return false;
}
private boolean isDuplicateRid(long rid, List<Element> packets) {
synchronized (currentRids) {
int hashCode = -1;
if ((packets != null) && (packets.size() > 0)) {
StringBuilder sb = new StringBuilder();
for (Element elem : packets) {
sb.append(elem.toString());
}
hashCode = sb.toString().hashCode();
}
for (int i = 0; i < currentRids.length; ++i) {
if (rid == currentRids[i]) {
return hashCode != hashCodes[i];
}
}
}
return false;
}
private void processAutomaticCache(Packet packet) {
if (packet.getElemName() == PRESENCE_ELEMENT_NAME) {
cache.addPresence(packet.getElement());
}
if (packet.getElemName() == MESSAGE_ELEMENT_NAME) {
cache.addFromMessage(packet.getElement());
}
if (packet.isXMLNS("/iq/query", "jabber:iq:roster")) {
cache.addRoster(packet.getElement());
}
if (packet.isXMLNS("/iq/bind", "urn:ietf:params:xml:ns:xmpp-bind")) {
cache.set(BoshSessionCache.RESOURCE_BIND_ID,
Collections.singletonList(packet.getElement()));
}
}
private long cache_reload_counter = 0;
private void processCache(CacheAction action, Packet packet) {
++cache_reload_counter;
int packet_counter = 0;
List<Element> children = packet.getElemChildren(BODY_EL_NAME);
String cache_id = packet.getAttribute(CACHE_ID_ATTR);
List<Element> cache_res = null;
switch (action) {
case on:
if (cache == null) {
cache = new BoshSessionCache();
}
cache_on = true;
log.fine("BoshSessionCache set to ON");
break;
case off:
cache_on = false;
log.fine("BoshSessionCache set to OFF");
break;
case set:
cache.set(cache_id, children);
break;
case add:
cache.add(cache_id, children);
break;
case get:
cache_res = cache.get(cache_id);
break;
case remove:
cache.remove(cache_id);
break;
case get_all:
cache_res = cache.getAll();
retireAllOldConnections();
break;
default:
log.warning("Unknown cache action: " + action.toString());
break;
}
if (cache_res != null) {
for (Element elem : cache_res) {
elem.addAttribute("reload-counter", "" + cache_reload_counter);
elem.addAttribute("packet-counter", "" + (++packet_counter));
waiting_packets.add(elem);
}
}
}
private void processRid(long rid, List<Element> packets) {
synchronized (currentRids) {
if ((previous_received_rid + 1) != rid) {
log.info("Incorrect packet order, last_rid=" + previous_received_rid
+ ", current_rid=" + rid);
}
if ((packets != null) && (packets.size() > 0)) {
StringBuilder sb = new StringBuilder();
for (Element elem : packets) {
sb.append(elem.toString());
}
hashCodes[rids_head] = sb.toString().hashCode();
} else {
hashCodes[rids_head] = -1;
}
previous_received_rid = rid;
currentRids[rids_head++] = rid;
if (rids_head >= currentRids.length) {
rids_head = 0;
}
}
}
private synchronized void sendBody(BoshIOService serv, Element body_par) {
Element body = body_par;
if (body == null) {
body = getBodyElem();
long rid = takeCurrentRidTail();
if (rid > 0) {
body.setAttribute(ACK_ATTR, "" + rid);
}
if (waiting_packets.size() > 0) {
// body.addChild(applyFilters(waiting_packets.poll()));
// Make sure the XMLNS is set correctly for all stanzas to avoid
// namespace confusion:
Element stanza = waiting_packets.poll();
if (stanza.getXMLNS() == null) {
stanza.setXMLNS(XMLNS_CLIENT_VAL);
}
body.addChild(stanza);
while ((waiting_packets.size() > 0) && (body.getChildren().size() < MAX_PACKETS)) {
// body.addChild(applyFilters(waiting_packets.poll()));
stanza = waiting_packets.poll();
if (stanza.getXMLNS() == null) {
stanza.setXMLNS(XMLNS_CLIENT_VAL);
}
body.addChild(stanza);
}
}
}
try {
if (terminate) {
body.setAttribute("type", StanzaType.terminate.toString());
}
handler.writeRawData(serv, body.toString());
retireConnectionService(serv);
// serv.writeRawData(body.toString());
// waiting_packets.clear();
// serv.stop();
// } catch (IOException e) {
// // I call it anyway at the end of method call
// //disconnected(null);
// log.log(Level.WARNING, "[" + connections.size() +
// "] Exception during writing to socket", e);
} catch (Exception e) {
log.log(Level.WARNING, "[" + connections.size()
+ "] Exception during writing to socket", e);
}
if (waitTimer != null) {
if (log.isLoggable(Level.FINEST)) {
log.finest("Canceling waitTimer: " + getSid());
}
handler.cancelTask(waitTimer);
}
}
private void retireConnectionService(BoshIOService serv) {
if (!old_connections.contains(serv)) {
while (!old_connections.offer(serv)) {
BoshIOService old_serv = old_connections.poll();
if (old_serv != null) {
old_serv.stop();
} else {
if (log.isLoggable(Level.WARNING)) {
log.warning("old_connections queue is empty but can not add new element!: "
+ getSid());
}
break;
}
}
}
serv.setSid(null);
disconnected(serv);
}
private void retireAllOldConnections() {
while (connections.size() > 1) {
BoshIOService serv = connections.poll();
if (serv != null) {
retireConnectionService(serv);
} else {
if (log.isLoggable(Level.WARNING)) {
log.warning("connections queue size is greater than 1 but poll returns null"
+ getSid());
}
}
}
}
private long takeCurrentRidTail() {
synchronized (currentRids) {
int idx = rids_tail++;
if (rids_tail >= currentRids.length) {
rids_tail = 0;
}
return currentRids[idx];
}
}
}
// ~ Formatted in Sun Code Convention
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.