answer
stringlengths
17
10.2M
package replicant; import arez.ArezContext; import arez.Disposable; import arez.annotations.Action; import arez.annotations.ContextRef; import arez.annotations.Observable; import arez.annotations.PreDispose; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Objects; import java.util.function.Consumer; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.realityforge.anodoc.TestOnly; import replicant.spy.ConnectFailureEvent; import replicant.spy.ConnectedEvent; import replicant.spy.DataLoadStatus; import replicant.spy.DisconnectFailureEvent; import replicant.spy.DisconnectedEvent; import replicant.spy.MessageProcessFailureEvent; import replicant.spy.MessageProcessedEvent; import replicant.spy.MessageReadFailureEvent; import replicant.spy.RestartEvent; import replicant.spy.SubscribeCompletedEvent; import replicant.spy.SubscribeFailedEvent; import replicant.spy.SubscribeRequestQueuedEvent; import replicant.spy.SubscribeStartedEvent; import replicant.spy.SubscriptionUpdateCompletedEvent; import replicant.spy.SubscriptionUpdateFailedEvent; import replicant.spy.SubscriptionUpdateRequestQueuedEvent; import replicant.spy.SubscriptionUpdateStartedEvent; import replicant.spy.UnsubscribeCompletedEvent; import replicant.spy.UnsubscribeFailedEvent; import replicant.spy.UnsubscribeRequestQueuedEvent; import replicant.spy.UnsubscribeStartedEvent; import static org.realityforge.braincheck.Guards.*; /** * The Connector is responsible for managing a Connection to a backend datasource. */ public abstract class Connector extends ReplicantService { private static final int DEFAULT_LINKS_TO_PROCESS_PER_TICK = 100; private static final int DEFAULT_CHANGES_TO_PROCESS_PER_TICK = 100; /** * The code to parse changesets. Extracted into a separate class so it can be vary by environment. */ private final ChangeSetParser _changeSetParser = new ChangeSetParser(); /** * The schema that defines data-API used to interact with datasource. */ @Nonnull private final SystemSchema _schema; /** * The transport that connects to the backend system. */ @Nonnull private final Transport _transport; @Nonnull private ConnectorState _state = ConnectorState.DISCONNECTED; /** * The current connection managed by the connector, if any. */ @Nullable private Connection _connection; /** * Flag indicating that the Connectors internal scheduler is actively progressing * requests and responses. A scheduler should only be active if there is a connection present. */ private boolean _schedulerActive; /** * Flag when the scheduler has been explicitly paused. * When this is true, the {@link #progressMessages()} will terminate the next time * it is invoked and the scheduler will not be activated. This is */ private boolean _schedulerPaused; /** * This lock is acquired by the Connector when it begins processing messages from the network. * Once the processor is idle the lock should be released to allow Arez to reflect all the changes. */ @Nullable private Disposable _schedulerLock; /** * Maximum number of entity links to attempt in a single tick of the scheduler. After this many links have * been processed then return and any remaining links can occur in a later tick. */ private int _linksToProcessPerTick = DEFAULT_LINKS_TO_PROCESS_PER_TICK; /** * Maximum number of EntityChange messages processed in a single tick of the scheduler. After this many changes have * been processed then return and any remaining change can be processed in a later tick. */ private int _changesToProcessPerTick = DEFAULT_CHANGES_TO_PROCESS_PER_TICK; /** * Action invoked after current MessageResponse is processed. This is typically used to update or alter * change Connection on message processing complete. */ @Nullable private SafeProcedure _postMessageResponseAction; protected Connector( @Nullable final ReplicantContext context, @Nonnull final SystemSchema schema, @Nonnull final Transport transport ) { super( context ); _schema = Objects.requireNonNull( schema ); _transport = Objects.requireNonNull( transport ); getReplicantRuntime().registerConnector( this ); getReplicantContext().getSchemaService().registerSchema( schema ); } @PreDispose final void preDispose() { _schedulerPaused = true; _schedulerActive = false; if ( null != _schedulerLock ) { _schedulerLock.dispose(); _schedulerLock = null; } } /** * Connect to the underlying data source. */ public void connect() { final ConnectorState state = getState(); if ( ConnectorState.CONNECTING != state && ConnectorState.CONNECTED != state ) { ConnectorState newState = ConnectorState.ERROR; try { getTransport().connect( this::onConnection, this::onConnectFailure ); newState = ConnectorState.CONNECTING; } finally { setState( newState ); } } } /** * Disconnect from underlying data source. */ public void disconnect() { final ConnectorState state = getState(); if ( ConnectorState.DISCONNECTING != state && ConnectorState.DISCONNECTED != state ) { ConnectorState newState = ConnectorState.ERROR; try { getTransport().disconnect( this::onDisconnection, this::onDisconnectionError ); newState = ConnectorState.DISCONNECTING; } finally { setState( newState ); } } } /** * Return the schema associated with the connector. * * @return the schema associated with the connector. */ @Nonnull public final SystemSchema getSchema() { return _schema; } void onConnection( @Nonnull final String connectionId ) { doSetConnection( new Connection( this, connectionId ) ); triggerMessageScheduler(); } private void onDisconnectionError( @Nonnull final Throwable error ) { onDisconnection(); onDisconnectFailure( error ); } final void onDisconnection() { doSetConnection( null ); } private void doSetConnection( @Nullable final Connection connection ) { final Connection existing = getConnection(); if ( null == existing || null == existing.getCurrentMessageResponse() ) { setConnection( connection ); } else { setPostMessageResponseAction( () -> setConnection( connection ) ); } } private void setConnection( @Nullable final Connection connection ) { _connection = connection; purgeSubscriptions(); if ( null != _connection ) { onConnected(); } else { onDisconnected(); } } @Nullable public final Connection getConnection() { return _connection; } @Nonnull final Connection ensureConnection() { if ( Replicant.shouldCheckInvariants() ) { invariant( () -> null != _connection, () -> "Replicant-0031: Connector.ensureConnection() when no connection is present." ); } assert null != _connection; return _connection; } @Nonnull private MessageResponse ensureCurrentMessageResponse() { return ensureConnection().ensureCurrentMessageResponse(); } @Nonnull final Transport getTransport() { return _transport; } @Action protected void purgeSubscriptions() { Stream.concat( getReplicantContext().getTypeSubscriptions().stream(), getReplicantContext().getInstanceSubscriptions().stream() ) // Only purge subscriptions for current system .filter( s -> s.getAddress().getSystemId() == getSchema().getId() ) // Purge in reverse order. First instance subscriptions then type subscriptions .sorted( Comparator.reverseOrder() ) .forEachOrdered( Disposable::dispose ); } final void setLinksToProcessPerTick( final int linksToProcessPerTick ) { _linksToProcessPerTick = linksToProcessPerTick; } final void setChangesToProcessPerTick( final int changesToProcessPerTick ) { _changesToProcessPerTick = changesToProcessPerTick; } /** * Return true if an area of interest action with specified parameters is pending or being processed. * When the action parameter is DELETE the filter parameter is ignored. */ final boolean isAreaOfInterestRequestPending( @Nonnull final AreaOfInterestRequest.Type action, @Nonnull final ChannelAddress address, @Nullable final Object filter ) { final Connection connection = getConnection(); return null != connection && connection.isAreaOfInterestRequestPending( action, address, filter ); } /** * Return the index of last matching Type in pending aoi actions list. */ final int lastIndexOfPendingAreaOfInterestRequest( @Nonnull final AreaOfInterestRequest.Type action, @Nonnull final ChannelAddress address, @Nullable final Object filter ) { final Connection connection = getConnection(); return null == connection ? -1 : connection.lastIndexOfPendingAreaOfInterestRequest( action, address, filter ); } final void requestSubscribe( @Nonnull final ChannelAddress address, @Nullable final Object filter ) { ensureConnection().requestSubscribe( address, filter ); triggerMessageScheduler(); if ( Replicant.areSpiesEnabled() && getReplicantContext().getSpy().willPropagateSpyEvents() ) { getReplicantContext().getSpy().reportSpyEvent( new SubscribeRequestQueuedEvent( address, filter ) ); } } final void requestSubscriptionUpdate( @Nonnull final ChannelAddress address, @Nullable final Object filter ) { //TODO: Verify that this address is for an updateable channel ensureConnection().requestSubscriptionUpdate( address, filter ); triggerMessageScheduler(); if ( Replicant.areSpiesEnabled() && getReplicantContext().getSpy().willPropagateSpyEvents() ) { getReplicantContext().getSpy().reportSpyEvent( new SubscriptionUpdateRequestQueuedEvent( address, filter ) ); } } final void requestUnsubscribe( @Nonnull final ChannelAddress address ) { ensureConnection().requestUnsubscribe( address ); triggerMessageScheduler(); if ( Replicant.areSpiesEnabled() && getReplicantContext().getSpy().willPropagateSpyEvents() ) { getReplicantContext().getSpy().reportSpyEvent( new UnsubscribeRequestQueuedEvent( address ) ); } } final boolean isSchedulerActive() { return _schedulerActive; } /** * Schedule request and response processing. * This method should be invoked when requests are queued or responses are received. */ protected final void triggerMessageScheduler() { if ( !_schedulerActive ) { _schedulerActive = true; if ( !_schedulerPaused ) { activateMessageScheduler(); } } } final boolean isSchedulerPaused() { return _schedulerPaused; } final void pauseMessageScheduler() { _schedulerPaused = true; } final void resumeMessageScheduler() { if ( _schedulerPaused ) { _schedulerPaused = false; if ( _schedulerActive ) { activateMessageScheduler(); } } } /** * Perform a single step progressing requests and responses. * This is invoked from the scheduler and will continue to be * invoked until it returns false. * * @return true if more work is to be done. */ final boolean progressMessages() { if ( _schedulerPaused ) { return false; } if ( null == _schedulerLock ) { _schedulerLock = context().pauseScheduler(); } try { final boolean step1 = progressAreaOfInterestRequestProcessing(); final boolean step2 = progressResponseProcessing(); _schedulerActive = step1 || step2; } catch ( final Throwable e ) { onMessageProcessFailure( e ); _schedulerActive = false; return false; } finally { if ( !_schedulerActive ) { _schedulerLock.dispose(); _schedulerLock = null; } } return _schedulerActive; } /** * Activate the scheduler. * This involves creating a scheduler that will invoke {@link #progressMessages()} until * that method returns false. */ private void activateMessageScheduler() { Scheduler.schedule( this::progressMessages ); } /** * Perform a single step processing messages received from the server. * * @return true if more work is to be done. */ boolean progressResponseProcessing() { final Connection connection = ensureConnection(); final MessageResponse response = connection.getCurrentMessageResponse(); if ( null == response ) { // Select the MessageResponse if there is none active return connection.selectNextMessageResponse(); } else if ( response.needsParsing() ) { // Parse the json parseMessageResponse(); return true; } else if ( response.needsChannelChangesProcessed() ) { // Process the updates to channels processChannelChanges(); return true; } else if ( response.areEntityChangesPending() ) { // Process a chunk of entity changes processEntityChanges(); return true; } else if ( response.areEntityLinksPending() ) { // Process a chunk of links processEntityLinks(); return true; } else if ( !response.hasWorldBeenValidated() ) { // Validate the world after the change set has been applied (if feature is enabled) validateWorld(); return true; } else { completeMessageResponse(); return true; } } /** * {@inheritDoc} */ @Nonnull @Observable public ConnectorState getState() { return _state; } protected void setState( @Nonnull final ConnectorState state ) { _state = Objects.requireNonNull( state ); } /** * Build a ChannelAddress from a ChannelChange value. * * @param channelChange the change. * @return the address. */ @Nonnull final ChannelAddress toAddress( @Nonnull final ChannelChange channelChange ) { final int channelId = channelChange.getChannelId(); final Integer subChannelId = channelChange.hasSubChannelId() ? channelChange.getSubChannelId() : null; return new ChannelAddress( getSchema().getId(), channelId, subChannelId ); } @Action protected void processChannelChanges() { final MessageResponse response = ensureCurrentMessageResponse(); final ChangeSet changeSet = response.getChangeSet(); final ChannelChange[] channelChanges = changeSet.getChannelChanges(); for ( final ChannelChange channelChange : channelChanges ) { final ChannelAddress address = toAddress( channelChange ); final Object filter = channelChange.getChannelFilter(); final ChannelChange.Action actionType = channelChange.getAction(); if ( ChannelChange.Action.ADD == actionType ) { response.incChannelAddCount(); final boolean explicitSubscribe = ensureConnection() .getCurrentAreaOfInterestRequests() .stream() .anyMatch( a -> a.isInProgress() && a.getAddress().equals( address ) ); getReplicantContext().getSubscriptionService().createSubscription( address, filter, explicitSubscribe ); } else if ( ChannelChange.Action.REMOVE == actionType ) { final Subscription subscription = getReplicantContext().findSubscription( address ); if ( Replicant.shouldCheckInvariants() ) { invariant( () -> null != subscription, () -> "Replicant-0028: Received ChannelChange of type REMOVE for address " + address + " but no such subscription exists." ); assert null != subscription; } assert null != subscription; Disposable.dispose( subscription ); response.incChannelRemoveCount(); } else { assert ChannelChange.Action.UPDATE == actionType; final Subscription subscription = getReplicantContext().findSubscription( address ); if ( Replicant.shouldCheckInvariants() ) { invariant( () -> null != subscription, () -> "Replicant-0033: Received ChannelChange of type UPDATE for address " + address + " but no such subscription exists." ); assert null != subscription; invariant( subscription::isExplicitSubscription, () -> "Replicant-0029: Received ChannelChange of type UPDATE for address " + address + " but subscription is implicitly subscribed." ); if ( Replicant.shouldCheckInvariants() ) { invariant( () -> ChannelSchema.FilterType.DYNAMIC == getSchema().getChannel( address.getChannelId() ).getFilterType(), () -> "Replicant-0076: Received ChannelChange of type UPDATE for address " + address + " but the channel does not have a DYNAMIC filter." ); } } assert null != subscription; subscription.setFilter( filter ); updateSubscriptionForFilteredEntities( subscription ); response.incChannelUpdateCount(); } } response.markChannelActionsProcessed(); } @Action protected void processEntityLinks() { final MessageResponse response = ensureCurrentMessageResponse(); Linkable linkable; for ( int i = 0; i < _linksToProcessPerTick && null != ( linkable = response.nextEntityToLink() ); i++ ) { linkable.link(); response.incEntityLinkCount(); } } /** * Method invoked when a filter has updated and the Connector needs to delink any entities * that are no longer part of the subscription now that the filter has changed. * * @param subscription the subscription that was updated. */ final void updateSubscriptionForFilteredEntities( @Nonnull final Subscription subscription ) { final ChannelAddress address = subscription.getAddress(); final ChannelSchema channel = getSchema().getChannel( address.getChannelId() ); if ( Replicant.shouldCheckInvariants() ) { invariant( () -> ChannelSchema.FilterType.DYNAMIC == channel.getFilterType(), () -> "Replicant-0077: Connector.updateSubscriptionForFilteredEntities invoked for address " + subscription.getAddress() + " but the channel does not have a DYNAMIC filter." ); } for ( final Class<?> entityType : new ArrayList<>( subscription.findAllEntityTypes() ) ) { final List<Entity> entities = subscription.findAllEntitiesByType( entityType ); if ( !entities.isEmpty() ) { final SubscriptionUpdateEntityFilter updateFilter = channel.getFilter(); assert null != updateFilter; final Object filter = subscription.getFilter(); for ( final Entity entity : entities ) { if ( !updateFilter.doesEntityMatchFilter( filter, entity ) ) { entity.delinkFromSubscription( subscription ); } } } } } final void setPostMessageResponseAction( @Nullable final SafeProcedure postMessageResponseAction ) { _postMessageResponseAction = postMessageResponseAction; } void completeMessageResponse() { final Connection connection = ensureConnection(); final MessageResponse response = connection.ensureCurrentMessageResponse(); // OOB messages are not sequenced if ( !response.isOob() ) { connection.setLastRxSequence( response.getChangeSet().getSequence() ); } //Step: Run the post actions final RequestEntry request = response.getRequest(); if ( null != request ) { request.markResultsAsArrived(); } /* * An action will be returned if the message is an OOB message * or it is an answer to a response and the rpc invocation has * already returned. */ final SafeProcedure action = response.getCompletionAction(); if ( null != action ) { action.call(); // OOB messages are not in response to requests (at least not request associated with the current connection) if ( !response.isOob() ) { // We can remove the request because this side ran second and the RPC channel has already returned. final ChangeSet changeSet = response.getChangeSet(); final Integer requestId = changeSet.getRequestId(); if ( null != requestId ) { connection.removeRequest( requestId ); } } } connection.setCurrentMessageResponse( null ); onMessageProcessed( response.toStatus() ); if ( null != _postMessageResponseAction ) { _postMessageResponseAction.call(); _postMessageResponseAction = null; } } @Action protected void removeExplicitSubscriptions( @Nonnull final List<AreaOfInterestRequest> requests ) { requests.forEach( request -> { if ( Replicant.shouldCheckInvariants() ) { invariant( () -> AreaOfInterestRequest.Type.REMOVE == request.getType(), () -> "Replicant-0034: Connector.removeExplicitSubscriptions() invoked with request " + "with type that is not REMOVE. Request: " + request ); } final Subscription subscription = getReplicantContext().findSubscription( request.getAddress() ); if ( null != subscription ) { /* * It is unclear whether this code is actually required as should note the response from the server * automatically setExplicitSubscription to false? */ subscription.setExplicitSubscription( false ); } } ); } @Action protected void removeUnneededAddRequests( @Nonnull final List<AreaOfInterestRequest> requests ) { requests.removeIf( request -> { final ChannelAddress address = request.getAddress(); final Subscription subscription = getReplicantContext().findSubscription( address ); if ( Replicant.shouldCheckInvariants() ) { invariant( () -> null == subscription || !subscription.isExplicitSubscription(), () -> "Replicant-0030: Request to add channel at address " + address + " but already explicitly subscribed to channel." ); } if ( null != subscription && !subscription.isExplicitSubscription() ) { // Existing subscription converted to an explicit subscription subscription.setExplicitSubscription( true ); request.markAsComplete(); return true; } else { return false; } } ); } @Action protected void removeUnneededUpdateRequests( @Nonnull final List<AreaOfInterestRequest> requests ) { requests.removeIf( a -> { final ChannelAddress address = a.getAddress(); final Subscription subscription = getReplicantContext().findSubscription( address ); if ( Replicant.shouldCheckInvariants() ) { invariant( () -> null != subscription, () -> "Replicant-0048: Request to update channel at address " + address + " but not subscribed to channel." ); } // The following code can probably be removed but it was present in the previous system // and it is unclear if there is any scenarios where it can still happen. The code has // been left in until we can verify it is no longer an issue. The above invariants will trigger // in development mode to help us track down these scenarios if ( null == subscription ) { a.markAsComplete(); return true; } else { return false; } } ); } @Action protected void removeUnneededRemoveRequests( @Nonnull final List<AreaOfInterestRequest> requests ) { requests.removeIf( request -> { final ChannelAddress address = request.getAddress(); final Subscription subscription = getReplicantContext().findSubscription( address ); if ( Replicant.shouldCheckInvariants() ) { invariant( () -> null != subscription, () -> "Replicant-0046: Request to unsubscribe from channel at address " + address + " but not subscribed to channel." ); invariant( () -> null == subscription || subscription.isExplicitSubscription(), () -> "Replicant-0047: Request to unsubscribe from channel at address " + address + " but subscription is not an explicit subscription." ); } // The following code can probably be removed but it was present in the previous system // and it is unclear if there is any scenarios where it can still happen. The code has // been left in until we can verify it is no longer an issue. The above invariants will trigger // in development mode to help us track down these scenarios if ( null == subscription || !subscription.isExplicitSubscription() ) { request.markAsComplete(); return true; } else { return false; } } ); } /** * Parse the json data associated with the current response and then enqueue it. */ void parseMessageResponse() { final Connection connection = ensureConnection(); final MessageResponse response = connection.ensureCurrentMessageResponse(); final String rawJsonData = response.getRawJsonData(); assert null != rawJsonData; final ChangeSet changeSet = _changeSetParser.parseChangeSet( rawJsonData ); if ( Replicant.shouldValidateChangeSetOnRead() ) { changeSet.validate(); } final RequestEntry request; if ( response.isOob() ) { /* * OOB messages are really just cached messages at this stage and they are the * same bytes as originally sent down and then cached. So the requestId present * in the json blob is for old connection and can be ignored. */ request = null; } else { final Integer requestId = changeSet.getRequestId(); final int sequence = changeSet.getSequence(); request = null != requestId ? connection.getRequest( requestId ) : null; if ( Replicant.shouldCheckApiInvariants() ) { apiInvariant( () -> null != request || null == requestId, () -> "Replicant-0066: Unable to locate request with id '" + requestId + "' specified for ChangeSet with sequence " + sequence + ". Existing Requests: " + connection.getRequests() ); } } cacheMessageIfPossible( rawJsonData, changeSet ); response.recordChangeSet( changeSet, request ); connection.queueCurrentResponse(); } private void cacheMessageIfPossible( @Nonnull final String rawJsonData, @Nonnull final ChangeSet changeSet ) { final String eTag = changeSet.getETag(); final CacheService cacheService = getReplicantContext().getCacheService(); boolean candidate = false; if ( null != cacheService && null != eTag && changeSet.hasChannelChanges() ) { final ChannelChange[] channelChanges = changeSet.getChannelChanges(); if ( 1 == channelChanges.length && ChannelChange.Action.ADD == channelChanges[ 0 ].getAction() && getSchema().getChannel( channelChanges[ 0 ].getChannelId() ).isCacheable() ) { final ChannelChange channelChange = channelChanges[ 0 ]; final String cacheKey = "RC-" + getSchema().getId() + "." + channelChange.getChannelId() + ( channelChange.hasSubChannelId() ? "." + channelChange.getSubChannelId() : "" ); cacheService.store( cacheKey, eTag, rawJsonData ); candidate = true; } } if ( Replicant.shouldCheckApiInvariants() ) { final boolean c = candidate; apiInvariant( () -> null == eTag || null == cacheService || c, () -> "Replicant-0072: eTag in reply for ChangeSet " + changeSet.getSequence() + " but ChangeSet is not a candidate for caching." ); } } @Action protected void processEntityChanges() { final MessageResponse response = ensureCurrentMessageResponse(); EntityChange change; for ( int i = 0; i < _changesToProcessPerTick && null != ( change = response.nextEntityChange() ); i++ ) { final int id = change.getId(); final int typeId = change.getTypeId(); final EntitySchema entitySchema = getSchema().getEntity( typeId ); final Class<?> type = entitySchema.getType(); Entity entity = getReplicantContext().getEntityService().findEntityByTypeAndId( type, id ); if ( change.isRemove() ) { if ( null != entity ) { Disposable.dispose( entity ); } else { if ( Replicant.shouldCheckInvariants() ) { fail( () -> "Replicant-0068: ChangeSet " + response.getChangeSet().getSequence() + " contained an " + "EntityChange message to delete entity of type " + typeId + " and id " + id + " but no such entity exists locally." ); } } response.incEntityRemoveCount(); } else { final EntityChangeData data = change.getData(); if ( null == entity ) { final String name = Replicant.areNamesEnabled() ? entitySchema.getName() + "/" + id : null; entity = getReplicantContext().getEntityService().findOrCreateEntity( name, type, id ); final Object userObject = getChangeMapper().createEntity( entitySchema, id, data ); entity.setUserObject( userObject ); } else { getChangeMapper().updateEntity( entitySchema, entity.getUserObject(), data ); } final EntityChannel[] changeCount = change.getChannels(); final int schemaId = getSchema().getId(); for ( final EntityChannel entityChannel : changeCount ) { final ChannelAddress address = entityChannel.toAddress( schemaId ); final Subscription subscription = getReplicantContext().findSubscription( address ); if ( Replicant.shouldCheckInvariants() ) { invariant( () -> null != subscription, () -> "Replicant-0069: ChangeSet " + response.getChangeSet().getSequence() + " contained an " + "EntityChange message referencing channel " + entityChannel.toAddress( schemaId ) + " but no such subscription exists locally." ); } assert null != subscription; entity.linkToSubscription( subscription ); } response.incEntityUpdateCount(); response.changeProcessed( entity.getUserObject() ); } } } @Nonnull protected abstract ChangeMapper getChangeMapper(); final void validateWorld() { ensureCurrentMessageResponse().markWorldAsValidated(); if ( Replicant.shouldValidateEntitiesOnLoad() ) { getReplicantContext().getValidator().validateEntities(); } } /** * Perform a single step in sending one (or a batch) or requests to the server. */ final boolean progressAreaOfInterestRequestProcessing() { final List<AreaOfInterestRequest> requests = new ArrayList<>( ensureConnection().getCurrentAreaOfInterestRequests() ); if ( requests.isEmpty() ) { return false; } else if ( requests.get( 0 ).isInProgress() ) { return false; } else { requests.forEach( AreaOfInterestRequest::markAsInProgress ); final AreaOfInterestRequest.Type type = requests.get( 0 ).getType(); if ( AreaOfInterestRequest.Type.ADD == type ) { progressAreaOfInterestAddRequests( requests ); } else if ( AreaOfInterestRequest.Type.REMOVE == type ) { progressAreaOfInterestRemoveRequests( requests ); } else { progressAreaOfInterestUpdateRequests( requests ); } return true; } } final void progressAreaOfInterestAddRequests( @Nonnull final List<AreaOfInterestRequest> requests ) { removeUnneededAddRequests( requests ); if ( requests.isEmpty() ) { completeAreaOfInterestRequest(); } else if ( 1 == requests.size() ) { progressAreaOfInterestAddRequest( requests.get( 0 ) ); } else { progressBulkAreaOfInterestAddRequests( requests ); } } final void progressAreaOfInterestAddRequest( @Nonnull final AreaOfInterestRequest request ) { final ChannelAddress address = request.getAddress(); onSubscribeStarted( address ); final SafeProcedure onSuccess = () -> { completeAreaOfInterestRequest(); onSubscribeCompleted( address ); }; final Consumer<Throwable> onError = error -> { completeAreaOfInterestRequest(); onSubscribeFailed( address, error ); }; final CacheService cacheService = getReplicantContext().getCacheService(); final boolean cacheable = null != cacheService && getSchema().getChannel( request.getAddress().getChannelId() ).isCacheable(); final CacheEntry cacheEntry = cacheable ? cacheService.lookup( request.getCacheKey() ) : null; if ( null != cacheEntry ) { //Found locally cached data final String eTag = cacheEntry.getETag(); final SafeProcedure onCacheValid = () -> { // Loading cached data completeAreaOfInterestRequest(); ensureConnection().enqueueOutOfBandResponse( cacheEntry.getContent(), onSuccess ); triggerMessageScheduler(); }; getTransport() .requestSubscribe( request.getAddress(), request.getFilter(), eTag, onCacheValid, onSuccess, onError ); } else { getTransport().requestSubscribe( request.getAddress(), request.getFilter(), onSuccess, onError ); } } final void progressBulkAreaOfInterestAddRequests( @Nonnull final List<AreaOfInterestRequest> requests ) { final List<ChannelAddress> addresses = requests.stream().map( AreaOfInterestRequest::getAddress ).collect( Collectors.toList() ); addresses.forEach( this::onSubscribeStarted ); final SafeProcedure onSuccess = () -> { completeAreaOfInterestRequest(); addresses.forEach( this::onSubscribeCompleted ); }; final Consumer<Throwable> onError = error -> { completeAreaOfInterestRequest(); addresses.forEach( a -> onSubscribeFailed( a, error ) ); }; getTransport().requestBulkSubscribe( addresses, requests.get( 0 ).getFilter(), onSuccess, onError ); } final void progressAreaOfInterestUpdateRequests( @Nonnull final List<AreaOfInterestRequest> requests ) { removeUnneededUpdateRequests( requests ); if ( requests.isEmpty() ) { completeAreaOfInterestRequest(); } else if ( requests.size() > 1 ) { progressBulkAreaOfInterestUpdateRequests( requests ); } else { progressAreaOfInterestUpdateRequest( requests.get( 0 ) ); } } final void progressAreaOfInterestUpdateRequest( @Nonnull final AreaOfInterestRequest request ) { final ChannelAddress address = request.getAddress(); onSubscriptionUpdateStarted( address ); final SafeProcedure onSuccess = () -> { completeAreaOfInterestRequest(); onSubscriptionUpdateCompleted( address ); }; final Consumer<Throwable> onError = error -> { completeAreaOfInterestRequest(); onSubscriptionUpdateFailed( address, error ); }; final Object filter = request.getFilter(); assert null != filter; getTransport().requestSubscriptionUpdate( address, filter, onSuccess, onError ); } final void progressBulkAreaOfInterestUpdateRequests( @Nonnull final List<AreaOfInterestRequest> requests ) { final List<ChannelAddress> addresses = requests.stream().map( AreaOfInterestRequest::getAddress ).collect( Collectors.toList() ); addresses.forEach( this::onSubscriptionUpdateStarted ); final SafeProcedure onSuccess = () -> { completeAreaOfInterestRequest(); addresses.forEach( this::onSubscriptionUpdateCompleted ); }; final Consumer<Throwable> onError = error -> { completeAreaOfInterestRequest(); addresses.forEach( a -> onSubscriptionUpdateFailed( a, error ) ); }; // All filters will be the same if they are grouped final Object filter = requests.get( 0 ).getFilter(); assert null != filter; getTransport().requestBulkSubscriptionUpdate( addresses, filter, onSuccess, onError ); } final void progressAreaOfInterestRemoveRequests( @Nonnull final List<AreaOfInterestRequest> requests ) { removeUnneededRemoveRequests( requests ); if ( requests.isEmpty() ) { completeAreaOfInterestRequest(); } else if ( requests.size() > 1 ) { progressBulkAreaOfInterestRemoveRequests( requests ); } else { progressAreaOfInterestRemoveRequest( requests.get( 0 ) ); } } final void progressAreaOfInterestRemoveRequest( @Nonnull final AreaOfInterestRequest request ) { final ChannelAddress address = request.getAddress(); onUnsubscribeStarted( address ); final SafeProcedure onSuccess = () -> { removeExplicitSubscriptions( Collections.singletonList( request ) ); completeAreaOfInterestRequest(); onUnsubscribeCompleted( address ); }; final Consumer<Throwable> onError = error -> { removeExplicitSubscriptions( Collections.singletonList( request ) ); completeAreaOfInterestRequest(); onUnsubscribeFailed( address, error ); }; getTransport().requestUnsubscribe( address, onSuccess, onError ); } final void progressBulkAreaOfInterestRemoveRequests( @Nonnull final List<AreaOfInterestRequest> requests ) { final List<ChannelAddress> addresses = requests.stream().map( AreaOfInterestRequest::getAddress ).collect( Collectors.toList() ); addresses.forEach( this::onUnsubscribeStarted ); final SafeProcedure onSuccess = () -> { removeExplicitSubscriptions( requests ); completeAreaOfInterestRequest(); addresses.forEach( this::onUnsubscribeCompleted ); }; final Consumer<Throwable> onError = error -> { removeExplicitSubscriptions( requests ); completeAreaOfInterestRequest(); addresses.forEach( a -> onUnsubscribeFailed( a, error ) ); }; getTransport().requestBulkUnsubscribe( addresses, onSuccess, onError ); } /** * The AreaOfInterestRequest currently being processed can be completed and * trigger scheduler to start next step. */ final void completeAreaOfInterestRequest() { ensureConnection().completeAreaOfInterestRequest(); triggerMessageScheduler(); } /** * Invoked to fire an event when disconnect has completed. */ @Action protected void onConnected() { setState( ConnectorState.CONNECTED ); if ( Replicant.areSpiesEnabled() && getReplicantContext().getSpy().willPropagateSpyEvents() ) { getReplicantContext().getSpy().reportSpyEvent( new ConnectedEvent( getSchema().getId(), getSchema().getName() ) ); } } /** * Invoked to fire an event when failed to connect. */ @Action protected void onConnectFailure( @Nonnull final Throwable error ) { setState( ConnectorState.ERROR ); if ( Replicant.areSpiesEnabled() && getReplicantContext().getSpy().willPropagateSpyEvents() ) { getReplicantContext().getSpy() .reportSpyEvent( new ConnectFailureEvent( getSchema().getId(), getSchema().getName(), error ) ); } } /** * Invoked to fire an event when disconnect has completed. */ @Action protected void onDisconnected() { setState( ConnectorState.DISCONNECTED ); if ( Replicant.areSpiesEnabled() && getReplicantContext().getSpy().willPropagateSpyEvents() ) { getReplicantContext().getSpy() .reportSpyEvent( new DisconnectedEvent( getSchema().getId(), getSchema().getName() ) ); } } /** * Invoked to fire an event when failed to connect. */ @Action protected void onDisconnectFailure( @Nonnull final Throwable error ) { setState( ConnectorState.ERROR ); if ( Replicant.areSpiesEnabled() && getReplicantContext().getSpy().willPropagateSpyEvents() ) { getReplicantContext().getSpy() .reportSpyEvent( new DisconnectFailureEvent( getSchema().getId(), getSchema().getName(), error ) ); } } /** * Invoked when a change set has been completely processed. * * @param status the status describing the results of data load. */ protected void onMessageProcessed( @Nonnull final DataLoadStatus status ) { if ( Replicant.areSpiesEnabled() && getReplicantContext().getSpy().willPropagateSpyEvents() ) { getReplicantContext().getSpy() .reportSpyEvent( new MessageProcessedEvent( getSchema().getId(), getSchema().getName(), status ) ); } } /** * Called when a data load has resulted in a failure. */ @Action protected void onMessageProcessFailure( @Nonnull final Throwable error ) { if ( Replicant.areSpiesEnabled() && getReplicantContext().getSpy().willPropagateSpyEvents() ) { getReplicantContext().getSpy() .reportSpyEvent( new MessageProcessFailureEvent( getSchema().getId(), getSchema().getName(), error ) ); } disconnectIfPossible( error ); } /** * Attempted to retrieve data from backend and failed. */ @Action protected void onMessageReadFailure( @Nonnull final Throwable error ) { if ( Replicant.areSpiesEnabled() && getReplicantContext().getSpy().willPropagateSpyEvents() ) { getReplicantContext().getSpy() .reportSpyEvent( new MessageReadFailureEvent( getSchema().getId(), getSchema().getName(), error ) ); } disconnectIfPossible( error ); } final void disconnectIfPossible( @Nonnull final Throwable cause ) { if ( !ConnectorState.isTransitionState( getState() ) ) { if ( Replicant.areSpiesEnabled() && getReplicantContext().getSpy().willPropagateSpyEvents() ) { getReplicantContext().getSpy() .reportSpyEvent( new RestartEvent( getSchema().getId(), getSchema().getName(), cause ) ); } disconnect(); } } @Action protected void onSubscribeStarted( @Nonnull final ChannelAddress address ) { updateAreaOfInterest( address, AreaOfInterest.Status.LOADING, null ); if ( Replicant.areSpiesEnabled() && getReplicantContext().getSpy().willPropagateSpyEvents() ) { getReplicantContext().getSpy() .reportSpyEvent( new SubscribeStartedEvent( getSchema().getId(), getSchema().getName(), address ) ); } } @Action protected void onSubscribeCompleted( @Nonnull final ChannelAddress address ) { updateAreaOfInterest( address, AreaOfInterest.Status.LOADED, null ); if ( Replicant.areSpiesEnabled() && getReplicantContext().getSpy().willPropagateSpyEvents() ) { getReplicantContext().getSpy() .reportSpyEvent( new SubscribeCompletedEvent( getSchema().getId(), getSchema().getName(), address ) ); } } @Action protected void onSubscribeFailed( @Nonnull final ChannelAddress address, @Nonnull final Throwable error ) { updateAreaOfInterest( address, AreaOfInterest.Status.LOAD_FAILED, error ); if ( Replicant.areSpiesEnabled() && getReplicantContext().getSpy().willPropagateSpyEvents() ) { getReplicantContext().getSpy() .reportSpyEvent( new SubscribeFailedEvent( getSchema().getId(), getSchema().getName(), address, error ) ); } } @Action protected void onUnsubscribeStarted( @Nonnull final ChannelAddress address ) { updateAreaOfInterest( address, AreaOfInterest.Status.UNLOADING, null ); if ( Replicant.areSpiesEnabled() && getReplicantContext().getSpy().willPropagateSpyEvents() ) { getReplicantContext().getSpy() .reportSpyEvent( new UnsubscribeStartedEvent( getSchema().getId(), getSchema().getName(), address ) ); } } @Action protected void onUnsubscribeCompleted( @Nonnull final ChannelAddress address ) { updateAreaOfInterest( address, AreaOfInterest.Status.UNLOADED, null ); if ( Replicant.areSpiesEnabled() && getReplicantContext().getSpy().willPropagateSpyEvents() ) { getReplicantContext().getSpy() .reportSpyEvent( new UnsubscribeCompletedEvent( getSchema().getId(), getSchema().getName(), address ) ); } } @Action protected void onUnsubscribeFailed( @Nonnull final ChannelAddress address, @Nonnull final Throwable error ) { updateAreaOfInterest( address, AreaOfInterest.Status.UNLOADED, null ); if ( Replicant.areSpiesEnabled() && getReplicantContext().getSpy().willPropagateSpyEvents() ) { getReplicantContext().getSpy() .reportSpyEvent( new UnsubscribeFailedEvent( getSchema().getId(), getSchema().getName(), address, error ) ); } } @Action protected void onSubscriptionUpdateStarted( @Nonnull final ChannelAddress address ) { updateAreaOfInterest( address, AreaOfInterest.Status.UPDATING, null ); if ( Replicant.areSpiesEnabled() && getReplicantContext().getSpy().willPropagateSpyEvents() ) { getReplicantContext().getSpy() .reportSpyEvent( new SubscriptionUpdateStartedEvent( getSchema().getId(), getSchema().getName(), address ) ); } } @Action protected void onSubscriptionUpdateCompleted( @Nonnull final ChannelAddress address ) { updateAreaOfInterest( address, AreaOfInterest.Status.UPDATED, null ); if ( Replicant.areSpiesEnabled() && getReplicantContext().getSpy().willPropagateSpyEvents() ) { getReplicantContext().getSpy() .reportSpyEvent( new SubscriptionUpdateCompletedEvent( getSchema().getId(), getSchema().getName(), address ) ); } } @Action protected void onSubscriptionUpdateFailed( @Nonnull final ChannelAddress address, @Nonnull final Throwable error ) { updateAreaOfInterest( address, AreaOfInterest.Status.UPDATE_FAILED, error ); if ( Replicant.areSpiesEnabled() && getReplicantContext().getSpy().willPropagateSpyEvents() ) { getReplicantContext() .getSpy() .reportSpyEvent( new SubscriptionUpdateFailedEvent( getSchema().getId(), getSchema().getName(), address, error ) ); } } private void updateAreaOfInterest( @Nonnull final ChannelAddress address, @Nonnull final AreaOfInterest.Status status, @Nullable final Throwable error ) { final AreaOfInterest areaOfInterest = getReplicantContext().findAreaOfInterestByAddress( address ); if ( null != areaOfInterest ) { areaOfInterest.updateAreaOfInterest( status, error ); } } @Nonnull final ReplicantRuntime getReplicantRuntime() { return getReplicantContext().getRuntime(); } @ContextRef @Nonnull protected abstract ArezContext context(); /** * {@inheritDoc} */ @Override public String toString() { return Replicant.areNamesEnabled() ? "Connector[" + getSchema().getName() + "]" : super.toString(); } @TestOnly @Nullable final Disposable getSchedulerLock() { return _schedulerLock; } @TestOnly @Nullable final SafeProcedure getPostMessageResponseAction() { return _postMessageResponseAction; } }
package soot.jimple.toolkits.annotation.logic; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import soot.Unit; import soot.jimple.Stmt; import soot.toolkits.graph.UnitGraph; /** * A (natural) loop in Jimple. A back-edge (t,h) is a control-flog edge for which * h dominates t. In this case h is the header and the loop consists of all statements * s which reach t without passing through h. * * @author Eric Bodden */ public class Loop { protected final Stmt header; protected final List<Stmt> loopStatements; protected final UnitGraph g; protected Collection<Stmt> loopExists; /** * Creates a new loop. Expects that the loop statements are ordered according to the * loop structure with the loop header being the last statement. {@link LoopFinder} will * normally guarantee this. * @param header the loop header * @param loopStatements an ordered list of loop statements, ending with the header * @param g the unit graph according to which the loop exists */ Loop(Stmt header, List<Stmt> loopStatements, UnitGraph g) { this.header = header; this.g = g; //put header to the top loopStatements.remove(header); loopStatements.add(0, header); //check for right order boolean hasRightOrder = true; Iterator<Stmt> stmtIter = loopStatements.iterator(); Stmt curr = stmtIter.next(); while(stmtIter.hasNext()) { Stmt next = stmtIter.next(); if(!g.getSuccsOf(curr).contains(next)) { hasRightOrder = false; break; } curr = next; } assert hasRightOrder; this.loopStatements = loopStatements; } /** * @return the loop head */ public Stmt getHead() { return header; } /** * @return all statements of the loop, including the header; * the header will be the first element returned and then the * other statements follow in the natural ordering of the loop */ public List<Stmt> getLoopStatements() { return loopStatements; } /** * Returns all loop exists. * A loop exit is a statement which has a successor that is not contained in the loop. */ public Collection<Stmt> getLoopExits() { if(loopExists==null) { loopExists = new HashSet<Stmt>(); for (Stmt s : loopStatements) { for (Unit succ : g.getSuccsOf(s)) { if(!loopStatements.contains(succ)) { loopExists.add(s); } } } } return loopExists; } /** * Computes all targets of the given loop exit, i.e. statements that the exit jumps to but which are not * part of this loop. */ public Collection<Stmt> targetsOfLoopExit(Stmt loopExit) { assert getLoopExits().contains(loopExit); List<Unit> succs = g.getSuccsOf(loopExit); Collection<Stmt> res = new HashSet<Stmt>(); for (Unit u : succs) { Stmt s = (Stmt)u; res.add(s); } res.removeAll(loopStatements); return res; } /** * Returns <code>true</code> if this loop certainly loops forever, i.e. if it has not exit. * @see #getLoopExits() */ public boolean loopsForever() { return getLoopExits().isEmpty(); } /** * Returns <code>true</code> if this loop has a single exit statement. * @see #getLoopExits() */ public boolean hasSingleExit() { return getLoopExits().size()==1; } /** * {@inheritDoc} */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((header == null) ? 0 : header.hashCode()); result = prime * result + ((loopStatements == null) ? 0 : loopStatements.hashCode()); return result; } /** * {@inheritDoc} */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final Loop other = (Loop) obj; if (header == null) { if (other.header != null) return false; } else if (!header.equals(other.header)) return false; if (loopStatements == null) { if (other.loopStatements != null) return false; } else if (!loopStatements.equals(other.loopStatements)) return false; return true; } }
package br.org.cesar.gporpino.fluentandroid.database.direct; import android.database.Cursor; import android.util.Log; import br.org.cesar.gporpino.fluentandroid.FluentAndroid; import br.org.cesar.gporpino.fluentandroid.FluentUtils; import br.org.cesar.gporpino.fluentandroid.database.FluentCursor; import br.org.cesar.gporpino.fluentandroid.database.FluentSQLiteOpenHelper; public class Select { public static final String ALL = null; public static final String COUNT_ALL = "COUNT(*)"; private String[] mProjection; private String mTableName; private FluentSQLiteOpenHelper mDatabaseHelper; private String mSelection; private String[] mSelectionArgs; private String mGroupBy; private String mHaving; private String mOrderBy; public Select(String... projection) { mProjection = projection; mDatabaseHelper = FluentAndroid.getInstance().getDatabaseHelper(); } public Select from(String tableName) { mTableName = tableName; return this; } public Select where(String selection, String...selectionArgs){ mSelection = selection; mSelectionArgs = selectionArgs; return this; } public Select groupBy(String...columnNames){ mGroupBy = FluentUtils.join(columnNames, ","); return this; } public Select having(String condition, String...havingArgs){ mHaving = condition; for (String arg : havingArgs) { mHaving = condition.replaceFirst("/?", arg); } return this; } public Select orderBy(String...columnNames){ mOrderBy = FluentUtils.join(columnNames, ","); return this; } public FluentCursor execute() { if (mTableName == null){ throw new IllegalStateException("Before call execute the method from should be called."); } try { Log.v(Select.class.getName(), "Select from " + mTableName); Cursor cursor = mDatabaseHelper.getReadableDatabase().query(mTableName, mProjection, mSelection, mSelectionArgs, mGroupBy, mHaving, mOrderBy); if (cursor != null) { return new FluentCursor(cursor); } } finally { Log.v(Select.class.getName(), "Closing database"); mDatabaseHelper.getReadableDatabase().close(); } return null; } }
package org.geogit.cli.test.functional; import static org.geogit.cli.test.functional.GlobalState.currentDirectory; import static org.geogit.cli.test.functional.GlobalState.geogit; import static org.geogit.cli.test.functional.GlobalState.geogitCLI; import static org.geogit.cli.test.functional.GlobalState.homeDirectory; import static org.geogit.cli.test.functional.GlobalState.stdOut; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.BufferedWriter; import java.io.File; import java.io.IOException; import java.net.URI; import java.util.List; import java.util.Map; import java.util.Random; import org.apache.commons.io.FileUtils; import org.geogit.api.GeoGIT; import org.geogit.api.GlobalInjectorBuilder; import org.geogit.api.NodeRef; import org.geogit.api.ObjectId; import org.geogit.api.Ref; import org.geogit.api.RevFeatureType; import org.geogit.api.plumbing.RefParse; import org.geogit.api.plumbing.UpdateRef; import org.geogit.api.plumbing.diff.AttributeDiff; import org.geogit.api.plumbing.diff.FeatureDiff; import org.geogit.api.plumbing.diff.GenericAttributeDiffImpl; import org.geogit.api.plumbing.diff.Patch; import org.geogit.api.plumbing.diff.PatchSerializer; import org.geogit.api.plumbing.merge.MergeConflictsException; import org.geogit.api.porcelain.BranchCreateOp; import org.geogit.api.porcelain.CheckoutOp; import org.geogit.api.porcelain.CommitOp; import org.geogit.api.porcelain.MergeOp; import org.opengis.feature.Feature; import org.opengis.feature.type.PropertyDescriptor; import com.google.common.base.Charsets; import com.google.common.base.Optional; import com.google.common.base.Suppliers; import com.google.common.collect.Maps; import com.google.common.io.Files; import com.google.inject.Injector; import cucumber.annotation.en.Given; import cucumber.annotation.en.Then; import cucumber.annotation.en.When; public class InitSteps extends AbstractGeogitFunctionalTest { private static final String LINE_SEPARATOR = System.getProperty("line.separator"); @cucumber.annotation.After public void after() { if (GlobalState.geogitCLI != null) { GlobalState.geogitCLI.close(); } if (GlobalState.geogit != null) { GlobalState.geogit.close(); } deleteDirectories(); } @Given("^I am in an empty directory$") public void I_am_in_an_empty_directory() throws Throwable { setUpDirectories(); assertEquals(0, currentDirectory.list().length); setupGeogit(); } @When("^I run the command \"([^\"]*)\"$") public void I_run_the_command_X(String commandSpec) throws Throwable { String[] args = commandSpec.split(" "); for (int i = 0; i < args.length; i++) { args[i] = args[i].replace("${currentdir}", currentDirectory.getAbsolutePath()); } runCommand(args); } @Then("^it should answer \"([^\"]*)\"$") public void it_should_answer_exactly(String expected) throws Throwable { expected = expected.replace("${currentdir}", currentDirectory.getAbsolutePath()) .toLowerCase().replaceAll("\\\\", "/"); String actual = stdOut.toString().replaceAll(LINE_SEPARATOR, "").replaceAll("\\\\", "/") .trim().toLowerCase(); assertEquals(expected, actual); } @Then("^the response should contain \"([^\"]*)\"$") public void the_response_should_contain(String expected) throws Throwable { String actual = stdOut.toString().replaceAll(LINE_SEPARATOR, "").replaceAll("\\\\", "/"); expected.replaceAll("\\\\", "/"); assertTrue(actual, actual.contains(expected)); } @Then("^the response should not contain \"([^\"]*)\"$") public void the_response_should_not_contain(String expected) throws Throwable { String actual = stdOut.toString().replaceAll(LINE_SEPARATOR, "").replaceAll("\\\\", "/"); expected.replaceAll("\\\\", "/"); assertFalse(actual, actual.contains(expected)); } @Then("^the response should contain ([^\"]*) lines$") public void the_response_should_contain_x_lines(int lines) throws Throwable { String[] lineStrings = stdOut.toString().split(LINE_SEPARATOR); assertEquals(lines, lineStrings.length); } @Then("^the response should start with \"([^\"]*)\"$") public void the_response_should_start_with(String expected) throws Throwable { String actual = stdOut.toString().replaceAll(LINE_SEPARATOR, ""); assertTrue(actual, actual.startsWith(expected)); } @Then("^the repository directory shall exist$") public void the_repository_directory_shall_exist() throws Throwable { List<String> output = runAndParseCommand("rev-parse", "--resolve-geogit-dir"); assertEquals(output.toString(), 1, output.size()); String location = output.get(0); assertNotNull(location); if (location.startsWith("Error:")) { fail(location); } File repoDir = new File(location); assertTrue("Repository directory not found: " + repoDir.getAbsolutePath(), repoDir.exists()); } @Given("^I have a remote ref called \"([^\"]*)\"$") public void i_have_a_remote_ref_called(String expected) throws Throwable { String ref = "refs/remotes/origin/" + expected; geogit.command(UpdateRef.class).setName(ref).setNewValue(ObjectId.NULL).call(); Optional<Ref> refValue = geogit.command(RefParse.class).setName(ref).call(); assertTrue(refValue.isPresent()); assertEquals(refValue.get().getObjectId(), ObjectId.NULL); } @Given("^I have an unconfigured repository$") public void I_have_an_unconfigured_repository() throws Throwable { setUpDirectories(); setupGeogit(); List<String> output = runAndParseCommand("init"); assertEquals(output.toString(), 1, output.size()); assertNotNull(output.get(0)); assertTrue(output.get(0), output.get(0).startsWith("Initialized")); } @Given("^I have a merge conflict state$") public void I_have_a_merge_conflict_state() throws Throwable { I_have_two_conflicting_branches(); Ref branch = geogit.command(RefParse.class).setName("branch1").call().get(); try { geogit.command(MergeOp.class).addCommit(Suppliers.ofInstance(branch.getObjectId())) .call(); fail(); } catch (MergeConflictsException e) { e = e; } } @Given("^I have two conflicting branches$") public void I_have_two_conflicting_branches() throws Throwable { // Create the following revision graph // o - Points 1 added // | o - TestBranch - Points 1 modified and points 2 added // o - master - HEAD - Points 1 modifiedB Feature points1ModifiedB = feature(pointsType, idP1, "StringProp1_3", new Integer(2000), "POINT(1 1)"); Feature points1Modified = feature(pointsType, idP1, "StringProp1_2", new Integer(1000), "POINT(1 1)"); insertAndAdd(points1); geogit.command(CommitOp.class).call(); geogit.command(BranchCreateOp.class).setName("branch1").call(); insertAndAdd(points1Modified); geogit.command(CommitOp.class).call(); geogit.command(CheckoutOp.class).setSource("branch1").call(); insertAndAdd(points1ModifiedB); insertAndAdd(points2); geogit.command(CommitOp.class).call(); geogit.command(CheckoutOp.class).setSource("master").call(); } @Given("^there is a remote repository$") public void there_is_a_remote_repository() throws Throwable { I_am_in_an_empty_directory(); GeoGIT oldGeogit = geogit; Injector oldInjector = geogitCLI.getGeogitInjector(); geogitCLI.setGeogitInjector(GlobalInjectorBuilder.builder.build()); List<String> output = runAndParseCommand("init", "remoterepo"); assertEquals(output.toString(), 1, output.size()); assertNotNull(output.get(0)); assertTrue(output.get(0), output.get(0).startsWith("Initialized")); geogit = geogitCLI.getGeogit(); runCommand("config", "--global", "user.name", "John Doe"); runCommand("config", "--global", "user.email", "JohnDoe@example.com"); insertAndAdd(points1); runCommand(("commit -m Commit1").split(" ")); runCommand(("branch -c branch1").split(" ")); insertAndAdd(points2); runCommand(("commit -m Commit2").split(" ")); insertAndAdd(points3); runCommand(("commit -m Commit3").split(" ")); runCommand(("checkout master").split(" ")); insertAndAdd(lines1); runCommand(("commit -m Commit4").split(" ")); geogit.close(); geogit = oldGeogit; geogitCLI.setGeogit(oldGeogit); geogitCLI.setGeogitInjector(oldInjector); } @Given("^I have a repository$") public void I_have_a_repository() throws Throwable { I_have_an_unconfigured_repository(); runCommand("config", "--global", "user.name", "John Doe"); runCommand("config", "--global", "user.email", "JohnDoe@example.com"); } @Given("^I have a repository with a remote$") public void I_have_a_repository_with_a_remote() throws Throwable { there_is_a_remote_repository(); List<String> output = runAndParseCommand("init", "localrepo"); assertEquals(output.toString(), 1, output.size()); assertNotNull(output.get(0)); assertTrue(output.get(0), output.get(0).startsWith("Initialized")); runCommand("config", "--global", "user.name", "John Doe"); runCommand("config", "--global", "user.email", "JohnDoe@example.com"); runCommand("remote", "add", "origin", currentDirectory + "/remoterepo"); } private void setUpDirectories() throws IOException { homeDirectory = new File("target", "fakeHomeDir" + new Random().nextInt()); FileUtils.deleteDirectory(homeDirectory); assertFalse(homeDirectory.exists()); assertTrue(homeDirectory.mkdirs()); currentDirectory = new File("target", "testrepo" + new Random().nextInt()); FileUtils.deleteDirectory(currentDirectory); assertFalse(currentDirectory.exists()); assertTrue(currentDirectory.mkdirs()); } private void deleteDirectories() { try { FileUtils.deleteDirectory(homeDirectory); assertFalse(homeDirectory.exists()); FileUtils.deleteDirectory(currentDirectory); assertFalse(currentDirectory.exists()); } catch (IOException e) { } } @Given("^I have staged \"([^\"]*)\"$") public void I_have_staged(String feature) throws Throwable { if (feature.equals("points1")) { insertAndAdd(points1); } else if (feature.equals("points2")) { insertAndAdd(points2); } else if (feature.equals("points3")) { insertAndAdd(points3); } else if (feature.equals("points1_modified")) { insertAndAdd(points1_modified); } else if (feature.equals("lines1")) { insertAndAdd(lines1); } else if (feature.equals("lines2")) { insertAndAdd(lines2); } else if (feature.equals("lines3")) { insertAndAdd(lines3); } else { throw new Exception("Unknown Feature"); } } @Given("^I have 6 unstaged features$") public void I_have_6_unstaged_features() throws Throwable { insertFeatures(); } @Given("^I have unstaged \"([^\"]*)\"$") public void I_have_unstaged(String feature) throws Throwable { if (feature.equals("points1")) { insert(points1); } else if (feature.equals("points2")) { insert(points2); } else if (feature.equals("points3")) { insert(points3); } else if (feature.equals("points1_modified")) { insert(points1_modified); } else if (feature.equals("lines1")) { insert(lines1); } else if (feature.equals("lines2")) { insert(lines2); } else if (feature.equals("lines3")) { insert(lines3); } else { throw new Exception("Unknown Feature"); } } @Given("^I stage 6 features$") public void I_stage_6_features() throws Throwable { insertAndAddFeatures(); } @Given("^I have several commits$") public void I_have_several_commits() throws Throwable { insertAndAdd(points1); insertAndAdd(points2); runCommand(("commit -m Commit1").split(" ")); insertAndAdd(points3); insertAndAdd(lines1); runCommand(("commit -m Commit2").split(" ")); insertAndAdd(lines2); insertAndAdd(lines3); runCommand(("commit -m Commit3").split(" ")); insertAndAdd(points1_modified); runCommand(("commit -m Commit4").split(" ")); } @Given("^I have several branches") public void I_have_several_branches() throws Throwable { insertAndAdd(points1); runCommand(("commit -m Commit1").split(" ")); runCommand(("branch -c branch1").split(" ")); insertAndAdd(points2); runCommand(("commit -m Commit2").split(" ")); insertAndAdd(points3); runCommand(("commit -m Commit3").split(" ")); runCommand(("branch -c branch2").split(" ")); insertAndAdd(lines1); runCommand(("commit -m Commit4").split(" ")); runCommand(("checkout master").split(" ")); insertAndAdd(lines2); runCommand(("commit -m Commit5").split(" ")); } @Given("I modify and add a feature") public void I_modify_and_add_a_feature() throws Throwable { insertAndAdd(points1_modified); } @Given("I modify a feature") public void I_modify_a_feature() throws Throwable { insert(points1_modified); } @Given("^I modify a feature type$") public void I_modify_a_feature_type() throws Throwable { deleteAndReplaceFeatureType(); } @Then("^if I change to the respository subdirectory \"([^\"]*)\"$") public void if_I_change_to_the_respository_subdirectory(String subdirSpec) throws Throwable { String[] subdirs = subdirSpec.split("/"); File dir = currentDirectory; for (String subdir : subdirs) { dir = new File(dir, subdir); } assertTrue(dir.exists()); currentDirectory = dir; } @Given("^I have a patch file$") public void I_have_a_patch_file() throws Throwable { Patch patch = new Patch(); String path = NodeRef.appendChild(pointsName, points1.getIdentifier().getID()); Map<PropertyDescriptor, AttributeDiff> map = Maps.newHashMap(); Optional<?> oldValue = Optional.fromNullable(points1.getProperty("sp").getValue()); GenericAttributeDiffImpl diff = new GenericAttributeDiffImpl(oldValue, Optional.of("new")); map.put(pointsType.getDescriptor("sp"), diff); FeatureDiff feaureDiff = new FeatureDiff(path, map, RevFeatureType.build(pointsType), RevFeatureType.build(pointsType)); patch.addModifiedFeature(feaureDiff); File file = new File(currentDirectory, "test.patch"); BufferedWriter writer = Files.newWriter(file, Charsets.UTF_8); PatchSerializer.write(writer, patch); writer.flush(); writer.close(); } @Given("^I am inside a repository subdirectory \"([^\"]*)\"$") public void I_am_inside_a_repository_subdirectory(String subdirSpec) throws Throwable { String[] subdirs = subdirSpec.split("/"); File dir = currentDirectory; for (String subdir : subdirs) { dir = new File(dir, subdir); } assertTrue(dir.mkdirs()); currentDirectory = dir; } }
//Contributors: BH, HC, TL package team.sprocket.subsystems; import edu.wpi.first.wpilibj.Victor; import edu.wpi.first.wpilibj.command.Subsystem; import team.sprocket.main.RobotMap; import team.sprocket.commands.CommandBase; public class MecanumDriveTrain extends Subsystem { private final Victor v_FrontLeftDriveTrain = new Victor(RobotMap.driveTrainDigitalModule, RobotMap.frontLeftDriveTrainMotorPort); private final Victor v_FrontRightDriveTrain = new Victor(RobotMap.driveTrainDigitalModule, RobotMap.frontRightDriveTrainMotorPort); private final Victor v_BackLeftDriveTrain = new Victor(RobotMap.driveTrainDigitalModule, RobotMap.backLeftDriveTrainMotorPort); private final Victor v_BackRightDriveTrain = new Victor(RobotMap.driveTrainDigitalModule, RobotMap.backRightDriveTrainMotorPort); private double frontLeftMag, frontRightMag, backLeftMag, backRightMag, direction, xComponent, yComponent; private final double deadBand = .000000000000001; //rounding compensation private final double r2d2 = Math.sqrt(2) / 2; //root 2 denominator 2 public void translate(double magnitude, double bearing){ magnitude *= Math.sqrt(2); bearing %= 360; //make sure bearing does not exceed 360 bearing -= CommandBase.sensors.getAngle(); direction = bearingToDirection(bearing); //calculate angle (in degrees) of magic triangle xComponent = magnitude * Math.cos(Math.toRadians(direction)); //calculate x component of translation vector yComponent = magnitude * Math.sin(Math.toRadians(direction)); //calculate y component of translation vector findMagnitudes(); //calculates needed speed for each motor setVictors(); //sends values to Victors } private double bearingToDirection(double bearing){ if(bearing < 0){ bearing += 360; } double d = 90-bearing; //we grew up watching ed, edd, 'n eddy if(d < 0){ //make sure direction is positive d += 360; //convert negative direction to positive direction } return d; } private void findMagnitudes(){ if(Math.abs(xComponent) - Math.abs(yComponent) > deadBand){ //if x is bigger than y frontLeftMag = backRightMag = r2d2 * (xComponent + yComponent); frontRightMag = backLeftMag = r2d2 * (yComponent - xComponent); } if(Math.abs(xComponent) - Math.abs(yComponent) < -1*deadBand){ //if x is smaller than y frontLeftMag = backRightMag = r2d2 * (xComponent + yComponent); frontRightMag = backLeftMag = r2d2 * (yComponent - xComponent); } if(Math.abs(Math.abs(yComponent) - Math.abs(xComponent)) < deadBand){ if((direction < 90 && direction > 0) || (direction > 180 && direction < 270)){ //if in Quadrant I or III frontLeftMag = backRightMag = r2d2 * (xComponent + yComponent); } if((direction > 90 && direction < 180) || (direction > 270 && direction < 360)){ //if in Quadrant II or IV frontRightMag = backLeftMag = r2d2 * (yComponent - xComponent); } } } private void setVictors(){ //sets victors to certain speed v_FrontLeftDriveTrain.set(frontLeftMag); v_FrontRightDriveTrain.set(frontRightMag); v_BackLeftDriveTrain.set(backLeftMag); v_BackRightDriveTrain.set(backRightMag); refresh(); } private void refresh(){ //refreshes magnitude values frontLeftMag = 0; frontRightMag = 0; backLeftMag = 0; backRightMag = 0; } public void turn(double speed, boolean dRoTA){ //parameter determines whether turn CW or CCW if(dRoTA){ frontRightMag = speed; backLeftMag = -1 * speed; } if(!dRoTA){ frontLeftMag = speed; backRightMag = -1 * speed; } } public void initDefaultCommand() { //empty } }
package org.voovan.network; import org.voovan.network.exception.SocketDisconnectByRemote; import org.voovan.tools.ByteBufferChannel; import org.voovan.tools.TByteBuffer; import org.voovan.tools.TEnv; import org.voovan.tools.log.Logger; import javax.net.ssl.*; import javax.net.ssl.SSLEngineResult.HandshakeStatus; import javax.net.ssl.SSLEngineResult.Status; import java.io.IOException; import java.nio.ByteBuffer; public class SSLParser { private SSLEngine engine; private ByteBuffer appData; private ByteBuffer netData; private IoSession session; boolean handShakeDone = false; /** * * @param engine SSLEngine * @param session session */ public SSLParser(SSLEngine engine,IoSession session) { this.engine = engine; this.session = session; session.setSSLParser(this); this.appData= buildAppDataBuffer(); this.netData = buildNetDataBuffer(); } /** * * @return */ public boolean isHandShakeDone() { return handShakeDone; } /** * SSLEngine * @return SSLEngine */ public SSLEngine getSSLEngine(){ return engine; } public ByteBuffer buildNetDataBuffer() { SSLSession sslSession = engine.getSession(); int newBufferMax = sslSession.getPacketBufferSize(); return ByteBuffer.allocateDirect(newBufferMax); } public ByteBuffer buildAppDataBuffer() { SSLSession sslSession = engine.getSession(); int newBufferMax = sslSession.getPacketBufferSize(); return ByteBuffer.allocateDirect(newBufferMax); } private void clearBuffer(){ appData.clear(); netData.clear(); } /** * * @param buffer * @return SSLEnginResult * @throws IOException IO */ public SSLEngineResult warpData(ByteBuffer buffer) throws IOException{ netData.clear(); SSLEngineResult engineResult = null; do{ engineResult = engine.wrap(buffer, netData); netData.flip(); if(session.isConnected() && engineResult.bytesProduced()>0 && netData.limit()>0){ session.send0(netData); } netData.clear(); }while(engineResult.getStatus() == Status.OK && buffer.hasRemaining()); return engineResult; } /** * Warp; * @return * @throws IOException * @throws Exception */ private HandshakeStatus doHandShakeWarp() throws IOException { clearBuffer(); appData.flip(); warpData(appData); // HandShake Task HandshakeStatus handshakeStatus = runDelegatedTasks(); return handshakeStatus; } /** * * @param netBuffer * @param appBuffer * @return SSLEngineResult * @throws SSLException SSL */ public SSLEngineResult unwarpData(ByteBuffer netBuffer,ByteBuffer appBuffer) throws SSLException{ SSLEngineResult engineResult = null; engineResult = engine.unwrap(netBuffer, appBuffer); return engineResult; } /** * Unwarp; * @return * @throws IOException * @throws Exception */ private HandshakeStatus doHandShakeUnwarp() throws IOException{ HandshakeStatus handshakeStatus =engine.getHandshakeStatus(); SSLEngineResult engineResult = null; int waitCount = 0; while(true){ if(waitCount >= session.socketContext().getReadTimeout()){ throw new SocketDisconnectByRemote("Hand shake on: "+ session.remoteAddress() + ":" + session.remotePort()+" timeout"); } clearBuffer(); ByteBufferChannel byteBufferChannel = session.getByteBufferChannel(); if(byteBufferChannel.isReleased()){ throw new IOException("Socket is disconnect"); } if(byteBufferChannel.size() > 0) { ByteBuffer byteBuffer = byteBufferChannel.getByteBuffer(); engineResult = unwarpData(byteBuffer, appData); if(engineResult.getStatus() == Status.OK) { // HandShake Task handshakeStatus = runDelegatedTasks(); } byteBufferChannel.compact(); if(engineResult.getStatus() == Status.CLOSED || engineResult.getStatus() == Status.BUFFER_OVERFLOW) { Logger.error(new SSLHandshakeException("Handshake failed: "+engineResult.getStatus())); break; } if(engineResult.getStatus() == Status.BUFFER_UNDERFLOW && !session.isConnected()){ Logger.error(new SSLHandshakeException("Handshake failed: "+engineResult.getStatus())); break; } if(engineResult.getStatus() == Status.OK) { break; } } waitCount++; TEnv.sleep(1); }; return handshakeStatus; } /** * * @throws Exception */ private HandshakeStatus runDelegatedTasks() { if(handShakeDone==false){ if (engine.getHandshakeStatus() == HandshakeStatus.NEED_TASK) { Runnable runnable; while ((runnable = engine.getDelegatedTask()) != null) { runnable.run(); } } return engine.getHandshakeStatus(); } return null; } public boolean doHandShake() throws IOException{ engine.beginHandshake(); int handShakeCount = 0; HandshakeStatus handshakeStatus = engine.getHandshakeStatus(); while(!handShakeDone && handShakeCount<20){ handShakeCount++; switch (handshakeStatus) { case NEED_TASK: handshakeStatus = runDelegatedTasks(); break; case NEED_WRAP: handshakeStatus = doHandShakeWarp(); break; case NEED_UNWRAP: handshakeStatus = doHandShakeUnwarp(); break; case FINISHED: handshakeStatus = engine.getHandshakeStatus(); break; case NOT_HANDSHAKING: handShakeDone = true; break; default: break; } // TEnv.sleep(1); } return handShakeDone; } /** * SSL * @param session Socket * @param netByteBufferChannel Socket SSL * @param appByteBufferChannel Socket SSL * @return * @throws IOException IO */ public int unWarpByteBufferChannel(IoSession session, ByteBufferChannel netByteBufferChannel, ByteBufferChannel appByteBufferChannel) throws IOException{ int readSize = 0; if(session.isConnected() && netByteBufferChannel.size()>0){ SSLEngineResult engineResult = null; while(true) { appData.clear(); ByteBuffer byteBuffer = netByteBufferChannel.getByteBuffer(); engineResult = unwarpData(byteBuffer, appData); netByteBufferChannel.compact(); appData.flip(); appByteBufferChannel.writeEnd(appData); if(engineResult!=null && engineResult.getStatus()==Status.OK && byteBuffer.remaining() == 0){ break; } if(engineResult!=null && (engineResult.getStatus() == Status.BUFFER_OVERFLOW || engineResult.getStatus() == Status.BUFFER_UNDERFLOW || engineResult.getStatus() == Status.CLOSED) ){ break; } } } return readSize; } public void release(){ TByteBuffer.release(netData); TByteBuffer.release(appData); } }
package com.twitter.intellij.pants.projectview; import com.intellij.icons.AllIcons; import com.intellij.ide.projectView.PresentationData; import com.intellij.ide.projectView.ProjectView; import com.intellij.ide.projectView.ProjectViewNode; import com.intellij.ide.projectView.ViewSettings; import com.intellij.ide.projectView.impl.ProjectViewImpl; import com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode; import com.intellij.ide.projectView.impl.nodes.PsiFileNode; import com.intellij.ide.util.treeView.AbstractTreeNode; import com.intellij.openapi.module.ModuleUtil; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Condition; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiDirectory; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiManager; import com.intellij.util.Function; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; public class VirtualFileTreeNode extends ProjectViewNode<VirtualFile> { public VirtualFileTreeNode( @NotNull Project project, @NotNull VirtualFile virtualFile, @NotNull ViewSettings viewSettings ) { super(project, virtualFile, viewSettings); } @Nullable @Override public VirtualFile getVirtualFile() { return getValue(); } @Override public int getWeight() { final ProjectView projectView = ProjectView.getInstance(myProject); final boolean foldersOnTop = projectView instanceof ProjectViewImpl && !((ProjectViewImpl)projectView).isFoldersAlwaysOnTop(); return foldersOnTop && getValue().isDirectory() ? 20 : 0; // see PsiDirectoryNode.getWeight() } @Override public boolean contains(@NotNull VirtualFile file) { final VirtualFile myFile = getValue(); return myFile.isDirectory() && VfsUtil.isAncestor(myFile, file, true); } @Override protected void update(PresentationData presentation) { final PsiManager psiManager = PsiManager.getInstance(myProject); final VirtualFile virtualFile = getValue(); final PsiFile psiElement = virtualFile.isValid() ? psiManager.findFile(virtualFile) : null; if (psiElement instanceof PsiDirectory) { new PsiDirectoryNode(myProject, (PsiDirectory)psiElement, getSettings()).update(presentation); } else if (psiElement != null) { new PsiFileNode(myProject, psiElement, getSettings()).update(presentation); } else { presentation.setPresentableText(virtualFile.getName()); presentation.setIcon(virtualFile.isDirectory() ? AllIcons.Nodes.Folder : virtualFile.getFileType().getIcon()); } } @NotNull @Override public Collection<? extends AbstractTreeNode> getChildren() { final PsiManager psiManager = PsiManager.getInstance(myProject); final VirtualFile virtualFile = getValue(); return ContainerUtil.map( virtualFile.isValid() && virtualFile.isDirectory() ? getFilteredChildren(virtualFile) : Collections.<VirtualFile>emptyList(), new Function<VirtualFile, AbstractTreeNode>() { @Override public AbstractTreeNode fun(VirtualFile file) { final PsiElement psiElement = file.isDirectory() ? psiManager.findDirectory(file) : psiManager.findFile(file); if (psiElement instanceof PsiDirectory && ModuleUtil.findModuleForPsiElement(psiElement) != null) { // PsiDirectoryNode doesn't render files outside of a project // let's use PsiDirectoryNode only for folders in a modules return new PsiDirectoryNode(myProject, (PsiDirectory)psiElement, getSettings()); } else if (psiElement instanceof PsiFile) { return new PsiFileNode(myProject, (PsiFile)psiElement, getSettings()); } else { return new VirtualFileTreeNode(myProject, file, getSettings()); } } } ); } private List<VirtualFile> getFilteredChildren(@NotNull VirtualFile folder) { return ContainerUtil.filter( folder.getChildren(), new Condition<VirtualFile>() { @Override public boolean value(VirtualFile file) { if (!file.isValid()) { return false; } //noinspection SimplifiableIfStatement if (file.isDirectory()) { // show even hidden folders like .pants.d and .idea return true; } return !file.getName().startsWith("."); } } ); } }
package test.dr.distibutions; import dr.math.distributions.GammaDistribution; import dr.math.functionEval.GammaFunction; import junit.framework.TestCase; public class GammaDistributionTest extends TestCase{ GammaDistribution gamma; public void setUp(){ gamma = new GammaDistribution(1.0,1.0); } /** * This test stochastically draws 100 gamma * variates and compares the coded pdf * with the actual pdf. * The tolerance is required to be at most 1e-10. */ public void testPdf(){ int numberOfTests = 50; for(int i = 0; i < numberOfTests; i++){ double j = i/500.0 + 1.0; double shape = 1.0/j; double scale = j; gamma.setShape(shape); gamma.setScale(scale); double value = gamma.nextGamma(); double mypdf = Math.pow(value, shape-1)/GammaFunction.gamma(shape) *Math.exp(-value/scale)/Math.pow(scale, shape); assertEquals(mypdf,gamma.pdf(value),1e-10); } gamma.setScale(1.0); gamma.setShape(1.0); } }
package com.valkryst.VTerminal.builder.component; import com.valkryst.VRadio.Radio; import com.valkryst.VTerminal.Panel; import com.valkryst.VTerminal.component.LoadingBar; import lombok.Getter; import lombok.Setter; import java.awt.*; public class LoadingBarBuilder extends ComponentBuilder<LoadingBar, LoadingBarBuilder> { /** The width of the loading bar, in characters. */ @Getter private int width; /** The height of the loading bar, in characters. */ @Getter private int height; /** The radio to transmit events to. */ @Getter private Radio<String> radio; /** The character that represents an incomplete cell. */ @Getter private char incompleteCharacter; /** The character that represents a complete cell. */ @Getter private char completeCharacter; /** The background color for incomplete cells. */ @Getter private Color backgroundColor_incomplete; /** The foreground color for incomplete cells. */ @Getter private Color foregroundColor_incomplete; /** The background color for complete cells. */ @Getter private Color backgroundColor_complete; /** The foreground color for complete cells. */ @Getter private Color foregroundColor_complete; @Override public LoadingBar build() throws IllegalStateException { checkState(); final LoadingBar loadingBar = new LoadingBar(this); super.panel.addComponent(loadingBar); return loadingBar; } protected void checkState() throws IllegalStateException { super.checkState(); if (radio == null) { throw new IllegalStateException("The box must have a radio to transmit to."); } } /** Resets the builder to it's default state. */ public void reset() { super.reset(); width = 10; height = 1; radio = null; incompleteCharacter = ''; completeCharacter = ''; backgroundColor_incomplete = new Color(0x366C9F);; foregroundColor_incomplete = Color.RED; backgroundColor_complete = new Color(0x366C9F);; foregroundColor_complete = Color.GREEN; } /** * Sets the width of the loading bar, in characters. * * @param width * The new width. * * @return * This. */ public LoadingBarBuilder setWidth(final int width) { if (width >= 1) { this.width = width; } return this; } /** * Sets the height of the loading bar, in characters. * * @param height * The new height. * * @return * This. */ public LoadingBarBuilder setHeight(final int height) { if (height >= 1) { this.height = height; } return this; } /** * Sets the character that represents an incomplete cell. * * @param incompleteCharacter * The character. * * @return * This. */ public LoadingBarBuilder setIncompleteCharacter(final char incompleteCharacter) { this.incompleteCharacter = incompleteCharacter; return this; } /** * Sets the character that represents a complete cell. * * @param completeCharacter * The character. * * @return * This. */ public LoadingBarBuilder setCompleteCharacter(final char completeCharacter) { this.completeCharacter = completeCharacter; return this; } /** * Sets the background color for incomplete cells * * @param backgroundColor_incomplete * The color. * * @return * This. */ public LoadingBarBuilder setBackgroundColor_incomplete(final Color backgroundColor_incomplete) { if (backgroundColor_incomplete != null) { this.backgroundColor_incomplete = backgroundColor_incomplete; } return this; } /** * Sets the foreground color for incomplete cells * * @param foregroundColor_incomplete * The color. * * @return * This. */ public LoadingBarBuilder setForegroundColor_incomplete(final Color foregroundColor_incomplete) { if (foregroundColor_incomplete != null) { this.foregroundColor_incomplete = foregroundColor_incomplete; } return this; } /** * Sets the background color for complete cells * * @param backgroundColor_complete * The color. * * @return * This. */ public LoadingBarBuilder setBackgroundColor_complete(final Color backgroundColor_complete) { if (backgroundColor_complete != null) { this.backgroundColor_complete = backgroundColor_complete; } return this; } /** * Sets the foreground color for complete cells * * @param foregroundColor_complete * The color. * * @return * This. */ public LoadingBarBuilder setForegroundColor_complete(final Color foregroundColor_complete) { if (foregroundColor_complete != null) { this.foregroundColor_complete = foregroundColor_complete; } return this; } }
package com.jcabi.immutable; import com.jcabi.aspects.Tv; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.Test; /** * Test case for {@link ArrayMap}. * @author Yegor Bugayenko (yegor@woquo.com) * @version $Id$ */ public final class ArrayMapTest { /** * ArrayMap can work as a map. * @throws Exception If some problem inside */ @Test public void worksAsANormalMap() throws Exception { final ConcurrentMap<Integer, String> map = new ConcurrentHashMap<Integer, String>(0); final String value = "first value"; map.put(1, value); map.put(2, "second"); MatcherAssert.assertThat( new ArrayMap<Integer, String>(map), Matchers.hasEntry(1, value) ); } /** * ArrayMap can make a map fluently. * @throws Exception If some problem inside */ @Test public void buildsMapFluently() throws Exception { MatcherAssert.assertThat( new ArrayMap<Integer, String>() .with(Tv.FIVE, "four") .with(Tv.FIVE, Integer.toString(Tv.FIVE)) .with(Tv.FORTY, "fourty") .without(Tv.FORTY) .with(Tv.TEN, "ten"), Matchers.allOf( Matchers.not(Matchers.hasKey(Tv.FORTY)), Matchers.hasValue(Integer.toString(Tv.FIVE)), Matchers.hasKey(Tv.FIVE), Matchers.hasEntry(Tv.FIVE, Integer.toString(Tv.FIVE)) ) ); } /** * ArrayMap can be equal to another map. * @throws Exception If some problem inside */ @Test public void comparesCorrectlyWithAnotherMap() throws Exception { MatcherAssert.assertThat( new ArrayMap<Integer, Integer>().with(1, 1).with(2, 2), Matchers.equalTo( new ArrayMap<Integer, Integer>().with(2, 2).with(1, 1) ) ); MatcherAssert.assertThat( new ArrayMap<Class<?>, Integer>() .with(String.class, 1) .with(Integer.class, 2), Matchers.equalTo( new ArrayMap<Class<?>, Integer>() .with(Integer.class, 2) .with(String.class, 1) ) ); } /** * ArrayMap can sort keys. * @throws Exception If some problem inside */ @Test public void sortsKeys() throws Exception { MatcherAssert.assertThat( new ArrayMap<Integer, String>() .with(Tv.FIVE, "") .with(Tv.FOUR, "") .with(1, "") .with(Tv.TEN, "") .keySet(), Matchers.hasToString("[1, 4, 5, 10]") ); } }
package com.vtence.mario; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.WebDriverException; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; public class DynamicHtmlTest extends WebTest { @Test public void assertingAnElementExists() { open("async-create.html"); browser.element(By.id("born")).exists(); } @Test public void assertingAnElementNoLongerExists() { open("async-delete.html"); browser.element(By.id("ghost")).exists(); browser.element(By.id("ghost")).isMissing(); } @Test public void assertingAnElementTextMatchesAGivenValue() { open("async-text-mutation.html"); browser.element(By.id("mutant")).hasText(containsString("Success")); } @Test public void assertingAnElementIsDisplayed() { open("async-display.html"); browser.element(By.id("secret")).isHidden(); browser.element(By.id("secret")).isShowingOnScreen(); } @Test public void assertingAnElementIsEnabled() { open("async-enable.html"); browser.element(By.id("action")).isDisabled(); browser.element(By.id("action")).isEnabled(); } @Test public void assertingAnElementState() { open("async-visible.html"); browser.element(By.id("action")).is(element -> { try { element.click(); return true; } catch (WebDriverException notClickable) { return false; } }, "clickable", "not clickable"); } @Test public void assertingAnElementProperty() { open("async-visible.html"); browser.element(By.id("action")).has("visibility", e -> e.getCssValue("visibility"), equalTo("hidden")); browser.element(By.id("action")).has("visibility", e -> e.getCssValue("visibility"), equalTo("visible")); } }
package dk.itu.kelvin.math; // JUnit annotations import org.junit.Test; // JUnit assertions import static org.junit.Assert.assertTrue; public final class HaversineTest { /** * Test the distance between two specified coordinates. */ @Test public void testDistance() { final double lat1 = 55.659890; final double lon1 = 12.591188; final double lat2 = 55.675637; final double lon2 = 12.569544; // we accept a deviation of 2 %. double realDist1 = 2.216 * 1.01; double realDist2 = 2.216 * 0.99; double ourDist = Haversine.distance(lat1, lon1, lat2, lon2) * 0.99; assertTrue( ourDist < realDist1); assertTrue( ourDist > realDist2); // from ITU to Bahamas. final double lat3 = 55.659890; final double lon3 = 12.591188; final double lat4 = 24.15; final double lon4 = 76.0; // we accept a deviation of 2 %. double realDist3 = 6159.197 * 1.02; double realDist4 = 6159.197 * 0.98; double ourDist1 = Haversine.distance(lat3, lon3, lat4, lon4) * 0.99; assertTrue( ourDist1 < realDist3); assertTrue( ourDist1 > realDist4); } }
package io.openshift.booster; import io.restassured.RestAssured; import io.restassured.response.Response; import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.openshift.client.*; import org.arquillian.cube.openshift.impl.enricher.AwaitRoute; import org.arquillian.cube.openshift.impl.enricher.RouteURL; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.junit.*; import org.junit.runner.RunWith; import org.junit.runners.MethodSorters; import java.net.MalformedURLException; import java.net.URL; import java.util.concurrent.TimeUnit; import static org.awaitility.Awaitility.await; import static io.restassured.RestAssured.get; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.core.IsEqual.equalTo; /** * Check the behavior of the application when running in OpenShift. */ @FixMethodOrder(MethodSorters.NAME_ASCENDING) @RunWith(Arquillian.class) public class OpenShiftIT { @RouteURL("${app.name}") @AwaitRoute private URL route; @ArquillianResource private OpenShiftClient oc; @Before public void setup() { RestAssured.baseURI = route.toString(); } @Test public void testAThatWeAreReady() { await().atMost(5, TimeUnit.MINUTES).catchUncaughtExceptions().until(() -> { Response response = get(); return response.getStatusCode() < 500; }); } @Test public void testBThatWeServeAsExpected() { get("/api/greeting").then().body("content", equalTo("Hello, World from a ConfigMap !")); get("/api/greeting?name=vert.x").then().body("content", equalTo("Hello, vert.x from a ConfigMap !")); } @Test public void testCThatWeCanReloadTheConfiguration() { ConfigMap map = oc.configMaps().withName("app-config").get(); assertThat(map).isNotNull(); oc.configMaps().withName("app-config").edit() .addToData("app-config.yml", "message : \"Bonjour, %s from a ConfigMap !\"") .done(); await().atMost(5, TimeUnit.MINUTES).catchUncaughtExceptions().until(() -> { Response response = get("/api/greeting"); return response.getStatusCode() < 500 && response.asString().contains("Bonjour"); }); get("/api/greeting?name=vert.x").then().body("content", equalTo("Bonjour, vert.x from a ConfigMap !")); } @Test public void testDThatWeServeErrorWithoutConfigMap() { get("/api/greeting").then().statusCode(200); oc.configMaps().withName("app-config").delete(); await().atMost(5, TimeUnit.MINUTES).catchUncaughtExceptions().untilAsserted(() -> get("/api/greeting").then().statusCode(500) ); } }
package junit.tests.framework; import junit.framework.AssertionFailedError; import junit.framework.ComparisonFailure; import junit.framework.TestCase; public class AssertTest extends TestCase { /* In the tests that follow, we can't use standard formatting * for exception tests: * try { * somethingThatShouldThrow(); * fail(); * catch (AssertionFailedError e) { * } * because fail() would never be reported. */ // public void assertGreaterThanPrimitiveTest() { // try{ // assertGreaterThanPrimitiveTest(null,null); // fail("eccezione non lanciata"); // catch (NullPointerException e){ // //eccezione lanciata // assertTrue(true); public void testFail() { // Also, we are testing fail, so we can't rely on fail() working. // We have to throw the exception manually. try { fail(); } catch (AssertionFailedError e) { return; } throw new AssertionFailedError(); } public void testAssertionFailedErrorToStringWithNoMessage() { // Also, we are testing fail, so we can't rely on fail() working. // We have to throw the exception manually. try { fail(); } catch (AssertionFailedError e) { assertEquals("junit.framework.AssertionFailedError", e.toString()); return; } throw new AssertionFailedError(); } public void testAssertionFailedErrorToStringWithMessage() { // Also, we are testing fail, so we can't rely on fail() working. // We have to throw the exception manually. try { fail("woops!"); } catch (AssertionFailedError e) { assertEquals("junit.framework.AssertionFailedError: woops!", e.toString()); return; } throw new AssertionFailedError(); } public void testAssertEquals() { Object o = new Object(); assertEquals(o, o); try { assertEquals(new Object(), new Object()); } catch (AssertionFailedError e) { return; } fail(); } public void testAssertEqualsNull() { assertEquals((Object) null, (Object) null); } public void testAssertStringEquals() { assertEquals("a", "a"); } public void testAssertNullNotEqualsString() { try { assertEquals(null, "foo"); fail(); } catch (ComparisonFailure e) { } } public void testAssertStringNotEqualsNull() { try { assertEquals("foo", null); fail(); } catch (ComparisonFailure e) { e.getMessage(); // why no assertion? } } public void testAssertNullNotEqualsNull() { try { assertEquals(null, new Object()); } catch (AssertionFailedError e) { e.getMessage(); // why no assertion? return; } fail(); } public void testAssertNull() { assertNull(null); try { assertNull(new Object()); } catch (AssertionFailedError e) { return; } fail(); } public void testAssertNotNull() { assertNotNull(new Object()); try { assertNotNull(null); } catch (AssertionFailedError e) { return; } fail(); } public void testAssertTrue() { assertTrue(true); try { assertTrue(false); } catch (AssertionFailedError e) { return; } fail(); } public void testAssertFalse() { assertFalse(false); try { assertFalse(true); } catch (AssertionFailedError e) { return; } fail(); } public void testAssertSame() { Object o = new Object(); assertSame(o, o); try { assertSame(new Integer(1), new Integer(1)); } catch (AssertionFailedError e) { return; } fail(); } public void testAssertNotSame() { assertNotSame(new Integer(1), null); assertNotSame(null, new Integer(1)); assertNotSame(new Integer(1), new Integer(1)); try { Integer obj = new Integer(1); assertNotSame(obj, obj); } catch (AssertionFailedError e) { return; } fail(); } public void testAssertNotSameFailsNull() { try { assertNotSame(null, null); } catch (AssertionFailedError e) { return; } fail(); } }
package org.junit.tests; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import java.util.List; import org.hamcrest.Matcher; import org.junit.Test; import org.junit.internal.matchers.TypeSafeMatcher; import org.junit.runner.Description; import org.junit.runner.JUnitCore; import org.junit.runner.Request; import org.junit.runner.Result; import org.junit.runner.manipulation.Filter; import org.junit.runner.notification.RunNotifier; import org.junit.runners.BlockJUnit4ClassRunner; import org.junit.runners.ParentRunner; import org.junit.runners.model.InitializationError; import org.junit.runners.model.RunnerScheduler; public class ParentRunnerTest { public static String log= ""; public static class FruitTest { @Test public void apple() { log+= "apple "; } @Test public void banana() { log+= "banana "; } } @Test public void useChildHarvester() throws InitializationError { log= ""; ParentRunner<?> runner= new BlockJUnit4ClassRunner(FruitTest.class); runner.setScheduler(new RunnerScheduler() { public void schedule(Runnable childStatement) { log+= "before "; childStatement.run(); log+= "after "; } public void finished() { log+= "afterAll "; } }); runner.run(new RunNotifier()); assertEquals("before apple after before banana after afterAll ", log); } @Test public void testMultipleFilters() throws Exception { JUnitCore junitCore= new JUnitCore(); Request request= Request.aClass(ExampleTest.class); Request requestFiltered= request.filterWith(new Exclude("test1")); Request requestFilteredFiltered= requestFiltered .filterWith(new Exclude("test2")); Result result= junitCore.run(requestFilteredFiltered); assertThat(result.getFailures(), isEmpty()); assertEquals(1, result.getRunCount()); } private Matcher<List<?>> isEmpty() { return new TypeSafeMatcher<List<?>>() { public void describeTo(org.hamcrest.Description description) { description.appendText("is empty"); } @Override public boolean matchesSafely(List<?> item) { return item.size() == 0; } }; } private static class Exclude extends Filter { private String methodName; public Exclude(String methodName) { this.methodName= methodName; } @Override public boolean shouldRun(Description description) { return !description.getMethodName().equals(methodName); } @Override public String describe() { return "filter method name: " + methodName; } } public static class ExampleTest { @Test public void test1() throws Exception { } @Test public void test2() throws Exception { } @Test public void test3() throws Exception { } } }
package org.myrobotlab.service; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.util.Arrays; import org.junit.Test; import org.myrobotlab.math.interfaces.Mapper; import org.myrobotlab.test.AbstractTest; /** * * @author GroG / kwatters * * FIXME - test one servo against EVERY TYPE OF CONTROLLER * (virtualized) !!!! iterate through all types * * FIXME - what is expected behavior when a s1 is attached at pin 3, * then a new servo s2 is requested to attach at pin 3 ? * * FIXME - test attach and isAttached on every controller */ public class ServoTest extends AbstractTest { static final String port01 = "COM9"; Integer pin = 5; @Test public void invertTest() throws Exception { // verify the outputs are inverted as expected. Servo servo01 = (Servo) Runtime.start("s1", "Servo"); Arduino arduino01 = (Arduino) Runtime.start("arduino01", "Arduino"); arduino01.connect(port01); servo01.attach(arduino01, 8, 40.0); servo01.enable(); servo01.setRest(90.0); servo01.rest(); servo01.moveTo(30.0); assertEquals(30.0, servo01.getTargetOutput(), 0.001); servo01.setInverted(true); assertEquals(150.0, servo01.getTargetOutput(), 0.001); servo01.moveTo(20.0); assertEquals(160.0, servo01.getTargetOutput(), 0.001); servo01.setInverted(false); assertEquals(20.0, servo01.getTargetOutput(), 0.001); } @Test public void mapTest() throws Exception { Servo servo01 = (Servo) Runtime.start("s1", "Servo"); Arduino arduino01 = (Arduino) Runtime.start("arduino01", "Arduino"); arduino01.connect(port01); servo01.attach(arduino01, 8, 40.0); servo01.setInverted(true); servo01.map(10, 170, 20, 160); Mapper mapper = servo01.getMapper(); assertTrue(mapper.isInverted()); servo01.setInverted(false); servo01.map(20, 160, 10, 170); assertFalse(mapper.isInverted()); assertEquals(20.0, mapper.getMinX(), 0.001); assertEquals(160.0, mapper.getMaxX(), 0.001); assertEquals(10.0, mapper.getMinY(), 0.001); assertEquals(170.0, mapper.getMaxY(), 0.001); } @Test public void testServo() throws Exception { // this basic test will create a servo and attach it to an arduino. // then detach Runtime runtime = Runtime.getInstance(); runtime.setVirtual(true); // Runtime.start("gui", "SwingGui"); Arduino arduino01 = (Arduino) Runtime.start("arduino01", "Arduino"); arduino01.connect(port01); Servo s = (Servo) Runtime.start("ser1", "Servo"); // the pin should always be set to something. s.setPin(pin); assertEquals(pin + "", s.getPin()); s.attach(arduino01); // maybe remove this interface // s.attach(ard1); // s.attachServoController(ard1); s.disable(); s.attach(arduino01); // This is broken // assertTrue(s.controller == ard2); s.rest(); assertEquals(s.getRest(), 90.0, 0.0); s.setRest(12.2); assertEquals(s.getRest(), 12.2, 0.0); s.rest(); // depricated. i feel like if you do s.enable(); s.moveTo(90.0); // test moving to the same position s.moveTo(90.0); // new position s.moveTo(91.0); s.disable(); assertFalse(s.isEnabled()); s.enable(); assertTrue(s.isEnabled()); // detach the servo. // ard2.detach(s); s.detach(arduino01); s.attach(arduino01, 10, 1.0); assertTrue(s.isEnabled()); s.disable(); assertFalse(s.isEnabled()); s.detach(arduino01); } @Test public void releaseService() { Servo servo01 = (Servo) Runtime.start("servo01", "Servo"); // Release the servo. servo01.releaseService(); assertNull(Runtime.getService("servo01")); } @Test public void testAutoDisable() throws Exception { // Start the test servo. Servo servo01 = (Servo) Runtime.start("servo01", "Servo"); Arduino arduino01 = (Arduino) Runtime.start("arduino01", "Arduino"); arduino01.connect(port01); servo01 = (Servo) Runtime.start("servo01", "Servo"); servo01.detach(); servo01.setPin(pin); servo01.setPosition(0.0); arduino01.attach(servo01); assertTrue("verifying servo is attached to the arduino.", servo01.isAttached("arduino01")); assertTrue("verifying servo should be enabled", servo01.isEnabled()); // Disable auto disable.. and move the servo. servo01.setAutoDisable(false); assertFalse("setting autoDisable false", servo01.isAutoDisable()); // choose a speed for this test. servo01.setSpeed(180.0); // set the timeout to 1/2 a second for the unit test. // Ok. now if we disable.. and move the servo.. it should be disabled after a certain amount of time. servo01.setIdleTimeout(500); assertEquals(500, servo01.getIdleTimeout()); servo01.setAutoDisable(true); servo01.moveTo(1.0); // we should move it and make sure it remains enabled. sleep(servo01.getIdleTimeout() + 500); assertTrue("Servo should be disabled.", !servo01.isEnabled()); log.warn("thread list {}", getThreadNames()); assertTrue("setting autoDisable true", servo01.isAutoDisable()); servo01.moveTo(2.0); sleep(servo01.getIdleTimeout()+500); // waiting for disable assertFalse("servo should have been disabled", servo01.isEnabled()); assertEquals(2.0, servo01.getCurrentInputPos(), 0.0001); } @Test public void moveToBlockingTest() throws Exception { Servo servo01 = (Servo) Runtime.start("servo01", "Servo"); Arduino arduino01 = (Arduino) Runtime.start("arduino01", "Arduino"); arduino01.connect(port01); servo01.setPosition(0.0); servo01.setPin(7); // use auto disable with a blocking move. servo01.setAutoDisable(true); // 60 degrees per second.. move from 0 to 180 in 3 seconds servo01.setSpeed(60.0); arduino01.attach(servo01); // Do I need to enable it?! servo01.enable(); long start = System.currentTimeMillis(); servo01.moveToBlocking(180.0); long delta = System.currentTimeMillis() - start; assertTrue("Move to blocking should have taken more than 3 seconds.", delta > 3000); // log.info("Move to blocking took {} milliseconds", delta); assertTrue("Servo should be ebabled", servo01.isEnabled()); assertFalse("Servo should not be moving now.", servo01.isMoving()); // Now let's wait for the idle disable timer to kick off + 1000ms // TODO: figure out why smaller values like 100ms cause this test to fail. // there seems to be some lag Thread.sleep(servo01.getIdleTimeout() + 1000); assertFalse("Servo should be disabled.", servo01.isEnabled()); } @Test public void testHelperMethods() throws Exception { Servo servo01 = (Servo) Runtime.start("servo01", "Servo"); Arduino arduino01 = (Arduino) Runtime.start("arduino01", "Arduino"); arduino01.connect(port01); servo01.setPosition(0.0); // 60 degrees per second.. move from 0 to 180 in 3 seconds servo01.setSpeed(60.0); servo01.setPin(7); servo01.attach("arduino01", 8, 1.0, 360.0); assertEquals("arduino01", servo01.getController()); assertEquals(Integer.valueOf(8).toString(), servo01.getPin()); servo01.unsetSpeed(); assertNull("Speed should be unset", servo01.getSpeed()); // verify that setMinMax sets both the input and output min/max values. servo01.setMinMax(10, 20); Mapper m = servo01.getMapper(); assertEquals(10, m.getMinX(), 0.001); assertEquals(10, m.getMinY(), 0.001); assertEquals(20, m.getMaxX(), 0.001); assertEquals(20, m.getMaxY(), 0.001); // now let's update the output mapping only. servo01.setMinMaxOutput(90, 180); assertEquals(10, m.getMinX(), 0.001); assertEquals(20, m.getMaxX(), 0.001); assertEquals(90, m.getMinY(), 0.001); assertEquals(180, m.getMaxY(), 0.001); servo01.map(0, 180, 42, 43); m = servo01.getMapper(); assertEquals(0, m.getMinX(), 0.001); assertEquals(180, m.getMaxX(), 0.001); assertEquals(42, m.getMinY(), 0.001); assertEquals(43, m.getMaxY(), 0.001); assertEquals(42, servo01.getMin(), 0.001); assertEquals(43, servo01.getMax(), 0.001); servo01.moveTo(90.0); assertEquals(90.0, servo01.getTargetPos(), 0.001); servo01.setSpeed(180.0); // servo velocity is speed now.. assertEquals(180.0, servo01.getVelocity(), 0.001); servo01.setVelocity(90.0); // servo velocity is speed now.. assertEquals(90.0, servo01.getSpeed(), 0.001); // by default the servo is not inverted assertFalse(servo01.isInverted()); servo01.setInverted(true); assertTrue(servo01.isInverted()); // you know for ol' times sake. servo01.enableAutoDisable(true); assertTrue(servo01.isAutoDisable()); } // TODO: test sweeping // TODO: test stopping a servo in the middle of a movement. // TOOD: implement and test waitTargetPos for servo. // TODO: publishMoveTo doesn't get exercised in this test // TODO: publishServoEnable is not exercised // TODO: publishServoMoveTo // TODO: publishServoStop // TODO: setting a custom mapper }
package seedu.taskitty.testutil; import com.google.common.io.Files; import guitests.guihandles.TaskCardHandle; import javafx.geometry.Bounds; import javafx.geometry.Point2D; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyCodeCombination; import javafx.scene.input.KeyCombination; import junit.framework.AssertionFailedError; import org.loadui.testfx.GuiTest; import org.testfx.api.FxToolkit; import seedu.taskitty.TestApp; import seedu.taskitty.commons.exceptions.IllegalValueException; import seedu.taskitty.commons.util.FileUtil; import seedu.taskitty.commons.util.XmlUtil; import seedu.taskitty.model.TaskManager; import seedu.taskitty.model.tag.Tag; import seedu.taskitty.model.tag.UniqueTagList; import seedu.taskitty.model.task.*; import seedu.taskitty.storage.XmlSerializableTaskManager; import java.io.File; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.time.LocalDate; import java.time.LocalTime; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.TimeoutException; import java.util.stream.Collectors; /** * A utility class for test cases. */ public class TestUtil { public static String LS = System.lineSeparator(); /** * Folder used for temp files created during testing. Ignored by Git. */ public static String SANDBOX_FOLDER = FileUtil.getPath("./src/test/data/sandbox/"); public static final Task[] sampleTaskData = getSampleTaskData(); //@@author A0139930B private static Task[] getSampleTaskData() { try { return new Task[]{ new Task(new Name("todo task"), new TaskPeriod(), new UniqueTagList()), new Task(new Name("deadline task"), new TaskPeriod(new TaskDate("23/12/2016"), new TaskTime("08:00")), new UniqueTagList()), new Task(new Name("event task"), new TaskPeriod(new TaskDate("13/12/2016"), new TaskTime("13:00"), new TaskDate("15/12/2016"), new TaskTime("10:00")), new UniqueTagList()), new Task(new Name("read clean code task"), new TaskPeriod(), new UniqueTagList()), new Task(new Name("spring cleaning task"), new TaskPeriod(new TaskDate("31/12/2016"), new TaskTime("15:00")), new UniqueTagList()), new Task(new Name("shop for xmas task"), new TaskPeriod(new TaskDate("12/12/2016"), new TaskTime("10:00"), new TaskDate("12/12/2016"), new TaskTime("19:00")), new UniqueTagList()), new Task(new Name("xmas dinner task"), new TaskPeriod(new TaskDate("25/12/2016"), new TaskTime("18:30"), new TaskDate("26/12/2016"), new TaskTime("02:00")), new UniqueTagList()) }; } catch (IllegalValueException e) { assert false; //not possible return null; } } //@@author public static void assertThrows(Class<? extends Throwable> expected, Runnable executable) { try { executable.run(); } catch (Throwable actualException) { if (!actualException.getClass().isAssignableFrom(expected)) { String message = String.format("Expected thrown: %s, actual: %s", expected.getName(), actualException.getClass().getName()); throw new AssertionFailedError(message); } else return; } throw new AssertionFailedError( String.format("Expected %s to be thrown, but nothing was thrown.", expected.getName())); } public static final Tag[] sampleTagData = getSampleTagData(); private static Tag[] getSampleTagData() { try { return new Tag[]{ new Tag("relatives"), new Tag("friends") }; } catch (IllegalValueException e) { assert false; return null; //not possible } } /** * Returns a String representing today's date plus daysToAdd * String format is the format for Storage from TaskDate, DATE_FORMATTER_STORAGE * * @param daysToAdd is the number of days to add to today. Can be negative. */ public static String getDateFromToday(int daysToAdd) { LocalDate today = LocalDate.now(); today.plusDays(daysToAdd); return today.format(TaskDate.DATE_FORMATTER_STORAGE); } /** * Returns a String representing today's date * String format is the format for Storage from TaskDate, DATE_FORMATTER_STORAGE */ public static String getDateToday() { return getDateFromToday(0); } /** * Returns a String representing the current time * String format is the format for Storage from TaskTime, TIME_FORMATTER_STORAGE * * @param minutesToAdd is the number of minutes to the current time. Can be negative. */ public static String getTimeFromNow(int minutesToAdd) { LocalTime now = LocalTime.now(); now.plusMinutes(minutesToAdd); return now.format(TaskTime.TIME_FORMATTER_STORAGE); } /** * Returns a String representing the current time * String format is the format for Storage from TaskTime, TIME_FORMATTER_STORAGE */ public static String getTimeNow() { return getTimeFromNow(0); } public static List<Task> generateSampleTaskData() { return Arrays.asList(sampleTaskData); } /** * Appends the file name to the sandbox folder path. * Creates the sandbox folder if it doesn't exist. * @param fileName * @return */ public static String getFilePathInSandboxFolder(String fileName) { try { FileUtil.createDirs(new File(SANDBOX_FOLDER)); } catch (IOException e) { throw new RuntimeException(e); } return SANDBOX_FOLDER + fileName; } public static void createDataFileWithSampleData(String filePath) { createDataFileWithData(generateSampleStorageAddressBook(), filePath); } public static <T> void createDataFileWithData(T data, String filePath) { try { File saveFileForTesting = new File(filePath); FileUtil.createIfMissing(saveFileForTesting); XmlUtil.saveDataToFile(saveFileForTesting, data); } catch (Exception e) { throw new RuntimeException(e); } } public static void main(String... s) { createDataFileWithSampleData(TestApp.SAVE_LOCATION_FOR_TESTING); } public static TaskManager generateEmptyTaskManager() { return new TaskManager(new UniqueTaskList(), new UniqueTagList()); } public static XmlSerializableTaskManager generateSampleStorageAddressBook() { return new XmlSerializableTaskManager(generateEmptyTaskManager()); } /** * Tweaks the {@code keyCodeCombination} to resolve the {@code KeyCode.SHORTCUT} to their * respective platform-specific keycodes */ public static KeyCode[] scrub(KeyCodeCombination keyCodeCombination) { List<KeyCode> keys = new ArrayList<>(); if (keyCodeCombination.getAlt() == KeyCombination.ModifierValue.DOWN) { keys.add(KeyCode.ALT); } if (keyCodeCombination.getShift() == KeyCombination.ModifierValue.DOWN) { keys.add(KeyCode.SHIFT); } if (keyCodeCombination.getMeta() == KeyCombination.ModifierValue.DOWN) { keys.add(KeyCode.META); } if (keyCodeCombination.getControl() == KeyCombination.ModifierValue.DOWN) { keys.add(KeyCode.CONTROL); } keys.add(keyCodeCombination.getCode()); return keys.toArray(new KeyCode[]{}); } public static boolean isHeadlessEnvironment() { String headlessProperty = System.getProperty("testfx.headless"); return headlessProperty != null && headlessProperty.equals("true"); } public static void captureScreenShot(String fileName) { File file = GuiTest.captureScreenshot(); try { Files.copy(file, new File(fileName + ".png")); } catch (IOException e) { e.printStackTrace(); } } public static String descOnFail(Object... comparedObjects) { return "Comparison failed \n" + Arrays.asList(comparedObjects).stream() .map(Object::toString) .collect(Collectors.joining("\n")); } public static void setFinalStatic(Field field, Object newValue) throws NoSuchFieldException, IllegalAccessException{ field.setAccessible(true); // remove final modifier from field Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); // ~Modifier.FINAL is used to remove the final modifier from field so that its value is no longer // final and can be changed modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); field.set(null, newValue); } public static void initRuntime() throws TimeoutException { FxToolkit.registerPrimaryStage(); FxToolkit.hideStage(); } public static void tearDownRuntime() throws Exception { FxToolkit.cleanupStages(); } /** * Gets private method of a class * Invoke the method using method.invoke(objectInstance, params...) * * Caveat: only find method declared in the current Class, not inherited from supertypes */ public static Method getPrivateMethod(Class objectClass, String methodName) throws NoSuchMethodException { Method method = objectClass.getDeclaredMethod(methodName); method.setAccessible(true); return method; } public static void renameFile(File file, String newFileName) { try { Files.copy(file, new File(newFileName)); } catch (IOException e1) { e1.printStackTrace(); } } /** * Gets mid point of a node relative to the screen. * @param node * @return */ public static Point2D getScreenMidPoint(Node node) { double x = getScreenPos(node).getMinX() + node.getLayoutBounds().getWidth() / 2; double y = getScreenPos(node).getMinY() + node.getLayoutBounds().getHeight() / 2; return new Point2D(x,y); } /** * Gets mid point of a node relative to its scene. * @param node * @return */ public static Point2D getSceneMidPoint(Node node) { double x = getScenePos(node).getMinX() + node.getLayoutBounds().getWidth() / 2; double y = getScenePos(node).getMinY() + node.getLayoutBounds().getHeight() / 2; return new Point2D(x,y); } /** * Gets the bound of the node relative to the parent scene. * @param node * @return */ public static Bounds getScenePos(Node node) { return node.localToScene(node.getBoundsInLocal()); } public static Bounds getScreenPos(Node node) { return node.localToScreen(node.getBoundsInLocal()); } public static double getSceneMaxX(Scene scene) { return scene.getX() + scene.getWidth(); } public static double getSceneMaxY(Scene scene) { return scene.getX() + scene.getHeight(); } public static Object getLastElement(List<?> list) { return list.get(list.size() - 1); } /** * Removes a subset from the list of persons. * @param persons The list of persons * @param personsToRemove The subset of persons. * @return The modified persons after removal of the subset from persons. */ public static TestTask[] removePersonsFromList(final TestTask[] persons, TestTask... personsToRemove) { List<TestTask> listOfPersons = asList(persons); listOfPersons.removeAll(asList(personsToRemove)); return listOfPersons.toArray(new TestTask[listOfPersons.size()]); } /** * Returns a copy of the list with the person at specified index removed. * @param list original list to copy from * @param targetIndexInOneIndexedFormat e.g. if the first element to be removed, 1 should be given as index. */ public static TestTask[] removePersonFromList(final TestTask[] list, int targetIndexInOneIndexedFormat) { return removePersonsFromList(list, list[targetIndexInOneIndexedFormat-1]); } /** * Replaces persons[i] with a person. * @param persons The array of persons. * @param person The replacement person * @param index The index of the person to be replaced. * @return */ public static TestTask[] replacePersonFromList(TestTask[] persons, TestTask person, int index) { TestTask[] editedList = Arrays.copyOf(persons, persons.length); editedList[index] = person; return editedList; } /** * Appends persons to the array of persons. * @param persons A array of persons. * @param personsToAdd The persons that are to be appended behind the original array. * @return The modified array of persons. */ public static TestTask[] addPersonsToList(final TestTask[] persons, TestTask... personsToAdd) { List<TestTask> listOfPersons = asList(persons); listOfPersons.addAll(asList(personsToAdd)); return listOfPersons.toArray(new TestTask[listOfPersons.size()]); } private static <T> List<T> asList(T[] objs) { List<T> list = new ArrayList<>(); for(T obj : objs) { list.add(obj); } return list; } public static boolean compareCardAndPerson(TaskCardHandle card, ReadOnlyTask person) { return card.isSameTask(person); } public static Tag[] getTagList(String tags) { if ("".equals(tags)) { return new Tag[]{}; } final String[] split = tags.split(", "); final List<Tag> collect = Arrays.asList(split).stream().map(e -> { try { return new Tag(e.replaceFirst("Tag: ", "")); } catch (IllegalValueException e1) { //not possible assert false; return null; } }).collect(Collectors.toList()); return collect.toArray(new Tag[split.length]); } }
package org.jdesktop.swingx; import java.awt.Color; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.util.logging.Logger; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.BorderFactory; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.SwingUtilities; import javax.swing.border.Border; import javax.swing.event.TableModelEvent; import javax.swing.table.TableCellRenderer; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.MutableTreeNode; import javax.swing.tree.TreePath; import org.jdesktop.swingx.action.LinkAction; import org.jdesktop.swingx.decorator.HighlighterFactory; import org.jdesktop.swingx.renderer.ButtonProvider; import org.jdesktop.swingx.renderer.CellContext; import org.jdesktop.swingx.renderer.ComponentProvider; import org.jdesktop.swingx.renderer.DefaultTableRenderer; import org.jdesktop.swingx.renderer.DefaultTreeRenderer; import org.jdesktop.swingx.renderer.HyperlinkProvider; import org.jdesktop.swingx.renderer.LabelProvider; import org.jdesktop.swingx.renderer.StringValue; import org.jdesktop.swingx.renderer.WrappingIconPanel; import org.jdesktop.swingx.renderer.WrappingProvider; import org.jdesktop.swingx.test.ActionMapTreeTableModel; import org.jdesktop.swingx.test.ComponentTreeTableModel; import org.jdesktop.swingx.test.TreeTableUtils; import org.jdesktop.swingx.treetable.DefaultTreeTableModel; import org.jdesktop.swingx.treetable.FileSystemModel; import org.jdesktop.swingx.treetable.MutableTreeTableNode; import org.jdesktop.swingx.treetable.TreeTableModel; import org.jdesktop.swingx.treetable.TreeTableNode; import org.jdesktop.test.TableModelReport; /** * Test to exposed known issues of <code>JXTreeTable</code>. <p> * * Ideally, there would be at least one failing test method per open * issue in the issue tracker. Plus additional failing test methods for * not fully specified or not yet decided upon features/behaviour.<p> * * Once the issues are fixed and the corresponding methods are passing, they * should be moved over to the XXTest. * * @author Jeanette Winzenburg */ public class JXTreeTableIssues extends InteractiveTestCase { private static final Logger LOG = Logger.getLogger(JXTreeTableIssues.class .getName()); public static void main(String[] args) { setSystemLF(true); JXTreeTableIssues test = new JXTreeTableIssues(); try { test.runInteractiveTests(); // test.runInteractiveTests(".*Adapter.*"); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } public void testSetModel() { TreeTableModel model = createCustomTreeTableModelFromDefault(); JXTreeTable treeTable = new JXTreeTable(model); treeTable.setRootVisible(true); treeTable.setTreeTableModel(createCustomTreeTableModelFromDefault()); } /** * Issue #493-swingx: JXTreeTable.TreeTableModelAdapter: Inconsistency * firing update. * * Test update events after updating table. * * from tiberiu@dev.java.net */ public void testTableEventUpdateOnTreeTableSetValueForRoot() { TreeTableModel model = createCustomTreeTableModelFromDefault(); final JXTreeTable table = new JXTreeTable(model); table.setRootVisible(true); table.expandAll(); final int row = 0; // sanity assertEquals("JTree", table.getValueAt(row, 0).toString()); final TableModelReport report = new TableModelReport(); table.getModel().addTableModelListener(report); // doesn't fire or isn't detectable? // Problem was: model was not-editable. table.setValueAt("games", row, 0); SwingUtilities.invokeLater(new Runnable() { public void run() { assertEquals("tableModel must have fired", 1, report.getEventCount()); assertEquals("the event type must be update", 1, report.getUpdateEventCount()); TableModelEvent event = report.getLastUpdateEvent(); assertEquals("the updated row ", row, event.getFirstRow()); } }); } /** * Issue #493-swingx: incorrect table events fired. * * Here: must fire structureChanged on setRoot(null). * fails - because the treeStructureChanged is mapped to a * tableDataChanged. * */ public void testTableEventOnSetNullRoot() { TreeTableModel model = createCustomTreeTableModelFromDefault(); final JXTreeTable table = new JXTreeTable(model); table.setRootVisible(true); table.expandAll(); final TableModelReport report = new TableModelReport(); table.getModel().addTableModelListener(report); ((DefaultTreeModel) model).setRoot(null); SwingUtilities.invokeLater(new Runnable() { public void run() { assertEquals("tableModel must have fired", 1, report.getEventCount()); assertTrue("event type must be structureChanged " + TableModelReport.printEvent(report.getLastEvent()), report.isStructureChanged(report.getLastEvent())); } }); } /** * Issue #493-swingx: incorrect table events fired. * * Here: must fire structureChanged on setRoot(otherroot). * fails - because the treeStructureChanged is mapped to a * tableDataChanged. */ public void testTableEventOnSetRoot() { TreeTableModel model = createCustomTreeTableModelFromDefault(); final JXTreeTable table = new JXTreeTable(model); table.setRootVisible(true); table.expandAll(); final TableModelReport report = new TableModelReport(); table.getModel().addTableModelListener(report); ((DefaultTreeModel) model).setRoot(new DefaultMutableTreeNode("other")); SwingUtilities.invokeLater(new Runnable() { public void run() { assertEquals("tableModel must have fired", 1, report.getEventCount()); assertTrue("event type must be structureChanged " + TableModelReport.printEvent(report.getLastEvent()), report.isStructureChanged(report.getLastEvent())); } }); } /** * Issue #493-swingx: incorrect table events fired. * * Here: must fire structureChanged on setModel. * */ public void testTableEventOnSetModel() { TreeTableModel model = createCustomTreeTableModelFromDefault(); final JXTreeTable table = new JXTreeTable(model); table.setRootVisible(true); table.expandAll(); final TableModelReport report = new TableModelReport(); table.getModel().addTableModelListener(report); table.setTreeTableModel(createCustomTreeTableModelFromDefault()); SwingUtilities.invokeLater(new Runnable() { public void run() { assertEquals("tableModel must have fired", 1, report.getEventCount()); assertTrue("event type must be structureChanged " + TableModelReport.printEvent(report.getLastEvent()), report.isStructureChanged(report.getLastEvent())); } }); } /** * Issue #493-swingx: JXTreeTable.TreeTableModelAdapter: Inconsistency * firing update. * * Test update events after updating treeTableModel. * * from tiberiu@dev.java.net */ public void testTableEventUpdateOnTreeTableModelSetValue() { TreeTableModel model = createCustomTreeTableModelFromDefault(); final JXTreeTable table = new JXTreeTable(model); table.setRootVisible(true); table.expandAll(); final int row = 6; // sanity assertEquals("sports", table.getValueAt(row, 0).toString()); final TableModelReport report = new TableModelReport(); table.getModel().addTableModelListener(report); model.setValueAt("games", table.getPathForRow(6).getLastPathComponent(), 0); SwingUtilities.invokeLater(new Runnable() { public void run() { assertEquals("tableModel must have fired", 1, report.getEventCount()); assertEquals("the event type must be update", 1, report.getUpdateEventCount()); TableModelEvent event = report.getLastUpdateEvent(); assertEquals("the updated row ", row, event.getFirstRow()); } }); } /** * Issue #493-swingx: JXTreeTable.TreeTableModelAdapter: Inconsistency * firing update. * * Test delete events after tree table model. * * from tiberiu@dev.java.net */ public void testTableEventDeleteOnTreeTableModel() { TreeTableModel model = createCustomTreeTableModelFromDefault(); MutableTreeNode root = (MutableTreeNode) model.getRoot(); MutableTreeNode sportsNode = (MutableTreeNode) root.getChildAt(1); int childrenToDelete = sportsNode.getChildCount() - 1; for (int i = 0; i < childrenToDelete; i++) { MutableTreeNode firstChild = (MutableTreeNode) sportsNode.getChildAt(0); ((DefaultTreeModel) model).removeNodeFromParent(firstChild); } // sanity assertEquals(1, sportsNode.getChildCount()); final JXTreeTable table = new JXTreeTable(model); table.setRootVisible(true); table.expandAll(); final int row = 6; // sanity assertEquals("sports", table.getValueAt(row, 0).toString()); final TableModelReport report = new TableModelReport(); table.getModel().addTableModelListener(report); // remove the last child from sports node MutableTreeNode firstChild = (MutableTreeNode) sportsNode.getChildAt(0); ((DefaultTreeModel) model).removeNodeFromParent(firstChild); SwingUtilities.invokeLater(new Runnable() { public void run() { assertEquals("tableModel must have fired exactly one event", 1, report.getEventCount()); TableModelEvent event = report.getLastEvent(); assertEquals("event type must be delete", TableModelEvent.DELETE, event.getType()); assertEquals("the deleted row ", row + 1, event.getFirstRow()); } }); } /** * Issue #493-swingx: JXTreeTable.TreeTableModelAdapter: Inconsistency * firing update. * * Test update events after updating table. * * from tiberiu@dev.java.net */ public void testTableEventUpdateOnTreeTableSetValue() { TreeTableModel model = createCustomTreeTableModelFromDefault(); final JXTreeTable table = new JXTreeTable(model); table.setRootVisible(true); table.expandAll(); final int row = 6; // sanity assertEquals("sports", table.getValueAt(row, 0).toString()); final TableModelReport report = new TableModelReport(); table.getModel().addTableModelListener(report); // doesn't fire or isn't detectable? // Problem was: model was not-editable. table.setValueAt("games", row, 0); SwingUtilities.invokeLater(new Runnable() { public void run() { assertEquals("tableModel must have fired", 1, report.getEventCount()); assertEquals("the event type must be update", 1, report.getUpdateEventCount()); TableModelEvent event = report.getLastUpdateEvent(); assertEquals("the updated row ", row, event.getFirstRow()); } }); } /** * Issue #493-swingx: JXTreeTable.TreeTableModelAdapter: Inconsistency * firing update. * Use the second child of root - first is accidentally okay. * * from tiberiu@dev.java.net */ public void interactiveTreeTableModelAdapterUpdate() { TreeTableModel customTreeTableModel = createCustomTreeTableModelFromDefault(); final JXTreeTable table = new JXTreeTable(customTreeTableModel); table.setRootVisible(true); table.expandAll(); table.setLargeModel(true); JXTree xtree = new JXTree(customTreeTableModel); xtree.setRootVisible(true); xtree.expandAll(); final JXFrame frame = wrapWithScrollingInFrame(table, xtree, "JXTreeTable.TreeTableModelAdapter: Inconsistency firing update"); Action changeValue = new AbstractAction("change sports to games") { public void actionPerformed(ActionEvent e) { String newValue = "games"; table.getTreeTableModel().setValueAt(newValue, table.getPathForRow(6).getLastPathComponent(), 0); } }; addAction(frame, changeValue); Action changeRoot = new AbstractAction("change root") { public void actionPerformed(ActionEvent e) { String newValue = "new Root"; table.getTreeTableModel().setValueAt(newValue, table.getPathForRow(0).getLastPathComponent(), 0); } }; addAction(frame, changeRoot); frame.pack(); frame.setVisible(true); } /** * Issue #493-swingx: JXTreeTable.TreeTableModelAdapter: Inconsistency * firing delete. * * from tiberiu@dev.java.net */ public void interactiveTreeTableModelAdapterDelete() { final TreeTableModel customTreeTableModel = createCustomTreeTableModelFromDefault(); final JXTreeTable table = new JXTreeTable(customTreeTableModel); table.setRootVisible(true); table.expandAll(); JXTree xtree = new JXTree(customTreeTableModel); xtree.setRootVisible(true); xtree.expandAll(); final JXFrame frame = wrapWithScrollingInFrame(table, xtree, "JXTreeTable.TreeTableModelAdapter: Inconsistency firing update"); Action changeValue = new AbstractAction("delete first child of sports") { public void actionPerformed(ActionEvent e) { MutableTreeNode firstChild = (MutableTreeNode) table.getPathForRow(6 +1).getLastPathComponent(); ((DefaultTreeModel) customTreeTableModel).removeNodeFromParent(firstChild); } }; addAction(frame, changeValue); frame.setVisible(true); } /** * Issue #493-swingx: JXTreeTable.TreeTableModelAdapter: Inconsistency * firing delete. * * from tiberiu@dev.java.net */ public void interactiveTreeTableModelAdapterMutateSelected() { final TreeTableModel customTreeTableModel = createCustomTreeTableModelFromDefault(); final JXTreeTable table = new JXTreeTable(customTreeTableModel); table.setRootVisible(true); table.expandAll(); JXTree xtree = new JXTree(customTreeTableModel); xtree.setRootVisible(true); xtree.expandAll(); final JXFrame frame = wrapWithScrollingInFrame(table, xtree, "JXTreeTable.TreeTableModelAdapter: Inconsistency firing delete expanded folder"); Action changeValue = new AbstractAction("delete selected node") { public void actionPerformed(ActionEvent e) { int row = table.getSelectedRow(); if (row < 0) return; MutableTreeNode firstChild = (MutableTreeNode) table.getPathForRow(row).getLastPathComponent(); ((DefaultTreeModel) customTreeTableModel).removeNodeFromParent(firstChild); } }; addAction(frame, changeValue); Action changeValue1 = new AbstractAction("insert as first child of selected node") { public void actionPerformed(ActionEvent e) { int row = table.getSelectedRow(); if (row < 0) return; MutableTreeNode firstChild = (MutableTreeNode) table.getPathForRow(row).getLastPathComponent(); MutableTreeNode newChild = new DefaultMutableTreeNode("inserted"); ((DefaultTreeModel) customTreeTableModel) .insertNodeInto(newChild, firstChild, 0); } }; addAction(frame, changeValue1); frame.pack(); frame.setVisible(true); } /** * Issue #493-swingx: JXTreeTable.TreeTableModelAdapter: Inconsistency * firing delete. * * from tiberiu@dev.java.net */ public void interactiveTreeTableModelAdapterMutateSelectedDiscontinous() { final TreeTableModel customTreeTableModel = createCustomTreeTableModelFromDefault(); final JXTreeTable table = new JXTreeTable(customTreeTableModel); table.setRootVisible(true); table.expandAll(); JXTree xtree = new JXTree(customTreeTableModel); xtree.setRootVisible(true); xtree.expandAll(); final JXFrame frame = wrapWithScrollingInFrame(table, xtree, "JXTreeTable.TreeTableModelAdapter: Inconsistency firing delete expanded folder"); Action changeValue = new AbstractAction("delete selected node + sibling") { public void actionPerformed(ActionEvent e) { int row = table.getSelectedRow(); if (row < 0) return; MutableTreeNode firstChild = (MutableTreeNode) table.getPathForRow(row).getLastPathComponent(); MutableTreeNode parent = (MutableTreeNode) firstChild.getParent(); MutableTreeNode secondNextSibling = null; int firstIndex = parent.getIndex(firstChild); if (firstIndex + 2 < parent.getChildCount()) { secondNextSibling = (MutableTreeNode) parent.getChildAt(firstIndex + 2); } if (secondNextSibling != null) { parent.remove(firstIndex + 2); parent.remove(firstIndex); int[] childIndices = new int[] {firstIndex, firstIndex + 2}; Object[] children = new Object[] {firstChild, secondNextSibling}; ((DefaultTreeModel) customTreeTableModel) .nodesWereRemoved(parent, childIndices, children); } else { // remove selected only ((DefaultTreeModel) customTreeTableModel).removeNodeFromParent(firstChild); } } }; addAction(frame, changeValue); Action changeValue1 = new AbstractAction("insert as first child of selected node") { public void actionPerformed(ActionEvent e) { int row = table.getSelectedRow(); if (row < 0) return; MutableTreeNode firstChild = (MutableTreeNode) table.getPathForRow(row).getLastPathComponent(); MutableTreeNode newChild = new DefaultMutableTreeNode("inserted"); ((DefaultTreeModel) customTreeTableModel) .insertNodeInto(newChild, firstChild, 0); } }; addAction(frame, changeValue1); frame.pack(); frame.setVisible(true); } /** * Creates and returns a custom model from JXTree default model. The model * is of type DefaultTreeModel, allowing for easy insert/remove. * * @return */ private TreeTableModel createCustomTreeTableModelFromDefault() { JXTree tree = new JXTree(); DefaultTreeModel treeModel = (DefaultTreeModel) tree.getModel(); TreeTableModel customTreeTableModel = TreeTableUtils .convertDefaultTreeModel(treeModel); return customTreeTableModel; } /** * A TreeTableModel inheriting from DefaultTreeModel (to ease * insert/delete). */ public static class CustomTreeTableModel extends DefaultTreeTableModel { /** * @param root */ public CustomTreeTableModel(TreeTableNode root) { super(root); } public int getColumnCount() { return 1; } public String getColumnName(int column) { return "User Object"; } public Object getValueAt(Object node, int column) { return ((DefaultMutableTreeNode) node).getUserObject(); } public boolean isCellEditable(Object node, int column) { return true; } public void setValueAt(Object value, Object node, int column) { ((MutableTreeTableNode) node).setUserObject(value); modelSupport.firePathChanged(new TreePath(getPathToRoot((TreeTableNode) node))); } } /** * Issue #??-swingx: hyperlink in JXTreeTable hierarchical column not * active. * */ public void interactiveTreeTableLinkRendererSimpleText() { LinkAction simpleAction = new LinkAction<Object>(null) { public void actionPerformed(ActionEvent e) { LOG.info("hit: " + getTarget()); } }; JXTreeTable tree = new JXTreeTable(new FileSystemModel()); HyperlinkProvider provider = new HyperlinkProvider(simpleAction); tree.getColumn(2).setCellRenderer(new DefaultTableRenderer(provider)); tree.setTreeCellRenderer(new DefaultTreeRenderer(provider)); // tree.setCellRenderer(new LinkRenderer(simpleAction)); tree.setHighlighters(HighlighterFactory.createSimpleStriping()); JFrame frame = wrapWithScrollingInFrame(tree, "table and simple links"); frame.setVisible(true); } /** * example how to use a custom component as * renderer in tree column of TreeTable. * */ public void interactiveTreeTableCustomRenderer() { JXTreeTable tree = new JXTreeTable(new FileSystemModel()); ComponentProvider provider = new ButtonProvider() { /** * show a unselected checkbox and text. */ @Override protected void format(CellContext context) { super.format(context); rendererComponent.setText(" ... " + getStringValue(context)); } /** * custom tooltip: show row. Note: the context is that * of the rendering tree. No way to get at table state? */ @Override protected void configureState(CellContext context) { super.configureState(context); rendererComponent.setToolTipText("Row: " + context.getRow()); } }; provider.setHorizontalAlignment(JLabel.LEADING); tree.setTreeCellRenderer(new DefaultTreeRenderer(provider)); tree.setHighlighters(HighlighterFactory.createSimpleStriping()); JFrame frame = wrapWithScrollingInFrame(tree, "treetable and custom renderer"); frame.setVisible(true); } /** * example how to use a custom component as * renderer in tree column of TreeTable. * */ public void interactiveTreeTableWrappingProvider() { final JXTreeTable treeTable = new JXTreeTable(createActionTreeModel()); treeTable.setHorizontalScrollEnabled(true); treeTable.packColumn(0, -1); StringValue format = new StringValue() { public String getString(Object value) { if (value instanceof Action) { return ((Action) value).getValue(Action.NAME) + "xx"; } return StringValue.TO_STRING.getString(value); } }; ComponentProvider tableProvider = new LabelProvider(format); TableCellRenderer tableRenderer = new DefaultTableRenderer(tableProvider); WrappingProvider wrappingProvider = new WrappingProvider(tableProvider) { Border redBorder = BorderFactory.createLineBorder(Color.RED); @Override public WrappingIconPanel getRendererComponent(CellContext context) { Dimension old = rendererComponent.getPreferredSize(); rendererComponent.setPreferredSize(null); super.getRendererComponent(context); Dimension dim = rendererComponent.getPreferredSize(); dim.width = Math.max(dim.width, treeTable.getColumn(0).getWidth()); rendererComponent.setPreferredSize(dim); rendererComponent.setBorder(redBorder); return rendererComponent; } }; DefaultTreeRenderer treeCellRenderer = new DefaultTreeRenderer(wrappingProvider); treeTable.setTreeCellRenderer(treeCellRenderer); treeTable.setHighlighters(HighlighterFactory.createSimpleStriping()); JXTree tree = new JXTree(treeTable.getTreeTableModel()); tree.setCellRenderer(treeCellRenderer); tree.setLargeModel(true); tree.setScrollsOnExpand(false); JFrame frame = wrapWithScrollingInFrame(treeTable, tree, "treetable and default wrapping provider"); frame.setVisible(true); } /** * Dirty example how to configure a custom renderer * to use treeTableModel.getValueAt(...) for showing. * */ public void interactiveTreeTableGetValueRenderer() { JXTreeTable tree = new JXTreeTable(new ComponentTreeTableModel(new JXFrame())); ComponentProvider provider = new ButtonProvider() { /** * show a unselected checkbox and text. */ @Override protected void format(CellContext context) { // this is dirty because the design idea was to keep the renderer // unaware of the context type TreeTableModel model = (TreeTableModel) ((JXTree) context.getComponent()).getModel(); // beware: currently works only if the node is not a DefaultMutableTreeNode // otherwise the WrappingProvider tries to be smart and replaces the node // by the userObject before passing on to the wrappee! Object nodeValue = model.getValueAt(context.getValue(), 0); rendererComponent.setText(" ... " + formatter.getString(nodeValue)); } /** * custom tooltip: show row. Note: the context is that * of the rendering tree. No way to get at table state? */ @Override protected void configureState(CellContext context) { super.configureState(context); rendererComponent.setToolTipText("Row: " + context.getRow()); } }; provider.setHorizontalAlignment(JLabel.LEADING); tree.setTreeCellRenderer(new DefaultTreeRenderer(provider)); tree.expandAll(); tree.setHighlighters(HighlighterFactory.createSimpleStriping()); JFrame frame = wrapWithScrollingInFrame(tree, "treeTable and getValueAt renderer"); frame.setVisible(true); } /** * Issue #399-swingx: editing terminated by selecting editing row. * */ public void testSelectionKeepsEditingWithExpandsTrue() { JXTreeTable treeTable = new JXTreeTable(new FileSystemModel()) { @Override public boolean isCellEditable(int row, int column) { return true; } }; // sanity: default value of expandsSelectedPath assertTrue(treeTable.getExpandsSelectedPaths()); boolean canEdit = treeTable.editCellAt(1, 2); // sanity: editing started assertTrue(canEdit); // sanity: nothing selected assertTrue(treeTable.getSelectionModel().isSelectionEmpty()); int editingRow = treeTable.getEditingRow(); treeTable.setRowSelectionInterval(editingRow, editingRow); assertEquals("after selection treeTable editing state must be unchanged", canEdit, treeTable.isEditing()); } /** * Issue #399-swingx: editing terminated by selecting editing row.<p> * Assert workaround: setExpandsSelectedPaths(false) */ public void testSelectionKeepsEditingWithExpandsFalse() { JXTreeTable treeTable = new JXTreeTable(new FileSystemModel()) { @Override public boolean isCellEditable(int row, int column) { return true; } }; boolean canEdit = treeTable.editCellAt(1, 2); // sanity: editing started assertTrue(canEdit); // sanity: nothing selected assertTrue(treeTable.getSelectionModel().isSelectionEmpty()); int editingRow = treeTable.getEditingRow(); treeTable.setExpandsSelectedPaths(false); treeTable.setRowSelectionInterval(editingRow, editingRow); assertEquals("after selection treeTable editing state must be unchanged", canEdit, treeTable.isEditing()); } /** * sanity: toggling select/unselect via mouse the lead is * always painted, doing unselect via model (clear/remove path) * seems to clear the lead? * */ public void testBasicTreeLeadSelection() { JXTree tree = new JXTree(); TreePath path = tree.getPathForRow(0); tree.setSelectionPath(path); assertEquals(0, tree.getSelectionModel().getLeadSelectionRow()); assertEquals(path, tree.getLeadSelectionPath()); tree.removeSelectionPath(path); assertNotNull(tree.getLeadSelectionPath()); assertEquals(0, tree.getSelectionModel().getLeadSelectionRow()); } /** * Issue #341-swingx: missing synch of lead. * test lead after remove selection via tree. * */ public void testLeadAfterRemoveSelectionFromTree() { JXTreeTable treeTable = prepareTreeTable(true); treeTable.getTreeSelectionModel().removeSelectionPath( treeTable.getTreeSelectionModel().getLeadSelectionPath()); assertEquals(treeTable.getSelectionModel().getLeadSelectionIndex(), treeTable.getTreeSelectionModel().getLeadSelectionRow()); } /** * Issue #341-swingx: missing synch of lead. * test lead after clear selection via table. * */ public void testLeadAfterClearSelectionFromTable() { JXTreeTable treeTable = prepareTreeTable(true); treeTable.clearSelection(); assertEquals(treeTable.getSelectionModel().getLeadSelectionIndex(), treeTable.getTreeSelectionModel().getLeadSelectionRow()); } /** * Issue #341-swingx: missing synch of lead. * test lead after clear selection via table. * */ public void testLeadAfterClearSelectionFromTree() { JXTreeTable treeTable = prepareTreeTable(true); treeTable.getTreeSelectionModel().clearSelection(); assertEquals(treeTable.getSelectionModel().getLeadSelectionIndex(), treeTable.getTreeSelectionModel().getLeadSelectionRow()); } /** * Issue #341-swingx: missing synch of lead. * test lead after setting selection via table. * */ public void testLeadSelectionFromTable() { JXTreeTable treeTable = prepareTreeTable(false); assertEquals(-1, treeTable.getSelectionModel().getLeadSelectionIndex()); assertEquals(-1, treeTable.getTreeSelectionModel().getLeadSelectionRow()); treeTable.setRowSelectionInterval(0, 0); assertEquals(treeTable.getSelectionModel().getLeadSelectionIndex(), treeTable.getTreeSelectionModel().getLeadSelectionRow()); } /** * Issue #341-swingx: missing synch of lead. * test lead after setting selection via treeSelection. * */ public void testLeadSelectionFromTree() { JXTreeTable treeTable = prepareTreeTable(false); assertEquals(-1, treeTable.getSelectionModel().getLeadSelectionIndex()); assertEquals(-1, treeTable.getTreeSelectionModel().getLeadSelectionRow()); treeTable.getTreeSelectionModel().setSelectionPath(treeTable.getPathForRow(0)); assertEquals(treeTable.getSelectionModel().getLeadSelectionIndex(), treeTable.getTreeSelectionModel().getLeadSelectionRow()); assertEquals(0, treeTable.getTreeSelectionModel().getLeadSelectionRow()); } /** * creates and configures a treetable for usage in selection tests. * * @param selectFirstRow boolean to indicate if the first row should * be selected. * @return */ protected JXTreeTable prepareTreeTable(boolean selectFirstRow) { JXTreeTable treeTable = new JXTreeTable(new ComponentTreeTableModel(new JXFrame())); treeTable.setRootVisible(true); // sanity: assert that we have at least two rows to change selection assertTrue(treeTable.getRowCount() > 1); if (selectFirstRow) { treeTable.setRowSelectionInterval(0, 0); } return treeTable; } public void testDummy() { } /** * @return */ private TreeTableModel createActionTreeModel() { JXTable table = new JXTable(10, 10); table.setHorizontalScrollEnabled(true); return new ActionMapTreeTableModel(table); } }
package de.Zorro.VierGewinnt.Main; import java.awt.Desktop; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintStream; import java.io.PrintWriter; import java.lang.ProcessBuilder.Redirect; import java.util.ArrayList; import java.util.Date; import java.util.LinkedList; import javax.script.Invocable; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; import JavaUtils.ClassLoader.UtilClass; import JavaUtils.ClassLoader.UtilClassBuilder; import de.Zorro.VierGewinnt.API.AI; import de.Zorro.VierGewinnt.Board.Board; import jline.console.ConsoleReader; public class VierGewinnt { private static boolean settable = false; private static Board b; private static AI ai1; private static AI ai2; private static int turn = 0; private static String aiName1; private static String aiName2; private static ConsoleReader cr; private static int lastWinner = -1; private static boolean log = false; private static boolean statisticsMode = false; private static int playingGames = 1; private static int playedGames = 0; private static int player1Wins = 0, player2Wins = 0; private static ArrayList<Double> times = new ArrayList<Double>(); private static ArrayList<Double> turnCounts = new ArrayList<Double>(); public static void main(String[] args) throws IOException { cr = new ConsoleReader(); cr.println("Starting Connect-Four Engine..."); if (args.length < 2) { cr.clearScreen(); cr.println("Not enough arguments. Usage: java -jar VierGewinnt.jar Path/To/Java/AI.java Path/To/Python/AI.py [-a|-log] [-export {source} {target}]"); cr.println(" -a [amount]: How many Games should be played through. Similiar to statistics.py in original CoRe"); cr.println(" -log: Logs every Game to a File, which can then be exported to a html."); cr.println(" -export [Source] [Target]: Exports a Logged Game (Source) to a html (Target)."); cr.println("PS: File Paths currently cannot have Spaces in them!"); return; } else if (args.length >= 3) { if (args[0].equalsIgnoreCase("-export")) { File s = new File(args[1]); File t = new File(args[2]); if (!s.exists()) { cr.println("File " + s.getAbsolutePath() + " cannot be found!"); return; } BufferedReader br = new BufferedReader(new FileReader(s)); String v = br.readLine(); aiName1 = v.split(" ")[0]; aiName2 = v.split(" ")[2]; String ints = br.readLine(); createBoard(); int player = 0; String g = ""; for(int i = 0;i<ints.length();i++){ settable = true; g = b.setNew(player, Integer.valueOf(String.valueOf((char)ints.codePointAt(i)))); player = 1 - player; } finish(g, t); return; } for (int i = 2; i < args.length; i++) { if (args[i].equalsIgnoreCase("-a")) { statisticsMode = true; playingGames = Integer.valueOf(args[i + 1]); i++; cr.println("Playing " + playingGames + " Games in Statistics Mode."); } else if (args[i].equalsIgnoreCase("-log")) { log = true; cr.println("Enabled Logging."); } } } // overrideDefaultSystemOut(); if (statisticsMode) { aiName1 = new File(args[0]).getName().split("\\.")[0]; aiName2 = new File(args[1]).getName().split("\\.")[0]; while (playingGames > playedGames) { printStatistics(); long time = System.currentTimeMillis(); playGame(args[0], args[1], false); ai1.shutdown(); ai2.shutdown(); time = System.currentTimeMillis() - time; times.add((double) (time / 1000)); turnCounts.add((double) turn); turn = 0; if (lastWinner == 1) { player1Wins++; } else if (lastWinner == 2) { player2Wins++; } playedGames++; } printStatistics(); } else { playGame(args[0], args[1], true); } } private static void printStatistics() throws IOException { cr.clearScreen(); cr.print(aiName1 + " vs " + aiName2 + " | Played " + playedGames + " Games of " + playingGames); cr.println(); cr.print("Player 1 Wins: " + player1Wins + " | Player 2 Wins: " + player2Wins + " | Ties: " + (player1Wins + player2Wins - playedGames)); cr.println(); double avgTime = 0; double avgturnCount = 0; if (times.size() > 0) { for (double time : times) { avgTime += time; } avgTime = avgTime / times.size(); for (double turnc : turnCounts) { avgturnCount += turnc; } } avgturnCount = avgturnCount / turnCounts.size(); cr.print("Average Roundtime: " + avgTime + " | Average Turncount: " + avgturnCount); cr.println(); cr.flush(); } private static void playGame(String ai1, String ai2, boolean autoFinish) { createBoard(); loadAIs(ai1, ai2); turn = 0; int c = 0; turn++; while (makeTurn(c, autoFinish)) { try { cr.println("Player " + (c + 1) + " finished Turn " + turn); cr.flush(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (c == 0) c = 1; else if (c == 1) c = 0; turn++; } } private static boolean makeTurn(int c, boolean autoFinish) { if (c == 0) { int x = -1; try { x = ai1.turn(b, "X"); } catch (Exception e) { e.printStackTrace(); } Security.shutdownThreads(); settable = true; String r = b.setNew(c, x); if (r.equalsIgnoreCase("e")) { try { cr.println("Error occured while spawning new ball for player " + c + " in round " + turn); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { lastWinner = 0; if (log) log(b); if (autoFinish) finish("l"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (autoFinish) System.exit(0); } if (!r.equalsIgnoreCase("g")) { try { lastWinner = (r.equalsIgnoreCase("X") ? 1 : (r.equalsIgnoreCase("O") ? 2 : 0)); if (log) log(b); if (autoFinish) finish(r); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return false; } return true; } else if (c == 1) { int x = -1; try { x = ai1.turn(b, "X"); } catch (Exception e) { e.printStackTrace(); } Security.shutdownThreads(); settable = true; String r = b.setNew(c, x); if (r.equalsIgnoreCase("e")) { try { cr.println("Error occured while spawning new ball for player " + c + " in round " + turn); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { lastWinner = 0; if (log) log(b); if (autoFinish) finish("l"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (autoFinish) System.exit(0); } if (!r.equalsIgnoreCase("g")) { try { lastWinner = (r.equalsIgnoreCase("X") ? 1 : 2); if (log) log(b); if (autoFinish) finish(r); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return false; } return true; } return false; } private static void log(Board b2) { File f = new File("logs" + File.separator + new Date().getTime() + ".save"); try { f.getParentFile().mkdirs(); f.createNewFile(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } PrintWriter pw = null; try { pw = new PrintWriter(new FileWriter(f)); pw.println(aiName1 + " vs " + aiName2); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } for (Integer i : b2.getPreviousTurns()) { pw.print(i); } pw.flush(); pw.close(); } private static void finish(String r) throws IOException { File f = new File("log.html"); finish(r,f); } private static void finish(String r, File f) throws IOException { if (ai1 != null) { ai1.shutdown(); ai2.shutdown(); } if (log) { return; } cr.println("Game Ended"); Board bN = new Board(b.getWidth(), b.getHeight(), false); if (f.exists()) f.delete(); f.createNewFile(); PrintWriter pw = new PrintWriter(new FileWriter(f)); pw.print("<!DOCTYPE html><title>" + aiName1 + " / " + aiName2 + "</title><style>body { font-family: monospace; background-color: rgb(50,50,50); color: rgb(150,150,150); }h1,h2,h3,.a { font-size: 32px; }a { color: rgb(200,200,200); }button { background-color: rgb(50,50,50); color: rgb(150,150,150); font-weight: bold;font-size: 24px; }table {background: rgb(100,100,100);}table, th, td {border: 1px solid black;border-collapse: collapse;}td, .X, .O { width: 64px; height: 64px; }.X {background: linear-gradient(to bottom right, grey, white);border-radius: 50%; }.O {background: linear-gradient(to bottom right, black, grey);border-radius: 50%; }</style><h1>Vier Gewinnt</h1><h2>" + aiName1 + " / " + aiName2 + "</h2><h3>" + b.getPreviousTurns().size() + " Turns</h3><hr/><button onclick=\"var styles = 'table{margin-bottom:100vh;}';var tag = document.createElement('style');tag.appendChild(document.createTextNode(styles));document.head.appendChild(tag); location.href = '#1';\">Simulate</button> <button onclick=\"var turn = prompt('Turn [1-64]', '1'); location.href = '#' + turn;\">Goto</button><hr/>"); int player = 1; LinkedList<Integer> t = b.getPreviousTurns(); for (int i = 0; i < t.size(); i++) { pw.print("<div class='a'>"); pw.print("<p>Player " + player + " (" + (player == 1 ? aiName1 : aiName2) + ") moved to " + (t.get(i) + 1) + "</p>"); pw.print("<a id='" + (i + 1) + "' href='#" + (i) + "'>back</a> <a href='#" + (i + 2) + "'>next</a>"); pw.print("<table>"); bN.setNew(player - 1, t.get(i)); for (int y = b.getHeight() - 1; y >= 0; y pw.print("<tr>"); for (int x = 0; x < b.getWidth(); x++) { pw.print("<td>"); if (bN.getCell(x, y).equalsIgnoreCase("X")) { pw.print("<div class='X'></div>"); } else if (bN.getCell(x, y).equalsIgnoreCase("O")) { pw.print("<div class='O'></div>"); } pw.print("</td>"); } pw.print("</tr>"); } pw.print("</table></div>"); if (player == 1) player = 2; else if (player == 2) player = 1; } pw.print("<div class='a'>"); if (r.equalsIgnoreCase("l")) { pw.print("<p>It's a Tie</p>"); } else if (r.equalsIgnoreCase("X")) { pw.print("<p>Player 1 (" + aiName1 + ") won!</p>"); } else if (r.equalsIgnoreCase("O")) { pw.print("<p>Player 2 (" + aiName2 + ") won!</p>"); } pw.print("</div></body></html>"); pw.flush(); pw.close(); Desktop.getDesktop().browse(f.toURI()); } public static void createBoard() { b = new Board(8, 8, true); } public static boolean isNewBlockSettable() { return settable; } public static void disableSettableBlock() { settable = false; } private static void loadAIs(String string, String string2) { File ai1 = new File(string); File ai2 = new File(string2); VierGewinnt.ai1 = loadAI(ai1); aiName1 = ai1.getName().split("\\.")[0]; VierGewinnt.ai2 = loadAI(ai2); aiName2 = ai2.getName().split("\\.")[0]; } private static AI loadAI(File ai) { if (!ai.exists()) { try { cr.println("ERROR: AI File " + ai.getName() + " does not exist!"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.exit(0); } int index = ai.getName().indexOf("."); int i = 0; while (index >= 0 && i >= 0) { i = ai.getName().indexOf(".", index + 1); if (i != -1) { index = i; } } if (index == -1) { try { cr.println("ERROR: AI File " + ai.getName() + " has no file ending! Can't find AI type! (Java,JS,Python)"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.exit(0); } switch (ai.getName().substring(index + 1)) { case "js": return loadJsAI(ai); case "py": return loadPyAI(ai); case "java": return loadJavaSrcAI(ai); case "class": return loadJavaClassAI(ai); case "jar": return loadJavaJarAI(ai); default: try { cr.println("ERROR: Could not find type of AI file with file ending: " + ai.getName().substring(index)); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.exit(0); return null; } } private static AI loadPyAI(File ai) { Process p = null; try { p = new ProcessBuilder("python", "." + File.separator + "python" + File.separator + "handler.py") .redirectErrorStream(true).start(); } catch (Exception e2) { e2.printStackTrace(); try { cr.println( "ERROR: Is Python installed on your system? And accessible with python?"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.exit(0); } final PrintWriter pw = new PrintWriter(new OutputStreamWriter(p.getOutputStream())); final BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream())); pw.println(ai.getAbsolutePath()); pw.println(b.getWidth()); pw.println(b.getHeight()); pw.flush(); final Process p2 = p; return new AI() { Process p = p2; @Override public void shutdown() { p.destroy(); } @Override public int turn(Board b, String symbol) { pw.println(turn); for (int x = 0; x < b.getWidth(); x++) { for (int y = 0; y < b.getHeight(); y++) { pw.println(b.getCell(x, y)); } } pw.println(symbol); pw.flush(); String line = ""; try { while ((line = br.readLine()) != null) { if (!line.startsWith("pos_x_result_handler=")) { cr.println(line); } else { int i = Integer.valueOf(line.split("=")[1]); return i; } } } catch (NumberFormatException | IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return 0; } }; } private static AI loadJsAI(File ai) { final ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn"); try { engine.eval(new FileReader(ai)); return new AI() { @Override public int turn(Board b, String symbol) { Invocable i = (Invocable) engine; try { Object o = i.invokeFunction("turn", b, symbol); if (o instanceof Integer) { return ((Integer) o).intValue(); } else { cr.println("ERROR: No Integer was returned by JS Script: " + o.toString()); return 0; } } catch (NoSuchMethodException | ScriptException | IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return 0; } @Override public void shutdown() { } }; } catch (FileNotFoundException | ScriptException e) { // TODO Auto-generated catch block e.printStackTrace(); try { cr.println( "ERROR: While initiating JS Script (JS syntax right? Function turn(board,symbol)?)"); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } return null; } private static AI loadJavaSrcAI(File ai) { File c = null; try { c = new File(ai.getPath() + File.separator + ai.getName().replace(".java", ".class")); if (c.exists()) c.delete(); if (new File("libs").exists()) { new ProcessBuilder("javac", "-cp", "." + File.separator + "*.jar;." + File.separator + "libs" + File.separator + "*", ai.getAbsolutePath()).redirectOutput(Redirect.INHERIT) .redirectErrorStream(true).start().waitFor(); } else { new ProcessBuilder("javac", "-cp", "." + File.separator + "*.jar", ai.getAbsolutePath()).redirectOutput(Redirect.INHERIT) .redirectErrorStream(true).start().waitFor(); } c = new File(ai.getParentFile().getAbsolutePath() + File.separator + ai.getName().replace(".java", ".class")); if (!c.exists()) { cr.println("ERROR: Compiling your Source Code File didn't work! (" + ai.getName() + ")"); System.exit(0); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } return loadJavaClassAI(c); } private static AI loadJavaJarAI(File ai) { try { UtilClassBuilder<AI> cb = new UtilClassBuilder<>(ai.getParentFile()); UtilClass<AI> a = cb.newUtilJarClass(ai, ai.getName().split("\\.")[0]); return a.initialise(); } catch (Exception e) { try { cr.println("ERROR: AI " + ai.getName() + " fails to load! (Wrong Name Scheme? Example: MainClassName.jar)"); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } System.exit(0); } return null; } private static AI loadJavaClassAI(File ai) { try { UtilClassBuilder<AI> cb = new UtilClassBuilder<>(ai.getParentFile()); UtilClass<AI> a = cb.newUtilClass(ai.getName().split("\\.")[0]); return a.initialise(); } catch (Exception e) { try { cr.println("ERROR: AI " + ai.getName() + " fails to load! (Corrupted File?)"); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } System.exit(0); } return null; } }
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class Primes { private Map<Long,List<Long>> known = new HashMap<>(); private long current = 2; public long next() { while (known.containsKey(current)) { for (Long prime : known.get(current)) { List<Long> primes = known.getOrDefault(current+prime, new ArrayList<>()); primes.add(prime); known.put(current+prime, primes); } known.remove(current); current++; } known.put(current * current, new ArrayList<Long>(){{add(current);}}); return current++; } public static void main(String[] args) { Primes primes = new Primes(); System.out.println(primes.next()); System.out.println(primes.next()); System.out.println(primes.next()); System.out.println(primes.next()); System.out.println(primes.next()); System.out.println(primes.next()); System.out.println(primes.next()); } }
package JpAws; import datameer.awstasks.aws.ec2.InstanceGroup; import datameer.awstasks.aws.ec2.ssh.SshClient; import java.io.File; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; public class WorkerThread extends Thread { public static final String JARNAME = "jpregel-aws.jar"; private InstanceGroup instanceGroup; private String masterDomainName; File privateKeyFile = new File("mungerkey.pem"); public WorkerThread(InstanceGroup instanceGroup, String masterDomainName) { this.instanceGroup = instanceGroup; this.masterDomainName = masterDomainName; } @Override public void run() { try { Thread.sleep(15000); } catch (InterruptedException ex) { Logger.getLogger(WorkerThread.class.getName()).log(Level.SEVERE, null, ex); } SshClient sshClient = instanceGroup.createSshClient("ec2-user", privateKeyFile); File jars = new File("jars.tar"); if(!jars.exists()) { try { Runtime.getRuntime().exec("tar -cvf jars.tar ./dist/lib"); } catch (IOException ex) { System.out.println("Error tarring jars."); System.exit(1); } } File thisjar = new File(JARNAME); File distjar = new File("dist/"+JARNAME); if(thisjar.exists()) { try { sshClient.uploadFile(thisjar, "~/" + JARNAME); } catch (IOException ex) { System.out.println("Error uploading jar"); System.exit(1); } } else if(distjar.exists()) { try { sshClient.uploadFile(distjar, "~/" + JARNAME); } catch (IOException ex) { System.out.println("Error uploading distjar"); System.exit(1); } } else { System.err.println("Didn't find jar in " + distjar.getAbsolutePath() + " or " + thisjar.getAbsolutePath()); System.exit(1); } try { sshClient.uploadFile(jars, "~/jars.tar"); sshClient.uploadFile(new File("key.AWSkey"), "~/key.AWSkey"); sshClient.uploadFile(new File("policy"), "~/policy"); sshClient.executeCommand("tar -xvf jars.tar", null);
package analysis; import analysis.bars.Bar; import analysis.bars.BarLexer; import analysis.bars.BarNote; import analysis.harmonic.ChordDegree; import analysis.harmonic.ChordDegreeSequenceExtractor; import analysis.harmonic.HarmonicProcessor; import analysis.metadata.MetadataExtractor; import jm.music.data.Score; import jm.util.Read; import java.util.ArrayList; import java.util.Collections; import java.util.ListIterator; /** * Class for Score analysis. Execute all the steps of the analysis on a specific score. * This class can be serialized in XML using the XStream library to create an input file for the training. */ public class ScoreAnalyser { private transient String fileName_; private transient Score score_; // Data of the score. private transient String title_; private Tonality tonality_; private double barUnit_; private int beatsPerBar_; private int tempo_; private int partNb_; private ArrayList<ChordDegree> degreeList_; private BarLexer barLexer_; private double quantum_; private transient ChordDegreeSequenceExtractor chordDegreeExtrator_; private transient Scale scale_; private int barNumber_; /** * Constructor for ScoreAnalyser * @param midiFile Path to MIDI file to analyse */ public ScoreAnalyser(String midiFile) { score_ = new Score(); try { Read.midi(score_, midiFile); fileName_ = midiFile.substring(midiFile.lastIndexOf('/') + 1, midiFile.length()); title_ = score_.getTitle(); tonality_ = MetadataExtractor.getTonality(score_.getKeySignature(), score_.getKeyQuality()); scale_ = MetadataExtractor.computeScale(tonality_); barUnit_ = MetadataExtractor.computeBarUnit(score_.getDenominator()); beatsPerBar_ = score_.getNumerator(); tempo_ = (int)score_.getTempo(); partNb_ = score_.getPartArray().length; quantum_ = MetadataExtractor.findQuantum(score_); barLexer_ = new BarLexer(score_, quantum_); ModulationDetector modulationDetector = new ModulationDetector(tonality_, barLexer_); modulationDetector.computeTonalities(); // Fill the Bars of barLexer_ with good Tonalities. ChordDegreeSequenceExtractor chordDegreeExtrator_ = new ChordDegreeSequenceExtractor(barLexer_); degreeList_ = chordDegreeExtrator_.getDegreeSequence(); barNumber_ = barLexer_.getBarNumber(); cleanDegreeList(); } catch (Exception e) { e.printStackTrace(); System.err.println("ScoreAnalyser: An error occurred while processing " + midiFile); } } /** * Display the important extracted data after analysis. */ public void printScoreInfo() { StringBuilder sb = new StringBuilder(" sb.append("Processed File: ").append(fileName_).append("\n"); sb.append("Score's Tonality: ").append(tonality_.toString()).append("\n"); sb.append("Score's Scale: ").append(scale_.toString()).append(" = [ "); for (int n : scale_.getScale()) sb.append(Tonality.pitchToFrenchString(n, true)).append(" "); sb.append("]\n"); sb.append("Score's Bar Unit: ").append(+ barUnit_).append("\n"); sb.append("Score's Beat Per Bar: ").append(beatsPerBar_).append("\n"); sb.append("Score's Bar Number: ").append(barLexer_.getBarNumber()).append("\n"); sb.append(" sb.append(degreeList_).append("\n\n"); System.out.println(sb); } public void cleanDegreeList() { ArrayList<Integer> removeBars = new ArrayList<>(); ArrayList<Integer> removeDegrees = new ArrayList<>(); ArrayList<Integer> barDegrees = new ArrayList<>(); int bar_frac = 0; int barIndex = 0; for (int i = 0; i <= degreeList_.size(); i++) { if (bar_frac == beatsPerBar_) { if (barDegrees.stream().anyMatch(degree_index -> degreeList_.get(degree_index).getDegree() == 0)) { removeDegrees.addAll(barDegrees); removeBars.add(barIndex); } barDegrees.clear(); barIndex++; bar_frac = 0; } if (i < degreeList_.size()) { barDegrees.add(i); bar_frac += (double)beatsPerBar_ / degreeList_.get(i).getBarFractionDen(); } } Collections.reverse(removeBars); Collections.reverse(removeDegrees); removeBars.stream().forEach(a -> barLexer_.getBars().remove((int)a)); removeDegrees.stream().forEach(a -> degreeList_.remove((int)a)); } // GETTERS / SETTERS /** * Getter for the Title class attribute. * @return */ public String getTitle() { return title_; } /** * Getter for the Score class attribute. * @return */ public Score getScore() { return score_; } /** * Getter for the Tonality class attribute. * @return tonality_ */ public Tonality getTonality() { return tonality_; } /** * Getter for the Scale class attribute. * @return scale_ */ public Scale getScale() { return scale_; } /** * Getter for the BarUnit class attribute. * @return barUnit_ */ public double getBarUnit() { return barUnit_; } /** * Getter for the BeatPerBar class attribute. * @return beatsPerBar */ public int getBeatsPerBar() { return beatsPerBar_; } /** * Getter for the Tempo class attribute. * @return tempo_ */ public double getTempo() { return tempo_; } /** * Getter for the PartNumber class attribute. * @return partNB */ public int getPartNb() { return partNb_; } /** * Getter for the DegreeList class attribute. * @return degreeList_ */ public ArrayList<ChordDegree> getDegreeList() { return degreeList_; } /** * Getter for the Quantum class attribute. * @return quantum_ */ public double getQuantum() { return quantum_; } /** * Getter for the BarLexer class attribute. * @return barLexer_ */ public BarLexer getBarLexer() { return barLexer_; } /** * Getter for the BarNumber class attribute. * @return barNumber_ */ public int getBarNumber() { return barNumber_; } }
public class Verifier { public static final String INPUT_SIGNAL_1 = "03036732577212944063491565474664"; public static final int[] SIGNAL_1_RESULT = {8, 4, 4, 6, 2, 0, 2, 6}; public static final String INPUT_SIGNAL_2 = "02935109699940807407585447034323"; public static final int[] SIGNAL_2_RESULT = {7, 8, 7, 2, 5, 2, 7, 0}; public static final String INPUT_SIGNAL_3 = "03081770884921959731165446850517"; public static final int[] SIGNAL_3_RESULT = {5, 3, 5, 5, 3, 7, 3, 1}; public Verifier (boolean debug) { _debug = debug; _fft = new Compute(_debug); } public final boolean verify () { boolean result = true; int[] signal = Util.replicate(INPUT_SIGNAL_1, Util.REPEAT_SIZE); int[] data = _fft.process(signal, Util.PHASES); long offset = Util.offset(INPUT_SIGNAL_1); //if (_debug) System.out.println("Offset for "+INPUT_SIGNAL_1+" is "+offset); System.out.println(); Util.printSignal(data, INPUT_SIGNAL_1.length()); return result; } private boolean _debug; Compute _fft; }
package com.cowbell.cordova.geofence; import android.content.Context; import android.content.Intent; import android.util.Log; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaInterface; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.CordovaWebView; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; public class GeofencePlugin extends CordovaPlugin { public static final String TAG = "GeofencePlugin"; private GeoNotificationManager geoNotificationManager; private Context context; protected static Boolean isInBackground = true; public static CordovaWebView webView = null; /** * @param cordova * The context of the main Activity. * @param webView * The associated CordovaWebView. */ @Override public void initialize(CordovaInterface cordova, CordovaWebView webView) { super.initialize(cordova, webView); GeofencePlugin.webView = webView; context = this.cordova.getActivity().getApplicationContext(); Logger.setLogger(new Logger(TAG, context, false)); geoNotificationManager = new GeoNotificationManager(context); } @Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { Log.d(TAG, "GeofencePlugin execute action: " + action + " args: " + args.toString()); if (action.equals("addOrUpdate")) { List<GeoNotification> geoNotifications = new ArrayList<GeoNotification>(); for (int i = 0; i < args.length(); i++) { GeoNotification not = parseFromJSONObject(args.getJSONObject(i)); if (not != null) { geoNotifications.add(not); } } geoNotificationManager.addGeoNotifications(geoNotifications, callbackContext); } else if (action.equals("remove")) { List<String> ids = new ArrayList<String>(); for (int i = 0; i < args.length(); i++) { ids.add(args.getString(i)); } geoNotificationManager.removeGeoNotifications(ids, callbackContext); } else if (action.equals("removeAll")) { geoNotificationManager.removeAllGeoNotifications(callbackContext); } else if (action.equals("getWatched")) { List<GeoNotification> geoNotifications = geoNotificationManager .getWatched(); callbackContext.success(Gson.get().toJson(geoNotifications)); } else if (action.equals("initialize")) { callbackContext.success(); } else if (action.equals("deviceReady")) { deviceReady(); callbackContext.success(); } else { return false; } return true; } private GeoNotification parseFromJSONObject(JSONObject object) { GeoNotification geo = null; geo = GeoNotification.fromJson(object.toString()); return geo; } public static void onTransitionReceived(List<GeoNotification> notifications) { Log.d(TAG, "Transition Event Received!"); String js = "setTimeout('geofence.onTransitionReceived(" + Gson.get().toJson(notifications) + ")',0)"; if (webView == null) { Log.d(TAG, "Webview is null"); } else { webView.sendJavascript(js); } } private void deviceReady() { Intent intent = cordova.getActivity().getIntent(); String data = intent.getStringExtra("geofence.notification.data"); String js = "setTimeout('geofence.onNotificationClicked(" + data + ")',0)"; if (data == null) { Log.d(TAG, "No notifications clicked."); } else { webView.sendJavascript(js); } } }
package eco; /** * This class describes the international market for wheat, * it manages wheat reserve goals and sells or buys to * meet it. * * @Author phil */ public class Economy { private static int treasury = 0; private static int wheatPrice = 10; public static int buyWheat(int ammount){ int neededMoney = wheatPrice * ammount; if (neededMoney <= treasury){ treasury -= neededMoney; return ammount; } else{ int canBuy = treasury / wheatPrice; treasury = 0; return canBuy; } } public static int sellWheat(int ammount){ treasury += wheatPrice * ammount; return ammount; } public static void updateMarket(int time){ wheatPrice += Util.randInt(-5, 7); // Biased to increase over time } public static int getTreasury(){ return treasury; } }
package edu.stuy; import edu.stuy.commands.*; import edu.stuy.commands.tuning.ShooterManualSpeed; import edu.stuy.subsystems.Shooter; import edu.wpi.first.wpilibj.DriverStation; import edu.wpi.first.wpilibj.DriverStationEnhancedIO; import edu.wpi.first.wpilibj.DriverStationEnhancedIO.EnhancedIOException; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.buttons.DigitalIOButton; import edu.wpi.first.wpilibj.buttons.JoystickButton; public class OI { private Joystick leftStick; private Joystick rightStick; private Joystick shooterStick; private Joystick debugBox; public static final int DISTANCE_BUTTON_AUTO = 1; public static final int DISTANCE_BUTTON_FAR = 2; public static final int DISTANCE_BUTTON_FENDER_WIDE = 3; public static final int DISTANCE_BUTTON_FENDER_NARROW = 4; public static final int DISTANCE_BUTTON_FENDER_SIDE = 5; public static final int DISTANCE_BUTTON_FENDER = 6; public static final int DISTANCE_BUTTON_STOP = 7; private DriverStationEnhancedIO enhancedIO; // EnhancedIO digital input public static final int ACQUIRER_IN_SWITCH_CHANNEL = 1; public static final int ACQUIRER_OUT_SWITCH_CHANNEL = 2; public static final int BIT_1_CHANNEL = 5; public static final int BIT_2_CHANNEL = 4; public static final int BIT_3_CHANNEL = 3; public static final int SHOOT_BUTTON_CHANNEL = 6; public static final int OVERRIDE_BUTTON_CHANNEL = 7; public static final int CONVEYOR_IN_SWITCH_CHANNEL = 8; public static final int CONVEYOR_OUT_SWITCH_CHANNEL = 9; public int distanceButton; public double distanceInches; // EnhancedIO digital output private static final int DISTANCE_BUTTON_AUTO_LIGHT_CHANNEL = 10; private static final int DISTANCE_BUTTON_FAR_LIGHT_CHANNEL = 11; private static final int DISTANCE_BUTTON_FENDER_WIDE_LIGHT_CHANNEL = 12; private static final int DISTANCE_BUTTON_FENDER_NARROW_LIGHT_CHANNEL = 13; private static final int DISTANCE_BUTTON_FENDER_SIDE_LIGHT_CHANNEL = 14; private static final int DISTANCE_BUTTON_FENDER_LIGHT_CHANNEL = 15; private static final int DISTANCE_BUTTON_STOP_LIGHT_CHANNEL = 16; // EnhancedIO analog input private static final int DISTANCE_BUTTONS_CHANNEL = 1; private static final int SPEED_TRIM_POT_CHANNEL = 2; private static final int SPIN_TRIM_POT_CHANNEL = 3; private static final int MAX_ANALOG_CHANNEL = 4; public OI() { if (!Devmode.DEV_MODE) { enhancedIO = DriverStation.getInstance().getEnhancedIO(); } leftStick = new Joystick(RobotMap.LEFT_JOYSTICK_PORT); rightStick = new Joystick(RobotMap.RIGHT_JOYSTICK_PORT); shooterStick = new Joystick(RobotMap.SHOOTER_JOYSTICK_PORT); debugBox = new Joystick(RobotMap.DEBUG_BOX_PORT); distanceButton = DISTANCE_BUTTON_STOP; distanceInches = 0; try { if (!Devmode.DEV_MODE) { enhancedIO.setDigitalConfig(BIT_1_CHANNEL, DriverStationEnhancedIO.tDigitalConfig.kInputPullUp); enhancedIO.setDigitalConfig(BIT_2_CHANNEL, DriverStationEnhancedIO.tDigitalConfig.kInputPullUp); enhancedIO.setDigitalConfig(BIT_3_CHANNEL, DriverStationEnhancedIO.tDigitalConfig.kInputPullUp); enhancedIO.setDigitalConfig(ACQUIRER_IN_SWITCH_CHANNEL, DriverStationEnhancedIO.tDigitalConfig.kInputPullUp); enhancedIO.setDigitalConfig(ACQUIRER_OUT_SWITCH_CHANNEL, DriverStationEnhancedIO.tDigitalConfig.kInputPullUp); enhancedIO.setDigitalConfig(CONVEYOR_IN_SWITCH_CHANNEL, DriverStationEnhancedIO.tDigitalConfig.kInputPullUp); enhancedIO.setDigitalConfig(CONVEYOR_OUT_SWITCH_CHANNEL, DriverStationEnhancedIO.tDigitalConfig.kInputPullUp); enhancedIO.setDigitalConfig(SHOOT_BUTTON_CHANNEL, DriverStationEnhancedIO.tDigitalConfig.kInputPullUp); enhancedIO.setDigitalConfig(OVERRIDE_BUTTON_CHANNEL, DriverStationEnhancedIO.tDigitalConfig.kInputPullUp); enhancedIO.setDigitalConfig(DISTANCE_BUTTON_AUTO_LIGHT_CHANNEL, DriverStationEnhancedIO.tDigitalConfig.kOutput); enhancedIO.setDigitalConfig(DISTANCE_BUTTON_FAR_LIGHT_CHANNEL, DriverStationEnhancedIO.tDigitalConfig.kOutput); enhancedIO.setDigitalConfig(DISTANCE_BUTTON_FENDER_WIDE_LIGHT_CHANNEL, DriverStationEnhancedIO.tDigitalConfig.kOutput); enhancedIO.setDigitalConfig(DISTANCE_BUTTON_FENDER_NARROW_LIGHT_CHANNEL, DriverStationEnhancedIO.tDigitalConfig.kOutput); enhancedIO.setDigitalConfig(DISTANCE_BUTTON_FENDER_SIDE_LIGHT_CHANNEL, DriverStationEnhancedIO.tDigitalConfig.kOutput); enhancedIO.setDigitalConfig(DISTANCE_BUTTON_FENDER_LIGHT_CHANNEL, DriverStationEnhancedIO.tDigitalConfig.kOutput); enhancedIO.setDigitalConfig(DISTANCE_BUTTON_STOP_LIGHT_CHANNEL, DriverStationEnhancedIO.tDigitalConfig.kOutput); } } catch (EnhancedIOException e) { } if (!Devmode.DEV_MODE) { new JoystickButton(leftStick, 1).whileHeld(new ShooterMoveFlyWheel(distanceInches)); new JoystickButton(rightStick, 1).whenPressed(new DrivetrainSetGear(false)); new JoystickButton(rightStick, 2).whenPressed(new DrivetrainSetGear(true)); new JoystickButton(leftStick, 1).whenPressed(new TusksExtend()); new JoystickButton(leftStick, 2).whenPressed(new TusksRetract()); // OI box switches new DigitalIOButton(ACQUIRER_IN_SWITCH_CHANNEL).whileHeld(new AcquirerAcquire()); new DigitalIOButton(ACQUIRER_OUT_SWITCH_CHANNEL).whileHeld(new AcquirerReverse()); new DigitalIOButton(CONVEYOR_IN_SWITCH_CHANNEL).whileHeld(new ConveyManual()); new DigitalIOButton(CONVEYOR_OUT_SWITCH_CHANNEL).whileHeld(new ConveyReverseManual()); new DigitalIOButton(SHOOT_BUTTON_CHANNEL).whileHeld(new ConveyAutomatic()); new JoystickButton(shooterStick, 1).whileHeld(new ConveyAutomatic()); new JoystickButton(shooterStick, 2).whileHeld(new AcquirerAcquire()); new JoystickButton(shooterStick, 3).whileHeld(new ConveyManual()); new JoystickButton(shooterStick, 4).whileHeld(new ConveyReverseManual()); new JoystickButton(shooterStick, 5).whileHeld(new AcquirerReverse()); new JoystickButton(shooterStick, 6).whenPressed(new ShooterManualSpeed()); } } // Copied from last year's DesDroid code. public double getRawAnalogVoltage() { try { return enhancedIO.getAnalogIn(DISTANCE_BUTTONS_CHANNEL); } catch (EnhancedIOException e) { return 0; } } public double getMaxVoltage() { try { return enhancedIO.getAnalogIn(MAX_ANALOG_CHANNEL); } catch (EnhancedIOException e) { return 2.2; } } /** * Determines which height button is pressed. All (7 logically because * side buttons are wired together) buttons are wired by means of * resistors to one analog input. Depending on the button that is pressed, a * different voltage is read by the analog input. Each resistor reduces the * voltage by about 1/7 the maximum voltage. * * @return An integer value representing the distance button that was pressed. * If a Joystick button is being used, that will returned. Otherwise, the * button will be returned from the voltage (if it returns 0, no button is pressed). */ public int getDistanceButton() { if (shooterStick.getRawButton(DISTANCE_BUTTON_STOP)) { distanceButton = DISTANCE_BUTTON_STOP; } if (shooterStick.getRawButton(DISTANCE_BUTTON_AUTO)) { distanceButton = DISTANCE_BUTTON_AUTO; } if (shooterStick.getRawButton(DISTANCE_BUTTON_FENDER)) { distanceButton = DISTANCE_BUTTON_FENDER; } if (shooterStick.getRawButton(DISTANCE_BUTTON_FAR)) { distanceButton = DISTANCE_BUTTON_FAR; } int preValue = (int) ((getRawAnalogVoltage() / (getMaxVoltage() / 8)) + 0.5); // If no buttons are pressed, it does not update the distance. if(preValue != 0){ distanceButton = preValue; } return distanceButton; } /** * Takes the distance button that has been pressed, and finds the distance for * the shooter to use. * @return distance for the shooter. */ public double getDistanceFromHeightButton(){ switch(distanceButton){ case DISTANCE_BUTTON_AUTO: distanceInches = CommandBase.drivetrain.getSonarDistance_in(); break; case DISTANCE_BUTTON_FAR: distanceInches = 725; // TODO: Max distance to max speed? break; case DISTANCE_BUTTON_FENDER_WIDE: distanceInches = Shooter.distances[Shooter.FENDER_LONG_INDEX]; break; case DISTANCE_BUTTON_FENDER_NARROW: distanceInches = Shooter.distances[Shooter.FENDER_WIDE_INDEX]; break; case DISTANCE_BUTTON_FENDER_SIDE: distanceInches = Shooter.distances[Shooter.FENDER_SIDE_INDEX]; break; case DISTANCE_BUTTON_FENDER: distanceInches = Shooter.distances[Shooter.FENDER_INDEX]; break; case DISTANCE_BUTTON_STOP: distanceInches = 0; break; default: break; } return distanceInches; } // Copied from last year's DesDroid code. public Joystick getLeftStick() { return leftStick; } public Joystick getRightStick() { return rightStick; } public Joystick getDebugBox() { return debugBox; } public boolean getShootOverrideButton() { try { return !enhancedIO.getDigital(OVERRIDE_BUTTON_CHANNEL) || shooterStick.getRawButton(8); } catch (EnhancedIOException ex) { return shooterStick.getRawButton(8); } } /** * Use a thumb wheel switch to set the autonomous mode setting. * @return Autonomous setting to run. */ public int getAutonSetting() { try { int switchNum = 0; int[] binaryValue = new int[3]; boolean[] dIO = {!enhancedIO.getDigital(BIT_1_CHANNEL), !enhancedIO.getDigital(BIT_2_CHANNEL), !enhancedIO.getDigital(BIT_3_CHANNEL)}; for (int i = 0; i < 3; i++) { if (dIO[i]) { binaryValue[i] = 1; } else { binaryValue[i] = 0; } } binaryValue[0] *= 4; // convert all binaryValues to decimal values binaryValue[1] *= 2; for (int i = 0; i < 3; i++) { // finish binary -> decimal conversion switchNum += binaryValue[i]; } return switchNum; } catch (EnhancedIOException e) { return -1; // Do nothing in case of failure } } public int getDebugBoxBinaryAutonSetting() { int switchNum = 0; int[] binaryValue = new int[4]; boolean[] dIO = {debugBox.getRawButton(1), debugBox.getRawButton(2), debugBox.getRawButton(3), debugBox.getRawButton(4)}; for (int i = 0; i < 4; i++) { if (dIO[i]) { binaryValue[i] = 1; } else { binaryValue[i] = 0; } } binaryValue[0] *= 8; // convert all binaryValues to decimal values binaryValue[1] *= 4; binaryValue[2] *= 2; for (int i = 0; i < 4; i++) { // finish binary -> decimal conversion switchNum += binaryValue[i]; } return switchNum; } public double getSpeedPot() { try { return enhancedIO.getAnalogIn(SPEED_TRIM_POT_CHANNEL); } catch (EnhancedIOException ex) { return 0.0; } } public double getSpinPot() { try { return enhancedIO.getAnalogIn(SPIN_TRIM_POT_CHANNEL); } catch (EnhancedIOException ex) { return 0.0; } } /** * Turns on specified light on OI. * @param lightNum */ public void setLight(int lightNum) { turnOffLights(); try { enhancedIO.setDigitalOutput(lightNum, true); } catch (EnhancedIOException e) { } } /** * Turns all lights off. */ public void turnOffLights(){ try { enhancedIO.setDigitalOutput(DISTANCE_BUTTON_AUTO_LIGHT_CHANNEL, false); enhancedIO.setDigitalOutput(DISTANCE_BUTTON_FAR_LIGHT_CHANNEL, false); enhancedIO.setDigitalOutput(DISTANCE_BUTTON_FENDER_WIDE_LIGHT_CHANNEL, false); enhancedIO.setDigitalOutput(DISTANCE_BUTTON_FENDER_NARROW_LIGHT_CHANNEL, false); enhancedIO.setDigitalOutput(DISTANCE_BUTTON_FENDER_SIDE_LIGHT_CHANNEL, false); enhancedIO.setDigitalOutput(DISTANCE_BUTTON_FENDER_LIGHT_CHANNEL, false); enhancedIO.setDigitalOutput(DISTANCE_BUTTON_STOP_LIGHT_CHANNEL, false); } catch (EnhancedIOException e) { } } /** * Meant to be called continuously to update the lights on the OI board. * Depending on which button has been pressed last (which distance is * currently set), that button will be lit. */ public void updateLights(){ switch(distanceButton){ case DISTANCE_BUTTON_AUTO: setLight(DISTANCE_BUTTON_AUTO_LIGHT_CHANNEL); break; case DISTANCE_BUTTON_FAR: setLight(DISTANCE_BUTTON_FAR_LIGHT_CHANNEL); break; case DISTANCE_BUTTON_FENDER_WIDE: setLight(DISTANCE_BUTTON_FENDER_WIDE_LIGHT_CHANNEL); break; case DISTANCE_BUTTON_FENDER_NARROW: setLight(DISTANCE_BUTTON_FENDER_NARROW_LIGHT_CHANNEL); break; case DISTANCE_BUTTON_FENDER_SIDE: setLight(DISTANCE_BUTTON_FENDER_SIDE_LIGHT_CHANNEL); break; case DISTANCE_BUTTON_FENDER: setLight(DISTANCE_BUTTON_FENDER_LIGHT_CHANNEL); break; case DISTANCE_BUTTON_STOP: setLight(DISTANCE_BUTTON_STOP_LIGHT_CHANNEL); break; default: turnOffLights(); break; } } // For debugging purposes. public boolean getValue(int channel) { boolean b = false; try{ b = enhancedIO.getDigital(channel); } catch (EnhancedIOException e) { } return b; } // For debugging purposes. public double getAnalogValue(int channel) { double b = 0; try{ b = enhancedIO.getAnalogOut(channel); } catch (EnhancedIOException e) { } return b; } }
package cn.jmessage.phonegap; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.media.MediaPlayer; import android.net.Uri; import android.os.Environment; import android.text.TextUtils; import android.util.Log; import com.google.gson.Gson; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaInterface; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.CordovaWebView; import org.apache.cordova.PluginResult; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import cn.jpush.im.android.api.JMessageClient; import cn.jpush.im.android.api.callback.CreateGroupCallback; import cn.jpush.im.android.api.callback.DownloadCompletionCallback; import cn.jpush.im.android.api.callback.GetAvatarBitmapCallback; import cn.jpush.im.android.api.callback.GetBlacklistCallback; import cn.jpush.im.android.api.callback.GetGroupIDListCallback; import cn.jpush.im.android.api.callback.GetGroupInfoCallback; import cn.jpush.im.android.api.callback.GetGroupMembersCallback; import cn.jpush.im.android.api.callback.GetUserInfoCallback; import cn.jpush.im.android.api.content.EventNotificationContent; import cn.jpush.im.android.api.content.ImageContent; import cn.jpush.im.android.api.content.MessageContent; import cn.jpush.im.android.api.content.TextContent; import cn.jpush.im.android.api.content.VoiceContent; import cn.jpush.im.android.api.enums.ContentType; import cn.jpush.im.android.api.enums.ConversationType; import cn.jpush.im.android.api.event.LoginStateChangeEvent; import cn.jpush.im.android.api.event.MessageEvent; import cn.jpush.im.android.api.event.NotificationClickEvent; import cn.jpush.im.android.api.model.Conversation; import cn.jpush.im.android.api.model.GroupInfo; import cn.jpush.im.android.api.model.Message; import cn.jpush.im.android.api.model.UserInfo; import cn.jpush.im.api.BasicCallback; public class JMessagePlugin extends CordovaPlugin { private static String TAG = "JMessagePlugin"; private static JMessagePlugin instance; private ExecutorService threadPool = Executors.newFixedThreadPool(1); private Gson mGson = new Gson(); private Activity mCordovaActivity; private Message mCurrentMsg; private static Message mBufMsg; private static boolean shouldCacheMsg = false; private int[] mMsgIds; public JMessagePlugin() { instance = this; } @Override public void initialize(CordovaInterface cordova, CordovaWebView webView) { super.initialize(cordova, webView); mCordovaActivity = cordova.getActivity(); JMessageClient.init(this.cordova.getActivity().getApplicationContext()); JMessageClient.registerEventReceiver(this); } public void onEvent(MessageEvent event) { final Message msg = event.getMessage(); try { String jsonStr = mGson.toJson(msg); JSONObject msgJson = new JSONObject(jsonStr); // Add user avatar path. UserInfo fromUser = msg.getFromUser(); String avatarPath = ""; File avatarFile = fromUser.getAvatarFile(); if (avatarFile != null) { avatarPath = avatarFile.getAbsolutePath(); } msgJson.getJSONObject("fromUser").put("avatarPath", avatarPath); String fromName = TextUtils.isEmpty(fromUser.getNickname()) ? fromUser.getUserName() : fromUser.getNickname(); msgJson.put("fromName", fromName); msgJson.put("fromID", fromUser.getUserName()); UserInfo myInfo = JMessageClient.getMyInfo(); String myInfoJson = mGson.toJson(myInfo); JSONObject myInfoJsonObj = new JSONObject(myInfoJson); File myAvatarFile = JMessageClient.getMyInfo().getAvatarFile(); String myAvatarPath = ""; if (myAvatarFile != null) { myAvatarPath = myAvatarFile.getAbsolutePath(); } myInfoJsonObj.put("avatarPath", myAvatarPath); msgJson.put("targetInfo", myInfoJsonObj); String targetName = ""; if (msg.getTargetType().equals(ConversationType.single)) { targetName = TextUtils.isEmpty(myInfo.getNickname()) ? myInfo.getUserName() : myInfo.getNickname(); msgJson.put("targetID", myInfo.getUserName()); } else if (msg.getTargetType().equals(ConversationType.group)) { GroupInfo targetInfo = (GroupInfo) msg.getTargetInfo(); targetName = TextUtils.isEmpty(targetInfo.getGroupName()) ? targetInfo.getGroupName() : (targetInfo.getGroupID() + ""); } msgJson.put("targetName", targetName); switch (msg.getContentType()) { case text: fireEvent("onReceiveTextMessage", jsonStr); break; case image: ImageContent imageContent = (ImageContent) msg.getContent(); String imgPath = imageContent.getLocalPath(); String imgLink = imageContent.getImg_link(); msgJson.getJSONObject("content").put("imagePath", imgPath); msgJson.getJSONObject("content").put("imageLink", imgLink); fireEvent("onReceiveImageMessage", msgJson.toString()); break; case voice: VoiceContent voiceContent = (VoiceContent) msg.getContent(); String voicePath = voiceContent.getLocalPath(); int duration = voiceContent.getDuration(); msgJson.getJSONObject("content").put("voicePath", voicePath); msgJson.getJSONObject("content").put("duration", duration); fireEvent("onReceiveVoiceMessage", msgJson.toString()); break; case custom: fireEvent("onReceiveCustomMessage", msgJson.toString()); break; case eventNotification: EventNotificationContent content = (EventNotificationContent) msg.getContent(); switch (content.getEventNotificationType()) { case group_member_added: fireEvent("onGroupMemberAdded", null); break; case group_member_removed: fireEvent("onGroupMemberRemoved", null); break; case group_member_exit: fireEvent("onGroupMemberExit", null); break; default: } break; case unknown: break; default: } Log.i(TAG, "onReceiveMessage: " + msgJson.toString()); fireEvent("onReceiveMessage", msgJson.toString()); } catch (JSONException e) { e.printStackTrace(); } } public void onEvent(LoginStateChangeEvent event) { LoginStateChangeEvent.Reason reason = event.getReason(); switch (reason) { case user_password_change: fireEvent("onUserPasswordChanged", null); break; case user_logout: fireEvent("onUserLogout", null); break; case user_deleted: fireEvent("onUserDeleted", null); break; default: } } public void onEvent(NotificationClickEvent event) { Message msg = event.getMessage(); if (shouldCacheMsg) { mBufMsg = msg; } String json = mGson.toJson(msg); fireEvent("onOpenMessage", json); Intent launch = cordova.getActivity().getApplicationContext() .getPackageManager().getLaunchIntentForPackage( cordova.getActivity().getApplicationContext().getPackageName()); launch.addCategory(Intent.CATEGORY_LAUNCHER); launch.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP); cordova.getActivity().getApplicationContext().startActivity(launch); } private void triggerMessageClickEvent(Message msg) { String json = mGson.toJson(msg); fireEvent("onOpenMessage", json); } private void fireEvent(String eventName, String jsonStr) { String format = "window.JMessage." + eventName + "(%s);"; String js; if (jsonStr != null) { js = String.format(format, jsonStr); } else { js = String.format(format, ""); } final String finalJs = js; mCordovaActivity.runOnUiThread(new Runnable() { @Override public void run() { instance.webView.loadUrl("javascript:" + finalJs); } }); } @Override public boolean execute(final String action, final JSONArray data, final CallbackContext callback) throws JSONException { threadPool.execute(new Runnable() { @Override public void run() { try { Method method = JMessagePlugin.class.getDeclaredMethod(action, JSONArray.class, CallbackContext.class); method.invoke(JMessagePlugin.this, data, callback); } catch (Exception e) { Log.e(TAG, e.toString()); } } }); return true; } public void onPause(boolean multitasking) { shouldCacheMsg = true; } @Override public void onResume(boolean multitasking) { super.onResume(multitasking); shouldCacheMsg = false; } public void onDestroy() { JMessageClient.unRegisterEventReceiver(this); mCordovaActivity = null; } // Login and register API. public void userRegister(JSONArray data, CallbackContext callback) { Log.i(TAG, " JMessageRegister \n" + data); final CallbackContext cb = callback; try { String username = data.getString(0); String password = data.getString(1); JMessageClient.register(username, password, new BasicCallback() { @Override public void gotResult(final int status, final String desc) { handleResult("", status, desc, cb); } }); } catch (JSONException e) { e.printStackTrace(); callback.error("error reading id json."); } } public void userLogin(JSONArray data, CallbackContext callback) { Log.i(TAG, " userLogin \n" + data); final CallbackContext cb = callback; try { String username = data.getString(0); String password = data.getString(1); JMessageClient.login(username, password, new BasicCallback() { @Override public void gotResult(final int status, final String desc) { handleResult("", status, desc, cb); } }); } catch (JSONException e) { e.printStackTrace(); callback.error("error reading id json"); } } public void userLogout(JSONArray data, CallbackContext callback) { Log.i(TAG, "Logout \n" + data); try { JMessageClient.logout(); callback.success(); } catch (Exception exception) { callback.error(exception.toString()); } } // User info API. public void getUserInfo(JSONArray data, final CallbackContext callback) { try { String username = data.getString(0); String appKey = data.isNull(1) ? "" : data.getString(1); JMessageClient.getUserInfo(username, appKey, new GetUserInfoCallback() { @Override public void gotResult(int responseCode, String responseDesc, UserInfo userInfo) { if (responseCode == 0) { try { String json = mGson.toJson(userInfo); JSONObject jsonObject = new JSONObject(json); String avatarPath = ""; if (userInfo.getAvatarFile() != null) { avatarPath = userInfo.getAvatarFile().getAbsolutePath(); } jsonObject.put("avatarPath", avatarPath); callback.success(jsonObject.toString()); } catch (JSONException e) { e.printStackTrace(); callback.error(e.getMessage()); } } else { callback.error(responseDesc); } } }); } catch (JSONException e) { e.printStackTrace(); callback.error("Parameter error."); } } public void getMyInfo(JSONArray data, CallbackContext callback) { UserInfo myInfo = JMessageClient.getMyInfo(); if (myInfo != null) { try { String json = mGson.toJson(myInfo); JSONObject jsonObject = new JSONObject(json); String avatarPath = ""; if (myInfo.getAvatarFile() != null) { avatarPath = myInfo.getAvatarFile().getAbsolutePath(); } jsonObject.put("avatarPath", avatarPath); callback.success(jsonObject.toString()); } catch (JSONException e) { e.printStackTrace(); callback.error(e.getMessage()); } } else { callback.error("My info is null."); } } public void updateMyInfo(JSONArray data, final CallbackContext callback) { try { String field = data.getString(0); String value = data.getString(1); UserInfo myInfo = JMessageClient.getMyInfo(); String result = updateUserInfo(myInfo, field, value); if (result == null) { callback.success(); } else { callback.error(result); } } catch (JSONException e) { e.printStackTrace(); callback.error("Parameter error."); } } /** * Update my password. * * @param data JSONArray; data.getString(0): old password, data.getString(1): new password. * @param callback result callback method. */ public void updateMyPassword(JSONArray data, CallbackContext callback) { final CallbackContext cb = callback; try { String oldPwd = data.getString(0); String newPwd = data.getString(1); JMessageClient.updateUserPassword(oldPwd, newPwd, new BasicCallback() { @Override public void gotResult(int status, String desc) { handleResult("", status, desc, cb); } }); } catch (JSONException e) { e.printStackTrace(); callback.error("error reading password json."); } } /** * Update my avatar. * * @param data data.getString(0): the URL of the users avatar file. * @param callback callback method. */ public void updateMyAvatar(JSONArray data, CallbackContext callback) { final CallbackContext cb = callback; try { String avatarUrlStr = data.getString(0); if (TextUtils.isEmpty(avatarUrlStr)) { callback.error("Avatar URL is empty!"); return; } URL url = new URL(avatarUrlStr); String path = url.getPath(); File avatarFile = new File(path); JMessageClient.updateUserAvatar(avatarFile, new BasicCallback() { @Override public void gotResult(int status, String errorDesc) { handleResult("", status, errorDesc, cb); } }); } catch (JSONException e) { e.printStackTrace(); callback.error("Reading alias JSON error."); } catch (MalformedURLException e) { e.printStackTrace(); callback.error("Avatar URL error."); } } public void updateMyAvatarByPath(JSONArray data, final CallbackContext callback) { try { String path = data.getString(0); File avatarFile = new File(path); if (!avatarFile.exists()) { callback.error("File not exist."); return; } JMessageClient.updateUserAvatar(avatarFile, new BasicCallback() { @Override public void gotResult(int status, String desc) { if (status == 0) { callback.success(); } else { callback.error(status); } } }); } catch (JSONException e) { e.printStackTrace(); callback.error("Argument error."); } } public void getUserAvatar(JSONArray data, final CallbackContext callback) { try { String username = data.isNull(0) ? "" : data.getString(0); if (TextUtils.isEmpty(username)) { UserInfo myInfo = JMessageClient.getMyInfo(); File avatarFile = myInfo.getAvatarFile(); String path = ""; if (avatarFile != null) { path = avatarFile.getAbsolutePath(); } callback.success(path); } else { JMessageClient.getUserInfo(username, new GetUserInfoCallback() { @Override public void gotResult(int status, String desc, UserInfo userInfo) { if (status == 0) { File avatarFile = userInfo.getAvatarFile(); String path = ""; if (avatarFile != null) { path = avatarFile.getAbsolutePath(); } callback.success(path); } else { Log.i(TAG, "getUserAvatar: " + status + " - " + desc); callback.error(status); } } }); } } catch (JSONException e) { e.printStackTrace(); callback.error("Argument error."); } } /** * username */ public void getOriginalUserAvatar(JSONArray data, final CallbackContext callback) { try { final String username = data.isNull(0) ? "" : data.getString(0); final String fileName; final String avatarPath = getAvatarPath(); if (TextUtils.isEmpty(username)) { final UserInfo myInfo = JMessageClient.getMyInfo(); fileName = "avatar_" + myInfo.getUserID(); File avatarFile = new File(avatarPath + fileName + ".png"); if (avatarFile.exists()) { Log.i(TAG, "isExists"); callback.success(avatarFile.getAbsolutePath()); return; } myInfo.getBigAvatarBitmap(new GetAvatarBitmapCallback() { @Override public void gotResult(int status, String desc, Bitmap bitmap) { if (status == 0) { if (bitmap == null) { callback.success(""); } else { callback.success(storeImage(bitmap, fileName)); } } else { Log.i(TAG, "getOriginalUserAvatar: " + status + " - " + desc); callback.error(status); } } }); } else { JMessageClient.getUserInfo(username, new GetUserInfoCallback() { @Override public void gotResult(int status, String desc, final UserInfo userInfo) { if (status == 0) { String fileName = "avatar_" + userInfo.getUserID(); File avatarFile = new File(avatarPath + fileName + ".png"); if (avatarFile.exists()) { callback.success(avatarFile.getAbsolutePath()); return; } userInfo.getBigAvatarBitmap(new GetAvatarBitmapCallback() { @Override public void gotResult(int status, String desc, Bitmap bitmap) { if (status == 0) { if (bitmap == null) { callback.success(""); } else { String filename = "avatar_" + userInfo.getUserID(); callback.success(storeImage(bitmap, filename)); } } else { Log.i(TAG, "getOriginalUserAvatar: " + status + " - " + desc); callback.error(status); } } }); } else { Log.i(TAG, "getOriginalUserAvatar: " + status + " - " + desc); callback.error(status); } } }); } } catch (JSONException e) { e.printStackTrace(); callback.error("Argument error."); } } // Message API. public void sendSingleTextMessage(JSONArray data, final CallbackContext callback) { Log.i(TAG, "sendSingleTextMessage \n" + data); try { String username = data.getString(0); String text = data.getString(1); String appKey = data.isNull(2) ? "" : data.getString(2); Conversation conversation = JMessageClient.getSingleConversation( username, appKey); if (conversation == null) { conversation = Conversation.createSingleConversation(username, appKey); } if (conversation == null) { callback.error(""); return; } TextContent content = new TextContent(text); final Message msg = conversation.createSendMessage(content); msg.setOnSendCompleteCallback(new BasicCallback() { @Override public void gotResult(int status, String desc) { if (status == 0) { callback.success(mGson.toJson(msg)); } else { callback.error(status + ": " + desc); } } }); JMessageClient.sendMessage(msg); } catch (JSONException e) { e.printStackTrace(); callback.error("error reading id json."); } } public void sendSingleTextMessageWithExtras(JSONArray data, final CallbackContext callback) { try { String username = data.getString(0); String text = data.getString(1); String json = data.getString(2); // Json String appkey = data.isNull(3) ? "" : data.getString(3); Conversation conversation = getConversation("single", username, appkey); if (conversation == null) { conversation = Conversation.createSingleConversation(username, appkey); } if (conversation == null) { callback.error(""); return; } TextContent content = new TextContent(text); if (!TextUtils.isEmpty(json)) { JSONObject values = new JSONObject(json); Iterator<? extends String> keys = values.keys(); Map<String, String> valuesMap = new HashMap<String, String>(); String key, value; while (keys.hasNext()) { key = keys.next(); value = values.getString(key); valuesMap.put(key, value); } content.setExtras(valuesMap); } final Message msg = conversation.createSendMessage(content); msg.setOnSendCompleteCallback(new BasicCallback() { @Override public void gotResult(int status, String desc) { if (status == 0) { callback.success(mGson.toJson(msg)); } else { callback.error(status + ": " + desc); } } }); JMessageClient.sendMessage(msg); } catch (JSONException e) { e.printStackTrace(); callback.error(e.toString()); } } /** * @param data JSONArray. * data.getString(0):username, data.getString(1):text * @param callback CallbackContext. */ public void sendSingleImageMessage(JSONArray data, final CallbackContext callback) { try { String userName = data.getString(0); String imgUrlStr = data.getString(1); String appKey = data.isNull(2) ? "" : data.getString(2); Conversation conversation = JMessageClient.getSingleConversation( userName, appKey); if (conversation == null) { conversation = Conversation.createSingleConversation(userName, appKey); } if (conversation == null) { callback.error(""); return; } URL imgUrl = new URL(imgUrlStr); File imgFile = new File(imgUrl.getPath()); final Message msg = conversation.createSendImageMessage(imgFile); msg.setOnSendCompleteCallback(new BasicCallback() { @Override public void gotResult(int status, String desc) { if (status == 0) { callback.success(mGson.toJson(msg)); } else { callback.error(status + ": " + desc); } } }); JMessageClient.sendMessage(msg); } catch (JSONException e) { e.printStackTrace(); callback.error("json data error"); } catch (FileNotFoundException e) { e.printStackTrace(); callback.error(""); } catch (MalformedURLException e) { e.printStackTrace(); callback.error("URL error."); } } public void sendSingleImageMessageWithExtras(JSONArray data, final CallbackContext callback) { try { String userName = data.getString(0); String imgUrlStr = data.getString(1); String json = data.getString(2); String appKey = data.isNull(3) ? "" : data.getString(3); Conversation conversation = JMessageClient.getSingleConversation( userName, appKey); if (conversation == null) { conversation = Conversation.createSingleConversation(userName, appKey); } if (conversation == null) { callback.error(""); return; } URL imgUrl = new URL(imgUrlStr); File imgFile = new File(imgUrl.getPath()); ImageContent content = new ImageContent(imgFile); if (!TextUtils.isEmpty(json)) { JSONObject values = new JSONObject(json); Iterator<? extends String> keys = values.keys(); Map<String, String> valuesMap = new HashMap<String, String>(); String key, value; while (keys.hasNext()) { key = keys.next(); value = values.getString(key); valuesMap.put(key, value); } content.setExtras(valuesMap); } final Message msg = conversation.createSendMessage(content); msg.setOnSendCompleteCallback(new BasicCallback() { @Override public void gotResult(int status, String desc) { if (status == 0) { callback.success(mGson.toJson(msg)); } else { callback.error(status + ": " + desc); } } }); JMessageClient.sendMessage(msg); } catch (JSONException e) { e.printStackTrace(); callback.error("json data error"); } catch (FileNotFoundException e) { e.printStackTrace(); callback.error(""); } catch (MalformedURLException e) { e.printStackTrace(); callback.error("URL error."); } } /** * @param data JSONArray. * data.getString(0):username, data.getString(1):voiceFileUrl. * @param callback CallbackContext. */ public void sendSingleVoiceMessage(JSONArray data, final CallbackContext callback) { try { String userName = data.getString(0); String voiceUrlStr = data.getString(1); String appKey = data.isNull(2) ? "" : data.getString(2); Conversation conversation = JMessageClient.getSingleConversation( userName, appKey); if (conversation == null) { conversation = Conversation.createSingleConversation(userName, appKey); } if (conversation == null) { callback.error(""); return; } URL url = new URL(voiceUrlStr); String voicePath = url.getPath(); File file = new File(voicePath); MediaPlayer mediaPlayer = MediaPlayer.create(this.cordova.getActivity(), Uri.parse(voicePath)); int duration = mediaPlayer.getDuration(); final Message msg = JMessageClient.createSingleVoiceMessage(userName, file, duration); msg.setOnSendCompleteCallback(new BasicCallback() { @Override public void gotResult(int status, String desc) { if (status == 0) { callback.success(mGson.toJson(msg)); } else { callback.error(status + ": " + desc); } } }); JMessageClient.sendMessage(msg); mediaPlayer.release(); } catch (JSONException e) { e.printStackTrace(); callback.error("json data error"); } catch (MalformedURLException e) { e.printStackTrace(); callback.error("file url error"); } catch (FileNotFoundException e) { e.printStackTrace(); callback.error("file not found."); } } public void sendSingleVoiceMessageWithExtras(JSONArray data, final CallbackContext callback) { try { String userName = data.getString(0); String voiceUrlStr = data.getString(1); String json = data.getString(2); String appKey = data.isNull(3) ? "" : data.getString(3); Conversation conversation = JMessageClient.getSingleConversation( userName, appKey); if (conversation == null) { conversation = Conversation.createSingleConversation(userName, appKey); } if (conversation == null) { callback.error(""); return; } URL url = new URL(voiceUrlStr); String voicePath = url.getPath(); File file = new File(voicePath); MediaPlayer mediaPlayer = MediaPlayer.create(this.cordova.getActivity(), Uri.parse(voicePath)); int duration = mediaPlayer.getDuration(); VoiceContent content = new VoiceContent(file, duration); if (!TextUtils.isEmpty(json)) { JSONObject values = new JSONObject(json); Iterator<? extends String> keys = values.keys(); Map<String, String> valuesMap = new HashMap<String, String>(); String key, value; while (keys.hasNext()) { key = keys.next(); value = values.getString(key); valuesMap.put(key, value); } content.setExtras(valuesMap); } final Message msg = conversation.createSendMessage(content); msg.setOnSendCompleteCallback(new BasicCallback() { @Override public void gotResult(int status, String desc) { if (status == 0) { callback.success(mGson.toJson(msg)); } else { callback.error(status + ": " + desc); } } }); JMessageClient.sendMessage(msg); mediaPlayer.release(); } catch (JSONException e) { e.printStackTrace(); callback.error("json data error"); } catch (MalformedURLException e) { e.printStackTrace(); callback.error("file url error"); } catch (FileNotFoundException e) { e.printStackTrace(); callback.error("file not found."); } } /** * @param data JSONArray. * data.getString(0):username, data.getJSONObject(1):custom key-values. * @param callback CallbackContext. */ public void sendSingleCustomMessage(JSONArray data, final CallbackContext callback) { try { String userName = data.getString(0); String appKey = data.isNull(2) ? "" : data.getString(2); Conversation con = JMessageClient.getSingleConversation(userName, appKey); if (con == null) { con = Conversation.createSingleConversation(userName, appKey); } if (con == null) { callback.error(""); return; } String jsonStr = data.getString(1); JSONObject values = new JSONObject(jsonStr); Iterator<? extends String> keys = values.keys(); Map<String, String> valuesMap = new HashMap<String, String>(); String key, value; while (keys.hasNext()) { key = keys.next(); value = values.getString(key); valuesMap.put(key, value); } final Message msg = JMessageClient.createSingleCustomMessage(userName, valuesMap); msg.setOnSendCompleteCallback(new BasicCallback() { @Override public void gotResult(int status, String desc) { if (status == 0) { callback.success(mGson.toJson(msg)); } else { callback.error(status + ": " + desc); } } }); JMessageClient.sendMessage(msg); } catch (JSONException e) { e.printStackTrace(); callback.error("Parameter error."); } } /** * @param data JSONArray. * data.getLong(0):groupId, data.getString(1):text. * @param callback CallbackContext. */ public void sendGroupTextMessage(JSONArray data, final CallbackContext callback) { try { long groupId = data.getLong(0); String text = data.getString(1); Conversation conversation = JMessageClient.getGroupConversation(groupId); if (conversation == null) { conversation = Conversation.createGroupConversation(groupId); } if (conversation == null) { callback.error(""); return; } final Message msg = JMessageClient.createGroupTextMessage(groupId, text); msg.setOnSendCompleteCallback(new BasicCallback() { @Override public void gotResult(int status, String desc) { if (status == 0) { callback.success(mGson.toJson(msg)); } else { callback.error(status + ": " + desc); } } }); JMessageClient.sendMessage(msg); } catch (JSONException e) { e.printStackTrace(); callback.error("error reading id json."); } } public void sendGroupTextMessageWithExtras(JSONArray data, final CallbackContext callback) { try { long groupId = data.getLong(0); String text = data.getString(1); String json = data.getString(2); Conversation conversation = JMessageClient.getGroupConversation(groupId); if (conversation == null) { conversation = Conversation.createGroupConversation(groupId); } if (conversation == null) { callback.error(""); return; } TextContent content = new TextContent(text); if (!TextUtils.isEmpty(json)) { content.setExtras(getExtras(json)); } final Message msg = conversation.createSendMessage(content); msg.setOnSendCompleteCallback(new BasicCallback() { @Override public void gotResult(int status, String desc) { if (status == 0) { callback.success(mGson.toJson(msg)); } else { callback.error(status + ": " + desc); } } }); JMessageClient.sendMessage(msg); } catch (JSONException e) { e.printStackTrace(); callback.error("error reading id json."); } } public void sendGroupImageMessage(JSONArray data, final CallbackContext callback) { try { long groupId = data.getLong(0); String imgUrlStr = data.getString(1); Conversation conversation = JMessageClient.getGroupConversation(groupId); if (conversation == null) { conversation = Conversation.createGroupConversation(groupId); } if (conversation == null) { callback.error(""); return; } URL imgUrl = new URL(imgUrlStr); File imgFile = new File(imgUrl.getPath()); final Message msg = JMessageClient.createGroupImageMessage(groupId, imgFile); msg.setOnSendCompleteCallback(new BasicCallback() { @Override public void gotResult(int status, String desc) { if (status == 0) { callback.success(mGson.toJson(msg)); } else { callback.error(status + ": " + desc); } } }); JMessageClient.sendMessage(msg); callback.success(mGson.toJson(msg)); } catch (JSONException e) { e.printStackTrace(); callback.error("Parameter error."); } catch (MalformedURLException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); callback.error("file not found."); } } public void sendGroupImageMessageWithExtras(JSONArray data, final CallbackContext callback) { try { long groupId = data.getLong(0); String imgUrlStr = data.getString(1); String json = data.getString(2); Conversation conversation = JMessageClient.getGroupConversation(groupId); if (conversation == null) { conversation = Conversation.createGroupConversation(groupId); } if (conversation == null) { callback.error(""); return; } URL imgUrl = new URL(imgUrlStr); File imgFile = new File(imgUrl.getPath()); ImageContent content = new ImageContent(imgFile); if (!TextUtils.isEmpty(json)) { content.setExtras(getExtras(json)); } final Message msg = conversation.createSendMessage(content); msg.setOnSendCompleteCallback(new BasicCallback() { @Override public void gotResult(int status, String desc) { if (status == 0) { callback.success(mGson.toJson(msg)); } else { callback.error(status + ": " + desc); } } }); JMessageClient.sendMessage(msg); callback.success(mGson.toJson(msg)); } catch (JSONException e) { e.printStackTrace(); callback.error("Parameter error."); } catch (MalformedURLException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); callback.error("file not found."); } } public void sendGroupVoiceMessage(JSONArray data, final CallbackContext callback) { try { long groupId = data.getLong(0); String voiceUrlStr = data.getString(1); Conversation conversation = JMessageClient.getGroupConversation(groupId); if (conversation == null) { conversation = Conversation.createGroupConversation(groupId); } if (conversation == null) { callback.error(""); return; } URL url = new URL(voiceUrlStr); String voicePath = url.getPath(); File file = new File(voicePath); MediaPlayer mediaPlayer = MediaPlayer.create(this.cordova.getActivity(), Uri.parse(voicePath)); int duration = mediaPlayer.getDuration(); final Message msg = JMessageClient.createGroupVoiceMessage(groupId, file, duration); msg.setOnSendCompleteCallback(new BasicCallback() { @Override public void gotResult(int status, String desc) { if (status == 0) { callback.success(mGson.toJson(msg)); } else { callback.error(status + ": " + desc); } } }); JMessageClient.sendMessage(msg); mediaPlayer.release(); } catch (JSONException e) { e.printStackTrace(); callback.error("json data error"); } catch (MalformedURLException e) { e.printStackTrace(); callback.error("file url error"); } catch (FileNotFoundException e) { e.printStackTrace(); callback.error("file not found."); } } public void sendGroupVoiceMessageWithExtras(JSONArray data, final CallbackContext callback) { try { long groupId = data.getLong(0); String voiceUrlStr = data.getString(1); String json = data.getString(2); Conversation conversation = JMessageClient.getGroupConversation(groupId); if (conversation == null) { conversation = Conversation.createGroupConversation(groupId); } if (conversation == null) { callback.error(""); return; } URL url = new URL(voiceUrlStr); String voicePath = url.getPath(); File file = new File(voicePath); MediaPlayer mediaPlayer = MediaPlayer.create(this.cordova.getActivity(), Uri.parse(voicePath)); int duration = mediaPlayer.getDuration(); VoiceContent content = new VoiceContent(file, duration); if (!TextUtils.isEmpty(json)) { content.setExtras(getExtras(json)); } final Message msg = JMessageClient.createGroupVoiceMessage(groupId, file, duration); msg.setOnSendCompleteCallback(new BasicCallback() { @Override public void gotResult(int status, String desc) { if (status == 0) { callback.success(mGson.toJson(msg)); } else { callback.error(status + ": " + desc); } } }); JMessageClient.sendMessage(msg); mediaPlayer.release(); } catch (JSONException e) { e.printStackTrace(); callback.error("json data error"); } catch (MalformedURLException e) { e.printStackTrace(); callback.error("file url error"); } catch (FileNotFoundException e) { e.printStackTrace(); callback.error("file not found."); } } /** * @param data JSONArray. * data.getLong(0):groupID, data.getJSONObject(1):custom key-values. * @param callback CallbackContext. */ public void sendGroupCustomMessage(JSONArray data, final CallbackContext callback) { try { long groupId = data.getLong(0); Conversation con = JMessageClient.getGroupConversation(groupId); if (con == null) { con = Conversation.createGroupConversation(groupId); } if (con == null) { callback.error(""); return; } String jsonStr = data.getString(1); JSONObject customValues = new JSONObject(jsonStr); Iterator<? extends String> keys = customValues.keys(); String key, value; Map<String, String> valuesMap = new HashMap<String, String>(); while (keys.hasNext()) { key = keys.next(); value = customValues.getString(key); valuesMap.put(key, value); } final Message msg = JMessageClient.createGroupCustomMessage(groupId, valuesMap); msg.setOnSendCompleteCallback(new BasicCallback() { @Override public void gotResult(int status, String desc) { if (status == 0) { callback.success(mGson.toJson(msg)); } else { callback.error(status + ": " + desc); } } }); JMessageClient.sendMessage(msg); } catch (JSONException e) { e.printStackTrace(); callback.error("error reading id json."); } } public void getLatestMessage(JSONArray data, CallbackContext callback) { try { String conversationType = data.getString(0); String value = data.getString(1); String appKey = data.isNull(2) ? "" : data.getString(2); Conversation conversation = getConversation(conversationType, value, appKey); if (conversation == null) { callback.error("Conversation is not exist."); return; } Message msg = conversation.getLatestMessage(); if (msg != null) { String json = mGson.toJson(msg); callback.success(json); } else { callback.success(""); } } catch (JSONException e) { e.printStackTrace(); callback.error("Parameter error."); } } public void getHistoryMessages(JSONArray data, CallbackContext callback) { try { String conversationType = data.getString(0); Conversation conversation; if (conversationType.equals("single")) { String username = data.getString(1); String appKey = data.isNull(2) ? "" : data.getString(2); Log.i(TAG, "username:" + username + "; appKey:" + appKey); conversation = JMessageClient.getSingleConversation( username, appKey); if (conversation == null) { callback.error("Conversation is not exist."); return; } } else if (conversationType.equals("group")) { long groupId = data.getLong(1); conversation = JMessageClient.getGroupConversation(groupId); if (conversation == null) { conversation = Conversation.createGroupConversation(groupId); } } else { callback.error("Conversation type error."); return; } int from = data.getInt(3); int limit = data.getInt(4); List<Message> messages = conversation.getMessagesFromNewest(from, limit); if (!messages.isEmpty()) { callback.success(mGson.toJson(messages)); } else { callback.success(""); } } catch (JSONException e) { e.printStackTrace(); callback.error("Parameter error."); } } public void getAllMessages(JSONArray data, CallbackContext callback) { try { String type = data.getString(0); Conversation conversation; if (type.equals("single")) { String username = data.getString(1); String appKey = data.isNull(2) ? "" : data.getString(2); conversation = JMessageClient.getSingleConversation( username, appKey); if (conversation == null) { callback.error("Conversation is not exist."); return; } } else if (type.equals("group")) { long groupId = data.getLong(1); conversation = JMessageClient.getGroupConversation(groupId); if (conversation == null) { conversation = Conversation.createGroupConversation(groupId); } } else { callback.error("Conversation type error."); return; } List<Message> messages = conversation.getAllMessage(); if (messages != null && !messages.isEmpty()) { String json = mGson.toJson(messages); callback.success(json); } else { callback.success(""); } } catch (JSONException e) { e.printStackTrace(); callback.error("Parameter error."); } } // Conversation API. public void isSingleConversationExist(JSONArray data, CallbackContext callback) { try { String username = data.getString(0); String appKey = data.isNull(1) ? "" : data.getString(1); Conversation con = JMessageClient.getSingleConversation(username, appKey); if (con == null) { callback.success(0); } else { callback.success(1); } } catch (JSONException e) { e.printStackTrace(); callback.error("Parameter error."); } } public void isGroupConversationExist(JSONArray data, CallbackContext callback) { try { long groupId = data.getLong(0); Conversation con = JMessageClient.getGroupConversation(groupId); if (con == null) { callback.success(0); } else { callback.success(1); } } catch (JSONException e) { e.printStackTrace(); callback.error("Parameter error."); } } public void getConversationList(JSONArray data, CallbackContext callback) { try { List<Conversation> conversationList = JMessageClient.getConversationList(); if (conversationList != null) { JSONArray conArr = new JSONArray(); JSONObject conJson; for (Conversation con : conversationList) { conJson = new JSONObject(mGson.toJson(con)); if (conJson.isNull("latestMessage")) { Message latestMsg = con.getLatestMessage(); JSONObject msgJson = new JSONObject(mGson.toJson(latestMsg)); conJson.put("latestMessage", msgJson); } conArr.put(conJson); } callback.success(conArr.toString()); } else { callback.success(""); } } catch (JSONException e) { e.printStackTrace(); } } public void setSingleConversationUnreadMessageCount(JSONArray data, CallbackContext callback) { try { String username = data.getString(0); String appKey = data.isNull(1) ? "" : data.getString(1); int unreadMessageCount = data.getInt(2); Conversation con = JMessageClient.getSingleConversation(username, appKey); if (con == null) { callback.error("Conversation is not exist."); return; } con.setUnReadMessageCnt(unreadMessageCount); callback.success(); } catch (JSONException e) { e.printStackTrace(); callback.error("Parameter error."); } } public void setGroupConversationUnreadMessageCount(JSONArray data, CallbackContext callback) { try { long groupId = data.getLong(0); int unreadMessageCount = data.getInt(1); Conversation con = JMessageClient.getGroupConversation(groupId); if (con == null) { callback.error("Conversation is not exist."); return; } con.setUnReadMessageCnt(unreadMessageCount); callback.success(); } catch (JSONException e) { e.printStackTrace(); callback.error("Parameter error."); } } public void enterSingleConversation(JSONArray data, CallbackContext callback) { try { String username = data.getString(0); String appKey = data.isNull(1) ? "" : data.getString(1); JMessageClient.enterSingleConversation(username, appKey); callback.success(); } catch (JSONException e) { e.printStackTrace(); callback.error("Parameter error."); } } public void enterGroupConversation(JSONArray data, CallbackContext callback) { try { long groupId = data.getLong(0); JMessageClient.enterGroupConversation(groupId); callback.success(); } catch (JSONException e) { e.printStackTrace(); callback.error("Parameter error."); } } public void getSingleConversation(JSONArray data, CallbackContext callback) { try { String username = data.getString(0); String appKey = data.isNull(1) ? "" : data.getString(1); Conversation conversation = JMessageClient.getSingleConversation(username, appKey); if (conversation != null) { String json = mGson.toJson(conversation); callback.success(json); } else { callback.success(""); } } catch (JSONException e) { e.printStackTrace(); callback.error("Parameter error."); } } public void getGroupConversation(JSONArray data, CallbackContext callback) { try { long groupId = data.getLong(0); Conversation conversation = JMessageClient.getGroupConversation(groupId); if (conversation != null) { String json = mGson.toJson(conversation); callback.success(json); } else { callback.success(""); } } catch (JSONException e) { e.printStackTrace(); callback.error("Parameter error."); } } public void deleteSingleConversation(JSONArray data, CallbackContext callback) { try { String username = data.getString(0); String appKey = data.isNull(1) ? "" : data.getString(1); if (TextUtils.isEmpty(appKey)) { JMessageClient.deleteSingleConversation(username); } else { JMessageClient.deleteSingleConversation(username, appKey); } callback.success(); } catch (JSONException e) { e.printStackTrace(); callback.error("Parameter error."); } } public void deleteGroupConversation(JSONArray data, CallbackContext callback) { try { long groupId = data.getLong(0); JMessageClient.deleteGroupConversation(groupId); callback.success(); } catch (JSONException e) { e.printStackTrace(); callback.error("Parameter error."); } } public void exitConversation(JSONArray data, CallbackContext callback) { try { JMessageClient.exitConversation(); callback.success(); } catch (Exception exception) { callback.error(exception.toString()); } } // Group API. public void createGroup(JSONArray data, final CallbackContext callback) { try { String groupName = data.getString(0); String groupDesc = data.getString(1); JMessageClient.createGroup(groupName, groupDesc, new CreateGroupCallback() { @Override public void gotResult(int responseCode, String responseMsg, long groupId) { if (responseCode == 0) { callback.success(String.valueOf(groupId)); } else { callback.error(responseCode); } } }); } catch (JSONException e) { e.printStackTrace(); callback.error("Parameter error."); } } public void getGroupIDList(JSONArray data, final CallbackContext callback) { JMessageClient.getGroupIDList(new GetGroupIDListCallback() { @Override public void gotResult(int responseCode, String responseMsg, List<Long> list) { if (responseCode == 0) { callback.success(mGson.toJson(list)); } else { callback.error(responseCode); } } }); } public void getGroupInfo(JSONArray data, final CallbackContext callback) { try { long groupId = data.getLong(0); JMessageClient.getGroupInfo(groupId, new GetGroupInfoCallback() { @Override public void gotResult(int responseCode, String responseMsg, GroupInfo groupInfo) { if (responseCode == 0) { callback.success(mGson.toJson(groupInfo)); } else { callback.error(responseCode); } } }); } catch (JSONException e) { e.printStackTrace(); callback.error("Parameter error."); } } public void updateGroupName(JSONArray data, final CallbackContext callback) { try { long groupId = data.getLong(0); String groupNewName = data.getString(1); JMessageClient.updateGroupName(groupId, groupNewName, new BasicCallback() { @Override public void gotResult(int responseCode, String responseDesc) { if (responseCode == 0) { callback.success(); } else { callback.error(responseCode); } } }); } catch (JSONException e) { e.printStackTrace(); callback.error("Parameter error."); } } public void updateGroupDescription(JSONArray data, final CallbackContext callback) { try { long groupId = data.getLong(0); String groupNewDesc = data.getString(1); JMessageClient.updateGroupDescription(groupId, groupNewDesc, new BasicCallback() { @Override public void gotResult(int responseCode, String responseMsg) { if (responseCode == 0) { callback.success(); } else { callback.error(responseMsg); } } }); } catch (JSONException e) { e.printStackTrace(); callback.error("Parameter error."); } } public void addGroupMembers(JSONArray data, final CallbackContext callback) { try { long groupId = data.getLong(0); String membersStr = data.getString(1); String[] members = membersStr.split(","); List<String> memberList = new ArrayList<String>(); Collections.addAll(memberList, members); JMessageClient.addGroupMembers(groupId, memberList, new BasicCallback() { @Override public void gotResult(int responseCode, String responseDesc) { if (responseCode == 0) { callback.success(); } else { callback.error(responseDesc); } } }); } catch (JSONException e) { e.printStackTrace(); callback.error("Parameter error."); } } public void removeGroupMembers(JSONArray data, final CallbackContext callback) { try { long groupId = data.getLong(0); String userNamesStr = data.getString(1); String[] userNamesArr = userNamesStr.split(","); List<String> userNamesList = Arrays.asList(userNamesArr); JMessageClient.removeGroupMembers(groupId, userNamesList, new BasicCallback() { @Override public void gotResult(int responseCode, String responseDesc) { if (responseCode == 0) { callback.success(); } else { callback.error(responseDesc); } } }); } catch (JSONException e) { e.printStackTrace(); } } public void exitGroup(JSONArray data, final CallbackContext callback) { try { long groupId = data.getLong(0); JMessageClient.exitGroup(groupId, new BasicCallback() { @Override public void gotResult(int responseCode, String responseDesc) { if (responseCode == 0) { callback.success(); } else { callback.error(responseDesc); } } }); } catch (JSONException e) { e.printStackTrace(); callback.error("Parameter error."); } } public void getGroupMembers(JSONArray data, final CallbackContext callback) { try { long groupId = data.getLong(0); JMessageClient.getGroupMembers(groupId, new GetGroupMembersCallback() { @Override public void gotResult(int responseCode, String responseDesc, List<UserInfo> list) { if (responseCode == 0) { String json = new Gson().toJson(list); callback.success(json); } else { callback.error(responseDesc); } } }); } catch (JSONException e) { e.printStackTrace(); callback.error("Parameter error."); } } // Black list API. public void addUsersToBlacklist(JSONArray data, final CallbackContext callback) { try { String usernameStr = data.getString(0); String[] usernameArr = usernameStr.split(","); List<String> usernameList = Arrays.asList(usernameArr); JMessageClient.addUsersToBlacklist(usernameList, new BasicCallback() { @Override public void gotResult(int responseCode, String responseDesc) { if (responseCode == 0) { callback.success(); } else { callback.error(responseDesc); } } }); } catch (JSONException e) { e.printStackTrace(); callback.error("Parameter error."); } } public void delUsersFromBlacklist(JSONArray data, final CallbackContext callback) { try { String usernameStr = data.getString(0); String[] usernameArr = usernameStr.split(","); List<String> usernameList = Arrays.asList(usernameArr); JMessageClient.delUsersFromBlacklist(usernameList, new BasicCallback() { @Override public void gotResult(int responseCode, String responseDesc) { if (responseCode == 0) { callback.success(); } else { callback.error(responseDesc); } } }); } catch (JSONException e) { e.printStackTrace(); callback.error("Parameter error."); } } public void getBlacklist(JSONArray data, final CallbackContext callback) { JMessageClient.getBlacklist(new GetBlacklistCallback() { @Override public void gotResult(int responseCode, String responseDesc, List<UserInfo> list) { if (responseCode == 0) { callback.success(mGson.toJson(list)); } else { callback.error(responseDesc); } } }); } public void setNotificationMode(JSONArray data, CallbackContext callback) { try { int mode = data.getInt(0); JMessageClient.setNotificationMode(mode); callback.success(); } catch (JSONException e) { e.printStackTrace(); callback.error("Parameter error."); } } public void getOriginImageInSingleConversation(JSONArray data, final CallbackContext callback) { try { String username = data.getString(0); long msgId = data.getLong(1); Conversation con = JMessageClient.getSingleConversation(username); if (con == null) { callback.error("Conversation isn't exist."); return; } List<Message> messageList = con.getAllMessage(); for (Message msg : messageList) { if (!msg.getContentType().equals(ContentType.image)) { continue; } if (msgId == msg.getServerMessageId()) { ImageContent imgContent = (ImageContent) msg.getContent(); if (!TextUtils.isEmpty(imgContent.getLocalPath())) { callback.success(imgContent.getLocalPath()); return; } imgContent.downloadOriginImage(msg, new DownloadCompletionCallback() { @Override public void onComplete(int status, String desc, File file) { if (status == 0) { callback.success(file.getAbsolutePath()); } else { Log.i(TAG, "getOriginImageInSingleConversation: " + status + " - " + desc); callback.error(status); } } }); } } } catch (JSONException e) { e.printStackTrace(); callback.error("Argument error."); } } public void getOriginImageInGroupConversation(JSONArray data, final CallbackContext callback) { try { long groupId = data.getLong(0); long msgId = data.getLong(1); Conversation con = JMessageClient.getGroupConversation(groupId); if (con == null) { callback.error("Conversation isn't exist."); return; } List<Message> messageList = con.getAllMessage(); for (Message msg : messageList) { if (!msg.getContentType().equals(ContentType.image)) { continue; } if (msgId == msg.getServerMessageId()) { ImageContent imgContent = (ImageContent) msg.getContent(); if (!TextUtils.isEmpty(imgContent.getLocalPath())) { callback.success(imgContent.getLocalPath()); return; } imgContent.downloadOriginImage(msg, new DownloadCompletionCallback() { @Override public void onComplete(int status, String desc, File file) { if (status == 0) { callback.success(file.getAbsolutePath()); } else { Log.i(TAG, "getOriginImageInGroupConversation: " + status + " - " + desc); callback.error(status); } } }); } } } catch (JSONException e) { e.printStackTrace(); callback.error("Argument error."); } } private JSONObject getJSonFormMessage(Message msg) { String contentText = ""; String msgType = ""; // js iOS switch (msg.getContentType()) { case text: contentText = ((TextContent) msg.getContent()).getText(); msgType = "text"; break; default: break; } Log.i(TAG, "msg " + contentText); JSONObject jsonItem = new JSONObject(); try { MessageContent content = msg.getContent(); UserInfo targetUser = (UserInfo) msg.getTargetInfo(); UserInfo fromUser = (UserInfo) msg.getFromUser(); jsonItem.put("target_type", "single"); jsonItem.put("target_id", targetUser.getUserName()); jsonItem.put("target_name", targetUser.getNickname()); jsonItem.put("from_id", fromUser.getUserName()); //jsonItem.put("from_name", fromUser.getNickname()); jsonItem.put("from_name", msg.getFromName()); jsonItem.put("create_time", msg.getCreateTime()); jsonItem.put("msg_type", msgType); //jsonItem.put("text", contentText); JSONObject contentBody = new JSONObject(); contentBody.put("text", contentText); jsonItem.put("msg_body", contentBody); } catch (JSONException e) { e.printStackTrace(); } return jsonItem; } public void getSingleConversationHistoryMessage(JSONArray data, CallbackContext callback) { Log.i(TAG, "getSingleConversationHistoryMessage \n" + data); try { String username = data.getString(0); int from = data.getInt(1); int limit = data.getInt(2); if (limit <= 0 || from < 0) { Log.w(TAG, "JMessageGetSingleHistoryMessage from: " + from + "limit" + limit); return; } Conversation conversation = JMessageClient.getSingleConversation( username); if (conversation == null) { conversation = Conversation.createSingleConversation(username); } if (conversation == null) { callback.error(""); return; } List<Message> list = conversation.getMessagesFromNewest(from, limit); Log.i(TAG, "JMessageGetSingleHistoryMessage list size is" + list.size()); JSONArray jsonResult = new JSONArray(); for (int i = 0; i < list.size(); ++i) { Message msg = list.get(i); JSONObject obj = this.getJSonFormMessage(msg); jsonResult.put(obj); } callback.success(jsonResult); } catch (JSONException e) { e.printStackTrace(); callback.error("error reading id json."); } } public void getAllSingleConversation(JSONArray data, CallbackContext callback) { try { List<Conversation> list = JMessageClient.getConversationList(); JSONArray jsonArr = new JSONArray(); JSONObject jsonObj; for (Conversation con : list) { if (con.getType() == ConversationType.single) { jsonObj = new JSONObject(mGson.toJson(con)); Message latestMsg = con.getLatestMessage(); if (!jsonObj.has("latestMessage")) { JSONObject msgJson = new JSONObject(mGson.toJson(latestMsg)); jsonObj.put("latestMessage", msgJson); } jsonArr.put(jsonObj); } } callback.success(jsonArr.toString()); } catch (JSONException e) { e.printStackTrace(); callback.error(e.getMessage()); } } public void getAllGroupConversation(JSONArray data, CallbackContext callback) { List<Conversation> list = JMessageClient.getConversationList(); JSONArray jsonArr = new JSONArray(); JSONObject jsonObj; try { for (Conversation con : list) { if (con.getType() == ConversationType.group) { jsonObj = new JSONObject(mGson.toJson(con)); Message latestMsg = con.getLatestMessage(); if (!jsonObj.has("latestMessage")) { JSONObject msgJson = new JSONObject(mGson.toJson(latestMsg)); jsonObj.put("latestMessage", msgJson); } jsonArr.put(jsonObj); } } callback.success(jsonArr.toString()); } catch (JSONException e) { e.printStackTrace(); callback.error(e.getMessage()); } } public void setJMessageReceiveCallbackChannel(JSONArray data, CallbackContext callback) { Log.i(TAG, "setJMessageReceiveCallbackChannel:" + callback.getCallbackId()); PluginResult dataResult = new PluginResult(PluginResult.Status.OK, "js call init ok"); dataResult.setKeepCallback(true); callback.sendPluginResult(dataResult); } /** * @param type 'single' or 'group' * @param value 'single' username * 'group' groupId * @param appKey 'single' * @return */ private Conversation getConversation(String type, String value, String appKey) { Conversation conversation = null; if (type.equals("single")) { conversation = JMessageClient.getSingleConversation(value, appKey); } else if (type.equals("group")) { long groupId = Long.parseLong(value); conversation = JMessageClient.getGroupConversation(groupId); } else { return null; } return conversation; } private void handleResult(String successString, int status, String desc, CallbackContext callback) { if (status == 0) { if (TextUtils.isEmpty(successString)) { callback.success(); } else { callback.success(successString); } } else { callback.error(desc); } } private String updateUserInfo(UserInfo userInfo, String field, String value) { final String[] result = {null}; if (field.equals("nickname")) { userInfo.setNickname(value); } else if (field.equals("birthday")) { long birthday = Long.parseLong(value); userInfo.setBirthday(birthday); } else if (field.equals("gender")) { if (value.equals("male")) { userInfo.setGender(UserInfo.Gender.male); } else if (value.equals("female")) { userInfo.setGender(UserInfo.Gender.female); } else { userInfo.setGender(UserInfo.Gender.unknown); } } else if (field.equals("signature")) { userInfo.setSignature(value); } else if (field.equals("region")) { userInfo.setRegion(value); } else { return "Field name error."; } JMessageClient.updateMyInfo(UserInfo.Field.valueOf(field), userInfo, new BasicCallback() { @Override public void gotResult(int responseCode, String responseDesc) { if (responseCode != 0) { result[0] = responseDesc; } } }); return result[0]; } private String getFilePath() { return Environment.getExternalStorageDirectory() + "/" + cordova.getActivity().getApplication().getPackageName(); } private String getAvatarPath() { return getFilePath() + "/images/avatar/"; } private String storeImage(Bitmap bitmap, String filename) { File avatarFile = new File(getAvatarPath()); if (!avatarFile.exists()) { avatarFile.mkdirs(); } String filePath = getAvatarPath() + filename + ".png"; try { FileOutputStream fos = new FileOutputStream(filePath); BufferedOutputStream bos = new BufferedOutputStream(fos); bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos); bos.flush(); bos.close(); return filePath; } catch (FileNotFoundException e) { e.printStackTrace(); return ""; } catch (IOException e) { e.printStackTrace(); return ""; } } private JSONObject getMessageJSONObject(Message msg) throws JSONException { String jsonStr = mGson.toJson(msg); JSONObject msgJson = new JSONObject(jsonStr); // Add user avatar path. UserInfo fromUser = msg.getFromUser(); String avatarPath = ""; File avatarFile = fromUser.getAvatarFile(); if (avatarFile != null) { avatarPath = avatarFile.getAbsolutePath(); } msgJson.getJSONObject("fromUser").put("avatarPath", avatarPath); File myAvatarFile = JMessageClient.getMyInfo().getAvatarFile(); String myAvatarPath = ""; if (myAvatarFile != null) { myAvatarPath = myAvatarFile.getAbsolutePath(); } msgJson.getJSONObject("targetInfo").put("avatarPath", myAvatarPath); switch (msg.getContentType()) { case image: ImageContent imageContent = (ImageContent) msg.getContent(); String imgPath = imageContent.getLocalPath(); String imgLink = imageContent.getImg_link(); msgJson.getJSONObject("content").put("imagePath", imgPath); msgJson.getJSONObject("content").put("imageLink", imgLink); break; case voice: VoiceContent voiceContent = (VoiceContent) msg.getContent(); String voicePath = voiceContent.getLocalPath(); int duration = voiceContent.getDuration(); msgJson.getJSONObject("content").put("voicePath", voicePath); msgJson.getJSONObject("content").put("duration", duration); break; case custom: break; } return msgJson; } private Map<String, String> getExtras(String json) throws JSONException { JSONObject values = new JSONObject(json); Iterator<? extends String> keys = values.keys(); Map<String, String> valuesMap = new HashMap<String, String>(); String key, value; while (keys.hasNext()) { key = keys.next(); value = values.getString(key); valuesMap.put(key, value); } return valuesMap; } }
package edu.stuy; import edu.stuy.commands.*; import edu.stuy.subsystems.Flywheel; import edu.stuy.util.InverseDigitalIOButton; import edu.wpi.first.wpilibj.DriverStation; import edu.wpi.first.wpilibj.DriverStationEnhancedIO; import edu.wpi.first.wpilibj.DriverStationEnhancedIO.EnhancedIOException; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.buttons.JoystickButton; public class OI { private Joystick leftStick; private Joystick rightStick; private Joystick shooterStick; private Joystick debugBox; public static final int DISTANCE_BUTTON_AUTO = 7; public static final int DISTANCE_BUTTON_FAR = 6; public static final int DISTANCE_BUTTON_FENDER_LENGTH = 5; public static final int DISTANCE_BUTTON_FENDER_WIDTH = 4; public static final int DISTANCE_BUTTON_FENDER_SIDE = 3; public static final int DISTANCE_BUTTON_FENDER = 2; public static final int DISTANCE_BUTTON_STOP = 1; private DriverStationEnhancedIO enhancedIO; // EnhancedIO digital input public static final int CONVEYOR_DOWN_SWITCH_CHANNEL = 1; public static final int CONVEYOR_UP_SWITCH_CHANNEL = 2; public static final int BIT_1_CHANNEL = 5; public static final int BIT_2_CHANNEL = 4; public static final int BIT_3_CHANNEL = 3; public static final int SHOOTER_BUTTON_CHANNEL = 7; public static final int HOOP_HEIGHT_SWITCH_CHANNEL = 6; public static final int ACQUIRER_IN_SWITCH_CHANNEL = 9; public static final int ACQUIRER_OUT_SWITCH_CHANNEL = 8; public int distanceButton; public double distanceInches; public boolean topHoop = true; // EnhancedIO digital output private static final int DISTANCE_BUTTON_AUTO_LIGHT_CHANNEL = 10; private static final int DISTANCE_BUTTON_FAR_LIGHT_CHANNEL = 11; private static final int DISTANCE_BUTTON_FENDER_WIDE_LIGHT_CHANNEL = 12; private static final int DISTANCE_BUTTON_FENDER_NARROW_LIGHT_CHANNEL = 13; private static final int DISTANCE_BUTTON_FENDER_SIDE_LIGHT_CHANNEL = 15; private static final int DISTANCE_BUTTON_FENDER_LIGHT_CHANNEL = 14; private static final int DISTANCE_BUTTON_STOP_LIGHT_CHANNEL = 16; // EnhancedIO analog input public static final int DISTANCE_BUTTONS_CHANNEL = 1; public static final int SPEED_TRIM_POT_CHANNEL = 2; public static final int DELAY_POT_CHANNEL = 3; public static final int MAX_ANALOG_CHANNEL = 4; public OI() { enhancedIO = DriverStation.getInstance().getEnhancedIO(); leftStick = new Joystick(RobotMap.LEFT_JOYSTICK_PORT); rightStick = new Joystick(RobotMap.RIGHT_JOYSTICK_PORT); shooterStick = new Joystick(RobotMap.SHOOTER_JOYSTICK_PORT); debugBox = new Joystick(RobotMap.DEBUG_BOX_PORT); distanceButton = DISTANCE_BUTTON_STOP; distanceInches = Flywheel.distances[Flywheel.STOP_INDEX]; try { if (!Devmode.DEV_MODE) { enhancedIO.setDigitalConfig(BIT_1_CHANNEL, DriverStationEnhancedIO.tDigitalConfig.kInputPullUp); enhancedIO.setDigitalConfig(BIT_2_CHANNEL, DriverStationEnhancedIO.tDigitalConfig.kInputPullUp); enhancedIO.setDigitalConfig(BIT_3_CHANNEL, DriverStationEnhancedIO.tDigitalConfig.kInputPullUp); enhancedIO.setDigitalConfig(ACQUIRER_IN_SWITCH_CHANNEL, DriverStationEnhancedIO.tDigitalConfig.kInputPullUp); enhancedIO.setDigitalConfig(ACQUIRER_OUT_SWITCH_CHANNEL, DriverStationEnhancedIO.tDigitalConfig.kInputPullUp); enhancedIO.setDigitalConfig(CONVEYOR_UP_SWITCH_CHANNEL, DriverStationEnhancedIO.tDigitalConfig.kInputPullUp); enhancedIO.setDigitalConfig(CONVEYOR_DOWN_SWITCH_CHANNEL, DriverStationEnhancedIO.tDigitalConfig.kInputPullUp); enhancedIO.setDigitalConfig(SHOOTER_BUTTON_CHANNEL, DriverStationEnhancedIO.tDigitalConfig.kInputPullUp); enhancedIO.setDigitalConfig(HOOP_HEIGHT_SWITCH_CHANNEL, DriverStationEnhancedIO.tDigitalConfig.kInputPullUp); enhancedIO.setDigitalConfig(DISTANCE_BUTTON_AUTO_LIGHT_CHANNEL, DriverStationEnhancedIO.tDigitalConfig.kOutput); enhancedIO.setDigitalConfig(DISTANCE_BUTTON_FAR_LIGHT_CHANNEL, DriverStationEnhancedIO.tDigitalConfig.kOutput); enhancedIO.setDigitalConfig(DISTANCE_BUTTON_FENDER_WIDE_LIGHT_CHANNEL, DriverStationEnhancedIO.tDigitalConfig.kOutput); enhancedIO.setDigitalConfig(DISTANCE_BUTTON_FENDER_NARROW_LIGHT_CHANNEL, DriverStationEnhancedIO.tDigitalConfig.kOutput); enhancedIO.setDigitalConfig(DISTANCE_BUTTON_FENDER_SIDE_LIGHT_CHANNEL, DriverStationEnhancedIO.tDigitalConfig.kOutput); enhancedIO.setDigitalConfig(DISTANCE_BUTTON_FENDER_LIGHT_CHANNEL, DriverStationEnhancedIO.tDigitalConfig.kOutput); enhancedIO.setDigitalConfig(DISTANCE_BUTTON_STOP_LIGHT_CHANNEL, DriverStationEnhancedIO.tDigitalConfig.kOutput); } } catch (EnhancedIOException e) { } if (!Devmode.DEV_MODE) { new JoystickButton(rightStick, 1).whenPressed(new DrivetrainSetGear(false)); new JoystickButton(rightStick, 2).whenPressed(new DrivetrainSetGear(true)); new JoystickButton(leftStick, 1).whenPressed(new TusksExtend()); new JoystickButton(leftStick, 2).whenPressed(new TusksRetract()); // OI box switches new InverseDigitalIOButton(ACQUIRER_IN_SWITCH_CHANNEL).whileHeld(new AcquirerAcquire()); new InverseDigitalIOButton(ACQUIRER_OUT_SWITCH_CHANNEL).whileHeld(new AcquirerReverse()); new InverseDigitalIOButton(CONVEYOR_UP_SWITCH_CHANNEL).whileHeld(new ConveyManual()); new InverseDigitalIOButton(CONVEYOR_DOWN_SWITCH_CHANNEL).whileHeld(new ConveyReverseManual()); new InverseDigitalIOButton(SHOOTER_BUTTON_CHANNEL).whileHeld(new ConveyAutomatic()); new JoystickButton(shooterStick, 1).whileHeld(new ConveyManual()); new JoystickButton(shooterStick, 4).whenPressed(new FlywheelStop()); new JoystickButton(shooterStick, 5).whileHeld(new AcquirerReverse()); new JoystickButton(shooterStick, 6).whileHeld(new ConveyReverseManual()); new JoystickButton(shooterStick, 7).whileHeld(new AcquirerAcquire()); new JoystickButton(shooterStick, 8).whileHeld(new ConveyAutomatic()); // see getDistanceButton() } } // Copied from last year's DesDroid code. public double getRawAnalogVoltage() { try { return enhancedIO.getAnalogIn(DISTANCE_BUTTONS_CHANNEL); } catch (EnhancedIOException e) { return 0; } } public double getMaxVoltage() { try { return enhancedIO.getAnalogIn(MAX_ANALOG_CHANNEL); } catch (EnhancedIOException e) { return 2.2; } } /** * Determines which height button is pressed. All (7 logically because * side buttons are wired together) buttons are wired by means of * resistors to one analog input. Depending on the button that is pressed, a * different voltage is read by the analog input. Each resistor reduces the * voltage by about 1/7 the maximum voltage. * * @return An integer value representing the distance button that was pressed. * If a Joystick button is being used, that will returned. Otherwise, the * button will be returned from the voltage (if it returns 0, no button is pressed). */ public int getDistanceButton() { if (shooterStick.getRawButton(9)) { distanceButton = DISTANCE_BUTTON_STOP; } else if(shooterStick.getRawButton(10)) { distanceButton = DISTANCE_BUTTON_FENDER; } else if(shooterStick.getRawButton(11)) { distanceButton = DISTANCE_BUTTON_FAR; } int preValue = (int) ((getRawAnalogVoltage() / (getMaxVoltage() / 8)) + 0.5); // If no buttons are pressed, it does not update the distance. if(preValue != 0){ distanceButton = preValue; } return distanceButton; } /** * Takes the distance button that has been pressed, and finds the distance for * the shooter to use. * @return distance for the shooter. */ public double getDistanceFromDistanceButton(){ switch(distanceButton){ /*case DISTANCE_BUTTON_AUTO: distanceInches = CommandBase.drivetrain.getSonarDistance_in(); break; */ case DISTANCE_BUTTON_FAR: distanceInches = Flywheel.distances[Flywheel.MAX_DIST]; case DISTANCE_BUTTON_FENDER_LENGTH: distanceInches = Flywheel.distances[Flywheel.FENDER_LONG_INDEX]; break; case DISTANCE_BUTTON_FENDER_WIDTH: distanceInches = Flywheel.distances[Flywheel.FENDER_WIDE_INDEX]; break; case DISTANCE_BUTTON_FENDER_SIDE: distanceInches = Flywheel.distances[Flywheel.FENDER_SIDE_INDEX]; break; case DISTANCE_BUTTON_FENDER: distanceInches = Flywheel.distances[Flywheel.FENDER_INDEX]; break; case DISTANCE_BUTTON_STOP: distanceInches = 0; break; default: break; } return distanceInches; } public double[] getHeightFromButton() { try { topHoop = !enhancedIO.getDigital(HOOP_HEIGHT_SWITCH_CHANNEL); } catch (EnhancedIOException ex) { topHoop = true; } return (topHoop ? Flywheel.speedsMiddleHoop : Flywheel.speedsTopHoop); } // Copied from last year's DesDroid code. public Joystick getLeftStick() { return leftStick; } public Joystick getRightStick() { return rightStick; } public Joystick getDebugBox() { return debugBox; } /** * Gets value of hoop height toggle switch. * @return true if high setting, false if middle */ public boolean getHoopHeightButton() { try { return !enhancedIO.getDigital(HOOP_HEIGHT_SWITCH_CHANNEL); } catch (EnhancedIOException ex) { return true; } } /** * Use a thumb wheel switch to set the autonomous mode setting. * @return Autonomous setting to run. */ public int getAutonSetting() { try { int switchNum = 0; int[] binaryValue = new int[3]; boolean[] dIO = {!enhancedIO.getDigital(BIT_1_CHANNEL), !enhancedIO.getDigital(BIT_2_CHANNEL), !enhancedIO.getDigital(BIT_3_CHANNEL)}; for (int i = 0; i < 3; i++) { if (dIO[i]) { binaryValue[i] = 1; } else { binaryValue[i] = 0; } } binaryValue[0] *= 4; // convert all binaryValues to decimal values binaryValue[1] *= 2; for (int i = 0; i < 3; i++) { // finish binary -> decimal conversion switchNum += binaryValue[i]; } return switchNum; } catch (EnhancedIOException e) { return -1; // Do nothing in case of failure } } public int getDebugBoxBinaryAutonSetting() { int switchNum = 0; int[] binaryValue = new int[4]; boolean[] dIO = {debugBox.getRawButton(1), debugBox.getRawButton(2), debugBox.getRawButton(3), debugBox.getRawButton(4)}; for (int i = 0; i < 4; i++) { if (dIO[i]) { binaryValue[i] = 1; } else { binaryValue[i] = 0; } } binaryValue[0] *= 8; // convert all binaryValues to decimal values binaryValue[1] *= 4; binaryValue[2] *= 2; for (int i = 0; i < 4; i++) { // finish binary -> decimal conversion switchNum += binaryValue[i]; } return switchNum; } public double getSpeedPot() { try { return getMaxVoltage() - enhancedIO.getAnalogIn(SPEED_TRIM_POT_CHANNEL); } catch (EnhancedIOException ex) { return 0.0; } } public double getDelayPot() { try { return getMaxVoltage() - enhancedIO.getAnalogIn(DELAY_POT_CHANNEL); } catch (EnhancedIOException ex) { return 0.0; } } public double getDelayTime(){ return getDelayPot() * 1000; } /** * Turns on specified light on OI. * @param lightNum */ public void setLight(int lightNum) { turnOffLights(); try { enhancedIO.setDigitalOutput(lightNum, true); } catch (EnhancedIOException e) { } } /** * Turns all lights off. */ public void turnOffLights(){ try { enhancedIO.setDigitalOutput(DISTANCE_BUTTON_AUTO_LIGHT_CHANNEL, false); enhancedIO.setDigitalOutput(DISTANCE_BUTTON_FAR_LIGHT_CHANNEL, false); enhancedIO.setDigitalOutput(DISTANCE_BUTTON_FENDER_WIDE_LIGHT_CHANNEL, false); enhancedIO.setDigitalOutput(DISTANCE_BUTTON_FENDER_NARROW_LIGHT_CHANNEL, false); enhancedIO.setDigitalOutput(DISTANCE_BUTTON_FENDER_SIDE_LIGHT_CHANNEL, false); enhancedIO.setDigitalOutput(DISTANCE_BUTTON_FENDER_LIGHT_CHANNEL, false); enhancedIO.setDigitalOutput(DISTANCE_BUTTON_STOP_LIGHT_CHANNEL, false); } catch (EnhancedIOException e) { } } /** * Turns all lights on. */ public void turnOnLights(){ try { enhancedIO.setDigitalOutput(DISTANCE_BUTTON_AUTO_LIGHT_CHANNEL, true); enhancedIO.setDigitalOutput(DISTANCE_BUTTON_FAR_LIGHT_CHANNEL, true); enhancedIO.setDigitalOutput(DISTANCE_BUTTON_FENDER_WIDE_LIGHT_CHANNEL, true); enhancedIO.setDigitalOutput(DISTANCE_BUTTON_FENDER_NARROW_LIGHT_CHANNEL, true); enhancedIO.setDigitalOutput(DISTANCE_BUTTON_FENDER_SIDE_LIGHT_CHANNEL, true); enhancedIO.setDigitalOutput(DISTANCE_BUTTON_FENDER_LIGHT_CHANNEL, true); enhancedIO.setDigitalOutput(DISTANCE_BUTTON_STOP_LIGHT_CHANNEL, true); } catch (EnhancedIOException e) { } } /** * Meant to be called continuously to update the lights on the OI board. * Depending on which button has been pressed last (which distance is * currently set), that button will be lit. */ public void updateLights(){ switch(distanceButton){ case DISTANCE_BUTTON_AUTO: setLight(DISTANCE_BUTTON_AUTO_LIGHT_CHANNEL); break; case DISTANCE_BUTTON_FAR: setLight(DISTANCE_BUTTON_FAR_LIGHT_CHANNEL); break; case DISTANCE_BUTTON_FENDER_LENGTH: setLight(DISTANCE_BUTTON_FENDER_WIDE_LIGHT_CHANNEL); break; case DISTANCE_BUTTON_FENDER_WIDTH: setLight(DISTANCE_BUTTON_FENDER_NARROW_LIGHT_CHANNEL); break; case DISTANCE_BUTTON_FENDER_SIDE: setLight(DISTANCE_BUTTON_FENDER_SIDE_LIGHT_CHANNEL); break; case DISTANCE_BUTTON_FENDER: setLight(DISTANCE_BUTTON_FENDER_LIGHT_CHANNEL); break; case DISTANCE_BUTTON_STOP: setLight(DISTANCE_BUTTON_STOP_LIGHT_CHANNEL); break; default: turnOffLights(); break; } } // For debugging purposes. public boolean getDigitalValue(int channel) { boolean b = false; try{ b = !enhancedIO.getDigital(channel); } catch (EnhancedIOException e) { } return b; } // For debugging purposes. public double getAnalogValue(int channel) { double b = 0; try{ b = enhancedIO.getAnalogOut(channel); } catch (EnhancedIOException e) { } return b; } public void resetBox(){ turnOffLights(); distanceButton = DISTANCE_BUTTON_STOP; } }
package edu.stuy; import edu.stuy.commands.*; import edu.stuy.subsystems.Flywheel; import edu.stuy.util.InverseDigitalIOButton; import edu.wpi.first.wpilibj.DriverStation; import edu.wpi.first.wpilibj.DriverStationEnhancedIO; import edu.wpi.first.wpilibj.DriverStationEnhancedIO.EnhancedIOException; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.buttons.JoystickButton; public class OI { private Joystick leftStick; private Joystick rightStick; private Joystick shooterStick; private Joystick debugBox; public static final int DISTANCE_BUTTON_KEY = 7; public static final int DISTANCE_BUTTON_FAR = 6; public static final int DISTANCE_BUTTON_FENDER_LENGTH = 5; public static final int DISTANCE_BUTTON_FENDER_WIDTH = 4; public static final int DISTANCE_BUTTON_FENDER_SIDE = 3; public static final int DISTANCE_BUTTON_FENDER = 2; public static final int DISTANCE_BUTTON_STOP = 1; private DriverStationEnhancedIO enhancedIO; // EnhancedIO digital input public static final int CONVEYOR_DOWN_SWITCH_CHANNEL = 1; public static final int CONVEYOR_UP_SWITCH_CHANNEL = 2; public static final int BIT_1_CHANNEL = 5; public static final int BIT_2_CHANNEL = 4; public static final int BIT_3_CHANNEL = 3; public static final int SHOOTER_BUTTON_CHANNEL = 7; public static final int HOOP_HEIGHT_SWITCH_CHANNEL = 6; public static final int ACQUIRER_IN_SWITCH_CHANNEL = 9; public static final int ACQUIRER_OUT_SWITCH_CHANNEL = 8; public int distanceButton; public double distanceInches; public boolean topHoop = true; // EnhancedIO digital output private static final int DISTANCE_BUTTON_KEY_LIGHT_CHANNEL = 10; private static final int DISTANCE_BUTTON_FAR_LIGHT_CHANNEL = 11; private static final int DISTANCE_BUTTON_FENDER_WIDE_LIGHT_CHANNEL = 12; private static final int DISTANCE_BUTTON_FENDER_NARROW_LIGHT_CHANNEL = 13; private static final int DISTANCE_BUTTON_FENDER_SIDE_LIGHT_CHANNEL = 15; private static final int DISTANCE_BUTTON_FENDER_LIGHT_CHANNEL = 14; private static final int DISTANCE_BUTTON_STOP_LIGHT_CHANNEL = 16; // EnhancedIO analog input public static final int DISTANCE_BUTTONS_CHANNEL = 1; public static final int SPEED_TRIM_POT_CHANNEL = 2; public static final int DELAY_POT_CHANNEL = 3; public static final int MAX_ANALOG_CHANNEL = 4; public static final int MAX_WAIT_TIME = 10; public OI() { enhancedIO = DriverStation.getInstance().getEnhancedIO(); leftStick = new Joystick(RobotMap.LEFT_JOYSTICK_PORT); rightStick = new Joystick(RobotMap.RIGHT_JOYSTICK_PORT); shooterStick = new Joystick(RobotMap.SHOOTER_JOYSTICK_PORT); debugBox = new Joystick(RobotMap.DEBUG_BOX_PORT); distanceButton = DISTANCE_BUTTON_STOP; distanceInches = Flywheel.distances[Flywheel.STOP_INDEX]; try { if (!Devmode.DEV_MODE) { enhancedIO.setDigitalConfig(BIT_1_CHANNEL, DriverStationEnhancedIO.tDigitalConfig.kInputPullUp); enhancedIO.setDigitalConfig(BIT_2_CHANNEL, DriverStationEnhancedIO.tDigitalConfig.kInputPullUp); enhancedIO.setDigitalConfig(BIT_3_CHANNEL, DriverStationEnhancedIO.tDigitalConfig.kInputPullUp); enhancedIO.setDigitalConfig(ACQUIRER_IN_SWITCH_CHANNEL, DriverStationEnhancedIO.tDigitalConfig.kInputPullUp); enhancedIO.setDigitalConfig(ACQUIRER_OUT_SWITCH_CHANNEL, DriverStationEnhancedIO.tDigitalConfig.kInputPullUp); enhancedIO.setDigitalConfig(CONVEYOR_UP_SWITCH_CHANNEL, DriverStationEnhancedIO.tDigitalConfig.kInputPullUp); enhancedIO.setDigitalConfig(CONVEYOR_DOWN_SWITCH_CHANNEL, DriverStationEnhancedIO.tDigitalConfig.kInputPullUp); enhancedIO.setDigitalConfig(SHOOTER_BUTTON_CHANNEL, DriverStationEnhancedIO.tDigitalConfig.kInputPullUp); enhancedIO.setDigitalConfig(HOOP_HEIGHT_SWITCH_CHANNEL, DriverStationEnhancedIO.tDigitalConfig.kInputPullUp); enhancedIO.setDigitalConfig(DISTANCE_BUTTON_KEY_LIGHT_CHANNEL, DriverStationEnhancedIO.tDigitalConfig.kOutput); enhancedIO.setDigitalConfig(DISTANCE_BUTTON_FAR_LIGHT_CHANNEL, DriverStationEnhancedIO.tDigitalConfig.kOutput); enhancedIO.setDigitalConfig(DISTANCE_BUTTON_FENDER_WIDE_LIGHT_CHANNEL, DriverStationEnhancedIO.tDigitalConfig.kOutput); enhancedIO.setDigitalConfig(DISTANCE_BUTTON_FENDER_NARROW_LIGHT_CHANNEL, DriverStationEnhancedIO.tDigitalConfig.kOutput); enhancedIO.setDigitalConfig(DISTANCE_BUTTON_FENDER_SIDE_LIGHT_CHANNEL, DriverStationEnhancedIO.tDigitalConfig.kOutput); enhancedIO.setDigitalConfig(DISTANCE_BUTTON_FENDER_LIGHT_CHANNEL, DriverStationEnhancedIO.tDigitalConfig.kOutput); enhancedIO.setDigitalConfig(DISTANCE_BUTTON_STOP_LIGHT_CHANNEL, DriverStationEnhancedIO.tDigitalConfig.kOutput); } } catch (EnhancedIOException e) { } if (!Devmode.DEV_MODE) { new JoystickButton(rightStick, 1).whenPressed(new DrivetrainSetGear(false)); new JoystickButton(rightStick, 2).whenPressed(new DrivetrainSetGear(true)); new JoystickButton(leftStick, 1).whenPressed(new TusksExtend()); new JoystickButton(leftStick, 2).whenPressed(new TusksRetract()); // OI box switches new InverseDigitalIOButton(ACQUIRER_IN_SWITCH_CHANNEL).whileHeld(new AcquirerAcquire()); new InverseDigitalIOButton(ACQUIRER_OUT_SWITCH_CHANNEL).whileHeld(new AcquirerReverse()); new InverseDigitalIOButton(CONVEYOR_UP_SWITCH_CHANNEL).whileHeld(new ConveyManual()); new InverseDigitalIOButton(CONVEYOR_DOWN_SWITCH_CHANNEL).whileHeld(new ConveyReverseManual()); new InverseDigitalIOButton(SHOOTER_BUTTON_CHANNEL).whileHeld(new ConveyAutomatic()); new JoystickButton(shooterStick, 1).whileHeld(new ConveyManual()); new JoystickButton(shooterStick, 4).whenPressed(new FlywheelStop()); new JoystickButton(shooterStick, 5).whileHeld(new AcquirerReverse()); new JoystickButton(shooterStick, 6).whileHeld(new ConveyReverseManual()); new JoystickButton(shooterStick, 7).whileHeld(new AcquirerAcquire()); new JoystickButton(shooterStick, 8).whileHeld(new ConveyAutomatic()); // see getDistanceButton() // Debug box switches new JoystickButton(debugBox, 1).whileHeld(new FlywheelRun(Flywheel.distances[Flywheel.FENDER_INDEX], Flywheel.speedsTopHoop)); new JoystickButton(debugBox, 2).whileHeld(new AcquirerAcquire()); new JoystickButton(debugBox, 3).whileHeld(new ConveyAutomatic()); // Debug box buttons new JoystickButton(debugBox, 5).whileHeld(new DrivetrainSetGear(false)); // low gear new JoystickButton(debugBox, 6).whileHeld(new DrivetrainSetGear(true)); // high gear new JoystickButton(debugBox, 9).whileHeld(new TusksExtend()); new JoystickButton(debugBox, 10).whileHeld(new TusksRetract()); } } // Copied from last year's DesDroid code. public double getRawAnalogVoltage() { try { return enhancedIO.getAnalogIn(DISTANCE_BUTTONS_CHANNEL); } catch (EnhancedIOException e) { return 0; } } public double getMaxVoltage() { try { return enhancedIO.getAnalogIn(MAX_ANALOG_CHANNEL); } catch (EnhancedIOException e) { return 2.2; } } /** * Determines which height button is pressed. All (7 logically because * side buttons are wired together) buttons are wired by means of * resistors to one analog input. Depending on the button that is pressed, a * different voltage is read by the analog input. Each resistor reduces the * voltage by about 1/7 the maximum voltage. * * @return An integer value representing the distance button that was pressed. * If a Joystick button is being used, that will returned. Otherwise, the * button will be returned from the voltage (if it returns 0, no button is pressed). */ public int getDistanceButton() { if (shooterStick.getRawButton(9)) { distanceButton = DISTANCE_BUTTON_STOP; } else if(shooterStick.getRawButton(10)) { distanceButton = DISTANCE_BUTTON_FENDER; } else if(shooterStick.getRawButton(11)) { distanceButton = DISTANCE_BUTTON_FAR; } int preValue = (int) ((getRawAnalogVoltage() / (getMaxVoltage() / 8)) + 0.5); // If no buttons are pressed, it does not update the distance. if(preValue != 0){ distanceButton = preValue; } return distanceButton; } /** * Takes the distance button that has been pressed, and finds the distance for * the shooter to use. * @return distance for the shooter. */ public double getDistanceFromDistanceButton(){ switch(distanceButton){ case DISTANCE_BUTTON_KEY: distanceInches = Flywheel.distances[Flywheel.KEY_INDEX]; break; case DISTANCE_BUTTON_FAR: distanceInches = Flywheel.distances[Flywheel.MAX_DIST]; break; case DISTANCE_BUTTON_FENDER_LENGTH: distanceInches = Flywheel.distances[Flywheel.FENDER_LONG_INDEX]; break; case DISTANCE_BUTTON_FENDER_WIDTH: distanceInches = Flywheel.distances[Flywheel.FENDER_WIDE_INDEX]; break; case DISTANCE_BUTTON_FENDER_SIDE: distanceInches = Flywheel.distances[Flywheel.FENDER_SIDE_INDEX]; break; case DISTANCE_BUTTON_FENDER: distanceInches = Flywheel.distances[Flywheel.FENDER_INDEX]; break; case DISTANCE_BUTTON_STOP: distanceInches = 0; break; default: break; } return distanceInches; } // Copied from last year's DesDroid code. public Joystick getLeftStick() { return leftStick; } public Joystick getRightStick() { return rightStick; } public Joystick getDebugBox() { return debugBox; } /** * Gets value of hoop height toggle switch. * @return true if high setting, false if middle */ public boolean getHoopHeightButton() { try { return !enhancedIO.getDigital(HOOP_HEIGHT_SWITCH_CHANNEL); } catch (EnhancedIOException ex) { return true; } } /** * Use a thumb wheel switch to set the autonomous mode setting. * @return Autonomous setting to run. */ public int getAutonSetting() { try { int switchNum = 0; int[] binaryValue = new int[3]; boolean[] dIO = {!enhancedIO.getDigital(BIT_1_CHANNEL), !enhancedIO.getDigital(BIT_2_CHANNEL), !enhancedIO.getDigital(BIT_3_CHANNEL)}; for (int i = 0; i < 3; i++) { if (dIO[i]) { binaryValue[i] = 1; } else { binaryValue[i] = 0; } } binaryValue[0] *= 4; // convert all binaryValues to decimal values binaryValue[1] *= 2; for (int i = 0; i < 3; i++) { // finish binary -> decimal conversion switchNum += binaryValue[i]; } return switchNum; } catch (EnhancedIOException e) { return -1; // Do nothing in case of failure } } public int getDebugBoxBinaryAutonSetting() { int switchNum = 0; int[] binaryValue = new int[4]; boolean[] dIO = {debugBox.getRawButton(1), debugBox.getRawButton(2), debugBox.getRawButton(3), debugBox.getRawButton(4)}; for (int i = 0; i < 4; i++) { if (dIO[i]) { binaryValue[i] = 1; } else { binaryValue[i] = 0; } } binaryValue[0] *= 8; // convert all binaryValues to decimal values binaryValue[1] *= 4; binaryValue[2] *= 2; for (int i = 0; i < 4; i++) { // finish binary -> decimal conversion switchNum += binaryValue[i]; } return switchNum; } public double getSpeedPot() { try { return getMaxVoltage() - enhancedIO.getAnalogIn(SPEED_TRIM_POT_CHANNEL); } catch (EnhancedIOException ex) { return 0.0; } } public double getSpeedTrim() { double trim = getSpeedPot(); // 0 to max voltage (the 0 might be a little negative) double halfMax = getMaxVoltage() / 2; double speed = 0; speed = (trim - halfMax) / halfMax; //deadband if(speed < -0.1) { speed = speed * 1.0/0.9; } else if (speed < 0.1) { speed = 0; } else { speed = speed * 1.0 / 0.9; } return Flywheel.MAX_TRIM_RPM * speed; } public double getDelayPot() { try { return getMaxVoltage() - enhancedIO.getAnalogIn(DELAY_POT_CHANNEL); } catch (EnhancedIOException ex) { return 0.0; } } public double getDelayTime() { double delay = getDelayPot(); if (delay > 0) { //Just in case the value from the pot is negative. We observed a -.2. return MAX_WAIT_TIME * delay / getMaxVoltage(); } else { return 0; } } /** * Turns on specified light on OI. * @param lightNum */ public void setLight(int lightNum) { turnOffLights(); try { enhancedIO.setDigitalOutput(lightNum, true); } catch (EnhancedIOException e) { } } /** * Turns all lights off. */ public void turnOffLights(){ try { enhancedIO.setDigitalOutput(DISTANCE_BUTTON_KEY_LIGHT_CHANNEL, false); enhancedIO.setDigitalOutput(DISTANCE_BUTTON_FAR_LIGHT_CHANNEL, false); enhancedIO.setDigitalOutput(DISTANCE_BUTTON_FENDER_WIDE_LIGHT_CHANNEL, false); enhancedIO.setDigitalOutput(DISTANCE_BUTTON_FENDER_NARROW_LIGHT_CHANNEL, false); enhancedIO.setDigitalOutput(DISTANCE_BUTTON_FENDER_SIDE_LIGHT_CHANNEL, false); enhancedIO.setDigitalOutput(DISTANCE_BUTTON_FENDER_LIGHT_CHANNEL, false); enhancedIO.setDigitalOutput(DISTANCE_BUTTON_STOP_LIGHT_CHANNEL, false); } catch (EnhancedIOException e) { } } /** * Turns all lights on. */ public void turnOnLights(){ try { enhancedIO.setDigitalOutput(DISTANCE_BUTTON_KEY_LIGHT_CHANNEL, true); enhancedIO.setDigitalOutput(DISTANCE_BUTTON_FAR_LIGHT_CHANNEL, true); enhancedIO.setDigitalOutput(DISTANCE_BUTTON_FENDER_WIDE_LIGHT_CHANNEL, true); enhancedIO.setDigitalOutput(DISTANCE_BUTTON_FENDER_NARROW_LIGHT_CHANNEL, true); enhancedIO.setDigitalOutput(DISTANCE_BUTTON_FENDER_SIDE_LIGHT_CHANNEL, true); enhancedIO.setDigitalOutput(DISTANCE_BUTTON_FENDER_LIGHT_CHANNEL, true); enhancedIO.setDigitalOutput(DISTANCE_BUTTON_STOP_LIGHT_CHANNEL, true); } catch (EnhancedIOException e) { } } /** * Meant to be called continuously to update the lights on the OI board. * Depending on which button has been pressed last (which distance is * currently set), that button will be lit. */ public void updateLights(){ switch(distanceButton){ case DISTANCE_BUTTON_KEY: setLight(DISTANCE_BUTTON_KEY_LIGHT_CHANNEL); break; case DISTANCE_BUTTON_FAR: setLight(DISTANCE_BUTTON_FAR_LIGHT_CHANNEL); break; case DISTANCE_BUTTON_FENDER_LENGTH: setLight(DISTANCE_BUTTON_FENDER_WIDE_LIGHT_CHANNEL); break; case DISTANCE_BUTTON_FENDER_WIDTH: setLight(DISTANCE_BUTTON_FENDER_NARROW_LIGHT_CHANNEL); break; case DISTANCE_BUTTON_FENDER_SIDE: setLight(DISTANCE_BUTTON_FENDER_SIDE_LIGHT_CHANNEL); break; case DISTANCE_BUTTON_FENDER: setLight(DISTANCE_BUTTON_FENDER_LIGHT_CHANNEL); break; case DISTANCE_BUTTON_STOP: setLight(DISTANCE_BUTTON_STOP_LIGHT_CHANNEL); break; default: turnOffLights(); break; } } // For debugging purposes. public boolean getDigitalValue(int channel) { boolean b = false; try{ b = !enhancedIO.getDigital(channel); } catch (EnhancedIOException e) { } return b; } // For debugging purposes. public double getAnalogValue(int channel) { double b = 0; try{ b = enhancedIO.getAnalogOut(channel); } catch (EnhancedIOException e) { } return b; } public void resetBox(){ turnOffLights(); distanceButton = DISTANCE_BUTTON_STOP; } }
/* * The main area for game logic. */ package engine; import celestial.Ship.Ship; import com.jme3.asset.AssetManager; import com.jme3.bullet.BulletAppState; import com.jme3.input.InputManager; import com.jme3.input.KeyInput; import com.jme3.input.RawInputListener; import com.jme3.input.controls.ActionListener; import com.jme3.input.controls.KeyTrigger; import com.jme3.input.controls.MouseButtonTrigger; import com.jme3.input.event.JoyAxisEvent; import com.jme3.input.event.JoyButtonEvent; import com.jme3.input.event.KeyInputEvent; import com.jme3.input.event.MouseButtonEvent; import com.jme3.input.event.MouseMotionEvent; import com.jme3.input.event.TouchEvent; import com.jme3.math.Vector2f; import com.jme3.math.Vector3f; import com.jme3.renderer.RenderManager; import com.jme3.scene.Node; import com.jme3.system.AppSettings; import entity.Entity; import java.io.FileInputStream; import java.io.ObjectInputStream; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import jmeplanet.PlanetAppState; import lib.astral.AstralIO; import lib.astral.AstralIO.Everything; import lib.astral.Parser; import lib.astral.Parser.Term; import universe.SolarSystem; import universe.Universe; /** * * @author Nathan Wiehoff */ public class Core { public enum GameState { PAUSED, IN_SPACE, } private GameState state = GameState.PAUSED; //game objects Universe universe; //nodes Node rootNode; Node guiNode; //hud HUD hud; //engine resources BulletAppState bulletAppState; PlanetAppState planetAppState; AppSettings settings; AssetManager assets; InputManager input; public Core(Node rootNode, Node guiNode, BulletAppState bulletAppState, AssetManager assets, PlanetAppState planetAppState, InputManager input, AppSettings settings) { this.rootNode = rootNode; this.guiNode = guiNode; this.bulletAppState = bulletAppState; this.assets = assets; this.planetAppState = planetAppState; this.input = input; this.settings = settings; //initialize init(); } private void init() { initKeys(); initMouse(); newGame("Default"); //do last initPhysicsListeners(); initHud(); } private void initHud() { hud = new HUD(guiNode, universe, settings.getWidth(), settings.getHeight(), assets); hud.add(); } private void initPhysicsListeners() { CollisionListener listener = new CollisionListener(); bulletAppState.getPhysicsSpace().addCollisionListener(listener); } private void newGame(String name) { //get the game from the universe Parser parse = new Parser("UNIVERSE.txt"); ArrayList<Term> games = parse.getTermsOfType("NewGame"); //find the one we want Term game = null; for (int a = 0; a < games.size(); a++) { if (games.get(a).getValue("name").equals(name)) { game = games.get(a); } } //generate the world universe = new Universe(assets); //determine start system String sysName = game.getValue("system"); SolarSystem start = universe.getSystemWithName(sysName); //determine start ship Parser ships = new Parser("SHIP.txt"); String shipName = game.getValue("ship"); Ship ship = null; ArrayList<Term> types = ships.getTermsOfType("Ship"); for (int a = 0; a < types.size(); a++) { if (types.get(a).getValue("type").equals(shipName)) { ship = new Ship(universe, types.get(a)); break; } } //put ship in start location float x = Float.parseFloat(game.getValue("x")); float y = Float.parseFloat(game.getValue("y")); float z = Float.parseFloat(game.getValue("z")); ship.setLocation(new Vector3f(x, y, z)); ship.setCurrentSystem(start); start.putEntityInSystem(ship); //setup start system addSystem(start); //center planetappstate on player ship planetAppState.setCameraShip(ship); //setup player shortcut universe.setPlayerShip(ship); //start game state = GameState.IN_SPACE; //TODO: init code } private void initMouse() { //mouse buttons input.addMapping("MOUSE_LClick", new MouseButtonTrigger(0)); input.addMapping("MOUSE_RClick", new MouseButtonTrigger(1)); input.addMapping("MOUSE_CClick", new MouseButtonTrigger(2)); //store input.addListener(actionListener, new String[]{"MOUSE_LClick", "MOUSE_RClick", "MOUSE_CClick"}); } private void initKeys() { //Number keys input.addMapping("KEY_0", new KeyTrigger(KeyInput.KEY_0)); input.addMapping("KEY_1", new KeyTrigger(KeyInput.KEY_1)); input.addMapping("KEY_2", new KeyTrigger(KeyInput.KEY_2)); input.addMapping("KEY_3", new KeyTrigger(KeyInput.KEY_3)); input.addMapping("KEY_4", new KeyTrigger(KeyInput.KEY_4)); input.addMapping("KEY_5", new KeyTrigger(KeyInput.KEY_5)); input.addMapping("KEY_6", new KeyTrigger(KeyInput.KEY_6)); input.addMapping("KEY_7", new KeyTrigger(KeyInput.KEY_7)); input.addMapping("KEY_8", new KeyTrigger(KeyInput.KEY_8)); input.addMapping("KEY_9", new KeyTrigger(KeyInput.KEY_9)); //Letter keys except WASD and EQ input.addMapping("KEY_B", new KeyTrigger(KeyInput.KEY_B)); input.addMapping("KEY_C", new KeyTrigger(KeyInput.KEY_C)); input.addMapping("KEY_F", new KeyTrigger(KeyInput.KEY_F)); input.addMapping("KEY_G", new KeyTrigger(KeyInput.KEY_G)); input.addMapping("KEY_H", new KeyTrigger(KeyInput.KEY_H)); input.addMapping("KEY_I", new KeyTrigger(KeyInput.KEY_I)); input.addMapping("KEY_J", new KeyTrigger(KeyInput.KEY_J)); input.addMapping("KEY_K", new KeyTrigger(KeyInput.KEY_K)); input.addMapping("KEY_L", new KeyTrigger(KeyInput.KEY_L)); input.addMapping("KEY_M", new KeyTrigger(KeyInput.KEY_M)); input.addMapping("KEY_N", new KeyTrigger(KeyInput.KEY_N)); input.addMapping("KEY_O", new KeyTrigger(KeyInput.KEY_O)); input.addMapping("KEY_P", new KeyTrigger(KeyInput.KEY_P)); input.addMapping("KEY_R", new KeyTrigger(KeyInput.KEY_R)); input.addMapping("KEY_T", new KeyTrigger(KeyInput.KEY_T)); input.addMapping("KEY_U", new KeyTrigger(KeyInput.KEY_U)); input.addMapping("KEY_V", new KeyTrigger(KeyInput.KEY_V)); input.addMapping("KEY_X", new KeyTrigger(KeyInput.KEY_X)); input.addMapping("KEY_Y", new KeyTrigger(KeyInput.KEY_Y)); input.addMapping("KEY_Z", new KeyTrigger(KeyInput.KEY_Z)); //space bar input.addMapping("KEY_SPACE", new KeyTrigger(KeyInput.KEY_SPACE)); //return and backspace input.addMapping("KEY_RETURN", new KeyTrigger(KeyInput.KEY_RETURN)); input.addMapping("KEY_BACKSPACE", new KeyTrigger(KeyInput.KEY_BACK)); //WASD keys input.addMapping("KEY_W", new KeyTrigger(KeyInput.KEY_W)); input.addMapping("KEY_A", new KeyTrigger(KeyInput.KEY_A)); input.addMapping("KEY_S", new KeyTrigger(KeyInput.KEY_S)); input.addMapping("KEY_D", new KeyTrigger(KeyInput.KEY_D)); //QE keys for rolling input.addMapping("KEY_Q", new KeyTrigger(KeyInput.KEY_Q)); input.addMapping("KEY_E", new KeyTrigger(KeyInput.KEY_E)); //arrow keys input.addMapping("KEY_UP", new KeyTrigger(KeyInput.KEY_UP)); input.addMapping("KEY_DOWN", new KeyTrigger(KeyInput.KEY_DOWN)); //function keys dedicated to engine control input.addMapping("Normal", new KeyTrigger(KeyInput.KEY_F1)); input.addMapping("Cruise", new KeyTrigger(KeyInput.KEY_F2)); input.addMapping("Newton", new KeyTrigger(KeyInput.KEY_F3)); //quick load and quick save dedicated keys input.addMapping("QuickSave", new KeyTrigger(KeyInput.KEY_INSERT)); input.addMapping("QuickLoad", new KeyTrigger(KeyInput.KEY_PAUSE)); //end key input.addMapping("KEY_END", new KeyTrigger(KeyInput.KEY_END)); //page keys input.addMapping("KEY_PGUP", new KeyTrigger(KeyInput.KEY_PGUP)); input.addMapping("KEY_PGDN", new KeyTrigger(KeyInput.KEY_PGDN)); //add input.addListener(actionListener, new String[]{ "KEY_0", "KEY_1", "KEY_2", "KEY_3", "KEY_4", "KEY_5", "KEY_6", "KEY_7", "KEY_8", "KEY_9", "KEY_B", "KEY_C", "KEY_F", "KEY_G", "KEY_H", "KEY_I", "KEY_J", "KEY_K", "KEY_L", "KEY_M", "KEY_N", "KEY_O", "KEY_P", "KEY_R", "KEY_T", "KEY_U", "KEY_V", "KEY_X", "KEY_Y", "KEY_Z", "KEY_W", "KEY_A", "KEY_S", "KEY_D", "KEY_SPACE", "KEY_RETURN", "KEY_Q", "KEY_E", "KEY_UP", "KEY_DOWN", "KEY_BACKSPACE", "Normal", "Cruise", "Newton", "QuickSave", "QuickLoad", "KEY_END", "KEY_PGUP", "KEY_PGDN"}); } private ActionListener actionListener = new ActionListener() { public void onAction(String name, boolean keyPressed, float tpf) { Vector2f origin = input.getCursorPosition(); String[] split = name.split("_"); if (split[0].matches("KEY")) { if (!hud.handleKeyAction(state, name, keyPressed)) { //handle nav actions if (name.matches("KEY_Q")) { if (keyPressed) { universe.getPlayerShip().setRoll(1); } else { universe.getPlayerShip().setRoll(0); } } if (name.matches("KEY_E")) { if (keyPressed) { universe.getPlayerShip().setRoll(-1); } else { universe.getPlayerShip().setRoll(0); } } if (name.matches("KEY_W")) { if (keyPressed) { universe.getPlayerShip().setThrottle(1); } else { universe.getPlayerShip().setThrottle(0); } } if (name.matches("KEY_S")) { if (keyPressed) { if (keyPressed) { universe.getPlayerShip().setThrottle(-1); } else { universe.getPlayerShip().setThrottle(0); } } } if (name.matches("KEY_A")) { if (keyPressed) { universe.getPlayerShip().setYaw(1); } else { universe.getPlayerShip().setYaw(0); } } if (name.matches("KEY_D")) { if (keyPressed) { universe.getPlayerShip().setYaw(-1); } else { universe.getPlayerShip().setYaw(0); } } if (name.matches("KEY_UP")) { if (keyPressed) { universe.getPlayerShip().setPitch(-1); } else { universe.getPlayerShip().setPitch(0); } } if (name.matches("KEY_DOWN")) { if (keyPressed) { universe.getPlayerShip().setPitch(1); } else { universe.getPlayerShip().setPitch(0); } } } } else if (split[0].matches("MOUSE")) { hud.handleMouseAction(state, name, keyPressed, new Vector3f(origin.x, origin.y, 0)); } else { /* * These events are handled here because they are for the * engine. */ //engine mode selection if (name.matches("Normal")) { universe.getPlayerShip().setEngine(Ship.EngineMode.NORMAL); } else if (name.matches("Cruise")) { universe.getPlayerShip().setEngine(Ship.EngineMode.CRUISE); } else if (name.matches("Newton")) { universe.getPlayerShip().setEngine(Ship.EngineMode.NEWTON); } //quickload and quicksave if (name.matches("QuickSave")) { save("Quick"); } else if (name.matches("QuickLoad")) { load("Quick"); } } } }; /*protected class JoystickEventListener implements RawInputListener { public void onJoyAxisEvent(JoyAxisEvent evt) { if (state == GameState.IN_SPACE) { if (evt.getAxis().getAxisId() == 0) { universe.getPlayer().getActiveShip().setYaw(-evt.getValue()); } else if (evt.getAxis().getAxisId() == 1) { universe.getPlayer().getActiveShip().setPitch(evt.getValue()); } else if (evt.getAxis().getAxisId() == 2) { universe.getPlayer().getActiveShip().setRoll(-evt.getValue()); } else if (evt.getAxis().getAxisId() == 3) { universe.getPlayer().getActiveShip().setThrottle(-evt.getValue()); } } } public void onJoyButtonEvent(JoyButtonEvent evt) { } public void beginInput() { } public void endInput() { } public void onMouseMotionEvent(MouseMotionEvent evt) { } public void onMouseButtonEvent(MouseButtonEvent evt) { } public void onKeyEvent(KeyInputEvent evt) { } public void onTouchEvent(TouchEvent evt) { } }*/ /* * Facilities for adding and removing game entities seamlessly FROM THE * SCENE, NOT FROM THE UNIVERSE */ public final void addSystem(SolarSystem system) { addEntity(system); } public final void removeSystem(SolarSystem system) { removeEntity(system); } public final void addEntity(Entity entity) { entity.construct(assets); entity.attach(rootNode, bulletAppState, planetAppState); } public final void removeEntity(Entity entity) { entity.detach(rootNode, bulletAppState, planetAppState); entity.deconstruct(); } /* * Moves an entity between solar systems. */ public final void moveEntity(Entity entity, SolarSystem in, SolarSystem out) { in.pullEntityFromSystem(entity); out.putEntityInSystem(entity); } /* * Taking over some important jobs from the Main class. */ public void periodicUpdate(float tpf) { /* * In-game updating */ if (state == GameState.IN_SPACE) { //update world for (int a = 0; a < universe.getSystems().size(); a++) { universe.getSystems().get(a).periodicUpdate(tpf); } //update HUD hud.periodicUpdate(tpf); } } public void render(RenderManager rm) { //render hud hud.render(assets); } /* * Loading and saving */ public void save(String gameName) { try { //save new AstralIO().saveGame(universe, gameName); } catch (Exception ex) { Logger.getLogger(Core.class.getName()).log(Level.SEVERE, null, ex); } } public void load(String gameName) { try { //unload universe if (universe != null) { removeSystem(universe.getPlayerShip().getCurrentSystem()); universe.setPlayerShip(null); universe = null; } //get everything Everything everything; FileInputStream fis = new FileInputStream(gameName + ".hab"); ObjectInputStream ois = new ObjectInputStream(fis); everything = (Everything) ois.readObject(); //unpack universe universe = everything.getUniverse(); //enter the player's system addSystem(universe.getPlayerShip().getCurrentSystem()); //restore camera planetAppState.freeCamera(); planetAppState.setCameraShip(universe.getPlayerShip()); //restore HUD if (hud != null) { hud.setUniverse(universe); } state = GameState.IN_SPACE; } catch (Exception e) { e.printStackTrace(); } } }
package mtr.data; import io.netty.buffer.Unpooled; import mtr.Registry; import mtr.TrigCache; import mtr.block.*; import mtr.entity.EntitySeat; import mtr.mappings.Utilities; import mtr.path.PathData; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.server.level.ServerPlayer; import net.minecraft.util.Mth; import net.minecraft.world.Container; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.HopperBlockEntity; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.AABB; import net.minecraft.world.phys.Vec3; import org.msgpack.value.Value; import java.util.*; import java.util.function.Consumer; public class TrainServer extends Train { private boolean canDeploy; private List<Map<UUID, Long>> trainPositions; private Map<Player, Set<TrainServer>> trainsInPlayerRange = new HashMap<>(); private long routeId; private int updateRailProgressCounter; private final List<Siding.TimeSegment> timeSegments; private static final int TRAIN_UPDATE_DISTANCE = 128; private static final float INNER_PADDING = 0.5F; private static final int BOX_PADDING = 3; private static final int TICKS_TO_SEND_RAIL_PROGRESS = 40; public TrainServer(long id, long sidingId, float railLength, String trainId, TrainType baseTrainType, int trainCars, List<PathData> path, List<Float> distances, float accelerationConstant, List<Siding.TimeSegment> timeSegments) { super(id, sidingId, railLength, trainId, baseTrainType, trainCars, path, distances, accelerationConstant); this.timeSegments = timeSegments; } public TrainServer(long sidingId, float railLength, List<PathData> path, List<Float> distances, List<Siding.TimeSegment> timeSegments, Map<String, Value> map) { super(sidingId, railLength, path, distances, map); this.timeSegments = timeSegments; } @Deprecated public TrainServer(long sidingId, float railLength, List<PathData> path, List<Float> distances, List<Siding.TimeSegment> timeSegments, CompoundTag compoundTag) { super(sidingId, railLength, path, distances, compoundTag); this.timeSegments = timeSegments; } @Override protected void startUp(Level world, int trainCars, int trainSpacing, boolean isOppositeRail) { canDeploy = false; isOnRoute = true; stopCounter = 0; speed = accelerationConstant; if (isOppositeRail) { railProgress += trainCars * trainSpacing; reversed = !reversed; } nextStoppingIndex = getNextStoppingIndex(); } @Override protected void simulateCar( Level world, int ridingCar, float ticksElapsed, double carX, double carY, double carZ, float carYaw, float carPitch, double prevCarX, double prevCarY, double prevCarZ, float prevCarYaw, float prevCarPitch, boolean doorLeftOpen, boolean doorRightOpen, double realSpacing, float doorValueRaw, float oldSpeed, float oldDoorValue, float oldRailProgress ) { final RailwayData railwayData = RailwayData.getInstance(world); if (railwayData == null) { return; } final float halfSpacing = baseTrainType.getSpacing() / 2F; final float halfWidth = baseTrainType.width / 2F; if (doorLeftOpen || doorRightOpen) { final float margin = halfSpacing + BOX_PADDING; world.getEntitiesOfClass(Player.class, new AABB(carX + margin, carY + margin, carZ + margin, carX - margin, carY - margin, carZ - margin), player -> !player.isSpectator() && !ridingEntities.contains(player.getUUID())).forEach(player -> { final Vec3 positionRotated = player.position().subtract(carX, carY, carZ).yRot(-carYaw).xRot(-carPitch); if (Math.abs(positionRotated.x) < halfWidth + INNER_PADDING && Math.abs(positionRotated.y) < 2.5 && Math.abs(positionRotated.z) <= halfSpacing) { final EntitySeat seat = railwayData.getSeatFromPlayer(player); if (seat != null) { ridingEntities.add(player.getUUID()); final float percentageX = (float) (positionRotated.x / baseTrainType.width + 0.5); final float percentageZ = (float) (realSpacing == 0 ? 0 : positionRotated.z / realSpacing + 0.5) + ridingCar; final FriendlyByteBuf packet = new FriendlyByteBuf(Unpooled.buffer()); packet.writeLong(id); packet.writeFloat(percentageX); packet.writeFloat(percentageZ); Registry.sendToPlayer((ServerPlayer) player, PACKET_UPDATE_TRAIN_PASSENGERS, packet); } } }); } final Set<UUID> ridersToRemove = new HashSet<>(); ridingEntities.forEach(uuid -> { final Player player = world.getPlayerByUUID(uuid); if (player != null) { final boolean remove; if (player.isSpectator() || player.isShiftKeyDown()) { remove = true; } else if (doorLeftOpen || doorRightOpen) { final Vec3 positionRotated = player.position().subtract(carX, carY, carZ).yRot(-carYaw).xRot(-carPitch); remove = Math.abs(positionRotated.z) <= halfSpacing && (Math.abs(positionRotated.x) > halfWidth + INNER_PADDING || Math.abs(positionRotated.y) > 2); } else { remove = false; } if (remove) { ridersToRemove.add(uuid); ((ServerPlayer) player).gameMode.getGameModeForPlayer().updatePlayerAbilities(Utilities.getAbilities(player)); } else { Utilities.getAbilities(player).mayfly = true; } } }); if (!ridersToRemove.isEmpty()) { ridersToRemove.forEach(ridingEntities::remove); } } @Override protected boolean handlePositions(Level world, Vec3[] positions, float ticksElapsed, float doorValueRaw, float oldDoorValue, float oldRailProgress) { final AABB trainAABB = new AABB(positions[0], positions[positions.length - 1]).inflate(TRAIN_UPDATE_DISTANCE); final boolean[] playerNearby = {false}; world.players().forEach(player -> { if (trainAABB.contains(player.position())) { if (!trainsInPlayerRange.containsKey(player)) { trainsInPlayerRange.put(player, new HashSet<>()); } trainsInPlayerRange.get(player).add(this); playerNearby[0] = true; } }); final BlockPos frontPos = new BlockPos(positions[reversed ? positions.length - 1 : 0]); if (world.hasChunk(frontPos.getX() / 16, frontPos.getZ() / 16)) { checkBlock(frontPos, checkPos -> { final BlockState state = world.getBlockState(checkPos); final Block block = state.getBlock(); if (block instanceof BlockTrainRedstoneSensor && BlockTrainSensorBase.matchesFilter(world, checkPos, routeId, speed)) { ((BlockTrainRedstoneSensor) block).power(world, state, checkPos); } if ((block instanceof BlockTrainCargoLoader || block instanceof BlockTrainCargoUnloader) && BlockTrainSensorBase.matchesFilter(world, checkPos, routeId, speed)) { for (final Direction direction : Direction.values()) { final Container nearbyInventory = HopperBlockEntity.getContainerAt(world, checkPos.relative(direction)); if (nearbyInventory != null) { if (block instanceof BlockTrainCargoLoader) { transferItems(nearbyInventory, inventory); } else { transferItems(inventory, nearbyInventory); } } } } }); } if (!ridingEntities.isEmpty()) { checkBlock(frontPos, checkPos -> { if (world.getBlockState(checkPos).getBlock() instanceof BlockTrainAnnouncer) { final BlockEntity entity = world.getBlockEntity(checkPos); if (entity instanceof BlockTrainAnnouncer.TileEntityTrainAnnouncer && ((BlockTrainAnnouncer.TileEntityTrainAnnouncer) entity).matchesFilter(routeId, speed)) { ridingEntities.forEach(uuid -> ((BlockTrainAnnouncer.TileEntityTrainAnnouncer) entity).announce(world.getPlayerByUUID(uuid))); } } }); } return playerNearby[0]; } @Override protected boolean canDeploy(Depot depot) { if (path.size() > 1 && depot != null) { depot.requestDeploy(sidingId, this); } return canDeploy; } @Override protected boolean isRailBlocked(int checkIndex) { if (trainPositions != null && checkIndex < path.size()) { final UUID railProduct = path.get(checkIndex).getRailProduct(); for (final Map<UUID, Long> trainPositionsMap : trainPositions) { if (trainPositionsMap.containsKey(railProduct) && trainPositionsMap.get(railProduct) != id) { return true; } } } return false; } @Override protected boolean skipScanBlocks(Level world, double trainX, double trainY, double trainZ) { return world.getNearestPlayer(trainX, trainY, trainZ, MAX_CHECK_DISTANCE, entity -> true) == null; } @Override protected boolean openDoors(Level world, Block block, BlockPos checkPos, float doorValue, int dwellTicks) { if (block instanceof BlockPSDAPGDoorBase) { for (int i = -1; i <= 1; i++) { final BlockPos doorPos = checkPos.above(i); final BlockState state = world.getBlockState(doorPos); final Block doorBlock = state.getBlock(); if (doorBlock instanceof BlockPSDAPGDoorBase) { final int doorStateValue = (int) Mth.clamp(doorValue * DOOR_MOVE_TIME, 0, BlockPSDAPGDoorBase.MAX_OPEN_VALUE); world.setBlockAndUpdate(doorPos, state.setValue(BlockPSDAPGDoorBase.OPEN, doorStateValue)); if (doorStateValue > 0 && !world.getBlockTicks().hasScheduledTick(doorPos, doorBlock)) { Utilities.scheduleBlockTick(world, doorPos, doorBlock, dwellTicks); } } } } return false; } @Override protected double asin(double value) { return TrigCache.asin(value); } public boolean simulateTrain(Level world, float ticksElapsed, Depot depot, DataCache dataCache, List<Map<UUID, Long>> trainPositions, Map<Player, Set<TrainServer>> trainsInPlayerRange, Map<Long, List<ScheduleEntry>> schedulesForPlatform, boolean isUnlimited) { this.trainPositions = trainPositions; this.trainsInPlayerRange = trainsInPlayerRange; final int oldStoppingIndex = nextStoppingIndex; final int oldPassengerCount = ridingEntities.size(); simulateTrain(world, ticksElapsed, depot); final long currentMillis = System.currentTimeMillis() - (long) (stopCounter * Depot.MILLIS_PER_TICK) + (isOnRoute ? 0 : (long) Math.max(0, depot.getNextDepartureTicks(Depot.getHour(world))) * Depot.MILLIS_PER_TICK); float currentTime = -1; int startingIndex = 0; for (final Siding.TimeSegment timeSegment : timeSegments) { if (RailwayData.isBetween(railProgress, timeSegment.startRailProgress, timeSegment.endRailProgress)) { currentTime = timeSegment.getTime(railProgress); break; } startingIndex++; } if (currentTime >= 0) { float offsetTime = 0; routeId = 0; for (int i = startingIndex; i < timeSegments.size() + (isUnlimited ? 0 : startingIndex); i++) { final Siding.TimeSegment timeSegment = timeSegments.get(i % timeSegments.size()); if (timeSegment.savedRailBaseId != 0) { if (timeSegment.routeId == 0) { RailwayData.useRoutesAndStationsFromIndex(path.get(getIndex(timeSegment.endRailProgress, true)).stopIndex - 1, depot.routeIds, dataCache, (thisRoute, nextRoute, thisStation, nextStation, lastStation) -> { timeSegment.lastStationId = lastStation == null ? 0 : lastStation.id; timeSegment.routeId = thisRoute == null ? 0 : thisRoute.id; timeSegment.isTerminating = nextStation == null; }); } final String destinationString; final String routeNumber; final Station lastStation = dataCache.stationIdMap.get(timeSegment.lastStationId); if (lastStation != null) { final Route thisRoute = dataCache.routeIdMap.get(timeSegment.routeId); routeNumber = thisRoute != null && thisRoute.isLightRailRoute ? thisRoute.lightRailRouteNumber : ""; destinationString = lastStation.name; } else { routeNumber = ""; destinationString = ""; } final long platformId = timeSegment.savedRailBaseId; if (!schedulesForPlatform.containsKey(platformId)) { schedulesForPlatform.put(platformId, new ArrayList<>()); } final long arrivalMillis = currentMillis + (long) ((timeSegment.endTime + offsetTime - currentTime) * Depot.MILLIS_PER_TICK); schedulesForPlatform.get(platformId).add(new ScheduleEntry(arrivalMillis, trainCars, platformId, timeSegment.routeId, routeNumber, destinationString, timeSegment.isTerminating)); } if (routeId == 0) { routeId = timeSegment.routeId; } if (i == timeSegments.size() - 1) { offsetTime = timeSegment.endTime; } } } updateRailProgressCounter++; if (updateRailProgressCounter == TICKS_TO_SEND_RAIL_PROGRESS) { updateRailProgressCounter = 0; } return oldPassengerCount > ridingEntities.size() || oldStoppingIndex != nextStoppingIndex; } public void writeTrainPositions(List<Map<UUID, Long>> trainPositions, SignalBlocks signalBlocks) { if (!path.isEmpty()) { final int trainSpacing = baseTrainType.getSpacing(); final int headIndex = getIndex(0, trainSpacing, true); final int tailIndex = getIndex(trainCars, trainSpacing, false); for (int i = tailIndex; i <= headIndex; i++) { if (i > 0 && path.get(i).savedRailBaseId != sidingId) { signalBlocks.occupy(path.get(i).getRailProduct(), trainPositions, id); } } } } public void deployTrain() { canDeploy = true; } private int getNextStoppingIndex() { final int headIndex = getIndex(0, 0, false); for (int i = headIndex; i < path.size(); i++) { if (path.get(i).dwellTime > 0) { return i; } } return path.size() - 1; } private void checkBlock(BlockPos pos, Consumer<BlockPos> callback) { final int checkRadius = (int) Math.floor(speed); for (int x = -checkRadius; x <= checkRadius; x++) { for (int z = -checkRadius; z <= checkRadius; z++) { for (int y = 0; y <= 3; y++) { callback.accept(pos.offset(x, -y, z)); } } } } private static void transferItems(Container inventoryFrom, Container inventoryTo) { for (int i = 0; i < inventoryFrom.getContainerSize(); i++) { if (!inventoryFrom.getItem(i).isEmpty()) { final ItemStack insertItem = new ItemStack(inventoryFrom.getItem(i).getItem(), 1); final ItemStack remainingStack = HopperBlockEntity.addItem(null, inventoryTo, insertItem, null); if (remainingStack.isEmpty()) { inventoryFrom.removeItem(i, 1); return; } } } } }
package de.mrapp.android.adapter.list.sortable; import java.util.Comparator; /** * Defines the interface, an adapter, whose underlying data is managed as a * sortable list of arbitrary items, must implement. Such an adapter's purpose * is to provide the underlying data for visualization using a {@link ListView} * widget. * * @param <DataType> * The type of the adapter's underlying data * * @author Michael Rapp * * @since 1.0.0 */ public interface SortableListAdapter<DataType> { /** * Sorts the adapter's items in an ascending order. */ void sort(); /** * Sorts the adapter's items in a specific order. * * @param order * The order, which should be used to sort the items, as a value * of the enum {@link Order}. The order may either be * <code>ASCENDING</code> order <code>DESCENDING</code> */ void sort(Order order); /** * Sorts the adapter's items in an ascending order, by using a comparator. * * @param comparator * The comparator, which should be used to sort the items, as an * instance of the type {@link Comparator}. The comparator may * not be null */ void sort(Comparator<DataType> comparator); /** * Sorts the adapter's items in a specific order, by using a comparator. * * @param comparator * The comparator, which should be used to sort the items, as an * instance of the type {@link Comparator}. The comparator may * not be null * @param order * The order, which should be used to sort the items, as a value * of the enum {@link Order}. The order may either be * <code>ASCENDING</code> order <code>DESCENDING</code> */ void sort(Order order, Comparator<DataType> comparator); /** * Adds a new listener, which should be notified, when the adapter's * underlying data has been sorted. * * @param listener * The listener, which should be added, as an instance of the * class {@link ListSortingListener}. The listener may not be * null */ void addSortingListner(final ListSortingListener<DataType> listener); /** * Removes a specific listener, which should not be notified, when the * adapter's underlying data has been sorted, anymore. * * @param listener * The listener, which should be removed, as an instance of the * class {@link ListSortingListener}. The listener may not be * null */ void removeSortingListener(ListSortingListener<DataType> listener); }
package thinwire.render.web; import java.io.IOException; import java.io.Reader; import java.io.Writer; import java.net.SocketTimeoutException; import java.util.Date; import java.util.LinkedList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * @author Joshua J. Gertzen */ class EventProcessor extends Thread { private static final char EVENT_WEB_COMPONENT = '0'; private static final char EVENT_GET_EVENTS = '1'; private static final char EVENT_SYNC_CALL = '2'; private static final char EVENT_RUN_TIMER = '3'; private static final int FIVE_MINUTES = 1000 * 60 * 5; private static final Level LEVEL = Level.FINER; private static final Logger log = Logger.getLogger(EventProcessor.class.getName()); private static int nextId = 0; private EventProcessorPool pool; private List<WebComponentEvent> queue = new LinkedList<WebComponentEvent>(); private StringBuilder sbParseUserAction = new StringBuilder(1024); private char[] complexValueBuffer = new char[256]; private String syncCallResponse; private Writer response; private boolean waitToRespond; private int updateEventsSize; private boolean active; private int captureCount; private boolean threadCaptured; private long lastActivityTime; WebApplication app; EventProcessor(EventProcessorPool pool) { if (pool == null) throw new IllegalArgumentException("pool == null"); setName("ThinWire-EventProcessorThread-" + (nextId++) + "-" + this.hashCode()); this.pool = pool; } boolean isInUse() { return threadCaptured || active; } public void run() { if (log.isLoggable(LEVEL)) log.log(LEVEL, getName() + ": entering thread"); active = true; synchronized (queue) { try { while (true) { processUserActionEvent(); } } catch (InterruptedException e) { //allow for graceful exit pool.removeFromPool(this); //Not entirely necessary, but it makes me feel better ;-) queue.clear(); queue = null; sbParseUserAction = null; response = null; pool = null; syncCallResponse = null; complexValueBuffer = null; } } if (log.isLoggable(LEVEL)) log.log(LEVEL, getName() + ": exiting thread"); } void captureThread() { int currentCaptureCount = ++captureCount; if (log.isLoggable(LEVEL)) log.log(LEVEL, getName() + ": capture count:" + captureCount); threadCaptured = true; try { while (threadCaptured) { processUserActionEvent(); if (currentCaptureCount == captureCount) threadCaptured = true; } } catch (InterruptedException e) { //Must throw an actual exception so the stack unrolls throw new RuntimeException(e); } } //Must only be called by the main run loop or the capture method! private void processUserActionEvent() throws InterruptedException { lastActivityTime = System.currentTimeMillis(); if (queue.size() > 0) { WebComponentEvent event = queue.remove(0); if (log.isLoggable(LEVEL)) log.log(LEVEL, getName() + ": process user action event:" + event); if (app.userActionListener != null) app.notifyUserActionReceived(event); if (app.playBackOn && !app.playBackEventReceived) { app.playBackEventReceived = true; app.playBackStart = new Date().getTime(); } if (app.playBackOn) { //TODO figure out what makes sense here //synchronized (response) { //response.reset(); if (ApplicationEventListener.SHUTDOWN.equals(event.getName())) app.setPlayBackOn(false); } try { WebComponentListener wcl = app.getWebComponentListener((Integer) event.getSource()); if (wcl != null) wcl.componentChange(event); } catch (Exception e) { app.reportException(null, e); } } else { active = false; waitToRespond = false; queue.notify(); if (log.isLoggable(LEVEL)) log.log(LEVEL, getName() + ": Notified request handler thread so it returns if it is currently blocking"); if (threadCaptured) { if (log.isLoggable(LEVEL)) log.log(LEVEL, getName() + ": Waiting for this captured thread to receive new user action events"); queue.wait(); } else { if (log.isLoggable(LEVEL)) log.log(LEVEL, getName() + ": Waiting " + FIVE_MINUTES + " to be given new user action events, otherwise it will be shutdown"); queue.wait(FIVE_MINUTES); //Bring the thread down if it's been idle for five minutes. if (app == null && queue.size() == 0 && (System.currentTimeMillis() - lastActivityTime) >= FIVE_MINUTES) { if (log.isLoggable(LEVEL)) log.log(LEVEL, getName() + ": Triggering thread interrupt to shutdown"); interrupt(); } } active = true; } } void releaseThread() { threadCaptured = false; captureCount if (log.isLoggable(LEVEL)) log.log(LEVEL, getName() + ": release count:" + captureCount); } //This method is called by the servers request handler thread, not this thread. void handleRequest(WebComponentEvent ev, Writer w) throws IOException { synchronized (queue) { if (log.isLoggable(LEVEL)) log.log(LEVEL, getName() + ": queue user action event:" + ev); queue.add(ev); queue.notify(); writeUpdateEvents(w); } } //This method is called by the servers request handler thread, not this thread. void handleRequest(Reader r, Writer w) throws IOException { synchronized (queue) { StringBuilder sb = sbParseUserAction; try { do { char eventType = (char)r.read(); r.read(); //Remove ':' switch (eventType) { case EVENT_GET_EVENTS: break; case EVENT_WEB_COMPONENT: { readSimpleValue(sb, r); Integer source = Integer.valueOf(sb.toString()); readSimpleValue(sb, r); String name = sb.toString(); readComplexValue(sb, r); String value = sb.toString(); WebComponentListener wcl = app.getWebComponentListener(source); if (wcl != null) { WebComponentEvent ev = new WebComponentEvent(source, name, value); if (log.isLoggable(LEVEL)) log.log(LEVEL, getName() + ": queue user action event:" + ev); queue.add(ev); } break; } case EVENT_RUN_TIMER: { readSimpleValue(sb, r); String timerId = sb.toString(); WebComponentEvent ev = ApplicationEventListener.newRunTimerEvent(timerId); if (log.isLoggable(LEVEL)) log.log(LEVEL, getName() + ": queue run timer event:" + ev); queue.add(ev); break; } case EVENT_SYNC_CALL: { readComplexValue(sb, r); syncCallResponse = sb.toString(); if (log.isLoggable(LEVEL)) log.log(LEVEL, getName() + ": sync call response:" + syncCallResponse); break; } } } while (r.read() == ':'); } catch (SocketTimeoutException e) { log.log(Level.WARNING, "Invalid action event format received from client", e); } finally { sb.setLength(0); } queue.notify(); writeUpdateEvents(w); } } //Must only be called by one of the handleRequest methods! private void writeUpdateEvents(Writer w) throws IOException { if (w == null) return; try { response = w; waitToRespond = true; updateEventsSize = 0; while (waitToRespond) { if (log.isLoggable(LEVEL)) log.log(LEVEL, getName() + ": waiting for events to be processed"); queue.wait(); } if (log.isLoggable(LEVEL)) log.log(LEVEL, getName() + ": finishing up update events, active=" + active + ", updateEventsSize=" + updateEventsSize); if (active) { w.write(updateEventsSize == 0 ? "[{m:\"" : ",{m:\""); w.write("sendGetEvents\",a:[],s:1,n:tw_em}"); updateEventsSize += 36; } } catch (InterruptedException e) { //Only occurs if the request handler thread is interrupted, in which case we should //try and gracefully exit; } finally { if (updateEventsSize > 0) response.write(']'); response = null; updateEventsSize = 0; } } private void readSimpleValue(StringBuilder sb, Reader r) throws IOException { sb.setLength(0); int ch; while ((ch = r.read()) != ':') { if (ch == -1) throw new IllegalStateException("premature end of post event encountered[" + sb.toString() + "]"); sb.append((char)ch); } } private void readComplexValue(StringBuilder sb, Reader r) throws IOException { readSimpleValue(sb, r); int length = Integer.parseInt(sb.toString()); sb.setLength(0); if (length > 0) { int size; char[] buff = complexValueBuffer; int buffLen = buff.length; do { size = length > buffLen ? buffLen : length; size = r.read(buff, 0, size); if (size == -1) throw new IllegalStateException("premature end of complex value on action event encountered[" + sb.toString() + "], length=" + length); length -= size; sb.append(buff, 0, size); } while (length > 0); } } String postUpdateEvent(boolean sync, Object objectId, String name, Object[] args) { try { int size = 0; response.write(updateEventsSize == 0 ? "[{m:\"" : ",{m:\""); size += 5; response.write(name); response.write('\"'); size += name.length() + 1; if (objectId != null) { if (objectId instanceof Integer) { response.write(",i:"); String value = objectId.toString(); response.write(value); size += 3 + value.length(); } else { response.write(",n:"); String value = (String)objectId; response.write(value); size += 3 + value.length(); } } if (args != null && args.length > 0) { response.write(",a:["); size += 4; for (int i = 0, cnt = args.length - 1; i < cnt; i++) { String value = WebApplication.stringValueOf(args[i]); response.write(value); response.write(','); size += value.length() + 1; } String value = WebApplication.stringValueOf(args[args.length - 1]); response.write(value); response.write(']'); size += value.length() + 1; } else { response.write(",a:[]"); size += 5; } if (sync) { response.write(",s:1}"); size += 5; } else { response.write("}"); size += 1; } updateEventsSize += size; if (waitToRespond && (sync || updateEventsSize >= 16384)) flush(); } catch (IOException e) { throw new RuntimeException(e); } return sync ? syncCallResponse : null; } void flush() { waitToRespond = false; queue.notify(); try { while (!waitToRespond) { queue.wait(); } } catch (InterruptedException e) { //Must throw an exception so the stack unrolls properly. throw new RuntimeException(e); } } }
package dr.inference.model; import dr.util.NumberFormatter; import dr.xml.Reportable; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.concurrent.*; /** * A likelihood function which is simply the product of a set of likelihood functions. * * @author Alexei Drummond * @author Andrew Rambaut * @version $Id: CompoundLikelihood.java,v 1.19 2005/05/25 09:14:36 rambaut Exp $ */ public class CompoundLikelihood implements Likelihood, Reportable { public final static boolean UNROLL_COMPOUND = true; public final static boolean EVALUATION_TIMERS = true; public final long[] evaluationTimes; public final int[] evaluationCounts; public CompoundLikelihood(int threads, Collection<Likelihood> likelihoods) { int i = 0; for (Likelihood l : likelihoods) { addLikelihood(l, i, true); i++; } if (threads < 0 && this.likelihoods.size() > 1) { // asking for an automatic threadpool size and there is more than one likelihood to compute threadCount = this.likelihoods.size(); } else if (threads > 0) { threadCount = threads; } else { // no thread pool requested or only one likelihood threadCount = 0; } if (threadCount > 0) { pool = Executors.newFixedThreadPool(threadCount); // } else if (threads < 0) { // // create a cached thread pool which should create one thread per likelihood... // pool = Executors.newCachedThreadPool(); } else { pool = null; } if (EVALUATION_TIMERS) { evaluationTimes = new long[this.likelihoods.size()]; evaluationCounts = new int[this.likelihoods.size()]; } else { evaluationTimes = null; evaluationCounts = null; } } public CompoundLikelihood(Collection<Likelihood> likelihoods) { pool = null; threadCount = 0; int i = 0; for (Likelihood l : likelihoods) { addLikelihood(l, i, false); i++; } if (EVALUATION_TIMERS) { evaluationTimes = new long[this.likelihoods.size()]; evaluationCounts = new int[this.likelihoods.size()]; } else { evaluationTimes = null; evaluationCounts = null; } } protected void addLikelihood(Likelihood likelihood, int index, boolean addToPool) { // unroll any compound likelihoods if (UNROLL_COMPOUND && addToPool && likelihood instanceof CompoundLikelihood) { for (Likelihood l : ((CompoundLikelihood)likelihood).getLikelihoods()) { addLikelihood(l, index, addToPool); } } else { if (!likelihoods.contains(likelihood)) { likelihoods.add(likelihood); if (likelihood.getModel() != null) { compoundModel.addModel(likelihood.getModel()); } if (likelihood.evaluateEarly()) { earlyLikelihoods.add(likelihood); } else { // late likelihood list is used to evaluate them if the thread pool is not being used... lateLikelihoods.add(likelihood); if (addToPool) { likelihoodCallers.add(new LikelihoodCaller(likelihood, index)); } } } } } public int getLikelihoodCount() { return likelihoods.size(); } public final Likelihood getLikelihood(int i) { return likelihoods.get(i); } public List<Likelihood> getLikelihoods() { return likelihoods; } public List<Callable<Double>> getLikelihoodCallers() { return likelihoodCallers; } // Likelihood IMPLEMENTATION public Model getModel() { return compoundModel; } // // todo: remove in release // static int DEBUG = 0; public double getLogLikelihood() { double logLikelihood = evaluateLikelihoods(earlyLikelihoods); if( logLikelihood == Double.NEGATIVE_INFINITY ) { return Double.NEGATIVE_INFINITY; } if (pool == null) { // Single threaded logLikelihood += evaluateLikelihoods(lateLikelihoods); } else { try { List<Future<Double>> results = pool.invokeAll(likelihoodCallers); for (Future<Double> result : results) { double logL = result.get(); logLikelihood += logL; } } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } // if( DEBUG > 0 ) { // int t = DEBUG; DEBUG = 0; // System.err.println(getId() + ": " + getDiagnosis(0) + " = " + logLikelihood); // DEBUG = t; return logLikelihood; } private double evaluateLikelihoods(ArrayList<Likelihood> likelihoods) { double logLikelihood = 0.0; int i = 0; for (Likelihood likelihood : likelihoods) { if (EVALUATION_TIMERS) { // this code is only compiled if EVALUATION_TIMERS is true long time = System.nanoTime(); double l = likelihood.getLogLikelihood(); evaluationTimes[i] += System.nanoTime() - time; evaluationCounts[i] ++; if( l == Double.NEGATIVE_INFINITY ) return Double.NEGATIVE_INFINITY; logLikelihood += l; i++; } else { final double l = likelihood.getLogLikelihood(); // if the likelihood is zero then short cut the rest of the likelihoods // This means that expensive likelihoods such as TreeLikelihoods should // be put after cheap ones such as BooleanLikelihoods if( l == Double.NEGATIVE_INFINITY ) return Double.NEGATIVE_INFINITY; logLikelihood += l; } } return logLikelihood; } public void makeDirty() { for( Likelihood likelihood : likelihoods ) { likelihood.makeDirty(); } } public boolean evaluateEarly() { return false; } public String getDiagnosis() { return getDiagnosis(0); } public String getDiagnosis(int indent) { String message = ""; boolean first = true; final NumberFormatter nf = new NumberFormatter(6); for( Likelihood lik : likelihoods ) { if( !first ) { message += ", "; } else { first = false; } if (indent >= 0) { message += "\n"; for (int i = 0; i < indent; i++) { message += " "; } } message += lik.prettyName() + "="; if( lik instanceof CompoundLikelihood ) { final String d = ((CompoundLikelihood) lik).getDiagnosis(indent < 0 ? -1 : indent + 2); if( d != null && d.length() > 0 ) { message += "(" + d; if (indent >= 0) { message += "\n"; for (int i = 0; i < indent; i++) { message += " "; } } message += ")"; } } else { final double logLikelihood = lik.getLogLikelihood(); if( logLikelihood == Double.NEGATIVE_INFINITY ) { message += "-Inf"; } else if( Double.isNaN(logLikelihood) ) { message += "NaN"; } else if( logLikelihood == Double.POSITIVE_INFINITY ) { message += "+Inf"; } else { message += nf.formatDecimal(logLikelihood, 4); } } } message += "\n"; for (int i = 0; i < indent; i++) { message += " "; } message += "Total = " + this.getLogLikelihood(); return message; } public String toString() { return getId(); // really bad for debugging //return Double.toString(getLogLikelihood()); } public String prettyName() { return Abstract.getPrettyName(this); } public boolean isUsed() { return used; } public void setUsed() { used = true; for (Likelihood l : likelihoods) { l.setUsed(); } } public int getThreadCount() { return threadCount; } // Loggable IMPLEMENTATION /** * @return the log columns. */ public dr.inference.loggers.LogColumn[] getColumns() { return new dr.inference.loggers.LogColumn[]{ new LikelihoodColumn(getId() == null ? "likelihood" : getId()) }; } private class LikelihoodColumn extends dr.inference.loggers.NumberColumn { public LikelihoodColumn(String label) { super(label); } public double getDoubleValue() { return getLogLikelihood(); } } // Reportable IMPLEMENTATION public String getReport() { return getReport(0); } public String getReport(int indent) { if (EVALUATION_TIMERS) { String message = ""; boolean first = true; final NumberFormatter nf = new NumberFormatter(6); int index = 0; for( Likelihood lik : likelihoods ) { if( !first ) { message += ", "; } else { first = false; } if (indent >= 0) { message += "\n"; for (int i = 0; i < indent; i++) { message += " "; } } message += lik.prettyName() + "="; if( lik instanceof CompoundLikelihood ) { final String d = ((CompoundLikelihood) lik).getReport(indent < 0 ? -1 : indent + 2); if( d != null && d.length() > 0 ) { message += "(" + d; if (indent >= 0) { message += "\n"; for (int i = 0; i < indent; i++) { message += " "; } } message += ")"; } } else { double secs = (double)evaluationTimes[index] / 1.0E9; message += evaluationCounts[index] + " evaluations in " + nf.format(secs) + " secs (" + nf.format(secs / evaluationCounts[index]) + " secs/eval)"; } index++; } return message; } else { return "No evaluation timer report available"; } } // Identifiable IMPLEMENTATION private String id = null; public void setId(String id) { this.id = id; } public String getId() { return id; } private boolean used = false; private final int threadCount; private final ExecutorService pool; private final ArrayList<Likelihood> likelihoods = new ArrayList<Likelihood>(); private final CompoundModel compoundModel = new CompoundModel("compoundModel"); private final ArrayList<Likelihood> earlyLikelihoods = new ArrayList<Likelihood>(); private final ArrayList<Likelihood> lateLikelihoods = new ArrayList<Likelihood>(); private final List<Callable<Double>> likelihoodCallers = new ArrayList<Callable<Double>>(); class LikelihoodCaller implements Callable<Double> { public LikelihoodCaller(Likelihood likelihood, int index) { this.likelihood = likelihood; this.index = index; } public Double call() throws Exception { if (EVALUATION_TIMERS) { long time = System.nanoTime(); double logL = likelihood.getLogLikelihood(); evaluationTimes[index] += System.nanoTime() - time; evaluationCounts[index] ++; return logL; } return likelihood.getLogLikelihood(); } private final Likelihood likelihood; private final int index; } }
package es.minetsii.MiningCrates; import org.bukkit.plugin.java.JavaPlugin; public class MiningCrates extends JavaPlugin { public static String prefix = "f[eMCratesPf] "; public static String use_Permission = "tempperm.use"; @Override public void onEnable() { getConfig().options().header( " "# - Mining Crates - #" + "\n" + " ); getConfig().addDefault("chests", new String[] {}); getConfig().options().copyHeader(true); getConfig().options().copyDefaults(true); saveConfig(); reloadConfig(); } @Override public void onDisable() { } }
package org.voltdb.client; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.net.UnknownHostException; import java.util.Arrays; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.locks.ReentrantLock; import java.util.logging.Logger; import org.voltdb.utils.CatalogUtil; /** * A client that connects to one or more nodes in a VoltCluster * and provides methods to call stored procedures and receive * responses. */ public final class ClientImpl implements Client, ReplicaProcCaller { private final AtomicLong m_handle = new AtomicLong(Long.MIN_VALUE); /* * Username and password as set by createConnection. Used * to ensure that the same credentials are used every time * with that inconsistent API. */ // stored credentials private boolean m_credentialsSet = false; private final ReentrantLock m_credentialComparisonLock = new ReentrantLock(); private String m_createConnectionUsername = null; private byte[] m_hashedPassword = null; private int m_passwordHashCode = 0; /* * Username and password as set by the constructor. */ private final String m_username; private final byte m_passwordHash[]; /** * These threads belong to the network thread pool * that invokes callbacks. These threads are "blessed" * and should never experience backpressure. This ensures that the * network thread pool doesn't block when queuing procedures from * a callback. */ private final CopyOnWriteArrayList<Long> m_blessedThreadIds = new CopyOnWriteArrayList<Long>(); private volatile boolean m_isShutdown = false; /** * Create a new client without any initial connections. * Also provide a hint indicating the expected serialized size of * most outgoing procedure invocations. This helps size initial allocations * for serializing network writes * @param expectedOutgoingMessageSize Expected size of procedure invocations in bytes * @param maxArenaSizes Maximum size arenas in the memory pool should grow to * @param heavyweight Whether to use multiple or a single thread */ ClientImpl(ClientConfig config) { m_distributer = new Distributer( config.m_heavyweight, config.m_procedureCallTimeoutMS, config.m_connectionResponseTimeoutMS); m_distributer.addClientStatusListener(new CSL()); m_username = config.m_username; m_passwordHash = ConnectionUtil.getHashedPassword(config.m_password); if (config.m_listener != null) { m_distributer.addClientStatusListener(config.m_listener); } assert(config.m_maxOutstandingTxns > 0); m_blessedThreadIds.addAll(m_distributer.getThreadIds()); if (config.m_autoTune) { m_distributer.m_rateLimiter.enableAutoTuning( config.m_autoTuneTargetInternalLatency); } else { m_distributer.m_rateLimiter.setLimits( config.m_maxTransactionsPerSecond, config.m_maxOutstandingTxns); } } private boolean verifyCredentialsAreAlwaysTheSame(String username, byte[] hashedPassword) { // handle the unauthenticated case if (m_createConnectionUsername == null) { m_createConnectionUsername = ""; return true; } m_credentialComparisonLock.lock(); try { if (m_credentialsSet == false) { m_credentialsSet = true; m_createConnectionUsername = username; if (hashedPassword != null) { m_hashedPassword = Arrays.copyOf(hashedPassword, hashedPassword.length); m_passwordHashCode = Arrays.hashCode(hashedPassword); } return true; } else { if (!m_createConnectionUsername.equals(username)) return false; if (hashedPassword == null) return m_hashedPassword == null; else for (int i = 0; i < hashedPassword.length; i++) if (hashedPassword[i] != m_hashedPassword[i]) return false; return true; } } finally { m_credentialComparisonLock.unlock(); } } public String getUsername() { return m_createConnectionUsername; } public int getPasswordHashCode() { return m_passwordHashCode; } public void createConnectionWithHashedCredentials(String host, int port, String program, byte[] hashedPassword) throws IOException { if (m_isShutdown) { throw new IOException("Client instance is shutdown"); } final String subProgram = (program == null) ? "" : program; final byte[] subPassword = (hashedPassword == null) ? ConnectionUtil.getHashedPassword("") : hashedPassword; if (!verifyCredentialsAreAlwaysTheSame(subProgram, subPassword)) { throw new IOException("New connection authorization credentials do not match previous credentials for client."); } m_distributer.createConnectionWithHashedCredentials(host, subProgram, subPassword, port); } /** * Synchronously invoke a procedure call blocking until a result is available. * @param procName class name (not qualified by package) of the procedure to execute. * @param parameters vararg list of procedure's parameter values. * @return array of VoltTable results. * @throws org.voltdb.client.ProcCallException * @throws NoConnectionsException */ @Override public final ClientResponse callProcedure(String procName, Object... parameters) throws IOException, NoConnectionsException, ProcCallException { final SyncCallback cb = new SyncCallback(); cb.setArgs(parameters); final ProcedureInvocation invocation = new ProcedureInvocation(m_handle.getAndIncrement(), procName, parameters); return callProcedure(cb, invocation); } /** * The synchronous procedure call method for DR replication */ @Override public ClientResponse callProcedure( long originalTxnId, String procName, Object... parameters) throws IOException, NoConnectionsException, ProcCallException { final SyncCallback cb = new SyncCallback(); cb.setArgs(parameters); final ProcedureInvocation invocation = new ProcedureInvocation(originalTxnId, m_handle.getAndIncrement(), procName, parameters); return callProcedure(cb, invocation); } private final ClientResponse callProcedure(SyncCallback cb, ProcedureInvocation invocation) throws IOException, NoConnectionsException, ProcCallException { if (m_isShutdown) { throw new NoConnectionsException("Client instance is shutdown"); } if (m_blessedThreadIds.contains(Thread.currentThread().getId())) { throw new IOException("Can't invoke a procedure synchronously from with the client callback thread " + " without deadlocking the client library"); } m_distributer.queue( invocation, cb, true); try { cb.waitForResponse(); } catch (final InterruptedException e) { throw new java.io.InterruptedIOException("Interrupted while waiting for response"); } if (cb.getResponse().getStatus() != ClientResponse.SUCCESS) { throw new ProcCallException(cb.getResponse(), cb.getResponse().getStatusString(), cb.getResponse().getException()); } // cb.result() throws ProcCallException if procedure failed return cb.getResponse(); } /** * Asynchronously invoke a procedure call. * @param callback TransactionCallback that will be invoked with procedure results. * @param procName class name (not qualified by package) of the procedure to execute. * @param parameters vararg list of procedure's parameter values. * @return True if the procedure was queued and false otherwise */ @Override public final boolean callProcedure(ProcedureCallback callback, String procName, Object... parameters) throws IOException, NoConnectionsException { if (m_isShutdown) { return false; } return callProcedure(callback, 0, procName, parameters); } /** * Asynchronously invoke a replicated procedure. If there is backpressure * this call will block until the invocation is queued. If configureBlocking(false) is invoked * then it will return immediately. Check * the return value to determine if queuing actually took place. * * @param callback ProcedureCallback that will be invoked with procedure results. * @param procName class name (not qualified by package) of the procedure to execute. * @param parameters vararg list of procedure's parameter values. * @return <code>true</code> if the procedure was queued and * <code>false</code> otherwise */ @Override public final boolean callProcedure( long originalTxnId, ProcedureCallback callback, String procName, Object... parameters) throws IOException, NoConnectionsException { if (callback instanceof ProcedureArgumentCacher) { ((ProcedureArgumentCacher)callback).setArgs(parameters); } ProcedureInvocation invocation = new ProcedureInvocation(originalTxnId, m_handle.getAndIncrement(), procName, parameters); return private_callProcedure(callback, 0, invocation); } @Override public int calculateInvocationSerializedSize(String procName, Object... parameters) { final ProcedureInvocation invocation = new ProcedureInvocation(0, procName, parameters); return invocation.getSerializedSize(); } @Override public final boolean callProcedure( ProcedureCallback callback, int expectedSerializedSize, String procName, Object... parameters) throws NoConnectionsException, IOException { if (callback instanceof ProcedureArgumentCacher) { ((ProcedureArgumentCacher)callback).setArgs(parameters); } ProcedureInvocation invocation = new ProcedureInvocation(m_handle.getAndIncrement(), procName, parameters); return private_callProcedure(callback, expectedSerializedSize, invocation); } private final boolean private_callProcedure( ProcedureCallback callback, int expectedSerializedSize, ProcedureInvocation invocation) throws IOException, NoConnectionsException { if (m_isShutdown) { return false; } if (callback == null) { callback = new NullCallback(); } //Blessed threads (the ones that invoke callbacks) are not subject to backpressure boolean isBlessed = m_blessedThreadIds.contains(Thread.currentThread().getId()); if (m_blockingQueue) { while (!m_distributer.queue( invocation, callback, isBlessed)) { try { backpressureBarrier(); } catch (InterruptedException e) { throw new java.io.InterruptedIOException("Interrupted while invoking procedure asynchronously"); } } return true; } else { return m_distributer.queue( invocation, callback, isBlessed); } } /** * Serializes catalog and deployment file for UpdateApplicationCatalog. * Catalog is serialized into byte array, deployment file is serialized into * string. * * @param catalogPath * @param deploymentPath * @return Parameters that can be passed to UpdateApplicationCatalog * @throws IOException If either of the files cannot be read */ private Object[] getUpdateCatalogParams(File catalogPath, File deploymentPath) throws IOException { Object[] params = new Object[2]; params[0] = CatalogUtil.toBytes(catalogPath); params[1] = new String(CatalogUtil.toBytes(deploymentPath), "UTF-8"); return params; } @Override public ClientResponse updateApplicationCatalog(File catalogPath, File deploymentPath) throws IOException, NoConnectionsException, ProcCallException { Object[] params = getUpdateCatalogParams(catalogPath, deploymentPath); return callProcedure("@UpdateApplicationCatalog", params); } @Override public boolean updateApplicationCatalog(ProcedureCallback callback, File catalogPath, File deploymentPath) throws IOException, NoConnectionsException { Object[] params = getUpdateCatalogParams(catalogPath, deploymentPath); return callProcedure(callback, "@UpdateApplicationCatalog", params); } @Override public void drain() throws InterruptedException { if (m_isShutdown) { return; } if (m_blessedThreadIds.contains(Thread.currentThread().getId())) { throw new RuntimeException("Can't invoke backpressureBarrier from within the client callback thread " + " without deadlocking the client library"); } m_distributer.drain(); } /** * Shutdown the client closing all network connections and release * all memory resources. * @throws InterruptedException */ @Override public void close() throws InterruptedException { if (m_blessedThreadIds.contains(Thread.currentThread().getId())) { throw new RuntimeException("Can't invoke backpressureBarrier from within the client callback thread " + " without deadlocking the client library"); } m_isShutdown = true; synchronized (m_backpressureLock) { m_backpressureLock.notifyAll(); } m_distributer.shutdown(); } @Override public void backpressureBarrier() throws InterruptedException { if (m_isShutdown) { return; } if (m_blessedThreadIds.contains(Thread.currentThread().getId())) { throw new RuntimeException("Can't invoke backpressureBarrier from within the client callback thread " + " without deadlocking the client library"); } if (m_backpressure) { synchronized (m_backpressureLock) { if (m_backpressure) { while (m_backpressure && !m_isShutdown) { m_backpressureLock.wait(); } } } } } class CSL extends ClientStatusListenerExt { @Override public void backpressure(boolean status) { synchronized (m_backpressureLock) { if (status) { m_backpressure = true; } else { m_backpressure = false; m_backpressureLock.notifyAll(); } } } @Override public void connectionLost(String hostname, int port, int connectionsLeft, ClientStatusListenerExt.DisconnectCause cause) { if (connectionsLeft == 0) { //Wake up client and let it attempt to queue work //and then fail with a NoConnectionsException synchronized (m_backpressureLock) { m_backpressure = false; m_backpressureLock.notifyAll(); } } } } static final Logger LOG = Logger.getLogger(ClientImpl.class.getName()); // Logger shared by client package. private final Distributer m_distributer; // de/multiplexes connections to a cluster private final Object m_backpressureLock = new Object(); private boolean m_backpressure = false; private boolean m_blockingQueue = true; @Override public void configureBlocking(boolean blocking) { m_blockingQueue = blocking; } @Override public ClientStatsContext createStatsContext() { return m_distributer.createStatsContext(); } @Override public Object[] getInstanceId() { return m_distributer.getInstanceId(); } @Override public String getBuildString() { return m_distributer.getBuildString(); } @Override public boolean blocking() { return m_blockingQueue; } private static String getHostnameFromHostnameColonPort(String server) { server = server.trim(); String[] parts = server.split(":"); if (parts.length == 1) { return server; } else { assert (parts.length == 2); return parts[0].trim(); } } public static int getPortFromHostnameColonPort(String server, int defaultPort) { String[] parts = server.split(":"); if (parts.length == 1) { return defaultPort; } else { assert (parts.length == 2); return Integer.parseInt(parts[1]); } } @Override public void createConnection(String host) throws UnknownHostException, IOException { if (m_username == null) { throw new IllegalStateException("Attempted to use createConnection(String host) " + "with a client that wasn't constructed with a username and password specified"); } int port = getPortFromHostnameColonPort(host, Client.VOLTDB_SERVER_PORT); host = getHostnameFromHostnameColonPort(host); createConnectionWithHashedCredentials(host, port, m_username, m_passwordHash); } @Override public void createConnection(String host, int port) throws UnknownHostException, IOException { if (m_username == null) { throw new IllegalStateException("Attempted to use createConnection(String host) " + "with a client that wasn't constructed with a username and password specified"); } createConnectionWithHashedCredentials(host, port, m_username, m_passwordHash); } @Override public int[] getThroughputAndOutstandingTxnLimits() { return m_distributer.m_rateLimiter.getLimits(); } @Override public void writeSummaryCSV(ClientStats stats, String path) throws IOException { // don't do anything (be silent) if empty path if ((path == null) || (path.length() == 0)) { return; } FileWriter fw = new FileWriter(path); fw.append(String.format("%d,%d,%d,%d,%d,%d,%d\n", stats.getStartTimestamp(), stats.getDuration(), stats.getInvocationsCompleted(), stats.kPercentileLatency(0.0), stats.kPercentileLatency(1.0), stats.kPercentileLatency(0.95), stats.kPercentileLatency(0.99))); fw.close(); } }
package com.codex.hackerrank; import java.util.Comparator; import java.util.PriorityQueue; import java.util.Scanner; public class MedianUpdates { class MyComparator implements Comparator<Integer> { @Override public int compare(Integer o1, Integer o2) { return o1 > o2 ? -1 : (o1 == o2 ? 0 : 1); } } private static void printMedian(PriorityQueue<Integer> leftHeap, PriorityQueue<Integer> rightHeap) { } private static void balanceHeap(PriorityQueue<Integer> leftHeap, PriorityQueue<Integer> rightHeap) { int l = leftHeap.size(); int r = rightHeap.size(); if(leftHeap.isEmpty() && rightHeap.isEmpty() || l==r) { return; } if(l==0 && r>0) { while(leftHeap.size()-rightHeap.size()<=1) { leftHeap.add(rightHeap.poll()); } } else if () { } } private static void median(int[] numbers, String[] operations) { PriorityQueue<Integer> leftHeap = new PriorityQueue<>(); MedianUpdates medianUpdates = new MedianUpdates(); Comparator<Integer> comparator = medianUpdates.new MyComparator(); PriorityQueue<Integer> rightHeap = new PriorityQueue<>(comparator); for (int i = 0; i < numbers.length; i++) { if (operations[i] == "r") { if (leftHeap.isEmpty() && rightHeap.isEmpty()) { System.out.println("Wrong!"); } else if (!leftHeap.isEmpty()) { rightHeap.remove(numbers[i]); balanceHeap(leftHeap, rightHeap); } else { leftHeap.remove(numbers[i]); balanceHeap(leftHeap, rightHeap); } } else if (operations[i] == "a") { if (leftHeap.isEmpty() && rightHeap.isEmpty()) { leftHeap.add(numbers[i]); //print here itself } else if (!leftHeap.isEmpty()) { leftHeap.add(numbers[i]); balanceHeap(leftHeap, rightHeap); } else { rightHeap.add(numbers[i]); balanceHeap(leftHeap, rightHeap); } } } } public static void main(String[] args) { PriorityQueue<Integer> queue = new PriorityQueue<Integer>(); queue.add(10); queue.add(13); queue.add(11); queue.add(19); queue.add(100); queue.add(90); // while (!queue.isEmpty()) { // System.out.println(queue.poll()); MedianUpdates medianUpdates = new MedianUpdates(); Comparator<Integer> comparator = medianUpdates.new MyComparator(); PriorityQueue<Integer> queue1 = new PriorityQueue<Integer>(comparator); queue1.add(10); queue1.add(11); queue1.add(3); queue1.add(4); queue1.add(7); queue1.add(2); queue1.add(14); // while (!queue1.isEmpty()) { // System.out.println(queue1.poll()); Scanner in = new Scanner(System.in); int N; N = in.nextInt(); String s[] = new String[N]; int x[] = new int[N]; for (int i = 0; i < N; i++) { s[i] = in.next(); x[i] = in.nextInt(); System.out.println("-->" + s[i] + ":" + x[i]); } // median(x, s); in.close(); } }
package dr.evomodel.continuous; import dr.evolution.tree.NodeAttributeProvider; import dr.evolution.tree.NodeRef; import dr.evolution.tree.Tree; import dr.evomodel.branchratemodel.BranchRateModel; import dr.evomodel.tree.TreeModel; import dr.inference.model.*; import dr.inference.loggers.LogColumn; import dr.inference.loggers.NumberColumn; import dr.xml.*; import dr.math.MathUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; import java.util.logging.Logger; /** * @author Marc Suchard */ public abstract class AbstractMultivariateTraitLikelihood extends AbstractModelLikelihood implements NodeAttributeProvider { public static final String TRAIT_LIKELIHOOD = "multivariateTraitLikelihood"; public static final String TRAIT_NAME = "traitName"; public static final String ROOT_PRIOR = "rootPrior"; public static final String MODEL = "diffusionModel"; public static final String TREE = "tree"; public static final String TRAIT_PARAMETER = "traitParameter"; public static final String SET_TRAIT = "setOutcomes"; public static final String MISSING = "missingIndicator"; public static final String CACHE_BRANCHES = "cacheBranches"; public static final String REPORT_MULTIVARIATE = "reportAsMultivariate"; public static final String DEFAULT_TRAIT_NAME = "trait"; public static final String RANDOMIZE = "randomize"; public static final String RANDOMIZE_LOWER = "lower"; public static final String RANDOMIZE_UPPER = "upper"; public static final String CHECK = "check"; public static final String USE_TREE_LENGTH = "useTreeLength"; public static final String SCALE_BY_TIME = "scaleByTime"; public static final String SUBSTITUTIONS = "substitutions"; public static final String SAMPLING_DENSITY = "samplingDensity"; public static final String INTEGRATE = "integrateInternalTraits"; public AbstractMultivariateTraitLikelihood(String traitName, TreeModel treeModel, MultivariateDiffusionModel diffusionModel, CompoundParameter traitParameter, List<Integer> missingIndices, boolean cacheBranches, boolean scaleByTime, boolean useTreeLength, BranchRateModel rateModel, Model samplingDensity, boolean reportAsMultivariate) { super(TRAIT_LIKELIHOOD); this.traitName = traitName; this.treeModel = treeModel; this.rateModel = rateModel; this.diffusionModel = diffusionModel; this.traitParameter = traitParameter; this.missingIndices = missingIndices; addModel(treeModel); addModel(diffusionModel); if (rateModel != null) { hasRateModel = true; addModel(rateModel); } if (samplingDensity != null) { addModel(samplingDensity); } if (traitParameter != null) addVariable(traitParameter); this.reportAsMultivariate = reportAsMultivariate; this.cacheBranches = cacheBranches; if (cacheBranches) { cachedLogLikelihoods = new double[treeModel.getNodeCount()]; storedCachedLogLikelihood = new double[treeModel.getNodeCount()]; validLogLikelihoods = new boolean[treeModel.getNodeCount()]; storedValidLogLikelihoods = new boolean[treeModel.getNodeCount()]; } this.scaleByTime = scaleByTime; this.useTreeLength = useTreeLength; StringBuffer sb = new StringBuffer("Creating multivariate diffusion model:\n"); sb.append("\tTrait: ").append(traitName).append("\n"); sb.append("\tDiffusion process: ").append(diffusionModel.getId()).append("\n"); sb.append("\tHeterogenity model: ").append(rateModel != null ? rateModel.getId() : "homogeneous").append("\n"); sb.append("\tTree normalization: ").append(scaleByTime ? (useTreeLength ? "length" : "height") : "off").append("\n"); if (scaleByTime) { recalculateTreeLength(); if (useTreeLength) { sb.append("\tInitial tree length: ").append(treeLength).append("\n"); } else { sb.append("\tInitial tree height: ").append(treeLength).append("\n"); } } sb.append(extraInfo()); sb.append("\tPlease cite Suchard, Lemey and Rambaut (in preparation) if you publish results using this model."); Logger.getLogger("dr.evomodel").info(sb.toString()); recalculateTreeLength(); } protected abstract String extraInfo(); public String getTraitName() { return traitName; } public double getRescaledBranchLength(NodeRef node) { double length = treeModel.getBranchLength(node); if (hasRateModel) length *= rateModel.getBranchRate(treeModel, node); if (scaleByTime) return length / treeLength; return length; } // ModelListener IMPLEMENTATION protected void handleModelChangedEvent(Model model, Object object, int index) { if (!cacheBranches) { likelihoodKnown = false; if (model == treeModel) recalculateTreeLength(); return; } if (model == diffusionModel) { updateAllNodes(); } // fireTreeEvents sends two events here when a node trait is changed, // ignoring object instance Parameter case else if (model == treeModel) { if (object instanceof TreeModel.TreeChangedEvent) { TreeModel.TreeChangedEvent event = (TreeModel.TreeChangedEvent) object; if (event.isHeightChanged()) { recalculateTreeLength(); if (useTreeLength || (scaleByTime && treeModel.isRoot(event.getNode()))) updateAllNodes(); else { updateNodeAndChildren(event.getNode()); } } else if (event.isNodeParameterChanged()) { updateNodeAndChildren(event.getNode()); } else if (event.isNodeChanged()) { recalculateTreeLength(); if (useTreeLength || (scaleByTime && treeModel.isRoot(event.getNode()))) updateAllNodes(); else { updateNodeAndChildren(event.getNode()); } } else { throw new RuntimeException("Unexpected TreeModel TreeChangedEvent occuring in AbstractMultivariateTraitLikelihood"); } } else if (object instanceof Parameter) { // Ignoring } else { throw new RuntimeException("Unexpected TreeModel event occuring in AbstractMultivariateTraitLikelihood"); } } else if (model == rateModel) { if (index == -1) { updateAllNodes(); } else { if (((Parameter)object).getDimension() == 2*(treeModel.getNodeCount()-1)) updateNode(treeModel.getNode(index)); // This is a branch specific update else updateAllNodes(); // Probably an epoch model } } else { throw new RuntimeException("Unknown componentChangedEvent"); } } private void updateAllNodes() { for(int i=0; i<treeModel.getNodeCount(); i++) validLogLikelihoods[i] = false; likelihoodKnown = false; } private void updateNode(NodeRef node) { validLogLikelihoods[node.getNumber()] = false; likelihoodKnown = false; } private void updateNodeAndChildren(NodeRef node) { validLogLikelihoods[node.getNumber()] = false; for(int i=0; i<treeModel.getChildCount(node); i++) validLogLikelihoods[treeModel.getChild(node,i).getNumber()] = false; likelihoodKnown = false; } public void recalculateTreeLength() { if (!scaleByTime) return; if (useTreeLength) { treeLength = 0; for (int i = 0; i < treeModel.getNodeCount(); i++) { NodeRef node = treeModel.getNode(i); if (!treeModel.isRoot(node)) treeLength += treeModel.getBranchLength(node); // Bug was here } } else { // Normalizing by tree height. treeLength = treeModel.getNodeHeight(treeModel.getRoot()); } } // VariableListener IMPLEMENTATION protected final void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) { // All parameter changes are handled first by the treeModel if (!cacheBranches) likelihoodKnown = false; } // Model IMPLEMENTATION /** * Stores the precalculated state: in this case the intervals */ protected void storeState() { storedLikelihoodKnown = likelihoodKnown; storedLogLikelihood = logLikelihood; storedTreeLength = treeLength; if (cacheBranches) { System.arraycopy(cachedLogLikelihoods,0,storedCachedLogLikelihood,0,treeModel.getNodeCount()); System.arraycopy(validLogLikelihoods,0,storedValidLogLikelihoods,0,treeModel.getNodeCount()); } } /** * Restores the precalculated state: that is the intervals of the tree. */ protected void restoreState() { likelihoodKnown = storedLikelihoodKnown; logLikelihood = storedLogLikelihood; treeLength = storedTreeLength; if (cacheBranches) { double[] tmp = storedCachedLogLikelihood; storedCachedLogLikelihood = cachedLogLikelihoods; cachedLogLikelihoods = tmp; boolean[] tmp2 = storedValidLogLikelihoods; storedValidLogLikelihoods = validLogLikelihoods; validLogLikelihoods = tmp2; } } protected void acceptState() { } // nothing to do public TreeModel getTreeModel() { return treeModel; } public MultivariateDiffusionModel getDiffusionModel() { return diffusionModel; } // public boolean getInSubstitutionTime() { // return inSubstitutionTime; // Likelihood IMPLEMENTATION public Model getModel() { return this; } public String toString() { return getClass().getName() + "(" + getLogLikelihood() + ")"; } public final double getLogLikelihood() { if (!likelihoodKnown) { logLikelihood = calculateLogLikelihood(); likelihoodKnown = true; } return logLikelihood; } public abstract double getLogDataLikelihood(); public void makeDirty() { likelihoodKnown = false; if (cacheBranches) updateAllNodes(); } public LogColumn[] getColumns() { return new LogColumn[]{ new LikelihoodColumn(getId()+".joint"), new NumberColumn(getId()+".data") { public double getDoubleValue() { return getLogDataLikelihood(); } } }; } public abstract double calculateLogLikelihood(); public double getMaxLogLikelihood() { return maxLogLikelihood; } // Loggable IMPLEMENTATION private String[] attributeLabel = null; public String[] getNodeAttributeLabel() { if (attributeLabel == null) { double[] trait = treeModel.getMultivariateNodeTrait(treeModel.getRoot(), traitName); if (trait.length == 1 || reportAsMultivariate) attributeLabel = new String[]{traitName}; else { attributeLabel = new String[trait.length]; for (int i = 1; i <= trait.length; i++) attributeLabel[i - 1] = traitName + i; } } return attributeLabel; } protected abstract double[] traitForNode(TreeModel tree, NodeRef node, String traitName); public String[] getAttributeForNode(Tree tree, NodeRef node) { // double trait[] = treeModel.getMultivariateNodeTrait(node, traitName); double trait[] = traitForNode(treeModel, node, traitName); String[] value; if (!reportAsMultivariate || trait.length == 1) { value = new String[trait.length]; for (int i = 0; i < trait.length; i++) value[i] = Double.toString(trait[i]); } else { StringBuffer sb = new StringBuffer("{"); for (int i = 0; i < trait.length - 1; i++) sb.append(Double.toString(trait[i])).append(","); sb.append(Double.toString(trait[trait.length - 1])).append("}"); value = new String[]{sb.toString()}; } return value; } public void randomize(Parameter trait, double[] lower, double[] upper) { // Draws each dimension in each trait from U[lower, upper) for(int i = 0; i < trait.getDimension(); i++) { final int whichLower = i % lower.length; final int whichUpper = i % upper.length; final double newValue = MathUtils.uniform(lower[whichLower],upper[whichUpper]); trait.setParameterValue(i, newValue); } //diffusionModel.randomize(trait); } public void check(Parameter trait) throws XMLParseException { diffusionModel.check(trait); } // XMLElement IMPLEMENTATION public Element createElement(Document d) { throw new RuntimeException("Not implemented yet!"); } // XMLObjectParser public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { public String getParserName() { return TRAIT_LIKELIHOOD; } public Object parseXMLObject(XMLObject xo) throws XMLParseException { MultivariateDiffusionModel diffusionModel = (MultivariateDiffusionModel) xo.getChild(MultivariateDiffusionModel.class); TreeModel treeModel = (TreeModel) xo.getChild(TreeModel.class); CompoundParameter traitParameter = (CompoundParameter) xo.getElementFirstChild(TRAIT_PARAMETER); boolean cacheBranches = xo.getAttribute(CACHE_BRANCHES, false); boolean integrate = xo.getAttribute(INTEGRATE,false); BranchRateModel rateModel = (BranchRateModel) xo.getChild(BranchRateModel.class); List<Integer> missingIndices = null; String traitName = DEFAULT_TRAIT_NAME; if (xo.hasAttribute(TRAIT_NAME)) { traitName = xo.getStringAttribute(TRAIT_NAME); // Fill in attributeValues int taxonCount = treeModel.getTaxonCount(); for (int i = 0; i < taxonCount; i++) { String taxonName = treeModel.getTaxonId(i); String paramName = taxonName + "." + traitName; Parameter traitParam = getTraitParameterByName(traitParameter, paramName); if (traitParam == null) throw new RuntimeException("Missing trait parameters at tree tips"); String object = (String) treeModel.getTaxonAttribute(i, traitName); if (object == null) throw new RuntimeException("Trait \"" + traitName + "\" not found for taxa \"" + taxonName + "\""); else { StringTokenizer st = new StringTokenizer(object); int count = st.countTokens(); if (count != traitParam.getDimension()) throw new RuntimeException("Trait length must match trait parameter dimension"); for (int j = 0; j < count; j++) { String oneValue = st.nextToken(); double value = Double.NaN; if (oneValue.compareTo("NA") == 0) { // Missing values not yet handled. } else { try { value = new Double(oneValue); } catch (NumberFormatException e) { throw new RuntimeException(e.getMessage()); } } traitParam.setParameterValue(j, value); } } } // Find missing values double[] allValues = traitParameter.getParameterValues(); missingIndices = new ArrayList<Integer>(); for (int i = 0; i < allValues.length; i++) { if ((new Double(allValues[i])).isNaN()) { traitParameter.setParameterValue(i, 0); missingIndices.add(i); } } if (xo.hasChildNamed(MISSING)) { XMLObject cxo = xo.getChild(MISSING); Parameter missingParameter = new Parameter.Default(allValues.length, 0.0); for (int i : missingIndices) { missingParameter.setParameterValue(i, 1.0); } missingParameter.addBounds(new Parameter.DefaultBounds(1.0, 0.0, allValues.length)); /* CompoundParameter missingParameter = new CompoundParameter(MISSING); System.err.println("TRAIT: "+traitParameter.toString()); System.err.println("CNT: "+traitParameter.getNumberOfParameters()); for(int i : missingIndices) { Parameter thisParameter = traitParameter.getIndicatorParameter(i); missingParameter.addVariable(thisParameter); }*/ ParameterParser.replaceParameter(cxo, missingParameter); } } Model samplingDensity = null; if (xo.hasChildNamed(SAMPLING_DENSITY)) { XMLObject cxo = xo.getChild(SAMPLING_DENSITY); samplingDensity = (Model) cxo.getChild(Model.class); } boolean useTreeLength = xo.getAttribute(USE_TREE_LENGTH, false); boolean scaleByTime = xo.getAttribute(SCALE_BY_TIME, false); boolean reportAsMultivariate = false; if (xo.hasAttribute(REPORT_MULTIVARIATE) && xo.getBooleanAttribute(REPORT_MULTIVARIATE)) reportAsMultivariate = true; if (integrate) return new IntegratedMultivariateTraitLikelihood(traitName, treeModel, diffusionModel, traitParameter, missingIndices, cacheBranches, scaleByTime, useTreeLength, rateModel, samplingDensity, reportAsMultivariate, null); AbstractMultivariateTraitLikelihood like = new SampledMultivariateTraitLikelihood(traitName, treeModel, diffusionModel, traitParameter, missingIndices, cacheBranches, scaleByTime, useTreeLength, rateModel, samplingDensity, reportAsMultivariate); if (xo.hasChildNamed(RANDOMIZE)) { XMLObject cxo = xo.getChild(RANDOMIZE); Parameter traits = (Parameter) cxo.getChild(Parameter.class); double[] randomizeLower; double[] randomizeUpper; if (cxo.hasAttribute(RANDOMIZE_LOWER)) { randomizeLower = cxo.getDoubleArrayAttribute(RANDOMIZE_LOWER); } else { randomizeLower = new double[] { -90.0 }; } if (cxo.hasAttribute(RANDOMIZE_UPPER)) { randomizeUpper = cxo.getDoubleArrayAttribute(RANDOMIZE_UPPER); } else { randomizeUpper = new double[] { +90.0 }; } like.randomize(traits, randomizeLower, randomizeUpper); } if (xo.hasChildNamed(CHECK)) { XMLObject cxo = xo.getChild(CHECK); Parameter check = (Parameter) cxo.getChild(Parameter.class); like.check(check); } return like; } private Parameter getTraitParameterByName(CompoundParameter traits, String name) { for (int i = 0; i < traits.getNumberOfParameters(); i++) { Parameter found = traits.getParameter(i); if (found.getStatisticName().compareTo(name) == 0) return found; } return null; }
package dr.inference.operators.repeatedMeasures; import dr.evolution.tree.TreeTrait; import dr.evomodel.treedatalikelihood.TreeDataLikelihood; import dr.evomodel.treedatalikelihood.continuous.ContinuousTraitPartialsProvider; import dr.evomodel.treedatalikelihood.continuous.IntegratedFactorAnalysisLikelihood; import dr.evomodel.treedatalikelihood.continuous.RepeatedMeasuresTraitDataModel; import dr.evomodel.treedatalikelihood.preorder.ModelExtensionProvider; import dr.inference.distribution.DistributionLikelihood; import dr.inference.distribution.LogNormalDistributionModel; import dr.inference.distribution.NormalDistributionModel; import dr.inference.model.CompoundParameter; import dr.inference.model.DiagonalMatrix; import dr.inference.model.MatrixParameterInterface; import dr.inference.model.Parameter; import dr.math.distributions.Distribution; import dr.math.matrixAlgebra.WrappedVector; import dr.util.Attribute; import org.ejml.data.DenseMatrix64F; import java.util.List; import static dr.evomodel.treedatalikelihood.preorder.AbstractRealizedContinuousTraitDelegate.REALIZED_TIP_TRAIT; /** * @author Marc A. Suchard * @author Gabriel Hassler */ public interface GammaGibbsProvider { SufficientStatistics getSufficientStatistics(int dim); Parameter getPrecisionParameter(); void drawValues(); class SufficientStatistics { final public int observationCount; final public double sumOfSquaredErrors; SufficientStatistics(int observationCount, double sumOfSquaredErrors) { this.observationCount = observationCount; this.sumOfSquaredErrors = sumOfSquaredErrors; } } class Default implements GammaGibbsProvider { private final Parameter precisionParameter; private final Parameter meanParameter; private final boolean isLog; private final List<Attribute<double[]>> dataList; public Default(DistributionLikelihood inLikelihood) { Distribution likelihood = inLikelihood.getDistribution(); this.dataList = inLikelihood.getDataList(); if (likelihood instanceof NormalDistributionModel) { this.precisionParameter = (Parameter) ((NormalDistributionModel) likelihood).getPrecision(); this.meanParameter = (Parameter) ((NormalDistributionModel) likelihood).getMean(); this.isLog = false; } else if (likelihood instanceof LogNormalDistributionModel) { if (((LogNormalDistributionModel) likelihood).getParameterization() == LogNormalDistributionModel.Parameterization.MU_PRECISION) { this.meanParameter = ((LogNormalDistributionModel) likelihood).getMuParameter(); } else { throw new RuntimeException("Must characterize likelihood in terms of mu and precision parameters"); } this.precisionParameter = ((LogNormalDistributionModel) likelihood).getPrecisionParameter(); isLog = true; } else throw new RuntimeException("Likelihood must be Normal or log Normal"); if (precisionParameter == null) throw new RuntimeException("Must characterize likelihood in terms of a precision parameter"); } @Override public SufficientStatistics getSufficientStatistics(int dim) { // Calculate weighted sum-of-squares final double mu = meanParameter.getParameterValue(dim); double SSE = 0; int n = 0; for (Attribute<double[]> statistic : dataList) { for (double x : statistic.getAttributeValue()) { if (isLog) { final double logX = Math.log(x); SSE += (logX - mu) * (logX - mu); } else { SSE += (x - mu) * (x - mu); } n++; } } return new SufficientStatistics(n, SSE); } @Override public Parameter getPrecisionParameter() { return precisionParameter; } @Override public void drawValues() { // Do nothing } } class NormalExtensionGibbsProvider implements GammaGibbsProvider { private final ModelExtensionProvider.NormalExtensionProvider dataModel; private final TreeDataLikelihood treeLikelihood; private final CompoundParameter traitParameter; private final Parameter precisionParameter; private final TreeTrait tipTrait; private final boolean[] missingVector; private double tipValues[]; public NormalExtensionGibbsProvider(ModelExtensionProvider.NormalExtensionProvider dataModel, TreeDataLikelihood treeLikelihood, String traitName) { this.dataModel = dataModel; this.treeLikelihood = treeLikelihood; this.traitParameter = dataModel.getParameter(); this.tipTrait = treeLikelihood.getTreeTrait(REALIZED_TIP_TRAIT + "." + traitName); this.missingVector = dataModel.getMissingIndicator(); MatrixParameterInterface matrixParameter = dataModel.getExtensionPrecision(); if (matrixParameter instanceof DiagonalMatrix) { this.precisionParameter = ((DiagonalMatrix) matrixParameter).getDiagonalParameter(); } else { //TODO: alternatively, check that the off-diagonal elements are zero every time you update the parameter? //TODO: does this belong in the parser? throw new RuntimeException(this.getClass().getName() + " only applies to diagonal precision matrices, but the " + ModelExtensionProvider.NormalExtensionProvider.class.getName() + " supplied a precision matrix of class " + matrixParameter.getClass().getName() + "."); } } @Override public SufficientStatistics getSufficientStatistics(int dim) { final int taxonCount = treeLikelihood.getTree().getExternalNodeCount(); final int traitDim = treeLikelihood.getDataLikelihoodDelegate().getTraitDim(); int missingCount = 0; double SSE = 0; for (int taxon = 0; taxon < taxonCount; ++taxon) { int offset = traitDim * taxon; if (missingVector == null || !missingVector[dim + offset]) { double traitValue = traitParameter.getParameter(taxon).getParameterValue(dim); double tipValue = tipValues[taxon * traitDim + dim]; SSE += (traitValue - tipValue) * (traitValue - tipValue); } else { missingCount += 1; } } return new SufficientStatistics(taxonCount - missingCount, SSE); } @Override public Parameter getPrecisionParameter() { return precisionParameter; } @Override public void drawValues() { double[] tipTraits = (double[]) tipTrait.getTrait(treeLikelihood.getTree(), null); tipValues = dataModel.transformTreeTraits(tipTraits); if (DEBUG) { System.err.println("tipValues: " + new WrappedVector.Raw(tipValues)); } } private static final boolean DEBUG = false; } }
package experimentalcode.erich.approxknn; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import de.lmu.ifi.dbs.elki.algorithm.outlier.KNNOutlier; import de.lmu.ifi.dbs.elki.algorithm.outlier.lof.LOF; import de.lmu.ifi.dbs.elki.data.NumberVector; import de.lmu.ifi.dbs.elki.data.type.TypeUtil; import de.lmu.ifi.dbs.elki.database.Database; import de.lmu.ifi.dbs.elki.database.StaticArrayDatabase; import de.lmu.ifi.dbs.elki.database.ids.DBIDIter; import de.lmu.ifi.dbs.elki.database.ids.DBIDUtil; import de.lmu.ifi.dbs.elki.database.ids.DBIDs; import de.lmu.ifi.dbs.elki.database.ids.HashSetModifiableDBIDs; import de.lmu.ifi.dbs.elki.database.relation.Relation; import de.lmu.ifi.dbs.elki.datasource.AbstractDatabaseConnection; import de.lmu.ifi.dbs.elki.datasource.FileBasedDatabaseConnection; import de.lmu.ifi.dbs.elki.datasource.filter.ClassLabelFilter; import de.lmu.ifi.dbs.elki.distance.distancefunction.DistanceFunction; import de.lmu.ifi.dbs.elki.distance.distancefunction.minkowski.ManhattanDistanceFunction; import de.lmu.ifi.dbs.elki.evaluation.roc.ROC; import de.lmu.ifi.dbs.elki.index.preprocessed.knn.MaterializeKNNPreprocessor; import de.lmu.ifi.dbs.elki.index.preprocessed.knn.RandomSampleKNNPreprocessor; import de.lmu.ifi.dbs.elki.logging.Logging; import de.lmu.ifi.dbs.elki.logging.progress.FiniteProgress; import de.lmu.ifi.dbs.elki.math.geometry.XYCurve; import de.lmu.ifi.dbs.elki.persistent.AbstractPageFileFactory; import de.lmu.ifi.dbs.elki.result.ResultUtil; import de.lmu.ifi.dbs.elki.result.outlier.OutlierResult; import de.lmu.ifi.dbs.elki.utilities.ClassGenericsUtil; import de.lmu.ifi.dbs.elki.utilities.DatabaseUtil; import de.lmu.ifi.dbs.elki.utilities.FormatUtil; import de.lmu.ifi.dbs.elki.utilities.RandomFactory; import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameterization.ListParameterization; /** * Simple experiment to estimate the effects of approximating the kNN distances. * * @author Erich Schubert */ public class RandomSampleKNNExperiment { private static final Logging LOG = Logging.getLogger(RandomSampleKNNExperiment.class); DistanceFunction<? super NumberVector> distanceFunction = ManhattanDistanceFunction.STATIC; private void run() { Database database = loadDatabase(); Relation<NumberVector> rel = database.getRelation(TypeUtil.NUMBER_VECTOR_FIELD); DBIDs ids = rel.getDBIDs(); HashSetModifiableDBIDs pos = DBIDUtil.newHashSet(); // Number of iterations and step size final int iters = 10; final int step = 1; final int maxk = iters * step; // Build positive ids (outliers) once. { Pattern p = Pattern.compile("Outlier", Pattern.CASE_INSENSITIVE); Relation<String> srel = DatabaseUtil.guessLabelRepresentation(database); for(DBIDIter id = ids.iter(); id.valid(); id.advance()) { String s = srel.get(id); if(s == null) { LOG.warning("Object without label: " + id); } else if(p.matcher(s).matches()) { pos.add(id); } } } ROC.DBIDsTest positive = new ROC.DBIDsTest(pos); // Collect the data for output double[][] data = new double[iters][6]; // Results for full kNN: { // Setup preprocessor MaterializeKNNPreprocessor.Factory<NumberVector> ppf = new MaterializeKNNPreprocessor.Factory<>(maxk + 1, distanceFunction); MaterializeKNNPreprocessor<NumberVector> pp = ppf.instantiate(rel); database.addIndex(pp); { FiniteProgress prog = LOG.isVerbose() ? new FiniteProgress("kNN iterations", iters, LOG) : null; for(int i = 1; i <= iters; i++) { final int k = i * step; KNNOutlier<NumberVector> knn = new KNNOutlier<>(distanceFunction, k); OutlierResult res = knn.run(database, rel); XYCurve roccurve = ROC.materializeROC(positive, new ROC.OutlierScoreAdapter(res)); double auc = XYCurve.areaUnderCurve(roccurve); data[i - 1][0] = auc; LOG.incrementProcessed(prog); } LOG.ensureCompleted(prog); } { FiniteProgress prog = LOG.isVerbose() ? new FiniteProgress("LOF iterations", iters, LOG) : null; for(int i = 1; i <= iters; i++) { final int k = i * step; LOF<NumberVector> lof = new LOF<>(k, distanceFunction); OutlierResult res = lof.run(database, rel); XYCurve roccurve = ROC.materializeROC(positive, new ROC.OutlierScoreAdapter(res)); double auc = XYCurve.areaUnderCurve(roccurve); data[i - 1][3] = auc; LOG.incrementProcessed(prog); } LOG.ensureCompleted(prog); } // Remove the preprocessor again. database.removeIndex(pp); ResultUtil.removeRecursive(database.getHierarchy(), pp); // Trigger GC cleanup pp = null; ppf = null; System.gc(); } // Partial kNN outlier { FiniteProgress prog = LOG.isVerbose() ? new FiniteProgress("Approximations.", iters - 1, LOG) : null; for(int i = 1; i < iters; i++) { final int k = i * step; double share = i / (double) iters; // Setup preprocessor RandomSampleKNNPreprocessor.Factory<NumberVector> ppf = new RandomSampleKNNPreprocessor.Factory<>(maxk + 1, distanceFunction, share, new RandomFactory(1L)); RandomSampleKNNPreprocessor<NumberVector> pp = ppf.instantiate(rel); database.addIndex(pp); // Max k kNNOutlier run { KNNOutlier<NumberVector> knn = new KNNOutlier<>(distanceFunction, maxk); OutlierResult res = knn.run(database, rel); XYCurve roccurve = ROC.materializeROC(positive, new ROC.OutlierScoreAdapter(res)); double auc = XYCurve.areaUnderCurve(roccurve); data[i - 1][1] = auc; } // Scaled k kNNOutlier run { KNNOutlier<NumberVector> knn = new KNNOutlier<>(distanceFunction, k); OutlierResult res = knn.run(database, rel); XYCurve roccurve = ROC.materializeROC(positive, new ROC.OutlierScoreAdapter(res)); double auc = XYCurve.areaUnderCurve(roccurve); data[i - 1][2] = auc; } // Max k LOF run { LOF<NumberVector> lof = new LOF<>(maxk, distanceFunction); OutlierResult res = lof.run(database, rel); XYCurve roccurve = ROC.materializeROC(positive, new ROC.OutlierScoreAdapter(res)); double auc = XYCurve.areaUnderCurve(roccurve); data[i - 1][4] = auc; } // Scaled k LOF run { LOF<NumberVector> lof = new LOF<>(k, distanceFunction); OutlierResult res = lof.run(database, rel); XYCurve roccurve = ROC.materializeROC(positive, new ROC.OutlierScoreAdapter(res)); double auc = XYCurve.areaUnderCurve(roccurve); data[i - 1][5] = auc; } // Remove preprocessor database.removeIndex(pp); ResultUtil.removeRecursive(database.getHierarchy(), pp); // Trigger GC cleanup pp = null; ppf = null; System.gc(); LOG.incrementProcessed(prog); System.out.println(k + " " + FormatUtil.format(data[i - 1], " ")); } LOG.ensureCompleted(prog); } for(int i = 1; i < iters; i++) { final int k = i * step; System.out.println(k + " " + FormatUtil.format(data[i - 1], " ")); } } private Database loadDatabase() { try { ListParameterization dbpar = new ListParameterization(); // Input file dbpar.addParameter(FileBasedDatabaseConnection.Parameterizer.INPUT_ID, "/nfs/multimedia/images/ALOI/ColorHistograms/outlier/aloi-27d-75000-max4-tot717.csv.gz"); // Index dbpar.addParameter(StaticArrayDatabase.Parameterizer.INDEX_ID, "tree.spatial.rstarvariants.rstar.RStarTreeFactory"); dbpar.addParameter(AbstractPageFileFactory.Parameterizer.PAGE_SIZE_ID, "10000"); // Class label filter List<Object> list = new ArrayList<>(1); list.add(ClassLabelFilter.class); dbpar.addParameter(AbstractDatabaseConnection.Parameterizer.FILTERS_ID, list); dbpar.addParameter(ClassLabelFilter.Parameterizer.CLASS_LABEL_INDEX_ID, 2); // Instantiate Database db = ClassGenericsUtil.tryInstantiate(Database.class, StaticArrayDatabase.class, dbpar); db.initialize(); return db; } catch(Exception e) { throw new RuntimeException("Cannot load database.", e); } } public static void main(String[] args) { // LoggingConfiguration.setDefaultLevel(Level.INFO); // logger.getWrappedLogger().setLevel(Level.INFO); try { new RandomSampleKNNExperiment().run(); } catch(Exception e) { LOG.exception(e); } } }
package fr.adrienbrault.idea.symfony2plugin.routing; import com.intellij.codeInsight.lookup.LookupElement; import com.intellij.psi.*; import com.jetbrains.php.lang.psi.elements.StringLiteralExpression; import fr.adrienbrault.idea.symfony2plugin.Symfony2ProjectComponent; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * @author Adrien Brault <adrien.brault@gmail.com> */ public class RouteReference extends PsiReferenceBase<PsiElement> implements PsiPolyVariantReference { private String routeName; public RouteReference(@NotNull StringLiteralExpression element) { super(element); this.routeName = element.getContents(); } @NotNull @Override public ResolveResult[] multiResolve(boolean incompleteCode) { List<ResolveResult> results = new ArrayList<ResolveResult>(); for (PsiElement psiElement : RouteHelper.getMethods(this.getElement().getProject(), this.routeName)) { results.add(new PsiElementResolveResult(psiElement)); } return results.toArray(new ResolveResult[results.size()]); } @Nullable @Override public PsiElement resolve() { return null; } @NotNull @Override public Object[] getVariants() { Symfony2ProjectComponent symfony2ProjectComponent = getElement().getProject().getComponent(Symfony2ProjectComponent.class); Map<String,Route> routes = symfony2ProjectComponent.getRoutes(); List<LookupElement> lookupElements = new ArrayList<LookupElement>(); for (Route route : routes.values()) { lookupElements.add(new RouteLookupElement(route)); } return lookupElements.toArray(); } }
package de.htwg.gobang.ui; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.AbstractButton; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import de.htwg.gobang.controller.GbLogic; import de.htwg.gobang.entities.GameToken; import de.htwg.gobang.entities.TokenBlack; import de.htwg.gobang.entities.TokenWhite; import java.awt.BorderLayout; import java.awt.Color; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.util.Enumeration; public class GUI extends JFrame implements ActionListener{ private static final long serialVersionUID = 1L; private GbLogic myGame; private GameToken player1; private GameToken player2; private GameToken cPlayer; private int cp1 = 0; private int cp2 = 0; private GridBagConstraints g; private JPanel gameField; private JMenuItem newGame; private JMenuItem help; private JMenuItem exit; private JMenuItem menuRound; private ButtonGroup group; private JButton position; private JButton lastPosition; private JButton remove; private JButton newRound; private JLabel currentPlayerLabelText; private JLabel player1LabelText; private JLabel player2LabelText; private static final int LENGTH = 20; private static final int ZERO = 0; private static final int ONE = 1; private static final int TWO = 2; private static final int THREE = 3; private static final int FOUR = 4; private static final int FIVE = 5; private static final int SIX = 6; private static final int SEVEN = 7; private static final int EIGHT= 8; private static final int NINE = 9; public GUI(){ JPanel choice; JMenuBar menuBar; JMenu menu; JLabel currentPlayerLabel; JLabel wins; JLabel player1Label; JLabel player2Label; this.setTitle("GoBang"); this.setLayout(new BorderLayout()); player1 = new TokenBlack(); player2 = new TokenWhite(); myGame = new GbLogic(player1, player2); cPlayer = myGame.getcPlayer(); //MenuBar menuBar = new JMenuBar(); menu = new JMenu("Menu"); newGame = new JMenuItem("new Game"); help = new JMenuItem("help"); exit = new JMenuItem("exit"); menuRound = new JMenuItem("new Round"); menuBar.add(menu); menuBar.setBackground(Color.WHITE); menu.add(newGame); menu.add(menuRound); menu.add(help); menu.add(exit); this.setJMenuBar(menuBar); //GameField gameField = new JPanel(); gameField.setLayout(new GridBagLayout()); group = new ButtonGroup(); g = new GridBagConstraints(); g.fill = GridBagConstraints.HORIZONTAL; g.ipadx = FIVE; g.ipady = FIVE; g.weightx = EIGHT; for(int i = 1; i < LENGTH; i++){ for(int k = 1; k < LENGTH; k++){ g.gridx = i; g.gridy = k; position = new JButton(); position.setName(i + "," + k); gameField.add(position ,g); position.addActionListener(this); group.add(position); } } g.gridx = LENGTH; g.gridy = ZERO; gameField.add(new JLabel(" ") ,g); g.gridx = LENGTH; g.gridy = LENGTH; gameField.add(new JLabel(" ") ,g); g.gridx = ZERO; g.gridy = LENGTH; gameField.add(new JLabel(" ") ,g); //Choice choice = new JPanel(); choice.setLayout(new GridBagLayout()); currentPlayerLabel = new JLabel("current Player: "); currentPlayerLabelText = new JLabel(cPlayer.getName()); JLabel fakeLabel = new JLabel("black"); fakeLabel.setForeground(new JButton().getBackground()); wins = new JLabel("Wins: "); player1Label = new JLabel("Player blue"); player2Label = new JLabel("Player black"); player1LabelText = new JLabel(new Integer(cp1).toString()); player2LabelText = new JLabel(new Integer(cp2).toString()); remove = new JButton("remove last token"); newRound = new JButton("new round"); newRound.setEnabled(false); GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.HORIZONTAL; c.ipadx = FIVE; c.ipady = FIVE; c.weightx = ONE; c.gridx = ZERO; c.gridy = ZERO; choice.add(currentPlayerLabel,c); c.gridx = ONE; c.gridy = ZERO; choice.add(currentPlayerLabelText,c); c.gridx = ONE; c.gridy = ONE; choice.add(fakeLabel, c); c.gridx = ZERO; c.gridy = TWO; choice.add(new JLabel(" "),c); c.gridx = ZERO; c.gridy = THREE; choice.add(wins,c); c.gridx = ZERO; c.gridy = FOUR; choice.add(player1Label, c); c.gridx = ONE; c.gridy = FOUR; choice.add(player1LabelText, c); c.gridx = ZERO; c.gridy = FIVE; choice.add(player2Label, c); c.gridx = ONE; c.gridy = FIVE; choice.add(player2LabelText, c); c.gridx = ZERO; c.gridy = SIX; choice.add(new JLabel(" "),c); c.gridx = ZERO; c.gridy = SEVEN; choice.add(remove, c); c.gridx = ZERO; c.gridy = EIGHT; choice.add(new JLabel(" "),c); c.gridx = ZERO; c.gridy = NINE; choice.add(newRound, c); c.gridx = FIVE; c.gridy = ZERO; choice.add(new JLabel(" "),c); remove.addActionListener(this); newRound.addActionListener(this); help.addActionListener(this); newGame.addActionListener(this); exit.addActionListener(this); menuRound.addActionListener(this); this.add(gameField, BorderLayout.CENTER); this.add(choice, BorderLayout.EAST); this.pack(); this.setResizable(false); this.setVisible(true); this.setDefaultCloseOperation(EXIT_ON_CLOSE); } public static void main(String[] args) { new GUI(); } @Override public void actionPerformed(ActionEvent e) { if(e.getSource() == this.remove) { myGame.removeToken(); lastPosition.setBackground(new JButton().getBackground()); } else if(e.getSource() == this.newRound) { createGame(); return; } else if (e.getSource() == this.newGame) { newGame(); } else if (e.getSource() == this.exit) { System.exit(0); } else if (e.getSource() == this.help) { help(); } else if (e.getSource() == this.menuRound){ createGame(); } else { position = (JButton) e.getSource(); lastPosition = position; putStone(position); } currentPlayerLabelText.setText(myGame.getcPlayer().getName()); } private void help() { JOptionPane.showMessageDialog(null, "Go Bang is a strategy board game for two players from Japane. " + "\nIt is played on a board of 19 x 19 fields. The players aim to align five " + "\nstones of the same token suite in vertical, horizontal or diagonal lines.", "Help", JOptionPane.OK_OPTION); } private void putStone(JButton tposition) { cPlayer = myGame.getcPlayer(); String[] tmp = tposition.getName().split(","); char status = myGame.setToken(Integer.parseInt(tmp[0]), Integer.parseInt(tmp[1])); switch (status) { case 'b': JOptionPane.showMessageDialog(null,"Already used", "Wrong Field", JOptionPane.OK_OPTION); break; case 'e': position.setBackground(cPlayer.getColor()); break; case 'g': position.setBackground(cPlayer.getColor()); JOptionPane.showMessageDialog(null,"Player " + cPlayer.getName() + " you won!", "Win", JOptionPane.OK_OPTION); if (cPlayer == player1) { cp1 += 1; player1LabelText.setText(new Integer(cp1).toString()); } else { cp2 += 1; player2LabelText.setText(new Integer(cp2).toString()); } changeButtons(false); newRound.setEnabled(true); break; default: break; } } private void changeButtons(boolean state){ Enumeration<AbstractButton> tbutton = group.getElements(); AbstractButton e = tbutton.nextElement(); try { if (state){ do { e.setEnabled(state); e.setBackground(new JButton().getBackground()); e = tbutton.nextElement(); } while (e != null); } else { do { e.setEnabled(state); e = tbutton.nextElement(); } while (e != null); } } catch (Exception NoSuchElementException) { } this.remove.setEnabled(state); this.newRound.setEnabled(false); currentPlayerLabelText.setVisible(state); } private void createGame() { if (cPlayer == player1){ myGame = new GbLogic(player1, player2); } else { myGame = new GbLogic(player2, player1); } myGame.reset(); changeButtons(true); currentPlayerLabelText.setText(cPlayer.getName()); } private void newGame(){ createGame(); cp1 = 0; cp2 = 0; player1LabelText.setText(new Integer(cp1).toString()); player2LabelText.setText(new Integer(cp2).toString()); } }
import java.util.*; /** * Your implementation of a naive bayes classifier. Please implement all four methods. */ public class NaiveBayesClassifierImpl implements NaiveBayesClassifier { private static final double DELTA = 0.00001; private int vocabularySize; private SpamProbability totalProbability; private Map<String, SpamProbability> spamProbabilities; /** * Trains the classifier with the provided training data and vocabulary size */ @Override public void train(Instance[] trainingData, int v) { this.vocabularySize = v; this.totalProbability = new SpamProbability(""); this.spamProbabilities = new HashMap<String, SpamProbability>(vocabularySize); for (Instance instance : trainingData) { // Set<String> words = new HashSet<String>(); for (String word : instance.words) { SpamProbability probability = spamProbabilities.get(word); if (probability == null) { probability = new SpamProbability(word); spamProbabilities.put(word, probability); } // if (!words.contains(word)) { if(Label.SPAM.equals(instance.label)) { probability.spamCount++; } probability.totalCount++; // words.add(word); } if(Label.SPAM.equals(instance.label)) { totalProbability.spamCount++; } totalProbability.totalCount++; } } /** * Returns the prior probability of the label parameter, i.e. P(SPAM) or P(HAM) */ @Override public double p_l(Label label) { return (Label.SPAM.equals(label)?totalProbability.spamCount:(totalProbability.totalCount-totalProbability.spamCount))/(double)totalProbability.totalCount; } /** * Returns the smoothed conditional probability of the word given the label, * i.e. P(word|SPAM) or P(word|HAM) */ @Override public double p_w_given_l(String word, Label label) { SpamProbability probability = spamProbabilities.get(word); if (probability == null) { return 0; } else { return ((Label.SPAM.equals(label)?probability.spamCount:(probability.totalCount-probability.spamCount))+DELTA)/((double)probability.totalCount + vocabularySize*DELTA); } } /** * Classifies an array of words as either SPAM or HAM. */ @Override public Label classify(String[] words) { // Implement return null; } /** * Print out 5 most informative words. */ public void show_informative_5words() { PriorityQueue<SpamProbability> maxQueue = new PriorityQueue<SpamProbability>(vocabularySize); for (SpamProbability spamProbability : spamProbabilities.values()) { maxQueue.add(spamProbability); } for (int i = 0; i < 5 && !maxQueue.isEmpty(); i++) { SpamProbability spamProbability = maxQueue.poll(); System.out.println(spamProbability.value + " " + spamProbability.informativeness()); } } }
package imj3.tools; import static net.sourceforge.aprog.tools.Tools.baseName; import java.awt.Image; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileOutputStream; import java.util.Date; import javax.imageio.ImageIO; import imj2.draft.AutoCloseableImageWriter; import imj3.core.Image2D; import net.sourceforge.aprog.tools.Canvas; import net.sourceforge.aprog.tools.CommandLineArgumentsParser; import net.sourceforge.aprog.tools.IllegalInstantiationException; import net.sourceforge.aprog.tools.TicToc; import net.sourceforge.aprog.tools.Tools; /** * @author codistmonk (creation 2015-03-04) */ public final class Multifile2JPG { private Multifile2JPG() { throw new IllegalInstantiationException(); } /** * @param commandLineArguments * <br>Must not be null * @throws Exception */ public static final void main(final String[] commandLineArguments) { final CommandLineArgumentsParser arguments = new CommandLineArgumentsParser(commandLineArguments); final String filePath = arguments.get("file", ""); final int[] lods = arguments.get("lod", 4); final String format = "jpg"; final float compressionQuality = 0.95F; for (final int lod : lods) { final File outputFile = new File(baseName(filePath) + "_lod" + lod + "." + format); if (outputFile.exists()) { final TicToc timer = new TicToc(); Tools.debugPrint("Testing", outputFile, "(AWT)", new Date(timer.tic())); try { final BufferedImage image = ImageIO.read(outputFile); Tools.debugPrint(image.getWidth(), image.getHeight(), image.getType()); Tools.debugPrint("Testing done in", timer.toc(), "ms"); continue; } catch (final Exception exception) { exception.printStackTrace(); } } final TicToc timer = new TicToc(); Tools.debugPrint(new Date(timer.tic())); Tools.debugPrint("Processing", filePath, "at LOD", lod); final Image2D image = new MultifileImage2D(new MultifileSource(filePath), lod); final int width = image.getWidth(); final int height = image.getHeight(); final int optimalTileWidth = image.getOptimalTileWidth(); final int optimalTileHeight = image.getOptimalTileHeight(); final Canvas canvas = new Canvas().setFormat(width, height, BufferedImage.TYPE_INT_ARGB); for (int tileY = 0; tileY < height; tileY += optimalTileHeight) { for (int tileX = 0; tileX < width; tileX += optimalTileWidth) { canvas.getGraphics().drawImage((Image) image.getTile(tileX, tileY).toAwt(), tileX, tileY, null); } } Tools.debugPrint("Writing", outputFile); try (final AutoCloseableImageWriter imageWriter = new AutoCloseableImageWriter(format) .setCompressionQuality(compressionQuality).setOutput(new FileOutputStream(outputFile))) { imageWriter.write(canvas.getImage()); } catch (final Exception exception) { exception.printStackTrace(); } Tools.debugPrint("Processing done in", timer.toc(), "ms"); } } }
package io.branch.referral; import java.util.Collection; import java.util.Iterator; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.Semaphore; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.content.Context; import android.net.Uri; import android.os.Handler; import android.util.Log; public class Branch { public static String FEATURE_TAG_SHARE = "share"; public static String FEATURE_TAG_REFERRAL = "referral"; public static String FEATURE_TAG_INVITE = "invite"; public static String FEATURE_TAG_DEAL = "deal"; public static String FEATURE_TAG_GIFT = "gift"; private static final int SESSION_KEEPALIVE = 5000; private static final int INTERVAL_RETRY = 3000; private static final int MAX_RETRIES = 5; private static Branch branchReferral_; private boolean isInit_; private BranchReferralInitListener initSessionFinishedCallback_; private BranchReferralInitListener initIdentityFinishedCallback_; private BranchReferralStateChangedListener stateChangedCallback_; private BranchLinkCreateListener linkCreateCallback_; private BranchListResponseListener creditHistoryCallback_; private BranchRemoteInterface kRemoteInterface_; private PrefHelper prefHelper_; private SystemObserver systemObserver_; private Context context_; private Timer closeTimer; private boolean keepAlive_; private Semaphore serverSema_; private ServerRequestQueue requestQueue_; private int networkCount_; private int retryCount_; private boolean initFinished_; private boolean hasNetwork_; private boolean debug_; private Branch(Context context) { prefHelper_ = PrefHelper.getInstance(context); kRemoteInterface_ = new BranchRemoteInterface(context); systemObserver_ = new SystemObserver(context); kRemoteInterface_.setNetworkCallbackListener(new ReferralNetworkCallback()); requestQueue_ = ServerRequestQueue.getInstance(context); serverSema_ = new Semaphore(1); closeTimer = new Timer(); keepAlive_ = false; isInit_ = false; networkCount_ = 0; initFinished_ = false; hasNetwork_ = true; debug_ = false; } public static Branch getInstance(Context context, String key) { if (branchReferral_ == null) { branchReferral_ = Branch.initInstance(context); } branchReferral_.context_ = context; branchReferral_.prefHelper_.setAppKey(key); return branchReferral_; } public static Branch getInstance(Context context) { if (branchReferral_ == null) { branchReferral_ = Branch.initInstance(context); } branchReferral_.context_ = context; return branchReferral_; } private static Branch initInstance(Context context) { return new Branch(context.getApplicationContext()); } public void resetUserSession() { isInit_ = false; } // if you want to flag debug, call this before initUserSession public void setDebug() { debug_ = true; } @Deprecated public void initUserSession(BranchReferralInitListener callback) { initSession(callback); } public void initSession(BranchReferralInitListener callback) { if (systemObserver_.getUpdateState() == 0 && !hasUser()) { prefHelper_.setIsReferrable(); } else { prefHelper_.clearIsReferrable(); } initUserSessionInternal(callback); } @Deprecated public void initUserSession(BranchReferralInitListener callback, Uri data) { initSession(callback, data); } public void initSession(BranchReferralInitListener callback, Uri data) { if (data != null) { if (data.getQueryParameter("link_click_id") != null) { prefHelper_.setLinkClickIdentifier(data.getQueryParameter("link_click_id")); } } initSession(callback); } @Deprecated public void initUserSession() { initSession(); } public void initSession() { initSession(null); } @Deprecated public void initUserSessionWithData(Uri data) { initSessionWithData(data); } public void initSessionWithData(Uri data) { if (data != null) { if (data.getQueryParameter("link_click_id") != null) { prefHelper_.setLinkClickIdentifier(data.getQueryParameter("link_click_id")); } } initSession(null); } @Deprecated public void initUserSession(boolean isReferrable) { initSession(isReferrable); } public void initSession(boolean isReferrable) { initSession(null, isReferrable); } @Deprecated public void initUserSession(BranchReferralInitListener callback, boolean isReferrable, Uri data) { initSession(callback, isReferrable, data); } public void initSession(BranchReferralInitListener callback, boolean isReferrable, Uri data) { if (data != null) { if (data.getQueryParameter("link_click_id") != null) { prefHelper_.setLinkClickIdentifier(data.getQueryParameter("link_click_id")); } } initSession(callback, isReferrable); } @Deprecated public void initUserSession(BranchReferralInitListener callback, boolean isReferrable) { initSession(callback, isReferrable); } public void initSession(BranchReferralInitListener callback, boolean isReferrable) { if (isReferrable) { this.prefHelper_.setIsReferrable(); } else { this.prefHelper_.clearIsReferrable(); } initUserSessionInternal(callback); } private void initUserSessionInternal(BranchReferralInitListener callback) { initSessionFinishedCallback_ = callback; if (!isInit_) { new Thread(new Runnable() { @Override public void run() { initializeSession(); } }).start(); isInit_ = true; } else { boolean installOrOpenInQueue = requestQueue_.containsInstallOrOpen(); if (hasUser() && hasSession() && !installOrOpenInQueue) { if (callback != null) callback.onInitFinished(new JSONObject()); } else { if (!installOrOpenInQueue) { new Thread(new Runnable() { @Override public void run() { initializeSession(); } }).start(); } else { processNextQueueItem(); } } } } public void closeSession() { if (keepAlive_) { return; } // else, real close isInit_ = false; if (!hasNetwork_) { // if there's no network connectivity, purge the old install/open ServerRequest req = requestQueue_.peek(); if (req != null && (req.getTag().equals(BranchRemoteInterface.REQ_TAG_REGISTER_INSTALL) || req.getTag().equals(BranchRemoteInterface.REQ_TAG_REGISTER_OPEN))) { requestQueue_.dequeue(); } } else { new Thread(new Runnable() { @Override public void run() { requestQueue_.enqueue(new ServerRequest(BranchRemoteInterface.REQ_TAG_REGISTER_CLOSE, null)); if (initFinished_ || !hasNetwork_) { processNextQueueItem(); } } }).start(); } } @Deprecated public void identifyUser(String userId, BranchReferralInitListener callback) { setIdentity(userId, callback); } public void setIdentity(String userId, BranchReferralInitListener callback) { initIdentityFinishedCallback_ = callback; setIdentity(userId); } @Deprecated public void identifyUser(final String userId) { setIdentity(userId); } public void setIdentity(final String userId) { if (userId == null || userId.length() == 0) { return; } new Thread(new Runnable() { @Override public void run() { JSONObject post = new JSONObject(); try { post.put("app_id", prefHelper_.getAppKey()); post.put("identity_id", prefHelper_.getIdentityID()); post.put("identity", userId); } catch (JSONException ex) { ex.printStackTrace(); return; } requestQueue_.enqueue(new ServerRequest(BranchRemoteInterface.REQ_TAG_IDENTIFY, post)); if (initFinished_ || !hasNetwork_) { processNextQueueItem(); } } }).start(); } @Deprecated public void clearUser() { logout(); } public void logout() { new Thread(new Runnable() { @Override public void run() { JSONObject post = new JSONObject(); try { post.put("app_id", prefHelper_.getAppKey()); post.put("session_id", prefHelper_.getSessionID()); } catch (JSONException ex) { ex.printStackTrace(); return; } requestQueue_.enqueue(new ServerRequest(BranchRemoteInterface.REQ_TAG_LOGOUT, post)); if (initFinished_ || !hasNetwork_) { processNextQueueItem(); } } }).start(); } public void loadActionCounts() { loadActionCounts(null); } public void loadActionCounts(BranchReferralStateChangedListener callback) { stateChangedCallback_ = callback; new Thread(new Runnable() { @Override public void run() { requestQueue_.enqueue(new ServerRequest(BranchRemoteInterface.REQ_TAG_GET_REFERRAL_COUNTS, null)); if (initFinished_ || !hasNetwork_) { processNextQueueItem(); } } }).start(); } public void loadRewards() { loadRewards(null); } public void loadRewards(BranchReferralStateChangedListener callback) { stateChangedCallback_ = callback; new Thread(new Runnable() { @Override public void run() { requestQueue_.enqueue(new ServerRequest(BranchRemoteInterface.REQ_TAG_GET_REWARDS, null)); if (initFinished_ || !hasNetwork_) { processNextQueueItem(); } } }).start(); } public int getCredits() { return prefHelper_.getCreditCount(); } public int getCreditsForBucket(String bucket) { return prefHelper_.getCreditCount(bucket); } public int getTotalCountsForAction(String action) { return prefHelper_.getActionTotalCount(action); } public int getUniqueCountsForAction(String action) { return prefHelper_.getActionUniqueCount(action); } public void redeemRewards(int count) { redeemRewards("default", count); } public void redeemRewards(final String bucket, final int count) { new Thread(new Runnable() { @Override public void run() { int creditsToRedeem = 0; int credits = prefHelper_.getCreditCount(bucket); if (count > credits) { creditsToRedeem = credits; Log.i("BranchSDK", "Branch Warning: You're trying to redeem more credits than are available. Have you updated loaded rewards"); } else { creditsToRedeem = count; } if (creditsToRedeem > 0) { retryCount_ = 0; JSONObject post = new JSONObject(); try { post.put("app_id", prefHelper_.getAppKey()); post.put("identity_id", prefHelper_.getIdentityID()); post.put("bucket", bucket); post.put("amount", creditsToRedeem); } catch (JSONException ex) { ex.printStackTrace(); return; } requestQueue_.enqueue(new ServerRequest(BranchRemoteInterface.REQ_TAG_REDEEM_REWARDS, post)); if (initFinished_ || !hasNetwork_) { processNextQueueItem(); } } } }).start(); } public void getCreditHistory(BranchListResponseListener callback) { getCreditHistory(null, null, 100, CreditHistoryOrder.kMostRecentFirst, callback); } public void getCreditHistory(final String bucket, BranchListResponseListener callback) { getCreditHistory(bucket, null, 100, CreditHistoryOrder.kMostRecentFirst, callback); } public void getCreditHistory(final String afterId, final int length, final CreditHistoryOrder order, BranchListResponseListener callback) { getCreditHistory(null, afterId, length, order, callback); } public void getCreditHistory(final String bucket, final String afterId, final int length, final CreditHistoryOrder order, BranchListResponseListener callback) { creditHistoryCallback_ = callback; new Thread(new Runnable() { @Override public void run() { JSONObject post = new JSONObject(); try { post.put("app_id", prefHelper_.getAppKey()); post.put("identity_id", prefHelper_.getIdentityID()); post.put("length", length); post.put("direction", order.ordinal()); if (bucket != null) { post.put("bucket", bucket); } if (afterId != null) { post.put("begin_after_id", afterId); } } catch (JSONException ex) { ex.printStackTrace(); return; } requestQueue_.enqueue(new ServerRequest(BranchRemoteInterface.REQ_TAG_GET_REWARD_HISTORY, post)); if (initFinished_ || !hasNetwork_) { processNextQueueItem(); } } }).start(); } public void userCompletedAction(final String action, final JSONObject metadata) { new Thread(new Runnable() { @Override public void run() { retryCount_ = 0; JSONObject post = new JSONObject(); try { post.put("app_id", prefHelper_.getAppKey()); post.put("session_id", prefHelper_.getSessionID()); post.put("event", action); if (metadata != null) post.put("metadata", metadata); } catch (JSONException ex) { ex.printStackTrace(); return; } requestQueue_.enqueue(new ServerRequest(BranchRemoteInterface.REQ_TAG_COMPLETE_ACTION, post)); if (initFinished_ || !hasNetwork_) { processNextQueueItem(); } } }).start(); } public void userCompletedAction(final String action) { userCompletedAction(action, null); } @Deprecated public JSONObject getInstallReferringParams() { return getFirstReferringParams(); } public JSONObject getFirstReferringParams() { String storedParam = prefHelper_.getInstallParams(); return convertParamsStringToDictionary(storedParam); } @Deprecated public JSONObject getReferringParams() { return getLatestReferringParams(); } public JSONObject getLatestReferringParams() { String storedParam = prefHelper_.getSessionParams(); return convertParamsStringToDictionary(storedParam); } public void getShortUrl(BranchLinkCreateListener callback) { generateShortLink(null, null, null, null, stringifyParams(null), callback); } public void getShortUrl(JSONObject params, BranchLinkCreateListener callback) { generateShortLink(null, null, null, null, stringifyParams(params), callback); } public void getReferralUrl(String channel, JSONObject params, BranchLinkCreateListener callback) { generateShortLink(null, channel, FEATURE_TAG_REFERRAL, null, stringifyParams(params), callback); } public void getReferralUrl(Collection<String> tags, String channel, JSONObject params, BranchLinkCreateListener callback) { generateShortLink(tags, channel, FEATURE_TAG_REFERRAL, null, stringifyParams(params), callback); } public void getContentUrl(String channel, JSONObject params, BranchLinkCreateListener callback) { generateShortLink(null, channel, FEATURE_TAG_SHARE, null, stringifyParams(params), callback); } public void getContentUrl(Collection<String> tags, String channel, JSONObject params, BranchLinkCreateListener callback) { generateShortLink(tags, channel, FEATURE_TAG_SHARE, null, stringifyParams(params), callback); } public void getShortUrl(String channel, String feature, String stage, JSONObject params, BranchLinkCreateListener callback) { generateShortLink(null, channel, feature, stage, stringifyParams(params), callback); } public void getShortUrl(Collection<String> tags, String channel, String feature, String stage, JSONObject params, BranchLinkCreateListener callback) { generateShortLink(tags, channel, feature, stage, stringifyParams(params), callback); } // PRIVATE FUNCTIONS private String stringifyParams(JSONObject params) { if (params == null) { params = new JSONObject(); } try { params.put("source", "android"); } catch (JSONException e) { e.printStackTrace(); } return params.toString(); } private void generateShortLink(final Collection<String> tags, final String channel, final String feature, final String stage, final String params, BranchLinkCreateListener callback) { linkCreateCallback_ = callback; if (hasUser()) { new Thread(new Runnable() { @Override public void run() { JSONObject linkPost = new JSONObject(); try { linkPost.put("app_id", prefHelper_.getAppKey()); linkPost.put("identity_id", prefHelper_.getIdentityID()); if (tags != null) { JSONArray tagArray = new JSONArray(); for (String tag : tags) tagArray.put(tag); linkPost.put("tags", tagArray); } if (channel != null) { linkPost.put("channel", channel); } if (feature != null) { linkPost.put("feature", feature); } if (stage != null) { linkPost.put("stage", stage); } if (params != null) linkPost.put("data", params); } catch (JSONException ex) { ex.printStackTrace(); } requestQueue_.enqueue(new ServerRequest(BranchRemoteInterface.REQ_TAG_GET_CUSTOM_URL, linkPost)); if (initFinished_ || !hasNetwork_) { processNextQueueItem(); } } }).start(); } } private JSONObject convertParamsStringToDictionary(String paramString) { if (paramString.equals(PrefHelper.NO_STRING_VALUE)) { return new JSONObject(); } else { try { return new JSONObject(paramString); } catch (JSONException e) { byte[] encodedArray = Base64.decode(paramString.getBytes(), Base64.NO_WRAP); try { return new JSONObject(new String(encodedArray)); } catch (JSONException ex) { ex.printStackTrace(); return new JSONObject(); } } } } private void processNextQueueItem() { try { serverSema_.acquire(); if (networkCount_ == 0 && requestQueue_.getSize() > 0) { networkCount_ = 1; serverSema_.release(); ServerRequest req = requestQueue_.peek(); if (!req.getTag().equals(BranchRemoteInterface.REQ_TAG_REGISTER_CLOSE)) { keepAlive(); } if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_REGISTER_INSTALL)) { kRemoteInterface_.registerInstall(PrefHelper.NO_STRING_VALUE, debug_); } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_REGISTER_OPEN)) { kRemoteInterface_.registerOpen(debug_); } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_GET_REFERRAL_COUNTS) && hasUser() && hasSession()) { kRemoteInterface_.getReferralCounts(); } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_GET_REWARDS) && hasUser() && hasSession()) { kRemoteInterface_.getRewards(); } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_REDEEM_REWARDS) && hasUser() && hasSession()) { kRemoteInterface_.redeemRewards(req.getPost()); } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_GET_REWARD_HISTORY) && hasUser() && hasSession()) { kRemoteInterface_.getCreditHistory(req.getPost()); } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_COMPLETE_ACTION) && hasUser() && hasSession()){ kRemoteInterface_.userCompletedAction(req.getPost()); } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_GET_CUSTOM_URL) && hasUser() && hasSession()) { kRemoteInterface_.createCustomUrl(req.getPost()); } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_IDENTIFY) && hasUser() && hasSession()) { kRemoteInterface_.identifyUser(req.getPost()); } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_REGISTER_CLOSE) && hasUser() && hasSession()) { kRemoteInterface_.registerClose(); } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_LOGOUT) && hasUser() && hasSession()) { kRemoteInterface_.logoutUser(req.getPost()); } else if (!hasUser()) { if (!hasAppKey() && hasSession()) { Log.i("BranchSDK", "Branch Warning: User session has not been initialized"); } else { networkCount_ = 0; initSession(); } } } else { serverSema_.release(); } } catch (Exception e) { e.printStackTrace(); } } private void handleFailure() { final ServerRequest req = requestQueue_.peek(); Handler mainHandler = new Handler(context_.getMainLooper()); mainHandler.post(new Runnable() { @Override public void run() { if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_REGISTER_INSTALL) || req.getTag().equals(BranchRemoteInterface.REQ_TAG_REGISTER_OPEN) ) { if (initSessionFinishedCallback_ != null) { JSONObject obj = new JSONObject(); try { obj.put("error_message", "Trouble reaching server. Please try again in a few minutes"); } catch(JSONException ex) { ex.printStackTrace(); } initSessionFinishedCallback_.onInitFinished(obj); } } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_GET_REFERRAL_COUNTS) || req.getTag().equals(BranchRemoteInterface.REQ_TAG_GET_REWARDS)) { if (stateChangedCallback_ != null) { stateChangedCallback_.onStateChanged(false); } } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_GET_REWARD_HISTORY)) { if (creditHistoryCallback_ != null) { creditHistoryCallback_.onReceivingResponse(null); } } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_GET_CUSTOM_URL)) { if (linkCreateCallback_ != null) { linkCreateCallback_.onLinkCreate("Trouble reaching server. Please try again in a few minutes"); } } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_IDENTIFY)) { if (initIdentityFinishedCallback_ != null) { JSONObject obj = new JSONObject(); try { obj.put("error_message", "Trouble reaching server. Please try again in a few minutes"); } catch(JSONException ex) { ex.printStackTrace(); } initIdentityFinishedCallback_.onInitFinished(obj); } } } }); } private void retryLastRequest() { retryCount_ = retryCount_ + 1; if (retryCount_ > MAX_RETRIES) { handleFailure(); requestQueue_.dequeue(); retryCount_ = 0; } else { try { Thread.sleep(INTERVAL_RETRY); } catch (InterruptedException e) { e.printStackTrace(); } } } private void updateAllRequestsInQueue() { try { for (int i = 0; i < requestQueue_.getSize(); i++) { ServerRequest req = requestQueue_.peekAt(i); if (req.getPost() != null) { Iterator<?> keys = req.getPost().keys(); while (keys.hasNext()) { String key = (String)keys.next(); if (key.equals("app_id")) { req.getPost().put(key, prefHelper_.getAppKey()); } else if (key.equals("session_id")) { req.getPost().put(key, prefHelper_.getSessionID()); } else if (key.equals("identity_id")) { req.getPost().put(key, prefHelper_.getIdentityID()); } } } } } catch (JSONException e) { e.printStackTrace(); } } private void clearTimer() { if (closeTimer == null) return; closeTimer.cancel(); closeTimer.purge(); closeTimer = new Timer(); } private void keepAlive() { keepAlive_ = true; clearTimer(); closeTimer.schedule(new TimerTask() { @Override public void run() { new Thread(new Runnable() { @Override public void run() { keepAlive_ = false; } }).start(); } }, SESSION_KEEPALIVE); } private boolean hasAppKey() { return !prefHelper_.getAppKey().equals(PrefHelper.NO_STRING_VALUE); } private boolean hasSession() { return !prefHelper_.getSessionID().equals(PrefHelper.NO_STRING_VALUE); } private boolean hasUser() { return !prefHelper_.getIdentityID().equals(PrefHelper.NO_STRING_VALUE); } private void insertRequestAtFront(ServerRequest req) { if (networkCount_ == 0) { requestQueue_.insert(req, 0); } else { requestQueue_.insert(req, 1); } } private void registerInstallOrOpen(String tag) { if (!requestQueue_.containsInstallOrOpen()) { insertRequestAtFront(new ServerRequest(tag)); } else { requestQueue_.moveInstallOrOpenToFront(tag, networkCount_); } processNextQueueItem(); } private void initializeSession() { if (hasUser()) { registerInstallOrOpen(BranchRemoteInterface.REQ_TAG_REGISTER_OPEN); } else { registerInstallOrOpen(BranchRemoteInterface.REQ_TAG_REGISTER_INSTALL); } } private void processReferralCounts(ServerResponse resp) { boolean updateListener = false; Iterator<?> keys = resp.getObject().keys(); while (keys.hasNext()) { String key = (String)keys.next(); try { JSONObject counts = resp.getObject().getJSONObject(key); int total = counts.getInt("total"); int unique = counts.getInt("unique"); if (total != prefHelper_.getActionTotalCount(key) || unique != prefHelper_.getActionUniqueCount(key)) { updateListener = true; } prefHelper_.setActionTotalCount(key, total); prefHelper_.setActionUniqueCount(key, unique); } catch (JSONException e) { e.printStackTrace(); } } final boolean finUpdateListener = updateListener; Handler mainHandler = new Handler(context_.getMainLooper()); mainHandler.post(new Runnable() { @Override public void run() { if (stateChangedCallback_ != null) { stateChangedCallback_.onStateChanged(finUpdateListener); } } }); } private void processRewardCounts(ServerResponse resp) { boolean updateListener = false; Iterator<?> keys = resp.getObject().keys(); while (keys.hasNext()) { String key = (String)keys.next(); try { int credits = resp.getObject().getInt(key); if (credits != prefHelper_.getCreditCount(key)) { updateListener = true; } prefHelper_.setCreditCount(key, credits); } catch (JSONException e) { e.printStackTrace(); } } final boolean finUpdateListener = updateListener; Handler mainHandler = new Handler(context_.getMainLooper()); mainHandler.post(new Runnable() { @Override public void run() { if (stateChangedCallback_ != null) { stateChangedCallback_.onStateChanged(finUpdateListener); } } }); } private void processCreditHistory(final ServerResponse resp) { Handler mainHandler = new Handler(context_.getMainLooper()); mainHandler.post(new Runnable() { @Override public void run() { if (creditHistoryCallback_ != null) { creditHistoryCallback_.onReceivingResponse(resp.getArray()); } } }); } public class ReferralNetworkCallback implements NetworkCallback { @Override public void finished(ServerResponse serverResponse) { if (serverResponse != null) { try { int status = serverResponse.getStatusCode(); String requestTag = serverResponse.getTag(); hasNetwork_ = true; if (status >= 400 && status < 500) { if (serverResponse.getObject().has("error") && serverResponse.getObject().getJSONObject("error").has("message")) { Log.i("BranchSDK", "Branch API Error: " + serverResponse.getObject().getJSONObject("error").getString("message")); } requestQueue_.dequeue(); } else if (status != 200) { if (status == RemoteInterface.NO_CONNECTIVITY_STATUS) { hasNetwork_ = false; handleFailure(); if (requestTag.equals(BranchRemoteInterface.REQ_TAG_REGISTER_CLOSE)) { requestQueue_.dequeue(); } Log.i("BranchSDK", "Branch API Error: " + "poor network connectivity. Please try again later."); } else { retryLastRequest(); } } else if (requestTag.equals(BranchRemoteInterface.REQ_TAG_GET_REFERRAL_COUNTS)) { processReferralCounts(serverResponse); requestQueue_.dequeue(); } else if (requestTag.equals(BranchRemoteInterface.REQ_TAG_GET_REWARDS)) { processRewardCounts(serverResponse); requestQueue_.dequeue(); } else if (requestTag.equals(BranchRemoteInterface.REQ_TAG_GET_REWARD_HISTORY)) { processCreditHistory(serverResponse); requestQueue_.dequeue(); } else if (requestTag.equals(BranchRemoteInterface.REQ_TAG_REGISTER_INSTALL)) { prefHelper_.setDeviceFingerPrintID(serverResponse.getObject().getString("device_fingerprint_id")); prefHelper_.setIdentityID(serverResponse.getObject().getString("identity_id")); prefHelper_.setUserURL(serverResponse.getObject().getString("link")); prefHelper_.setSessionID(serverResponse.getObject().getString("session_id")); prefHelper_.setLinkClickIdentifier(PrefHelper.NO_STRING_VALUE); if (prefHelper_.getIsReferrable() == 1) { if (serverResponse.getObject().has("data")) { String params = serverResponse.getObject().getString("data"); prefHelper_.setInstallParams(params); } else { prefHelper_.setInstallParams(PrefHelper.NO_STRING_VALUE); } } if (serverResponse.getObject().has("link_click_id")) { prefHelper_.setLinkClickID(serverResponse.getObject().getString("link_click_id")); } else { prefHelper_.setLinkClickID(PrefHelper.NO_STRING_VALUE); } if (serverResponse.getObject().has("data")) { String params = serverResponse.getObject().getString("data"); prefHelper_.setSessionParams(params); } else { prefHelper_.setSessionParams(PrefHelper.NO_STRING_VALUE); } updateAllRequestsInQueue(); Handler mainHandler = new Handler(context_.getMainLooper()); mainHandler.post(new Runnable() { @Override public void run() { if (initSessionFinishedCallback_ != null) { initSessionFinishedCallback_.onInitFinished(getLatestReferringParams()); } } }); requestQueue_.dequeue(); initFinished_ = true; } else if (requestTag.equals(BranchRemoteInterface.REQ_TAG_REGISTER_OPEN)) { prefHelper_.setSessionID(serverResponse.getObject().getString("session_id")); prefHelper_.setLinkClickIdentifier(PrefHelper.NO_STRING_VALUE); if (serverResponse.getObject().has("link_click_id")) { prefHelper_.setLinkClickID(serverResponse.getObject().getString("link_click_id")); } else { prefHelper_.setLinkClickID(PrefHelper.NO_STRING_VALUE); } if (prefHelper_.getIsReferrable() == 1) { if (serverResponse.getObject().has("data")) { String params = serverResponse.getObject().getString("data"); prefHelper_.setInstallParams(params); } } if (serverResponse.getObject().has("data")) { String params = serverResponse.getObject().getString("data"); prefHelper_.setSessionParams(params); } else { prefHelper_.setSessionParams(PrefHelper.NO_STRING_VALUE); } Handler mainHandler = new Handler(context_.getMainLooper()); mainHandler.post(new Runnable() { @Override public void run() { if (initSessionFinishedCallback_ != null) { initSessionFinishedCallback_.onInitFinished(getLatestReferringParams()); } } }); requestQueue_.dequeue(); initFinished_ = true; } else if (requestTag.equals(BranchRemoteInterface.REQ_TAG_GET_CUSTOM_URL)) { final String url = serverResponse.getObject().getString("url"); Handler mainHandler = new Handler(context_.getMainLooper()); mainHandler.post(new Runnable() { @Override public void run() { if (linkCreateCallback_ != null) { linkCreateCallback_.onLinkCreate(url); } } }); requestQueue_.dequeue(); } else if (requestTag.equals(BranchRemoteInterface.REQ_TAG_LOGOUT)) { prefHelper_.setSessionID(serverResponse.getObject().getString("session_id")); prefHelper_.setIdentityID(serverResponse.getObject().getString("identity_id")); prefHelper_.setUserURL(serverResponse.getObject().getString("link")); prefHelper_.setInstallParams(PrefHelper.NO_STRING_VALUE); prefHelper_.setSessionParams(PrefHelper.NO_STRING_VALUE); prefHelper_.setIdentity(PrefHelper.NO_STRING_VALUE); prefHelper_.clearUserValues(); requestQueue_.dequeue(); } else if (requestTag.equals(BranchRemoteInterface.REQ_TAG_IDENTIFY)) { prefHelper_.setIdentityID(serverResponse.getObject().getString("identity_id")); prefHelper_.setUserURL(serverResponse.getObject().getString("link")); if (serverResponse.getObject().has("referring_data")) { String params = serverResponse.getObject().getString("referring_data"); prefHelper_.setInstallParams(params); } if (requestQueue_.getSize() > 0) { ServerRequest req = requestQueue_.peek(); if (req.getPost() != null && req.getPost().has("identity")) { prefHelper_.setIdentity(req.getPost().getString("identity")); } } Handler mainHandler = new Handler(context_.getMainLooper()); mainHandler.post(new Runnable() { @Override public void run() { if (initIdentityFinishedCallback_ != null) { initIdentityFinishedCallback_.onInitFinished(getFirstReferringParams()); } } }); requestQueue_.dequeue(); } else { requestQueue_.dequeue(); } networkCount_ = 0; if (hasNetwork_) { processNextQueueItem(); } } catch (JSONException ex) { ex.printStackTrace(); } } } } public interface BranchReferralInitListener { public void onInitFinished(JSONObject referringParams); } public interface BranchReferralStateChangedListener { public void onStateChanged(boolean changed); } public interface BranchLinkCreateListener { public void onLinkCreate(String url); } public interface BranchListResponseListener { public void onReceivingResponse(JSONArray list); } public enum CreditHistoryOrder { kMostRecentFirst, kLeastRecentFirst } }
package net.hyperic.sigar.cmd; import net.hyperic.sigar.SigarException; import net.hyperic.sigar.SigarNotImplementedException; /** * Show process command line arguments. */ public class ShowArgs extends SigarCommandBase { public ShowArgs(Shell shell) { super(shell); } public ShowArgs() { super(); } protected boolean validateArgs(String[] args) { return true; } public String getUsageShort() { return "Show process command line arguments"; } public boolean isPidCompleter() { return true; } public void output(String[] args) throws SigarException { long[] pids = this.shell.findPids(args); for (int i=0; i<pids.length; i++) { try { println("pid=" + pids[i]); output(pids[i]); } catch (SigarException e) { println(e.getMessage()); } println("\n } } public void output(long pid) throws SigarException { String[] argv = this.proxy.getProcArgs(pid); try { String exe = this.proxy.getProcExe(pid).getName(); println("exe=" + exe); } catch (SigarNotImplementedException e) { } catch (SigarException e) { println("exe=???"); } try { String cwd = this.proxy.getProcExe(pid).getCwd(); println("cwd=" + cwd); } catch (SigarNotImplementedException e) { } catch (SigarException e) { println("cwd=???"); } for (int i=0; i<argv.length; i++) { println(" " + i + "=>" + argv[i] + "<="); } } public static void main(String[] args) throws Exception { new ShowArgs().processCommand(args); } }
package gov.nih.nci.calab.service.submit; import gov.nih.nci.calab.db.DataAccessProxy; import gov.nih.nci.calab.db.IDataAccess; import gov.nih.nci.calab.domain.Keyword; import gov.nih.nci.calab.domain.nano.characterization.physical.composition.CarbonNanotubeComposition; import gov.nih.nci.calab.domain.nano.characterization.physical.composition.ComplexComposition; import gov.nih.nci.calab.domain.nano.characterization.physical.composition.DendrimerComposition; import gov.nih.nci.calab.domain.nano.characterization.physical.composition.EmulsionComposition; import gov.nih.nci.calab.domain.nano.characterization.physical.composition.FullereneComposition; import gov.nih.nci.calab.domain.nano.characterization.physical.composition.LiposomeComposition; import gov.nih.nci.calab.domain.nano.characterization.physical.composition.MetalParticleComposition; import gov.nih.nci.calab.domain.nano.characterization.physical.composition.ParticleComposition; import gov.nih.nci.calab.domain.nano.characterization.physical.composition.PolymerComposition; import gov.nih.nci.calab.domain.nano.characterization.physical.composition.QuantumDotComposition; import gov.nih.nci.calab.domain.nano.particle.Nanoparticle; import gov.nih.nci.calab.dto.characterization.composition.CarbonNanotubeBean; import gov.nih.nci.calab.dto.characterization.composition.ComplexParticleBean; import gov.nih.nci.calab.dto.characterization.composition.CompositionBean; import gov.nih.nci.calab.dto.characterization.composition.DendrimerBean; import gov.nih.nci.calab.dto.characterization.composition.EmulsionBean; import gov.nih.nci.calab.dto.characterization.composition.FullereneBean; import gov.nih.nci.calab.dto.characterization.composition.LiposomeBean; import gov.nih.nci.calab.dto.characterization.composition.MetalParticleBean; import gov.nih.nci.calab.dto.characterization.composition.PolymerBean; import gov.nih.nci.calab.dto.characterization.composition.QuantumDotBean; import gov.nih.nci.calab.dto.workflow.FileBean; import gov.nih.nci.calab.exception.CalabException; import gov.nih.nci.calab.service.security.UserService; import gov.nih.nci.calab.service.util.CalabConstants; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; /** * This class includes service calls involved in creating nanoparticles and * adding functions and characterizations for nanoparticles. * * @author pansu * */ public class SubmitNanoparticleService { private static Logger logger = Logger .getLogger(SubmitNanoparticleService.class); /** * Update keywords and visibilities for the particle with the given name and * type * * @param particleType * @param particleName * @param keywords * @param visibilities * @throws Exception */ public void createNanoparticle(String particleType, String particleName, String[] keywords, String[] visibilities) throws Exception { // save nanoparticle to the database IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); // get the existing particle from database created during sample // creation List results = ida.search("from Nanoparticle where name='" + particleName + "' and type='" + particleType + "'"); Nanoparticle particle = null; for (Object obj : results) { particle = (Nanoparticle) obj; } if (particle == null) { throw new CalabException("No such particle in the database"); } particle.getKeywordCollection().clear(); if (keywords != null) { for (String keyword : keywords) { Keyword keywordObj = new Keyword(); keywordObj.setName(keyword); particle.getKeywordCollection().add(keywordObj); } } } catch (Exception e) { ida.rollback(); logger .error("Problem updating particle with name: " + particleName); throw e; } finally { ida.close(); } // remove existing visiblities for the nanoparticle UserService userService = new UserService(CalabConstants.CSM_APP_NAME); List<String> currentVisibilities = userService.getAccessibleGroups( particleName, "R"); for (String visiblity : currentVisibilities) { userService.removeAccessibleGroup(particleName, visiblity, "R"); } // set new visibilities for the nanoparticle for (String visibility : visibilities) { // by default, always set visibility to NCL_PI and NCL_Researcher to // be true userService.secureObject(particleName, "NCL_PI", "R"); userService.secureObject(particleName, "NCL_Researcher", "R"); userService.secureObject(particleName, visibility, "R"); } } /** * Saves the particle composition to the database * * @param particleType * @param particleName * @param composition * @throws Exception */ public void addParticleComposition(String particleType, String particleName, CompositionBean composition) throws Exception { // if ID is not set save to the database otherwise update ParticleComposition doComp = null; if (composition instanceof CarbonNanotubeBean) { doComp = new CarbonNanotubeComposition(); } else if (composition instanceof ComplexParticleBean) { doComp = new ComplexComposition(); } else if (composition instanceof DendrimerBean) { doComp = new DendrimerComposition(); } else if (composition instanceof EmulsionBean) { doComp = new EmulsionComposition(); } else if (composition instanceof FullereneBean) { doComp = new FullereneComposition(); } else if (composition instanceof LiposomeBean) { doComp = new LiposomeComposition(); } else if (composition instanceof QuantumDotBean) { doComp = new QuantumDotComposition(); } else if (composition instanceof MetalParticleBean) { doComp = new MetalParticleComposition(); } else if (composition instanceof PolymerBean) { doComp = new PolymerComposition(); } else { throw new CalabException( "Can't save composition for the given particle type: " + composition.getClass().getName()); } composition.updateDomainObj(doComp); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); Nanoparticle particle = null; int existingViewTitleCount = -1; try { ida.open(); // check if viewTitle is already used String viewTitleQuery = ""; if (doComp.getId() == null) { viewTitleQuery = "select count(achar) from Characterization achar where achar.identificationName='" + doComp.getIdentificationName() + "'"; } else { viewTitleQuery = "select count(achar) from Characterization achar where achar.identificationName='" + doComp.getIdentificationName() + "' and achar.id!=" + doComp.getId(); } List viewTitleResult = ida.search(viewTitleQuery); for (Object obj : viewTitleResult) { existingViewTitleCount = ((Integer) (obj)).intValue(); } if (existingViewTitleCount == 0) { // if ID exists, do update if (doComp.getId() != null) { ida.store(doComp); } else {// get the existing particle and compositions // from database // created // during sample // creation List results = ida .search("select particle from Nanoparticle particle left join fetch particle.characterizationCollection where particle.name='" + particleName + "' and particle.type='" + particleType + "'"); for (Object obj : results) { particle = (Nanoparticle) obj; } if (particle != null) { particle.getCharacterizationCollection().add(doComp); } } } } catch (Exception e) { e.printStackTrace(); ida.rollback(); logger.error("Problem saving composition: "); throw e; } finally { ida.close(); } if (existingViewTitleCount > 0) { throw new CalabException( "The view title is already in use. Please enter a different one."); } } public void saveAssayResult(String particleName, String fileName, String title, String description, String comments, String[] keywords) { } public List<FileBean> getAllRunFiles(String particleName) { List<FileBean> runFiles = new ArrayList<FileBean>(); // TODO fill in the database query code FileBean file = new FileBean(); file.setId("1"); file.setShortFilename("NCL_3_distri.jpg"); runFiles.add(file); return runFiles; } }
package gov.nih.nci.calab.service.submit; import gov.nih.nci.calab.db.DataAccessProxy; import gov.nih.nci.calab.db.HibernateDataAccess; import gov.nih.nci.calab.db.IDataAccess; import gov.nih.nci.calab.domain.Instrument; import gov.nih.nci.calab.domain.InstrumentConfiguration; import gov.nih.nci.calab.domain.Keyword; import gov.nih.nci.calab.domain.LabFile; import gov.nih.nci.calab.domain.LookupType; import gov.nih.nci.calab.domain.MeasureType; import gov.nih.nci.calab.domain.MeasureUnit; import gov.nih.nci.calab.domain.OutputFile; import gov.nih.nci.calab.domain.nano.characterization.Characterization; import gov.nih.nci.calab.domain.nano.characterization.CharacterizationFileType; import gov.nih.nci.calab.domain.nano.characterization.DatumName; import gov.nih.nci.calab.domain.nano.characterization.DerivedBioAssayData; import gov.nih.nci.calab.domain.nano.characterization.DerivedBioAssayDataCategory; import gov.nih.nci.calab.domain.nano.characterization.invitro.CFU_GM; import gov.nih.nci.calab.domain.nano.characterization.invitro.Caspase3Activation; import gov.nih.nci.calab.domain.nano.characterization.invitro.CellLineType; import gov.nih.nci.calab.domain.nano.characterization.invitro.CellViability; import gov.nih.nci.calab.domain.nano.characterization.invitro.Chemotaxis; import gov.nih.nci.calab.domain.nano.characterization.invitro.Coagulation; import gov.nih.nci.calab.domain.nano.characterization.invitro.ComplementActivation; import gov.nih.nci.calab.domain.nano.characterization.invitro.CytokineInduction; import gov.nih.nci.calab.domain.nano.characterization.invitro.EnzymeInduction; import gov.nih.nci.calab.domain.nano.characterization.invitro.Hemolysis; import gov.nih.nci.calab.domain.nano.characterization.invitro.LeukocyteProliferation; import gov.nih.nci.calab.domain.nano.characterization.invitro.NKCellCytotoxicActivity; import gov.nih.nci.calab.domain.nano.characterization.invitro.OxidativeBurst; import gov.nih.nci.calab.domain.nano.characterization.invitro.OxidativeStress; import gov.nih.nci.calab.domain.nano.characterization.invitro.Phagocytosis; import gov.nih.nci.calab.domain.nano.characterization.invitro.PlasmaProteinBinding; import gov.nih.nci.calab.domain.nano.characterization.invitro.PlateletAggregation; import gov.nih.nci.calab.domain.nano.characterization.physical.MolecularWeight; import gov.nih.nci.calab.domain.nano.characterization.physical.Morphology; import gov.nih.nci.calab.domain.nano.characterization.physical.MorphologyType; import gov.nih.nci.calab.domain.nano.characterization.physical.Purity; import gov.nih.nci.calab.domain.nano.characterization.physical.Shape; import gov.nih.nci.calab.domain.nano.characterization.physical.ShapeType; import gov.nih.nci.calab.domain.nano.characterization.physical.Size; import gov.nih.nci.calab.domain.nano.characterization.physical.Solubility; import gov.nih.nci.calab.domain.nano.characterization.physical.SolventType; import gov.nih.nci.calab.domain.nano.characterization.physical.Surface; import gov.nih.nci.calab.domain.nano.characterization.physical.composition.ParticleComposition; import gov.nih.nci.calab.domain.nano.function.Agent; import gov.nih.nci.calab.domain.nano.function.AgentTarget; import gov.nih.nci.calab.domain.nano.function.Function; import gov.nih.nci.calab.domain.nano.function.Linkage; import gov.nih.nci.calab.domain.nano.particle.Nanoparticle; import gov.nih.nci.calab.dto.characterization.CharacterizationBean; import gov.nih.nci.calab.dto.characterization.DatumBean; import gov.nih.nci.calab.dto.characterization.DerivedBioAssayDataBean; import gov.nih.nci.calab.dto.characterization.composition.CompositionBean; import gov.nih.nci.calab.dto.characterization.invitro.CytotoxicityBean; import gov.nih.nci.calab.dto.characterization.physical.MorphologyBean; import gov.nih.nci.calab.dto.characterization.physical.ShapeBean; import gov.nih.nci.calab.dto.characterization.physical.SolubilityBean; import gov.nih.nci.calab.dto.characterization.physical.SurfaceBean; import gov.nih.nci.calab.dto.common.LabFileBean; import gov.nih.nci.calab.dto.function.FunctionBean; import gov.nih.nci.calab.exception.CalabException; import gov.nih.nci.calab.service.common.FileService; import gov.nih.nci.calab.service.security.UserService; import gov.nih.nci.calab.service.util.CaNanoLabConstants; import gov.nih.nci.calab.service.util.PropertyReader; import gov.nih.nci.calab.service.util.StringUtils; import java.io.File; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; /** * This class includes service calls involved in creating nanoparticle general * info and adding functions and characterizations for nanoparticles, as well as * creating reports. * * @author pansu * */ public class SubmitNanoparticleService { private static Logger logger = Logger .getLogger(SubmitNanoparticleService.class); // remove existing visibilities for the data private UserService userService; public SubmitNanoparticleService() throws Exception { userService = new UserService(CaNanoLabConstants.CSM_APP_NAME); } /** * Update keywords and visibilities for the particle with the given name and * type * * @param particleType * @param particleName * @param keywords * @param visibilities * @throws Exception */ public void addParticleGeneralInfo(String particleType, String particleName, String[] keywords, String[] visibilities) throws Exception { // save nanoparticle to the database IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); // get the existing particle from database created during sample // creation List results = ida.search("from Nanoparticle where name='" + particleName + "' and type='" + particleType + "'"); Nanoparticle particle = null; for (Object obj : results) { particle = (Nanoparticle) obj; } if (particle == null) { throw new CalabException("No such particle in the database"); } particle.getKeywordCollection().clear(); if (keywords != null) { for (String keyword : keywords) { Keyword keywordObj = new Keyword(); keywordObj.setName(keyword); particle.getKeywordCollection().add(keywordObj); } } } catch (Exception e) { ida.rollback(); logger .error("Problem updating particle with name: " + particleName); throw e; } finally { ida.close(); } userService.setVisiblity(particleName, visibilities); } /** * Save characterization to the database. * * @param particleType * @param particleName * @param achar * @throws Exception */ private void addParticleCharacterization(String particleType, String particleName, Characterization achar, CharacterizationBean charBean) throws Exception { // if ID is not set save to the database otherwise update IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); Nanoparticle particle = null; int existingViewTitleCount = -1; try { ida.open(); // check if viewTitle is already used the same type of // characterization for the same particle boolean viewTitleUsed = isCharacterizationViewTitleUsed(ida, particleType, particleName, achar); if (!viewTitleUsed) { if (achar.getInstrumentConfiguration() != null) { addInstrumentConfig(achar.getInstrumentConfiguration(), ida); } // if ID exists, do update if (achar.getId() != null) { // check if ID is still valid try { Characterization storedChara = (Characterization) ida .load(Characterization.class, achar.getId()); } catch (Exception e) { throw new Exception( "This characterization is no longer in the database. Please log in again to refresh."); } ida.store(achar); } else {// get the existing particle and characterizations // from database created during sample creation List results = ida .search("select particle from Nanoparticle particle left join fetch particle.characterizationCollection where particle.name='" + particleName + "' and particle.type='" + particleType + "'"); for (Object obj : results) { particle = (Nanoparticle) obj; } if (particle != null) { particle.getCharacterizationCollection().add(achar); } } } if (existingViewTitleCount > 0) { throw new Exception( "The view title is already in use. Please enter a different one."); } } catch (Exception e) { e.printStackTrace(); ida.rollback(); logger.error("Problem saving characterization. "); throw e; } finally { ida.close(); } // save file to the file system // if this block of code is inside the db try catch block, hibernate // doesn't persist derivedBioAssayData if (!achar.getDerivedBioAssayDataCollection().isEmpty()) { int count=0; for (DerivedBioAssayData derivedBioAssayData : achar .getDerivedBioAssayDataCollection()) { DerivedBioAssayDataBean derivedBioAssayDataBean = new DerivedBioAssayDataBean( derivedBioAssayData); //assign visibility DerivedBioAssayDataBean unsaved=charBean.getDerivedBioAssayDataList().get(count); derivedBioAssayDataBean.setVisibilityGroups(unsaved.getVisibilityGroups()); saveCharacterizationFile(derivedBioAssayDataBean); count++; } } } public void addNewCharacterizationDataDropdowns( CharacterizationBean charBean, String characterizationName) throws Exception { IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); if (!charBean.getDerivedBioAssayDataList().isEmpty()) { for (DerivedBioAssayDataBean derivedBioAssayDataBean : charBean .getDerivedBioAssayDataList()) { // add new characterization file type if necessary if (derivedBioAssayDataBean.getType().length() > 0) { CharacterizationFileType fileType = new CharacterizationFileType(); addLookupType(ida, fileType, derivedBioAssayDataBean .getType()); } // add new derived data cateory for (String category : derivedBioAssayDataBean .getCategories()) { addDerivedDataCategory(ida, category, characterizationName); } // add new datum name, measure type, and unit for (DatumBean datumBean : derivedBioAssayDataBean .getDatumList()) { addDatumName(ida, datumBean.getName(), characterizationName); MeasureType measureType = new MeasureType(); addLookupType(ida, measureType, datumBean .getStatisticsType()); addMeasureUnit(ida, datumBean.getUnit(), characterizationName); } } } } catch (Exception e) { e.printStackTrace(); ida.rollback(); logger.error("Problem saving characterization data drop downs. "); throw e; } finally { ida.close(); } } /* * check if viewTitle is already used the same type of characterization for * the same particle */ private boolean isCharacterizationViewTitleUsed(IDataAccess ida, String particleType, String particleName, Characterization achar) throws Exception { String viewTitleQuery = ""; if (achar.getId() == null) { viewTitleQuery = "select count(achar.identificationName) from Nanoparticle particle join particle.characterizationCollection achar where particle.name='" + particleName + "' and particle.type='" + particleType + "' and achar.identificationName='" + achar.getIdentificationName() + "' and achar.name='" + achar.getName() + "'"; } else { viewTitleQuery = "select count(achar.identificationName) from Nanoparticle particle join particle.characterizationCollection achar where particle.name='" + particleName + "' and particle.type='" + particleType + "' and achar.identificationName='" + achar.getIdentificationName() + "' and achar.name='" + achar.getName() + "' and achar.id!=" + achar.getId(); } List viewTitleResult = ida.search(viewTitleQuery); int existingViewTitleCount = -1; for (Object obj : viewTitleResult) { existingViewTitleCount = ((Integer) (obj)).intValue(); } if (existingViewTitleCount > 0) { return true; } else { return false; } } /** * Save the file to the file system * * @param fileBean */ public void saveCharacterizationFile(DerivedBioAssayDataBean fileBean) throws Exception { byte[] fileContent = fileBean.getFileContent(); String rootPath = PropertyReader.getProperty( CaNanoLabConstants.FILEUPLOAD_PROPERTY, "fileRepositoryDir"); if (fileContent != null) { FileService fileService = new FileService(); fileService.writeFile(fileContent, rootPath + File.separator + fileBean.getUri()); } userService.setVisiblity(fileBean.getId(), fileBean .getVisibilityGroups()); } private void addInstrumentConfig(InstrumentConfiguration instrumentConfig, IDataAccess ida) throws Exception { Instrument instrument = instrumentConfig.getInstrument(); // check if instrument is already in database List instrumentResults = ida .search("select instrument from Instrument instrument where instrument.type='" + instrument.getType() + "' and instrument.manufacturer='" + instrument.getManufacturer() + "'"); Instrument storedInstrument = null; for (Object obj : instrumentResults) { storedInstrument = (Instrument) obj; } if (storedInstrument != null) { instrument.setId(storedInstrument.getId()); } else { ida.createObject(instrument); } // if new instrumentConfig, save it if (instrumentConfig.getId() == null) { ida.createObject(instrumentConfig); } else { InstrumentConfiguration storedInstrumentConfig = (InstrumentConfiguration) ida .load(InstrumentConfiguration.class, instrumentConfig .getId()); storedInstrumentConfig.setDescription(instrumentConfig .getDescription()); storedInstrumentConfig.setInstrument(instrument); } } /** * Saves the particle composition to the database * * @param particleType * @param particleName * @param composition * @throws Exception */ public void addParticleComposition(String particleType, String particleName, CompositionBean composition) throws Exception { ParticleComposition doComp = composition.getDomainObj(); addParticleCharacterization(particleType, particleName, doComp, composition); } /** * O Saves the size characterization to the database * * @param particleType * @param particleName * @param size * @throws Exception */ public void addParticleSize(String particleType, String particleName, CharacterizationBean size) throws Exception { Size doSize = new Size(); size.updateDomainObj(doSize); addParticleCharacterization(particleType, particleName, doSize, size); } /** * Saves the size characterization to the database * * @param particleType * @param particleName * @param surface * @throws Exception */ public void addParticleSurface(String particleType, String particleName, CharacterizationBean surface) throws Exception { Surface doSurface = new Surface(); ((SurfaceBean) surface).updateDomainObj(doSurface); addParticleCharacterization(particleType, particleName, doSurface, surface); // addMeasureUnit(doSurface.getCharge().getUnitOfMeasurement(), // CaNanoLabConstants.UNIT_TYPE_CHARGE); // addMeasureUnit(doSurface.getSurfaceArea().getUnitOfMeasurement(), // CaNanoLabConstants.UNIT_TYPE_AREA); // addMeasureUnit(doSurface.getZetaPotential().getUnitOfMeasurement(), // CaNanoLabConstants.UNIT_TYPE_ZETA_POTENTIAL); } private void addLookupType(IDataAccess ida, LookupType lookupType, String type) throws Exception { String className = lookupType.getClass().getSimpleName(); List results = ida.search("select count(distinct name) from " + className + " type where name='" + type + "'"); lookupType.setName(type); int count = -1; for (Object obj : results) { count = ((Integer) (obj)).intValue(); } if (count == 0) { ida.createObject(lookupType); } } private void addDatumName(IDataAccess ida, String name, String characterizationName) throws Exception { List results = ida.search("select count(distinct name) from DatumName" + " where characterizationName='" + characterizationName + "'" + " and name='" + name + "'"); DatumName datumName = new DatumName(); datumName.setName(name); datumName.setCharacterizationName(characterizationName); datumName.setDatumParsed(false); int count = -1; for (Object obj : results) { count = ((Integer) (obj)).intValue(); } if (count == 0) { ida.createObject(datumName); } } private void addDerivedDataCategory(IDataAccess ida, String name, String characterizationName) throws Exception { List results = ida .search("select count(distinct name) from DerivedBioAssayDataCategory" + " where characterizationName='" + characterizationName + "'" + " and name='" + name + "'"); DerivedBioAssayDataCategory category = new DerivedBioAssayDataCategory(); category.setName(name); category.setCharacterizationName(characterizationName); int count = -1; for (Object obj : results) { count = ((Integer) (obj)).intValue(); } if (count == 0) { ida.createObject(category); } } private void addLookupType(LookupType lookupType, String type) throws Exception { // if ID is not set save to the database otherwise update IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); String className = lookupType.getClass().getSimpleName(); try { ida.open(); List results = ida.search("select count(distinct name) from " + className + " type where name='" + type + "'"); lookupType.setName(type); int count = -1; for (Object obj : results) { count = ((Integer) (obj)).intValue(); } if (count == 0) { ida.createObject(lookupType); } } catch (Exception e) { e.printStackTrace(); ida.rollback(); logger.error("Problem saving look up type: " + type); throw e; } finally { ida.close(); } } // private void addMeasureUnit(String unit, String type) throws Exception { // if (unit == null || unit.length() == 0) { // return; // // if ID is not set save to the database otherwise update // IDataAccess ida = (new DataAccessProxy()) // .getInstance(IDataAccess.HIBERNATE); // MeasureUnit measureUnit = new MeasureUnit(); // try { // ida.open(); // List results = ida // .search("select count(distinct measureUnit.name) from " // + "MeasureUnit measureUnit where measureUnit.name='" // + unit + "' and measureUnit.type='" + type + "'"); // int count = -1; // for (Object obj : results) { // count = ((Integer) (obj)).intValue(); // if (count == 0) { // measureUnit.setName(unit); // measureUnit.setType(type); // ida.createObject(measureUnit); // } catch (Exception e) { // e.printStackTrace(); // ida.rollback(); // logger.error("Problem saving look up type: " + type); // throw e; // } finally { // ida.close(); private void addMeasureUnit(IDataAccess ida, String unit, String type) throws Exception { if (unit == null || unit.length() == 0) { return; } List results = ida.search("select count(distinct name) from " + " MeasureUnit where name='" + unit + "' and type='" + type + "'"); int count = -1; for (Object obj : results) { count = ((Integer) (obj)).intValue(); } MeasureUnit measureUnit = new MeasureUnit(); if (count == 0) { measureUnit.setName(unit); measureUnit.setType(type); ida.createObject(measureUnit); } } /** * Saves the molecular weight characterization to the database * * @param particleType * @param particleName * @param molecularWeight * @throws Exception */ public void addParticleMolecularWeight(String particleType, String particleName, CharacterizationBean molecularWeight) throws Exception { MolecularWeight doMolecularWeight = new MolecularWeight(); molecularWeight.updateDomainObj(doMolecularWeight); addParticleCharacterization(particleType, particleName, doMolecularWeight, molecularWeight); } /** * Saves the morphology characterization to the database * * @param particleType * @param particleName * @param morphology * @throws Exception */ public void addParticleMorphology(String particleType, String particleName, CharacterizationBean morphology) throws Exception { Morphology doMorphology = new Morphology(); ((MorphologyBean) morphology).updateDomainObj(doMorphology); addParticleCharacterization(particleType, particleName, doMorphology, morphology); MorphologyType morphologyType = new MorphologyType(); addLookupType(morphologyType, doMorphology.getType()); } /** * Saves the shape characterization to the database * * @param particleType * @param particleName * @param shape * @throws Exception */ public void addParticleShape(String particleType, String particleName, CharacterizationBean shape) throws Exception { Shape doShape = new Shape(); ((ShapeBean) shape).updateDomainObj(doShape); addParticleCharacterization(particleType, particleName, doShape, shape); ShapeType shapeType = new ShapeType(); addLookupType(shapeType, doShape.getType()); } /** * Saves the purity characterization to the database * * @param particleType * @param particleName * @param purity * @throws Exception */ public void addParticlePurity(String particleType, String particleName, CharacterizationBean purity) throws Exception { Purity doPurity = new Purity(); purity.updateDomainObj(doPurity); // TODO think about how to deal with characterization file. addParticleCharacterization(particleType, particleName, doPurity, purity); } /** * Saves the solubility characterization to the database * * @param particleType * @param particleName * @param solubility * @throws Exception */ public void addParticleSolubility(String particleType, String particleName, CharacterizationBean solubility) throws Exception { Solubility doSolubility = new Solubility(); ((SolubilityBean) solubility).updateDomainObj(doSolubility); // TODO think about how to deal with characterization file. addParticleCharacterization(particleType, particleName, doSolubility, solubility); SolventType solventType = new SolventType(); addLookupType(solventType, doSolubility.getSolvent()); // addMeasureUnit(doSolubility.getCriticalConcentration() // .getUnitOfMeasurement(), // CaNanoLabConstants.UNIT_TYPE_CONCENTRATION); } /** * Saves the invitro hemolysis characterization to the database * * @param particleType * @param particleName * @param hemolysis * @throws Exception */ public void addHemolysis(String particleType, String particleName, CharacterizationBean hemolysis) throws Exception { Hemolysis doHemolysis = new Hemolysis(); hemolysis.updateDomainObj(doHemolysis); // TODO think about how to deal with characterization file. addParticleCharacterization(particleType, particleName, doHemolysis, hemolysis); } /** * Saves the invitro coagulation characterization to the database * * @param particleType * @param particleName * @param coagulation * @throws Exception */ public void addCoagulation(String particleType, String particleName, CharacterizationBean coagulation) throws Exception { Coagulation doCoagulation = new Coagulation(); coagulation.updateDomainObj(doCoagulation); addParticleCharacterization(particleType, particleName, doCoagulation, coagulation); } /** * Saves the invitro plate aggregation characterization to the database * * @param particleType * @param particleName * @param plateletAggregation * @throws Exception */ public void addPlateletAggregation(String particleType, String particleName, CharacterizationBean plateletAggregation) throws Exception { PlateletAggregation doPlateletAggregation = new PlateletAggregation(); plateletAggregation.updateDomainObj(doPlateletAggregation); addParticleCharacterization(particleType, particleName, doPlateletAggregation, plateletAggregation); } /** * Saves the invitro Complement Activation characterization to the database * * @param particleType * @param particleName * @param complementActivation * @throws Exception */ public void addComplementActivation(String particleType, String particleName, CharacterizationBean complementActivation) throws Exception { ComplementActivation doComplementActivation = new ComplementActivation(); complementActivation.updateDomainObj(doComplementActivation); addParticleCharacterization(particleType, particleName, doComplementActivation, complementActivation); } /** * Saves the invitro chemotaxis characterization to the database * * @param particleType * @param particleName * @param chemotaxis * @throws Exception */ public void addChemotaxis(String particleType, String particleName, CharacterizationBean chemotaxis) throws Exception { Chemotaxis doChemotaxis = new Chemotaxis(); chemotaxis.updateDomainObj(doChemotaxis); addParticleCharacterization(particleType, particleName, doChemotaxis, chemotaxis); } /** * Saves the invitro NKCellCytotoxicActivity characterization to the * database * * @param particleType * @param particleName * @param nkCellCytotoxicActivity * @throws Exception */ public void addNKCellCytotoxicActivity(String particleType, String particleName, CharacterizationBean nkCellCytotoxicActivity) throws Exception { NKCellCytotoxicActivity doNKCellCytotoxicActivity = new NKCellCytotoxicActivity(); nkCellCytotoxicActivity.updateDomainObj(doNKCellCytotoxicActivity); addParticleCharacterization(particleType, particleName, doNKCellCytotoxicActivity, nkCellCytotoxicActivity); } /** * Saves the invitro LeukocyteProliferation characterization to the database * * @param particleType * @param particleName * @param leukocyteProliferation * @throws Exception */ public void addLeukocyteProliferation(String particleType, String particleName, CharacterizationBean leukocyteProliferation) throws Exception { LeukocyteProliferation doLeukocyteProliferation = new LeukocyteProliferation(); leukocyteProliferation.updateDomainObj(doLeukocyteProliferation); addParticleCharacterization(particleType, particleName, doLeukocyteProliferation, leukocyteProliferation); } /** * Saves the invitro CFU_GM characterization to the database * * @param particleType * @param particleName * @param cfu_gm * @throws Exception */ public void addCFU_GM(String particleType, String particleName, CharacterizationBean cfu_gm) throws Exception { CFU_GM doCFU_GM = new CFU_GM(); cfu_gm.updateDomainObj(doCFU_GM); addParticleCharacterization(particleType, particleName, doCFU_GM, cfu_gm); } /** * Saves the invitro OxidativeBurst characterization to the database * * @param particleType * @param particleName * @param oxidativeBurst * @throws Exception */ public void addOxidativeBurst(String particleType, String particleName, CharacterizationBean oxidativeBurst) throws Exception { OxidativeBurst doOxidativeBurst = new OxidativeBurst(); oxidativeBurst.updateDomainObj(doOxidativeBurst); addParticleCharacterization(particleType, particleName, doOxidativeBurst, oxidativeBurst); } /** * Saves the invitro Phagocytosis characterization to the database * * @param particleType * @param particleName * @param phagocytosis * @throws Exception */ public void addPhagocytosis(String particleType, String particleName, CharacterizationBean phagocytosis) throws Exception { Phagocytosis doPhagocytosis = new Phagocytosis(); phagocytosis.updateDomainObj(doPhagocytosis); addParticleCharacterization(particleType, particleName, doPhagocytosis, phagocytosis); } /** * Saves the invitro CytokineInduction characterization to the database * * @param particleType * @param particleName * @param cytokineInduction * @throws Exception */ public void addCytokineInduction(String particleType, String particleName, CharacterizationBean cytokineInduction) throws Exception { CytokineInduction doCytokineInduction = new CytokineInduction(); cytokineInduction.updateDomainObj(doCytokineInduction); addParticleCharacterization(particleType, particleName, doCytokineInduction, cytokineInduction); } /** * Saves the invitro plasma protein binding characterization to the database * * @param particleType * @param particleName * @param plasmaProteinBinding * @throws Exception */ public void addProteinBinding(String particleType, String particleName, CharacterizationBean plasmaProteinBinding) throws Exception { PlasmaProteinBinding doProteinBinding = new PlasmaProteinBinding(); plasmaProteinBinding.updateDomainObj(doProteinBinding); addParticleCharacterization(particleType, particleName, doProteinBinding, plasmaProteinBinding); } /** * Saves the invitro binding characterization to the database * * @param particleType * @param particleName * @param cellViability * @throws Exception */ public void addCellViability(String particleType, String particleName, CharacterizationBean cellViability) throws Exception { CellViability doCellViability = new CellViability(); ((CytotoxicityBean) cellViability).updateDomainObj(doCellViability); addParticleCharacterization(particleType, particleName, doCellViability, cellViability); CellLineType cellLineType = new CellLineType(); addLookupType(cellLineType, doCellViability.getCellLine()); } /** * Saves the invitro EnzymeInduction binding characterization to the * database * * @param particleType * @param particleName * @param enzymeInduction * @throws Exception */ public void addEnzymeInduction(String particleType, String particleName, CharacterizationBean enzymeInduction) throws Exception { EnzymeInduction doEnzymeInduction = new EnzymeInduction(); enzymeInduction.updateDomainObj(doEnzymeInduction); addParticleCharacterization(particleType, particleName, doEnzymeInduction, enzymeInduction); } /** * Saves the invitro OxidativeStress characterization to the database * * @param particleType * @param particleName * @param oxidativeStress * @throws Exception */ public void addOxidativeStress(String particleType, String particleName, CharacterizationBean oxidativeStress) throws Exception { OxidativeStress doOxidativeStress = new OxidativeStress(); oxidativeStress.updateDomainObj(doOxidativeStress); addParticleCharacterization(particleType, particleName, doOxidativeStress, oxidativeStress); } /** * Saves the invitro Caspase3Activation characterization to the database * * @param particleType * @param particleName * @param caspase3Activation * @throws Exception */ public void addCaspase3Activation(String particleType, String particleName, CharacterizationBean caspase3Activation) throws Exception { Caspase3Activation doCaspase3Activation = new Caspase3Activation(); caspase3Activation.updateDomainObj(doCaspase3Activation); addParticleCharacterization(particleType, particleName, doCaspase3Activation, caspase3Activation); CellLineType cellLineType = new CellLineType(); addLookupType(cellLineType, doCaspase3Activation.getCellLine()); } public void setCharacterizationFile(String particleName, String characterizationName, LabFileBean fileBean) { } public void addParticleFunction(String particleType, String particleName, FunctionBean function) throws Exception { Function doFunction = function.getDomainObj(); // if ID is not set save to the database otherwise update IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); Nanoparticle particle = null; int existingViewTitleCount = -1; try { // Have to seperate this section out in a different hibernate // session. // check linkage id object type ida.open(); if (doFunction.getId() != null && doFunction.getLinkageCollection() != null) { for (Linkage linkage : doFunction.getLinkageCollection()) { // check linkage id object type if (linkage.getId() != null) { List result = ida .search("from Linkage linkage where linkage.id = " + linkage.getId()); if (result != null && result.size() > 0) { Linkage existingObj = (Linkage) result.get(0); // the the type is different, if (existingObj.getClass() != linkage.getClass()) { linkage.setId(null); ida.removeObject(existingObj); } } } } } ida.close(); ida.open(); if (doFunction.getLinkageCollection() != null) { for (Linkage linkage : doFunction.getLinkageCollection()) { Agent agent = linkage.getAgent(); if (agent != null) { for (AgentTarget agentTarget : agent .getAgentTargetCollection()) { ida.store(agentTarget); } ida.store(agent); } ida.store(linkage); } } boolean viewTitleUsed = isFunctionViewTitleUsed(ida, particleType, particleName, doFunction); if (!viewTitleUsed) { if (doFunction.getId() != null) { ida.store(doFunction); } else {// get the existing particle and compositions // from database created during sample creation List results = ida .search("select particle from Nanoparticle particle left join fetch particle.functionCollection where particle.name='" + particleName + "' and particle.type='" + particleType + "'"); for (Object obj : results) { particle = (Nanoparticle) obj; } if (particle != null) { particle.getFunctionCollection().add(doFunction); } } } } catch (Exception e) { e.printStackTrace(); ida.rollback(); logger.error("Problem saving characterization: "); throw e; } finally { ida.close(); } if (existingViewTitleCount > 0) { throw new CalabException( "The view title is already in use. Please enter a different one."); } } /* * check if viewTitle is already used the same type of function for the same * particle */ private boolean isFunctionViewTitleUsed(IDataAccess ida, String particleType, String particleName, Function function) throws Exception { // check if viewTitle is already used the same type of // function for the same particle String viewTitleQuery = ""; if (function.getId() == null) { viewTitleQuery = "select count(function.identificationName) from Nanoparticle particle join particle.functionCollection function where particle.name='" + particleName + "' and particle.type='" + particleType + "' and function.identificationName='" + function.getIdentificationName() + "' and function.type='" + function.getType() + "'"; } else { viewTitleQuery = "select count(function.identificationName) from Nanoparticle particle join particle.functionCollection function where particle.name='" + particleName + "' and particle.type='" + particleType + "' and function.identificationName='" + function.getIdentificationName() + "' and function.id!=" + function.getId() + " and function.type='" + function.getType() + "'"; } List viewTitleResult = ida.search(viewTitleQuery); int existingViewTitleCount = -1; for (Object obj : viewTitleResult) { existingViewTitleCount = ((Integer) (obj)).intValue(); } if (existingViewTitleCount > 0) { return true; } else { return false; } } /** * Load the file for the given fileId from the database * * @param fileId * @return */ public LabFileBean getFile(String fileId) throws Exception { IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); LabFileBean fileBean = null; try { ida.open(); LabFile file = (LabFile) ida.load(LabFile.class, StringUtils .convertToLong(fileId)); fileBean = new LabFileBean(file); } catch (Exception e) { e.printStackTrace(); ida.rollback(); logger.error("Problem getting file with file ID: " + fileId); throw e; } finally { ida.close(); } // get visibilities UserService userService = new UserService( CaNanoLabConstants.CSM_APP_NAME); List<String> accessibleGroups = userService.getAccessibleGroups( fileBean.getId(), CaNanoLabConstants.CSM_READ_ROLE); String[] visibilityGroups = accessibleGroups.toArray(new String[0]); fileBean.setVisibilityGroups(visibilityGroups); return fileBean; } /** * Load the derived data file for the given fileId from the database * * @param fileId * @return */ public DerivedBioAssayDataBean getDerivedBioAssayData(String fileId) throws Exception { IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); DerivedBioAssayDataBean fileBean = null; try { ida.open(); DerivedBioAssayData file = (DerivedBioAssayData) ida.load( DerivedBioAssayData.class, StringUtils .convertToLong(fileId)); // load keywords file.getKeywordCollection(); fileBean = new DerivedBioAssayDataBean(file, CaNanoLabConstants.OUTPUT); } catch (Exception e) { e.printStackTrace(); ida.rollback(); logger.error("Problem getting file with file ID: " + fileId); throw e; } finally { ida.close(); } // get visibilities UserService userService = new UserService( CaNanoLabConstants.CSM_APP_NAME); List<String> accessibleGroups = userService.getAccessibleGroups( fileBean.getId(), CaNanoLabConstants.CSM_READ_ROLE); String[] visibilityGroups = accessibleGroups.toArray(new String[0]); fileBean.setVisibilityGroups(visibilityGroups); return fileBean; } /** * Get the list of all run output files associated with a particle * * @param particleName * @return * @throws Exception */ public List<LabFileBean> getAllRunFiles(String particleName) throws Exception { List<LabFileBean> runFiles = new ArrayList<LabFileBean>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String query = "select distinct outFile from Run run join run.outputFileCollection outFile join run.runSampleContainerCollection runContainer where runContainer.sampleContainer.sample.name='" + particleName + "'"; List results = ida.search(query); for (Object obj : results) { OutputFile file = (OutputFile) obj; // active status only if (file.getDataStatus() == null) { LabFileBean fileBean = new LabFileBean(); fileBean.setId(file.getId().toString()); fileBean.setName(file.getFilename()); fileBean.setUri(file.getUri()); runFiles.add(fileBean); } } } catch (Exception e) { e.printStackTrace(); ida.rollback(); logger.error("Problem getting run files for particle: " + particleName); throw e; } finally { ida.close(); } return runFiles; } /** * Update the meta data associated with a file stored in the database * * @param fileBean * @throws Exception */ public void updateFileMetaData(LabFileBean fileBean) throws Exception { IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); LabFile file = (LabFile) ida.load(LabFile.class, StringUtils .convertToLong(fileBean.getId())); file.setTitle(fileBean.getTitle().toUpperCase()); file.setDescription(fileBean.getDescription()); file.setComments(fileBean.getComments()); } catch (Exception e) { e.printStackTrace(); ida.rollback(); logger.error("Problem updating file meta data: "); throw e; } finally { ida.close(); } userService.setVisiblity(fileBean.getId(), fileBean .getVisibilityGroups()); } /** * Update the meta data associated with a file stored in the database * * @param fileBean * @throws Exception */ public void updateDerivedBioAssayDataMetaData( DerivedBioAssayDataBean fileBean) throws Exception { IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); DerivedBioAssayData file = (DerivedBioAssayData) ida.load( DerivedBioAssayData.class, StringUtils .convertToLong(fileBean.getId())); file.setTitle(fileBean.getTitle().toUpperCase()); file.setDescription(fileBean.getDescription()); file.getKeywordCollection().clear(); if (fileBean.getKeywords() != null) { for (String keyword : fileBean.getKeywords()) { Keyword keywordObj = new Keyword(); keywordObj.setName(keyword); file.getKeywordCollection().add(keywordObj); } } } catch (Exception e) { e.printStackTrace(); ida.rollback(); logger.error("Problem updating derived data file meta data: "); throw e; } finally { ida.close(); } userService.setVisiblity(fileBean.getId(), fileBean .getVisibilityGroups()); } /** * Delete the characterization */ public void deleteCharacterization(String strCharId) throws Exception { // if ID is not set save to the database otherwise update HibernateDataAccess ida = (HibernateDataAccess) (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); // Get ID Long charId = Long.parseLong(strCharId); Object charObj = ida.load(Characterization.class, charId); ida.delete(charObj); } catch (Exception e) { e.printStackTrace(); ida.rollback(); logger.error("Problem saving characterization: "); throw e; } finally { ida.close(); } } /** * Delete the characterizations */ public void deleteCharacterizations(String particleName, String particleType, String[] charIds) throws Exception { // if ID is not set save to the database otherwise update HibernateDataAccess ida = (HibernateDataAccess) (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); // Get ID for (String strCharId : charIds) { Long charId = Long.parseLong(strCharId); Object charObj = ida.load(Characterization.class, charId); // deassociate first String hqlString = "from Nanoparticle particle where particle.characterizationCollection.id = '" + strCharId + "'"; List results = ida.search(hqlString); for (Object obj : results) { Nanoparticle particle = (Nanoparticle) obj; particle.getCharacterizationCollection().remove(charObj); } // then delete ida.delete(charObj); } } catch (Exception e) { e.printStackTrace(); ida.rollback(); logger.error("Problem deleting characterization: "); throw new Exception( "The characterization is no longer exist in the database, please login again to refresh the view."); } finally { ida.close(); } } }
import vtk.vtkNativeLibrary; import vtk.vtkSphereSource; import vtk.vtkPolyDataMapper; import vtk.vtkRenderWindow; import vtk.vtkRenderWindowInteractor; import vtk.vtkRenderer; import vtk.vtkActor; public class FullScreen { // Load VTK library and print which library was not properly loaded static { if (!vtkNativeLibrary.LoadAllNativeLibraries()) { for (vtkNativeLibrary lib : vtkNativeLibrary.values()) { if (!lib.IsLoaded()) { System.out.println(lib.GetLibraryName() + " not loaded"); } } } vtkNativeLibrary.DisableOutputWindow(null); } public static void main(String s[]) { // Create a sphere vtkSphereSource SphereSource = new vtkSphereSource(); SphereSource.Update(); vtkPolyDataMapper Mapper = new vtkPolyDataMapper(); Mapper.SetInputConnection(SphereSource.GetOutputPort()); vtkActor Actor = new vtkActor(); Actor.SetMapper(Mapper); // Create the renderer, render window and interactor. vtkRenderer ren = new vtkRenderer(); vtkRenderWindow renWin = new vtkRenderWindow(); renWin.AddRenderer(ren); vtkRenderWindowInteractor iren = new vtkRenderWindowInteractor(); iren.SetRenderWindow(renWin); // Visualise Sphere in full screen window ren.AddActor(Actor); renWin.Render(); renWin.SetFullScreen(1); ren.ResetCamera(); ren.ResetCameraClippingRange(); iren.Initialize(); iren.Start(); } }
package gov.nih.nci.cananolab.util; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.PipedInputStream; import java.io.PipedOutputStream; import java.lang.reflect.Method; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Utilility class to handle domain class manipulations * * @author pansu * */ public class ClassUtils { /** * Get all caNanoLab domain classes * * @return * @throws Exception */ public static Collection<Class> getDomainClasses() throws Exception { Collection<Class> list = new ArrayList<Class>(); JarFile file = null; URL url = Thread.currentThread().getContextClassLoader().getResource( "application-config.xml"); File webinfDirect = (new File(url.getPath())).getParentFile() .getParentFile(); String fullJarFilePath = webinfDirect + File.separator + "lib" + File.separatorChar + Constants.SDK_BEAN_JAR; file = new JarFile(fullJarFilePath); if (file == null) throw new Exception("Could not locate the bean jar"); Enumeration e = file.entries(); while (e.hasMoreElements()) { JarEntry o = (JarEntry) e.nextElement(); if (!o.isDirectory()) { String name = o.getName(); if (name.endsWith(".class")) { String klassName = name.replace('/', '.').substring(0, name.lastIndexOf('.')); list.add(Class.forName(klassName)); } } } return list; } /** * Get child classes of a parent class in caNanoLab * * @param parentClassName * @return * @throws Exception */ public static List<Class> getChildClasses(String parentClassName) throws Exception { Collection<Class> classes = getDomainClasses(); List<Class> childClasses = new ArrayList<Class>(); for (Class c : classes) { if (c.getSuperclass().getName().equals(parentClassName)) { childClasses.add(c); } } return childClasses; } /** * Get child class names of a parent class in caNanoLab * * @param parentClassName * @return * @throws Exception */ public static List<String> getChildClassNames(String parentClassName) throws Exception { List<Class> childClasses = getChildClasses(parentClassName); List<String> childClassNames = new ArrayList<String>(); for (Class c : childClasses) { childClassNames.add(c.getCanonicalName()); } return childClassNames; } /** * get the short class name without fully qualified path * * @param className * @return */ public static String getShortClassName(String className) { String[] strs = className.split("\\."); return strs[strs.length - 1]; } /** * check if a class has children classes * * @param parent * class name * @return */ public static boolean hasChildrenClasses(String parentClassName) throws Exception { boolean hasChildernFlag = false; if (parentClassName == null) { return hasChildernFlag; } List<String> subclassList = ClassUtils .getChildClassNames(parentClassName); if (subclassList == null || subclassList.size() == 0) hasChildernFlag = false; else hasChildernFlag = true; return hasChildernFlag; } public static Class getFullClass(String shortClassName) throws Exception { if (shortClassName == null || shortClassName.length() == 0) { return null; } Collection<Class> classes = getDomainClasses(); for (Class clazz : classes) { if (clazz.getCanonicalName().endsWith(shortClassName)) { return clazz; } } return Object.class; } /** * Utility for making deep copies (vs. clone()'s shallow copies) of objects. * Objects are first serialized and then deserialized. Error checking is * fairly minimal in this implementation. If an object is encountered that * cannot be serialized (or that references an object that cannot be * serialized) an error is printed to System.err and null is returned. * Depending on your specific application, it might make more sense to have * copy(...) re-throw the exception. * * A later version of this class includes some minor optimizations. */ /** * Returns a copy of the object, or null if the object cannot be serialized. */ public static Object deepCopy(Object orig) { Object obj = null; try { // Write the object out to a byte array ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(bos); out.writeObject(orig); out.flush(); out.close(); // Make an input stream from the byte array and read // a copy of the object back in. ObjectInputStream in = new ObjectInputStream( new ByteArrayInputStream(bos.toByteArray())); obj = in.readObject(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException cnfe) { cnfe.printStackTrace(); } return obj; } public static void main(String[] args) { try { List<String> names = ClassUtils .getChildClassNames("gov.nih.nci.cananolab.domain.particle.FunctionalizingEntity"); for (String name : names) { System.out.println(name); } String displayName = ClassUtils.getDisplayName("SmallMolecule"); System.out.println(displayName); String className = ClassUtils .getShortClassNameFromDisplayName("other small molecule"); System.out.println(className); // test, put this to the beginnging of ClassUtils.mapObjects // Report report1 = new Report(); // report1.setCategory("myCategory"); // report1.setTitle("mytitle"); // inputObjects = new Object[1]; // inputObjects[0] = report1; // aTargetClazz = new Report().getClass(); // end of test // List<Report> reportLists = ClassUtils.mapObjects(null, null); } catch (Exception e) { e.printStackTrace(); } } /** * Utility for making deep copies (vs. clone()'s shallow copies) of objects * in a memory efficient way. Objects are serialized in the calling thread * and de-serialized in another thread. * * Error checking is fairly minimal in this implementation. If an object is * encountered that cannot be serialized (or that references an object that * cannot be serialized) an error is printed to System.err and null is * returned. Depending on your specific application, it might make more * sense to have copy(...) re-throw the exception. */ /* * Flag object used internally to indicate that deserialization failed. */ private static final Object ERROR = new Object(); /** * Returns a copy of the object, or null if the object cannot be serialized. */ public static Object deepCopyToo(Object orig) { Object obj = null; try { // Make a connected pair of piped streams PipedInputStream in = new PipedInputStream(); PipedOutputStream pos = new PipedOutputStream(in); // Make a deserializer thread (see inner class below) Deserializer des = new Deserializer(in); // Write the object to the pipe ObjectOutputStream out = new ObjectOutputStream(pos); out.writeObject(orig); // Wait for the object to be deserialized obj = des.getDeserializedObject(); // See if something went wrong if (obj == ERROR) obj = null; } catch (IOException ioe) { ioe.printStackTrace(); } return obj; } public static Object mapObjects(Class aTargetClazz, Object inputObject) { List objList = new ArrayList(); objList.add(inputObject); List resultObjs = mapObjects(aTargetClazz, objList); return resultObjs.get(0); } /** * copy attributes of one object to another * * mapping attribute criteria: - use setter and getter to copy value - * getter method have no parameter types, * method.getParameterTypes().length==0 - setter method have one and only * one parameter types, method.getParameterTypes().length==1 - setter method * returns void type - The return type of getter method matches the * parameter type of the setter method */ public static List mapObjects(Class aTargetClazz, List inputObjects) { List resultObjs = new ArrayList(); if (inputObjects != null && inputObjects.size() > 0) { // put to inputObjects map Map<String, Method> setterMethodsMap = new HashMap<String, Method>(); Method[] inputObjectMethods = inputObjects.get(0).getClass() .getMethods(); for (Method method : inputObjectMethods) { if (method.getName().startsWith("set") && method.getParameterTypes().length == 1 && method.getReturnType().toString().equals("void")) { setterMethodsMap.put(method.getName().replaceFirst("set", ""), method); } } Method setterMethod = null; try { // take the first object to get methods Class objClazz = inputObjects.get(0).getClass(); Method[] allMethods = objClazz.getMethods(); // qualified getter methods List<Method> methods = new ArrayList<Method>( (int) (allMethods.length / 2)); for (Method method : allMethods) { if (method.getName().startsWith("get") && !method.getName().equals("getClass") && method.getParameterTypes().length == 0) { methods.add(method); } } Object getterResult = null; for (int i = 0; i < inputObjects.size(); i++) { resultObjs.add(aTargetClazz.newInstance()); for (Method method : methods) { System.out.println("method: " + method); getterResult = method.invoke(inputObjects.get(0), (Object[]) null); setterMethod = setterMethodsMap.get(method.getName() .replaceFirst("get", "")); if (getterResult != null && getterResult.getClass().getName().equals( setterMethod.getParameterTypes()[0] .getName())) { System.out .println(" getterResult.getClass().getName(): " + getterResult.getClass().getName()); System.out .println(" setterMethod.getParameterTypes()[0].getName(): " + setterMethod.getParameterTypes()[0] .getName()); // invoke setter System.out .println(" going to set: " + getterResult); setterMethod .invoke(resultObjs.get(i), getterResult); } } } System.out.println("completed"); } catch (Exception ex) { ex.printStackTrace(); } } return resultObjs; } /** * Thread subclass that handles deserializing from a PipedInputStream. */ private static class Deserializer extends Thread { /** * Object that we are deserializing */ private Object obj = null; /** * Lock that we block on while deserialization is happening */ private Object lock = null; /** * InputStream that the object is deserialized from. */ private PipedInputStream in = null; public Deserializer(PipedInputStream pin) throws IOException { lock = new Object(); this.in = pin; start(); } public void run() { Object o = null; try { ObjectInputStream oin = new ObjectInputStream(in); o = oin.readObject(); } catch (IOException e) { // This should never happen. If it does we make sure // that a the object is set to a flag that indicates // deserialization was not possible. e.printStackTrace(); } catch (ClassNotFoundException cnfe) { // Same here... cnfe.printStackTrace(); } synchronized (lock) { if (o == null) obj = ERROR; else obj = o; lock.notifyAll(); } } /** * Returns the deserialized object. This method will block until the * object is actually available. */ public Object getDeserializedObject() { // Wait for the object to show up try { synchronized (lock) { while (obj == null) { lock.wait(); } } } catch (InterruptedException ie) { // If we are interrupted we just return null } return obj; } } public static String getIdString(Object obj) throws Exception { if (obj instanceof String) { return obj.toString(); } Class clazz = obj.getClass(); Method[] allMethods = clazz.getMethods(); Method method = null; for (Method m : allMethods) { if (m.getName().equals("getId")) { method = m; break; } } if (method != null) { Object result = method.invoke(obj, new Object[0]); return result.toString(); } else { return null; } } public static String getDisplayName(String shortClassName) { return shortClassName.replaceAll("([A-Z])", " $1").trim().toLowerCase(); } public static String getShortClassNameFromDisplayName(String displayName) { String[] words = displayName.split(" "); List<String> newWords = new ArrayList<String>(); for (String word : words) { String newWord = Character.toString(word.charAt(0)).toUpperCase() + word.substring(1); newWords.add(newWord); } String shortClassName = StringUtils.join(newWords, ""); return shortClassName; } }
package grafica; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import javax.swing.Box; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.text.PlainDocument; import negozio.Prodotto; public class JSelectProductWithAmountPanel extends JPanel implements ActionListener { private static final long serialVersionUID = -8842725930146342385L; private StringBuilder code; private ArrayList <Prodotto> articoli; private JComboBox <String> codeComboBox; private JTextField amountTextfield; private AmountDocumentFilter amountDocumentFilter; private static final int CODE_TEXTFIELD_WIDTH = 150; private static final int AMOUNT_TEXTFIELD_COLUMNS = 3; private static final int COMPONENTS_SPACE = 30; private static final int DEFAULT_AMOUNT = 0; private static final String CODE_TEXT = "Codice: "; private static final String AMOUNT_TEXT = "Qnt: "; public JSelectProductWithAmountPanel (ArrayList <Prodotto> articoli) { this.articoli = articoli; ArrayList <String> codici = new ArrayList <> (); for (Prodotto articolo : this.articoli) { codici.add(articolo.getCodice()); } this.codeComboBox = new JComboBox <String> (codici.toArray( new String[codici.size()])); this.codeComboBox.setPreferredSize(new Dimension(CODE_TEXTFIELD_WIDTH, this.codeComboBox.getPreferredSize().height)); this.codeComboBox.addActionListener(this); this.code = new StringBuilder(this.codeComboBox.getItemAt(0).toString()); this.amountTextfield = new JTextField(String.valueOf(DEFAULT_AMOUNT), AMOUNT_TEXTFIELD_COLUMNS); PlainDocument doc = (PlainDocument) this.amountTextfield.getDocument(); this.amountDocumentFilter = new AmountDocumentFilter(this.articoli.get(0).getQuantita()); doc.setDocumentFilter(this.amountDocumentFilter); this.add(new JLabel(CODE_TEXT)); this.add(this.codeComboBox); this.add(Box.createHorizontalStrut(COMPONENTS_SPACE)); this.add(new JLabel(AMOUNT_TEXT)); this.add(this.amountTextfield); } public int getAmount () { return Integer.parseInt(this.amountTextfield.getText()); } public StringBuilder getCode () { return this.code; } public JTextField getAmountTextfield () { return this.amountTextfield; } @Override public void actionPerformed(ActionEvent e) { this.code.replace(0, this.code.length(), this.codeComboBox.getSelectedItem().toString()); this.amountTextfield.setText(String.valueOf(DEFAULT_AMOUNT)); this.amountDocumentFilter.setMaxValue(this.articoli.get(this.codeComboBox.getSelectedIndex()).getQuantita()); } }
package eu.verdelhan.ta4j; /** * An operation of a {@link Trade trade}. * <p> * The operation is defined by: * <ul> * <li>the index (in the {@link TimeSeries time series}) it is executed * <li>a {@link OperationType type} (BUY or SELL) * </ul> */ public class Operation { /** Type of the operation */ private OperationType type; /** The index the operation was executed */ private int index; /** * @param index the index the operation was executed * @param type the type of the operation */ public Operation(int index, OperationType type) { this.type = type; this.index = index; } /** * @return the type of the operation (BUY or SELL) */ public OperationType getType() { return type; } /** * @return true if this is a BUY operation, false otherwise */ public boolean isBuy() { return type == OperationType.BUY; } /** * @return true if this is a SELL operation, false otherwise */ public boolean isSell() { return type == OperationType.SELL; } /** * @return the index the operation was executed */ public int getIndex() { return index; } @Override public int hashCode() { return index + (type.hashCode() * 31); } @Override public boolean equals(Object obj) { if (obj instanceof Operation) { Operation o = (Operation) obj; return type.equals(o.getType()) && (index == o.getIndex()); } return false; } @Override public String toString() { return " Index: " + index + " type: " + type.toString(); } }
package test; import java.io.*; import junit.framework.*; import aQute.bnd.osgi.resource.*; import aQute.bnd.osgi.resource.FilterParser.Expression; public class FilterParserTest extends TestCase { FilterParser fp = new FilterParser(); public void testNestedAnd() throws IOException { aQute.bnd.osgi.resource.FilterParser.Expression exp = fp .parse("(&(osgi.wiring.package=osgi.enroute.webserver)(&(version>=1.0.0)(!(version>=2.0.0))))"); System.out.println(exp); } public void testSimple() throws IOException { aQute.bnd.osgi.resource.FilterParser.Expression exp = fp .parse("(&(osgi.wiring.package=package)(|(|(c=4)))(!(version>=2.0.0))(!(a=3))(version>=1.0.0))"); System.out.println(exp); } public void testReduce() throws IOException { Expression exp = fp.parse("(&(osgi.wiring.package=package)(!(version>=2.0.0))(version>=1.0.0))"); System.out.println(exp); } public void testVoidRange() throws IOException { Expression exp = fp.parse("(&(osgi.wiring.package=package)(version>=0.0.0))"); System.out.println(exp); } public void testIdentity() throws IOException { Expression exp = fp.parse("(&(osgi.identity=identity)(version>=0.0.0))"); System.out.println(exp); exp = fp.parse("(&(osgi.identity=identity)(!(version>=2.0.0))(version>=1.0.0))"); System.out.println(exp); } /** * Since the filters are cached we need to get similar filters to check if * this works. * * @throws IOException */ public void testCache() throws IOException { Expression exp = fp.parse("(&(osgi.wiring.package=a)(version>=1)(!(version>=2.0.0)))"); Expression exp2 = fp.parse("(&(osgi.wiring.package=b)(version>=1.1)(!(version>=2.0.0)))"); assertNotNull(exp2); assertNotNull(exp); } }
package test; import static org.junit.Assert.*; import java.util.Random; import org.junit.BeforeClass; import org.junit.Test; import markovChords.Chord; public class ChordTest { protected static Chord chord; protected static int rand_note, rand_octave; protected static Chord.Tonality rand_tone; @BeforeClass public static void chordInit() { rand_note = new Random().nextInt(11); switch(new Random().nextInt(4)){ case 0: rand_tone = Chord.Tonality.MAJOR; break; case 1: rand_tone = Chord.Tonality.MINOR; break; case 2: rand_tone = Chord.Tonality.DIMINISHED; break; case 3: rand_tone = Chord.Tonality.AUGMENTED; break; default: rand_tone = Chord.Tonality.MAJOR; } rand_octave = new Random().nextInt(7) - 3; System.out.println("Creating " + rand_tone + " chord: " + rand_note + " in octave " + rand_octave); try { chord = new Chord(rand_note, rand_tone, rand_octave); } catch (Exception e) { System.err.println("Oh no! An error occurred: " + e.getMessage()); } } @Test public void testInitialization(){ try{ chord = new Chord(rand_note, rand_tone, rand_octave); assertEquals(rand_tone, chord.getTonality()); assertEquals(rand_octave, chord.getOctave()); assertEquals(rand_note, (int)chord.getNotes().get("root")); if(rand_tone.equals(Chord.Tonality.MINOR) || rand_tone.equals(Chord.Tonality.DIMINISHED)) assertEquals((rand_note + 3) % 12, (int)chord.getNotes().get("third")); else assertEquals((rand_note + 4) % 12, (int)chord.getNotes().get("third")); if(rand_tone.equals(Chord.Tonality.DIMINISHED)) assertEquals((rand_note + 6) % 12, (int)chord.getNotes().get("fifth")); else if(rand_tone.equals(Chord.Tonality.AUGMENTED)) assertEquals((rand_note + 8) % 12, (int)chord.getNotes().get("fifth")); else assertEquals((rand_note + 7) % 12, (int)chord.getNotes().get("fifth")); } catch (Exception e) { System.err.println("Oh no! An error occurred: " + e.getMessage()); } } @Test public void testInitializationEdgeCases(){ //test upper bound Chord upper_chord; try { upper_chord = new Chord(11, Chord.Tonality.MAJOR, 7); assertEquals(11, (int)upper_chord.getNotes().get("root")); assertEquals(3, (int)upper_chord.getNotes().get("third")); assertEquals(6, (int)upper_chord.getNotes().get("fifth")); } catch (Exception e) { System.err.println("Oh no! An error occurred: " + e.getMessage()); } //test lower bound Chord lower_chord; try { lower_chord = new Chord(0, Chord.Tonality.DIMINISHED, -7); assertEquals(0, (int)lower_chord.getNotes().get("root")); assertEquals(3, (int)lower_chord.getNotes().get("third")); assertEquals(6, (int)lower_chord.getNotes().get("fifth")); } catch (Exception e) { System.err.println("Oh no! An error occurred: " + e.getMessage()); } } @Test (expected = Exception.class) public void testNegativeChord() throws Exception{ new Chord(-1, Chord.Tonality.AUGMENTED, 0); } @Test (expected = Exception.class) public void testInvalidChord() throws Exception{ new Chord(12, Chord.Tonality.DIMINISHED, 0); } @Test public void testMakeMajor(){ int original_octave = chord.getOctave(); chord.makeMajor(); assertEquals((chord.getNotes().get("root") + 4) % 12, (int)chord.getNotes().get("third")); assertEquals((chord.getNotes().get("root") + 7) % 12, (int)chord.getNotes().get("fifth")); assertEquals(original_octave, chord.getOctave()); assertEquals(Chord.Tonality.MAJOR, chord.getTonality()); } @Test public void testMakeMinor(){ int original_octave = chord.getOctave(); chord.makeMinor(); assertEquals((chord.getNotes().get("root") + 3) % 12, (int)chord.getNotes().get("third")); assertEquals((chord.getNotes().get("root") + 7) % 12, (int)chord.getNotes().get("fifth")); assertEquals(original_octave, chord.getOctave()); assertEquals(Chord.Tonality.MINOR, chord.getTonality()); } @Test public void testMakeDiminished(){ int original_octave = chord.getOctave(); chord.makeDiminished(); assertEquals((chord.getNotes().get("root") + 3) % 12, (int)chord.getNotes().get("third")); assertEquals((chord.getNotes().get("root") + 6) % 12, (int)chord.getNotes().get("fifth")); assertEquals(original_octave, chord.getOctave()); assertEquals(Chord.Tonality.DIMINISHED, chord.getTonality()); } @Test public void testMakeAugmented(){ int original_octave = chord.getOctave(); chord.makeAugmented(); assertEquals((chord.getNotes().get("root") + 4) % 12, (int)chord.getNotes().get("third")); assertEquals((chord.getNotes().get("root") + 8) % 12, (int)chord.getNotes().get("fifth")); assertEquals(original_octave, chord.getOctave()); assertEquals(Chord.Tonality.AUGMENTED, chord.getTonality()); } @Test public void testChangeOctave(){ int original_octave = chord.getOctave(); chord.changeOctave(original_octave); assertEquals(original_octave, chord.getOctave()); chord.changeOctave(5); assertEquals(5, chord.getOctave()); chord.changeOctave(-3); assertEquals(-3, chord.getOctave()); } @Test public void testEquals(){ try{ chord = new Chord(rand_note, rand_tone, rand_octave); Chord chord2 = new Chord(rand_note, rand_tone, rand_octave); assertTrue(chord.equals(chord2)); assertTrue(chord2.equals(chord)); chord2.changeOctave(rand_octave + 1); assertFalse(chord.equals(chord2)); assertFalse(chord2.equals(chord)); chord2.changeOctave(rand_octave); assertTrue(chord.equals(chord2)); assertTrue(chord2.equals(chord)); chord.makeDiminished(); chord2.makeDiminished(); assertTrue(chord.equals(chord2)); assertTrue(chord2.equals(chord)); chord.makeMinor(); assertFalse(chord.equals(chord2)); assertFalse(chord2.equals(chord)); } catch (Exception e) { System.err.println("Oh no! An error occurred: " + e.getMessage()); } } }
package gov.nih.nci.cananolab.ui.particle; /** * This class sets up the submit a new nanoparticle sample page and submits a new nanoparticle sample * * @author pansu */ /* CVS $Id: SubmitNanoparticleAction.java,v 1.12 2008-04-21 23:12:02 pansu Exp $ */ import gov.nih.nci.cananolab.dto.common.UserBean; import gov.nih.nci.cananolab.dto.particle.ParticleBean; import gov.nih.nci.cananolab.exception.CaNanoLabSecurityException; import gov.nih.nci.cananolab.service.particle.NanoparticleSampleService; import gov.nih.nci.cananolab.service.security.AuthorizationService; import gov.nih.nci.cananolab.ui.core.AbstractDispatchAction; import gov.nih.nci.cananolab.ui.security.InitSecuritySetup; import gov.nih.nci.cananolab.util.CaNanoLabConstants; import java.util.Date; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.validator.DynaValidatorForm; public class SubmitNanoparticleAction extends AbstractDispatchAction { public ActionForward create(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionForward forward = null; DynaValidatorForm theForm = (DynaValidatorForm) form; ParticleBean particleSampleBean = (ParticleBean) theForm .get("particleSampleBean"); UserBean user = (UserBean) request.getSession().getAttribute("user"); particleSampleBean.getParticleSample() .setCreatedBy(user.getLoginName()); particleSampleBean.getParticleSample().setCreatedDate(new Date()); // persist in the database NanoparticleSampleService service = new NanoparticleSampleService(); service.saveNanoparticleSample(particleSampleBean); // set CSM visibility AuthorizationService authService = new AuthorizationService( CaNanoLabConstants.CSM_APP_NAME); authService.setVisibility(particleSampleBean.getParticleSample() .getName(), particleSampleBean.getVisibilityGroups()); theForm.set("particleSampleBean", particleSampleBean); forward = mapping.findForward("success"); request.setAttribute("theParticle", particleSampleBean); request.setAttribute("updateDataTree", "true"); InitNanoparticleSetup.getInstance().getDataTree(particleSampleBean, request); return forward; } public ActionForward setupUpdate(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(); InitNanoparticleSetup.getInstance().setAllNanoparticleSampleSources( request); InitSecuritySetup.getInstance().setAllVisibilityGroups(session); DynaValidatorForm theForm = (DynaValidatorForm) form; String particleId = request.getParameter("particleId"); UserBean user = (UserBean) session.getAttribute("user"); NanoparticleSampleService service = new NanoparticleSampleService(); ParticleBean particleSampleBean = service.findNanoparticleSampleById( particleId, user); theForm.set("particleSampleBean", particleSampleBean); request.setAttribute("theParticle", particleSampleBean); request.setAttribute("updateDataTree", "true"); InitNanoparticleSetup.getInstance().getDataTree(particleSampleBean, request); return mapping.findForward("update"); } public ActionForward setupView(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { return setupUpdate(mapping, form, request, response); } public ActionForward setup(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(); InitNanoparticleSetup.getInstance().setAllNanoparticleSampleSources( request); InitSecuritySetup.getInstance().setAllVisibilityGroups(session); return mapping.getInputForward(); } public boolean loginRequired() { return false; } public boolean canUserExecute(UserBean user) throws CaNanoLabSecurityException { return InitSecuritySetup.getInstance().userHasCreatePrivilege(user, CaNanoLabConstants.CSM_PG_PARTICLE); } }
package gov.nih.nci.cananolab.ui.particle; /** * This class sets up the submit a new nanoparticle sample page and submits a new nanoparticle sample * * @author pansu */ /* CVS $Id: SubmitNanoparticleAction.java,v 1.20 2008-04-30 22:11:25 pansu Exp $ */ import gov.nih.nci.cananolab.dto.common.UserBean; import gov.nih.nci.cananolab.dto.particle.ParticleBean; import gov.nih.nci.cananolab.exception.CaNanoLabSecurityException; import gov.nih.nci.cananolab.service.particle.NanoparticleSampleService; import gov.nih.nci.cananolab.service.security.AuthorizationService; import gov.nih.nci.cananolab.ui.security.InitSecuritySetup; import gov.nih.nci.cananolab.util.CaNanoLabConstants; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.validator.DynaValidatorForm; public class SubmitNanoparticleAction extends BaseAnnotationAction { public ActionForward create(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionForward forward = null; DynaValidatorForm theForm = (DynaValidatorForm) form; ParticleBean particleSampleBean = (ParticleBean) theForm .get("particleSampleBean"); particleSampleBean.setDomainParticleSample(); // persist in the database NanoparticleSampleService service = new NanoparticleSampleService(); service.saveNanoparticleSample(particleSampleBean .getDomainParticleSample()); // set CSM visibility // add sample source as a new CSM_GROUP and assign the sample to // the new group AuthorizationService authService = new AuthorizationService( CaNanoLabConstants.CSM_APP_NAME); String[] visibleGroups = new String[particleSampleBean .getVisibilityGroups().length + 1]; for (int i = 0; i < visibleGroups.length - 1; i++) { visibleGroups[i] = particleSampleBean.getVisibilityGroups()[i]; } visibleGroups[visibleGroups.length - 1] = particleSampleBean .getDomainParticleSample().getSource().getOrganizationName(); particleSampleBean.setVisibilityGroups(visibleGroups); authService.setVisibility(particleSampleBean.getDomainParticleSample() .getName(), visibleGroups); theForm.set("particleSampleBean", particleSampleBean); forward = mapping.findForward("success"); request.setAttribute("theParticle", particleSampleBean); request.setAttribute("updateDataTree", "true"); InitNanoparticleSetup.getInstance() .getDataTree( particleSampleBean.getDomainParticleSample().getId() .toString(), request); UserBean user = (UserBean) request.getSession().getAttribute("user"); InitNanoparticleSetup.getInstance().getNanoparticleSampleSources( request, user); InitSecuritySetup.getInstance().getAllVisibilityGroups(request); return forward; } public ActionForward setupUpdate(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; ParticleBean particleSampleBean = setupParticle(theForm, request); UserBean user = (UserBean) (request.getSession().getAttribute("user")); // set visibility NanoparticleSampleService service = new NanoparticleSampleService(); service.setVisibility(particleSampleBean, user); theForm.set("particleSampleBean", particleSampleBean); InitNanoparticleSetup.getInstance().getAllNanoparticleSampleSources( request); InitSecuritySetup.getInstance().getAllVisibilityGroups(request); setupDataTree(theForm, request); return mapping.findForward("update"); } public ActionForward setupView(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { return setupUpdate(mapping, form, request, response); } public ActionForward setup(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { UserBean user = (UserBean) request.getSession().getAttribute("user"); InitNanoparticleSetup.getInstance().getNanoparticleSampleSources(request, user); InitSecuritySetup.getInstance().getAllVisibilityGroups(request); return mapping.getInputForward(); } public boolean loginRequired() { return true; } public boolean canUserExecute(UserBean user) throws CaNanoLabSecurityException { return InitSecuritySetup.getInstance().userHasCreatePrivilege(user, CaNanoLabConstants.CSM_PG_PARTICLE); } }
package gov.nih.nci.cananolab.ui.publication; import gov.nih.nci.cananolab.domain.common.Author; import gov.nih.nci.cananolab.dto.common.PublicationBean; import gov.nih.nci.cananolab.dto.common.UserBean; import gov.nih.nci.cananolab.exception.ExperimentConfigException; import gov.nih.nci.cananolab.exception.PublicationException; import gov.nih.nci.cananolab.service.common.LookupService; import gov.nih.nci.cananolab.service.publication.PubMedXMLHandler; import gov.nih.nci.cananolab.ui.core.InitSetup; import gov.nih.nci.cananolab.ui.sample.InitSampleSetup; import gov.nih.nci.cananolab.util.Constants; import java.util.SortedSet; import javax.servlet.http.HttpServletRequest; import org.apache.log4j.Logger; import org.apache.struts.validator.DynaValidatorForm; import org.directwebremoting.WebContext; import org.directwebremoting.WebContextFactory; public class DWRPublicationManager { Logger logger = Logger.getLogger(DWRPublicationManager.class); public DWRPublicationManager() { } public PublicationBean retrievePubMedInfo(String pubmedID) { PubMedXMLHandler phandler = PubMedXMLHandler.getInstance(); WebContext wctx = WebContextFactory.get(); PublicationForm form = (PublicationForm) wctx.getSession() .getAttribute("publicationForm"); PublicationBean pbean = (PublicationBean) form.get("publication"); if (pubmedID != null && pubmedID.length() > 0 && !pubmedID.equals("0")) { Long pubMedIDLong = 0L; try { pubMedIDLong = Long.valueOf(pubmedID); } catch (Exception ex) { logger.error("invalid PubMed ID"); return null; } phandler.parsePubMedXML(pubMedIDLong, pbean); } return pbean; } public String[] getPublicationCategories(String searchLocations) { WebContext wctx = WebContextFactory.get(); HttpServletRequest request = wctx.getHttpServletRequest(); try { boolean isLocal = false; if (Constants.LOCAL_SITE.equals(searchLocations)) { isLocal = true; } SortedSet<String> types = null; if (isLocal) { types = InitSetup.getInstance().getDefaultAndOtherLookupTypes( request, "publicationCategories", "Publication", "category", "otherCategory", true); } else { types = LookupService.findLookupValues("Publication", "category"); } types.add(""); String[] eleArray = new String[types.size()]; return types.toArray(eleArray); } catch (Exception e) { logger.error("Problem getting publication types: \n", e); e.printStackTrace(); } return new String[] { "" }; } public String[] getPublicationStatuses(String searchLocations) { WebContext wctx = WebContextFactory.get(); HttpServletRequest request = wctx.getHttpServletRequest(); try { boolean isLocal = false; if (Constants.LOCAL_SITE.equals(searchLocations)) { isLocal = true; } SortedSet<String> types = null; if (isLocal) { types = InitSetup.getInstance().getDefaultAndOtherLookupTypes( request, "publicationStatuses", "Publication", "status", "otherStatus", true); } else { types = LookupService.findLookupValues("Publication", "status"); } types.add(""); String[] eleArray = new String[types.size()]; return types.toArray(eleArray); } catch (Exception e) { logger.error("Problem getting publication statuses: \n", e); e.printStackTrace(); } return new String[] { "" }; } public String[] getAllSampleNames() { WebContext wctx = WebContextFactory.get(); UserBean user = (UserBean) wctx.getSession().getAttribute("user"); if (user == null) { return null; } try { SortedSet<String> allSampleNames = InitSampleSetup.getInstance() .getAllSampleNames(wctx.getHttpServletRequest(), user); return allSampleNames.toArray(new String[0]); } catch (Exception e) { logger.error("Problem getting all sample names for publication submission \n", e); return new String[]{""}; } } public PublicationBean addAuthor(Author author) throws PublicationException { DynaValidatorForm pubForm = (DynaValidatorForm) (WebContextFactory .get().getSession().getAttribute("publicationForm")); if (pubForm == null) { return null; } PublicationBean pubBean = (PublicationBean) (pubForm.get("publication")); pubBean.addAuthor(author); return pubBean; } public PublicationBean deleteAuthor(Author author) throws ExperimentConfigException { DynaValidatorForm pubForm = (DynaValidatorForm) (WebContextFactory .get().getSession().getAttribute("publicationForm")); if (pubForm == null) { return null; } PublicationBean pubBean = (PublicationBean) (pubForm.get("publication")); pubBean.removeAuthor(author); return pubBean; } }
package org.rstudio.studio.client.workbench.ui; import com.google.gwt.animation.client.Animation; import com.google.gwt.core.client.JsArray; import com.google.gwt.core.client.JsArrayString; import com.google.gwt.dom.client.Element; import com.google.gwt.event.logical.shared.SelectionEvent; import com.google.gwt.event.logical.shared.SelectionHandler; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.user.client.Command; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.SplitterResizedEvent; import com.google.gwt.user.client.ui.Widget; import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.name.Named; import org.rstudio.core.client.Debug; import org.rstudio.core.client.Triad; import org.rstudio.core.client.command.AppCommand; import org.rstudio.core.client.command.CommandBinder; import org.rstudio.core.client.command.Handler; import org.rstudio.core.client.dom.DomUtils; import org.rstudio.core.client.events.ManageLayoutCommandsEvent; import org.rstudio.core.client.events.WindowEnsureVisibleEvent; import org.rstudio.core.client.events.WindowStateChangeEvent; import org.rstudio.core.client.js.JsObject; import org.rstudio.core.client.layout.DualWindowLayoutPanel; import org.rstudio.core.client.layout.LogicalWindow; import org.rstudio.core.client.layout.WindowState; import org.rstudio.core.client.theme.MinimizedModuleTabLayoutPanel; import org.rstudio.core.client.theme.MinimizedWindowFrame; import org.rstudio.core.client.theme.PrimaryWindowFrame; import org.rstudio.core.client.theme.WindowFrame; import org.rstudio.core.client.theme.res.ThemeResources; import org.rstudio.core.client.widget.ToolbarButton; import org.rstudio.studio.client.application.events.EventBus; import org.rstudio.studio.client.workbench.commands.Commands; import org.rstudio.studio.client.workbench.events.ZoomPaneEvent; import org.rstudio.studio.client.workbench.model.ClientState; import org.rstudio.studio.client.workbench.model.Session; import org.rstudio.studio.client.workbench.model.WorkbenchServerOperations; import org.rstudio.studio.client.workbench.model.helper.IntStateValue; import org.rstudio.studio.client.workbench.model.helper.JSObjectStateValue; import org.rstudio.studio.client.workbench.prefs.model.UIPrefs; import org.rstudio.studio.client.workbench.views.console.ConsoleInterruptButton; import org.rstudio.studio.client.workbench.views.console.ConsolePane; import org.rstudio.studio.client.workbench.views.output.find.FindOutputTab; import org.rstudio.studio.client.workbench.views.output.markers.MarkersOutputTab; import org.rstudio.studio.client.workbench.views.source.SourceShim; import org.rstudio.studio.client.workbench.views.source.SourceWindowManager; import org.rstudio.studio.client.workbench.views.source.model.SourceDocument; import java.util.ArrayList; import java.util.HashMap; import java.util.List; /* * TODO: Push client state when selected tab or layout changes */ public class PaneManager { public interface Binder extends CommandBinder<Commands, PaneManager> {} public enum Tab { History, Files, Plots, Packages, Help, VCS, Build, Presentation, Environment, Viewer, Source, Console } class SelectedTabStateValue extends IntStateValue { SelectedTabStateValue(String name, WorkbenchTabPanel tabPanel) { super("workbench-pane", name, ClientState.PROJECT_PERSISTENT, session_.getSessionInfo().getClientState(), true); tabPanel_ = tabPanel; finishInit(session_.getSessionInfo().getClientState()); } @Override protected void onInit(Integer value) { if (value != null) tabPanel_.selectTab(value); } @Override protected Integer getValue() { return tabPanel_.getSelectedIndex(); } private final WorkbenchTabPanel tabPanel_; } private class ZoomedTabStateValue extends JSObjectStateValue { public ZoomedTabStateValue() { super("workbench-pane", "TabZoom", ClientState.PROJECT_PERSISTENT, session_.getSessionInfo().getClientState(), true); finishInit(session_.getSessionInfo().getClientState()); } @Override protected void onInit(final JsObject value) { if (value == null) return; if (!value.hasKey(MAXIMIZED_TAB_KEY) || !value.hasKey(WIDGET_SIZE_KEY)) return; // Time-out action just to ensure all client state is ready new Timer() { @Override public void run() { String tabString = value.getString(MAXIMIZED_TAB_KEY); double widgetSize = value.getDouble(WIDGET_SIZE_KEY); maximizedTab_ = Tab.valueOf(tabString); maximizedWindow_ = getWindowForTab(maximizedTab_); widgetSizePriorToZoom_ = widgetSize; fullyMaximizeWindow(maximizedWindow_, maximizedTab_); manageLayoutCommands(); } }.schedule(200); } @Override protected boolean hasChanged() { JsObject oldValue = lastValue_; JsObject newValue = getValue(); boolean oldHasKey = oldValue.hasKey(MAXIMIZED_TAB_KEY); boolean newHasKey = newValue.hasKey(MAXIMIZED_TAB_KEY); if (oldHasKey && newHasKey) return !oldValue.getString(MAXIMIZED_TAB_KEY).equals(newValue.getString(MAXIMIZED_TAB_KEY)); return oldHasKey != newHasKey; } @Override protected JsObject getValue() { final JsObject object = JsObject.createJsObject(); if (maximizedTab_ != null) object.setString(MAXIMIZED_TAB_KEY, maximizedTab_.toString()); if (widgetSizePriorToZoom_ >= 0) object.setDouble(WIDGET_SIZE_KEY, widgetSizePriorToZoom_); lastValue_ = object; return object; } private static final String MAXIMIZED_TAB_KEY = "MaximizedTab"; private static final String WIDGET_SIZE_KEY = "WidgetSize"; private JsObject lastValue_; } private LogicalWindow getWindowForTab(Tab tab) { switch (tab) { case Console: return getConsoleLogicalWindow(); case Source: return getSourceLogicalWindow(); default: return getOwnerTabPanel(tab).getParentWindow(); } } @Inject public PaneManager(Provider<MainSplitPanel> pSplitPanel, WorkbenchServerOperations server, EventBus eventBus, Session session, Binder binder, Commands commands, UIPrefs uiPrefs, @Named("Console") final Widget consolePane, ConsoleInterruptButton consoleInterrupt, SourceShim source, @Named("History") final WorkbenchTab historyTab, @Named("Files") final WorkbenchTab filesTab, @Named("Plots") final WorkbenchTab plotsTab, @Named("Packages") final WorkbenchTab packagesTab, @Named("Help") final WorkbenchTab helpTab, @Named("VCS") final WorkbenchTab vcsTab, @Named("Build") final WorkbenchTab buildTab, @Named("Presentation") final WorkbenchTab presentationTab, @Named("Environment") final WorkbenchTab environmentTab, @Named("Viewer") final WorkbenchTab viewerTab, @Named("Compile PDF") final WorkbenchTab compilePdfTab, @Named("Source Cpp") final WorkbenchTab sourceCppTab, @Named("R Markdown") final WorkbenchTab renderRmdTab, @Named("Deploy") final WorkbenchTab deployContentTab, final MarkersOutputTab markersTab, final FindOutputTab findOutputTab) { eventBus_ = eventBus; session_ = session; commands_ = commands; consolePane_ = (ConsolePane)consolePane; consoleInterrupt_ = consoleInterrupt; source_ = source; historyTab_ = historyTab; filesTab_ = filesTab; plotsTab_ = plotsTab; packagesTab_ = packagesTab; helpTab_ = helpTab; vcsTab_ = vcsTab; buildTab_ = buildTab; presentationTab_ = presentationTab; environmentTab_ = environmentTab; viewerTab_ = viewerTab; compilePdfTab_ = compilePdfTab; findOutputTab_ = findOutputTab; sourceCppTab_ = sourceCppTab; renderRmdTab_ = renderRmdTab; deployContentTab_ = deployContentTab; markersTab_ = markersTab; binder.bind(commands, this); PaneConfig config = validateConfig(uiPrefs.paneConfig().getValue()); initPanes(config); panes_ = createPanes(config); left_ = createSplitWindow(panes_.get(0), panes_.get(1), "left", 0.4); right_ = createSplitWindow(panes_.get(2), panes_.get(3), "right", 0.6); panel_ = pSplitPanel.get(); panel_.initialize(left_, right_); // count the number of source docs assigned to this window JsArray<SourceDocument> docs = session_.getSessionInfo().getSourceDocuments(); String windowId = SourceWindowManager.getSourceWindowId(); int numDocs = 0; for (int i = 0; i < docs.length(); i++) { String docWindowId = docs.get(i).getSourceWindowId(); if (docWindowId == windowId) { numDocs++; } } if (numDocs == 0 && sourceLogicalWindow_.getState() != WindowState.HIDE) { sourceLogicalWindow_.onWindowStateChange( new WindowStateChangeEvent(WindowState.HIDE)); } else if (numDocs > 0 && sourceLogicalWindow_.getState() == WindowState.HIDE) { sourceLogicalWindow_.onWindowStateChange( new WindowStateChangeEvent(WindowState.NORMAL)); } uiPrefs.paneConfig().addValueChangeHandler(new ValueChangeHandler<PaneConfig>() { public void onValueChange(ValueChangeEvent<PaneConfig> evt) { ArrayList<LogicalWindow> newPanes = createPanes(validateConfig(evt.getValue())); panes_ = newPanes; left_.replaceWindows(newPanes.get(0), newPanes.get(1)); right_.replaceWindows(newPanes.get(2), newPanes.get(3)); tabSet1TabPanel_.clear(); tabSet2TabPanel_.clear(); populateTabPanel(tabNamesToTabs(evt.getValue().getTabSet1()), tabSet1TabPanel_, tabSet1MinPanel_); populateTabPanel(tabNamesToTabs(evt.getValue().getTabSet2()), tabSet2TabPanel_, tabSet2MinPanel_); } }); eventBus_.addHandler(ZoomPaneEvent.TYPE, new ZoomPaneEvent.Handler() { @Override public void onZoomPane(ZoomPaneEvent event) { String pane = event.getPane(); LogicalWindow window = panesByName_.get(pane); assert window != null : "No pane with name '" + pane + "'"; toggleWindowZoom(window, tabForName(event.getTab())); } }); eventBus_.addHandler(WindowEnsureVisibleEvent.TYPE, new WindowEnsureVisibleEvent.Handler() { @Override public void onWindowEnsureVisible(WindowEnsureVisibleEvent event) { final LogicalWindow window = getLogicalWindow(event.getWindowFrame()); if (window == null) return; // If we're currently zooming a pane, and we're now ensuring // a separate window is visible (e.g. a pane raising itself), // then transfer zoom to that window. if (maximizedWindow_ != null && !maximizedWindow_.equals(window)) { fullyMaximizeWindow(window, lastSelectedTab_); return; } int width = window.getActiveWidget().getOffsetWidth(); // If the widget is already visible horizontally, then bail // (other logic handles vertical visibility) if (width > 0) return; final Command afterAnimation = new Command() { @Override public void execute() { window.getNormal().onResize(); } }; int newWidth = computeAppropriateWidth(); resizeHorizontally(0, newWidth, afterAnimation); } }); eventBus_.addHandler( ManageLayoutCommandsEvent.TYPE, new ManageLayoutCommandsEvent.Handler() { @Override public void onManageLayoutCommands(ManageLayoutCommandsEvent event) { manageLayoutCommands(); } }); manageLayoutCommands(); new ZoomedTabStateValue(); } int computeAppropriateWidth() { double windowWidth = Window.getClientWidth(); double candidateWidth = 2.0 * windowWidth / 5.0; return (int) candidateWidth; } LogicalWindow getLogicalWindow(WindowFrame frame) { for (LogicalWindow window : panes_) if (window.getNormal() == frame) return window; return null; } LogicalWindow getParentLogicalWindow(Element el) { LogicalWindow targetWindow = null; while (el != null && targetWindow == null) { el = el.getParentElement(); for (LogicalWindow window : panes_) { if (el.equals(window.getActiveWidget().getElement())) { targetWindow = window; break; } } } return targetWindow; } public LogicalWindow getActiveLogicalWindow() { Element activeEl = DomUtils.getActiveElement(); return getParentLogicalWindow(activeEl); } @Handler public void onLayoutZoomCurrentPane() { LogicalWindow activeWindow = getActiveLogicalWindow(); if (activeWindow == null) return; toggleWindowZoom(activeWindow, null); } @Handler public void onLayoutEndZoom() { restoreLayout(); } private <T> boolean equals(T lhs, T rhs) { if (lhs == null) return rhs == null; return lhs.equals(rhs); } public void toggleWindowZoom(LogicalWindow window, Tab tab) { if (isAnimating_) return; boolean hasZoom = maximizedWindow_ != null; if (hasZoom) { if (equals(window, maximizedWindow_)) { // If we're zooming a different tab in the same window, // just activate that tab. if (!equals(tab, maximizedTab_)) { maximizedTab_ = tab; manageLayoutCommands(); activateTab(tab); } // Otherwise, we're trying to maximize the same tab // and the same window. Interpret this as a toggle off. else { restoreLayout(); } } else { // We're transferring zoom from one window to another -- // maximize the new window. fullyMaximizeWindow(window, tab); } } else { // No zoom currently on -- just zoom the selected window + tab. fullyMaximizeWindow(window, tab); } } private void fullyMaximizeWindow(final LogicalWindow window, final Tab tab) { if (window.equals(getSourceLogicalWindow())) maximizedTab_ = Tab.Source; else if (window.equals(getConsoleLogicalWindow())) maximizedTab_ = Tab.Console; else maximizedTab_ = tab; maximizedWindow_ = window; manageLayoutCommands(); panel_.setSplitterEnabled(false); if (widgetSizePriorToZoom_ < 0) widgetSizePriorToZoom_ = panel_.getWidgetSize(right_); // Put all of the panes in NORMAL mode, just to ensure an appropriate // transfer to EXCLUSIVE mode works. (It seems that 'exclusive' -> 'exclusive' // transfers don't always propagate as expected) for (LogicalWindow pane : panes_) pane.onWindowStateChange(new WindowStateChangeEvent(WindowState.NORMAL)); boolean isLeftWidget = DomUtils.contains(left_.getElement(), window.getActiveWidget().getElement()); window.onWindowStateChange(new WindowStateChangeEvent(WindowState.EXCLUSIVE)); final double initialSize = panel_.getWidgetSize(right_); double targetSize = isLeftWidget ? 0 : panel_.getOffsetWidth(); if (targetSize < 0) targetSize = 0; resizeHorizontally(initialSize, targetSize); } private void resizeHorizontally(final double start, final double end) { resizeHorizontally(start, end, null); } private void resizeHorizontally(final double start, final double end, final Command afterComplete) { horizontalResizeAnimation(start, end, afterComplete).run(300); } private Animation horizontalResizeAnimation(final double start, final double end, final Command afterComplete) { return new Animation() { @Override protected void onUpdate(double progress) { double size = (1 - progress) * start + progress * end; panel_.setWidgetSize(right_, size); } @Override protected void onStart() { isAnimating_ = true; super.onStart(); } @Override protected void onComplete() { isAnimating_ = false; panel_.onSplitterResized(new SplitterResizedEvent()); super.onComplete(); if (afterComplete != null) afterComplete.execute(); } }; } private void restoreLayout() { // If we're currently zoomed, then use that to provide the previous // 'non-zoom' state. if (maximizedWindow_ != null) restoreSavedLayout(); else restoreFourPaneLayout(); } private void invalidateSavedLayoutState(boolean enableSplitter) { maximizedWindow_ = null; maximizedTab_ = null; widgetSizePriorToZoom_ = -1; panel_.setSplitterEnabled(enableSplitter); manageLayoutCommands(); } private void restoreFourPaneLayout() { // Ensure that all windows are in the 'normal' state. This allows // hidden windows to display themselves, and so on. This also forces // widgets to size themselves vertically. for (LogicalWindow window : panes_) window.onWindowStateChange(new WindowStateChangeEvent(WindowState.NORMAL, true)); double rightWidth = panel_.getWidgetSize(right_); double panelWidth = panel_.getOffsetWidth(); double minThreshold = (2.0 / 5.0) * panelWidth; double maxThreshold = (3.0 / 5.0) * panelWidth; if (rightWidth <= minThreshold) resizeHorizontally(rightWidth, minThreshold); else if (rightWidth >= maxThreshold) resizeHorizontally(rightWidth, maxThreshold); invalidateSavedLayoutState(true); } private void restoreSavedLayout() { // Ensure that all windows are in the 'normal' state. This allows // hidden windows to display themselves, and so on. for (LogicalWindow window : panes_) window.onWindowStateChange(new WindowStateChangeEvent(WindowState.NORMAL, true)); maximizedWindow_.onWindowStateChange(new WindowStateChangeEvent(WindowState.NORMAL, true)); resizeHorizontally(panel_.getWidgetSize(right_), widgetSizePriorToZoom_); invalidateSavedLayoutState(true); } @Handler public void onMaximizeConsole() { LogicalWindow consoleWindow = panesByName_.get("Console"); if (consoleWindow.getState() != WindowState.MAXIMIZE) { consoleWindow.onWindowStateChange( new WindowStateChangeEvent(WindowState.MAXIMIZE)); } } private ArrayList<LogicalWindow> createPanes(PaneConfig config) { ArrayList<LogicalWindow> results = new ArrayList<LogicalWindow>(); JsArrayString panes = config.getPanes(); for (int i = 0; i < 4; i++) { results.add(panesByName_.get(panes.get(i))); } return results; } private void initPanes(PaneConfig config) { panesByName_ = new HashMap<String, LogicalWindow>(); panesByName_.put("Console", createConsole()); panesByName_.put("Source", createSource()); Triad<LogicalWindow, WorkbenchTabPanel, MinimizedModuleTabLayoutPanel> ts1 = createTabSet( "TabSet1", tabNamesToTabs(config.getTabSet1())); panesByName_.put("TabSet1", ts1.first); tabSet1TabPanel_ = ts1.second; tabSet1MinPanel_ = ts1.third; Triad<LogicalWindow, WorkbenchTabPanel, MinimizedModuleTabLayoutPanel> ts2 = createTabSet( "TabSet2", tabNamesToTabs(config.getTabSet2())); panesByName_.put("TabSet2", ts2.first); tabSet2TabPanel_ = ts2.second; tabSet2MinPanel_ = ts2.third; } private ArrayList<Tab> tabNamesToTabs(JsArrayString tabNames) { ArrayList<Tab> tabList = new ArrayList<Tab>(); for (int j = 0; j < tabNames.length(); j++) tabList.add(Enum.valueOf(Tab.class, tabNames.get(j))); return tabList; } private PaneConfig validateConfig(PaneConfig config) { if (config == null) config = PaneConfig.createDefault(); if (!config.validateAndAutoCorrect()) { Debug.log("Pane config is not valid"); config = PaneConfig.createDefault(); } return config; } public MainSplitPanel getPanel() { return panel_; } public WorkbenchTab getTab(Tab tab) { switch (tab) { case History: return historyTab_; case Files: return filesTab_; case Plots: return plotsTab_; case Packages: return packagesTab_; case Help: return helpTab_; case VCS: return vcsTab_; case Build: return buildTab_; case Presentation: return presentationTab_; case Environment: return environmentTab_; case Viewer: return viewerTab_; case Source: case Console: // not 'real' tabs so should be an error to ask for their tabs } throw new IllegalArgumentException("Unknown tab"); } public WorkbenchTab[] getAllTabs() { return new WorkbenchTab[] { historyTab_, filesTab_, plotsTab_, packagesTab_, helpTab_, vcsTab_, buildTab_, presentationTab_, environmentTab_, viewerTab_}; } public void activateTab(Tab tab) { lastSelectedTab_ = tab; WorkbenchTabPanel panel = getOwnerTabPanel(tab); // Ensure that the pane is visible (otherwise tab selection will fail) LogicalWindow parent = panel.getParentWindow(); if (parent.getState() == WindowState.MINIMIZE || parent.getState() == WindowState.HIDE) { parent.onWindowStateChange(new WindowStateChangeEvent(WindowState.NORMAL)); } int index = tabToIndex_.get(tab); panel.selectTab(index); } public void activateTab(String tabName) { Tab tab = tabForName(tabName); if (tab != null) activateTab(tab); } public void zoomTab(Tab tab) { activateTab(tab); WorkbenchTabPanel tabPanel = getOwnerTabPanel(tab); LogicalWindow parentWindow = tabPanel.getParentWindow(); if (parentWindow == null) return; toggleWindowZoom(parentWindow, tab); } public ConsolePane getConsole() { return consolePane_; } public WorkbenchTabPanel getOwnerTabPanel(Tab tab) { return tabToPanel_.get(tab); } public LogicalWindow getSourceLogicalWindow() { return sourceLogicalWindow_; } public LogicalWindow getConsoleLogicalWindow() { return panesByName_.get("Console"); } private DualWindowLayoutPanel createSplitWindow(LogicalWindow top, LogicalWindow bottom, String name, double bottomDefaultPct) { return new DualWindowLayoutPanel( eventBus_, top, bottom, session_, name, WindowState.NORMAL, (int) (Window.getClientHeight()*bottomDefaultPct)); } private LogicalWindow createConsole() { PrimaryWindowFrame frame = new PrimaryWindowFrame("Console", null); ToolbarButton goToWorkingDirButton = commands_.goToWorkingDir().createToolbarButton(); goToWorkingDirButton.addStyleName( ThemeResources.INSTANCE.themeStyles().windowFrameToolbarButton()); LogicalWindow logicalWindow = new LogicalWindow(frame, new MinimizedWindowFrame("Console")); @SuppressWarnings("unused") ConsoleTabPanel consoleTabPanel = new ConsoleTabPanel(frame, logicalWindow, consolePane_, compilePdfTab_, findOutputTab_, sourceCppTab_, renderRmdTab_, deployContentTab_, markersTab_, eventBus_, consoleInterrupt_, goToWorkingDirButton); return logicalWindow; } private LogicalWindow createSource() { WindowFrame sourceFrame = new WindowFrame(); sourceFrame.setFillWidget(source_.asWidget()); source_.forceLoad(); return sourceLogicalWindow_ = new LogicalWindow( sourceFrame, new MinimizedWindowFrame("Source")); } private Triad<LogicalWindow, WorkbenchTabPanel, MinimizedModuleTabLayoutPanel> createTabSet(String persisterName, ArrayList<Tab> tabs) { final WindowFrame frame = new WindowFrame(); final MinimizedModuleTabLayoutPanel minimized = new MinimizedModuleTabLayoutPanel(); final LogicalWindow logicalWindow = new LogicalWindow(frame, minimized); final WorkbenchTabPanel tabPanel = new WorkbenchTabPanel(frame, logicalWindow); populateTabPanel(tabs, tabPanel, minimized); frame.setFillWidget(tabPanel); minimized.addSelectionHandler(new SelectionHandler<Integer>() { public void onSelection(SelectionEvent<Integer> integerSelectionEvent) { int tab = integerSelectionEvent.getSelectedItem(); tabPanel.selectTab(tab); } }); tabPanel.addSelectionHandler(new SelectionHandler<Integer>() { public void onSelection(SelectionEvent<Integer> integerSelectionEvent) { int index = integerSelectionEvent.getSelectedItem(); WorkbenchTab selected = tabPanel.getTab(index); lastSelectedTab_ = workbenchTabToTab(selected); session_.persistClientState(); } }); new SelectedTabStateValue(persisterName, tabPanel); return new Triad<LogicalWindow, WorkbenchTabPanel, MinimizedModuleTabLayoutPanel>( logicalWindow, tabPanel, minimized); } private Tab workbenchTabToTab(WorkbenchTab tab) { return wbTabToTab_.get(tab); } private void populateTabPanel(ArrayList<Tab> tabs, WorkbenchTabPanel tabPanel, MinimizedModuleTabLayoutPanel minimized) { ArrayList<WorkbenchTab> tabList = new ArrayList<WorkbenchTab>(); for (int i = 0; i < tabs.size(); i++) { Tab tab = tabs.get(i); WorkbenchTab wbTab = getTab(tab); wbTabToTab_.put(wbTab, tab); tabToPanel_.put(tab, tabPanel); tabToIndex_.put(tab, i); tabList.add(wbTab); } tabPanel.setTabs(tabList); ArrayList<String> labels = new ArrayList<String>(); for (Tab tab : tabs) { if (!getTab(tab).isSuppressed()) labels.add(getTabLabel(tab)); } minimized.setTabs(labels.toArray(new String[labels.size()])); } private String getTabLabel(Tab tab) { switch (tab) { case VCS: return getTab(tab).getTitle(); case Presentation: return getTab(tab).getTitle(); default: return tab.toString(); } } private Tab tabForName(String name) { if (name.equalsIgnoreCase("history")) return Tab.History; if (name.equalsIgnoreCase("files")) return Tab.Files; if (name.equalsIgnoreCase("plots")) return Tab.Plots; if (name.equalsIgnoreCase("packages")) return Tab.Packages; if (name.equalsIgnoreCase("help")) return Tab.Help; if (name.equalsIgnoreCase("vcs")) return Tab.VCS; if (name.equalsIgnoreCase("build")) return Tab.Build; if (name.equalsIgnoreCase("presentation")) return Tab.Presentation; if (name.equalsIgnoreCase("environment")) return Tab.Environment; if (name.equalsIgnoreCase("viewer")) return Tab.Viewer; if (name.equalsIgnoreCase("source")) return Tab.Source; if (name.equalsIgnoreCase("console")) return Tab.Console; return null; } private AppCommand getLayoutCommandForTab(Tab tab) { if (tab == null) return commands_.layoutEndZoom(); switch (tab) { case Build: return commands_.layoutZoomBuild(); case Console: return commands_.layoutZoomConsole(); case Environment: return commands_.layoutZoomEnvironment(); case Files: return commands_.layoutZoomFiles(); case Help: return commands_.layoutZoomHelp(); case History: return commands_.layoutZoomHistory(); case Packages: return commands_.layoutZoomPackages(); case Plots: return commands_.layoutZoomPlots(); case Presentation: return commands_.layoutZoomPresentation(); case Source: return commands_.layoutZoomSource(); case VCS: return commands_.layoutZoomVcs(); default: throw new IllegalArgumentException("Unexpected tab '" + tab.toString() + "'"); } } private void manageLayoutCommands() { List<AppCommand> layoutCommands = getLayoutCommands(); AppCommand activeCommand = getLayoutCommandForTab(maximizedTab_); for (AppCommand command : layoutCommands) command.setChecked(activeCommand.equals(command)); } private List<AppCommand> getLayoutCommands() { List<AppCommand> commands = new ArrayList<AppCommand>(); commands.add(commands_.layoutEndZoom()); commands.add(commands_.layoutZoomBuild()); commands.add(commands_.layoutZoomConsole()); commands.add(commands_.layoutZoomEnvironment()); commands.add(commands_.layoutZoomFiles()); commands.add(commands_.layoutZoomHelp()); commands.add(commands_.layoutZoomHistory()); commands.add(commands_.layoutZoomPackages()); commands.add(commands_.layoutZoomPlots()); commands.add(commands_.layoutZoomPresentation()); commands.add(commands_.layoutZoomSource()); commands.add(commands_.layoutZoomVcs()); return commands; } private final EventBus eventBus_; private final Session session_; private final Commands commands_; private final FindOutputTab findOutputTab_; private final WorkbenchTab compilePdfTab_; private final WorkbenchTab sourceCppTab_; private final ConsolePane consolePane_; private final ConsoleInterruptButton consoleInterrupt_; private final SourceShim source_; private final WorkbenchTab historyTab_; private final WorkbenchTab filesTab_; private final WorkbenchTab plotsTab_; private final WorkbenchTab packagesTab_; private final WorkbenchTab helpTab_; private final WorkbenchTab vcsTab_; private final WorkbenchTab buildTab_; private final WorkbenchTab presentationTab_; private final WorkbenchTab environmentTab_; private final WorkbenchTab viewerTab_; private final WorkbenchTab renderRmdTab_; private final WorkbenchTab deployContentTab_; private final MarkersOutputTab markersTab_; private MainSplitPanel panel_; private LogicalWindow sourceLogicalWindow_; private final HashMap<Tab, WorkbenchTabPanel> tabToPanel_ = new HashMap<Tab, WorkbenchTabPanel>(); private final HashMap<Tab, Integer> tabToIndex_ = new HashMap<Tab, Integer>(); private final HashMap<WorkbenchTab, Tab> wbTabToTab_ = new HashMap<WorkbenchTab, Tab>(); private HashMap<String, LogicalWindow> panesByName_; private DualWindowLayoutPanel left_; private DualWindowLayoutPanel right_; private ArrayList<LogicalWindow> panes_; private WorkbenchTabPanel tabSet1TabPanel_; private MinimizedModuleTabLayoutPanel tabSet1MinPanel_; private WorkbenchTabPanel tabSet2TabPanel_; private MinimizedModuleTabLayoutPanel tabSet2MinPanel_; private Tab lastSelectedTab_ = null; private LogicalWindow maximizedWindow_ = null; private Tab maximizedTab_ = null; private double widgetSizePriorToZoom_ = -1; private boolean isAnimating_ = false; }
package info.guardianproject.otr.app.im.plugin.xmpp; import info.guardianproject.otr.app.im.engine.Address; import info.guardianproject.otr.app.im.engine.ChatGroupManager; import info.guardianproject.otr.app.im.engine.ChatSession; import info.guardianproject.otr.app.im.engine.ChatSessionManager; import info.guardianproject.otr.app.im.engine.Contact; import info.guardianproject.otr.app.im.engine.ContactList; import info.guardianproject.otr.app.im.engine.ContactListListener; import info.guardianproject.otr.app.im.engine.ContactListManager; import info.guardianproject.otr.app.im.engine.ImConnection; import info.guardianproject.otr.app.im.engine.ImErrorInfo; import info.guardianproject.otr.app.im.engine.ImException; import info.guardianproject.otr.app.im.engine.Message; import info.guardianproject.otr.app.im.engine.Presence; import info.guardianproject.otr.app.im.provider.Imps; import info.guardianproject.util.DNSUtil; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.security.KeyStore; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import org.apache.harmony.javax.security.auth.callback.Callback; import org.apache.harmony.javax.security.auth.callback.CallbackHandler; import org.jivesoftware.smack.Connection; import org.jivesoftware.smack.ConnectionConfiguration; import org.jivesoftware.smack.ConnectionConfiguration.SecurityMode; import org.jivesoftware.smack.ConnectionCreationListener; import org.jivesoftware.smack.ConnectionListener; import org.jivesoftware.smack.PacketCollector; import org.jivesoftware.smack.PacketListener; import org.jivesoftware.smack.Roster; import org.jivesoftware.smack.RosterEntry; import org.jivesoftware.smack.RosterGroup; import org.jivesoftware.smack.RosterListener; import org.jivesoftware.smack.SASLAuthentication; import org.jivesoftware.smack.SmackConfiguration; import org.jivesoftware.smack.XMPPConnection; import org.jivesoftware.smack.XMPPException; import org.jivesoftware.smack.filter.AndFilter; import org.jivesoftware.smack.filter.PacketFilter; import org.jivesoftware.smack.filter.PacketIDFilter; import org.jivesoftware.smack.filter.PacketTypeFilter; import org.jivesoftware.smack.packet.IQ; import org.jivesoftware.smack.packet.Packet; import org.jivesoftware.smack.packet.Presence.Mode; import org.jivesoftware.smack.packet.Presence.Type; import org.jivesoftware.smack.proxy.ProxyInfo; import org.jivesoftware.smack.proxy.ProxyInfo.ProxyType; import org.jivesoftware.smackx.ServiceDiscoveryManager; import org.jivesoftware.smackx.packet.VCard; import android.content.ContentResolver; import android.content.Context; import android.os.Environment; import android.os.Parcel; import android.util.Log; public class XmppConnection extends ImConnection implements CallbackHandler { final static String TAG = "Gibberbot.XmppConnection"; private final static boolean DEBUG_ENABLED = false; private XmppContactList mContactListManager; private Contact mUser; // watch out, this is a different XMPPConnection class than XmppConnection! ;) // Synchronized by executor thread private MyXMPPConnection mConnection; private XmppStreamHandler mStreamHandler; private XmppChatSessionManager mSessionManager; private ConnectionConfiguration mConfig; // True if we are in the process of reconnecting. Reconnection is retried once per heartbeat. // Synchronized by executor thread. private boolean mNeedReconnect; private boolean mRetryLogin; private ThreadPoolExecutor mExecutor; private ProxyInfo mProxyInfo = null; private long mAccountId = -1; private long mProviderId = -1; private String mPasswordTemp; private final static String TRUSTSTORE_TYPE = "BKS"; private final static String TRUSTSTORE_PATH = "cacerts.bks"; private final static String TRUSTSTORE_PASS = "changeit"; private final static String KEYMANAGER_TYPE = "X509"; private final static String SSLCONTEXT_TYPE = "TLS"; private ServerTrustManager sTrustManager; private SSLContext sslContext; private KeyStore ks = null; private KeyManager[] kms = null; private Context aContext; private final static String IS_GOOGLE = "google"; private final static int SOTIMEOUT = 15000; private PacketCollector mPingCollector; private String mUsername; private String mPassword; private String mResource; private int mPriority; public XmppConnection(Context context) { super(context); aContext = context; SmackConfiguration.setPacketReplyTimeout(SOTIMEOUT); // Create a single threaded executor. This will serialize actions on the underlying connection. createExecutor(); XmppStreamHandler.addExtensionProviders(); DeliveryReceipts.addExtensionProviders(); ServiceDiscoveryManager.setIdentityName("Gibberbot"); ServiceDiscoveryManager.setIdentityType("phone"); } private void createExecutor() { mExecutor = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue< Runnable >()); } private boolean execute(Runnable runnable) { try { mExecutor.execute(runnable); } catch (RejectedExecutionException ex) { return false; } return true; } // Execute a runnable only if we are idle private boolean executeIfIdle(Runnable runnable) { if (mExecutor.getActiveCount() + mExecutor.getQueue().size() == 0) { return execute(runnable); } return false; } // This runs in executor thread, and since there is only one such thread, we will definitely // succeed in shutting down the executor if we get here. public void join() { final ExecutorService executor = mExecutor; mExecutor = null; // This will send us an interrupt, which we will ignore. We will terminate // anyway after the caller is done. This also drains the executor queue. executor.shutdownNow(); } public void sendPacket(final org.jivesoftware.smack.packet.Packet packet) { execute(new Runnable() { @Override public void run() { if (mConnection == null) { Log.w(TAG, "dropped packet to " + packet.getTo() + " because we are not connected"); return; } try { mConnection.sendPacket(packet); } catch (IllegalStateException ex) { Log.w(TAG, "dropped packet to " + packet.getTo() + " because socket is disconnected"); } } }); } public VCard getVCard(String myJID) { VCard vCard = new VCard(); try { // FIXME synchronize this to executor thread vCard.load(mConnection, myJID); // If VCard is loaded, then save the avatar to the personal folder. byte[] bytes = vCard.getAvatar(); if (bytes != null) { try { String filename = vCard.getAvatarHash() + ".jpg"; File sdCard = Environment.getExternalStorageDirectory(); File file = new File(sdCard, filename); OutputStream output = new FileOutputStream(file); output.write(bytes); output.close(); } catch (Exception e){ e.printStackTrace(); } } } catch (XMPPException ex) { ex.printStackTrace(); } return vCard; } @Override protected void doUpdateUserPresenceAsync(Presence presence) { org.jivesoftware.smack.packet.Presence packet = makePresencePacket(presence); sendPacket(packet); mUserPresence = presence; notifyUserPresenceUpdated(); } private org.jivesoftware.smack.packet.Presence makePresencePacket(Presence presence) { String statusText = presence.getStatusText(); Type type = Type.available; Mode mode = Mode.available; int priority = mPriority; final int status = presence.getStatus(); if (status == Presence.AWAY) { priority = 10; mode = Mode.away; } else if (status == Presence.IDLE) { priority = 15; mode = Mode.away; } else if (status == Presence.DO_NOT_DISTURB) { priority = 5; mode = Mode.dnd; } else if (status == Presence.OFFLINE) { priority = 0; type = Type.unavailable; statusText = "Offline"; } // The user set priority is the maximum allowed if (priority > mPriority) priority = mPriority; org.jivesoftware.smack.packet.Presence packet = new org.jivesoftware.smack.packet.Presence(type, statusText, priority, mode); return packet; } @Override public int getCapability() { // TODO chat groups return ImConnection.CAPABILITY_SESSION_REESTABLISHMENT; } @Override public ChatGroupManager getChatGroupManager() { // TODO chat groups return null; } @Override public synchronized ChatSessionManager getChatSessionManager() { if (mSessionManager == null) mSessionManager = new XmppChatSessionManager(); return mSessionManager; } @Override public synchronized XmppContactList getContactListManager() { if (mContactListManager == null) mContactListManager = new XmppContactList(); return mContactListManager; } @Override public Contact getLoginUser() { return mUser; } @Override public Map<String, String> getSessionContext() { // Empty state for now (but must have at least one key) return Collections.singletonMap("state", "empty"); } @Override public int[] getSupportedPresenceStatus() { return new int[] { Presence.AVAILABLE, Presence.AWAY, Presence.IDLE, Presence.OFFLINE, Presence.DO_NOT_DISTURB, }; } @Override public void loginAsync(long accountId, String passwordTemp, long providerId, boolean retry) { mAccountId = accountId; mPasswordTemp = passwordTemp; mProviderId = providerId; mRetryLogin = retry; execute(new Runnable() { @Override public void run() { do_login(); } }); } // Runs in executor thread private void do_login() { if (mConnection != null) { setState(getState(), new ImErrorInfo(ImErrorInfo.CANT_CONNECT_TO_SERVER, "still trying...")); return; } ContentResolver contentResolver = mContext.getContentResolver(); Imps.ProviderSettings.QueryMap providerSettings = new Imps.ProviderSettings.QueryMap(contentResolver, mProviderId, false, null); // providerSettings is closed in initConnection() String userName = Imps.Account.getUserName(contentResolver, mAccountId); String password = Imps.Account.getPassword(contentResolver, mAccountId); String domain = providerSettings.getDomain(); if (mPasswordTemp != null) password = mPasswordTemp; mNeedReconnect = true; setState(LOGGING_IN, null); mUserPresence = new Presence(Presence.AVAILABLE, "", Presence.CLIENT_TYPE_MOBILE); try { if (userName.length() == 0) throw new XMPPException("empty username not allowed"); initConnection(userName, password, providerSettings); } catch (Exception e) { Log.w(TAG, "login failed", e); mConnection = null; ImErrorInfo info = new ImErrorInfo(ImErrorInfo.CANT_CONNECT_TO_SERVER, e.getMessage()); if (e == null || e.getMessage() == null) { Log.w(TAG, "NPE", e); info = new ImErrorInfo(ImErrorInfo.INVALID_USERNAME, "unknown error"); disconnected(info); mRetryLogin = false; } else if (e.getMessage().contains("not-authorized")||e.getMessage().contains("authentication failed")) { Log.w(TAG, "not authorized - will not retry"); info = new ImErrorInfo(ImErrorInfo.INVALID_USERNAME, "invalid user/password"); disconnected(info); mRetryLogin = false; } else if (mRetryLogin) { Log.w(TAG, "will retry"); setState(LOGGING_IN, info); } else { Log.w(TAG, "will not retry"); mConnection = null; disconnected(info); } return; } finally { mNeedReconnect = false; } // TODO should we really be using the same name for both address and name? String xmppName = userName + '@' + domain; mUser = new Contact(new XmppAddress(userName, xmppName), xmppName); setState(LOGGED_IN, null); debug(TAG, "logged in"); } // TODO shouldn't setProxy be handled in Imps/settings? public void setProxy (String type, String host, int port) { if (type == null) { mProxyInfo = ProxyInfo.forNoProxy(); } else { ProxyInfo.ProxyType pType = ProxyType.valueOf(type); mProxyInfo = new ProxyInfo(pType, host, port,"",""); } } public void initConnection(MyXMPPConnection connection, Contact user, int state) { mConnection = connection; mUser = user; setState(state, null); } // Runs in executor thread private void initConnection(String userName, final String password, Imps.ProviderSettings.QueryMap providerSettings) throws Exception { // android.os.Debug.waitForDebugger(); boolean allowPlainAuth = providerSettings.getAllowPlainAuth(); boolean requireTls = providerSettings.getRequireTls(); boolean doDnsSrv = providerSettings.getDoDnsSrv(); boolean tlsCertVerify = providerSettings.getTlsCertVerify(); boolean allowSelfSignedCerts = !tlsCertVerify; boolean doVerifyDomain = tlsCertVerify; boolean useSASL = true;//!allowPlainAuth; String domain = providerSettings.getDomain(); String server = providerSettings.getServer(); String xmppResource = providerSettings.getXmppResource(); mPriority = providerSettings.getXmppResourcePrio(); int serverPort = providerSettings.getPort(); providerSettings.close(); // close this, which was opened in do_login() debug(TAG, "TLS required? " + requireTls); debug(TAG, "Do SRV check? " + doDnsSrv); debug(TAG, "cert verification? " + tlsCertVerify); if (mProxyInfo == null) mProxyInfo = ProxyInfo.forNoProxy(); // try getting a connection without DNS SRV first, and if that doesn't work and the prefs allow it, use DNS SRV if (doDnsSrv) { //java.lang.System.setProperty("java.net.preferIPv4Stack", "true"); //java.lang.System.setProperty("java.net.preferIPv6Addresses", "false"); debug(TAG, "(DNS SRV) resolving: "+domain); DNSUtil.HostAddress srvHost = DNSUtil.resolveXMPPDomain(domain); server = srvHost.getHost(); //serverPort = srvHost.getPort(); //ignore port right now, as we are always a client debug(TAG, "(DNS SRV) resolved: "+domain+"=" + server + ":" + serverPort); } if (server == null) { // no server specified in prefs, use the domain debug(TAG, "(use domain) ConnectionConfiguration("+domain+", "+serverPort+", "+domain+", mProxyInfo);"); if (mProxyInfo == null) mConfig = new ConnectionConfiguration(domain, serverPort); else mConfig = new ConnectionConfiguration(domain, serverPort, mProxyInfo); } else { debug(TAG, "(use server) ConnectionConfiguration("+server+", "+serverPort+", "+domain+", mProxyInfo);"); if (mProxyInfo == null) mConfig = new ConnectionConfiguration(server, serverPort, domain); else mConfig = new ConnectionConfiguration(server, serverPort, domain, mProxyInfo); //if domain of login user is the same as server doVerifyDomain = (domain.equals(server)); } mConfig.setDebuggerEnabled(DEBUG_ENABLED); mConfig.setSASLAuthenticationEnabled(useSASL); if (requireTls) { mConfig.setSecurityMode(SecurityMode.required); SASLAuthentication.supportSASLMechanism("PLAIN", 0); SASLAuthentication.supportSASLMechanism("DIGEST-MD5", 1); } else { // if it finds a cert, still use it, but don't check anything since // TLS errors are not expected by the user mConfig.setSecurityMode(SecurityMode.enabled); if(allowPlainAuth) { SASLAuthentication.supportSASLMechanism("PLAIN", 0); SASLAuthentication.supportSASLMechanism("DIGEST-MD5", 1); } else { SASLAuthentication.unsupportSASLMechanism("PLAIN"); SASLAuthentication.supportSASLMechanism("DIGEST-MD5", 0); } } // Android has no support for Kerberos or GSSAPI, so disable completely SASLAuthentication.unregisterSASLMechanism("KERBEROS_V4"); SASLAuthentication.unregisterSASLMechanism("GSSAPI"); mConfig.setVerifyChainEnabled(tlsCertVerify); mConfig.setVerifyRootCAEnabled(tlsCertVerify); mConfig.setExpiredCertificatesCheckEnabled(tlsCertVerify); mConfig.setNotMatchingDomainCheckEnabled(doVerifyDomain && (!allowSelfSignedCerts)); mConfig.setSelfSignedCertificateEnabled(allowSelfSignedCerts); mConfig.setTruststoreType(TRUSTSTORE_TYPE); mConfig.setTruststorePath(TRUSTSTORE_PATH); mConfig.setTruststorePassword(TRUSTSTORE_PASS); if (server == null) initSSLContext(domain, mConfig); else initSSLContext(server, mConfig); // Don't use smack reconnection - not reliable mConfig.setReconnectionAllowed(false); mConfig.setSendPresence(false); mConfig.setRosterLoadedAtLogin(true); mConnection = new MyXMPPConnection(mConfig); //debug(TAG,"is secure connection? " + mConnection.isSecureConnection()); //debug(TAG,"is using TLS? " + mConnection.isUsingTLS()); mConnection.addPacketListener(new PacketListener() { @Override public void processPacket(Packet packet) { org.jivesoftware.smack.packet.Message smackMessage = (org.jivesoftware.smack.packet.Message) packet; String address = parseAddressBase(smackMessage.getFrom()); ChatSession session = findOrCreateSession(address); DeliveryReceipts.DeliveryReceipt dr = (DeliveryReceipts.DeliveryReceipt)smackMessage.getExtension("received", DeliveryReceipts.NAMESPACE); if (dr != null) { debug(TAG, "got delivery receipt for " + dr.getId()); session.onMessageReceipt(dr.getId()); } if (smackMessage.getBody() == null) return; Message rec = new Message(smackMessage.getBody()); rec.setTo(mUser.getAddress()); rec.setFrom(session.getParticipant().getAddress()); rec.setDateTime(new Date()); session.onReceiveMessage(rec); if (smackMessage.getExtension("request", DeliveryReceipts.NAMESPACE) != null) { debug(TAG, "got delivery receipt request"); // got XEP-0184 request, send receipt sendReceipt(smackMessage); session.onReceiptsExpected(); } } }, new PacketTypeFilter(org.jivesoftware.smack.packet.Message.class)); mConnection.addPacketListener(new PacketListener() { @Override public void processPacket(Packet packet) { org.jivesoftware.smack.packet.Presence presence = (org.jivesoftware.smack.packet.Presence)packet; String address = parseAddressBase(presence.getFrom()); String name = parseAddressName(presence.getFrom()); Contact contact = findOrCreateContact(name,address); if (presence.getType() == Type.subscribe) { debug(TAG, "sub request from " + address); mContactListManager.getSubscriptionRequestListener().onSubScriptionRequest(contact); } else { int type = parsePresence(presence); contact.setPresence(new Presence(type, presence.getStatus(), null, null, Presence.CLIENT_TYPE_DEFAULT)); } } }, new PacketTypeFilter(org.jivesoftware.smack.packet.Presence.class)); mConnection.connect(); initServiceDiscovery(); mConnection.addConnectionListener(new ConnectionListener() { /** * Called from smack when connect() is fully successful * * This is called on the executor thread while we are in reconnect() */ @Override public void reconnectionSuccessful() { debug(TAG, "reconnection success"); mNeedReconnect = false; setState(LOGGED_IN, null); } @Override public void reconnectionFailed(Exception e) { // We are not using the reconnection manager throw new UnsupportedOperationException(); } @Override public void reconnectingIn(int seconds) { // We are not using the reconnection manager throw new UnsupportedOperationException(); } @Override public void connectionClosedOnError(final Exception e) { /* * This fires when: * - Packet reader or writer detect an error * - Stream compression failed * - TLS fails but is required * - Network error * - We forced a socket shutdown */ Log.e(TAG, "reconnect on error", e); if (e.getMessage().contains("conflict")) { execute(new Runnable() { @Override public void run() { disconnect(); disconnected(new ImErrorInfo(ImErrorInfo.CANT_CONNECT_TO_SERVER, "logged in from another location")); } }); } else if (!mNeedReconnect) { execute(new Runnable() { @Override public void run() { if (getState() == LOGGED_IN) setState(LOGGING_IN, new ImErrorInfo(ImErrorInfo.NETWORK_ERROR, e.getMessage())); maybe_reconnect(); } }); } } @Override public void connectionClosed() { debug(TAG, "connection closed"); /* * This can be called in these cases: * - Connection is shutting down * - because we are calling disconnect * - in do_logout * * - NOT * - because server disconnected "normally" * - we were trying to log in (initConnection), but are failing * - due to network error * - due to login failing */ } }); Connection.addConnectionCreationListener(new ConnectionCreationListener (){ @Override public void connectionCreated(Connection arg0) { debug(TAG, "connection created!"); } }); if (server.contains(IS_GOOGLE)) { this.mUsername = userName + '@' + domain; } else { this.mUsername = userName; } this.mPassword = password; this.mResource = xmppResource; mStreamHandler = new XmppStreamHandler(mConnection); mConnection.login(mUsername, mPassword, mResource); mStreamHandler.notifyInitialLogin(); sendPresencePacket(); Roster roster = mConnection.getRoster(); roster.setSubscriptionMode(Roster.SubscriptionMode.manual); getContactListManager().listenToRoster(roster); } private void sendPresencePacket() { org.jivesoftware.smack.packet.Presence presence = makePresencePacket(mUserPresence); mConnection.sendPacket(presence); } public void sendReceipt(org.jivesoftware.smack.packet.Message msg) { debug(TAG, "sending XEP-0184 ack to " + msg.getFrom() + " id=" + msg.getPacketID()); org.jivesoftware.smack.packet.Message ack = new org.jivesoftware.smack.packet.Message(msg.getFrom(), msg.getType()); ack.addExtension(new DeliveryReceipts.DeliveryReceipt(msg.getPacketID())); mConnection.sendPacket(ack); } private void initSSLContext (String server, ConnectionConfiguration config) throws Exception { ks = KeyStore.getInstance(TRUSTSTORE_TYPE); try { ks.load(new FileInputStream(TRUSTSTORE_PATH), TRUSTSTORE_PASS.toCharArray()); } catch(Exception e) { ks = null; } KeyManagerFactory kmf = KeyManagerFactory.getInstance(KEYMANAGER_TYPE); try { kmf.init(ks, TRUSTSTORE_PASS.toCharArray()); kms = kmf.getKeyManagers(); } catch (NullPointerException npe) { kms = null; } sslContext = SSLContext.getInstance(SSLCONTEXT_TYPE); sTrustManager = new ServerTrustManager(aContext, server, config, this); sslContext.init(kms, new javax.net.ssl.TrustManager[]{sTrustManager}, new java.security.SecureRandom()); config.setCustomSSLContext(sslContext); config.setCallbackHandler(this); } void sslCertificateError () { this.disconnect(); } // We must release resources here, because we will not be reused void disconnected(ImErrorInfo info) { Log.w(TAG, "disconnected"); join(); setState(DISCONNECTED, info); } protected static int parsePresence(org.jivesoftware.smack.packet.Presence presence) { int type = Presence.AVAILABLE; Mode rmode = presence.getMode(); Type rtype = presence.getType(); if (rmode == Mode.away || rmode == Mode.xa) type = Presence.AWAY; else if (rmode == Mode.dnd) type = Presence.DO_NOT_DISTURB; else if (rtype == Type.unavailable) type = Presence.OFFLINE; return type; } protected static String parseAddressBase(String from) { return from.replaceFirst("/.*", ""); } protected static String parseAddressName(String from) { return from.replaceFirst("@.*", ""); } @Override public void logoutAsync() { execute(new Runnable() { @Override public void run() { do_logout(); } }); } // Force immediate logout public void logout() { do_logout(); } // Usually runs in executor thread, unless called from logout() private void do_logout() { Log.w(TAG, "logout"); setState(LOGGING_OUT, null); disconnect(); disconnected(null); } // Runs in executor thread private void disconnect() { clearPing(); XMPPConnection conn = mConnection; mConnection = null; try { conn.disconnect(); } catch (Throwable th) { // ignore } mNeedReconnect = false; mRetryLogin = false; } @Override public void reestablishSessionAsync(Map<String, String> sessionContext) { execute(new Runnable() { @Override public void run() { if (getState() == SUSPENDED) { debug(TAG, "reestablish"); setState(LOGGING_IN, null); maybe_reconnect(); } } }); } @Override public void suspend() { execute(new Runnable() { @Override public void run() { debug(TAG, "suspend"); setState(SUSPENDED, null); mNeedReconnect = false; clearPing(); // Do not try to reconnect anymore if we were asked to suspend mConnection.shutdown(); } }); } private ChatSession findOrCreateSession(String address) { ChatSession session = mSessionManager.findSession(address); if (session == null) { Contact contact = findOrCreateContact(parseAddressName(address),address); session = mSessionManager.createChatSession(contact); } return session; } Contact findOrCreateContact(String name, String address) { Contact contact = mContactListManager.getContact(address); if (contact == null) { contact = makeContact(name, address); } return contact; } private static Contact makeContact(String name, String address) { Contact contact = new Contact(new XmppAddress(name, address), address); return contact; } private final class XmppChatSessionManager extends ChatSessionManager { @Override public void sendMessageAsync(ChatSession session, Message message) { org.jivesoftware.smack.packet.Message msg = new org.jivesoftware.smack.packet.Message( message.getTo().getFullName(), org.jivesoftware.smack.packet.Message.Type.chat ); msg.addExtension(new DeliveryReceipts.DeliveryReceiptRequest()); msg.setBody(message.getBody()); debug(TAG, "sending packet ID " + msg.getPacketID()); message.setID(msg.getPacketID()); sendPacket(msg); } ChatSession findSession(String address) { for (Iterator<ChatSession> iter = mSessions.iterator(); iter.hasNext();) { ChatSession session = iter.next(); if (session.getParticipant().getAddress().getFullName().equals(address)) return session; } return null; } } public ChatSession findSession (String address) { return mSessionManager.findSession(address); } public ChatSession createChatSession (Contact contact) { return mSessionManager.createChatSession(contact); } public class XmppContactList extends ContactListManager { //private Hashtable<String, org.jivesoftware.smack.packet.Presence> unprocdPresence = new Hashtable<String, org.jivesoftware.smack.packet.Presence>(); @Override protected void setListNameAsync(final String name, final ContactList list) { execute(new Runnable() { @Override public void run() { do_setListName(name, list); } }); } // Runs in executor thread private void do_setListName(String name, ContactList list) { debug(TAG, "set list name"); mConnection.getRoster().getGroup(list.getName()).setName(name); notifyContactListNameUpdated(list, name); } @Override public String normalizeAddress(String address) { return address; } @Override public void loadContactListsAsync() { execute(new Runnable() { @Override public void run() { do_loadContactLists(); } }); } // For testing public void loadContactLists() { do_loadContactLists(); } /** * Create new list of contacts from roster entries. * * Runs in executor thread * * @param entryIter iterator of roster entries to add to contact list * @param skipList list of contacts which should be omitted; new contacts are added to this list automatically * @return contacts from roster which were not present in skiplist. */ private Collection<Contact> fillContacts(Collection<RosterEntry> entryIter, Set<String> skipList) { Roster roster = mConnection.getRoster(); Collection<Contact> contacts = new ArrayList<Contact>(); for (RosterEntry entry : entryIter) { String address = parseAddressBase(entry.getUser()); /* Skip entries present in the skip list */ if (skipList != null && !skipList.add(address)) continue; String name = entry.getName(); if (name == null) name = address; XmppAddress xaddress = new XmppAddress(name, address); Contact contact = mContactListManager.getContact(xaddress.getFullName()); if (contact == null) contact = new Contact(xaddress, name); org.jivesoftware.smack.packet.Presence presence = roster.getPresence(address); contact.setPresence(new Presence(parsePresence(presence), presence.getStatus(), null, null, Presence.CLIENT_TYPE_DEFAULT)); contacts.add(contact); // getVCard(xaddress.getFullName()); // commented out to fix slow contact loading } return contacts; } // Runs in executor thread private void do_loadContactLists() { debug(TAG, "load contact lists"); if (mConnection == null) return; Roster roster = mConnection.getRoster(); //Set<String> seen = new HashSet<String>(); // This group will also contain all the unfiled contacts. We will create it locally if it // does not exist. String generalGroupName = "Buddies"; for (Iterator<RosterGroup> giter = roster.getGroups().iterator(); giter.hasNext();) { RosterGroup group = giter.next(); debug(TAG, "loading group: " + group.getName() + " size:" + group.getEntryCount()); Collection<Contact> contacts = fillContacts(group.getEntries(), null); if (group.getName().equals(generalGroupName) && roster.getUnfiledEntryCount() > 0) { Collection<Contact> unfiled = fillContacts(roster.getUnfiledEntries(), null); contacts.addAll(unfiled); } ContactList cl = new ContactList(mUser.getAddress(), group.getName(), group.getName().equals(generalGroupName), contacts, this); notifyContactListCreated(cl); notifyContactsPresenceUpdated(contacts.toArray(new Contact[contacts.size()])); } Collection<Contact> contacts; if (roster.getUnfiledEntryCount() > 0) { contacts = fillContacts(roster.getUnfiledEntries(), null); } else { contacts = new ArrayList<Contact>(); } ContactList cl = getContactList(generalGroupName); // We might have already created the Buddies contact list above if (cl == null) { cl = new ContactList(mUser.getAddress(), generalGroupName, true, contacts, this); notifyContactListCreated(cl); notifyContactsPresenceUpdated(contacts.toArray(new Contact[contacts.size()])); } notifyContactListsLoaded(); } /* * iterators through a list of contacts to see if there were any Presence * notifications sent before the contact was loaded */ /* private void processQueuedPresenceNotifications (Collection<Contact> contacts) { Roster roster = mConnection.getRoster(); //now iterate through the list of queued up unprocessed presence changes for (Contact contact : contacts) { String address = parseAddressBase(contact.getAddress().getFullName()); org.jivesoftware.smack.packet.Presence presence = roster.getPresence(address); if (presence != null) { debug(TAG, "processing queued presence: " + address + " - " + presence.getStatus()); unprocdPresence.remove(address); contact.setPresence(new Presence(parsePresence(presence), presence.getStatus(), null, null, Presence.CLIENT_TYPE_DEFAULT)); Contact[] updatedContact = {contact}; notifyContactsPresenceUpdated(updatedContact); } } }*/ public void listenToRoster(final Roster roster) { roster.addRosterListener(rListener); } RosterListener rListener = new RosterListener() { // private Stack<String> entriesToAdd = new Stack<String>(); // private Stack<String> entriesToDel = new Stack<String>(); @Override public void presenceChanged(org.jivesoftware.smack.packet.Presence presence) { handlePresenceChanged(presence); } @Override public void entriesUpdated(Collection<String> addresses) { debug(TAG, "roster entries updated"); //entriesAdded(addresses); } @Override public void entriesDeleted(Collection<String> addresses) { debug(TAG, "roster entries deleted: " + addresses.size()); /* if (addresses != null) entriesToDel.addAll(addresses); if (mContactListManager.getState() == ContactListManager.LISTS_LOADED) { synchronized (entriesToDel) { while (!entriesToDel.empty()) try { Contact contact = mContactListManager.getContact(entriesToDel.pop()); mContactListManager.removeContactFromListAsync(contact, mContactListManager.getDefaultContactList()); } catch (ImException e) { Log.e(TAG,e.getMessage(),e); } } } else { debug(TAG, "roster delete entries queued"); }*/ } @Override public void entriesAdded(Collection<String> addresses) { debug(TAG, "roster entries added: " + addresses.size()); /* if (addresses != null) entriesToAdd.addAll(addresses); if (mContactListManager.getState() == ContactListManager.LISTS_LOADED) { debug(TAG, "roster entries added"); while (!entriesToAdd.empty()) try { mContactListManager.addContactToListAsync(entriesToAdd.pop(), mContactListManager.getDefaultContactList()); } catch (ImException e) { Log.e(TAG,e.getMessage(),e); } } else { debug(TAG, "roster add entries queued"); }*/ } }; private void handlePresenceChanged (org.jivesoftware.smack.packet.Presence presence) { String name = parseAddressName(presence.getFrom()); String address = parseAddressBase(presence.getFrom()); XmppAddress xaddress = new XmppAddress(name, address); Contact contact = getContact(xaddress.getFullName()); /* if (mConnection != null) { Roster roster = mConnection.getRoster(); // Get it from the roster - it handles priorities, etc. if (roster != null) presence = roster.getPresence(address); }*/ int type = parsePresence(presence); if (contact == null) { contact = new Contact(xaddress, name); debug(TAG, "got presence updated for NEW user: " + contact.getAddress().getFullName() + " presence:" + type); //store the latest presence notification for this user in this queue //unprocdPresence.put(user, presence); } else { debug(TAG, "Got present update for EXISTING user: " + contact.getAddress().getFullName() + " presence:" + type); Presence p = new Presence(type, presence.getStatus(), null, null, Presence.CLIENT_TYPE_DEFAULT); contact.setPresence(p); Contact []contacts = new Contact[] { contact }; notifyContactsPresenceUpdated(contacts); } } @Override protected ImConnection getConnection() { return XmppConnection.this; } @Override protected void doRemoveContactFromListAsync(Contact contact, ContactList list) { // FIXME synchronize this to executor thread if (mConnection == null) return; Roster roster = mConnection.getRoster(); String address = contact.getAddress().getFullName(); try { RosterGroup group = roster.getGroup(list.getName()); if (group == null) { Log.e(TAG, "could not find group " + list.getName() + " in roster"); return; } RosterEntry entry = roster.getEntry(address); if (entry == null) { Log.e(TAG, "could not find entry " + address + " in group " + list.getName()); return; } group.removeEntry(entry); } catch (XMPPException e) { Log.e(TAG, "remove entry failed", e); throw new RuntimeException(e); } org.jivesoftware.smack.packet.Presence response = new org.jivesoftware.smack.packet.Presence(org.jivesoftware.smack.packet.Presence.Type.unsubscribed); response.setTo(address); sendPacket(response); notifyContactListUpdated(list, ContactListListener.LIST_CONTACT_REMOVED, contact); } @Override protected void doDeleteContactListAsync(ContactList list) { // TODO delete contact list debug(TAG, "delete contact list " + list.getName()); } @Override protected void doCreateContactListAsync(String name, Collection<Contact> contacts, boolean isDefault) { // TODO create contact list debug(TAG, "create contact list " + name + " default " + isDefault); } @Override protected void doBlockContactAsync(String address, boolean block) { // TODO block contact } @Override protected void doAddContactToListAsync(String address, ContactList list) throws ImException { debug(TAG, "add contact to " + list.getName()); org.jivesoftware.smack.packet.Presence response = new org.jivesoftware.smack.packet.Presence(org.jivesoftware.smack.packet.Presence.Type.subscribed); response.setTo(address); sendPacket(response); Roster roster = mConnection.getRoster(); String[] groups = new String[] { list.getName() }; try { final String name = parseAddressName(address); roster.createEntry(address, name, groups); // If contact exists locally, don't create another copy Contact contact = makeContact(name, address); if (!containsContact(contact)) notifyContactListUpdated(list, ContactListListener.LIST_CONTACT_ADDED, contact); else debug(TAG, "skip adding existing contact locally " + name); } catch (XMPPException e) { throw new RuntimeException(e); } } @Override public void declineSubscriptionRequest(String contact) { debug(TAG, "decline subscription"); org.jivesoftware.smack.packet.Presence response = new org.jivesoftware.smack.packet.Presence(org.jivesoftware.smack.packet.Presence.Type.unsubscribed); response.setTo(contact); sendPacket(response); mContactListManager.getSubscriptionRequestListener().onSubscriptionDeclined(contact); } @Override public void approveSubscriptionRequest(String contact) { debug(TAG, "approve subscription"); try { mContactListManager.doAddContactToListAsync(contact, getDefaultContactList()); } catch (ImException e) { Log.e(TAG, "failed to add " + contact + " to default list"); } mContactListManager.getSubscriptionRequestListener().onSubscriptionApproved(contact); } @Override public Contact createTemporaryContact(String address) { debug(TAG, "create temporary " + address); return makeContact(parseAddressName(address),address); } } public static class XmppAddress extends Address { private String address; private String name; public XmppAddress() { } public XmppAddress(String name, String address) { this.name = name; this.address = address; } public XmppAddress(String address) { this.name = parseAddressName(address); this.address = address; } @Override public String getFullName() { return address; } @Override public String getScreenName() { return name; } @Override public void readFromParcel(Parcel source) { name = source.readString(); address = source.readString(); } @Override public void writeToParcel(Parcel dest) { dest.writeString(name); dest.writeString(address); } } /* * Alarm event fired * @see info.guardianproject.otr.app.im.engine.ImConnection#sendHeartbeat() */ public void sendHeartbeat() { // Don't let heartbeats queue up if we have long running tasks - only // do the heartbeat if executor is idle. boolean success = executeIfIdle(new Runnable() { @Override public void run() { debug(TAG, "heartbeat state = " + getState()); doHeartbeat(); } }); if (!success) { debug(TAG, "failed to schedule heartbeat state = " + getState()); } } // Runs in executor thread public void doHeartbeat() { if (mConnection == null && mRetryLogin) { debug(TAG, "reconnect with login"); do_login(); } if (mConnection == null) return; if (getState() == SUSPENDED) { debug(TAG, "heartbeat during suspend"); return; } if (mNeedReconnect) { reconnect(); } else if (mConnection.isConnected() && getState() == LOGGED_IN) { debug(TAG, "ping"); if (!sendPing()) { Log.w(TAG, "reconnect on ping failed"); setState(LOGGING_IN, new ImErrorInfo(ImErrorInfo.NETWORK_ERROR, "network timeout")); force_reconnect(); } } } private void clearPing() { debug(TAG, "clear ping"); mPingCollector = null; } // Runs in executor thread private boolean sendPing() { // Check ping result from previous send if (mPingCollector != null) { IQ result = (IQ)mPingCollector.pollResult(); mPingCollector.cancel(); if (result == null || result.getError() != null) { clearPing(); Log.e(TAG, "ping timeout"); return false; } } IQ req = new IQ() { public String getChildElementXML() { return "<ping xmlns='urn:xmpp:ping'/>"; } }; req.setType(IQ.Type.GET); PacketFilter filter = new AndFilter(new PacketIDFilter(req.getPacketID()), new PacketTypeFilter(IQ.class)); mPingCollector = mConnection.createPacketCollector(filter); mConnection.sendPacket(req); return true; } // watch out, this is a different XMPPConnection class than XmppConnection! ;) // org.jivesoftware.smack.XMPPConnection // info.guardianproject.otr.app.im.plugin.xmpp.XmppConnection public static class MyXMPPConnection extends XMPPConnection { public MyXMPPConnection(ConnectionConfiguration config) { super(config); //this.getConfiguration().setSocketFactory(arg0) } public void shutdown() { try { // Be forceful in shutting down since SSL can get stuck try { socket.shutdownInput(); } catch (Exception e) {} socket.close(); shutdown(new org.jivesoftware.smack.packet.Presence(org.jivesoftware.smack.packet.Presence.Type.unavailable)); } catch (Exception e) { Log.e(TAG, "error on shutdown()",e); } } } @Override public void networkTypeChanged() { super.networkTypeChanged(); } /* * Force a shutdown and reconnect, unless we are already reconnecting. * * Runs in executor thread */ private void force_reconnect() { debug(TAG, "force_reconnect need=" + mNeedReconnect); if (mConnection == null) return; if (mNeedReconnect) return; mNeedReconnect = true; try { if (mConnection != null && mConnection.isConnected()) { mConnection.shutdown(); } } catch (Exception e) { Log.w(TAG, "problem disconnecting on force_reconnect: " + e.getMessage()); } reconnect(); } /* * Reconnect unless we are already in the process of doing so. * * Runs in executor thread. */ private void maybe_reconnect() { debug(TAG, "maybe_reconnect mNeedReconnect=" + mNeedReconnect + " state=" + getState() + " connection?=" + (mConnection != null)); // This is checking whether we are already in the process of reconnecting. If we are, // doHeartbeat will take care of reconnecting. if (mNeedReconnect) return; if (getState() == SUSPENDED) return; if (mConnection == null) return; mNeedReconnect = true; reconnect(); } /* * Retry connecting * * Runs in executor thread */ private void reconnect() { if (getState() == SUSPENDED) { debug(TAG, "reconnect during suspend, ignoring"); return; } try { Thread.sleep(2000); // Wait for network to settle } catch (InterruptedException e) { /* ignore */ } if (mConnection != null) { // It is safe to ask mConnection whether it is connected, because either: // - We detected an error using ping and called force_reconnect, which did a shutdown // - Smack detected an error, so it knows it is not connected // so there are no cases where mConnection can be confused about being connected here. // The only left over cases are reconnect() being called too many times due to errors // reported multiple times or errors reported during a forced reconnect. if (mConnection.isConnected()) { Log.w(TAG, "reconnect while already connected, assuming good"); mNeedReconnect = false; setState(LOGGED_IN, null); return; } Log.i(TAG, "reconnect"); clearPing(); try { if (mStreamHandler.isResumePossible()) { // Connect without binding, will automatically trigger a resume mConnection.connect(false); //initServiceDiscovery(); } else { mConnection.connect(); //initServiceDiscovery(); if (!mConnection.isAuthenticated()) { // This can happen if a reconnect failed and the smack connection now has wasAuthenticated = false. // It can also happen if auth exception was swallowed by smack. // Try to login manually. Log.e(TAG, "authentication did not happen in connect() - login manually"); mConnection.login(mUsername, mPassword, mResource); // Make sure if (!mConnection.isAuthenticated()) throw new XMPPException("manual auth failed"); // Manually set the state since manual auth doesn't notify listeners mNeedReconnect = false; setState(LOGGED_IN, null); } sendPresencePacket(); } } catch (Exception e) { mConnection.shutdown(); Log.e(TAG, "reconnection attempt failed", e); // Smack incorrectly notified us that reconnection was successful, reset in case it fails mNeedReconnect = true; setState(LOGGING_IN, new ImErrorInfo(ImErrorInfo.NETWORK_ERROR, e.getMessage())); } } else { mNeedReconnect = true; debug(TAG, "reconnection on network change failed"); setState(LOGGING_IN, new ImErrorInfo(ImErrorInfo.NETWORK_ERROR, "reconnection on network change failed")); } } @Override protected void setState(int state, ImErrorInfo error) { debug(TAG, "setState to " + state); super.setState(state, error); } public static void debug (String tag, String msg) { //Log.d(tag, msg); } @Override public void handle(Callback[] arg0) throws IOException { for (Callback cb : arg0) { debug(TAG, cb.toString()); } } /* public class MySASLDigestMD5Mechanism extends SASLMechanism { public MySASLDigestMD5Mechanism(SASLAuthentication saslAuthentication) { super(saslAuthentication); } protected void authenticate() throws IOException, XMPPException { String mechanisms[] = { getName() }; java.util.Map props = new HashMap(); sc = Sasl.createSaslClient(mechanisms, null, "xmpp", hostname, props, this); super.authenticate(); } public void authenticate(String username, String host, String password) throws IOException, XMPPException { authenticationId = username; this.password = password; hostname = host; String mechanisms[] = { getName() }; java.util.Map props = new HashMap(); sc = Sasl.createSaslClient(mechanisms, null, "xmpp", host, props, this); super.authenticate(); } public void authenticate(String username, String host, CallbackHandler cbh) throws IOException, XMPPException { String mechanisms[] = { getName() }; java.util.Map props = new HashMap(); sc = Sasl.createSaslClient(mechanisms, null, "xmpp", host, props, cbh); super.authenticate(); } protected String getName() { return "DIGEST-MD5"; } public void challengeReceived(String challenge) throws IOException { //StringBuilder stanza = new StringBuilder(); byte response[]; if(challenge != null) response = sc.evaluateChallenge(Base64.decode(challenge)); else //response = sc.evaluateChallenge(null); response = sc.evaluateChallenge(new byte[0]); //String authenticationText = ""; Packet responseStanza; //if(response != null) //{ //authenticationText = Base64.encodeBytes(response, 8); //if(authenticationText.equals("")) //authenticationText = "="; if (response == null){ responseStanza = new Response(); } else { responseStanza = new Response(Base64.encodeBytes(response,Base64.DONT_BREAK_LINES)); } //} //stanza.append("<response xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\">"); //stanza.append(authenticationText); //stanza.append("</response>"); //getSASLAuthentication().send(stanza.toString()); getSASLAuthentication().send(responseStanza); } } */ private void initServiceDiscovery() { debug(TAG, "init service discovery"); // register connection features ServiceDiscoveryManager sdm = ServiceDiscoveryManager.getInstanceFor(mConnection); if (sdm == null) sdm = new ServiceDiscoveryManager(mConnection); sdm.addFeature("http://jabber.org/protocol/disco#info"); sdm.addFeature(DeliveryReceipts.NAMESPACE); } }
package info.guardianproject.otr.app.im.plugin.xmpp; import info.guardianproject.otr.TorProxyInfo; import info.guardianproject.otr.app.im.R; import info.guardianproject.otr.app.im.app.DatabaseUtils; import info.guardianproject.otr.app.im.app.ImApp; import info.guardianproject.otr.app.im.engine.Address; import info.guardianproject.otr.app.im.engine.ChatGroup; import info.guardianproject.otr.app.im.engine.ChatGroupManager; import info.guardianproject.otr.app.im.engine.ChatSession; import info.guardianproject.otr.app.im.engine.ChatSessionManager; import info.guardianproject.otr.app.im.engine.Contact; import info.guardianproject.otr.app.im.engine.ContactList; import info.guardianproject.otr.app.im.engine.ContactListListener; import info.guardianproject.otr.app.im.engine.ContactListManager; import info.guardianproject.otr.app.im.engine.ImConnection; import info.guardianproject.otr.app.im.engine.ImEntity; import info.guardianproject.otr.app.im.engine.ImErrorInfo; import info.guardianproject.otr.app.im.engine.ImException; import info.guardianproject.otr.app.im.engine.Invitation; import info.guardianproject.otr.app.im.engine.Message; import info.guardianproject.otr.app.im.engine.Presence; import info.guardianproject.otr.app.im.plugin.xmpp.auth.GTalkOAuth2; import info.guardianproject.otr.app.im.provider.Imps; import info.guardianproject.otr.app.im.provider.ImpsErrorInfo; import info.guardianproject.util.DNSUtil; import info.guardianproject.util.Debug; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.security.KeyManagementException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.Hashtable; import java.util.Iterator; import java.util.LinkedList; import java.util.Map; import java.util.NoSuchElementException; import java.util.Random; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ExecutorService; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.X509TrustManager; import org.apache.harmony.javax.security.auth.callback.Callback; import org.apache.harmony.javax.security.auth.callback.CallbackHandler; import org.jivesoftware.smack.ConnectionConfiguration; import org.jivesoftware.smack.ConnectionConfiguration.SecurityMode; import org.jivesoftware.smack.ConnectionListener; import org.jivesoftware.smack.PacketCollector; import org.jivesoftware.smack.PacketListener; import org.jivesoftware.smack.Roster; import org.jivesoftware.smack.RosterEntry; import org.jivesoftware.smack.RosterGroup; import org.jivesoftware.smack.RosterListener; import org.jivesoftware.smack.SASLAuthentication; import org.jivesoftware.smack.SmackConfiguration; import org.jivesoftware.smack.XMPPConnection; import org.jivesoftware.smack.XMPPException; import org.jivesoftware.smack.filter.AndFilter; import org.jivesoftware.smack.filter.PacketFilter; import org.jivesoftware.smack.filter.PacketIDFilter; import org.jivesoftware.smack.filter.PacketTypeFilter; import org.jivesoftware.smack.packet.IQ; import org.jivesoftware.smack.packet.Message.Body; import org.jivesoftware.smack.packet.Packet; import org.jivesoftware.smack.packet.Presence.Mode; import org.jivesoftware.smack.packet.Presence.Type; import org.jivesoftware.smack.packet.RosterPacket.ItemStatus; import org.jivesoftware.smack.provider.PrivacyProvider; import org.jivesoftware.smack.provider.ProviderManager; import org.jivesoftware.smack.proxy.ProxyInfo; import org.jivesoftware.smack.proxy.ProxyInfo.ProxyType; import org.jivesoftware.smackx.Form; import org.jivesoftware.smackx.FormField; import org.jivesoftware.smackx.GroupChatInvitation; import org.jivesoftware.smackx.PrivateDataManager; import org.jivesoftware.smackx.ServiceDiscoveryManager; import org.jivesoftware.smackx.bytestreams.socks5.provider.BytestreamsProvider; import org.jivesoftware.smackx.muc.MultiUserChat; import org.jivesoftware.smackx.muc.RoomInfo; import org.jivesoftware.smackx.packet.ChatStateExtension; import org.jivesoftware.smackx.packet.LastActivity; import org.jivesoftware.smackx.packet.OfflineMessageInfo; import org.jivesoftware.smackx.packet.OfflineMessageRequest; import org.jivesoftware.smackx.packet.SharedGroupsInfo; import org.jivesoftware.smackx.packet.VCard; import org.jivesoftware.smackx.provider.AdHocCommandDataProvider; import org.jivesoftware.smackx.provider.DataFormProvider; import org.jivesoftware.smackx.provider.DelayInformationProvider; import org.jivesoftware.smackx.provider.DiscoverInfoProvider; import org.jivesoftware.smackx.provider.DiscoverItemsProvider; import org.jivesoftware.smackx.provider.MUCAdminProvider; import org.jivesoftware.smackx.provider.MUCOwnerProvider; import org.jivesoftware.smackx.provider.MUCUserProvider; import org.jivesoftware.smackx.provider.MessageEventProvider; import org.jivesoftware.smackx.provider.MultipleAddressesProvider; import org.jivesoftware.smackx.provider.RosterExchangeProvider; import org.jivesoftware.smackx.provider.StreamInitiationProvider; import org.jivesoftware.smackx.provider.VCardProvider; import org.jivesoftware.smackx.provider.XHTMLExtensionProvider; import org.jivesoftware.smackx.search.UserSearch; import android.accounts.AccountManager; import android.content.ContentResolver; import android.content.Context; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Build; import android.os.RemoteException; import android.util.Log; import de.duenndns.ssl.MemorizingTrustManager; public class XmppConnection extends ImConnection implements CallbackHandler { private static final String DISCO_FEATURE = "http://jabber.org/protocol/disco#info"; final static String TAG = "GB.XmppConnection"; private final static boolean PING_ENABLED = true; private XmppContactListManager mContactListManager; private Contact mUser; // watch out, this is a different XMPPConnection class than XmppConnection! ;) // Synchronized by executor thread private MyXMPPConnection mConnection; private XmppStreamHandler mStreamHandler; private Roster mRoster; private XmppChatSessionManager mSessionManager; private ConnectionConfiguration mConfig; // True if we are in the process of reconnecting. Reconnection is retried once per heartbeat. // Synchronized by executor thread. private boolean mNeedReconnect; private boolean mRetryLogin; private ThreadPoolExecutor mExecutor; private Timer mTimerPresence; private ProxyInfo mProxyInfo = null; private long mAccountId = -1; private long mProviderId = -1; private boolean mIsGoogleAuth = false; private final static String SSLCONTEXT_TYPE = "TLS"; private static SSLContext sslContext; private Context aContext; private final static String IS_GOOGLE = "google"; private final static int SOTIMEOUT = 60000; private PacketCollector mPingCollector; private String mUsername; private String mPassword; private String mResource; private int mPriority; private int mGlobalId; private static int mGlobalCount; private final Random rndForTorCircuits = new Random(); // Maintains a sequence counting up to the user configured heartbeat interval private int heartbeatSequence = 0; LinkedList<String> qAvatar = new LinkedList <String>(); LinkedList<org.jivesoftware.smack.packet.Presence> qPresence = new LinkedList<org.jivesoftware.smack.packet.Presence>(); LinkedList<org.jivesoftware.smack.packet.Packet> qPacket = new LinkedList<org.jivesoftware.smack.packet.Packet>(); public XmppConnection(Context context) throws IOException, KeyStoreException, NoSuchAlgorithmException, CertificateException { super(context); synchronized (XmppConnection.class) { mGlobalId = mGlobalCount++; } aContext = context; Debug.onConnectionStart(); //setup SSL managers SmackConfiguration.setPacketReplyTimeout(SOTIMEOUT); // Create a single threaded executor. This will serialize actions on the underlying connection. createExecutor(); addProviderManagerExtensions(); XmppStreamHandler.addExtensionProviders(); DeliveryReceipts.addExtensionProviders(); ServiceDiscoveryManager.setIdentityName("ChatSecure"); ServiceDiscoveryManager.setIdentityType("phone"); } public void initUser(long providerId, long accountId) throws ImException { ContentResolver contentResolver = mContext.getContentResolver(); Cursor cursor = contentResolver.query(Imps.ProviderSettings.CONTENT_URI,new String[] {Imps.ProviderSettings.NAME, Imps.ProviderSettings.VALUE},Imps.ProviderSettings.PROVIDER + "=?",new String[] { Long.toString(providerId)},null); if (cursor == null) throw new ImException("unable to query settings"); Imps.ProviderSettings.QueryMap providerSettings = new Imps.ProviderSettings.QueryMap( cursor, contentResolver, providerId, false, null); mProviderId = providerId; mAccountId = accountId; mUser = makeUser(providerSettings, contentResolver); providerSettings.close(); } private Contact makeUser(Imps.ProviderSettings.QueryMap providerSettings, ContentResolver contentResolver) { String userName = Imps.Account.getUserName(contentResolver, mAccountId); String domain = providerSettings.getDomain(); String xmppName = userName + '@' + domain + '/' + providerSettings.getXmppResource(); return new Contact(new XmppAddress(xmppName), userName); } private void createExecutor() { mExecutor = new ThreadPoolExecutor(1, 1, 1L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>()); } private boolean execute(Runnable runnable) { if (mExecutor == null) createExecutor (); //if we disconnected, will need to recreate executor here, because join() made it null try { mExecutor.execute(runnable); } catch (RejectedExecutionException ex) { return false; } return true; } // Execute a runnable only if we are idle private boolean executeIfIdle(Runnable runnable) { if (mExecutor.getActiveCount() + mExecutor.getQueue().size() == 0) { return execute(runnable); } return false; } // This runs in executor thread, and since there is only one such thread, we will definitely // succeed in shutting down the executor if we get here. public void join() { final ExecutorService executor = mExecutor; mExecutor = null; // This will send us an interrupt, which we will ignore. We will terminate // anyway after the caller is done. This also drains the executor queue. if (executor != null) executor.shutdownNow(); } // For testing boolean joinGracefully() throws InterruptedException { final ExecutorService executor = mExecutor; mExecutor = null; // This will send us an interrupt, which we will ignore. We will terminate // anyway after the caller is done. This also drains the executor queue. if (executor != null) { executor.shutdown(); return executor.awaitTermination(1, TimeUnit.SECONDS); } return false; } public void sendPacket(final org.jivesoftware.smack.packet.Packet packet) { qPacket.add(packet); } void postpone(final org.jivesoftware.smack.packet.Packet packet) { if (packet instanceof org.jivesoftware.smack.packet.Message) { boolean groupChat = ((org.jivesoftware.smack.packet.Message) packet).getType().equals( org.jivesoftware.smack.packet.Message.Type.groupchat); ChatSession session = findOrCreateSession(packet.getTo(), groupChat); session.onMessagePostponed(packet.getPacketID()); } } private boolean mLoadingAvatars = false; private void loadVCardsAsync () { if (!mLoadingAvatars) { execute(new AvatarLoader()); } } private class AvatarLoader implements Runnable { @Override public void run () { mLoadingAvatars = true; ContentResolver resolver = mContext.getContentResolver(); try { while (qAvatar.size()>0) { loadVCard (resolver, qAvatar.pop(), null); } } catch (Exception e) {} mLoadingAvatars = false; } } private boolean loadVCard (ContentResolver resolver, String jid, String hash) { try { boolean loadAvatar = false; if (hash != null) loadAvatar = (!DatabaseUtils.doesAvatarHashExist(resolver, Imps.Avatars.CONTENT_URI, jid, hash)); else { loadAvatar = DatabaseUtils.hasAvatarContact(resolver, Imps.Avatars.CONTENT_URI, jid); } if (!loadAvatar) { debug(ImApp.LOG_TAG, "loading vcard for: " + jid); VCard vCard = new VCard(); // FIXME synchronize this to executor thread vCard.load(mConnection, jid); // If VCard is loaded, then save the avatar to the personal folder. String avatarHash = vCard.getAvatarHash(); if (avatarHash != null) { byte[] avatarBytes = vCard.getAvatar(); if (avatarBytes != null) { debug(ImApp.LOG_TAG, "found avatar image in vcard for: " + jid); debug(ImApp.LOG_TAG, "start avatar length: " + avatarBytes.length); int width = ImApp.DEFAULT_AVATAR_WIDTH; int height = ImApp.DEFAULT_AVATAR_HEIGHT; BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeByteArray(avatarBytes, 0, avatarBytes.length,options); options.inSampleSize = DatabaseUtils.calculateInSampleSize(options, width, height); options.inJustDecodeBounds = false; Bitmap b = BitmapFactory.decodeByteArray(avatarBytes, 0, avatarBytes.length,options); b = Bitmap.createScaledBitmap(b, ImApp.DEFAULT_AVATAR_WIDTH, ImApp.DEFAULT_AVATAR_HEIGHT, false); ByteArrayOutputStream stream = new ByteArrayOutputStream(); b.compress(Bitmap.CompressFormat.JPEG, 80, stream); byte[] avatarBytesCompressed = stream.toByteArray(); debug(ImApp.LOG_TAG, "compressed avatar length: " + avatarBytesCompressed.length); DatabaseUtils.insertAvatarBlob(resolver, Imps.Avatars.CONTENT_URI, mProviderId, mAccountId, avatarBytesCompressed, hash, jid); // int providerId, int accountId, byte[] data, String hash,String contact return true; } } } } catch (XMPPException e) { // Log.d(ImApp.LOG_TAG,"err loading vcard"); if (e.getStreamError() != null) { String streamErr = e.getStreamError().getCode(); if (streamErr != null && (streamErr.contains("404") || streamErr.contains("503"))) { return false; } } } return false; } @Override protected void doUpdateUserPresenceAsync(Presence presence) { org.jivesoftware.smack.packet.Presence packet = makePresencePacket(presence); sendPacket(packet); mUserPresence = presence; notifyUserPresenceUpdated(); } private org.jivesoftware.smack.packet.Presence makePresencePacket(Presence presence) { String statusText = presence.getStatusText(); Type type = Type.available; Mode mode = Mode.available; int priority = mPriority; final int status = presence.getStatus(); if (status == Presence.AWAY) { priority = 10; mode = Mode.away; } else if (status == Presence.IDLE) { priority = 15; mode = Mode.away; } else if (status == Presence.DO_NOT_DISTURB) { priority = 5; mode = Mode.dnd; } else if (status == Presence.OFFLINE) { priority = 0; type = Type.unavailable; statusText = "Offline"; } // The user set priority is the maximum allowed if (priority > mPriority) priority = mPriority; org.jivesoftware.smack.packet.Presence packet = new org.jivesoftware.smack.packet.Presence( type, statusText, priority, mode); return packet; } @Override public int getCapability() { return ImConnection.CAPABILITY_SESSION_REESTABLISHMENT | ImConnection.CAPABILITY_GROUP_CHAT; } private XmppChatGroupManager mChatGroupManager = null; @Override public synchronized ChatGroupManager getChatGroupManager() { if (mChatGroupManager == null) mChatGroupManager = new XmppChatGroupManager(); return mChatGroupManager; } public class XmppChatGroupManager extends ChatGroupManager { private Hashtable<String,MultiUserChat> mMUCs = new Hashtable<String,MultiUserChat>(); public MultiUserChat getMultiUserChat (String chatRoomJid) { return mMUCs.get(chatRoomJid); } @Override public boolean createChatGroupAsync(String chatRoomJid, String nickname) throws Exception { RoomInfo roomInfo = null; Address address = new XmppAddress (chatRoomJid); try { //first check if the room already exists roomInfo = MultiUserChat.getRoomInfo(mConnection, chatRoomJid); } catch (Exception e) { //who knows? } if (roomInfo == null) { //if the room does not exist, then create one //should be room@server String[] parts = chatRoomJid.split("@"); String room = parts[0]; String server = parts[1]; try { // Create a MultiUserChat using a Connection for a room MultiUserChat muc = new MultiUserChat(mConnection, chatRoomJid); try { // Create the room muc.create(nickname); } catch (XMPPException iae) { if (iae.getMessage().contains("Creation failed")) { //some server's don't return the proper 201 create code, so we can just assume the room was created! } else { throw iae; } } try { Form form = muc.getConfigurationForm(); Form submitForm = form.createAnswerForm(); for (Iterator fields = form.getFields();fields.hasNext();){ FormField field = (FormField) fields.next(); if(!FormField.TYPE_HIDDEN.equals(field.getType()) && field.getVariable()!= null){ submitForm.setDefaultAnswer(field.getVariable()); } } submitForm.setAnswer("muc#roomconfig_publicroom", true); muc.sendConfigurationForm(submitForm); } catch (XMPPException xe) { if (Debug.DEBUG_ENABLED) Log.w(ImApp.LOG_TAG,"(ignoring) got an error configuring MUC room: " + xe.getLocalizedMessage()); } muc.join(nickname); ChatGroup chatGroup = new ChatGroup(address,room,this); mGroups.put(address.getAddress(), chatGroup); mMUCs.put(chatRoomJid, muc); return true; } catch (XMPPException e) { Log.e(ImApp.LOG_TAG,"error creating MUC",e); return false; } } else { //otherwise, join the room! joinChatGroupAsync(address); return true; } } @Override public void deleteChatGroupAsync(ChatGroup group) { String chatRoomJid = group.getAddress().getAddress(); if (mMUCs.containsKey(chatRoomJid)) { MultiUserChat muc = mMUCs.get(chatRoomJid); try { muc.destroy("", null); mMUCs.remove(chatRoomJid); } catch (XMPPException e) { Log.e(ImApp.LOG_TAG,"error destroying MUC",e); } } } @Override protected void addGroupMemberAsync(ChatGroup group, Contact contact) { String chatRoomJid = group.getAddress().getAddress(); if (mMUCs.containsKey(chatRoomJid)) { MultiUserChat muc = mMUCs.get(chatRoomJid); } } @Override protected void removeGroupMemberAsync(ChatGroup group, Contact contact) { // TODO Auto-generated method stub } @Override public void joinChatGroupAsync(Address address) { String chatRoomJid = address.getAddress(); String[] parts = chatRoomJid.split("@"); String room = parts[0]; String server = parts[1]; String nickname = mUser.getName().split("@")[0]; try { // Create a MultiUserChat using a Connection for a room MultiUserChat muc = new MultiUserChat(mConnection, chatRoomJid); // Create the room muc.join(nickname); ChatGroup chatGroup = new ChatGroup(address,room,this); mGroups.put(address.getAddress(), chatGroup); mMUCs.put(chatRoomJid, muc); } catch (XMPPException e) { Log.e(ImApp.LOG_TAG,"error joining MUC",e); } } @Override public void leaveChatGroupAsync(ChatGroup group) { String chatRoomJid = group.getAddress().getAddress(); if (mMUCs.containsKey(chatRoomJid)) { MultiUserChat muc = mMUCs.get(chatRoomJid); muc.leave(); mMUCs.remove(chatRoomJid); } } @Override public void inviteUserAsync(ChatGroup group, Contact invitee) { String chatRoomJid = group.getAddress().getAddress(); if (mMUCs.containsKey(chatRoomJid)) { MultiUserChat muc = mMUCs.get(chatRoomJid); String reason = ""; //no reason for now muc.invite(invitee.getAddress().getAddress(),reason); } } @Override public void acceptInvitationAsync(Invitation invitation) { Address addressGroup = invitation.getGroupAddress(); joinChatGroupAsync (addressGroup); } @Override public void rejectInvitationAsync(Invitation invitation) { Address addressGroup = invitation.getGroupAddress(); String reason = ""; // no reason for now MultiUserChat.decline(mConnection, addressGroup.getAddress(),invitation.getSender().getAddress(),reason); } }; @Override public synchronized ChatSessionManager getChatSessionManager() { if (mSessionManager == null) mSessionManager = new XmppChatSessionManager(); return mSessionManager; } @Override public synchronized XmppContactListManager getContactListManager() { if (mContactListManager == null) mContactListManager = new XmppContactListManager(); return mContactListManager; } @Override public Contact getLoginUser() { return mUser; } @Override public Map<String, String> getSessionContext() { // Empty state for now (but must have at least one key) return Collections.singletonMap("state", "empty"); } @Override public int[] getSupportedPresenceStatus() { return new int[] { Presence.AVAILABLE, Presence.AWAY, Presence.IDLE, Presence.OFFLINE, Presence.DO_NOT_DISTURB, }; } @Override public void loginAsync(long accountId, String passwordTemp, long providerId, boolean retry) { mAccountId = accountId; mPassword = passwordTemp; mProviderId = providerId; mRetryLogin = retry; ContentResolver contentResolver = mContext.getContentResolver(); if (mPassword == null) mPassword = Imps.Account.getPassword(contentResolver, mAccountId); mIsGoogleAuth = mPassword.startsWith(GTalkOAuth2.NAME); if (mIsGoogleAuth) { mPassword = mPassword.split(":")[1]; } Cursor cursor = contentResolver.query(Imps.ProviderSettings.CONTENT_URI,new String[] {Imps.ProviderSettings.NAME, Imps.ProviderSettings.VALUE},Imps.ProviderSettings.PROVIDER + "=?",new String[] { Long.toString(mProviderId)},null); if (cursor == null) return; Imps.ProviderSettings.QueryMap providerSettings = new Imps.ProviderSettings.QueryMap( cursor, contentResolver, mProviderId, false, null); mUser = makeUser(providerSettings, contentResolver); providerSettings.close(); execute(new Runnable() { @Override public void run() { do_login(); } }); } // Runs in executor thread private void do_login() { if (mConnection != null) { setState(getState(), new ImErrorInfo(ImErrorInfo.CANT_CONNECT_TO_SERVER, "still trying...")); return; } ContentResolver contentResolver = mContext.getContentResolver(); Cursor cursor = contentResolver.query(Imps.ProviderSettings.CONTENT_URI,new String[] {Imps.ProviderSettings.NAME, Imps.ProviderSettings.VALUE},Imps.ProviderSettings.PROVIDER + "=?",new String[] { Long.toString(mProviderId)},null); if (cursor == null) return; //not going to work Imps.ProviderSettings.QueryMap providerSettings = new Imps.ProviderSettings.QueryMap( cursor, contentResolver, mProviderId, false, null); // providerSettings is closed in initConnection(); String userName = Imps.Account.getUserName(contentResolver, mAccountId); String defaultStatus = null; mNeedReconnect = true; setState(LOGGING_IN, null); mUserPresence = new Presence(Presence.AVAILABLE, defaultStatus, Presence.CLIENT_TYPE_MOBILE); try { if (userName == null || userName.length() == 0) throw new XMPPException("empty username not allowed"); initConnectionAndLogin(providerSettings, userName); setState(LOGGED_IN, null); debug(TAG, "logged in"); mNeedReconnect = false; } catch (XMPPException e) { debug(TAG, "exception thrown on connection",e); ImErrorInfo info = new ImErrorInfo(ImErrorInfo.CANT_CONNECT_TO_SERVER, e.getMessage()); mRetryLogin = true; // our default behavior is to retry if (mConnection != null && mConnection.isConnected() && (!mConnection.isAuthenticated())) { if (mIsGoogleAuth) { debug (TAG, "google failed; may need to refresh"); String newPassword = refreshGoogleToken (userName, mPassword,providerSettings.getDomain()); if (newPassword != null) mPassword = newPassword; mRetryLogin = true; } else { debug(TAG, "not authorized - will not retry"); info = new ImErrorInfo(ImErrorInfo.INVALID_USERNAME, "invalid user/password"); mRetryLogin = false; mNeedReconnect = false; } } if (mRetryLogin && getState() != SUSPENDED) { debug(TAG, "will retry"); setState(LOGGING_IN, info); maybe_reconnect(); } else { debug(TAG, "will not retry"); disconnect(); disconnected(info); } } catch (Exception e) { debug(TAG, "login failed",e); mRetryLogin = true; mNeedReconnect = true; debug(TAG, "will retry"); ImErrorInfo info = new ImErrorInfo(ImErrorInfo.UNKNOWN_ERROR, "keymanagement exception"); setState(LOGGING_IN, info); } finally { providerSettings.close(); } } private String refreshGoogleToken (String userName, String oldPassword, String domain) { String expiredToken = oldPassword; if (expiredToken.startsWith(IS_GOOGLE)) { expiredToken = expiredToken.split(":")[1]; } //invalidate our old one, that is locally cached AccountManager.get(mContext.getApplicationContext()).invalidateAuthToken("com.google", expiredToken); //request a new one String password = GTalkOAuth2.getGoogleAuthToken(userName + '@' + domain, mContext.getApplicationContext()); if (password != null) { //now store the new one, for future use until it expires ImApp.insertOrUpdateAccount(mContext.getContentResolver(), mProviderId, userName, GTalkOAuth2.NAME + ':' + password ); } return password; } // TODO shouldn't setProxy be handled in Imps/settings? public void setProxy(String type, String host, int port) { if (type == null) { mProxyInfo = ProxyInfo.forNoProxy(); } else { ProxyInfo.ProxyType pType = ProxyType.valueOf(type); String username = null; String password = null; if (type.equals(TorProxyInfo.PROXY_TYPE) //socks5 && host.equals(TorProxyInfo.PROXY_HOST) //127.0.0.1 && port == TorProxyInfo.PROXY_PORT) //9050 { //if the proxy is for Orbot/Tor then generate random usr/pwd to isolate Tor streams username = rndForTorCircuits.nextInt(100000)+""; password = rndForTorCircuits.nextInt(100000)+""; } mProxyInfo = new ProxyInfo(pType, host, port, username, password); } } public void initConnection(MyXMPPConnection connection, Contact user, int state) { mConnection = connection; mRoster = mConnection.getRoster(); mUser = user; setState(state, null); } private void initConnectionAndLogin (Imps.ProviderSettings.QueryMap providerSettings,String userName) throws XMPPException, KeyManagementException, NoSuchAlgorithmException, IllegalStateException, RuntimeException { Debug.onConnectionStart(); //only activates if Debug TRUE is set, so you can leave this in! initConnection(providerSettings, userName); mResource = providerSettings.getXmppResource(); //disable compression based on statement by Ge0rg mConfig.setCompressionEnabled(false); if (mConnection.isConnected()) { mConnection.login(mUsername, mPassword, mResource); String fullJid = mConnection.getUser(); XmppAddress xa = new XmppAddress(fullJid); mUser = new Contact(xa, xa.getUser()); mStreamHandler.notifyInitialLogin(); initServiceDiscovery(); sendPresencePacket(); mRoster = mConnection.getRoster(); mRoster.setSubscriptionMode(Roster.SubscriptionMode.manual); getContactListManager().listenToRoster(mRoster); } else { disconnect(); disconnected(new ImErrorInfo(ImpsErrorInfo.SERVER_UNAVAILABLE, "not connected on login")); } } // Runs in executor thread private void initConnection(Imps.ProviderSettings.QueryMap providerSettings, String userName) throws NoSuchAlgorithmException, KeyManagementException, XMPPException { boolean allowPlainAuth = providerSettings.getAllowPlainAuth(); boolean requireTls = providerSettings.getRequireTls(); boolean doDnsSrv = providerSettings.getDoDnsSrv(); boolean tlsCertVerify = providerSettings.getTlsCertVerify(); boolean useSASL = true;//!allowPlainAuth; String domain = providerSettings.getDomain(); mPriority = providerSettings.getXmppResourcePrio(); int serverPort = providerSettings.getPort(); String server = providerSettings.getServer(); if ("".equals(server)) server = null; debug(TAG, "TLS required? " + requireTls); debug(TAG, "cert verification? " + tlsCertVerify); if (providerSettings.getUseTor()) { setProxy(TorProxyInfo.PROXY_TYPE, TorProxyInfo.PROXY_HOST, TorProxyInfo.PROXY_PORT); } else { setProxy(null, null, -1); } if (mProxyInfo == null) mProxyInfo = ProxyInfo.forNoProxy(); // If user did not specify a server, and SRV requested then lookup SRV if (doDnsSrv) { //java.lang.System.setProperty("java.net.preferIPv4Stack", "true"); //java.lang.System.setProperty("java.net.preferIPv6Addresses", "false"); debug(TAG, "(DNS SRV) resolving: " + domain); DNSUtil.HostAddress srvHost = DNSUtil.resolveXMPPDomain(domain); server = srvHost.getHost(); if (serverPort <= 0) { // If user did not override port, use port from SRV record serverPort = srvHost.getPort(); } debug(TAG, "(DNS SRV) resolved: " + domain + "=" + server + ":" + serverPort); } if (server != null && server.contains("google.com")) { mUsername = userName + '@' + domain; } else if (domain.contains("gmail.com")) { mUsername = userName + '@' + domain; } else if (mIsGoogleAuth) { mUsername = userName + '@' + domain; } else { mUsername = userName; } if (serverPort == 0) //if serverPort is set to 0 then use 5222 as default serverPort = 5222; // No server requested and SRV lookup wasn't requested or returned nothing - use domain if (server == null) { debug(TAG, "(use domain) ConnectionConfiguration(" + domain + ", " + serverPort + ", " + domain + ", mProxyInfo);"); if (mProxyInfo == null) mConfig = new ConnectionConfiguration(domain, serverPort); else mConfig = new ConnectionConfiguration(domain, serverPort, mProxyInfo); //server = domain; } else { debug(TAG, "(use server) ConnectionConfiguration(" + server + ", " + serverPort + ", " + domain + ", mProxyInfo);"); //String serviceName = domain; //if (server != null && (!server.endsWith(".onion"))) //if a connect server was manually entered, and is not an .onion address // serviceName = server; if (mProxyInfo == null) mConfig = new ConnectionConfiguration(server, serverPort, domain); else mConfig = new ConnectionConfiguration(server, serverPort, domain, mProxyInfo); } mConfig.setDebuggerEnabled(Debug.DEBUG_ENABLED); mConfig.setSASLAuthenticationEnabled(useSASL); // Android has no support for Kerberos or GSSAPI, so disable completely SASLAuthentication.unregisterSASLMechanism("KERBEROS_V4"); SASLAuthentication.unregisterSASLMechanism("GSSAPI"); SASLAuthentication.registerSASLMechanism( GTalkOAuth2.NAME, GTalkOAuth2.class ); if (mIsGoogleAuth) //if using google auth enable sasl SASLAuthentication.supportSASLMechanism( GTalkOAuth2.NAME, 0); else if (domain.contains("google.com")||domain.contains("gmail.com")) //if not google auth, disable if doing direct google auth SASLAuthentication.unsupportSASLMechanism( GTalkOAuth2.NAME); SASLAuthentication.supportSASLMechanism("PLAIN", 1); SASLAuthentication.supportSASLMechanism("DIGEST-MD5", 2); if (requireTls) { MemorizingTrustManager trustManager = ImApp.sImApp.getTrustManager(); if (sslContext == null) { sslContext = SSLContext.getInstance(SSLCONTEXT_TYPE); SecureRandom secureRandom = new java.security.SecureRandom(); sslContext.init(null, new javax.net.ssl.TrustManager[] { trustManager }, secureRandom); sslContext.getDefaultSSLParameters().getCipherSuites(); if (Build.VERSION.SDK_INT >= 20) { sslContext.getDefaultSSLParameters().setCipherSuites(XMPPCertPins.SSL_IDEAL_CIPHER_SUITES_API_20); } else { sslContext.getDefaultSSLParameters().setCipherSuites(XMPPCertPins.SSL_IDEAL_CIPHER_SUITES); } } int currentapiVersion = android.os.Build.VERSION.SDK_INT; if (currentapiVersion >= 16){ // Enable TLS1.2 and TLS1.1 on supported versions of android //mConfig.setEnabledProtocols(new String[] { "TLSv1.2", "TLSv1.1", "TLSv1" }); sslContext.getDefaultSSLParameters().setProtocols(new String[] { "TLSv1.2", "TLSv1.1", "TLSv1" }); } if (currentapiVersion >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH){ mConfig.setEnabledCipherSuites(XMPPCertPins.SSL_IDEAL_CIPHER_SUITES); } HostnameVerifier hv = trustManager.wrapHostnameVerifier(HttpsURLConnection.getDefaultHostnameVerifier()); mConfig.setHostnameVerifier(hv); mConfig.setCustomSSLContext(sslContext); mConfig.setSecurityMode(SecurityMode.required); mConfig.setVerifyChainEnabled(true); mConfig.setVerifyRootCAEnabled(true); mConfig.setExpiredCertificatesCheckEnabled(true); mConfig.setNotMatchingDomainCheckEnabled(true); mConfig.setSelfSignedCertificateEnabled(false); mConfig.setCallbackHandler(this); } else { // if it finds a cert, still use it, but don't check anything since // TLS errors are not expected by the user mConfig.setSecurityMode(SecurityMode.enabled); if (sslContext == null) { sslContext = SSLContext.getInstance(SSLCONTEXT_TYPE); SecureRandom mSecureRandom = new java.security.SecureRandom(); sslContext.init(null, new javax.net.ssl.TrustManager[] { getDummyTrustManager () }, mSecureRandom); sslContext.getDefaultSSLParameters().setCipherSuites(XMPPCertPins.SSL_IDEAL_CIPHER_SUITES); } mConfig.setCustomSSLContext(sslContext); if (!allowPlainAuth) SASLAuthentication.unsupportSASLMechanism("PLAIN"); mConfig.setVerifyChainEnabled(false); mConfig.setVerifyRootCAEnabled(false); mConfig.setExpiredCertificatesCheckEnabled(false); mConfig.setNotMatchingDomainCheckEnabled(false); mConfig.setSelfSignedCertificateEnabled(true); } // Don't use smack reconnection - not reliable mConfig.setReconnectionAllowed(false); mConfig.setSendPresence(true); mConfig.setRosterLoadedAtLogin(true); mConnection = new MyXMPPConnection(mConfig); //debug(TAG,"is secure connection? " + mConnection.isSecureConnection()); //debug(TAG,"is using TLS? " + mConnection.isUsingTLS()); mConnection.addPacketListener(new PacketListener() { @Override public void processPacket(Packet packet) { debug(TAG, "receive message: " + packet.getFrom() + " to " + packet.getTo()); org.jivesoftware.smack.packet.Message smackMessage = (org.jivesoftware.smack.packet.Message) packet; String address = smackMessage.getFrom(); String body = smackMessage.getBody(); if (body == null) { Collection<Body> mColl = smackMessage.getBodies(); for (Body bodyPart : mColl) { String msg = bodyPart.getMessage(); if (msg != null) { body = msg; break; } } } DeliveryReceipts.DeliveryReceipt dr = (DeliveryReceipts.DeliveryReceipt) smackMessage .getExtension("received", DeliveryReceipts.NAMESPACE); if (dr != null) { debug(TAG, "got delivery receipt for " + dr.getId()); boolean groupMessage = smackMessage.getType() == org.jivesoftware.smack.packet.Message.Type.groupchat; ChatSession session = findOrCreateSession(address, groupMessage); session.onMessageReceipt(dr.getId()); } if (body != null) { XmppAddress aFrom = new XmppAddress(smackMessage.getFrom()); boolean isGroupMessage = smackMessage.getType() == org.jivesoftware.smack.packet.Message.Type.groupchat; ChatSession session = findOrCreateSession(address, isGroupMessage); Message rec = new Message(body); rec.setTo(mUser.getAddress()); rec.setFrom(aFrom); rec.setDateTime(new Date()); rec.setType(Imps.MessageType.INCOMING); // Detect if this was said by us, and mark message as outgoing if (isGroupMessage && rec.getFrom().getResource().equals(rec.getTo().getUser())) { rec.setType(Imps.MessageType.OUTGOING); } boolean good = session.onReceiveMessage(rec); if (smackMessage.getExtension("request", DeliveryReceipts.NAMESPACE) != null) { if (good) { debug(TAG, "sending delivery receipt"); // got XEP-0184 request, send receipt sendReceipt(smackMessage); session.onReceiptsExpected(); } else { debug(TAG, "not sending delivery receipt due to processing error"); } } else if (!good) { debug(TAG, "packet processing error"); } } } }, new PacketTypeFilter(org.jivesoftware.smack.packet.Message.class)); mConnection.addPacketListener(new PacketListener() { @Override public void processPacket(Packet packet) { org.jivesoftware.smack.packet.Presence presence = (org.jivesoftware.smack.packet.Presence) packet; qPresence.push(presence); } }, new PacketTypeFilter(org.jivesoftware.smack.packet.Presence.class)); initPacketProcessor(); initPresenceProcessor (); ConnectionListener connectionListener = new ConnectionListener() { /** * Called from smack when connect() is fully successful * * This is called on the executor thread while we are in reconnect() */ @Override public void reconnectionSuccessful() { if (mStreamHandler == null || !mStreamHandler.isResumePending()) { debug(TAG, "Reconnection success"); onReconnectionSuccessful(); mRoster = mConnection.getRoster(); } else { debug(TAG, "Ignoring reconnection callback due to pending resume"); } } @Override public void reconnectionFailed(Exception e) { // We are not using the reconnection manager throw new UnsupportedOperationException(); } @Override public void reconnectingIn(int seconds) { // // We are not using the reconnection manager // throw new UnsupportedOperationException(); } @Override public void connectionClosedOnError(final Exception e) { /* * This fires when: * - Packet reader or writer detect an error * - Stream compression failed * - TLS fails but is required * - Network error * - We forced a socket shutdown */ debug(TAG, "reconnect on error: " + e.getMessage()); if (e.getMessage().contains("conflict")) { execute(new Runnable() { @Override public void run() { disconnect(); disconnected(new ImErrorInfo(ImpsErrorInfo.ALREADY_LOGGED, "logged in from another location")); } }); } else if (!mNeedReconnect) { execute(new Runnable() { public void run() { if (getState() == LOGGED_IN) { //Thread.sleep(1000); mNeedReconnect = true; setState(LOGGING_IN, new ImErrorInfo(ImErrorInfo.NETWORK_ERROR, "network error")); reconnect(); } } }); } } @Override public void connectionClosed() { debug(TAG, "connection closed"); /* * This can be called in these cases: * - Connection is shutting down * - because we are calling disconnect * - in do_logout * * - NOT * - because server disconnected "normally" * - we were trying to log in (initConnection), but are failing * - due to network error * - due to login failing */ } }; mConnection.addConnectionListener(connectionListener); mStreamHandler = new XmppStreamHandler(mConnection, connectionListener); for (int i = 0; i < 3; i++) { try { mConnection.connect(); break; } catch (Exception uhe) { //sometimes DNS fails.. let's wait and try again a few times try { Thread.sleep(500);} catch (Exception e){} } } if (!mConnection.isConnected()) throw new XMPPException("Unable to connect to host"); } private void sendPresencePacket() { qPacket.add(makePresencePacket(mUserPresence)); } public void sendReceipt(org.jivesoftware.smack.packet.Message msg) { debug(TAG, "sending XEP-0184 ack to " + msg.getFrom() + " id=" + msg.getPacketID()); org.jivesoftware.smack.packet.Message ack = new org.jivesoftware.smack.packet.Message( msg.getFrom(), msg.getType()); ack.addExtension(new DeliveryReceipts.DeliveryReceipt(msg.getPacketID())); mConnection.sendPacket(ack); } public X509TrustManager getDummyTrustManager () { return new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } }; } protected int parsePresence(org.jivesoftware.smack.packet.Presence presence) { int type = Presence.AVAILABLE; Mode rmode = presence.getMode(); Type rtype = presence.getType(); //if a device sends something other than available, check if there is a higher priority one available on the server /* if (rmode != Mode.available) { if (mRoster != null) { org.jivesoftware.smack.packet.Presence npresence = mRoster.getPresence(XmppAddress.stripResource(presence.getFrom())); rmode = npresence.getMode(); rtype = npresence.getType(); if (rmode == Mode.away || rmode == Mode.xa) type = Presence.AWAY; else if (rmode == Mode.dnd) type = Presence.DO_NOT_DISTURB; else if (rtype == Type.unavailable || rtype == Type.error) type = Presence.OFFLINE; } }*/ if (rmode == Mode.away || rmode == Mode.xa) type = Presence.AWAY; else if (rmode == Mode.dnd) type = Presence.DO_NOT_DISTURB; else if (rtype == Type.unavailable || rtype == Type.error) type = Presence.OFFLINE; else if (rtype == Type.unsubscribed) type = Presence.NOT_SUBSCRIBED; return type; } // We must release resources here, because we will not be reused void disconnected(ImErrorInfo info) { debug(TAG, "disconnected"); join(); setState(DISCONNECTED, info); } @Override public void logoutAsync() { new Thread(new Runnable() { @Override public void run() { do_logout(); } }).start(); } // Force immediate logout public void logout() { logoutAsync(); } // Usually runs in executor thread, unless called from logout() private void do_logout() { setState(LOGGING_OUT, null); disconnect(); disconnected(null); } // Runs in executor thread private void disconnect() { clearPing(); XMPPConnection conn = mConnection; mConnection = null; try { conn.disconnect(); } catch (Throwable th) { // ignore } mNeedReconnect = false; mRetryLogin = false; } @Override public void reestablishSessionAsync(Map<String, String> sessionContext) { execute(new Runnable() { @Override public void run() { if (getState() == SUSPENDED) { debug(TAG, "reestablish"); mNeedReconnect = false; setState(LOGGING_IN, null); maybe_reconnect(); } } }); } @Override public void suspend() { execute(new Runnable() { @Override public void run() { debug(TAG, "suspend"); setState(SUSPENDED, null); mNeedReconnect = false; clearPing(); // Do not try to reconnect anymore if we were asked to suspend if (mStreamHandler != null) mStreamHandler.quickShutdown(); } }); } private ChatSession findOrCreateSession(String address, boolean groupChat) { ChatSession session = mSessionManager.findSession(address); if (session == null) { ImEntity participant = findOrCreateParticipant(address, groupChat); session = mSessionManager.createChatSession(participant,false); } return session; } ImEntity findOrCreateParticipant(String address, boolean groupChat) { ImEntity participant = mContactListManager.getContact(address); if (participant == null) { if (!groupChat) { participant = makeContact(address); } else { try { mChatGroupManager.createChatGroupAsync(address, mUser.getName()); Address xmppAddress = new XmppAddress(address); participant = mChatGroupManager.getChatGroup(xmppAddress); } catch (Exception e) { Log.e(ImApp.LOG_TAG,"unable to join group chat",e); } } } return participant; } Contact findOrCreateContact(String address) { return (Contact) findOrCreateParticipant(address, false); } private Contact makeContact(String address) { Contact contact = null; //load from roster if we don't have the contact RosterEntry rEntry = null; if (mConnection != null) rEntry = mConnection.getRoster().getEntry(address); if (rEntry != null) { XmppAddress xAddress = new XmppAddress(address); String name = rEntry.getName(); if (name == null) name = xAddress.getUser(); contact = new Contact(xAddress, name); } else { XmppAddress xAddress = new XmppAddress(address); contact = new Contact(xAddress, xAddress.getUser()); } return contact; } private final class XmppChatSessionManager extends ChatSessionManager { @Override public void sendMessageAsync(ChatSession session, Message message) { String chatRoomJid = message.getTo().getAddress(); MultiUserChat muc = ((XmppChatGroupManager)getChatGroupManager()).getMultiUserChat(chatRoomJid); org.jivesoftware.smack.packet.Message msgXmpp = null; if (muc != null) { msgXmpp = muc.createMessage(); } else { msgXmpp = new org.jivesoftware.smack.packet.Message( message.getTo().getAddress(), org.jivesoftware.smack.packet.Message.Type.chat); msgXmpp.addExtension(new DeliveryReceipts.DeliveryReceiptRequest()); } //mRoster.getPresence(xaddress.getBareAddress()) msgXmpp.setFrom(message.getFrom().getAddress()); msgXmpp.setBody(message.getBody()); sendPacket(msgXmpp); //set message ID value on internal message message.setID(msgXmpp.getPacketID()); } ChatSession findSession(String address) { return mSessions.get(Address.stripResource(address)); } @Override public ChatSession createChatSession(ImEntity participant, boolean isNewSession) { qAvatar.push(participant.getAddress().getAddress()); ChatSession session = super.createChatSession(participant,isNewSession); // mSessions.put(Address.stripResource(participant.getAddress().getAddress()),session); return session; } } public class XmppContactListManager extends ContactListManager { @Override protected void setListNameAsync(final String name, final ContactList list) { execute(new Runnable() { @Override public void run() { do_setListName(name, list); } }); } // Runs in executor thread private void do_setListName(String name, ContactList list) { debug(TAG, "set list name"); mConnection.getRoster().getGroup(list.getName()).setName(name); notifyContactListNameUpdated(list, name); } @Override public String normalizeAddress(String address) { return Address.stripResource(address); } @Override public void loadContactListsAsync() { execute(new Runnable() { @Override public void run() { do_loadContactLists(); } }); } // For testing /* public void loadContactLists() { do_loadContactLists(); }*/ /** * Create new list of contacts from roster entries. * * Runs in executor thread * * @param entryIter iterator of roster entries to add to contact list * @param skipList list of contacts which should be omitted; new * contacts are added to this list automatically * @return contacts from roster which were not present in skiplist. */ /* private Collection<Contact> fillContacts(Collection<RosterEntry> entryIter, Set<String> skipList) { Roster roster = mConnection.getRoster(); Collection<Contact> contacts = new ArrayList<Contact>(); for (RosterEntry entry : entryIter) { String address = entry.getUser(); if (skipList != null && !skipList.add(address)) continue; String name = entry.getName(); if (name == null) name = address; XmppAddress xaddress = new XmppAddress(address); org.jivesoftware.smack.packet.Presence presence = roster.getPresence(address); String status = presence.getStatus(); String resource = null; Presence p = new Presence(parsePresence(presence), status, null, null, Presence.CLIENT_TYPE_DEFAULT); String from = presence.getFrom(); if (from != null && from.lastIndexOf("/") > 0) { resource = from.substring(from.lastIndexOf("/") + 1); if (resource.indexOf('.')!=-1) resource = resource.substring(0,resource.indexOf('.')); p.setResource(resource); } Contact contact = mContactListManager.getContact(xaddress.getBareAddress()); if (contact == null) contact = new Contact(xaddress, name); contact.setPresence(p); contacts.add(contact); } return contacts; } */ // Runs in executor thread private void do_loadContactLists() { debug(TAG, "load contact lists"); if (mConnection == null) return; Roster roster = mConnection.getRoster(); //Set<String> seen = new HashSet<String>(); // This group will also contain all the unfiled contacts. We will create it locally if it // does not exist. /* String generalGroupName = mContext.getString(R.string.buddies); for (Iterator<RosterGroup> giter = roster.getGroups().iterator(); giter.hasNext();) { RosterGroup group = giter.next(); debug(TAG, "loading group: " + group.getName() + " size:" + group.getEntryCount()); Collection<Contact> contacts = fillContacts(group.getEntries(), null); if (group.getName().equals(generalGroupName) && roster.getUnfiledEntryCount() > 0) { Collection<Contact> unfiled = fillContacts(roster.getUnfiledEntries(), null); contacts.addAll(unfiled); } XmppAddress groupAddress = new XmppAddress(group.getName()); ContactList cl = new ContactList(groupAddress, group.getName(), group .getName().equals(generalGroupName), contacts, this); notifyContactListCreated(cl); notifyContactsPresenceUpdated(contacts.toArray(new Contact[contacts.size()])); } Collection<Contact> contacts; if (roster.getUnfiledEntryCount() > 0) { contacts = fillContacts(roster.getUnfiledEntries(), null); } else { contacts = new ArrayList<Contact>(); } ContactList cl = getContactList(generalGroupName); cl = new ContactList(groupAddress, group.getName(), group .getName().equals(generalGroupName), contacts, this); // We might have already created the Buddies contact list above if (cl == null) { cl = new ContactList(mUser.getAddress(), generalGroupName, true, contacts, this); notifyContactListCreated(cl); notifyContactsPresenceUpdated(contacts.toArray(new Contact[contacts.size()])); } */ //since we don't show lists anymore, let's just load all entries together ContactList cl; try { cl = mContactListManager.getDefaultContactList(); } catch (ImException e1) { debug(TAG,"couldn't read default list"); cl = null; } if (cl == null) { String generalGroupName = mContext.getString(R.string.buddies); Collection<Contact> contacts = new ArrayList<Contact>(); XmppAddress groupAddress = new XmppAddress(generalGroupName); cl = new ContactList(groupAddress,generalGroupName, true, contacts, this); notifyContactListCreated(cl); } for (RosterEntry rEntry : roster.getEntries()) { String address = rEntry.getUser(); String name = rEntry.getName(); if (mUser.getAddress().getBareAddress().equals(address)) //don't load a roster for yourself continue; Contact contact = getContact(address); if (contact == null) { XmppAddress xAddr = new XmppAddress(address); if (name == null || name.length() == 0) name = xAddr.getUser(); contact = new Contact(xAddr,name); } //org.jivesoftware.smack.packet.Presence p = roster.getPresence(contact.getAddress().getBareAddress()); //qPresence.push(p); if (!cl.containsContact(contact)) { try { cl.addExistingContact(contact); } catch (ImException e) { debug(TAG,"could not add contact to list: " + e.getLocalizedMessage()); } } } notifyContactListLoaded(cl); notifyContactListsLoaded(); } // Runs in executor thread public void addContactsToList(Collection<String> addresses) { debug(TAG, "add contacts to lists"); if (mConnection == null) return; Roster roster = mConnection.getRoster(); ContactList cl; try { cl = mContactListManager.getDefaultContactList(); } catch (ImException e1) { debug(TAG,"couldn't read default list"); cl = null; } if (cl == null) { String generalGroupName = mContext.getString(R.string.buddies); Collection<Contact> contacts = new ArrayList<Contact>(); XmppAddress groupAddress = new XmppAddress(generalGroupName); cl = new ContactList(groupAddress,generalGroupName, true, contacts, this); notifyContactListCreated(cl); } for (String address : addresses) { if (mUser.getAddress().getBareAddress().equals(address)) //don't load a roster for yourself continue; Contact contact = getContact(address); if (contact == null) { XmppAddress xAddr = new XmppAddress(address); contact = new Contact(xAddr,xAddr.getUser()); } //org.jivesoftware.smack.packet.Presence p = roster.getPresence(contact.getAddress().getBareAddress()); //qPresence.push(p); if (!cl.containsContact(contact)) { try { cl.addExistingContact(contact); } catch (ImException e) { debug(TAG,"could not add contact to list: " + e.getLocalizedMessage()); } } } notifyContactListLoaded(cl); notifyContactListsLoaded(); } /* * iterators through a list of contacts to see if there were any Presence * notifications sent before the contact was loaded */ /* private void processQueuedPresenceNotifications (Collection<Contact> contacts) { Roster roster = mConnection.getRoster(); //now iterate through the list of queued up unprocessed presence changes for (Contact contact : contacts) { String address = parseAddressBase(contact.getAddress().getFullName()); org.jivesoftware.smack.packet.Presence presence = roster.getPresence(address); if (presence != null) { debug(TAG, "processing queued presence: " + address + " - " + presence.getStatus()); unprocdPresence.remove(address); contact.setPresence(new Presence(parsePresence(presence), presence.getStatus(), null, null, Presence.CLIENT_TYPE_DEFAULT)); Contact[] updatedContact = {contact}; notifyContactsPresenceUpdated(updatedContact); } } }*/ public void listenToRoster(final Roster roster) { roster.addRosterListener(rListener); } RosterListener rListener = new RosterListener() { @Override public void presenceChanged(org.jivesoftware.smack.packet.Presence presence) { qPresence.push(presence); } @Override public void entriesUpdated(Collection<String> addresses) { /* for (String address :addresses) { org.jivesoftware.smack.packet.Presence p = mRoster.getPresence(XmppAddress.stripResource(address)); qPresence.push(p); }*/ } @Override public void entriesDeleted(Collection<String> addresses) { ContactList cl; try { cl = mContactListManager.getDefaultContactList(); for (String address : addresses) { Contact contact = mContactListManager.getContact(XmppAddress.stripResource(address)); mContactListManager.notifyContactListUpdated(cl, ContactListListener.LIST_CONTACT_REMOVED, contact); } } catch (ImException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public void entriesAdded(Collection<String> addresses) { try { if (mContactListManager.getState() == LISTS_LOADED) { for (String address : addresses) { // org.jivesoftware.smack.packet.Presence p = mRoster.getPresence(Address.stripResource(address)); // qPresence.push(p); Contact contact = getContact(address); if (contact == null) { XmppAddress xAddr = new XmppAddress(address); contact = new Contact(xAddr,xAddr.getUser()); } try { ContactList cl = mContactListManager.getDefaultContactList(); if (!cl.containsContact(contact)) cl.addExistingContact(contact); } catch (Exception e) { debug(TAG,"could not add contact to list: " + e.getLocalizedMessage()); } } } } catch (Exception e) { Log.d(ImApp.LOG_TAG,"error adding contacts",e); } } }; @Override protected ImConnection getConnection() { return XmppConnection.this; } @Override protected void doRemoveContactFromListAsync(Contact contact, ContactList list) { // FIXME synchronize this to executor thread if (mConnection == null) return; Roster roster = mConnection.getRoster(); String address = contact.getAddress().getAddress(); try { RosterEntry entry = roster.getEntry(address); RosterGroup group = roster.getGroup(list.getName()); if (group == null) { debug(TAG, "could not find group " + list.getName() + " in roster"); roster.removeEntry(entry); } else { group.removeEntry(entry); entry = roster.getEntry(address); // Remove from Roster if this is the last group if (entry != null && entry.getGroups().size() <= 1) roster.removeEntry(entry); } } catch (XMPPException e) { debug(TAG, "remove entry failed: " + e.getMessage()); throw new RuntimeException(e); } //otherwise, send unsub message and delete from local contact database org.jivesoftware.smack.packet.Presence response = new org.jivesoftware.smack.packet.Presence( org.jivesoftware.smack.packet.Presence.Type.unsubscribed); response.setTo(address); sendPacket(response); notifyContactListUpdated(list, ContactListListener.LIST_CONTACT_REMOVED, contact); } @Override protected void doDeleteContactListAsync(ContactList list) { // TODO delete contact list debug(TAG, "delete contact list " + list.getName()); } @Override protected void doCreateContactListAsync(String name, Collection<Contact> contacts, boolean isDefault) { // TODO create contact list debug(TAG, "create contact list " + name + " default " + isDefault); } @Override protected void doBlockContactAsync(String address, boolean block) { // TODO block contact } @Override protected void doAddContactToListAsync(Contact contact, ContactList list) throws ImException { debug(TAG, "add contact to " + list.getName()); if (mConnection.isConnected()) { org.jivesoftware.smack.packet.Presence reqSubscribe = new org.jivesoftware.smack.packet.Presence( org.jivesoftware.smack.packet.Presence.Type.subscribe); reqSubscribe.setTo(contact.getAddress().getBareAddress()); sendPacket(reqSubscribe); org.jivesoftware.smack.packet.Presence reqSubscribed = new org.jivesoftware.smack.packet.Presence( org.jivesoftware.smack.packet.Presence.Type.subscribed); reqSubscribed.setTo(contact.getAddress().getBareAddress()); sendPacket(reqSubscribed); Roster roster = mConnection.getRoster(); String[] groups = new String[] { list.getName() }; try { RosterEntry rEntry = roster.getEntry(contact.getAddress().getBareAddress()); RosterGroup rGroup = roster.getGroup(list.getName()); if (rGroup == null) { if (rEntry == null) roster.createEntry (contact.getAddress().getBareAddress(), contact.getName(), null); } else if (rEntry == null) { roster.createEntry(contact.getAddress().getBareAddress(), contact.getName(), groups); } } catch (XMPPException e) { debug(TAG,"error updating remote roster",e); throw new ImException("error updating remote roster"); } do_loadContactLists(); notifyContactListUpdated(list, ContactListListener.LIST_CONTACT_ADDED, contact); } } @Override public void declineSubscriptionRequest(Contact contact) { debug(TAG, "decline subscription"); org.jivesoftware.smack.packet.Presence response = new org.jivesoftware.smack.packet.Presence( org.jivesoftware.smack.packet.Presence.Type.unsubscribed); response.setTo(contact.getAddress().getBareAddress()); sendPacket(response); try { mContactListManager.getSubscriptionRequestListener().onSubscriptionDeclined(contact, mProviderId, mAccountId); } catch (RemoteException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public void approveSubscriptionRequest(Contact contact) { debug(TAG, "approve subscription: " + contact.getAddress().getAddress()); org.jivesoftware.smack.packet.Presence response = new org.jivesoftware.smack.packet.Presence( org.jivesoftware.smack.packet.Presence.Type.subscribed); response.setTo(contact.getAddress().getBareAddress()); sendPacket(response); try { mContactListManager.getSubscriptionRequestListener().onSubscriptionApproved(contact, mProviderId, mAccountId); doAddContactToListAsync(contact, getContactListManager().getDefaultContactList()); } catch (ImException e) { debug (TAG, "error responding to subscription approval: " + e.getLocalizedMessage()); } catch (RemoteException e) { debug (TAG, "error responding to subscription approval: " + e.getLocalizedMessage()); } } @Override public Contact[] createTemporaryContacts(String[] addresses) { // debug(TAG, "create temporary " + address); Contact[] contacts = new Contact[addresses.length]; int i = 0; for (String address : addresses) { contacts[i++] = makeContact(address); } notifyContactsPresenceUpdated(contacts); return contacts; } @Override protected void doSetContactName(String address, String name) throws ImException { Roster roster = mConnection.getRoster(); RosterEntry entry = roster.getEntry(address); // confirm entry still exists if (entry == null) { return; } // set name entry.setName(name); } } public void sendHeartbeat(final long heartbeatInterval) { // Don't let heartbeats queue up if we have long running tasks - only // do the heartbeat if executor is idle. boolean success = executeIfIdle(new Runnable() { @Override public void run() { debug(TAG, "heartbeat state = " + getState()); doHeartbeat(heartbeatInterval); } }); if (!success) { debug(TAG, "failed to schedule heartbeat state = " + getState()); } } // Runs in executor thread public void doHeartbeat(long heartbeatInterval) { heartbeatSequence++; if (getState() == SUSPENDED) { debug(TAG, "heartbeat during suspend"); return; } if (mConnection == null && mRetryLogin) { debug(TAG, "reconnect with login"); do_login(); return; } if (mConnection == null) return; if (mNeedReconnect) { reconnect(); } else if (!mConnection.isConnected() && getState() == LOGGED_IN) { // Smack failed to tell us about a disconnect debug(TAG, "reconnect on unreported state change"); setState(LOGGING_IN, new ImErrorInfo(ImErrorInfo.NETWORK_ERROR, "network disconnected")); force_reconnect(); } else if (getState() == LOGGED_IN) { if (PING_ENABLED) { // Check ping on every heartbeat. checkPing() will return true immediately if we already checked. if (!checkPing()) { debug(TAG, "reconnect on ping failed: " + mUser.getAddress().getAddress()); setState(LOGGING_IN, new ImErrorInfo(ImErrorInfo.NETWORK_ERROR, "network timeout")); maybe_reconnect(); } else { // Send pings only at intervals configured by the user if (heartbeatSequence >= heartbeatInterval) { heartbeatSequence = 0; debug(TAG, "ping"); sendPing(); } } } } } private void clearPing() { debug(TAG, "clear ping"); mPingCollector = null; heartbeatSequence = 0; } // Runs in executor thread private void sendPing() { IQ req = new IQ() { public String getChildElementXML() { return "<ping xmlns='urn:xmpp:ping'/>"; } }; req.setType(IQ.Type.GET); PacketFilter filter = new AndFilter(new PacketIDFilter(req.getPacketID()), new PacketTypeFilter(IQ.class)); mPingCollector = mConnection.createPacketCollector(filter); mConnection.sendPacket(req); } // Runs in executor thread private boolean checkPing() { if (mPingCollector != null) { IQ result = (IQ) mPingCollector.pollResult(); mPingCollector.cancel(); mPingCollector = null; if (result == null) { Log.e(TAG, "ping timeout"); return false; } } return true; } // watch out, this is a different XMPPConnection class than XmppConnection! ;) // org.jivesoftware.smack.XMPPConnection // info.guardianproject.otr.app.im.plugin.xmpp.XmppConnection public static class MyXMPPConnection extends XMPPConnection { public MyXMPPConnection(ConnectionConfiguration config) { super(config); } public void shutdown() { if (socket != null) { try { // Be forceful in shutting down since SSL can get stuck try { socket.shutdownInput(); } catch (Exception e) { } socket.close(); shutdown(new org.jivesoftware.smack.packet.Presence( org.jivesoftware.smack.packet.Presence.Type.unavailable)); } catch (Exception e) { Log.e(TAG, "error on shutdown()", e); } } } } @Override public void networkTypeChanged() { super.networkTypeChanged(); execute(new Runnable() { @Override public void run() { debug(TAG, "network type changed"); mNeedReconnect = false; setState(LOGGING_IN, null); reconnect(); } }); } /* * Force a shutdown and reconnect, unless we are already reconnecting. * * Runs in executor thread */ private void force_reconnect() { debug(TAG, "force_reconnect mNeedReconnect=" + mNeedReconnect + " state=" + getState() + " connection?=" + (mConnection != null)); if (mConnection == null) return; if (mNeedReconnect) return; mNeedReconnect = true; try { if (mConnection != null && mConnection.isConnected()) { mStreamHandler.quickShutdown(); } } catch (Exception e) { Log.w(TAG, "problem disconnecting on force_reconnect: " + e.getMessage()); } reconnect(); } /* * Reconnect unless we are already in the process of doing so. * * Runs in executor thread. */ private void maybe_reconnect() { debug(TAG, "maybe_reconnect mNeedReconnect=" + mNeedReconnect + " state=" + getState() + " connection?=" + (mConnection != null)); // This is checking whether we are already in the process of reconnecting. If we are, // doHeartbeat will take care of reconnecting. if (mNeedReconnect) return; if (getState() == SUSPENDED) return; if (mConnection == null) return; mNeedReconnect = true; reconnect(); } /* * Retry connecting * * Runs in executor thread */ private void reconnect() { if (getState() == SUSPENDED) { debug(TAG, "reconnect during suspend, ignoring"); return; } if (mConnection != null) { // It is safe to ask mConnection whether it is connected, because either: // - We detected an error using ping and called force_reconnect, which did a shutdown // - Smack detected an error, so it knows it is not connected // so there are no cases where mConnection can be confused about being connected here. // The only left over cases are reconnect() being called too many times due to errors // reported multiple times or errors reported during a forced reconnect. // The analysis above is incorrect in the case where Smack loses connectivity // while trying to log in. This case is handled in a future heartbeat // by checking ping responses. clearPing(); if (mConnection.isConnected()) { debug(TAG,"reconnect while already connected, assuming good: " + mConnection); mNeedReconnect = false; setState(LOGGED_IN, null); return; } debug(TAG, "reconnect"); try { if (mStreamHandler.isResumePossible()) { // Connect without binding, will automatically trigger a resume debug(TAG, "mStreamHandler resume"); mConnection.connect(false); initServiceDiscovery(); } else { debug(TAG, "reconnection on network change failed: " + mUser.getAddress().getAddress()); mConnection = null; mNeedReconnect = false; setState(LOGGING_IN, new ImErrorInfo(ImErrorInfo.NETWORK_ERROR, null)); while (mNeedReconnect) do_login(); } } catch (Exception e) { if (mStreamHandler != null) mStreamHandler.quickShutdown(); mConnection = null; debug(TAG, "reconnection attempt failed", e); // Smack incorrectly notified us that reconnection was successful, reset in case it fails mNeedReconnect = false; setState(LOGGING_IN, new ImErrorInfo(ImErrorInfo.NETWORK_ERROR, e.getMessage())); while (mNeedReconnect) do_login(); } } else { mNeedReconnect = false; mConnection = null; debug(TAG, "reconnection on network change failed"); setState(LOGGING_IN, new ImErrorInfo(ImErrorInfo.NETWORK_ERROR, "reconnection on network change failed")); while (mNeedReconnect) do_login(); } } @Override protected void setState(int state, ImErrorInfo error) { debug(TAG, "setState to " + state); super.setState(state, error); if (state == LOGGED_IN) { mUserPresence = new Presence(Presence.AVAILABLE, "", Presence.CLIENT_TYPE_MOBILE); sendPresencePacket(); } } private void refreshPresence () { for (RosterEntry rEntry : mRoster.getEntries()) { org.jivesoftware.smack.packet.Presence p = mRoster.getPresence(rEntry.getUser()); qPresence.push(p); } } public void debug(String tag, String msg) { // if (Log.isLoggable(TAG, Log.DEBUG)) { if (Debug.DEBUG_ENABLED) { Log.d(tag, "" + mGlobalId + " : " + msg); } } public void debug(String tag, String msg, Exception e) { if (Debug.DEBUG_ENABLED) { Log.e(tag, "" + mGlobalId + " : " + msg,e); } } @Override public void handle(Callback[] arg0) throws IOException { for (Callback cb : arg0) { debug(TAG, cb.toString()); } } /* public class MySASLDigestMD5Mechanism extends SASLMechanism { public MySASLDigestMD5Mechanism(SASLAuthentication saslAuthentication) { super(saslAuthentication); } protected void authenticate() throws IOException, XMPPException { String mechanisms[] = { getName() }; java.util.Map props = new HashMap(); sc = Sasl.createSaslClient(mechanisms, null, "xmpp", hostname, props, this); super.authenticate(); } public void authenticate(String username, String host, String password) throws IOException, XMPPException { authenticationId = username; this.password = password; hostname = host; String mechanisms[] = { getName() }; java.util.Map props = new HashMap(); sc = Sasl.createSaslClient(mechanisms, null, "xmpp", host, props, this); super.authenticate(); } public void authenticate(String username, String host, CallbackHandler cbh) throws IOException, XMPPException { String mechanisms[] = { getName() }; java.util.Map props = new HashMap(); sc = Sasl.createSaslClient(mechanisms, null, "xmpp", host, props, cbh); super.authenticate(); } protected String getName() { return "DIGEST-MD5"; } public void challengeReceived(String challenge) throws IOException { //StringBuilder stanza = new StringBuilder(); byte response[]; if(challenge != null) response = sc.evaluateChallenge(Base64.decode(challenge)); else //response = sc.evaluateChallenge(null); response = sc.evaluateChallenge(new byte[0]); //String authenticationText = ""; Packet responseStanza; //if(response != null) //{ //authenticationText = Base64.encodeBytes(response, 8); //if(authenticationText.equals("")) //authenticationText = "="; if (response == null){ responseStanza = new Response(); } else { responseStanza = new Response(Base64.encodeBytes(response,Base64.DONT_BREAK_LINES)); } //} //stanza.append("<response xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\">"); //stanza.append(authenticationText); //stanza.append("</response>"); //getSASLAuthentication().send(stanza.toString()); getSASLAuthentication().send(responseStanza); } } */ private void initServiceDiscovery() { debug(TAG, "init service discovery"); // register connection features ServiceDiscoveryManager sdm = ServiceDiscoveryManager.getInstanceFor(mConnection); if (sdm == null) sdm = new ServiceDiscoveryManager(mConnection); if (!sdm.includesFeature(DISCO_FEATURE)) sdm.addFeature(DISCO_FEATURE); if (!sdm.includesFeature(DeliveryReceipts.NAMESPACE)) sdm.addFeature(DeliveryReceipts.NAMESPACE); } private void onReconnectionSuccessful() { mNeedReconnect = false; setState(LOGGED_IN, null); } private void addProviderManagerExtensions () { ProviderManager pm = ProviderManager.getInstance(); // Private Data Storage pm.addIQProvider("query","jabber:iq:private", new PrivateDataManager.PrivateDataIQProvider()); // Time try { pm.addIQProvider("query","jabber:iq:time", Class.forName("org.jivesoftware.smackx.packet.Time")); } catch (ClassNotFoundException e) { Log.w("TestClient", "Can't load class for org.jivesoftware.smackx.packet.Time"); } // Roster Exchange pm.addExtensionProvider("x","jabber:x:roster", new RosterExchangeProvider()); // Message Events pm.addExtensionProvider("x","jabber:x:event", new MessageEventProvider()); // Chat State pm.addExtensionProvider("active","http://jabber.org/protocol/chatstates", new ChatStateExtension.Provider()); pm.addExtensionProvider("composing","http://jabber.org/protocol/chatstates", new ChatStateExtension.Provider()); pm.addExtensionProvider("paused","http://jabber.org/protocol/chatstates", new ChatStateExtension.Provider()); pm.addExtensionProvider("inactive","http://jabber.org/protocol/chatstates", new ChatStateExtension.Provider()); pm.addExtensionProvider("gone","http://jabber.org/protocol/chatstates", new ChatStateExtension.Provider()); // XHTML pm.addExtensionProvider("html","http://jabber.org/protocol/xhtml-im", new XHTMLExtensionProvider()); // Group Chat Invitations pm.addExtensionProvider("x","jabber:x:conference", new GroupChatInvitation.Provider()); // Service Discovery # Items pm.addIQProvider("query","http://jabber.org/protocol/disco#items", new DiscoverItemsProvider()); // Service Discovery # Info pm.addIQProvider("query","http://jabber.org/protocol/disco#info", new DiscoverInfoProvider()); // Data Forms pm.addExtensionProvider("x","jabber:x:data", new DataFormProvider()); // MUC User pm.addExtensionProvider("x","http://jabber.org/protocol/muc#user", new MUCUserProvider()); // MUC Admin pm.addIQProvider("query","http://jabber.org/protocol/muc#admin", new MUCAdminProvider()); // MUC Owner pm.addIQProvider("query","http://jabber.org/protocol/muc#owner", new MUCOwnerProvider()); // Delayed Delivery pm.addExtensionProvider("x","jabber:x:delay", new DelayInformationProvider()); // Version try { pm.addIQProvider("query","jabber:iq:version", Class.forName("org.jivesoftware.smackx.packet.Version")); } catch (ClassNotFoundException e) { // Not sure what's happening here. } // VCard pm.addIQProvider("vCard","vcard-temp", new VCardProvider()); // Offline Message Requests pm.addIQProvider("offline","http://jabber.org/protocol/offline", new OfflineMessageRequest.Provider()); // Offline Message Indicator pm.addExtensionProvider("offline","http://jabber.org/protocol/offline", new OfflineMessageInfo.Provider()); // Last Activity pm.addIQProvider("query","jabber:iq:last", new LastActivity.Provider()); // User Search pm.addIQProvider("query","jabber:iq:search", new UserSearch.Provider()); // SharedGroupsInfo pm.addIQProvider("sharedgroup","http: // JEP-33: Extended Stanza Addressing pm.addExtensionProvider("addresses","http://jabber.org/protocol/address", new MultipleAddressesProvider()); // FileTransfer pm.addIQProvider("si","http://jabber.org/protocol/si", new StreamInitiationProvider()); pm.addIQProvider("query","http://jabber.org/protocol/bytestreams", new BytestreamsProvider()); // Privacy pm.addIQProvider("query","jabber:iq:privacy", new PrivacyProvider()); pm.addIQProvider("command", "http://jabber.org/protocol/commands", new AdHocCommandDataProvider()); pm.addExtensionProvider("malformed-action", "http://jabber.org/protocol/commands", new AdHocCommandDataProvider.MalformedActionError()); pm.addExtensionProvider("bad-locale", "http://jabber.org/protocol/commands", new AdHocCommandDataProvider.BadLocaleError()); pm.addExtensionProvider("bad-payload", "http://jabber.org/protocol/commands", new AdHocCommandDataProvider.BadPayloadError()); pm.addExtensionProvider("bad-sessionid", "http://jabber.org/protocol/commands", new AdHocCommandDataProvider.BadSessionIDError()); pm.addExtensionProvider("session-expired", "http://jabber.org/protocol/commands", new AdHocCommandDataProvider.SessionExpiredError()); } class NameSpace { public static final String DISCO_INFO = "http://jabber.org/protocol/disco#info"; public static final String DISCO_ITEMS = "http://jabber.org/protocol/disco#items"; public static final String IQ_GATEWAY = "jabber:iq:gateway"; public static final String IQ_GATEWAY_REGISTER = "jabber:iq:gateway:register"; public static final String IQ_LAST = "jabber:iq:last"; public static final String IQ_REGISTER = "jabber:iq:register"; public static final String IQ_REGISTERED = "jabber:iq:registered"; public static final String IQ_ROSTER = "jabber:iq:roster"; public static final String IQ_VERSION = "jabber:iq:version"; public static final String CHATSTATES = "http://jabber.org/protocol/chatstates"; public static final String XEVENT = "jabber:x:event"; public static final String XDATA = "jabber:x:data"; public static final String MUC = "http://jabber.org/protocol/muc"; public static final String MUC_USER = MUC + "#user"; public static final String MUC_ADMIN = MUC + "#admin"; public static final String SPARKNS = "http: public static final String DELAY = "urn:xmpp:delay"; public static final String OFFLINE = "http://jabber.org/protocol/offline"; public static final String X_DELAY = "jabber:x:delay"; public static final String VCARD_TEMP = "vcard-temp"; public static final String VCARD_TEMP_X_UPDATE = "vcard-temp:x:update"; public static final String ATTENTIONNS = "urn:xmpp:attention:0"; } public boolean registerAccount (Imps.ProviderSettings.QueryMap providerSettings, String username, String password, Map<String,String> params) throws Exception { initConnection(providerSettings, username); if (mConnection.getAccountManager().supportsAccountCreation()) { mConnection.getAccountManager().createAccount(username, password, params); return true; } else { return false;//not supported } } private Contact handlePresenceChanged(org.jivesoftware.smack.packet.Presence presence) { if (presence == null) return null; XmppAddress xaddress = new XmppAddress(presence.getFrom()); if (mUser.getAddress().getBareAddress().equals(xaddress.getBareAddress())) //ignore presence from yourself return null; String status = presence.getStatus(); Presence p = new Presence(parsePresence(presence), status, null, null, Presence.CLIENT_TYPE_DEFAULT); // Get presence from the Roster to handle priorities and such // TODO: this causes bad network and performance issues // if (presence.getType() == Type.available) //get the latest presence for the highest priority Contact contact = mContactListManager.getContact(xaddress.getBareAddress()); String[] presenceParts = presence.getFrom().split("/"); if (presenceParts.length > 1) p.setResource(presenceParts[1]); if (contact == null && presence.getType() == Type.subscribe) { XmppAddress xAddr = new XmppAddress(presence.getFrom()); RosterEntry rEntry = mRoster.getEntry(xAddr.getBareAddress()); String name = null; if (rEntry != null) name = rEntry.getName(); if (name == null || name.length() == 0) name = xAddr.getUser(); contact = new Contact(xAddr,name); try { if (!mContactListManager.getDefaultContactList().containsContact(contact.getAddress())) { mContactListManager.getDefaultContactList().addExistingContact(contact); } } catch (ImException e) { debug(TAG,"unable to add new contact to default list: " + e.getLocalizedMessage()); } } else if (contact == null) { return null; //do nothing if we don't have a contact } if (presence.getType() == Type.subscribe) { debug(TAG,"got subscribe request: " + presence.getFrom()); try { mContactListManager.getSubscriptionRequestListener().onSubScriptionRequest(contact, mProviderId, mAccountId); } catch (RemoteException e) { Log.e(TAG,"remote exception on subscription handling",e); } } else if (presence.getType() == Type.subscribed) { debug(TAG,"got subscribed confirmation request: " + presence.getFrom()); try { mContactListManager.getSubscriptionRequestListener().onSubscriptionApproved(contact, mProviderId, mAccountId); } catch (RemoteException e) { Log.e(TAG,"remote exception on subscription handling",e); } } else if (presence.getType() == Type.unsubscribe) { debug(TAG,"got unsubscribe request: " + presence.getFrom()); //TBD how to handle this // mContactListManager.getSubscriptionRequestListener().onUnSubScriptionRequest(contact); } else if (presence.getType() == Type.unsubscribed) { debug(TAG,"got unsubscribe request: " + presence.getFrom()); try { mContactListManager.getSubscriptionRequestListener().onSubscriptionDeclined(contact, mProviderId, mAccountId); } catch (RemoteException e) { Log.e(TAG,"remote exception on subscription handling",e); } } else { //this is typical presence, let's get the latest/highest priority contact.setPresence(p); /* presence = mRoster.getPresence(contact.getAddress().getBareAddress()); p = new Presence(parsePresence(presence), status, null, null, Presence.CLIENT_TYPE_DEFAULT); presenceParts = presence.getFrom().split("/"); if (presenceParts.length > 1) p.setResource(presenceParts[1]); */ } return contact; } private void initPresenceProcessor () { mTimerPresence = new Timer(); mTimerPresence.scheduleAtFixedRate(new TimerTask() { public void run() { if (qPresence.size() > 0) { ArrayList<Contact> alUpdate = new ArrayList<Contact>(); org.jivesoftware.smack.packet.Presence p = null; Contact contact = null; try { while (qPresence.peek() != null) { p = qPresence.pop(); contact = handlePresenceChanged(p); if (contact != null) alUpdate.add(contact); } } catch (NoSuchElementException e) { Log.e(ImApp.LOG_TAG,"wtf is this?",e); } Log.d(ImApp.LOG_TAG,"XMPP processed presence q=" + alUpdate.size()); mContactListManager.notifyContactsPresenceUpdated(alUpdate.toArray(new Contact[alUpdate.size()])); loadVCardsAsync(); } } }, 1000, 5000); } Timer mTimerPackets = null; private void initPacketProcessor () { mTimerPackets = new Timer(); mTimerPackets.scheduleAtFixedRate(new TimerTask() { public void run() { try { org.jivesoftware.smack.packet.Packet packet = null; if (qPacket.size() > 0) while ((packet = qPacket.poll())!=null) { if (mConnection == null) { debug(TAG, "postponed packet to " + packet.getTo() + " because we are not connected"); postpone(packet); return; } try { mConnection.sendPacket(packet); } catch (IllegalStateException ex) { postpone(packet); debug(TAG, "postponed packet to " + packet.getTo() + " because socket is disconnected"); } } } catch (Exception e) { Log.e(ImApp.LOG_TAG,"error processing presence",e); } } }, 500, 1000); } }
package thredds.client.catalog; import org.jdom2.Namespace; import thredds.client.catalog.builder.AccessBuilder; import thredds.client.catalog.builder.CatalogBuilder; import thredds.client.catalog.builder.CatalogRefBuilder; import thredds.client.catalog.builder.DatasetBuilder; import ucar.nc2.time.CalendarDate; import ucar.nc2.util.URLnaming; import javax.annotation.concurrent.Immutable; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * A Client Catalog * * @author caron * @since 1/7/2015 */ @Immutable public class Catalog extends DatasetNode { static public final String CATALOG_NAMESPACE_10 = "http: static public final Namespace defNS = Namespace.getNamespace(CATALOG_NAMESPACE_10); static public final String NJ22_NAMESPACE = "http: static public final Namespace ncmlNS = Namespace.getNamespace("ncml", NJ22_NAMESPACE); static public final String XLINK_NAMESPACE = "http: static public final Namespace xlinkNS = Namespace.getNamespace("xlink", XLINK_NAMESPACE); static public final Namespace xsiNS = Namespace.getNamespace("xsi", "http: // all of these are catalog only // public static final String CatalogScan = "CatalogScan"; // List<CatalogScan> public static final String DatasetHash = "DatasetHash"; // Map<String,Dataset> public static final String DatasetRoots = "DatasetRoots"; // List<DatasetRootConfig> public static final String Expires = "Expires"; // CalendarDate public static final String Services = "Services"; // List<Service> (LOOK what about using Map ?) public static final String Version = "Version"; // String private final URI baseURI; // LOOK its possible we never want to use this. perhaps "location" instead ?? public Catalog(URI baseURI, String name, Map<String, Object> flds, List<DatasetBuilder> datasets) { super(null, name, flds, datasets); this.baseURI = baseURI; Map<String, Dataset> datasetMap = new HashMap<>(); addDatasetsToHash(getDatasetsLocal(), datasetMap); if (!datasetMap.isEmpty()) flds.put(Catalog.DatasetHash, datasetMap); } private void addDatasetsToHash(List<Dataset> datasets, Map<String, Dataset> datasetMap) { if (datasets == null) return; for (Dataset ds : datasets) { String id = ds.getIdOrPath(); if (id != null) datasetMap.put(id, ds); if (ds instanceof CatalogRef) continue; // dont recurse into catrefs addDatasetsToHash(ds.getDatasetsLocal(), datasetMap); } } public URI getBaseURI() { return baseURI; } public CalendarDate getExpires() { return (CalendarDate) flds.get(Catalog.Expires); } public String getVersion() { return (String) flds.get(Catalog.Version); } public List<Service> getServices() { List<Service> services = (List<Service>) flds.get(Catalog.Services); return services == null ? new ArrayList<>(0) : services; } public boolean hasService(String name) { for (Service s : getServices()) if (s.getName().equalsIgnoreCase(name)) return true; return false; } public Service findService(String serviceName) { if (serviceName == null) return null; List<Service> services = (List<Service>) flds.get(Catalog.Services); return findService(services, serviceName); } public Service findService(ServiceType type) { if (type == null) return null; List<Service> services = (List<Service>) flds.get(Catalog.Services); return findService(services, type); } private Service findService(List<Service> services, String want) { if (services == null) return null; for (Service s : services) { if (s.getName().equals(want)) return s; } for (Service s : services) { Service result = findService(s.getNestedServices(), want); if (result != null) return result; } return null; } private Service findService(List<Service> services, ServiceType type) { if (services == null) return null; for (Service s : services) { if (s.getType() == type) return s; } for (Service s : services) { Service result = findService(s.getNestedServices(), type); if (result != null) return result; } return null; } public List<Property> getProperties() { List<Property> properties = (List<Property>) flds.get(Dataset.Properties); return properties == null ? new ArrayList<>(0) : properties; } public Dataset findDatasetByID( String id) { Map<String, Dataset> datasetMap = (Map<String, Dataset>) flds.get(Catalog.DatasetHash); return datasetMap == null ? null : datasetMap.get(id); } // get all datasets contained directly in this catalog public Iterable<Dataset> getAllDatasets() { List<Dataset> all = new ArrayList<>(); addAll(this, all); return all; } private void addAll(DatasetNode node, List<Dataset> all) { all.addAll(node.getDatasetsLocal()); for (DatasetNode nested : node.getDatasetsLocal()) addAll(nested, all); } /** * Resolve reletive URIs, using the catalog's base URI. If the uriString is not reletive, then * no resolution is done. This also allows baseURI to be a file: scheme. * * @param uriString any url, reletive or absolute * @return resolved url string, or null on error * @throws java.net.URISyntaxException if uriString violates RFC 2396 * @see java.net.URI#resolve */ public URI resolveUri(String uriString) throws URISyntaxException { if (baseURI == null) return new URI(uriString); String resolved = URLnaming.resolve(baseURI.toString(), uriString); return new URI(resolved); } // look is this different than URLnaming ?? public static URI resolveUri(URI baseURI, String uriString) throws URISyntaxException { URI want = new URI(uriString); if ((baseURI == null) || want.isAbsolute()) return want; // gotta deal with file ourself String scheme = baseURI.getScheme(); if ((scheme != null) && scheme.equals("file")) { String baseString = baseURI.toString(); if ((uriString.length() > 0) && (uriString.charAt(0) == ' return new URI(baseString + uriString); int pos = baseString.lastIndexOf('/'); if (pos > 0) { String r = baseString.substring(0, pos + 1) + uriString; return new URI(r); } } //otherwise let the URI class resolve it return baseURI.resolve(want); } public String getUriString() { URI baseURI = getBaseURI(); return baseURI == null ? null : baseURI.toString(); } // from DeepCopyUtils, for subsetting public Catalog subsetCatalogOnDataset( Dataset dataset) { if ( dataset == null ) throw new IllegalArgumentException( "Dataset may not be null." ); if ( dataset.getParentCatalog() != this ) throw new IllegalArgumentException( "Catalog must contain the dataset." ); CatalogBuilder builder = new CatalogBuilder(); URI docBaseUri = formDocBaseUriForSubsetCatalog( dataset ); builder.setBaseURI(docBaseUri); builder.setName( dataset.getName()); List<Service> neededServices = new ArrayList<>(); DatasetBuilder topDs = copyDataset( null, dataset, neededServices, true ); // LOOK, cant set catalog as datasetNode parent for (Service s : neededServices) builder.addService(s); builder.addDataset( topDs ); return builder.makeCatalog(); } private DatasetBuilder copyDataset( DatasetBuilder parent, Dataset dataset, List<Service> neededServices, boolean copyInherited ) { neededServices.add(dataset.getServiceDefault()); DatasetBuilder result; if ( dataset instanceof CatalogRef ) { CatalogRef catRef = (CatalogRef) dataset; CatalogRefBuilder catBuilder = new CatalogRefBuilder( parent); catBuilder.setHref( catRef.getXlinkHref()); catBuilder.setTitle( catRef.getName()); result = catBuilder; } else { result = new DatasetBuilder(parent); List<Access> access = dataset.getLocalFieldAsList(Dataset.Access); // dont expand for ( Access curAccess : access) { result.addAccess( copyAccess( result, curAccess, neededServices )); } List<Dataset> datasets = dataset.getLocalFieldAsList(Dataset.Datasets); // dont expand for ( Dataset currDs : datasets) { result.addDataset( copyDataset( result, currDs, neededServices, copyInherited )); } } result.setName( dataset.getName() ); result.transferMetadata(dataset, copyInherited); // make a copy of all local metadata return result; } private AccessBuilder copyAccess( DatasetBuilder parent, Access access, List<Service> neededServices ) { neededServices.add(access.getService()); // LOOK may get dups return new AccessBuilder( parent, access.getUrlPath(), access.getService(), access.getDataFormatName(), access.getDataSize() ); } private URI formDocBaseUriForSubsetCatalog( Dataset dataset ) { String catDocBaseUri = getUriString(); String subsetDocBaseUriString = catDocBaseUri + "/" + ( dataset.getID() != null ? dataset.getID() : dataset.getName() ); try { return new URI( subsetDocBaseUriString); } catch ( URISyntaxException e ) { // This shouldn't happen. But just in case ... throw new IllegalStateException( "Bad document Base URI for new catalog [" + catDocBaseUri + "/" + (dataset.getID() != null ? dataset.getID() : dataset.getName()) + "].", e ); } } }
package com.liveramp.kafka_service.consumer.utils; import java.util.List; import java.util.Map; import com.clearspring.analytics.stream.cardinality.HyperLogLogPlus; import com.google.common.collect.Lists; import kafka.utils.Json; import org.json.JSONException; import org.json.JSONObject; import com.liveramp.commons.collections.nested_map.TwoKeyTuple; import com.liveramp.commons.collections.nested_map.TwoNestedMap; public class StatsSummer { final static int HLL_PRECISION = 14; private final TwoNestedMap<String, Long, Long> totalCountMap = new TwoNestedMap<String, Long, Long>(); private final TwoNestedMap<String, Long, Double> valueMap = new TwoNestedMap<String, Long, Double>(); private final TwoNestedMap<String, Long, HyperLogLogPlus> uniqueClickCountMap = new TwoNestedMap<String, Long, HyperLogLogPlus>(); private final TwoNestedMap<String, String, Long> errorCountMap = new TwoNestedMap<String, String, Long>(); public void summJson(String jsonStr) throws JSONException { JSONObject json = new JSONObject(jsonStr); long jobId = json.getLong("job_id"); long ircId = json.getLong("irc_id"); int fieldId = json.getInt("field_definition_id"); double value = json.getDouble("value"); String clickUid = json.getString("click_uid"); String key1 = getCombinedKey(jobId, ircId); long key2 = (long)fieldId; if (!totalCountMap.containsKey(key1, key2)) { totalCountMap.put(key1, key2, 0L); valueMap.put(key1, key2, 0.0); uniqueClickCountMap.put(key1, key2, new HyperLogLogPlus(HLL_PRECISION)); } totalCountMap.put(key1, key2, totalCountMap.get(key1, key2) + 1); valueMap.put(key1, key2, valueMap.get(key1, key2) + value); uniqueClickCountMap.get(key1, key2).offer(clickUid.getBytes()); // count across all fields for job and irc. totalCountMap.put(key1, -1L, totalCountMap.containsKey(key1, -1L) ? totalCountMap.get(key1, -1L) + 1 : 1L); if (json.has("status")) { try { int categoryEnumId = json.getInt("category_enum_id"); String k2 = getCombinedKey(fieldId, categoryEnumId); if (!errorCountMap.containsKey(key1, k2)) { errorCountMap.put(key1, k2, 0L); } errorCountMap.put(key1, k2, errorCountMap.get(key1, k2) + 1); } catch (JSONException e) { throw new RuntimeException("Status and category enum id are inconsistent in the log"); } } } public static String getCombinedKey(long jobId, long ircId) { return jobId + "-" + ircId; } public TwoKeyTuple<Long, Long> separateTwoKeys(String str) { String[] keys = str.split("-"); return new TwoKeyTuple<Long, Long>(Long.parseLong(keys[0]), Long.parseLong(keys[1])); } public List<String> getStatsJsonStrings() { List<String> statJsonStrings = Lists.newArrayList(); for (TwoKeyTuple<String, Long> keys : totalCountMap.key12Set()) { TwoKeyTuple<Long, Long> twoKey = separateTwoKeys(keys.getK1()); statJsonStrings.add(JsonFactory.createTotalCountEntry(twoKey.getK1(), twoKey.getK2(), keys.getK2(), totalCountMap.get(keys))); } for (TwoKeyTuple<String, Long> keys : valueMap.key12Set()) { TwoKeyTuple<Long, Long> twoKey = separateTwoKeys(keys.getK1()); statJsonStrings.add(JsonFactory.createTransactionValueEntry(twoKey.getK1(), twoKey.getK2(), keys.getK2(), valueMap.get(keys))); } for (TwoKeyTuple<String, Long> keys : uniqueClickCountMap.key12Set()) { TwoKeyTuple<Long, Long> twoKey = separateTwoKeys(keys.getK1()); statJsonStrings.add(JsonFactory.createUniqClickCountEntry(twoKey.getK1(), twoKey.getK2(), keys.getK2(), uniqueClickCountMap.get(keys).cardinality())); } for (TwoKeyTuple<String, String> keys : errorCountMap.key12Set()) { TwoKeyTuple<Long, Long> twoKey1 = separateTwoKeys(keys.getK1()); TwoKeyTuple<Long, Long> twoKey2 = separateTwoKeys(keys.getK2()); statJsonStrings.add(JsonFactory.createErrorCountEntry(twoKey1.getK1(), twoKey1.getK2(), twoKey2.getK1(), twoKey2.getK2(), errorCountMap.get(keys))); } return statJsonStrings; } public void summStatJson(JsonFactory.StatsType type, String statsJsonString) throws JSONException { JSONObject json = new JSONObject(statsJsonString); switch (type) { case TOTAL_COUNT: long count = totalCountMap .get(getCombinedKey(json.getLong(JsonFactory.JOB_ID), json.getLong(JsonFactory.IRC_ID)), json.getLong(JsonFactory.FIELD_ID)); totalCountMap.put(getCombinedKey(json.getLong(JsonFactory.JOB_ID), json.getLong(JsonFactory.IRC_ID)), json.getLong(JsonFactory.FIELD_ID), count + json.getLong(JsonFactory.COUNT)); case TRANSACTION_VALUE: double value = valueMap .get(getCombinedKey(json.getLong(JsonFactory.JOB_ID), json.getLong(JsonFactory.IRC_ID)), json.getLong(JsonFactory.FIELD_ID)); valueMap .put(getCombinedKey(json.getLong(JsonFactory.JOB_ID), json.getLong(JsonFactory.IRC_ID)), json.getLong(JsonFactory.FIELD_ID), value + json.getDouble(JsonFactory.COUNT)); case ERROR_COUNT: long count1 = errorCountMap .get(getCombinedKey(json.getLong(JsonFactory.JOB_ID), json.getLong(JsonFactory.IRC_ID)), getCombinedKey(json.getLong(JsonFactory.FIELD_ID), json.getLong(JsonFactory.CATEGORY_ENUM_ID))); errorCountMap .put(getCombinedKey(json.getLong(JsonFactory.JOB_ID), json.getLong(JsonFactory.IRC_ID)), getCombinedKey(json.getLong(JsonFactory.FIELD_ID), json.getLong(JsonFactory.CATEGORY_ENUM_ID)), count1 + json.getLong(JsonFactory.COUNT)); default: break; } } public void clear() { totalCountMap.clear(); valueMap.clear(); uniqueClickCountMap.clear(); errorCountMap.clear(); } public long getTotalCount(long jobId, long ircId, long fieldId) { Long count = totalCountMap.get(getCombinedKey(jobId, ircId), fieldId); return count == null ? 0 : count; } public long getErrorCount(long jobId, long ircId, long fieldId) { Map<String, Long> subMap = errorCountMap.get(getCombinedKey(jobId, ircId)); long count = 0; for (String combinedKey : subMap.keySet()) { TwoKeyTuple<Long, Long> key2 = separateTwoKeys(combinedKey); if (key2.getK1() == fieldId) { count += subMap.get(combinedKey); } } return count; } }
// Narya library - tools for developing networked games // This library is free software; you can redistribute it and/or modify it // (at your option) any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.cast.bundle; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import com.samskivert.util.HashIntMap; import com.samskivert.util.IntIntMap; import com.samskivert.util.Tuple; import org.apache.commons.collections.iterators.FilterIterator; import org.apache.commons.collections.Predicate; import com.threerings.resource.ResourceBundle; import com.threerings.resource.ResourceManager; import com.threerings.media.image.Colorization; import com.threerings.media.image.FastImageIO; import com.threerings.media.image.ImageDataProvider; import com.threerings.media.image.ImageManager; import com.threerings.media.tile.IMImageProvider; import com.threerings.media.tile.Tile; import com.threerings.media.tile.TileSet; import com.threerings.media.tile.TrimmedTile; import com.threerings.util.DirectionCodes; import com.threerings.cast.ActionFrames; import com.threerings.cast.ActionSequence; import com.threerings.cast.CharacterComponent; import com.threerings.cast.ComponentClass; import com.threerings.cast.ComponentRepository; import com.threerings.cast.FrameProvider; import com.threerings.cast.Log; import com.threerings.cast.NoSuchComponentException; import com.threerings.cast.StandardActions; import com.threerings.cast.TrimmedMultiFrameImage; /** * A component repository implementation that obtains information from * resource bundles. * * @see ResourceManager */ public class BundledComponentRepository implements DirectionCodes, ComponentRepository { /** * Constructs a repository which will obtain its resource set from the * supplied resource manager. * * @param rmgr the resource manager from which to obtain our resource * set. * @param imgr the image manager that we'll use to decode and cache * images. * @param name the name of the resource set from which we will be * loading our component data. * * @exception IOException thrown if an I/O error occurs while reading * our metadata from the resource bundles. */ public BundledComponentRepository ( ResourceManager rmgr, ImageManager imgr, String name) throws IOException { // keep this guy around _imgr = imgr; // first we obtain the resource set from whence will come our // bundles ResourceBundle[] rbundles = rmgr.getResourceSet(name); // look for our metadata info in each of the bundles try { int rcount = (rbundles == null) ? 0 : rbundles.length; for (int i = 0; i < rcount; i++) { if (_actions == null) { _actions = (HashMap)BundleUtil.loadObject( rbundles[i], BundleUtil.ACTIONS_PATH, true); } if (_actionSets == null) { _actionSets = (HashMap)BundleUtil.loadObject( rbundles[i], BundleUtil.ACTION_SETS_PATH, true); } if (_classes == null) { _classes = (HashMap)BundleUtil.loadObject( rbundles[i], BundleUtil.CLASSES_PATH, true); } } // now go back and load up all of the component information for (int i = 0; i < rcount; i++) { HashIntMap comps = null; comps = (HashIntMap)BundleUtil.loadObject( rbundles[i], BundleUtil.COMPONENTS_PATH, true); if (comps == null) { continue; } // create a frame provider for this bundle FrameProvider fprov = new ResourceBundleProvider(_imgr, rbundles[i]); // now create character component instances for each component // in the serialized table Iterator iter = comps.keySet().iterator(); while (iter.hasNext()) { int componentId = ((Integer)iter.next()).intValue(); Tuple info = (Tuple)comps.get(componentId); createComponent(componentId, (String)info.left, (String)info.right, fprov); } } } catch (ClassNotFoundException cnfe) { throw (IOException) new IOException( "Internal error unserializing metadata").initCause(cnfe); } // if we failed to load our classes or actions, create empty // hashtables so that we can safely enumerate our emptiness if (_actions == null) { _actions = new HashMap(); } if (_classes == null) { _classes = new HashMap(); } } /** * Configures the bundled component repository to wipe any bundles * that report certain kinds of failure. In the event that an unpacked * bundle becomes corrupt, this is useful in that it will force the * bundle to be unpacked on the next application invocation, * potentially remedying the problem of a corrupt unpacking. */ public void setWipeOnFailure (boolean wipeOnFailure) { _wipeOnFailure = true; } // documentation inherited public CharacterComponent getComponent (int componentId) throws NoSuchComponentException { CharacterComponent component = (CharacterComponent) _components.get(componentId); if (component == null) { throw new NoSuchComponentException(componentId); } return component; } // documentation inherited public CharacterComponent getComponent (String className, String compName) throws NoSuchComponentException { // look up the list for that class ArrayList comps = (ArrayList)_classComps.get(className); if (comps != null) { // scan the list for the named component int ccount = comps.size(); for (int i = 0; i < ccount; i++) { CharacterComponent comp = (CharacterComponent)comps.get(i); if (comp.name.equals(compName)) { return comp; } } } throw new NoSuchComponentException(className, compName); } // documentation inherited public ComponentClass getComponentClass (String className) { return (ComponentClass)_classes.get(className); } // documentation inherited public Iterator enumerateComponentClasses () { return _classes.values().iterator(); } // documentation inherited public Iterator enumerateActionSequences () { return _actions.values().iterator(); } // documentation inherited public Iterator enumerateComponentIds (final ComponentClass compClass) { Predicate classP = new Predicate() { public boolean evaluate (Object input) { CharacterComponent comp = (CharacterComponent) _components.get(input); return comp.componentClass.equals(compClass); } }; return new FilterIterator(_components.keySet().iterator(), classP); } /** * Creates a component and inserts it into the component table. */ protected void createComponent ( int componentId, String cclass, String cname, FrameProvider fprov) { // look up the component class information ComponentClass clazz = (ComponentClass)_classes.get(cclass); if (clazz == null) { Log.warning("Non-existent component class " + "[class=" + cclass + ", name=" + cname + ", id=" + componentId + "]."); return; } // create the component CharacterComponent component = new CharacterComponent( componentId, cname, clazz, fprov); // stick it into the appropriate tables _components.put(componentId, component); // we have a hash of lists for mapping components by class/name ArrayList comps = (ArrayList)_classComps.get(cclass); if (comps == null) { comps = new ArrayList(); _classComps.put(cclass, comps); } if (!comps.contains(component)) { comps.add(component); } else { Log.info("Requested to register the same component twice? " + "[component=" + component + "]."); } } /** * Instances of these provide images to our component action tilesets * and frames to our components. */ protected class ResourceBundleProvider extends IMImageProvider implements ImageDataProvider, FrameProvider { /** * Constructs an instance that will obtain image data from the * specified resource bundle. */ public ResourceBundleProvider (ImageManager imgr, ResourceBundle bundle) { super(imgr, (String)null); _dprov = this; _bundle = bundle; } // documentation inherited from interface public String getIdent () { return "bcr:" + _bundle.getSource(); } // documentation inherited from interface public BufferedImage loadImage (String path) throws IOException { return FastImageIO.read(_bundle.getResourceFile(path)); } // documentation inherited public ActionFrames getFrames ( CharacterComponent component, String action, String type) { // obtain the action sequence definition for this action ActionSequence actseq = (ActionSequence)_actions.get(action); if (actseq == null) { Log.warning("Missing action sequence definition " + "[action=" + action + ", component=" + component + "]."); return null; } // determine our image path name String imgpath = action, dimgpath = ActionSequence.DEFAULT_SEQUENCE; if (type != null) { imgpath += "_" + type; dimgpath += "_" + type; } String root = component.componentClass.name + "/" + component.name + "/"; String cpath = root + imgpath + BundleUtil.TILESET_EXTENSION; String dpath = root + dimgpath + BundleUtil.TILESET_EXTENSION; // look to see if this tileset is already cached (as the // custom action or the default action) TileSet aset = (TileSet)_setcache.get(cpath); if (aset == null) { aset = (TileSet)_setcache.get(dpath); if (aset != null) { // save ourselves a lookup next time _setcache.put(cpath, aset); } } try { // then try loading up a tileset customized for this action if (aset == null) { aset = (TileSet)BundleUtil.loadObject( _bundle, cpath, false); } // if that failed, try loading the default tileset if (aset == null) { aset = (TileSet)BundleUtil.loadObject( _bundle, dpath, false); _setcache.put(dpath, aset); } // if this is a shadow image, no need to freak out as they are // optional if (StandardActions.SHADOW_TYPE.equals(type)) { return null; } // if that failed too, we're hosed if (aset == null) { Log.warning("Unable to locate tileset for action '" + imgpath + "' " + component + "."); if (_wipeOnFailure) { _bundle.wipeBundle(false); } return null; } aset.setImageProvider(this); _setcache.put(cpath, aset); return new TileSetFrameImage(aset, actseq); } catch (Exception e) { Log.warning("Error loading tileset for action '" + imgpath + "' " + component + "."); Log.logStackTrace(e); return null; } } /** The resource bundle from which we obtain image data. */ protected ResourceBundle _bundle; /** Cache of tilesets loaded from our bundle. */ protected HashMap _setcache = new HashMap(); } /** * Used to provide multiframe images using data obtained from a * tileset. */ protected static class TileSetFrameImage implements ActionFrames { /** * Constructs a tileset frame image with the specified tileset and * for the specified orientation. */ public TileSetFrameImage (TileSet set, ActionSequence actseq) { _set = set; _actseq = actseq; // compute these now to avoid pointless recomputation later _ocount = actseq.orients.length; _fcount = set.getTileCount() / _ocount; // create our mapping from orientation to animation sequence // index for (int ii = 0; ii < _ocount; ii++) { _orients.put(actseq.orients[ii], ii); } } // documentation inherited from interface public int getOrientationCount () { return _ocount; } // documentation inherited from interface public TrimmedMultiFrameImage getFrames (final int orient) { return new TrimmedMultiFrameImage() { // documentation inherited public int getFrameCount () { return _fcount; } // documentation inherited from interface public int getWidth (int index) { Tile tile = getTile(orient, index); return (tile == null) ? 0 : tile.getWidth(); } // documentation inherited from interface public int getHeight (int index) { Tile tile = getTile(orient, index); return (tile == null) ? 0 : tile.getHeight(); } // documentation inherited from interface public void paintFrame (Graphics2D g, int index, int x, int y) { Tile tile = getTile(orient, index); if (tile != null) { tile.paint(g, x, y); } } // documentation inherited from interface public boolean hitTest (int index, int x, int y) { Tile tile = getTile(orient, index); return (tile != null) ? tile.hitTest(x, y) : false; } // documentation inherited from interface public void getTrimmedBounds (int index, Rectangle bounds) { Tile tile = getTile(orient, index); if (tile instanceof TrimmedTile) { ((TrimmedTile)tile).getTrimmedBounds(bounds); } else { bounds.setBounds( 0, 0, tile.getWidth(), tile.getHeight()); } } }; } // documentation inherited from interface public int getXOrigin (int orient, int index) { return _actseq.origin.x; } // documentation inherited from interface public int getYOrigin (int orient, int index) { return _actseq.origin.y; } // documentation inherited from interface public ActionFrames cloneColorized (Colorization[] zations) { return new TileSetFrameImage(_set.clone(zations), _actseq); } /** * Fetches the requested tile. */ protected Tile getTile (int orient, int index) { int tileIndex = _orients.get(orient) * _fcount + index; return _set.getTile(tileIndex); } /** The tileset from which we obtain our frame images. */ protected TileSet _set; /** The action sequence for which we're providing frame images. */ protected ActionSequence _actseq; /** Frame and orientation counts. */ protected int _fcount, _ocount; /** A mapping from orientation code to animation sequence * index. */ protected IntIntMap _orients = new IntIntMap(); } /** We use the image manager to decode and cache images. */ protected ImageManager _imgr; /** A table of action sequences. */ protected HashMap _actions; /** A table of action sequence tilesets. */ protected HashMap _actionSets; /** A table of component classes. */ protected HashMap _classes; /** A table of component lists indexed on classname. */ protected HashMap _classComps = new HashMap(); /** The component table. */ protected HashIntMap _components = new HashIntMap(); /** Whether or not we wipe our bundles on any failure. */ protected boolean _wipeOnFailure; }
// Nenya library - tools for developing networked games // This library is free software; you can redistribute it and/or modify it // (at your option) any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.cast.bundle; import java.util.ArrayList; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.io.IOException; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.image.BufferedImage; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.collect.Iterators; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.samskivert.util.IntIntMap; import com.samskivert.util.IntMap; import com.samskivert.util.IntMaps; import com.samskivert.util.Tuple; import com.threerings.util.DirectionCodes; import com.threerings.resource.FileResourceBundle; import com.threerings.resource.ResourceBundle; import com.threerings.resource.ResourceManager; import com.threerings.media.image.BufferedMirage; import com.threerings.media.image.Colorization; import com.threerings.media.image.ImageDataProvider; import com.threerings.media.image.ImageManager; import com.threerings.media.image.Mirage; import com.threerings.media.tile.IMImageProvider; import com.threerings.media.tile.Tile; import com.threerings.media.tile.TileSet; import com.threerings.media.tile.TrimmedTile; import com.threerings.cast.ActionFrames; import com.threerings.cast.ActionSequence; import com.threerings.cast.CharacterComponent; import com.threerings.cast.ComponentClass; import com.threerings.cast.ComponentRepository; import com.threerings.cast.FrameProvider; import com.threerings.cast.NoSuchComponentException; import com.threerings.cast.StandardActions; import com.threerings.cast.TrimmedMultiFrameImage; import static com.threerings.cast.Log.log; /** * A component repository implementation that obtains information from resource bundles. * * @see ResourceManager */ public class BundledComponentRepository implements DirectionCodes, ComponentRepository { /** * Constructs a repository which will obtain its resource set from the supplied resource * manager. * * @param rmgr the resource manager from which to obtain our resource set. * @param imgr the image manager that we'll use to decode and cache images. * @param name the name of the resource set from which we will be loading our component data. * * @exception IOException thrown if an I/O error occurs while reading our metadata from the * resource bundles. */ public BundledComponentRepository ( ResourceManager rmgr, ImageManager imgr, String name) throws IOException { // keep this guy around _imgr = imgr; // first we obtain the resource set from whence will come our bundles ResourceBundle[] rbundles = rmgr.getResourceSet(name); if (rbundles == null) { // Couldn't find a bundle with that name, so just make empty maps for safe enumerating _actions = Maps.newHashMap(); _classes = Maps.newHashMap(); return; } // look for our metadata info in each of the bundles try { for (ResourceBundle rbundle : rbundles) { if (_actions == null) { @SuppressWarnings("unchecked") Map<String, ActionSequence> amap = (Map<String, ActionSequence>)BundleUtil.loadObject( rbundle, BundleUtil.ACTIONS_PATH, true); _actions = amap; } if (_actionSets == null) { @SuppressWarnings("unchecked") Map<String, TileSet> asets = (Map<String, TileSet>)BundleUtil.loadObject( rbundle, BundleUtil.ACTION_SETS_PATH, true); _actionSets = asets; } if (_classes == null) { @SuppressWarnings("unchecked") Map<String, ComponentClass> cmap = (Map<String, ComponentClass>)BundleUtil.loadObject( rbundle, BundleUtil.CLASSES_PATH, true); _classes = cmap; } } // now go back and load up all of the component information for (ResourceBundle rbundle : rbundles) { @SuppressWarnings("unchecked") IntMap<Tuple<String, String>> comps = (IntMap<Tuple<String, String>>)BundleUtil.loadObject( rbundle, BundleUtil.COMPONENTS_PATH, true); if (comps == null) { continue; } // create a frame provider for this bundle FrameProvider fprov = new ResourceBundleProvider(_imgr, rbundle); // now create char. component instances for each component in the serialized table Iterator<Integer> iter = comps.keySet().iterator(); while (iter.hasNext()) { int componentId = iter.next().intValue(); Tuple<String, String> info = comps.get(componentId); createComponent(componentId, info.left, info.right, fprov); } } } catch (ClassNotFoundException cnfe) { throw (IOException) new IOException( "Internal error unserializing metadata").initCause(cnfe); } // if we failed to load our classes or actions, create empty hashtables so that we can // safely enumerate our emptiness if (_actions == null) { _actions = Maps.newHashMap(); } if (_classes == null) { _classes = Maps.newHashMap(); } } /** * Configures the bundled component repository to wipe any bundles that report certain kinds of * failure. In the event that an unpacked bundle becomes corrupt, this is useful in that it * will force the bundle to be unpacked on the next application invocation, potentially * remedying the problem of a corrupt unpacking. */ public void setWipeOnFailure (boolean wipeOnFailure) { _wipeOnFailure = true; } // documentation inherited public CharacterComponent getComponent (int componentId) throws NoSuchComponentException { CharacterComponent component = _components.get(componentId); if (component == null) { throw new NoSuchComponentException(componentId); } return component; } // documentation inherited public CharacterComponent getComponent (String className, String compName) throws NoSuchComponentException { // look up the list for that class ArrayList<CharacterComponent> comps = _classComps.get(className); if (comps != null) { // scan the list for the named component int ccount = comps.size(); for (int i = 0; i < ccount; i++) { CharacterComponent comp = comps.get(i); if (comp.name.equals(compName)) { return comp; } } } throw new NoSuchComponentException(className, compName); } // documentation inherited public ComponentClass getComponentClass (String className) { return _classes.get(className); } // documentation inherited public Iterator<ComponentClass> enumerateComponentClasses () { return _classes.values().iterator(); } // documentation inherited public Iterator<ActionSequence> enumerateActionSequences () { return _actions.values().iterator(); } // documentation inherited public Iterator<Integer> enumerateComponentIds (final ComponentClass compClass) { Predicate<Map.Entry<Integer,CharacterComponent>> pred = new Predicate<Map.Entry<Integer,CharacterComponent>>() { public boolean apply (Map.Entry<Integer,CharacterComponent> entry) { return entry.getValue().componentClass.equals(compClass); } }; Function<Map.Entry<Integer,CharacterComponent>,Integer> func = new Function<Map.Entry<Integer,CharacterComponent>,Integer>() { public Integer apply (Map.Entry<Integer,CharacterComponent> entry) { return entry.getKey(); } }; return Iterators.transform(Iterators.filter(_components.entrySet().iterator(), pred), func); } /** * Creates a component and inserts it into the component table. */ protected void createComponent ( int componentId, String cclass, String cname, FrameProvider fprov) { // look up the component class information ComponentClass clazz = _classes.get(cclass); if (clazz == null) { log.warning("Non-existent component class", "class", cclass, "name", cname, "id", componentId); return; } // create the component CharacterComponent component = new CharacterComponent(componentId, cname, clazz, fprov); // stick it into the appropriate tables _components.put(componentId, component); // we have a hash of lists for mapping components by class/name ArrayList<CharacterComponent> comps = _classComps.get(cclass); if (comps == null) { comps = Lists.newArrayList(); _classComps.put(cclass, comps); } if (!comps.contains(component)) { comps.add(component); } else { log.info("Requested to register the same component twice?", "comp", component); } } /** * Instances of these provide images to our component action tilesets and frames to our * components. */ protected class ResourceBundleProvider extends IMImageProvider implements ImageDataProvider, FrameProvider { /** * Constructs an instance that will obtain image data from the specified resource bundle. */ public ResourceBundleProvider (ImageManager imgr, ResourceBundle bundle) { super(imgr, (String)null); _dprov = this; _bundle = bundle; } // from interface ImageDataProvider public String getIdent () { return "bcr:" + _bundle.getIdent(); } // from interface ImageDataProvider public BufferedImage loadImage (String path) throws IOException { return _bundle.getImageResource(path, true); } // from interface FrameProvider public ActionFrames getFrames (CharacterComponent component, String action, String type) { // obtain the action sequence definition for this action ActionSequence actseq = _actions.get(action); if (actseq == null) { log.warning("Missing action sequence definition [action=" + action + ", component=" + component + "]."); return null; } // determine our image path name String imgpath = action, dimgpath = ActionSequence.DEFAULT_SEQUENCE; if (type != null) { imgpath += "_" + type; dimgpath += "_" + type; } String root = component.componentClass.name + "/" + component.name + "/"; String cpath = root + imgpath + BundleUtil.TILESET_EXTENSION; String dpath = root + dimgpath + BundleUtil.TILESET_EXTENSION; // look to see if this tileset is already cached (as the custom action or the default // action) TileSet aset = _setcache.get(cpath); if (aset == null) { aset = _setcache.get(dpath); if (aset != null) { // save ourselves a lookup next time _setcache.put(cpath, aset); } } try { // then try loading up a tileset customized for this action if (aset == null) { aset = (TileSet)BundleUtil.loadObject(_bundle, cpath, false); } // if that failed, try loading the default tileset if (aset == null) { aset = (TileSet)BundleUtil.loadObject(_bundle, dpath, false); _setcache.put(dpath, aset); } // if that failed too, we're hosed if (aset == null) { // if this is a shadow or crop image, no need to freak out as they are optional if (!StandardActions.CROP_TYPE.equals(type) && !StandardActions.SHADOW_TYPE.equals(type)) { log.warning("Unable to locate tileset for action '" + imgpath + "' " + component + "."); if (_wipeOnFailure && _bundle instanceof FileResourceBundle) { ((FileResourceBundle)_bundle).wipeBundle(false); } } return null; } aset.setImageProvider(this); _setcache.put(cpath, aset); return new TileSetFrameImage(aset, actseq); } catch (Exception e) { log.warning("Error loading tset for action '" + imgpath + "' " + component + ".", e); return null; } } // from interface FrameProvider public String getFramePath (CharacterComponent component, String action, String type, Set<String> existentPaths) { String actionPath = makePath(component, action, type); if(!existentPaths.contains(actionPath)) { return makePath(component, ActionSequence.DEFAULT_SEQUENCE, type); } return actionPath; } protected String makePath(CharacterComponent component, String action, String type) { String imgpath = action; if (type != null) { imgpath += "_" + type; } String root = component.componentClass.name + "/" + component.name + "/"; return _bundle.getIdent() + root + imgpath + BundleUtil.IMAGE_EXTENSION; } @Override public Mirage getTileImage (String path, Rectangle bounds, Colorization[] zations) { // we don't need our images prepared for screen rendering BufferedImage src = _imgr.getImage(getImageKey(path), zations); float percentageOfDataBuffer = 1; if (bounds != null) { percentageOfDataBuffer = (bounds.height * bounds.width) / (float)(src.getHeight() * src.getWidth()); src = src.getSubimage(bounds.x, bounds.y, bounds.width, bounds.height); } return new BufferedMirage(src, percentageOfDataBuffer); } /** The resource bundle from which we obtain image data. */ protected ResourceBundle _bundle; /** Cache of tilesets loaded from our bundle. */ protected Map<String, TileSet> _setcache = Maps.newHashMap(); } /** * Used to provide multiframe images using data obtained from a tileset. */ public static class TileSetFrameImage implements ActionFrames { /** * Constructs a tileset frame image with the specified tileset and for the specified * orientation. */ public TileSetFrameImage (TileSet set, ActionSequence actseq) { this(set, actseq, 0, 0); } /** * Constructs a tileset frame image with the specified tileset and for the specified * orientation, with an optional translation. */ public TileSetFrameImage (TileSet set, ActionSequence actseq, int dx, int dy) { _set = set; _actseq = actseq; _dx = dx; _dy = dy; // compute these now to avoid pointless recomputation later _ocount = actseq.orients.length; _fcount = set.getTileCount() / _ocount; // create our mapping from orientation to animation sequence index for (int ii = 0; ii < _ocount; ii++) { _orients.put(actseq.orients[ii], ii); } } // documentation inherited from interface public int getOrientationCount () { return _ocount; } // documentation inherited from interface public TrimmedMultiFrameImage getFrames (final int orient) { return new TrimmedMultiFrameImage() { public int getFrameCount () { return _fcount; } public int getWidth (int index) { return _set.getTile(getTileIndex(orient, index)).getWidth(); } public int getHeight (int index) { return _set.getTile(getTileIndex(orient, index)).getHeight(); } public void paintFrame (Graphics2D g, int index, int x, int y) { _set.getTile(getTileIndex(orient, index)).paint(g, x + _dx, y + _dy); } public boolean hitTest (int index, int x, int y) { return _set.getTile(getTileIndex(orient, index)).hitTest(x + _dx, y + _dy); } public void getTrimmedBounds (int index, Rectangle bounds) { TileSetFrameImage.this.getTrimmedBounds(orient, index, bounds); } }; } public void getTrimmedBounds (int orient, int index, Rectangle bounds) { Tile tile = getTile(orient, index); if (tile instanceof TrimmedTile) { ((TrimmedTile)tile).getTrimmedBounds(bounds); } else { bounds.setBounds(0, 0, tile.getWidth(), tile.getHeight()); } bounds.translate(_dx, _dy); } // documentation inherited from interface public int getXOrigin (int orient, int index) { return _actseq.origin.x; } // documentation inherited from interface public int getYOrigin (int orient, int index) { return _actseq.origin.y; } // documentation inherited from interface public ActionFrames cloneColorized (Colorization[] zations) { return new TileSetFrameImage(_set.clone(zations), _actseq); } // documentation inherited from interface public ActionFrames cloneTranslated (int dx, int dy) { return new TileSetFrameImage(_set, _actseq, dx, dy); } protected int getTileIndex (int orient, int index) { return _orients.get(orient) * _fcount + index; } public Tile getTile (int orient, int index) { return _set.getTile(getTileIndex(orient, index)); } public Mirage getTileMirage (int orient, int index) { return _set.getTileMirage(getTileIndex(orient, index)); } /** The tileset from which we obtain our frame images. */ protected TileSet _set; /** The action sequence for which we're providing frame images. */ protected ActionSequence _actseq; /** A translation to apply to the images. */ protected int _dx, _dy; /** Frame and orientation counts. */ protected int _fcount, _ocount; /** A mapping from orientation code to animation sequence index. */ protected IntIntMap _orients = new IntIntMap(); } /** We use the image manager to decode and cache images. */ protected ImageManager _imgr; /** A table of action sequences. */ protected Map<String, ActionSequence> _actions; /** A table of action sequence tilesets. */ protected Map<String, TileSet> _actionSets; /** A table of component classes. */ protected Map<String, ComponentClass> _classes; /** A table of component lists indexed on classname. */ protected Map<String, ArrayList<CharacterComponent>> _classComps = Maps.newHashMap(); /** The component table. */ protected IntMap<CharacterComponent> _components = IntMaps.newHashIntMap(); /** Whether or not we wipe our bundles on any failure. */ protected boolean _wipeOnFailure; }
package net.kaleidos.hibernate.usertype; import java.sql.Array; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import org.hibernate.HibernateException; import grails.util.GrailsWebUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hibernate.MappingException; import org.hibernate.usertype.ParameterizedType; import java.io.Serializable; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.*; public class IdentityEnumArrayType extends IntegerArrayType implements ParameterizedType { public static int SQLTYPE = AbstractArrayType.ENUM_INTEGER_ARRAY; private static final Log LOG = LogFactory.getLog(IdentityEnumArrayType.class); private Class<? extends Enum<?>> enumClass; public static final String ENUM_ID_ACCESSOR = "getId"; public static final String PARAM_ENUM_CLASS = "enumClass"; @Override public Class<?> returnedClass() { // This may not be 100%. // Is there anyway to return the actual enumClass as an array and not cause issues? return Enum[].class; } @Override public int[] sqlTypes() { return new int[] { SQLTYPE }; } public Object idToEnum(Object id) throws HibernateException, SQLException { try { BidiEnumMap bidiMap = new BidiEnumMap(enumClass); return bidiMap.getEnumValue(id); } catch (Exception e) { throw new HibernateException("Uh oh. Unable to create bidirectional enum map for " + enumClass + " with nested exception: " + e.toString()); } } @Override @SuppressWarnings({"rawtypes", "unchecked"}) public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws HibernateException, SQLException { Object result = super.nullSafeGet(rs, names, owner); if (result == null) { return result; } else { Integer[] results = (Integer[]) result; Object converted = java.lang.reflect.Array.newInstance(enumClass, results.length); for (int i = 0; i < results.length; i++) { java.lang.reflect.Array.set(converted, i, idToEnum(results[i])); } return converted; } } @Override public void nullSafeSet(PreparedStatement st, Object value, int index) throws HibernateException, SQLException { Object converted = value; if (value != null) { Object[] o = (Object[])value; for (int i = 0; i < o.length; i++) { if (! (o[i] instanceof Integer)) { o[i] = ((Enum)o[i]).ordinal(); } } converted = o; } super.nullSafeSet(st, converted, index); } public void setParameterValues(Properties properties) { try { enumClass = (Class<? extends Enum<?>>)properties.get(PARAM_ENUM_CLASS); } catch (Exception e) { throw new MappingException("Error mapping Enum Class using IdentityEnumArrayType", e); } } // This code was lifted from IdentityEnumType.java (see class comments for more info) @SuppressWarnings({"rawtypes", "unchecked"}) public static class BidiEnumMap implements Serializable { private static final long serialVersionUID = 3325751131102095834L; private final Map enumToKey; private final Map keytoEnum; private Class keyType; private BidiEnumMap(Class<? extends Enum> enumClass) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { if (LOG.isDebugEnabled()) { LOG.debug(String.format("Building Bidirectional Enum Map...")); } @SuppressWarnings("hiding") EnumMap enumToKey = new EnumMap(enumClass); @SuppressWarnings("hiding") HashMap keytoEnum = new HashMap(); Method idAccessor = enumClass.getMethod(ENUM_ID_ACCESSOR); keyType = idAccessor.getReturnType(); Method valuesAccessor = enumClass.getMethod("values"); Object[] values = (Object[]) valuesAccessor.invoke(enumClass); for (Object value : values) { Object id = idAccessor.invoke(value); enumToKey.put((Enum) value, id); if (keytoEnum.containsKey(id)) { LOG.warn(String.format("Duplicate Enum ID '%s' detected for Enum %s!", id, enumClass.getName())); } keytoEnum.put(id, value); } this.enumToKey = Collections.unmodifiableMap(enumToKey); this.keytoEnum = Collections.unmodifiableMap(keytoEnum); } public Object getEnumValue(Object id) { return keytoEnum.get(id); } public Object getKey(Object enumValue) { return enumToKey.get(enumValue); } } }
package org.apache.bcel.verifier.structurals; import java.util.ArrayList; import java.util.HashMap; import java.util.Hashtable; import org.apache.bcel.generic.ATHROW; import org.apache.bcel.generic.BranchInstruction; import org.apache.bcel.generic.GotoInstruction; import org.apache.bcel.generic.Instruction; import org.apache.bcel.generic.InstructionHandle; import org.apache.bcel.generic.JsrInstruction; import org.apache.bcel.generic.MethodGen; import org.apache.bcel.generic.RET; import org.apache.bcel.generic.ReturnInstruction; import org.apache.bcel.generic.Select; import org.apache.bcel.verifier.exc.AssertionViolatedException; import org.apache.bcel.verifier.exc.StructuralCodeConstraintException; public class ControlFlowGraph{ /** * Objects of this class represent a node in a ControlFlowGraph. * These nodes are instructions, not basic blocks. */ private class InstructionContextImpl implements InstructionContext{ /** * The TAG field is here for external temporary flagging, such * as graph colouring. * * @see #getTag() * @see #setTag(int) */ private int TAG; /** * The InstructionHandle this InstructionContext is wrapped around. */ private InstructionHandle instruction; /** * The 'incoming' execution Frames. */ private HashMap inFrames; // key: the last-executed JSR /** * The 'outgoing' execution Frames. */ private HashMap outFrames; // key: the last-executed JSR /** * The 'execution predecessors' - a list of type InstructionContext * of those instances that have been execute()d before in that order. */ private ArrayList executionPredecessors = null; // Type: InstructionContext /** * Creates an InstructionHandleImpl object from an InstructionHandle. * Creation of one per InstructionHandle suffices. Don't create more. */ public InstructionContextImpl(InstructionHandle inst){ if (inst == null) throw new AssertionViolatedException("Cannot instantiate InstructionContextImpl from NULL."); instruction = inst; inFrames = new java.util.HashMap(); outFrames = new java.util.HashMap(); } /* Satisfies InstructionContext.getTag(). */ public int getTag(){ return TAG; } /* Satisfies InstructionContext.setTag(int). */ public void setTag(int tag){ TAG = tag; } /** * Returns the exception handlers of this instruction. */ public ExceptionHandler[] getExceptionHandlers(){ return exceptionhandlers.getExceptionHandlers(getInstruction()); } /** * Returns a clone of the "outgoing" frame situation with respect to the given ExecutionChain. */ public Frame getOutFrame(ArrayList execChain){ executionPredecessors = execChain; Frame org; InstructionContext jsr = lastExecutionJSR(); org = (Frame) outFrames.get(jsr); if (org == null){ throw new AssertionViolatedException("outFrame not set! This:\n"+this+"\nExecutionChain: "+getExecutionChain()+"\nOutFrames: '"+outFrames+"'."); } return org.getClone(); } /** * "Merges in" (vmspec2, page 146) the "incoming" frame situation; * executes the instructions symbolically * and therefore calculates the "outgoing" frame situation. * Returns: True iff the "incoming" frame situation changed after * merging with "inFrame". * The execPreds ArrayList must contain the InstructionContext * objects executed so far in the correct order. This is just * one execution path [out of many]. This is needed to correctly * "merge" in the special case of a RET's successor. * <B>The InstConstraintVisitor and ExecutionVisitor instances * must be set up correctly.</B> * @return true - if and only if the "outgoing" frame situation * changed from the one before execute()ing. */ public boolean execute(Frame inFrame, ArrayList execPreds, InstConstraintVisitor icv, ExecutionVisitor ev){ executionPredecessors = (ArrayList) execPreds.clone(); //sanity check if ( (lastExecutionJSR() == null) && (subroutines.subroutineOf(getInstruction()) != subroutines.getTopLevel() ) ){ throw new AssertionViolatedException("Huh?! Am I '"+this+"' part of a subroutine or not?"); } if ( (lastExecutionJSR() != null) && (subroutines.subroutineOf(getInstruction()) == subroutines.getTopLevel() ) ){ throw new AssertionViolatedException("Huh?! Am I '"+this+"' part of a subroutine or not?"); } Frame inF = (Frame) inFrames.get(lastExecutionJSR()); if (inF == null){// no incoming frame was set, so set it. inFrames.put(lastExecutionJSR(), inFrame); inF = inFrame; } else{// if there was an "old" inFrame if (inF.equals(inFrame)){ //shortcut: no need to merge equal frames. return false; } if (! mergeInFrames(inFrame)){ return false; } } // Now we're sure the inFrame has changed! // new inFrame is already merged in, see above. Frame workingFrame = inF.getClone(); try{ // This verifies the InstructionConstraint for the current // instruction, but does not modify the workingFrame object. //InstConstraintVisitor icv = InstConstraintVisitor.getInstance(VerifierFactory.getVerifier(method_gen.getClassName())); icv.setFrame(workingFrame); getInstruction().accept(icv); } catch(StructuralCodeConstraintException ce){ ce.extendMessage("","\nInstructionHandle: "+getInstruction()+"\n"); ce.extendMessage("","\nExecution Frame:\n"+workingFrame); extendMessageWithFlow(ce); throw ce; } // This executes the Instruction. // Therefore the workingFrame object is modified. //ExecutionVisitor ev = ExecutionVisitor.getInstance(VerifierFactory.getVerifier(method_gen.getClassName())); ev.setFrame(workingFrame); getInstruction().accept(ev); //getInstruction().accept(ExecutionVisitor.withFrame(workingFrame)); outFrames.put(lastExecutionJSR(), workingFrame); return true; // new inFrame was different from old inFrame so merging them // yielded a different this.inFrame. } /** * Returns a simple String representation of this InstructionContext. */ public String toString(){ //TODO: Put information in the brackets, e.g. // Is this an ExceptionHandler? Is this a RET? Is this the start of // a subroutine? String ret = getInstruction().toString(false)+"\t[InstructionContext]"; return ret; } /** * Does the actual merging (vmspec2, page 146). * Returns true IFF this.inFrame was changed in course of merging with inFrame. */ private boolean mergeInFrames(Frame inFrame){ // TODO: Can be performance-improved. Frame inF = (Frame) inFrames.get(lastExecutionJSR()); OperandStack oldstack = inF.getStack().getClone(); LocalVariables oldlocals = inF.getLocals().getClone(); try{ inF.getStack().merge(inFrame.getStack()); inF.getLocals().merge(inFrame.getLocals()); } catch (StructuralCodeConstraintException sce){ extendMessageWithFlow(sce); throw sce; } if ( oldstack.equals(inF.getStack()) && oldlocals.equals(inF.getLocals()) ){ return false; } else{ return true; } } /** * Returns the control flow execution chain. This is built * while execute(Frame, ArrayList)-ing the code represented * by the surrounding ControlFlowGraph. */ private String getExecutionChain(){ String s = this.toString(); for (int i=executionPredecessors.size()-1; i>=0; i s = executionPredecessors.get(i)+"\n" + s; } return s; } /** * Extends the StructuralCodeConstraintException ("e") object with an at-the-end-extended message. * This extended message will then reflect the execution flow needed to get to the constraint * violation that triggered the throwing of the "e" object. */ private void extendMessageWithFlow(StructuralCodeConstraintException e){ String s = "Execution flow:\n"; e.extendMessage("", s+getExecutionChain()); } /* * Fulfils the contract of InstructionContext.getInstruction(). */ public InstructionHandle getInstruction(){ return instruction; } /** * Returns the InstructionContextImpl with an JSR/JSR_W * that was last in the ExecutionChain, without * a corresponding RET, i.e. * we were called by this one. * Returns null if we were called from the top level. */ private InstructionContextImpl lastExecutionJSR(){ int size = executionPredecessors.size(); int retcount = 0; for (int i=size-1; i>=0; i InstructionContextImpl current = (InstructionContextImpl) (executionPredecessors.get(i)); Instruction currentlast = current.getInstruction().getInstruction(); if (currentlast instanceof RET) retcount++; if (currentlast instanceof JsrInstruction){ retcount if (retcount == -1) return current; } } return null; } /* Satisfies InstructionContext.getSuccessors(). */ public InstructionContext[] getSuccessors(){ return contextsOf(_getSuccessors()); } /** * A utility method that calculates the successors of a given InstructionHandle * That means, a RET does have successors as defined here. * A JsrInstruction has its target as its successor * (opposed to its physical successor) as defined here. */ // TODO: implement caching! private InstructionHandle[] _getSuccessors(){ final InstructionHandle[] empty = new InstructionHandle[0]; final InstructionHandle[] single = new InstructionHandle[1]; final InstructionHandle[] pair = new InstructionHandle[2]; Instruction inst = getInstruction().getInstruction(); if (inst instanceof RET){ Subroutine s = subroutines.subroutineOf(getInstruction()); if (s==null){ //return empty; // RET in dead code. "empty" would be the correct answer, but we know something about the surrounding project... throw new AssertionViolatedException("Asking for successors of a RET in dead code?!"); } //TODO: remove throw new AssertionViolatedException("DID YOU REALLY WANT TO ASK FOR RET'S SUCCS?"); /* InstructionHandle[] jsrs = s.getEnteringJsrInstructions(); InstructionHandle[] ret = new InstructionHandle[jsrs.length]; for (int i=0; i<jsrs.length; i++){ ret[i] = jsrs[i].getNext(); } return ret; */ } // Terminates method normally. if (inst instanceof ReturnInstruction){ return empty; } // Terminates method abnormally, because JustIce mandates // subroutines not to be protected by exception handlers. if (inst instanceof ATHROW){ return empty; } // See method comment. if (inst instanceof JsrInstruction){ single[0] = ((JsrInstruction) inst).getTarget(); return single; } if (inst instanceof GotoInstruction){ single[0] = ((GotoInstruction) inst).getTarget(); return single; } if (inst instanceof BranchInstruction){ if (inst instanceof Select){ // BCEL's getTargets() returns only the non-default targets, // thanks to Eli Tilevich for reporting. InstructionHandle[] matchTargets = ((Select) inst).getTargets(); InstructionHandle[] ret = new InstructionHandle[matchTargets.length+1]; ret[0] = ((Select) inst).getTarget(); System.arraycopy(matchTargets, 0, ret, 1, matchTargets.length); return ret; } else{ pair[0] = getInstruction().getNext(); pair[1] = ((BranchInstruction) inst).getTarget(); return pair; } } // default case: Fall through. single[0] = getInstruction().getNext(); return single; } } // End Inner InstructionContextImpl Class. /** The MethofGen object we're working on. */ private final MethodGen method_gen; /** The Subroutines object for the method whose control flow is represented by this ControlFlowGraph. */ private final Subroutines subroutines; /** The ExceptionHandlers object for the method whose control flow is represented by this ControlFlowGraph. */ private final ExceptionHandlers exceptionhandlers; /** All InstructionContext instances of this ControlFlowGraph. */ private Hashtable instructionContexts = new Hashtable(); //keys: InstructionHandle, values: InstructionContextImpl /** * A Control Flow Graph. */ public ControlFlowGraph(MethodGen method_gen){ subroutines = new Subroutines(method_gen); exceptionhandlers = new ExceptionHandlers(method_gen); InstructionHandle[] instructionhandles = method_gen.getInstructionList().getInstructionHandles(); for (int i=0; i<instructionhandles.length; i++){ instructionContexts.put(instructionhandles[i], new InstructionContextImpl(instructionhandles[i])); } this.method_gen = method_gen; } /** * Returns the InstructionContext of a given instruction. */ public InstructionContext contextOf(InstructionHandle inst){ InstructionContext ic = (InstructionContext) instructionContexts.get(inst); if (ic == null){ throw new AssertionViolatedException("InstructionContext requested for an InstructionHandle that's not known!"); } return ic; } /** * Returns the InstructionContext[] of a given InstructionHandle[], * in a naturally ordered manner. */ public InstructionContext[] contextsOf(InstructionHandle[] insts){ InstructionContext[] ret = new InstructionContext[insts.length]; for (int i=0; i<insts.length; i++){ ret[i] = contextOf(insts[i]); } return ret; } /** * Returns an InstructionContext[] with all the InstructionContext instances * for the method whose control flow is represented by this ControlFlowGraph * <B>(NOT ORDERED!)</B>. */ public InstructionContext[] getInstructionContexts(){ InstructionContext[] ret = new InstructionContext[instructionContexts.values().size()]; return (InstructionContext[]) instructionContexts.values().toArray(ret); } /** * Returns true, if and only if the said instruction is not reachable; that means, * if it is not part of this ControlFlowGraph. */ public boolean isDead(InstructionHandle i){ return instructionContexts.containsKey(i); } }
package org.jivesoftware.messenger.component; import org.dom4j.Element; import org.dom4j.io.XPPPacketReader; import org.jivesoftware.messenger.*; import org.jivesoftware.messenger.auth.AuthFactory; import org.jivesoftware.messenger.auth.UnauthorizedException; import org.jivesoftware.util.LocaleUtils; import org.jivesoftware.util.Log; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmpp.component.Component; import org.xmpp.component.ComponentManager; import org.xmpp.packet.JID; import org.xmpp.packet.Packet; import org.xmpp.packet.StreamError; import java.io.IOException; import java.io.Writer; /** * Represents a session between the server and a component. * * @author Gaston Dombiak */ public class ComponentSession extends Session { private ExternalComponent component = new ExternalComponent(); /** * Returns a newly created session between the server and a component. The session will be * created and returned only if all the checkings were correct.<p> * * A domain will be binded for the new connecting component. This method is following * the JEP-114 where the domain to bind is sent in the TO attribute of the stream header. * * @param serverName the name of the server where the session is connecting to. * @param reader the reader that is reading the provided XML through the connection. * @param connection the connection with the component. * @return a newly created session between the server and a component. */ public static Session createSession(String serverName, XPPPacketReader reader, Connection connection) throws UnauthorizedException, IOException, XmlPullParserException { XmlPullParser xpp = reader.getXPPParser(); Session session; String domain = xpp.getAttributeValue("", "to"); Log.debug("[ExComp] Starting registration of new external component for domain: " + domain); // Get the requested subdomain String subdomain = domain; int index = domain.indexOf(serverName); if (index > -1) { subdomain = domain.substring(0, index -1); } Writer writer = connection.getWriter(); // Default answer header in case of an error StringBuilder sb = new StringBuilder(); sb.append("<?xml version='1.0' encoding='"); sb.append(CHARSET); sb.append("'?>"); sb.append("<stream:stream "); sb.append("xmlns:stream=\"http://etherx.jabber.org/streams\" "); sb.append("xmlns=\"jabber:component:accept\" from=\""); sb.append(domain); sb.append("\">"); // Check that a domain was provided in the stream header if (domain == null) { Log.debug("[ExComp] Domain not specified in stanza: " + xpp.getText()); // Include the bad-format in the response StreamError error = new StreamError(StreamError.Condition.bad_format); sb.append(error.toXML()); writer.write(sb.toString()); writer.flush(); // Close the underlying connection connection.close(); return null; } // Check that an external component for the specified subdomain may connect to this server if (!ExternalComponentManager.canAccess(subdomain)) { Log.debug("[ExComp] Component is not allowed to connect with subdomain: " + subdomain); StreamError error = new StreamError(StreamError.Condition.host_unknown); sb.append(error.toXML()); writer.write(sb.toString()); writer.flush(); // Close the underlying connection connection.close(); return null; } // Check that a secret key was configured in the server String secretKey = ExternalComponentManager.getSecretForComponent(subdomain); if (secretKey == null) { Log.debug("[ExComp] A shared secret for the component was not found."); // Include the internal-server-error in the response StreamError error = new StreamError(StreamError.Condition.internal_server_error); sb.append(error.toXML()); writer.write(sb.toString()); writer.flush(); // Close the underlying connection connection.close(); return null; } // Check that the requested subdomain is not already in use if (InternalComponentManager.getInstance().getComponent(subdomain) != null) { Log.debug("[ExComp] Another component is already using domain: " + domain); // Domain already occupied so return a conflict error and close the connection // Include the conflict error in the response StreamError error = new StreamError(StreamError.Condition.conflict); sb.append(error.toXML()); writer.write(sb.toString()); writer.flush(); // Close the underlying connection connection.close(); return null; } // Create a ComponentSession for the external component session = SessionManager.getInstance().createComponentSession(connection); // Set the bind address as the address of the session session.setAddress(new JID(null, domain , null)); try { Log.debug("[ExComp] Send stream header with ID: " + session.getStreamID() + " for component with domain: " + domain); // Build the start packet response sb = new StringBuilder(); sb.append("<?xml version='1.0' encoding='"); sb.append(CHARSET); sb.append("'?>"); sb.append("<stream:stream "); sb.append("xmlns:stream=\"http://etherx.jabber.org/streams\" "); sb.append("xmlns=\"jabber:component:accept\" from=\""); sb.append(domain); sb.append("\" id=\""); sb.append(session.getStreamID().toString()); sb.append("\">"); writer.write(sb.toString()); writer.flush(); // Perform authentication. Wait for the handshake (with the secret key) Element doc = reader.parseDocument().getRootElement(); String digest = "handshake".equals(doc.getName()) ? doc.getStringValue() : ""; String anticipatedDigest = AuthFactory.createDigest(session.getStreamID().getID(), secretKey); // Check that the provided handshake (secret key + sessionID) is correct if (!anticipatedDigest.equalsIgnoreCase(digest)) { Log.debug("[ExComp] Incorrect handshake for component with domain: " + domain); // The credentials supplied by the initiator are not valid (answer an error // and close the connection) sb = new StringBuilder(); // Include the conflict error in the response StreamError error = new StreamError(StreamError.Condition.not_authorized); sb.append(error.toXML()); writer.write(sb.toString()); writer.flush(); // Close the underlying connection connection.close(); return null; } else { // Component has authenticated fine session.setStatus(Session.STATUS_AUTHENTICATED); // Send empty handshake element to acknowledge success writer.write("<handshake></handshake>"); writer.flush(); // Bind the domain to this component ExternalComponent component = ((ComponentSession) session).getExternalComponent(); component.setSubdomain(subdomain); InternalComponentManager.getInstance().addComponent(subdomain, component); Log.debug("[ExComp] External component was registered SUCCESSFULLY with domain: " + domain); return session; } } catch (Exception e) { Log.error("An error occured while creating a ComponentSession", e); // Close the underlying connection connection.close(); return null; } } public ComponentSession(String serverName, Connection conn, StreamID id) { super(serverName, conn, id); } public void process(Packet packet) throws PacketException { // Since ComponentSessions are not being stored in the RoutingTable this messages is very // unlikely to be sent component.processPacket(packet); } public ExternalComponent getExternalComponent() { return component; } /** * The ExternalComponent acts as a proxy of the remote connected component. Any Packet that is * sent to this component will be delivered to the real component on the other side of the * connection.<p> * * An ExternalComponent will be added as a route in the RoutingTable for each connected * external component. This implies that when the server receives a packet whose domain matches * the external component services address then a route to the external component will be used * and the packet will be forwarded to the component on the other side of the connection. */ public class ExternalComponent implements Component { private String name; private String type; private String category; private String subdomain; public void processPacket(Packet packet) { if (conn != null && !conn.isClosed()) { try { conn.deliver(packet); } catch (Exception e) { Log.error(LocaleUtils.getLocalizedString("admin.error"), e); conn.close(); } } } public String getName() { return name; } public String getDescription() { return category + " - " + type; } public void setName(String name) { this.name = name; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public String getSubdomain() { return subdomain; } public void setSubdomain(String subdomain) { this.subdomain = subdomain; } public void initialize(JID jid, ComponentManager componentManager) { } public void start() { } public void shutdown() { } } }
package org.jivesoftware.openfire.commands.admin.user; import org.dom4j.Element; import org.jivesoftware.openfire.XMPPServer; import org.jivesoftware.openfire.commands.AdHocCommand; import org.jivesoftware.openfire.commands.SessionData; import org.jivesoftware.openfire.component.InternalComponentManager; import org.jivesoftware.openfire.user.UserAlreadyExistsException; import org.jivesoftware.openfire.user.UserManager; import org.jivesoftware.util.StringUtils; import org.xmpp.forms.DataForm; import org.xmpp.forms.FormField; import org.xmpp.packet.JID; import java.util.Arrays; import java.util.List; import java.util.Map; public class AddUser extends AdHocCommand { public String getCode() { return "http://jabber.org/protocol/admin#add-user"; } public String getDefaultLabel() { return "Add a User"; } public int getMaxStages(SessionData data) { return 1; } public void execute(SessionData sessionData, Element command) { Element note = command.addElement("note"); // Check if groups cannot be modified (backend is read-only) if (UserManager.getUserProvider().isReadOnly()) { note.addAttribute("type", "error"); note.setText("User provider is read only. New users cannot be created."); return; } Map<String, List<String>> data = sessionData.getData(); // Let's create the jid and check that they are a local user JID account; try { account = new JID(get(data, "accountjid", 0)); } catch (NullPointerException npe) { note.addAttribute("type", "error"); note.setText("JID required parameter."); return; } if (!XMPPServer.getInstance().isLocal(account)) { note.addAttribute("type", "error"); note.setText("Cannot create remote user."); return; } String password = get(data, "password", 0); String passwordRetry = get(data, "password-verify", 0); if (password == null || "".equals(password) || !password.equals(passwordRetry)) { note.addAttribute("type", "error"); note.setText("Passwords do not match."); return; } String email = get(data, "email", 0); String givenName = get(data, "given_name", 0); String surName = get(data, "surname", 0); String name = (givenName == null ? "" : givenName) + (surName == null ? "" : surName); name = (name.equals("") ? null : name); // If provider requires email, validate if (UserManager.getUserProvider().isEmailRequired() && !StringUtils.isValidEmailAddress(email)) { note.addAttribute("type", "error"); note.setText("No email was specified."); return; } try { UserManager.getInstance().createUser(account.getNode(), password, name, email); } catch (UserAlreadyExistsException e) { note.addAttribute("type", "error"); note.setText("User already exists."); return; } // Answer that the operation was successful note.addAttribute("type", "info"); note.setText("Operation finished successfully"); } protected void addStageInformation(SessionData data, Element command) { DataForm form = new DataForm(DataForm.Type.form); form.setTitle("Adding a user"); form.addInstruction("Fill out this form to add a user."); FormField field = form.addField(); field.setType(FormField.Type.hidden); field.setVariable("FORM_TYPE"); field.addValue("http://jabber.org/protocol/admin"); field = form.addField(); field.setType(FormField.Type.jid_single); field.setLabel("The Jabber ID for the account to be added"); field.setVariable("accountjid"); field.setRequired(true); field = form.addField(); field.setType(FormField.Type.text_private); field.setLabel("The password for this account"); field.setVariable("password"); field = form.addField(); field.setType(FormField.Type.text_private); field.setLabel("Retype password"); field.setVariable("password-verify"); field = form.addField(); field.setType(FormField.Type.text_single); field.setLabel("Email address"); field.setVariable("email"); field = form.addField(); field.setType(FormField.Type.text_single); field.setLabel("Given name"); field.setVariable("given_name"); field = form.addField(); field.setType(FormField.Type.text_single); field.setLabel("Family name"); field.setVariable("surname"); // Add the form to the command command.add(form.getElement()); } private String get(Map<String, List<String>> data, String key, int value) { List<String> list = data.get(key); if (list == null) { return null; } else { return list.get(value); } } protected List<Action> getActions(SessionData data) { return Arrays.asList(AdHocCommand.Action.complete); } protected AdHocCommand.Action getExecuteAction(SessionData data) { return AdHocCommand.Action.complete; } public boolean hasPermission(JID requester) { return (super.hasPermission(requester) || InternalComponentManager.getInstance().hasComponent(requester)) && !UserManager.getUserProvider().isReadOnly(); } }
package org.jivesoftware.spark.ui.conferences; import org.jivesoftware.resource.Res; import org.jivesoftware.smack.XMPPException; import org.jivesoftware.smackx.Form; import org.jivesoftware.smackx.FormField; import org.jivesoftware.smackx.ServiceDiscoveryManager; import org.jivesoftware.smackx.muc.MultiUserChat; import org.jivesoftware.smackx.muc.RoomInfo; import org.jivesoftware.smackx.packet.DataForm; import org.jivesoftware.smackx.packet.DiscoverInfo; import org.jivesoftware.spark.ChatManager; import org.jivesoftware.spark.SparkManager; import org.jivesoftware.spark.ui.ChatRoomNotFoundException; import org.jivesoftware.spark.ui.rooms.GroupChatRoom; import org.jivesoftware.spark.util.ModelUtil; import org.jivesoftware.spark.util.SwingWorker; import org.jivesoftware.spark.util.log.Log; import org.jivesoftware.sparkimpl.settings.local.LocalPreferences; import org.jivesoftware.sparkimpl.settings.local.SettingsManager; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.Iterator; import java.util.List; import javax.swing.JOptionPane; import javax.swing.JPasswordField; public class ConferenceUtils { private ConferenceUtils() { } /** * Return a list of available Conference rooms from the server * based on the service name. * * @param serviceName the service name (ex. conference@jivesoftware.com) * @return a collection of rooms. * @throws Exception if an error occured during fetch. */ public static Collection getRoomList(String serviceName) throws Exception { return MultiUserChat.getHostedRooms(SparkManager.getConnection(), serviceName); } /** * Return the number of occupants in a room. * * @param roomJID the full JID of the conference room. (ex. dev@conference.jivesoftware.com) * @return the number of occupants in the room if available. * @throws XMPPException thrown if an error occured during retrieval of the information. */ public static int getNumberOfOccupants(String roomJID) throws XMPPException { final RoomInfo roomInfo = MultiUserChat.getRoomInfo(SparkManager.getConnection(), roomJID); return roomInfo.getOccupantsCount(); } /** * Retrieve the date (in yyyyMMdd) format of the time the room was created. * * @param roomJID the jid of the room. * @return the formatted date. * @throws Exception throws an exception if we are unable to retrieve the date. */ public static String getCreationDate(String roomJID) throws Exception { ServiceDiscoveryManager discoManager = ServiceDiscoveryManager.getInstanceFor(SparkManager.getConnection()); final DateFormat dateFormatter = new SimpleDateFormat("yyyyMMdd'T'HH:mm:ss"); final SimpleDateFormat simpleFormat = new SimpleDateFormat("EEE MM/dd/yyyy h:mm:ss a"); DiscoverInfo infoResult = discoManager.discoverInfo(roomJID); DataForm dataForm = (DataForm)infoResult.getExtension("x", "jabber:x:data"); if (dataForm == null) { return "Not available"; } Iterator fieldIter = dataForm.getFields(); String creationDate = ""; while (fieldIter.hasNext()) { FormField field = (FormField)fieldIter.next(); String label = field.getLabel(); if (label != null && "Creation date".equalsIgnoreCase(label)) { Iterator valueIterator = field.getValues(); while (valueIterator.hasNext()) { Object oo = valueIterator.next(); creationDate = "" + oo; Date date = dateFormatter.parse(creationDate); creationDate = simpleFormat.format(date); } } } return creationDate; } public static void autoJoinConferenceRoom(final String roomName, String roomJID, String password) { ChatManager chatManager = SparkManager.getChatManager(); final MultiUserChat groupChat = new MultiUserChat(SparkManager.getConnection(), roomJID); LocalPreferences pref = SettingsManager.getLocalPreferences(); final String nickname = pref.getNickname().trim(); try { GroupChatRoom chatRoom = (GroupChatRoom)chatManager.getChatContainer().getChatRoom(roomJID); MultiUserChat muc = chatRoom.getMultiUserChat(); if (!muc.isJoined()) { joinRoom(muc, nickname, password); } chatManager.getChatContainer().activateChatRoom(chatRoom); return; } catch (ChatRoomNotFoundException e) { } final GroupChatRoom room = new GroupChatRoom(groupChat); room.setTabTitle(roomName); if (requiresPassword(roomJID) && password == null) { JPasswordField field = new JPasswordField(); JOptionPane.showMessageDialog(null, field, Res.getString("title.password"), JOptionPane.QUESTION_MESSAGE); password = new String(field.getPassword()); if (!ModelUtil.hasLength(password)) { return; } } final List errors = new ArrayList(); final String userPassword = password; final SwingWorker startChat = new SwingWorker() { public Object construct() { if (!groupChat.isJoined()) { int groupChatCounter = 0; while (true) { groupChatCounter++; String joinName = nickname; if (groupChatCounter > 1) { joinName = joinName + groupChatCounter; } if (groupChatCounter < 10) { try { if (ModelUtil.hasLength(userPassword)) { groupChat.join(joinName, userPassword); } else { groupChat.join(joinName); } break; } catch (XMPPException ex) { int code = 0; if (ex.getXMPPError() != null) { code = ex.getXMPPError().getCode(); } if (code == 0) { errors.add("No response from server."); } else if (code == 401) { errors.add("The password did not match the room's password."); } else if (code == 403) { errors.add("You have been banned from this room."); } else if (code == 404) { errors.add("The room you are trying to enter does not exist."); } else if (code == 407) { errors.add("You are not a member of this room.\nThis room requires you to be a member to join."); } else if (code != 409) { break; } } } else { break; } } } return "ok"; } public void finished() { if (errors.size() > 0) { String error = (String)errors.get(0); JOptionPane.showMessageDialog(SparkManager.getMainWindow(), error, "Unable to join the room at this time.", JOptionPane.ERROR_MESSAGE); return; } else if (groupChat.isJoined()) { ChatManager chatManager = SparkManager.getChatManager(); chatManager.getChatContainer().addChatRoom(room); chatManager.getChatContainer().activateChatRoom(room); } else { JOptionPane.showMessageDialog(SparkManager.getMainWindow(), "Unable to join the room.", "Error", JOptionPane.ERROR_MESSAGE); return; } } }; startChat.start(); } public static void joinConferenceRoom(final String roomName, String roomJID) { JoinConferenceRoomDialog joinDialog = new JoinConferenceRoomDialog(); joinDialog.joinRoom(roomJID, roomName); } public static void enterRoom(final MultiUserChat groupChat, String tabTitle, final String nickname, final String password) { final GroupChatRoom room = new GroupChatRoom(groupChat); room.setTabTitle(tabTitle); if (room == null) { return; } final List errors = new ArrayList(); if (!groupChat.isJoined()) { int groupChatCounter = 0; while (true) { groupChatCounter++; String joinName = nickname; if (groupChatCounter > 1) { joinName = joinName + groupChatCounter; } if (groupChatCounter < 10) { try { if (ModelUtil.hasLength(password)) { groupChat.join(joinName, password); } else { groupChat.join(joinName); } break; } catch (XMPPException ex) { int code = 0; if (ex.getXMPPError() != null) { code = ex.getXMPPError().getCode(); } if (code == 0) { errors.add("No response from server."); } else if (code == 401) { errors.add("A Password is required to enter this room."); } else if (code == 403) { errors.add("You have been banned from this room."); } else if (code == 404) { errors.add("The room you are trying to enter does not exist."); } else if (code == 407) { errors.add("You are not a member of this room.\nThis room requires you to be a member to join."); } else if (code != 409) { break; } } } else { break; } } } if (errors.size() > 0) { String error = (String)errors.get(0); JOptionPane.showMessageDialog(SparkManager.getMainWindow(), error, "Could Not Join Room", JOptionPane.ERROR_MESSAGE); return; } else if (groupChat.isJoined()) { ChatManager chatManager = SparkManager.getChatManager(); chatManager.getChatContainer().addChatRoom(room); chatManager.getChatContainer().activateChatRoom(room); } else { JOptionPane.showMessageDialog(SparkManager.getMainWindow(), "Unable to join room.", "Error", JOptionPane.ERROR_MESSAGE); return; } } public static List joinRoom(MultiUserChat groupChat, String nickname, String password) { final List errors = new ArrayList(); if (!groupChat.isJoined()) { int groupChatCounter = 0; while (true) { groupChatCounter++; String joinName = nickname; if (groupChatCounter > 1) { joinName = joinName + groupChatCounter; } if (groupChatCounter < 10) { try { if (ModelUtil.hasLength(password)) { groupChat.join(joinName, password); } else { groupChat.join(joinName); } break; } catch (XMPPException ex) { int code = 0; if (ex.getXMPPError() != null) { code = ex.getXMPPError().getCode(); } if (code == 0) { errors.add("No response from server."); } else if (code == 401) { errors.add("A Password is required to enter this room."); } else if (code == 403) { errors.add("You have been banned from this room."); } else if (code == 404) { errors.add("The room you are trying to enter does not exist."); } else if (code == 407) { errors.add("You are not a member of this room.\nThis room requires you to be a member to join."); } else if (code != 409) { break; } } } else { break; } } } return errors; } /** * Invites users to an existing room. * * @param serviceName the service name to use. * @param roomName the name of the room. * @param jids a collection of the users to invite. */ public static final void inviteUsersToRoom(String serviceName, String roomName, Collection jids) { ConferenceInviteDialog inviteDialog = new ConferenceInviteDialog(); inviteDialog.inviteUsersToRoom(serviceName, roomName, jids); } /** * Returns true if the room requires a password. * * @param roomJID the JID of the room. * @return true if the room requires a password. */ public static final boolean requiresPassword(String roomJID) { // Check to see if the room is password protected ServiceDiscoveryManager discover = new ServiceDiscoveryManager(SparkManager.getConnection()); try { DiscoverInfo info = discover.discoverInfo(roomJID); return info.containsFeature("muc_passwordprotected"); } catch (XMPPException e) { Log.error(e); } return false; } /** * Creates a private conference. * * @param serviceName the service name to use for the private conference. * @param message the message sent to each individual invitee. * @param roomName the name of the room to create. * @param jids a collection of the user JIDs to invite. */ public static void createPrivateConference(String serviceName, String message, String roomName, Collection jids) { final MultiUserChat chatRoom = new MultiUserChat(SparkManager.getConnection(), roomName + "@" + serviceName); final GroupChatRoom room = new GroupChatRoom(chatRoom); try { LocalPreferences pref = SettingsManager.getLocalPreferences(); chatRoom.create(pref.getNickname()); // Since this is a private room, make the room not public and set user as owner of the room. Form submitForm = chatRoom.getConfigurationForm().createAnswerForm(); submitForm.setAnswer("muc#roomconfig_publicroom", false); submitForm.setAnswer("muc#roomconfig_roomname", roomName); List owners = new ArrayList(); owners.add(SparkManager.getSessionManager().getBareAddress()); submitForm.setAnswer("muc#roomconfig_roomowners", owners); chatRoom.sendConfigurationForm(submitForm); } catch (XMPPException e1) { Log.error("Unable to send conference room chat configuration form.", e1); } ChatManager chatManager = SparkManager.getChatManager(); // Check if room already is open try { chatManager.getChatContainer().getChatRoom(room.getRoomname()); } catch (ChatRoomNotFoundException e) { chatManager.getChatContainer().addChatRoom(room); chatManager.getChatContainer().activateChatRoom(room); } final Iterator jidsToInvite = jids.iterator(); while (jidsToInvite.hasNext()) { String jid = (String)jidsToInvite.next(); chatRoom.invite(jid, message); room.getTranscriptWindow().insertNotificationMessage("Waiting for " + jid + " to join."); } } public static GroupChatRoom enterRoomOnSameThread(final String roomName, String roomJID, String password) { ChatManager chatManager = SparkManager.getChatManager(); final LocalPreferences pref = SettingsManager.getLocalPreferences(); final String nickname = pref.getNickname().trim(); try { GroupChatRoom chatRoom = (GroupChatRoom)chatManager.getChatContainer().getChatRoom(roomJID); MultiUserChat muc = chatRoom.getMultiUserChat(); if (!muc.isJoined()) { joinRoom(muc, nickname, password); } chatManager.getChatContainer().activateChatRoom(chatRoom); return chatRoom; } catch (ChatRoomNotFoundException e) { } final MultiUserChat groupChat = new MultiUserChat(SparkManager.getConnection(), roomJID); final GroupChatRoom room = new GroupChatRoom(groupChat); room.setTabTitle(roomName); if (requiresPassword(roomJID) && password == null) { password = JOptionPane.showInputDialog(null, "Enter Room Password", "Need Password", JOptionPane.QUESTION_MESSAGE); if (!ModelUtil.hasLength(password)) { return null; } } final List errors = new ArrayList(); final String userPassword = password; if (!groupChat.isJoined()) { int groupChatCounter = 0; while (true) { groupChatCounter++; String joinName = nickname; if (groupChatCounter > 1) { joinName = joinName + groupChatCounter; } if (groupChatCounter < 10) { try { if (ModelUtil.hasLength(userPassword)) { groupChat.join(joinName, userPassword); } else { groupChat.join(joinName); } break; } catch (XMPPException ex) { int code = 0; if (ex.getXMPPError() != null) { code = ex.getXMPPError().getCode(); } if (code == 0) { errors.add("No response from server."); } else if (code == 401) { errors.add("The password did not match the room's password."); } else if (code == 403) { errors.add("You have been banned from this room."); } else if (code == 404) { errors.add("The room you are trying to enter does not exist."); } else if (code == 407) { errors.add("You are not a member of this room.\nThis room requires you to be a member to join."); } else if (code != 409) { break; } } } else { break; } } } if (errors.size() > 0) { String error = (String)errors.get(0); JOptionPane.showMessageDialog(SparkManager.getMainWindow(), error, "Unable to join the room at this time.", JOptionPane.ERROR_MESSAGE); return null; } else if (groupChat.isJoined()) { chatManager.getChatContainer().addChatRoom(room); chatManager.getChatContainer().activateChatRoom(room); } else { JOptionPane.showMessageDialog(SparkManager.getMainWindow(), "Unable to join the room.", "Error", JOptionPane.ERROR_MESSAGE); return null; } return room; } }
package org.testng.internal.remote; import java.net.Socket; /** * <code>SocketLinkedBlockingQueue</code> is a wrapper on LinkedBlockingQueue so * we may factor out code common to JDK14 and JDK5+ using different implementation * of LinkedBlockingQueue * * @author cquezel * @since 5.2 */ public class SocketLinkedBlockingQueue extends edu.emory.mathcs.backport.java.util.concurrent.LinkedBlockingQueue { public Socket take() throws InterruptedException { return (Socket) super.take(); } }
package org.helioviewer.gl3d.model.image; import java.awt.Color; import java.awt.Graphics; import java.awt.Point; import java.util.ArrayList; import java.util.List; import javax.media.opengl.GL; import javax.swing.JFrame; import javax.swing.JPanel; import org.helioviewer.base.logging.Log; import org.helioviewer.base.physics.Constants; import org.helioviewer.gl3d.GL3DHelper; import org.helioviewer.gl3d.camera.GL3DCamera; import org.helioviewer.gl3d.camera.GL3DCameraListener; import org.helioviewer.gl3d.model.GL3DHitReferenceShape; import org.helioviewer.gl3d.scenegraph.GL3DDrawBits.Bit; import org.helioviewer.gl3d.scenegraph.GL3DNode; import org.helioviewer.gl3d.scenegraph.GL3DOrientedGroup; import org.helioviewer.gl3d.scenegraph.GL3DState; import org.helioviewer.gl3d.scenegraph.math.GL3DMat4d; import org.helioviewer.gl3d.scenegraph.math.GL3DQuatd; import org.helioviewer.gl3d.scenegraph.math.GL3DVec3d; import org.helioviewer.gl3d.scenegraph.math.GL3DVec4d; import org.helioviewer.gl3d.scenegraph.rt.GL3DRay; import org.helioviewer.gl3d.scenegraph.rt.GL3DRayTracer; import org.helioviewer.gl3d.shader.GL3DImageCoronaFragmentShaderProgram; import org.helioviewer.gl3d.shader.GL3DImageFragmentShaderProgram; import org.helioviewer.gl3d.view.GL3DCoordinateSystemView; import org.helioviewer.gl3d.view.GL3DImageTextureView; import org.helioviewer.gl3d.view.GL3DView; import org.helioviewer.gl3d.wcs.CoordinateConversion; import org.helioviewer.gl3d.wcs.CoordinateSystem; import org.helioviewer.gl3d.wcs.CoordinateVector; import org.helioviewer.gl3d.wcs.HeliocentricCartesian2000CoordinateSystem; import org.helioviewer.jhv.internal_plugins.filter.opacity.DynamicOpacityFilter; import org.helioviewer.viewmodel.changeevent.ChangeEvent; import org.helioviewer.viewmodel.filter.Filter; import org.helioviewer.viewmodel.metadata.HelioviewerMetaData; import org.helioviewer.viewmodel.metadata.MetaData; import org.helioviewer.viewmodel.region.Region; import org.helioviewer.viewmodel.region.StaticRegion; import org.helioviewer.viewmodel.view.MetaDataView; import org.helioviewer.viewmodel.view.RegionView; import org.helioviewer.viewmodel.view.View; import org.helioviewer.viewmodel.view.opengl.GLFilterView; /** * This is the scene graph equivalent of an image layer sub view chain attached * to the GL3DLayeredView. It represents exactly one image layer in the view * chain * * @author Simon Spoerri (simon.spoerri@fhnw.ch) * */ public abstract class GL3DImageLayer extends GL3DOrientedGroup implements GL3DCameraListener { private static int nextLayerId = 0; private final int layerId; private GL3DVec4d direction = new GL3DVec4d(0,0,1,0); public int getLayerId() { return layerId; } protected GL3DView mainLayerView; protected GL3DImageTextureView imageTextureView; protected GL3DCoordinateSystemView coordinateSystemView; protected MetaDataView metaDataView; protected RegionView regionView; protected GL3DImageLayers layerGroup; public double minZ = -Constants.SunRadius; public double maxZ = Constants.SunRadius; protected GL3DNode accellerationShape; protected boolean doUpdateROI = true; private JFrame frame = new JFrame("Hitpoints original"); private JFrame frame1 = new JFrame("Hitpoints"); private JPanel contentPane = new JPanel(); private JPanel contentPane1 = new JPanel(); private ArrayList<Point> points = new ArrayList<Point>(); private DynamicOpacityFilter opacityFilter; private double lastViewAngle = 0.0; protected GL gl; protected GL3DImageCoronaFragmentShaderProgram fragmentShader = null; protected GL3DImageFragmentShaderProgram sphereFragmentShader = null; public GL3DImageLayer(String name, GL3DView mainLayerView) { super(name); frame.setContentPane(contentPane); frame.setBounds(50, 50, 640, 480); frame1.setContentPane(contentPane1); frame1.setBounds(50, 50, 640, 480); layerId = nextLayerId++; this.mainLayerView = mainLayerView; if (this.mainLayerView == null) { throw new NullPointerException("Cannot create GL3DImageLayer from null Layer"); } this.imageTextureView = this.mainLayerView.getAdapter(GL3DImageTextureView.class); if (this.imageTextureView == null) { throw new IllegalStateException("Cannot create GL3DImageLayer when no GL3DImageTextureView is present in Layer"); } this.coordinateSystemView = this.mainLayerView.getAdapter(GL3DCoordinateSystemView.class); if (this.coordinateSystemView == null) { throw new IllegalStateException("Cannot create GL3DImageLayer when no GL3DCoordinateSystemView is present in Layer"); } this.metaDataView = this.mainLayerView.getAdapter(MetaDataView.class); if (this.metaDataView == null) { throw new IllegalStateException("Cannot create GL3DImageLayer when no MetaDataView is present in Layer"); } this.regionView = this.mainLayerView.getAdapter(RegionView.class); if (this.regionView == null) { throw new IllegalStateException("Cannot create GL3DImageLayer when no RegionView is present in Layer"); } initOpacityFilter(mainLayerView); getCoordinateSystem().addListener(this); this.doUpdateROI = true; this.markAsChanged(); } private void initOpacityFilter(View mainLayerView) { // Get opacity filter from view chain View filterView = mainLayerView; while ((filterView = filterView.getAdapter(GLFilterView.class)) != null && opacityFilter == null) { Filter filter = ((GLFilterView) filterView).getFilter(); if (DynamicOpacityFilter.class.isInstance(filter)){ opacityFilter = (DynamicOpacityFilter) filter; } } if (opacityFilter == null) throw new IllegalStateException("Cannot create GL3DImageLayer when no DynamicOpacityFilter is present in ViewChain"); } public void shapeInit(GL3DState state) { this.createImageMeshNodes(state.gl); CoordinateVector orientationVector = this.getOrientation(); CoordinateConversion toViewSpace = this.getCoordinateSystem().getConversion(state.getActiveCamera().getViewSpaceCoordinateSystem()); GL3DVec3d orientation = GL3DHelper.toVec(toViewSpace.convert(orientationVector)).normalize(); double phi = 0.0; if (!(orientation.equals(new GL3DVec3d(0, 1, 0)))) { GL3DVec3d orientationXZ = new GL3DVec3d(orientation.x, 0, orientation.z); phi = Math.acos(orientationXZ.z); if (orientationXZ.x < 0) { phi = 0 - phi; } phi = 0.0; } this.accellerationShape = new GL3DHitReferenceShape(true, phi); this.addNode(this.accellerationShape); super.shapeInit(state); this.doUpdateROI = true; this.markAsChanged(); updateROI(state.getActiveCamera()); GL3DQuatd phiRotation = GL3DQuatd.createRotation(2*Math.PI - phi, new GL3DVec3d(0,1,0)); state.getActiveCamera().getRotation().set(phiRotation); state.getActiveCamera().updateCameraTransformation(); } protected abstract void createImageMeshNodes(GL gl); protected abstract GL3DImageMesh getImageCorona(); protected abstract GL3DImageMesh getImageSphere(); public void shapeUpdate(GL3DState state) { super.shapeUpdate(state); if (doUpdateROI) { // Log.debug("GL3DImageLayer: '"+getName()+" is updating its ROI"); this.updateROI(state.getActiveCamera()); doUpdateROI = false; this.accellerationShape.setUnchanged(); } } public void cameraMoved(GL3DCamera camera) { doUpdateROI = true; if(this.accellerationShape!=null) this.accellerationShape.markAsChanged(); cameraMoving(camera); } public double getLastViewAngle() { return lastViewAngle; } public void paint(Graphics g){ for (Point p : points){ g.fillRect(p.x-1, p.y-1, 2, 2); } } public void cameraMoving(GL3DCamera camera) { GL3DMat4d camTrans = camera.getRotation().toMatrix().inverse(); GL3DVec4d camDirection = new GL3DVec4d(0, 0, 1, 1); camDirection = camTrans.multiply(camDirection); camDirection.w = 0; camDirection.normalize(); double angle = (Math.acos(camDirection.dot(direction))/Math.PI * 180.0); double maxAngle = 60; double minAngle = 30; if (angle != lastViewAngle){ lastViewAngle = angle; float alpha = (float) ((Math.abs(90-lastViewAngle)-minAngle)/(maxAngle-minAngle)); if (this.fragmentShader != null) this.fragmentShader.changeAlpha(alpha); } } public GL3DVec4d getLayerDirection() { // Convert layer orientation to heliocentric coordinate system /*CoordinateVector orientation = coordinateSystemView.getOrientation(); CoordinateSystem targetSystem = new HeliocentricCartesianCoordinateSystem(); CoordinateConversion converter = orientation.getCoordinateSystem().getConversion(targetSystem); orientation = converter.convert(orientation); GL3DVec3d layerDirection = new GL3DVec3d(orientation.getValue(0), orientation.getValue(1), orientation.getValue(2));*/ //GL3DVec4d n = new GL3DVec4d(0, 0, 1, 1); //n = modelView().multiply(n); //GL3DVec3d layerDirection = new GL3DVec3d(n.x, n.y, n.z); //layerDirection.normalize(); return direction; } public void setLayerDirection(GL3DVec4d direction){ this.direction = direction; } public CoordinateSystem getCoordinateSystem() { return this.coordinateSystemView.getCoordinateSystem(); } public CoordinateVector getOrientation() { HelioviewerMetaData h = (HelioviewerMetaData) this.metaDataView.getMetaData(); CoordinateVector c = this.coordinateSystemView.getOrientation(); return this.coordinateSystemView.getOrientation(); } private void updateROI(GL3DCamera activeCamera) { MetaData metaData = metaDataView.getMetaData(); if (metaData == null) { // No Image Data found return; } double hh = Math.tan(Math.toRadians(activeCamera.getFOV() / 2)) * activeCamera.getClipNear(); double hw = hh * activeCamera.getAspect(); double pixelSize = hw / activeCamera.getWidth() * 2; GL3DRayTracer rayTracer = new GL3DRayTracer(this.accellerationShape, activeCamera); // Shoot Rays in the corners of the viewport int width = (int) activeCamera.getWidth(); int height = (int) activeCamera.getHeight(); List<GL3DRay> regionTestRays = new ArrayList<GL3DRay>(); contentPane.removeAll(); contentPane.setLayout(null); contentPane1.removeAll(); contentPane1.setLayout(null); //frame.setVisible(true); //frame1.setVisible(true); for (int i = 0; i <= 10; i++){ for (int j = 0; j <= 10; j++){ regionTestRays.add(rayTracer.cast(i*(width/10), j*(height/10))); } } double minPhysicalX = Double.MAX_VALUE; double minPhysicalY = Double.MAX_VALUE; double minPhysicalZ = Double.MAX_VALUE; double maxPhysicalX = -Double.MAX_VALUE; double maxPhysicalY = -Double.MAX_VALUE; double maxPhysicalZ = -Double.MAX_VALUE; CoordinateVector orientationVector = this.getOrientation(); CoordinateConversion toViewSpace = this.getCoordinateSystem().getConversion(activeCamera.getViewSpaceCoordinateSystem()); GL3DVec3d orientation = GL3DHelper.toVec(toViewSpace.convert(orientationVector)).normalize(); GL3DMat4d phiRotation = null; if (!(orientation.equals(new GL3DVec3d(0, 1, 0)))) { GL3DVec3d orientationXZ = new GL3DVec3d(orientation.x, 0, orientation.z); double phi = Math.acos(orientationXZ.z); if (orientationXZ.x < 0) { phi = 0 - phi; } phi = 2 * Math.PI - phi; phiRotation = GL3DMat4d.rotation(phi, new GL3DVec3d(0, 1, 0)); } for (GL3DRay ray : regionTestRays) { GL3DVec3d hitPoint = ray.getHitPoint(); if (hitPoint != null) { hitPoint = this.wmI.multiply(hitPoint); double coordx = (hitPoint.x - metaData.getPhysicalLowerLeft().getX())/metaData.getPhysicalImageWidth(); double coordy = ((1-hitPoint.y) - metaData.getPhysicalLowerLeft().getY())/metaData.getPhysicalImageHeight(); JPanel panel = new JPanel(); panel.setBackground(Color.BLACK); panel.setBounds((int)(coordx * contentPane.getWidth())-3,(int)(coordy * contentPane.getHeight())-3, 5 , 5); contentPane.add(panel); double x = phiRotation.m[0]*hitPoint.x + phiRotation.m[4]*hitPoint.y + phiRotation.m[8]*hitPoint.z + phiRotation.m[12]; double y = phiRotation.m[1]*hitPoint.x + phiRotation.m[5]*hitPoint.y + phiRotation.m[9]*hitPoint.z + phiRotation.m[13]; double z = phiRotation.m[2]*hitPoint.x + phiRotation.m[6]*hitPoint.y + phiRotation.m[10]*hitPoint.z + phiRotation.m[14]; coordx = (x - metaData.getPhysicalLowerLeft().getX())/metaData.getPhysicalImageWidth(); coordy = ((1-y) - metaData.getPhysicalLowerLeft().getY())/metaData.getPhysicalImageHeight(); JPanel panel1 = new JPanel(); panel1.setBackground(Color.BLACK); panel1.setBounds((int)(coordx * contentPane.getWidth())-3,(int)(coordy * contentPane.getHeight())-3, 5 , 5); contentPane1.add(panel1); minPhysicalX = Math.min(minPhysicalX, x); minPhysicalY = Math.min(minPhysicalY, y); minPhysicalZ = Math.min(minPhysicalZ, z); maxPhysicalX = Math.max(maxPhysicalX, x); maxPhysicalY = Math.max(maxPhysicalY, y); maxPhysicalZ = Math.max(maxPhysicalZ, z); // Log.debug("GL3DImageLayer: Hitpoint: "+hitPoint+" - "+ray.isOnSun); } } //frame.repaint(); //frame1.repaint(); // Restrict maximal region to physically available region minPhysicalX = Math.max(minPhysicalX, metaData.getPhysicalLowerLeft().getX()); minPhysicalY = Math.max(minPhysicalY, metaData.getPhysicalLowerLeft().getY()); maxPhysicalX = Math.min(maxPhysicalX, metaData.getPhysicalUpperRight().getX()); maxPhysicalY = Math.min(maxPhysicalY, metaData.getPhysicalUpperRight().getY()); minPhysicalX -= Math.abs(minPhysicalX)*0.1; minPhysicalY -= Math.abs(minPhysicalY)*0.1; maxPhysicalX += Math.abs(maxPhysicalX)*0.1; maxPhysicalY += Math.abs(maxPhysicalY)*0.1; if (minPhysicalX < metaData.getPhysicalLowerLeft().getX()) minPhysicalX = metaData.getPhysicalLowerLeft().getX(); if (minPhysicalY < metaData.getPhysicalLowerLeft().getY()) minPhysicalY = metaData.getPhysicalLowerLeft().getX(); if (maxPhysicalX > metaData.getPhysicalUpperRight().getX()) maxPhysicalX = metaData.getPhysicalUpperRight().getX(); if (maxPhysicalY > metaData.getPhysicalUpperRight().getY()) maxPhysicalY = metaData.getPhysicalUpperRight().getY(); double regionWidth = maxPhysicalX - minPhysicalX; double regionHeight = maxPhysicalY - minPhysicalY; if (regionWidth > 0 && regionHeight > 0) { Region newRegion = StaticRegion.createAdaptedRegion(minPhysicalX, minPhysicalY, regionWidth, regionHeight); // Log.debug("GL3DImageLayer: '"+getName()+" set its region"); this.regionView.setRegion(newRegion, new ChangeEvent()); } else { Log.error("Illegal Region calculated! " + regionWidth + ":" + regionHeight + ". x = " + minPhysicalX + " - " + maxPhysicalX + ", y = " + minPhysicalY + " - " + maxPhysicalY); } } public void setCoronaVisibility(boolean visible) { GL3DNode node = this.first; while (node != null) { if (node instanceof GL3DImageCorona) { node.getDrawBits().set(Bit.Hidden, !visible); } node = node.getNext(); } } protected GL3DImageTextureView getImageTextureView() { return this.imageTextureView; } public void setLayerGroup(GL3DImageLayers layers) { layerGroup = layers; } public GL3DImageLayers getLayerGroup() { return layerGroup; } }
package com.izforge.izpack.panels; import net.n3.nanoxml.XMLElement; import com.izforge.izpack.installer.AutomatedInstallData; import com.izforge.izpack.installer.PanelAutomation; import com.izforge.izpack.installer.PanelAutomationHelper; import com.izforge.izpack.installer.Unpacker; import com.izforge.izpack.util.AbstractUIProgressHandler; /** * Functions to support automated usage of the InstallPanel * * @author Jonathan Halliday */ public class InstallPanelAutomationHelper extends PanelAutomationHelper implements PanelAutomation, AbstractUIProgressHandler { // state var for thread sync. private boolean done = false; private int noOfPacks = 0; /** * Null op - this panel type has no state to serialize. * * @param installData unused. * @param panelRoot unused. */ public void makeXMLData(AutomatedInstallData installData, XMLElement panelRoot) { // do nothing. } /** * Perform the installation actions. * * @param panelRoot The panel XML tree root. */ public void runAutomated(AutomatedInstallData idata, XMLElement panelRoot) { Unpacker unpacker = new Unpacker(idata, this); unpacker.start(); done = false; while (!done && unpacker.isAlive()) { try { Thread.sleep(100); } catch (InterruptedException e) { // ignore it, we're waiting for the unpacker to finish... } } } /** * Reports progress on System.out * * @see AbstractUIProgressHandler#startAction(String, int) */ public void startAction (String name, int no_of_steps) { System.out.println("[ Starting to unpack ]"); this.noOfPacks = no_of_steps; } /** * Sets state variable for thread sync. * * @see com.izforge.izpack.util.AbstractUIProgressHandler#stopAction() */ public void stopAction() { System.out.println("[ Unpacking finished. ]"); done = true; } /** * Null op. * * @param val * @param msg * @see com.izforge.izpack.util.AbstractUIProgressHandler#progress(int, String) */ public void progress(int val, String msg) { // silent for now. should log individual files here, if we had a verbose mode? } /** * Reports progress to System.out * * @param packName The currently installing pack. * @param stepno The number of the pack * @param stepsize unused * @see com.izforge.izpack.util.AbstractUIProgressHandler#nextStep(String, int, int) */ public void nextStep (String packName, int stepno, int stepsize) { System.out.print("[ Processing package: " + packName +" ("); System.out.print (stepno); System.out.print ('/'); System.out.print (this.noOfPacks); System.out.println (") ]"); } }
package acmi.l2.clientmod.unreal; import acmi.l2.clientmod.io.ObjectInput; import acmi.l2.clientmod.io.ObjectInputStream; import acmi.l2.clientmod.io.ObjectOutput; import acmi.l2.clientmod.io.*; import acmi.l2.clientmod.unreal.annotation.Bytecode; import acmi.l2.clientmod.unreal.annotation.NameRef; import acmi.l2.clientmod.unreal.annotation.ObjectRef; import acmi.l2.clientmod.unreal.bytecode.BytecodeContext; import acmi.l2.clientmod.unreal.bytecode.TokenSerializerFactory; import acmi.l2.clientmod.unreal.bytecode.token.Token; import acmi.l2.clientmod.unreal.core.Object; import acmi.l2.clientmod.unreal.core.Struct; import acmi.l2.clientmod.unreal.properties.PropertiesUtil; import javafx.beans.InvalidationListener; import javafx.collections.FXCollections; import javafx.collections.ObservableSet; import java.io.*; import java.lang.annotation.Annotation; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.*; import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.Stream; public class UnrealSerializerFactory extends ReflectionSerializerFactory<UnrealRuntimeContext> { private static final Logger log = Logger.getLogger(UnrealSerializerFactory.class.getName()); public static String unrealClassesPackage = "acmi.l2.clientmod.unreal"; public static final Predicate<String> IS_STRUCT = c -> c.equalsIgnoreCase("Core.Struct") || c.equalsIgnoreCase("Core.Function") || c.equalsIgnoreCase("Core.State") || c.equalsIgnoreCase("Core.Class"); private ForkJoinPool forkJoinPool = new ForkJoinPool(); private Map<UnrealPackage.Entry, Object> objects = new HashMap<>(); private Map<Integer, acmi.l2.clientmod.unreal.core.Function> nativeFunctions = new HashMap<>(); private ObservableSet<String> loaded = FXCollections.observableSet(new HashSet<>()); private Environment environment; public UnrealSerializerFactory(Environment environment) { this.environment = new EnvironmentWrapper(environment.getStartDir(), environment.getPaths()); } public Environment getEnvironment() { return environment; } @Override protected Function<ObjectInput<UnrealRuntimeContext>, java.lang.Object> createInstantiator(Class<?> clazz) { if (Object.class.isAssignableFrom(clazz)) return objectInput -> { UnrealRuntimeContext context = objectInput.getContext(); int objRef = objectInput.readCompactInt(); UnrealPackage.Entry entry = context.getUnrealPackage().objectReference(objRef); return getOrCreateObject(entry); }; return super.createInstantiator(clazz); } public Object getOrCreateObject(UnrealPackage.Entry packageLocalEntry) throws UncheckedIOException { if (packageLocalEntry == null) return null; if (!objects.containsKey(packageLocalEntry)) { log.fine(() -> String.format("Loading %s", packageLocalEntry)); UnrealPackage.ExportEntry entry; try { entry = resolveExportEntry(packageLocalEntry).orElse(null); if (entry != null) { Class<? extends Object> clazz = getClass(entry.getFullClassName()); Object obj = clazz.newInstance(); objects.put(entry, obj); load(obj, entry); } else { create(packageLocalEntry.getObjectFullName(), packageLocalEntry.getFullClassName()); } } catch (Throwable e) { throw new IllegalStateException(e); } } return objects.get(packageLocalEntry); } private void create(String objName, String objClass) { log.fine(() -> String.format("Create dummy %s[%s]", objName, objClass)); UnrealPackage.Entry entry = new UnrealPackage.Entry(null, 0, 0, 0) { @Override public String getObjectFullName() { return objName; } @Override public String getFullClassName() { return objClass; } @Override public int getObjectReference() { return 0; } @Override public List getTable() { return null; } }; objects.put(entry, new acmi.l2.clientmod.unreal.core.Class() { @Override public String getFullName() { return objName; } @Override public String getClassFullName() { return objClass; } }); } public Object getOrCreateObject(String objName, Predicate<String> objClass) throws UncheckedIOException { return getOrCreateObject(getExportEntry(objName, objClass) .orElseThrow(() -> new UnrealException("Entry " + objName + " not found"))); } public Optional<UnrealPackage.ExportEntry> resolveExportEntry(UnrealPackage.Entry entry) { if (entry == null) return Optional.empty(); return entry instanceof UnrealPackage.ExportEntry ? Optional.of((UnrealPackage.ExportEntry) entry) : getExportEntry(entry.getObjectFullName(), clazz -> clazz.equalsIgnoreCase(entry.getFullClassName())); } private Optional<UnrealPackage.ExportEntry> getExportEntry(String objName, Predicate<String> objClass) { return environment.getExportEntry(objName, objClass); } private Class<? extends Object> getClass(String className) throws UncheckedIOException { Class<?> clazz = null; try { String javaClassName = unrealClassesPackage + "." + unrealClassNameToJavaClassName(className); log.finer(() -> String.format("unreal[%s]->jvm[%s]", className, javaClassName)); clazz = Class.forName(javaClassName); return clazz.asSubclass(Object.class); } catch (ClassNotFoundException e) { log.finer(() -> String.format("Class %s not implemented in java", className)); } catch (ClassCastException e) { Class<?> clazzLocal = clazz; log.warning(() -> String.format("%s is not subclass of %s", clazzLocal, Object.class)); } return getClass(getExportEntry(className, c -> c.equalsIgnoreCase("Core.Class")) .map(e -> e.getObjectSuperClass().getObjectFullName()) .orElse("Core.Object")); // Object object = getOrCreateObject(className, c -> c.equalsIgnoreCase("Core.Class")); // return getClass(object.entry.getObjectSuperClass().getObjectFullName()); } private String unrealClassNameToJavaClassName(String className) { String[] path = className.split("\\."); return String.format("%s.%s", path[0].toLowerCase(), path[1]); } @Override protected <T> void serializer(Class type, Function<T, java.lang.Object> getter, BiConsumer<T, Supplier> setter, Function<Class<? extends Annotation>, Annotation> getAnnotation, List<BiConsumer<T, ObjectInput<UnrealRuntimeContext>>> read, List<BiConsumer<T, ObjectOutput<UnrealRuntimeContext>>> write) { if (type == String.class && Objects.nonNull(getAnnotation.apply(NameRef.class))) { read.add((object, dataInput) -> setter.accept(object, () -> dataInput.getContext().getUnrealPackage().nameReference(dataInput.readCompactInt()))); write.add((object, dataOutput) -> dataOutput.writeCompactInt(dataOutput.getContext().getUnrealPackage().nameReference((String) getter.apply(object)))); } else if (Object.class.isAssignableFrom(type) && Objects.nonNull(getAnnotation.apply(ObjectRef.class))) { read.add((object, dataInput) -> setter.accept(object, () -> getOrCreateObject(dataInput.getContext().getUnrealPackage().objectReference(dataInput.readCompactInt())))); write.add((object, dataOutput) -> { Object obj = (Object) getter.apply(object); dataOutput.writeCompactInt(obj.entry.getObjectReference()); }); } else if (type.isArray() && type.getComponentType() == Token.class && Objects.nonNull(getAnnotation.apply(Bytecode.class))) { read.add((object, dataInput) -> { BytecodeContext context = new BytecodeContext(dataInput.getContext()); SerializerFactory<BytecodeContext> serializerFactory = new TokenSerializerFactory(); ObjectInput<BytecodeContext> input = ObjectInput.objectInput(dataInput, serializerFactory, context); int size = input.readInt(); int readSize = 0; List<Token> tokens = new ArrayList<>(); while (readSize < size) { Token token = input.readObject(Token.class); readSize += token.getSize(context); tokens.add(token); } setter.accept(object, () -> tokens.toArray(new Token[tokens.size()])); }); write.add((object, dataOutput) -> { BytecodeContext context = new BytecodeContext(dataOutput.getContext()); SerializerFactory<BytecodeContext> serializerFactory = new TokenSerializerFactory(); ObjectOutput<BytecodeContext> output = ObjectOutput.objectOutput(dataOutput, serializerFactory, context); Token[] array = (Token[]) getter.apply(object); output.writeInt(array.length); for (Token token : array) output.write(token); }); } else { super.serializer(type, getter, setter, getAnnotation, read, write); } } private void load(Object obj, UnrealPackage.ExportEntry entry) throws Throwable { try { ObjectInput<UnrealRuntimeContext> input = new ObjectInputStream<UnrealRuntimeContext>( new ByteArrayInputStream(entry.getObjectRawDataExternally()), entry.getUnrealPackage().getFile().getCharset(), entry.getOffset(), this, new UnrealRuntimeContext(entry, this) ) { @Override public java.lang.Object readObject(Class clazz) throws UncheckedIOException { if (getSerializerFactory() == null) throw new IllegalStateException("SerializerFactory is null"); Serializer serializer = getSerializerFactory().forClass(clazz); java.lang.Object obj = serializer.instantiate(this); if (!(obj instanceof acmi.l2.clientmod.unreal.core.Object)) throw new RuntimeException("USE input.getSerializerFactory().forClass(class).readObject(object, input);"); return obj; } }; CompletableFuture.runAsync(() -> { Serializer serializer = forClass(obj.getClass()); serializer.readObject(obj, input); }, forkJoinPool).join(); if (obj instanceof acmi.l2.clientmod.unreal.core.Function) { acmi.l2.clientmod.unreal.core.Function func = (acmi.l2.clientmod.unreal.core.Function) obj; if (func.nativeIndex > 0) nativeFunctions.put(func.nativeIndex, func); } if (entry.getFullClassName().equalsIgnoreCase("Core.Class")) { Runnable loadProps = () -> { obj.properties.addAll(PropertiesUtil.readProperties(input, obj.getFullName())); loaded.add(entry.getObjectFullName()); log.fine(() -> entry.getObjectFullName() + " properties loaded"); }; if (entry.getObjectSuperClass() != null) { String superClass = entry.getObjectSuperClass().getObjectFullName(); if (loaded.contains(superClass)) { loadProps.run(); } else { AtomicInteger ai = new AtomicInteger(0); Consumer<InvalidationListener> c = il -> { if (loaded.contains(superClass) && ai.getAndIncrement() == 0) { loaded.removeListener(il); loadProps.run(); } }; InvalidationListener il = new InvalidationListener() { @Override public void invalidated(javafx.beans.Observable observable) { c.accept(this); } }; loaded.addListener(il); c.accept(il); } } else { loadProps.run(); } } if (!(obj instanceof acmi.l2.clientmod.unreal.core.Class)) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { while (true) baos.write(input.readUnsignedByte()); } catch (UncheckedIOException ignore) { } obj.unreadBytes = baos.toByteArray(); if (obj.unreadBytes.length > 0) log.warning(() -> obj + " " + obj.unreadBytes.length + " bytes ignored"); } log.fine(() -> entry.getObjectFullName() + " loaded"); } catch (CompletionException e) { throw e.getCause(); } } public Optional<Struct> getStruct(String name) { try { return Optional.ofNullable((Struct) getOrCreateObject(name, IS_STRUCT)); } catch (Exception e) { log.log(Level.WARNING, e, () -> ""); return Optional.empty(); } } public String getSuperClass(String clazz) { Optional<UnrealPackage.ExportEntry> opt = getExportEntry(clazz, IS_STRUCT); if (opt.isPresent()) return opt.get().getObjectSuperClass() != null ? opt.get().getObjectSuperClass().getObjectFullName() : null; else { try { Class<?> javaClass = Class.forName(unrealClassesPackage + "." + unrealClassNameToJavaClassName(clazz)); Class<?> javaSuperClass = javaClass.getSuperclass(); String javaSuperClassName = javaSuperClass.getName(); if (javaSuperClassName.contains(unrealClassesPackage)) { javaSuperClassName = javaSuperClassName.substring(unrealClassesPackage.length() + 1); return javaSuperClassName.substring(0, 1).toUpperCase() + javaSuperClassName.substring(1); } } catch (ClassNotFoundException ignore) { } } return null; } private final Map<String, Boolean> isSubclassCache = new HashMap<>(); public boolean isSubclass(String parent, String child) { if (parent.equalsIgnoreCase(Objects.requireNonNull(child))) return true; String k = parent + "@" + child; synchronized (isSubclassCache) { if (!isSubclassCache.containsKey(k)) { child = getSuperClass(child); isSubclassCache.put(k, child != null && isSubclass(parent, child)); } return isSubclassCache.get(k); } } public <T extends Struct> List<T> getStructTree(T struct) { List<T> list = new ArrayList<>(); for (UnrealPackage.ExportEntry entry = struct.entry; entry != null; entry = resolveExportEntry(entry.getObjectSuperClass()).orElse(null)) { list.add((T) getOrCreateObject(entry)); } Collections.reverse(list); return list; } public Optional<acmi.l2.clientmod.unreal.core.Function> getNativeFunction(int index) { return Optional.ofNullable(nativeFunctions.get(index)); } private static class EnvironmentWrapper extends Environment { private Map<String, UnrealPackage> adds = new HashMap<>(); public EnvironmentWrapper(File startDir, List<String> paths) { super(startDir, paths); } @Override public Stream<UnrealPackage> listPackages(String name) { Stream<UnrealPackage> stream = super.listPackages(name); if (name.equalsIgnoreCase("Engine") || name.equalsIgnoreCase("Core")) { stream = appendCustomPackage(stream, name); } return stream; } private Stream<UnrealPackage> appendCustomPackage(Stream<UnrealPackage> stream, String name) { if (!adds.containsKey(name)) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try (InputStream is = getClass().getResourceAsStream("/" + name + ".u")) { byte[] buf = new byte[1024]; int r; while ((r = is.read(buf)) != -1) baos.write(buf, 0, r); } catch (IOException e) { throw new UnrealException(e); } try (UnrealPackage up = new UnrealPackage(new RandomAccessMemory(name, baos.toByteArray(), UnrealPackage.getDefaultCharset()))) { adds.put(name, up); } } return Stream.concat(Stream.of(adds.get(name)), stream); } } }
package au.com.agic.apptesting.steps; import au.com.agic.apptesting.State; import au.com.agic.apptesting.exception.WebElementException; import au.com.agic.apptesting.utils.AutoAliasUtils; import au.com.agic.apptesting.utils.FeatureState; import au.com.agic.apptesting.utils.GetBy; import au.com.agic.apptesting.utils.SimpleWebElementInteraction; import au.com.agic.apptesting.utils.SleepUtils; import au.com.agic.apptesting.utils.impl.AutoAliasUtilsImpl; import au.com.agic.apptesting.utils.impl.GetByImpl; import au.com.agic.apptesting.utils.impl.SimpleWebElementInteractionImpl; import au.com.agic.apptesting.utils.impl.SleepUtilsImpl; import org.apache.commons.lang3.StringUtils; import org.openqa.selenium.By; import org.openqa.selenium.TimeoutException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.ExecutionException; import cucumber.api.java.en.When; public class WaitStepDefinitions { private static final Logger LOGGER = LoggerFactory.getLogger(WaitStepDefinitions.class); private static final SleepUtils SLEEP_UTILS = new SleepUtilsImpl(); private static final GetBy GET_BY = new GetByImpl(); private static final AutoAliasUtils AUTO_ALIAS_UTILS = new AutoAliasUtilsImpl(); private static final SimpleWebElementInteraction SIMPLE_WEB_ELEMENT_INTERACTION = new SimpleWebElementInteractionImpl(); private static final long MILLISECONDS_PER_SECOND = 1000; /** * Get the web driver for this thread */ private final FeatureState featureState = State.THREAD_DESIRED_CAPABILITY_MAP.getDesiredCapabilitiesForThread(); /** * Pauses the execution of the test script for the given number of seconds * * @param sleepDuration The number of seconds to pause the script for */ @When("^I (?:wait|sleep) for \"(\\d+)\" second(?:s?)$") public void sleepStep(final String sleepDuration) { SLEEP_UTILS.sleep(Integer.parseInt(sleepDuration) * MILLISECONDS_PER_SECOND); } /** * Waits the given amount of time for an element to be displayed (i.e. to be visible) on the page. <p> * This is most useful when waiting for a page to load completely. You can use this step to pause the * script until some known element is visible, which is a good indication that the page has loaded * completely. * * @param waitDuration The maximum amount of time to wait for * @param alias If this word is found in the step, it means the selectorValue is found from the * data set. * @param selectorValue The value used in conjunction with the selector to match the element. If alias * was set, this value is found from the data set. Otherwise it is a literal * value. * @param ignoringTimeout include this text to continue the script in the event that the element can't be * found */ @When("^I wait \"(\\d+)\" seconds for (?:a|an|the) element found by( alias)? \"([^\"]*)\" to be displayed" + "(,? ignoring timeouts?)?") public void displaySimpleWaitStep( final String waitDuration, final String alias, final String selectorValue, final String ignoringTimeout) throws ExecutionException, InterruptedException { try { SIMPLE_WEB_ELEMENT_INTERACTION.getVisibleElementFoundBy( StringUtils.isNotBlank(alias), selectorValue, featureState, Long.parseLong(waitDuration)); } catch (final Exception ex) { /* Rethrow if we have not ignored errors */ if (StringUtils.isBlank(ignoringTimeout)) { throw ex; } } } /** * Waits the given amount of time for an element to not be displayed (i.e. to be visible) on the page. <p> * This is most useful when waiting for a page to load completely. You can use this step to pause the * script until some known element is visible, which is a good indication that the page has loaded * completely. * * @param waitDuration The maximum amount of time to wait for * @param alias If this word is found in the step, it means the selectorValue is found from the * data set. * @param selectorValue The value used in conjunction with the selector to match the element. If alias * was set, this value is found from the data set. Otherwise it is a literal * value. * @param ignoringTimeout include this text to continue the script in the event that the element can't be * found */ @When("^I wait \"(\\d+)\" seconds for (?:a|an|the) element found by( alias)? \"([^\"]*)\" to not be displayed" + "(,? ignoring timeouts?)?") public void notDisplaySimpleWaitStep( final String waitDuration, final String alias, final String selectorValue, final String ignoringTimeout) throws ExecutionException, InterruptedException { try { SIMPLE_WEB_ELEMENT_INTERACTION.getVisibleElementFoundBy( StringUtils.isNotBlank(alias), selectorValue, featureState, Long.parseLong(waitDuration)); } catch (final Exception ex) { /* Rethrow if we have not ignored errors */ if (StringUtils.isBlank(ignoringTimeout)) { throw ex; } } } /** * Waits the given amount of time for an element to be displayed (i.e. to be visible) on the page. <p> * This is most useful when waiting for a page to load completely. You can use this step to pause the * script until some known element is visible, which is a good indication that the page has loaded * completely. * * @param waitDuration The maximum amount of time to wait for * @param selector Either ID, class, xpath, name or css selector * @param alias If this word is found in the step, it means the selectorValue is found from the * data set. * @param selectorValue The value used in conjunction with the selector to match the element. If alias * was set, this value is found from the data set. Otherwise it is a literal * value. * @param ignoringTimeout include this text to continue the script in the event that the element can't be * found */ @When("^I wait \"(\\d+)\" seconds for (?:a|an|the) element with " + "(?:a|an|the) (ID|class|xpath|name|css selector)( alias)? of \"([^\"]*)\" to be displayed" + "(,? ignoring timeouts?)?") public void displayWaitStep( final String waitDuration, final String selector, final String alias, final String selectorValue, final String ignoringTimeout) { final WebDriver webDriver = State.THREAD_DESIRED_CAPABILITY_MAP.getWebDriverForThread(); final By by = GET_BY.getBy(selector, StringUtils.isNotBlank(alias), selectorValue, featureState); final WebDriverWait wait = new WebDriverWait( webDriver, Integer.parseInt(waitDuration)); try { wait.until(ExpectedConditions.visibilityOfElementLocated(by)); } catch (final TimeoutException ex) { /* Rethrow if we have not ignored errors */ if (StringUtils.isBlank(ignoringTimeout)) { throw ex; } } } /** * Waits the given amount of time for an element to be displayed (i.e. to be visible) on the page. <p> * This is most useful when waiting for a page to load completely. You can use this step to pause the * script until some known element is visible, which is a good indication that the page has loaded * completely. * * @param waitDuration The maximum amount of time to wait for * @param selector Either ID, class, xpath, name or css selector * @param alias If this word is found in the step, it means the selectorValue is found from the * data set. * @param selectorValue The value used in conjunction with the selector to match the element. If alias * was set, this value is found from the data set. Otherwise it is a literal * value. * @param ignoringTimeout include this text to continue the script in the event that the element can't be * found */ @When("^I wait \"(\\d+)\" seconds for (?:a|an|the) element with " + "(?:a|an|the) (ID|class|xpath|name|css selector)( alias)? of \"([^\"]*)\" to not be displayed" + "(,? ignoring timeouts?)?") public void notDisplayWaitStep( final String waitDuration, final String selector, final String alias, final String selectorValue, final String ignoringTimeout) { final WebDriver webDriver = State.THREAD_DESIRED_CAPABILITY_MAP.getWebDriverForThread(); final By by = GET_BY.getBy(selector, StringUtils.isNotBlank(alias), selectorValue, featureState); final WebDriverWait wait = new WebDriverWait( webDriver, Integer.parseInt(waitDuration)); try { final boolean result = wait.until( ExpectedConditions.not(ExpectedConditions.visibilityOfAllElementsLocatedBy(by))); if (!result) { throw new TimeoutException( "Gave up after waiting " + Integer.parseInt(waitDuration) + " seconds for the element to not be displayed"); } } catch (final TimeoutException ex) { /* Rethrow if we have not ignored errors */ if (StringUtils.isBlank(ignoringTimeout)) { throw ex; } } } /** * Waits the given amount of time for an element to be clickable on the page. <p> This is most * useful when waiting for an element to be in a state where it can be interacted with. * * @param waitDuration The maximum amount of time to wait for * @param alias If this word is found in the step, it means the selectorValue is found from the * data set. * @param selectorValue The value used in conjunction with the selector to match the element. If alias * was set, this value is found from the data set. Otherwise it is a literal * value. * @param ignoringTimeout include this text to continue the script in the event that the element can't be * found */ @When("^I wait \"(\\d+)\" seconds for (?:a|an|the) element found by" + "( alias)? \"([^\"]*)\" to be clickable(,? ignoring timeouts?)?") public void clickWaitStep( final String waitDuration, final String alias, final String selectorValue, final String ignoringTimeout) throws ExecutionException, InterruptedException { try { SIMPLE_WEB_ELEMENT_INTERACTION.getClickableElementFoundBy( StringUtils.isNotBlank(alias), selectorValue, featureState, Long.parseLong(waitDuration)); } catch (final WebElementException ex) { /* Rethrow if we have not ignored errors */ if (StringUtils.isBlank(ignoringTimeout)) { throw ex; } } } /** * Waits the given amount of time for an element to be clickable on the page. <p> This is most * useful when waiting for an element to be in a state where it can be interacted with. * * @param waitDuration The maximum amount of time to wait for * @param selector Either ID, class, xpath, name or css selector * @param alias If this word is found in the step, it means the selectorValue is found from the * data set. * @param selectorValue The value used in conjunction with the selector to match the element. If alias * was set, this value is found from the data set. Otherwise it is a literal * value. * @param ignoringTimeout include this text to continue the script in the event that the element can't be * found */ @When("^I wait \"(\\d+)\" seconds for (?:a|an|the) element with " + "(?:a|an|the) (ID|class|xpath|name|css selector)( alias)? of \"([^\"]*)\" to be clickable" + "(,? ignoring timeouts?)?") public void clickWaitStep( final String waitDuration, final String selector, final String alias, final String selectorValue, final String ignoringTimeout) { final WebDriver webDriver = State.THREAD_DESIRED_CAPABILITY_MAP.getWebDriverForThread(); final By by = GET_BY.getBy(selector, StringUtils.isNotBlank(alias), selectorValue, featureState); final WebDriverWait wait = new WebDriverWait( webDriver, Integer.parseInt(waitDuration)); try { wait.until(ExpectedConditions.elementToBeClickable(by)); } catch (final TimeoutException ex) { /* Rethrow if we have not ignored errors */ if (StringUtils.isBlank(ignoringTimeout)) { throw ex; } } } /** * Waits the given amount of time for an element to be clickable on the page. <p> This is most * useful when waiting for an element to be in a state where it can be interacted with. * * @param waitDuration The maximum amount of time to wait for * @param selector Either ID, class, xpath, name or css selector * @param alias If this word is found in the step, it means the selectorValue is found from the * data set. * @param selectorValue The value used in conjunction with the selector to match the element. If alias * was set, this value is found from the data set. Otherwise it is a literal * value. * @param ignoringTimeout include this text to continue the script in the event that the element can't be * found */ @When("^I wait \"(\\d+)\" seconds for (?:a|an|the) element with " + "(?:a|an|the) (ID|class|xpath|name|css selector)( alias)? of \"([^\"]*)\" to not be clickable" + "(,? ignoring timeouts?)?") public void notClickWaitStep( final String waitDuration, final String selector, final String alias, final String selectorValue, final String ignoringTimeout) { final WebDriver webDriver = State.THREAD_DESIRED_CAPABILITY_MAP.getWebDriverForThread(); final By by = GET_BY.getBy(selector, StringUtils.isNotBlank(alias), selectorValue, featureState); final WebDriverWait wait = new WebDriverWait( webDriver, Integer.parseInt(waitDuration)); try { final boolean result = wait.until( ExpectedConditions.not(ExpectedConditions.elementToBeClickable(by))); if (!result) { throw new TimeoutException( "Gave up after waiting " + Integer.parseInt(waitDuration) + " seconds for the element to not be clickable"); } } catch (final TimeoutException ex) { /* Rethrow if we have not ignored errors */ if (StringUtils.isBlank(ignoringTimeout)) { throw ex; } } } /** * Waits the given amount of time for an element to be placed in the DOM. Note that the element does not * have to be visible, just present in the HTML. <p> This is most useful when waiting for a page to load * completely. You can use this step to pause the script until some known element is visible, which is a * good indication that the page has loaded completely. * * @param waitDuration The maximum amount of time to wait for * @param alias If this word is found in the step, it means the selectorValue is found from the * data set. * @param selectorValue The value used in conjunction with the selector to match the element. If alias * was set, this value is found from the data set. Otherwise it is a literal * value. * @param ignoringTimeout Include this text to ignore a timeout while waiting for the element to be * present */ @When("^I wait \"(\\d+)\" seconds for (?:a|an|the) element found by( alias)? \"([^\"]*)\" " + "to be present(,? ignoring timeouts?)?") public void presentSimpleWaitStep( final String waitDuration, final String alias, final String selectorValue, final String ignoringTimeout) throws ExecutionException, InterruptedException { try { SIMPLE_WEB_ELEMENT_INTERACTION.getPresenceElementFoundBy( StringUtils.isNotBlank(alias), selectorValue, featureState, Long.parseLong(waitDuration)); } catch (final WebElementException ex) { /* Rethrow if we have not ignored errors */ if (StringUtils.isBlank(ignoringTimeout)) { throw ex; } } } /** * Waits the given amount of time for an element to be placed in the DOM. Note that the element does not * have to be visible, just present in the HTML. <p> This is most useful when waiting for a page to load * completely. You can use this step to pause the script until some known element is visible, which is a * good indication that the page has loaded completely. * * @param waitDuration The maximum amount of time to wait for * @param selector Either ID, class, xpath, name or css selector * @param alias If this word is found in the step, it means the selectorValue is found from the * data set. * @param selectorValue The value used in conjunction with the selector to match the element. If alias * was set, this value is found from the data set. Otherwise it is a literal * value. * @param ignoringTimeout Include this text to ignore a timeout while waiting for the element to be * present */ @When("^I wait \"(\\d+)\" seconds for (?:a|an|the) element with (?:a|an|the) " + "(ID|class|xpath|name|css selector)( alias)? of \"([^\"]*)\" " + "to be present(,? ignoring timeouts?)?") public void presentWaitStep( final String waitDuration, final String selector, final String alias, final String selectorValue, final String ignoringTimeout) { final WebDriver webDriver = State.THREAD_DESIRED_CAPABILITY_MAP.getWebDriverForThread(); final By by = GET_BY.getBy(selector, StringUtils.isNotBlank(alias), selectorValue, featureState); final WebDriverWait wait = new WebDriverWait( webDriver, Integer.parseInt(waitDuration)); try { wait.until(ExpectedConditions.presenceOfElementLocated(by)); } catch (final TimeoutException ex) { /* Rethrow if we have not ignored errors */ if (StringUtils.isBlank(ignoringTimeout)) { throw ex; } } } /** * Waits the given amount of time for an element to be placed in the DOM. Note that the element does not * have to be visible, just present in the HTML. <p> This is most useful when waiting for a page to load * completely. You can use this step to pause the script until some known element is visible, which is a * good indication that the page has loaded completely. * * @param waitDuration The maximum amount of time to wait for * @param selector Either ID, class, xpath, name or css selector * @param alias If this word is found in the step, it means the selectorValue is found from the * data set. * @param selectorValue The value used in conjunction with the selector to match the element. If alias * was set, this value is found from the data set. Otherwise it is a literal * value. * @param ignoringTimeout Include this text to ignore a timeout while waiting for the element to be * present */ @When("^I wait \"(\\d+)\" seconds for (?:a|an|the) element with (?:a|an|the) " + "(ID|class|xpath|name|css selector)( alias)? of \"([^\"]*)\" " + "to not be present(,? ignoring timeouts?)?") public void notPresentWaitStep( final String waitDuration, final String selector, final String alias, final String selectorValue, final String ignoringTimeout) { final WebDriver webDriver = State.THREAD_DESIRED_CAPABILITY_MAP.getWebDriverForThread(); final By by = GET_BY.getBy(selector, StringUtils.isNotBlank(alias), selectorValue, featureState); final WebDriverWait wait = new WebDriverWait( webDriver, Integer.parseInt(waitDuration)); try { final boolean result = wait.until( ExpectedConditions.not(ExpectedConditions.presenceOfAllElementsLocatedBy(by))); if (!result) { throw new TimeoutException( "Gave up after waiting " + Integer.parseInt(waitDuration) + " seconds for the element to not be present"); } } catch (final TimeoutException ex) { /* Rethrow if we have not ignored errors */ if (StringUtils.isBlank(ignoringTimeout)) { throw ex; } } } /** * Waits the given amount of time for a link with the supplied text to be placed in the DOM. Note that the * element does not have to be visible just present in the HTML. * * @param waitDuration The maximum amount of time to wait for * @param alias If this word is found in the step, it means the linkContent is found from the * data set. * @param linkContent The text content of the link we are wait for */ @When("^I wait \"(\\d+)\" seconds for a link with the text content of" +"( alias) \"([^\"]*)\" to be present(,? ignoring timeouts?)?") public void presentLinkStep( final String waitDuration, final String alias, final String linkContent, final String ignoringTimeout) { try { final WebDriver webDriver = State.THREAD_DESIRED_CAPABILITY_MAP.getWebDriverForThread(); final String content = AUTO_ALIAS_UTILS.getValue( linkContent, StringUtils.isNotBlank(alias), featureState); final WebDriverWait wait = new WebDriverWait( webDriver, Integer.parseInt(waitDuration)); wait.until(ExpectedConditions.presenceOfElementLocated(By.linkText(content))); } catch (final TimeoutException ex) { /* Rethrow if we have not ignored errors */ if (StringUtils.isBlank(ignoringTimeout)) { throw ex; } } } /** * Waits the given amount of time for a link with the supplied text to be placed in the DOM. Note that the * element does not have to be visible just present in the HTML. * * @param waitDuration The maximum amount of time to wait for * @param alias If this word is found in the step, it means the linkContent is found from the * data set. * @param linkContent The text content of the link we are wait for */ @When("^I wait \"(\\d+)\" seconds for a link with the text content of" + "( alias) \"([^\"]*)\" to not be present(,? ignoring timeouts?)?") public void notPresentLinkStep( final String waitDuration, final String alias, final String linkContent, final String ignoringTimeout) { try { final WebDriver webDriver = State.THREAD_DESIRED_CAPABILITY_MAP.getWebDriverForThread(); final String content = AUTO_ALIAS_UTILS.getValue( linkContent, StringUtils.isNotBlank(alias), featureState); final WebDriverWait wait = new WebDriverWait( webDriver, Integer.parseInt(waitDuration)); final boolean result = wait.until( ExpectedConditions.not(ExpectedConditions.presenceOfAllElementsLocatedBy(By.linkText(content)))); if (!result) { throw new TimeoutException( "Gave up after waiting " + Integer.parseInt(waitDuration) + " seconds for the element to not be present"); } } catch (final TimeoutException ex) { /* Rethrow if we have not ignored errors */ if (StringUtils.isBlank(ignoringTimeout)) { throw ex; } } } /** * Waits the given amount of time for an element with the supplied attribute and attribute value to be displayed * (i.e. to be visible) on the page. * * @param waitDuration The maximum amount of time to wait for * @param attribute The attribute to use to select the element with * @param alias If this word is found in the step, it means the selectorValue is found from the data set. * @param selectorValue The value used in conjunction with the selector to match the element. If alias was set, this * value is found from the data set. Otherwise it is a literal value. * @param ignoringTimeout Include this text to ignore a timeout while waiting for the element to be present */ @When("^I wait \"(\\d+)\" seconds for (?:a|an|the) element with (?:a|an|the) attribute of \"([^\"]*)\" " + "equal to( alias)? \"([^\"]*)\" to be displayed(,? ignoring timeouts?)?") public void displayAttrWait( final String waitDuration, final String attribute, final String alias, final String selectorValue, final String ignoringTimeout) { final String attributeValue = AUTO_ALIAS_UTILS.getValue( selectorValue, StringUtils.isNotBlank(alias), featureState); try { final WebDriver webDriver = State.THREAD_DESIRED_CAPABILITY_MAP.getWebDriverForThread(); final WebDriverWait wait = new WebDriverWait( webDriver, Integer.parseInt(waitDuration)); wait.until(ExpectedConditions.visibilityOfElementLocated( By.cssSelector("[" + attribute + "='" + attributeValue + "']"))); } catch (final TimeoutException ex) { /* Rethrow if we have not ignored errors */ if (StringUtils.isBlank(ignoringTimeout)) { throw ex; } } } /** * Waits the given amount of time for an element with the supplied attribute and attribute value to be displayed * (i.e. to be visible) on the page. * * @param waitDuration The maximum amount of time to wait for * @param attribute The attribute to use to select the element with * @param alias If this word is found in the step, it means the selectorValue is found from the data set. * @param selectorValue The value used in conjunction with the selector to match the element. If alias was set, this * value is found from the data set. Otherwise it is a literal value. * @param ignoringTimeout Include this text to ignore a timeout while waiting for the element to be present */ @When("^I wait \"(\\d+)\" seconds for (?:a|an|the) element with (?:a|an|the) attribute of \"([^\"]*)\" " + "equal to( alias)? \"([^\"]*)\" to not be displayed(,? ignoring timeouts?)?") public void notDisplayAttrWait( final String waitDuration, final String attribute, final String alias, final String selectorValue, final String ignoringTimeout) { final String attributeValue = AUTO_ALIAS_UTILS.getValue( selectorValue, StringUtils.isNotBlank(alias), featureState); try { final WebDriver webDriver = State.THREAD_DESIRED_CAPABILITY_MAP.getWebDriverForThread(); final WebDriverWait wait = new WebDriverWait( webDriver, Integer.parseInt(waitDuration)); final boolean result = wait.until( ExpectedConditions.not(ExpectedConditions.visibilityOfAllElementsLocatedBy( By.cssSelector("[" + attribute + "='" + attributeValue + "']")))); if (!result) { throw new TimeoutException( "Gave up after waiting " + Integer.parseInt(waitDuration) + " seconds for the element to not be displayed"); } } catch (final TimeoutException ex) { /* Rethrow if we have not ignored errors */ if (StringUtils.isBlank(ignoringTimeout)) { throw ex; } } } /** * Waits the given amount of time for an element with the supplied attribute and attribute value to be displayed * (i.e. to be visible) on the page. * * @param waitDuration The maximum amount of time to wait for * @param attribute The attribute to use to select the element with * @param alias If this word is found in the step, it means the selectorValue is found from the data set. * @param selectorValue The value used in conjunction with the selector to match the element. If alias was set, this * value is found from the data set. Otherwise it is a literal value. * @param ignoringTimeout Include this text to ignore a timeout while waiting for the element to be present */ @When("^I wait \"(\\d+)\" seconds for (?:a|an|the) element with (?:a|an|the) attribute of \"([^\"]*)\" " + "equal to( alias)? \"([^\"]*)\" to be present(,? ignoring timeouts?)?") public void presentAttrWait( final String waitDuration, final String attribute, final String alias, final String selectorValue, final String ignoringTimeout) { final String attributeValue = AUTO_ALIAS_UTILS.getValue( selectorValue, StringUtils.isNotBlank(alias), featureState); try { final WebDriver webDriver = State.THREAD_DESIRED_CAPABILITY_MAP.getWebDriverForThread(); final WebDriverWait wait = new WebDriverWait( webDriver, Integer.parseInt(waitDuration)); wait.until(ExpectedConditions.presenceOfElementLocated( By.cssSelector("[" + attribute + "='" + attributeValue + "']"))); } catch (final TimeoutException ex) { /* Rethrow if we have not ignored errors */ if (StringUtils.isBlank(ignoringTimeout)) { throw ex; } } } /** * Waits the given amount of time for an element with the supplied attribute and attribute value to be displayed * (i.e. to be visible) on the page. * * @param waitDuration The maximum amount of time to wait for * @param attribute The attribute to use to select the element with * @param alias If this word is found in the step, it means the selectorValue is found from the data set. * @param selectorValue The value used in conjunction with the selector to match the element. If alias was set, this * value is found from the data set. Otherwise it is a literal value. * @param ignoringTimeout Include this text to ignore a timeout while waiting for the element to be present */ @When("^I wait \"(\\d+)\" seconds for (?:a|an|the) element with (?:a|an|the) attribute of \"([^\"]*)\" " + "equal to( alias)? \"([^\"]*)\" to not be present(,? ignoring timeouts?)?") public void notPresentAttrWait( final String waitDuration, final String attribute, final String alias, final String selectorValue, final String ignoringTimeout) { final String attributeValue = AUTO_ALIAS_UTILS.getValue( selectorValue, StringUtils.isNotBlank(alias), featureState); try { final WebDriver webDriver = State.THREAD_DESIRED_CAPABILITY_MAP.getWebDriverForThread(); final WebDriverWait wait = new WebDriverWait( webDriver, Integer.parseInt(waitDuration)); final boolean result = wait.until( ExpectedConditions.not(ExpectedConditions.presenceOfAllElementsLocatedBy( By.cssSelector("[" + attribute + "='" + attributeValue + "']")))); if (!result) { throw new TimeoutException( "Gave up after waiting " + Integer.parseInt(waitDuration) + " seconds for the element to not be present"); } } catch (final TimeoutException ex) { /* Rethrow if we have not ignored errors */ if (StringUtils.isBlank(ignoringTimeout)) { throw ex; } } } }
package bakersoftware.maven_replacer_plugin; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; /** * Goal replaces token with value inside file * * @goal replace * * @phase compile */ public class ReplacerMojo extends AbstractMojo implements StreamFactory { private static final String LINE_SEPARATOR = System.getProperty("line.separator"); /** * File to check and replace tokens * * @parameter expression="" */ private String file; /** * Token * * @parameter expression="" */ private String token; /** * Ignore missing files * * @parameter expression="" */ private boolean ignoreMissingFile; /** * Value to replace token with * * @parameter expression="" */ private String value; /** * Token uses regex * * @parameter expression="" */ private boolean regex = true; /** * Output to another file * * @parameter expression="" */ private String outputFile; public void execute() throws MojoExecutionException { try { if (ignoreMissingFile && !fileExists(file)) { getLog().info("Ignoring missing file"); return; } getLog().info("Replacing " + token + " with " + value + " in " + file); getTokenReplacer().replaceTokens(token, value, isRegex()); } catch (IOException e) { throw new MojoExecutionException(e.getMessage()); } } public boolean isRegex() { return regex; } public void setRegex(boolean regex) { this.regex = regex; } private boolean fileExists(String filename) { return new File(filename).exists(); } public TokenReplacer getTokenReplacer() { return new TokenReplacer(this, LINE_SEPARATOR); } public void setFile(String file) { this.file = file; } public void setToken(String token) { this.token = token; } public void setValue(String value) { this.value = value; } public void setIgnoreMissingFile(boolean ignoreMissingFile) { this.ignoreMissingFile = ignoreMissingFile; } public InputStream getNewInputStream() { try { return new FileInputStream(file); } catch (FileNotFoundException e) { throw new RuntimeException(e); } } public OutputStream getNewOutputStream() { try { if (outputFile != null) { if (!fileExists(outputFile)) { ensureFolderStructureExists(outputFile); } return new FileOutputStream(outputFile); } else { return new FileOutputStream(file); } } catch (Exception e) { throw new RuntimeException(e); } } private void ensureFolderStructureExists(String file) throws MojoExecutionException { File outputFile = new File(file); if (!outputFile.isDirectory()) { File parentPath = new File(outputFile.getParent()); if (!parentPath.exists()) { parentPath.mkdirs(); } } else { String errorMsg = "Parameter outputFile cannot be a directory: " + file; throw new MojoExecutionException(errorMsg); } } public String getOutputFile() { return outputFile; } public void setOutputFile(String outputFile) { this.outputFile = outputFile; } }
package cn.kunter.common.generator.main; import java.util.List; import cn.kunter.common.generator.entity.Table; import cn.kunter.common.generator.make.GetTableConfig; import cn.kunter.common.generator.make.MakeBaseXml; import cn.kunter.common.generator.make.MakeEntity; import cn.kunter.common.generator.make.MakeExample; import cn.kunter.common.generator.make.MakeMyBatisConfig; import cn.kunter.common.generator.make.MakeXml; import cn.kunter.common.generator.make.service.MakeDao; import cn.kunter.common.generator.make.service.MakeService; import cn.kunter.common.generator.make.service.MakeServiceImpl; /** * @author yangziran * @version 1.0 20141020 */ public class GeneratorService { public static void main(String[] args) throws Exception { List<Table> tables = GetTableConfig.getTableConfig(); for (final Table table : tables) { Thread thread = new Thread(new Runnable() { public void run() { try { MakeEntity.makerEntity(table); MakeExample.makerExample(table); MakeBaseXml.makerBaseXml(table); MakeXml.makerXml(table); MakeDao.makerDao(table); MakeService.makeService(table); MakeServiceImpl.makeService(table); } catch (Exception e) { e.printStackTrace(); } } }); thread.start(); } MakeMyBatisConfig.makerMyBatisConfig(tables); } }
package codechicken.lib.render.buffer; import codechicken.lib.math.MathHelper; import codechicken.lib.texture.TextureUtils; import codechicken.lib.vec.uv.UV; import codechicken.lib.util.VectorUtils; import codechicken.lib.util.VertexDataUtils; import codechicken.lib.vec.Vector3; import com.google.common.collect.ImmutableList; import net.minecraft.client.renderer.VertexBuffer; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.renderer.vertex.VertexFormat; import net.minecraft.util.EnumFacing; import net.minecraftforge.client.model.pipeline.LightUtil; import net.minecraftforge.fml.common.FMLLog; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedList; import java.util.List; public class BakingVertexBuffer extends VertexBuffer { private HashMap<Integer, TextureAtlasSprite> spriteMap; private boolean useSprites = true; private boolean useDiffuseLighting = true; private static ThreadLocal<BakingVertexBuffer> threadBuffers = new ThreadLocal<BakingVertexBuffer>() { @Override protected BakingVertexBuffer initialValue() { return new BakingVertexBuffer(0x200000); } }; public static BakingVertexBuffer create() { return threadBuffers.get(); } private BakingVertexBuffer(int bufferSizeIn) { super(bufferSizeIn); } @Override public void begin(int glMode, VertexFormat format) { if (glMode != 7) { throw new IllegalArgumentException("Unable to bake GL Mode, only Quads supported! To bake triangles pipe through CCQuad then quadulate."); } super.begin(glMode, format); } @Override public void reset() { spriteMap = new HashMap<Integer, TextureAtlasSprite>(); useSprites = true; useDiffuseLighting = true; super.reset(); } /** * Sets the sprite for a specific vertex. * * @param sprite The sprite to set. */ public BakingVertexBuffer setSprite(TextureAtlasSprite sprite) { spriteMap.put(MathHelper.floor(getVertexCount() / 4D), sprite); return this; } /** * Sets the baker to ignore all sprite calculations and just use the missing icon. * This should only be used in cases where you know the quads are not going to be transformed by another mod at any point. */ public BakingVertexBuffer ignoreSprites() { useSprites = false; return this; } /** * Sets the baker to use any set vertex range sprite, or calculate sprites for a given UV mapping. * This is enabled by default. */ public BakingVertexBuffer useSprites() { useSprites = true; return this; } /** * Disables DiffuseLighting on quads. */ public BakingVertexBuffer dissableDiffuseLighting(){ useDiffuseLighting = false; return this; } /** * Enables DiffuseLighting on quads. * This is enabled by default. */ public BakingVertexBuffer enableDiffuseLighting(){ useDiffuseLighting = true; return this; } /** * Bakes the data inside the VertexBuffer to a baked quad. * * @return The list of quads baked. */ public List<BakedQuad> bake() { if (isDrawing) { FMLLog.info("CodeChickenLib", new IllegalStateException("Bake called before finishDrawing!"),"Someone is calling bake before finishDrawing!"); finishDrawing(); } State state = getVertexState(); VertexFormat format = state.getVertexFormat(); if (!format.hasUvOffset(0)) { throw new IllegalStateException("Unable to bake format that does not have UV mappings!"); } int[] rawBuffer = Arrays.copyOf(state.getRawBuffer(), state.getRawBuffer().length); List<BakedQuad> quads = new LinkedList<BakedQuad>(); TextureAtlasSprite sprite = TextureUtils.getMissingSprite(); int curr = 0; int next = format.getNextOffset(); int i = 0; while (rawBuffer.length >= next) { int[] quadData = Arrays.copyOfRange(rawBuffer, curr, next); Vector3 normal = new Vector3(); if (format.hasNormal()) { //Grab first normal. float[] normalData = new float[4]; LightUtil.unpack(quadData, normalData, format, 0, VertexDataUtils.getNormalElement(format)); normal = Vector3.fromArray(normalData); } else { //No normal provided in format, so we calculate. float[][] posData = new float[4][4]; for (int v = 0; v < 4; v++) { LightUtil.unpack(quadData, posData[v], format, v, VertexDataUtils.getPositionElement(format)); } normal.set(VectorUtils.calculateNormal(Vector3.fromArray(posData[0]), Vector3.fromArray(posData[1]), Vector3.fromArray(posData[3]))); } if (useSprites) { //Attempt to get sprite for vertex. if (spriteMap.containsKey(i)) { //Use provided sprite for vertex. sprite = spriteMap.get(i); } else { //Sprite not found for vertex, so we attempt to calculate the sprite. float[] uvData = new float[4]; LightUtil.unpack(quadData, uvData, format, 0, VertexDataUtils.getUVElement(format)); UV uv = new UV(uvData[0], uvData[1]); sprite = VertexDataUtils.getSpriteForUV(TextureUtils.getTextureMap(), uv); } } //Use normal to calculate facing. EnumFacing facing = VectorUtils.calcNormalSide(normal); if (facing == null){ facing = EnumFacing.UP; } BakedQuad quad = new BakedQuad(quadData, -1, facing, sprite, useDiffuseLighting, format); quads.add(quad); curr = next; next += format.getNextOffset(); i++; } return ImmutableList.copyOf(quads); } }
package com.akiban.sql.optimizer.plan; import com.akiban.sql.optimizer.plan.JoinNode.JoinType; import java.util.Iterator; import java.util.NoSuchElementException; /** Joins within a single {@link TableGroup} represented as a tree * whose structure mirrors that of the group. * This is an intermediate form between the original tree of joins based on the * original SQL syntax and the <code>Scan</code> and <code>Lookup</code> form * once an access path has been chosen. */ public class TableGroupJoinTree extends BaseJoinable implements Iterable<TableGroupJoinTree.TableGroupJoinNode> { public static class TableGroupJoinNode implements Iterable<TableGroupJoinNode> { TableSource table; TableGroupJoinNode parent, nextSibling, firstChild; JoinType parentJoinType; public TableGroupJoinNode(TableSource table) { this.table = table; } public TableSource getTable() { return table; } public TableGroupJoinNode getParent() { return parent; } public void setParent(TableGroupJoinNode parent) { this.parent = parent; } public TableGroupJoinNode getNextSibling() { return nextSibling; } public void setNextSibling(TableGroupJoinNode nextSibling) { this.nextSibling = nextSibling; } public TableGroupJoinNode getFirstChild() { return firstChild; } public void setFirstChild(TableGroupJoinNode firstChild) { this.firstChild = firstChild; } public JoinType getParentJoinType() { return parentJoinType; } public void setParentJoinType(JoinType parentJoinType) { this.parentJoinType = parentJoinType; } /** Find the given table in this (sub-)tree. */ public TableGroupJoinNode findTable(TableSource table) { for (TableGroupJoinNode node : this) { if (node.getTable() == table) { return node; } } return null; } @Override public Iterator<TableGroupJoinNode> iterator() { return new TableGroupJoinIterator(this); } } static class TableGroupJoinIterator implements Iterator<TableGroupJoinNode> { TableGroupJoinNode root, next; TableGroupJoinIterator(TableGroupJoinNode root) { this.root = this.next = root; } @Override public boolean hasNext() { return (next != null); } @Override public TableGroupJoinNode next() { if (next == null) throw new NoSuchElementException(); TableGroupJoinNode node = next; advance(); return node; } protected void advance() { TableGroupJoinNode node = next.getFirstChild(); if (node != null) { next = node; return; } while (true) { node = next.getNextSibling(); if (node != null) { next = node; return; } if (next == root) { next = null; return; } next = next.getParent(); } } @Override public void remove() { throw new UnsupportedOperationException(); } } private TableGroup group; private TableGroupJoinNode root; public TableGroupJoinTree(TableGroupJoinNode root) { this.group = root.getTable().getGroup(); this.root = root; } public TableGroup getGroup() { return group; } public TableGroupJoinNode getRoot() { return root; } @Override public Iterator<TableGroupJoinNode> iterator() { return new TableGroupJoinIterator(root); } public boolean accept(PlanVisitor v) { if (v.visitEnter(this)) { TableGroupJoinNode next = root; top: while (true) { if (v.visitEnter(next.getTable())) { TableGroupJoinNode node = next.getFirstChild(); if (node != null) { next = node; continue; } } while (true) { if (v.visitLeave(next.getTable())) { TableGroupJoinNode node = next.getNextSibling(); if (node != null) { next = node; break; } } if (next == root) break top; next = next.getParent(); } } } return v.visitLeave(this); } public String summaryString() { StringBuilder str = new StringBuilder(super.summaryString()); str.append("("); str.append(group); str.append(", "); summarizeJoins(str); str.append(")"); return str.toString(); } private void summarizeJoins(StringBuilder str) { for (TableGroupJoinNode node : this) { if (node != root) { str.append(" "); str.append(node.getParentJoinType()); str.append(" "); } str.append(node.getTable().getTable().getTable().getName().getTableName()); } } }
package com.antew.redditinpictures.sqlite; import android.net.Uri; import android.provider.BaseColumns; import com.antew.redditinpictures.pro.BuildConfig; public class RedditContract { private RedditContract() { } ; public static final String CONTENT_AUTHORITY = "com.antew.redditinpictures." + BuildConfig.FLAVOR; public static final int BASE = 1; public static final int REDDIT = 100; public static final int REDDIT_ID = 101; public static final int POSTS = 200; public static final int POSTS_ID = 201; public static final int LOGIN = 300; public static final int LOGIN_ID = 301; public static final int SUBREDDIT = 400; public static final int SUBREDDIT_ID = 401; public static final Uri BASE_CONTENT_URI = Uri.parse("content://" + CONTENT_AUTHORITY); public static final String PATH_POSTS = "posts"; public static final String PATH_REDDIT_DATA = "reddit_data"; public static final String PATH_SUBREDDITS = "subreddits"; public static final String PATH_LOGIN = "login"; public interface RedditDataColumns { String MODHASH = "modhash"; String AFTER = "after"; String BEFORE = "before"; } public interface LoginColumns { String USERNAME = "username"; String MODHASH = "modhash"; String COOKIE = "cookie"; String ERROR_MESSAGE = "errorMessage"; String SUCCESS = "success"; } /** * Container for Subreddit data */ public interface SubredditColumns { String DISPLAY_NAME = "displayName"; String HEADER_IMAGE = "headerImage"; String TITLE = "title"; String URL = "url"; String DESCRIPTION = "description"; String CREATED = "created"; String CREATED_UTC = "createdUtc"; String HEADER_SIZE = "headerSize"; String OVER_18 = "over18"; String SUBSCRIBERS = "subscribers"; String ACCOUNTS_ACTIVE = "accountsActive"; String PUBLIC_DESCRIPTION = "publicDescription"; String HEADER_TITLE = "headerTitle"; String SUBREDDIT_ID = "subredditId"; String NAME = "name"; String PRIORITY = "priority"; } public interface PostColumns { // String MODHASH = "modhash"; String DOMAIN = "domain"; String BANNED_BY = "bannedby"; String SUBREDDIT = "subreddit"; String SELFTEXT_HTML = "selfTextHtml"; String SELFTEXT = "selfText"; String VOTE = "vote"; String SAVED = "saved"; String POST_ID = "postId"; String CLICKED = "clicked"; String TITLE = "title"; String COMMENTS = "numComments"; String SCORE = "score"; String APPROVED_BY = "approvedBy"; String OVER_18 = "over18"; String HIDDEN = "hidden"; String THUMBNAIL = "thumbnail"; String SUBREDDIT_ID = "subredditId"; String AUTHOR_FLAIR_CSS_CLASS = "authorFlairCssClass"; String DOWNS = "downs"; String IS_SELF = "isSelf"; String PERMALINK = "permalink"; String NAME = "name"; String CREATED = "created"; String URL = "url"; String AUTHOR_FLAIR_TEXT = "authorFlairText"; String AUTHOR = "author"; String CREATED_UTC = "createdUtc"; String LINK_FLAIR_TEXT = "linkFlairText"; String DECODED_URL = "decodedUrl"; String LOADED_AT = "loadedAt"; } public static class Posts implements PostColumns, BaseColumns { public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_POSTS).build(); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.redditinpictures.postdata"; public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.redditinpictures.postdata"; public static final String DEFAULT_SORT = BaseColumns._ID + " ASC"; public static final String[] GRIDVIEW_PROJECTION = new String[] { _ID, URL, THUMBNAIL }; public static final String[] LISTVIEW_PROJECTION = new String[] { _ID, URL, THUMBNAIL, TITLE, SCORE, SELFTEXT, COMMENTS, SUBREDDIT, DOMAIN, AUTHOR, VOTE, NAME }; public static Uri buildPostDataUri(long postNumber) { return CONTENT_URI.buildUpon().appendPath(String.valueOf(postNumber)).build(); } } public static class Login implements LoginColumns, BaseColumns { public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_LOGIN).build(); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.redditinpictures.login"; public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.redditinpictures.login"; public static final String DEFAULT_SORT = BaseColumns._ID + " ASC"; public static Uri buildLoginUri(String username) { return CONTENT_URI.buildUpon().appendPath(username).build(); } } public static class RedditData implements RedditDataColumns, BaseColumns { public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_REDDIT_DATA).build(); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.redditinpictures.redditdata"; public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.redditinpictures.redditdata"; public static final String DEFAULT_SORT = BaseColumns._ID + " ASC"; public static Uri buildPostDataUri(String modhash) { return CONTENT_URI.buildUpon().appendPath(modhash).build(); } } public static class Subreddits implements SubredditColumns, BaseColumns { public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_SUBREDDITS).build(); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.redditinpictures.subreddits"; public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.redditinpictures.subreddits"; public static final String[] SUBREDDITS_PROJECTION = new String[] { _ID, DISPLAY_NAME, PRIORITY }; public static final String DEFAULT_SORT = PRIORITY + " DESC, " + DISPLAY_NAME + " COLLATE NOCASE ASC"; public static Uri buildSubredditUri(String displayName) { return CONTENT_URI.buildUpon().appendPath(displayName).build(); } } }
package com.bakerbeach.market.core.api.model; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; public interface ShopContext { static final String FLASH_TYPE = "FLASH"; static final String REGULAR_TYPE = "REGULAR"; String getShopType(); void setShopType(String type); ShopContext refine(Customer customer); String getShopCode(); void setShopCode(String shopCode); List<String> getGroupCodes(); void setGroupCodes(List<String> groupCodes); void setGroupCodesString(String groupCodesString); void setOrderSequenceRandomOffset(Long orderSequenceRandomOffset); Long getOrderSequenceRandomOffset(); void setOrderSequenceCode(String orderSequenceCode); String getOrderSequenceCode(); String getHost(); void setHost(String host); Integer getPort(); void setPort(Integer port); Integer getSecurePort(); void setSecurePort(Integer securePort); String getPath(); void setPath(String path); String getProtocol(); void setProtocol(String protocol); String getPageId(); void setPageId(String pageId); FilterList getFilterList(); void setFilterList(FilterList filterList); @Deprecated Map<String, Object> getData(); Map<String, Object> getRequestData(); Map<String, Object> getSessionData(); Map<String, Currency> getCurrencies(); String getDefaultCurrency(); void setData(Map<String, Object> data); String getCartCode(); void setCartCode(String cartCode); @Deprecated String getCurrency(); @Deprecated Boolean isCurrencySymbolAtFront(); @Deprecated String getCurrencySymbol(); Currency getCurrentCurrency(); List<Locale> getLocales(); void setLocales(List<Locale> locales); Locale getDefaultLocale(); void setDefaultLocale(Locale defaultLocale); Locale getCurrentLocale(); void setCurrentLocale(Locale currentLocale); List<String> getPriceGroups(); void setPriceGroups(List<String> priceGroups); String getDefaultPriceGroup(); void setDefaultPriceGroup(String defaultPriceGroup); String getCurrentPriceGroup(); void setCurrentPriceGroup(String currentPriceGroup); List<String> getValidCountries(); void setValidCountries(List<String> validCountries); boolean isCountryValid(String countryCode); String getCountryOfDelivery(); String getDefaultCountryOfDelivery(); void setDefaultCountryOfDelivery(String defaultCountryOfDelivery); String getDeviceClass(); void setDeviceClass(String deviceClass); Address getBillingAddress(); void setBillingAddress(Address billingAddress); Address getShippingAddress(); void setShippingAddress(Address shippingAddress); String getOrderStatus(); void setOrderStatus(String orderStatus); String getOrderId(); void setOrderId(String orderId); Set<Integer> getValidSteps(); void setValidSteps(Set<Integer> validSteps); String getRemoteIp(); void setRemoteIp(String remoteIp); void setSolrUrl(String solrUrl); String getSolrUrl(); String getAssortmentCode(); void setAssortmentCode(String assortmentCode); String getDevice(); void setDevice(String device); List<String> getNewsletterIds(); void setGtmId(String gtmId); String getGtmId(); String getRightCurrencySymbol(); String getLeftCurrencySymbol(); String getApplicationPath(); void setCurrency(String currency); }
package com.cisco.trex.stateful.api.lowlevel; /** Java implementation for TRex python sdk ASTFCmdRecv class */ public class ASTFCmdRecv extends ASTFCmd { private static final String NAME = "rx"; /** * construct * * @param minBytes minimal receive bytes * @param clear true if clear data */ public ASTFCmdRecv(long minBytes, boolean clear) { super(); fields.addProperty("name", NAME); fields.addProperty("min_bytes", minBytes); if (clear) { fields.addProperty("clear", true); } stream = true; } @Override public String getName() { return NAME; } }
package com.evanzeimet.testidmapper; import java.util.List; public abstract class AbstractTestIdMapper<ReferrerType, ReferencePersistenceType, ReferenceTestType, ReferencePersistenceIdType> { private IdProducer<ReferrerType, ReferencePersistenceType, ReferenceTestType, ReferencePersistenceIdType> idProducer; private IdMap<ReferencePersistenceIdType> idMap = new IdMap<>(); public AbstractTestIdMapper(IdProducer<ReferrerType, ReferencePersistenceType, ReferenceTestType, ReferencePersistenceIdType> idProducer) { this.idProducer = idProducer; } public void mapReferenceIds(List<? extends ReferencePersistenceType> persistedReferences, List<? extends ReferenceTestType> testReferences) { int persistedReferenceCount = persistedReferences.size(); int testReferenceCount = testReferences.size(); if (persistedReferenceCount != testReferenceCount) { String message = String.format("Found [%s] persisted references and [%s] test references. In order to map correctly, the persisted references and test references must map 1-to-1 in order", persistedReferenceCount, testReferenceCount); throw new IllegalArgumentException(message); } for (int i = 0; i < persistedReferenceCount; i++) { ReferencePersistenceType persistedReference = persistedReferences.get(i); ReferenceTestType testReference = testReferences.get(i); mapReferenceIds(persistedReference, testReference); } } protected void mapReferenceIds(ReferencePersistenceType persistedReference, ReferenceTestType testReference) { ReferencePersistenceIdType persistenceId = idProducer.produceReferencePersistenceId(persistedReference); String testId = idProducer.produceReferenceTestId(testReference); idMap.putPersistenceId(testId, persistenceId); } protected void setReferrerReferencePersistenceId(ReferrerType referrer) { String testId = idProducer.produceReferrerReferencedTestId(referrer); ReferencePersistenceIdType persistenceId = idMap.getPersistenceId(testId); idProducer.setReferrerReferencePersistenceId(referrer, persistenceId); } public void setReferrerReferencePersistenceIdsForTestIds(List<? extends ReferrerType> referrers) { for (ReferrerType referrer : referrers) { setReferrerReferencePersistenceId(referrer); } } }
package com.foundationdb.sql.pg; import com.foundationdb.ais.model.AkibanInformationSchema; import com.foundationdb.sql.server.ServerServiceRequirements; import com.foundationdb.sql.server.ServerSessionBase; import com.foundationdb.sql.server.ServerSessionMonitor; import com.foundationdb.sql.server.ServerStatement; import com.foundationdb.sql.server.ServerStatementCache; import com.foundationdb.sql.server.ServerValueDecoder; import com.foundationdb.sql.server.ServerValueEncoder; import com.foundationdb.sql.StandardException; import com.foundationdb.sql.parser.ParameterNode; import com.foundationdb.sql.parser.SQLParserException; import com.foundationdb.sql.parser.StatementNode; import com.foundationdb.qp.operator.QueryBindings; import com.foundationdb.qp.operator.QueryContext; import com.foundationdb.server.api.DDLFunctions; import com.foundationdb.server.error.*; import com.foundationdb.server.service.metrics.LongMetric; import com.foundationdb.server.service.monitor.CursorMonitor; import com.foundationdb.server.service.monitor.MonitorStage; import com.foundationdb.server.service.monitor.PreparedStatementMonitor; import com.foundationdb.util.MultipleCauseException; import com.foundationdb.util.tap.InOutTap; import com.foundationdb.util.tap.Tap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.ietf.jgss.*; import java.security.Principal; import java.security.PrivilegedAction; import java.security.SecureRandom; import javax.security.auth.Subject; import javax.security.auth.login.LoginException; import java.net.*; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; import java.io.*; import java.util.*; /** * Connection to a Postgres server client. * Runs in its own thread; has its own Main Session. * */ public class PostgresServerConnection extends ServerSessionBase implements PostgresServerSession, Runnable { private static final Logger logger = LoggerFactory.getLogger(PostgresServerConnection.class); private static final InOutTap READ_MESSAGE = Tap.createTimer("PostgresServerConnection: read message"); private static final InOutTap PROCESS_MESSAGE = Tap.createTimer("PostgresServerConnection: process message"); private static final String THREAD_NAME_PREFIX = "PostgresServer_Session-"; // Session ID appended private static final String MD5_SALT = "MD5_SALT"; private static final ErrorCode[] slowErrors = {ErrorCode.FDB_PAST_VERSION, ErrorCode.QUERY_TIMEOUT}; private final PostgresServer server; private boolean running = false, ignoreUntilSync = false; private Socket socket; private PostgresMessenger messenger; private ServerValueEncoder valueEncoder; private ServerValueDecoder valueDecoder; private OutputFormat outputFormat = OutputFormat.TABLE; private final int sessionId, secret; private int version; private Map<String,PostgresPreparedStatement> preparedStatements = new HashMap<>(); private Map<String,PostgresBoundQueryContext> boundPortals = new HashMap<>(); private ServerStatementCache<PostgresStatement> statementCache; private PostgresStatementParser[] unparsedGenerators; private PostgresStatementGenerator[] parsedGenerators; private Thread thread; private final LongMetric bytesInMetric, bytesOutMetric; private volatile String cancelForKillReason, cancelByUser; public PostgresServerConnection(PostgresServer server, Socket socket, int sessionId, int secret, LongMetric bytesInMetric, LongMetric bytesOutMetric, ServerServiceRequirements reqs) { super(reqs); this.server = server; this.socket = socket; this.sessionId = sessionId; this.secret = secret; this.bytesInMetric = bytesInMetric; this.bytesOutMetric = bytesOutMetric; this.sessionMonitor = new ServerSessionMonitor(PostgresServer.SERVER_TYPE, sessionId) { @Override public List<PreparedStatementMonitor> getPreparedStatements() { List<PreparedStatementMonitor> result = new ArrayList<>(preparedStatements.size()); synchronized (preparedStatements) { result.addAll(preparedStatements.values()); } return result; } @Override public List<CursorMonitor> getCursors() { List<CursorMonitor> result = new ArrayList<>(boundPortals.size()); synchronized (boundPortals) { result.addAll(boundPortals.values()); } return result; } }; sessionMonitor.setRemoteAddress(socket.getInetAddress().getHostAddress()); session = reqs.sessionService().createSession(); reqs.monitor().registerSessionMonitor(sessionMonitor, session); } public void start() { running = true; thread = new Thread(this, THREAD_NAME_PREFIX + sessionId); thread.start(); } public void stop() { running = false; // Can only wake up stream read by closing down socket. try { socket.close(); } catch (IOException ex) { } if ((thread != null) && (thread != Thread.currentThread())) { try { // Wait a bit, but don't hang up shutdown if thread is wedged. thread.join(500); if (thread.isAlive()) logger.warn("Connection {} still running", sessionId); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } thread = null; } } public void run() { try { createMessenger(); topLevel(); } catch (Exception ex) { if (running) logger.warn("Error in server", ex); } catch (Throwable ex) { logger.error("Error in server {}", ex); } finally { try { socket.close(); } catch (IOException ex) { } } } protected void createMessenger() throws IOException { messenger = new PostgresMessenger(socket) { @Override public void beforeIdle() throws IOException { super.beforeIdle(); sessionMonitor.enterStage(MonitorStage.IDLE); } @Override public void afterIdle() throws IOException { sessionMonitor.leaveStage(); super.afterIdle(); } @Override public void idle() { if (cancelForKillReason != null) { String msg = cancelForKillReason; cancelForKillReason = null; if (cancelByUser != null) { msg += " by " + cancelByUser; cancelByUser = null; } throw new ConnectionTerminatedException(msg); } } @Override public void bytesRead(int count) { bytesInMetric.increment(count); } @Override public void bytesWritten(int count) { bytesOutMetric.increment(count); } }; } protected void topLevel() throws IOException, Exception { logger.debug("Connect from {}" + socket.getRemoteSocketAddress()); boolean startupComplete = false; try { while (running) { READ_MESSAGE.in(); PostgresMessages type; try { type = messenger.readMessage(startupComplete); } catch (ConnectionTerminatedException ex) { logger.debug("About to terminate", ex); notifyClient(QueryContext.NotificationLevel.WARNING, ex.getCode(), ex.getShortMessage()); stop(); continue; } finally { READ_MESSAGE.out(); } PROCESS_MESSAGE.in(); if (ignoreUntilSync) { if ((type != PostgresMessages.EOF_TYPE) && (type != PostgresMessages.SYNC_TYPE)) continue; ignoreUntilSync = false; } long startNsec = System.nanoTime(); try { switch (type) { case EOF_TYPE: // EOF stop(); break; case SYNC_TYPE: readyForQuery(); break; case STARTUP_MESSAGE_TYPE: startupComplete = processStartupMessage(); break; case PASSWORD_MESSAGE_TYPE: processPasswordMessage(); break; case QUERY_TYPE: processQuery(); break; case PARSE_TYPE: processParse(); break; case BIND_TYPE: processBind(); break; case DESCRIBE_TYPE: processDescribe(); break; case EXECUTE_TYPE: processExecute(); break; case FLUSH_TYPE: processFlush(); break; case CLOSE_TYPE: processClose(); break; case TERMINATE_TYPE: processTerminate(); break; } } catch (QueryCanceledException ex) { InvalidOperationException nex = ex; boolean forKill = false; if (cancelForKillReason != null) { nex = new ConnectionTerminatedException(cancelForKillReason); nex.initCause(ex); cancelForKillReason = null; forKill = true; } logError(ErrorLogLevel.INFO, "Query {} canceled", nex); String msg = nex.getShortMessage(); if (cancelByUser != null) { if (!forKill) msg = "Query canceled"; msg += " by " + cancelByUser; cancelByUser = null; } sendErrorResponse(type, nex, nex.getCode(), msg); if (forKill) stop(); } catch (ConnectionTerminatedException ex) { logError(ErrorLogLevel.DEBUG, "Query {} terminated self", ex); sendErrorResponse(type, ex, ex.getCode(), ex.getShortMessage()); stop(); } catch (InvalidOperationException ex) { // Most likely a user error, not a system error. String fmt = logger.isDebugEnabled() ? "Error in query {}" : // Include stack trace "Error in query {} => {}"; // Just summarize error logError(ErrorLogLevel.WARN, fmt, ex); sendErrorResponse(type, ex, ex.getCode(), ex.getShortMessage()); } catch (MultipleCauseException ex) { int count = 1; int length = ex.getCauses().size(); for(Throwable throwable : ex.getCauses()) { if (throwable instanceof InvalidOperationException){ if(count == length){ logError(ErrorLogLevel.WARN, "Error in query {}", ex); sendErrorResponse(type, ((InvalidOperationException) throwable), ((InvalidOperationException) throwable).getCode(), ((InvalidOperationException) throwable).getShortMessage()); } else { notifyClient(QueryContext.NotificationLevel.WARNING, ((InvalidOperationException) throwable).getCode(), ((InvalidOperationException) throwable).getShortMessage()); } } else { if(count == length){ logError(ErrorLogLevel.WARN, "Unexpected runtime exception in query {}", ex); sendErrorResponse(type, (RuntimeException)throwable, ErrorCode.UNEXPECTED_EXCEPTION, ex.getMessage()); } else { notifyClient(QueryContext.NotificationLevel.WARNING, ErrorCode.UNEXPECTED_EXCEPTION, ex.getMessage()); } } count++; } } catch (Exception ex) { logError(ErrorLogLevel.WARN, "Unexpected error in query {}", ex); String message = (ex.getMessage() == null ? ex.getClass().toString() : ex.getMessage()); sendErrorResponse(type, ex, ErrorCode.UNEXPECTED_EXCEPTION, message); } catch (AssertionError ex) { logError(ErrorLogLevel.WARN, "Assertion in query {}", ex); throw ex; } finally { long stopNsec = System.nanoTime(); if (logger.isTraceEnabled()) { logger.trace("Executed {}: {} usec", type, (stopNsec - startNsec) / 1000); } } PROCESS_MESSAGE.out(); } } finally { if (transaction != null) { transaction.abort(); transaction = null; } server.removeConnection(sessionId); reqs.monitor().deregisterSessionMonitor(sessionMonitor, session); logger.debug("Disconnect"); } } private enum ErrorLogLevel { WARN, INFO, DEBUG }; private void logError(ErrorLogLevel level, String msg, Throwable ex) { String sql = null; if (sessionMonitor.getCurrentStatementEndTimeMillis() < 0) { // Current statement did not complete, include in error message. sql = sessionMonitor.getCurrentStatement(); if (sql != null) { sessionMonitor.endStatement(-1); // For system tables and for next time. if(reqs.monitor().isQueryLogEnabled() && ex instanceof InvalidOperationException){ for(ErrorCode slowError : slowErrors) { if (((InvalidOperationException) ex).getCode() == slowError) { reqs.monitor().logQuery(sessionMonitor); } } } } } if (sql == null) sql = ""; if (reqs.config().testing()) { level = ErrorLogLevel.DEBUG; } switch (level) { case DEBUG: logger.debug(msg, sql, ex); break; case INFO: logger.info(msg, sql, ex); break; case WARN: default: logger.warn(msg, sql, ex); break; } } protected void sendErrorResponse(PostgresMessages type, Exception exception, ErrorCode errorCode, String message) throws Exception { PostgresMessages.ErrorMode errorMode = type.errorMode(); if (errorMode == PostgresMessages.ErrorMode.NONE) { throw exception; } else if (version < 3<<16) { // V2 error message has no length field. We do not support // that version, except enough to tell the client that we // do not. OutputStream raw = messenger.getOutputStream(); raw.write(PostgresMessages.ERROR_RESPONSE_TYPE.code()); raw.write(message.getBytes(messenger.getEncoding())); raw.write(0); raw.flush(); } else { messenger.beginMessage(PostgresMessages.ERROR_RESPONSE_TYPE.code()); messenger.write('S'); messenger.writeString((errorMode == PostgresMessages.ErrorMode.FATAL) ? "FATAL" : "ERROR"); messenger.write('C'); messenger.writeString(errorCode.getFormattedValue()); messenger.write('M'); messenger.writeString(message); if (exception instanceof BaseSQLException) { int pos = ((BaseSQLException)exception).getErrorPosition(); if (pos > 0) { messenger.write('P'); messenger.writeString(Integer.toString(pos)); } } messenger.write(0); messenger.sendMessage(true); } switch (errorMode) { case FATAL: stop(); break; case EXTENDED: ignoreUntilSync = true; break; default: readyForQuery(); } } protected void readyForQuery() throws IOException { messenger.beginMessage(PostgresMessages.READY_FOR_QUERY_TYPE.code()); char mode = 'I'; // Idle if (isTransactionActive()) mode = isTransactionRollbackPending() ? 'E' : 'T'; messenger.writeByte(mode); messenger.sendMessage(true); } protected boolean processStartupMessage() throws IOException { int version = messenger.readInt(); switch (version) { case PostgresMessenger.VERSION_CANCEL: processCancelRequest(); return false; case PostgresMessenger.VERSION_SSL: processSSLMessage(); return false; default: this.version = version; if (version < 3<<16) { throw new UnsupportedProtocolException("protocol version " + (version >> 16)); } logger.debug("Version {}.{}", (version >> 16), (version & 0xFFFF)); } Properties clientProperties = new Properties(server.getProperties()); while (true) { String param = messenger.readString(); if (param.length() == 0) break; String value = messenger.readString(); clientProperties.put(param, value); } logger.debug("Properties: {}", clientProperties); setProperties(clientProperties); // TODO: Not needed right now and not a convenient time to // encounter schema lock from long-running DDL. // But see comment in initParser(): what if we wanted to warn // or error when schema does not exist? //updateAIS(null); switch (server.getAuthenticationType()) { case NONE: { String user = properties.getProperty("user"); logger.debug("Login {}", user); authenticationOkay(); } break; case CLEAR_TEXT: { messenger.beginMessage(PostgresMessages.AUTHENTICATION_TYPE.code()); messenger.writeInt(PostgresMessenger.AUTHENTICATION_CLEAR_TEXT); messenger.sendMessage(true); } break; case MD5: { byte[] salt = new byte[4]; new SecureRandom().nextBytes(salt); setAttribute(MD5_SALT, salt); messenger.beginMessage(PostgresMessages.AUTHENTICATION_TYPE.code()); messenger.writeInt(PostgresMessenger.AUTHENTICATION_MD5); messenger.write(salt); messenger.sendMessage(true); } break; case GSS: authenticationGSS(); break; } return true; } protected void processCancelRequest() throws IOException { int sessionId = messenger.readInt(); int secret = messenger.readInt(); PostgresServerConnection connection = server.getConnection(sessionId); if ((connection != null) && (secret == connection.secret)) { connection.cancelQuery(null, null); } stop(); // That's all for this connection. } protected void processSSLMessage() throws IOException { OutputStream raw = messenger.getOutputStream(); if (System.getProperty("javax.net.ssl.keyStore") == null) { // JSSE doesn't have a keystore; TLSv1 handshake is gonna fail. Deny support. raw.write('N'); raw.flush(); } else { // Someone seems to have configured for SSL. Wrap the // socket and start server mode negotiation. Client should // then use SSL socket to start regular server protocol. raw.write('S'); raw.flush(); SSLSocketFactory sslFactory = (SSLSocketFactory)SSLSocketFactory.getDefault(); SSLSocket sslSocket = (SSLSocket)sslFactory.createSocket(socket, socket.getLocalAddress().toString(), socket.getLocalPort(), true); socket = sslSocket; createMessenger(); sslSocket.setUseClientMode(false); sslSocket.startHandshake(); } } protected void processPasswordMessage() throws IOException { String user = properties.getProperty("user"); String pass = messenger.readString(); Principal principal = null; switch (server.getAuthenticationType()) { case NONE: break; case CLEAR_TEXT: principal = reqs.securityService() .authenticate(session, user, pass); break; case MD5: principal = reqs.securityService() .authenticate(session, user, pass, (byte[])attributes.remove(MD5_SALT)); break; } logger.debug("Login {}", (principal != null) ? principal : user); authenticationOkay(); sessionMonitor.setUserMonitor(reqs.monitor().getUserMonitor(user)); } // Currently supported subset given by Postgres 9.1. protected static final String[] INITIAL_STATUS_SETTINGS = { "client_encoding", "server_encoding", "server_version", "session_authorization", "DateStyle", "integer_datetimes", "standard_conforming_strings", "foundationdb_server" }; protected void authenticationOkay() throws IOException { { messenger.beginMessage(PostgresMessages.AUTHENTICATION_TYPE.code()); messenger.writeInt(PostgresMessenger.AUTHENTICATION_OK); messenger.sendMessage(); } for (String prop : INITIAL_STATUS_SETTINGS) { messenger.beginMessage(PostgresMessages.PARAMETER_STATUS_TYPE.code()); messenger.writeString(prop); messenger.writeString(getSessionSetting(prop)); messenger.sendMessage(); } { messenger.beginMessage(PostgresMessages.BACKEND_KEY_DATA_TYPE.code()); messenger.writeInt(sessionId); messenger.writeInt(secret); messenger.sendMessage(); } readyForQuery(); } protected void authenticationGSS() throws IOException { messenger.beginMessage(PostgresMessages.AUTHENTICATION_TYPE.code()); messenger.writeInt(PostgresMessenger.AUTHENTICATION_GSS); messenger.sendMessage(true); final Subject gssLogin; try { gssLogin = server.getGSSLogin(); } catch (LoginException ex) { throw new AuthenticationFailedException(ex); // or is this internal? } GSSName authenticated = Subject.doAs(gssLogin, new PrivilegedAction<GSSName>() { @Override public GSSName run() { return gssNegotation(gssLogin); } }); logger.debug("Login {}", authenticated); properties.setProperty("user", authenticated.toString()); authenticationOkay(); } protected GSSName gssNegotation(Subject gssLogin) { String serverName = null; Iterator<Principal> iter = gssLogin.getPrincipals().iterator(); if (iter.hasNext()) serverName = iter.next().getName(); try { GSSManager manager = GSSManager.getInstance(); GSSCredential serverCreds = manager.createCredential(manager.createName(serverName, null), GSSCredential.INDEFINITE_LIFETIME, new Oid("1.2.840.113554.1.2.2"), // krb5 GSSCredential.ACCEPT_ONLY); GSSContext serverContext = manager.createContext(serverCreds); do { switch (messenger.readMessage()) { case PASSWORD_MESSAGE_TYPE: break; default: throw new AuthenticationFailedException("Protocol error: not password message"); } byte[] token = messenger.getRawMessage(); // Note: not a String. token = serverContext.acceptSecContext(token, 0, token.length); if (token != null) { messenger.beginMessage(PostgresMessages.AUTHENTICATION_TYPE.code()); messenger.writeInt(PostgresMessenger.AUTHENTICATION_GSS_CONTINUE); messenger.write(token); // Again, no wrapping. messenger.sendMessage(true); } } while (!serverContext.isEstablished()); return serverContext.getSrcName(); } catch (GSSException ex) { throw new AuthenticationFailedException(ex); } catch (IOException ex) { throw new AkibanInternalException("Error reading message", ex); } } protected void processQuery() throws IOException { long startTime = System.currentTimeMillis(); String sql = messenger.readString(); logger.debug("Query: {}", sql); if (sql.length() == 0) { emptyQuery(); return; } sessionMonitor.startStatement(sql, startTime); PostgresQueryContext context = new PostgresQueryContext(this); QueryBindings bindings = context.createBindings(); // Empty of parameters. updateAIS(context); PostgresStatement pstmt = null; if (statementCache != null) pstmt = statementCache.get(sql); if (pstmt == null) { for (PostgresStatementParser parser : unparsedGenerators) { // Try special recognition first; only allowed to turn // into one statement. pstmt = parser.parse(this, sql, null); if (pstmt != null) { pstmt.setAISGeneration(ais.getGeneration()); break; } } } int rowsProcessed = 0; if (pstmt != null) { pstmt.sendDescription(context, false, false); rowsProcessed = executeStatementWithAutoTxn(pstmt, context, bindings, -1); } else { // Parse as a _list_ of statements and process each in turn. List<StatementNode> stmts; try { sessionMonitor.enterStage(MonitorStage.PARSE); stmts = parser.parseStatements(sql); } catch (SQLParserException ex) { throw new SQLParseException(ex); } catch (StandardException ex) { throw new SQLParserInternalException(ex); } finally { sessionMonitor.leaveStage(); } boolean singleStmt = (stmts.size() == 1); for (StatementNode stmt : stmts) { String stmtSQL; if (singleStmt) stmtSQL = sql; else stmtSQL = sql.substring(stmt.getBeginOffset(), stmt.getEndOffset() + 1); pstmt = generateStatementStub(stmtSQL, stmt, null, null); boolean local = beforeExecute(pstmt); boolean success = false; try { pstmt = finishGenerating(context, pstmt, stmtSQL, stmt, null, null); if ((statementCache != null) && singleStmt && pstmt.putInCache()) statementCache.put(stmtSQL, pstmt); pstmt.sendDescription(context, false, false); rowsProcessed = executeStatement(pstmt, context, bindings, -1); success = true; } finally { afterExecute(pstmt, local, success); } } } readyForQuery(); sessionMonitor.endStatement(rowsProcessed); logger.debug("Query complete: {} rows", rowsProcessed); if (reqs.monitor().isQueryLogEnabled()) { reqs.monitor().logQuery(sessionMonitor); } } protected void processParse() throws IOException { String stmtName = messenger.readString(); String sql = messenger.readString(); short nparams = messenger.readShort(); int[] paramTypes = new int[nparams]; for (int i = 0; i < nparams; i++) paramTypes[i] = messenger.readInt(); sessionMonitor.startStatement(sql, stmtName); logger.debug("Parse: {} = {}", stmtName, sql); PostgresQueryContext context = new PostgresQueryContext(this); updateAIS(context); PostgresStatement pstmt = null; if (statementCache != null) pstmt = statementCache.get(sql); // Verify the parameter types from the parse request match the // parameter requests from our potential cached statement // if they don't match, assume the statement isn't a match if (pstmt != null) { if (pstmt.getParameterTypes() != null && pstmt.getParameterTypes().length >= nparams){ for (int i = 0; i < nparams; i++ ) { if (pstmt.getParameterTypes()[i].getOid() != paramTypes[i]) { pstmt = null; break; } } } } if (pstmt == null) { for (PostgresStatementParser parser : unparsedGenerators) { pstmt = parser.parse(this, sql, null); if (pstmt != null) { pstmt.setAISGeneration(ais.getGeneration()); break; } } } if (pstmt == null) { StatementNode stmt; List<ParameterNode> params; try { sessionMonitor.enterStage(MonitorStage.PARSE); stmt = parser.parseStatement(sql); params = parser.getParameterList(); } catch (SQLParserException ex) { throw new SQLParseException(ex); } catch (StandardException ex) { throw new SQLParserInternalException(ex); } finally { sessionMonitor.leaveStage(); } pstmt = generateStatementStub(sql, stmt, params, paramTypes); boolean local = beforeExecute(pstmt); boolean success = false; try { pstmt = finishGenerating(context, pstmt, sql, stmt, params, paramTypes); success = true; } finally { afterExecute(pstmt, local, success); } if ((statementCache != null) && pstmt.putInCache()) { statementCache.put(sql, pstmt); } } PostgresPreparedStatement ppstmt = new PostgresPreparedStatement(this, stmtName, sql, pstmt, sessionMonitor.getCurrentStatementStartTimeMillis()); synchronized (preparedStatements) { preparedStatements.put(stmtName, ppstmt); } messenger.beginMessage(PostgresMessages.PARSE_COMPLETE_TYPE.code()); messenger.sendMessage(); } protected void processBind() throws IOException { String portalName = messenger.readString(); String stmtName = messenger.readString(); byte[][] params = null; boolean[] paramsBinary = null; { short nformats = messenger.readShort(); if (nformats > 0) { paramsBinary = new boolean[nformats]; for (int i = 0; i < nformats; i++) paramsBinary[i] = (messenger.readShort() == 1); } short nparams = messenger.readShort(); if (nparams > 0) { params = new byte[nparams][]; for (int i = 0; i < nparams; i++) { int len = messenger.readInt(); if (len < 0) continue; // Null byte[] param = new byte[len]; messenger.readFully(param, 0, len); params[i] = param; } } } boolean[] resultsBinary = null; boolean defaultResultsBinary = false; { short nresults = messenger.readShort(); if (nresults == 1) defaultResultsBinary = (messenger.readShort() == 1); else if (nresults > 0) { resultsBinary = new boolean[nresults]; for (int i = 0; i < nresults; i++) { resultsBinary[i] = (messenger.readShort() == 1); } defaultResultsBinary = resultsBinary[nresults-1]; } } logger.debug("Bind: {} = {}", stmtName, portalName); PostgresPreparedStatement pstmt = preparedStatements.get(stmtName); if (pstmt == null) throw new NoSuchPreparedStatementException(stmtName); PostgresStatement stmt = pstmt.getStatement(); boolean canSuspend = ((stmt instanceof PostgresCursorGenerator) && ((PostgresCursorGenerator<?>)stmt).canSuspend(this)); PostgresBoundQueryContext bound = new PostgresBoundQueryContext(this, pstmt, portalName, canSuspend, true); QueryBindings bindings = bound.createBindings(); if (params != null) { if (valueDecoder == null) valueDecoder = new ServerValueDecoder(typesTranslator(), messenger.getEncoding()); PostgresType[] parameterTypes = null; if (stmt instanceof PostgresBaseStatement) { PostgresDMLStatement dml = (PostgresDMLStatement)stmt; parameterTypes = dml.getParameterTypes(); } for (int i = 0; i < params.length; i++) { PostgresType pgType = null; if (parameterTypes != null) pgType = parameterTypes[i]; boolean binary = false; if ((paramsBinary != null) && (i < paramsBinary.length)) binary = paramsBinary[i]; valueDecoder.decodeValue(params[i], pgType, binary, bindings, i); } logger.debug("Bound params: {}", bindings); } bound.setBindings(bindings); bound.setColumnBinary(resultsBinary, defaultResultsBinary); PostgresBoundQueryContext prev; synchronized (boundPortals) { prev = boundPortals.put(portalName, bound); } if (prev != null) prev.close(); messenger.beginMessage(PostgresMessages.BIND_COMPLETE_TYPE.code()); messenger.sendMessage(); } protected void processDescribe() throws IOException{ byte source = messenger.readByte(); String name = messenger.readString(); PostgresStatement pstmt; PostgresQueryContext context; boolean params; switch (source) { case (byte)'S': pstmt = preparedStatements.get(name).getStatement(); if (pstmt == null) throw new NoSuchPreparedStatementException(name); context = new PostgresQueryContext(this); params = true; break; case (byte)'P': { PostgresBoundQueryContext bound = boundPortals.get(name); if (bound == null) throw new NoSuchCursorException(name); pstmt = bound.getStatement().getStatement(); context = bound; } params = false; break; default: throw new IOException("Unknown describe source: " + (char)source); } pstmt.sendDescription(context, true, params); } protected void processExecute() throws IOException { long startTime = System.currentTimeMillis(); String portalName = messenger.readString(); int maxrows = messenger.readInt(); logger.debug("Execute: {}", portalName); PostgresBoundQueryContext context = boundPortals.get(portalName); if (context == null) throw new NoSuchCursorException(portalName); QueryBindings bindings = context.getBindings(); PostgresPreparedStatement pstmt = context.getStatement(); sessionMonitor.startStatement(pstmt.getSQL(), pstmt.getName(), startTime); int rowsProcessed = executeStatementWithAutoTxn(pstmt.getStatement(), context, bindings, maxrows); sessionMonitor.endStatement(rowsProcessed); logger.debug("Execute complete: {} rows", rowsProcessed); if (reqs.monitor().isQueryLogEnabled()) { reqs.monitor().logQuery(sessionMonitor); } } protected void processFlush() throws IOException { messenger.flush(); } protected void processClose() throws IOException { byte source = messenger.readByte(); String name = messenger.readString(); switch (source) { case (byte)'S': deallocatePreparedStatement(name); break; case (byte)'P': closeBoundPortal(name); break; default: throw new IOException("Unknown describe source: " + (char)source); } messenger.beginMessage(PostgresMessages.CLOSE_COMPLETE_TYPE.code()); messenger.sendMessage(); } protected void processTerminate() throws IOException { stop(); } public void cancelQuery(String forKillReason, String byUser) { this.cancelForKillReason = forKillReason; this.cancelByUser = byUser; // A running query checks session state for query cancelation during Cursor.next() calls. If the // query is stuck in a blocking operation, then thread interruption should unstick it. Either way, // the query should eventually throw QueryCanceledException which will be caught by topLevel(). if (session != null) { session.cancelCurrentQuery(true); } if (thread != null) { thread.interrupt(); } } public void waitAndStop() { // Wait a little bit for the connection to stop itself. for (int i = 0; i < 5; i++) { if (!running) return; try { Thread.sleep(50); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); break; } } // Force stop. stop(); } // When the AIS changes, throw everything away, since it might // point to obsolete objects. protected void updateAIS(PostgresQueryContext context) { DDLFunctions ddl = reqs.dxl().ddlFunctions(); AkibanInformationSchema newAIS = ddl.getAIS(session); if ((ais != null) && (ais.getGeneration() == newAIS.getGeneration())) return; // Unchanged. ais = newAIS; rebuildCompiler(); } protected void rebuildCompiler() { Object parserKeys = initParser(); PostgresOperatorCompiler compiler; String format = getProperty("OutputFormat", "table"); if (format.equals("table")) outputFormat = OutputFormat.TABLE; else if (format.equals("json")) outputFormat = OutputFormat.JSON; else if (format.equals("json_with_meta_data")) outputFormat = OutputFormat.JSON_WITH_META_DATA; else throw new InvalidParameterValueException(format); switch (outputFormat) { case TABLE: default: compiler = PostgresOperatorCompiler.create(this, reqs.store()); break; case JSON: case JSON_WITH_META_DATA: compiler = PostgresJsonCompiler.create(this, reqs.store()); break; } initAdapters(compiler); unparsedGenerators = new PostgresStatementParser[] { new PostgresEmulatedMetaDataStatementParser(this), new PostgresEmulatedSessionStatementParser(this) }; parsedGenerators = new PostgresStatementGenerator[] { // Can be ordered by frequency so long as there is no overlap. compiler, new PostgresDDLStatementGenerator(this, compiler), new PostgresSessionStatementGenerator(this), new PostgresCallStatementGenerator(this), new PostgresExplainStatementGenerator(this), new PostgresServerStatementGenerator(this), new PostgresCursorStatementGenerator(this), new PostgresCopyStatementGenerator(this) }; statementCache = getStatementCache(); } protected ServerStatementCache<PostgresStatement> getStatementCache() { // Statement cache depends on some connection settings. return server.getStatementCache(Arrays.asList(parser.getFeatures(), defaultSchemaName, getProperty("OutputFormat", "table"), getProperty("optimizerDummySetting")), ais.getGeneration()); } @Override protected void sessionChanged() { if (parsedGenerators == null) return; // setAttribute() from generator's ctor. for (PostgresStatementParser parser : unparsedGenerators) { parser.sessionChanged(this); } for (PostgresStatementGenerator generator : parsedGenerators) { generator.sessionChanged(this); } statementCache = getStatementCache(); } protected PostgresStatement generateStatementStub(String sql, StatementNode stmt, List<ParameterNode> params, int[] paramTypes) { try { sessionMonitor.enterStage(MonitorStage.OPTIMIZE); for (PostgresStatementGenerator generator : parsedGenerators) { PostgresStatement pstmt = generator.generateStub(this, sql, stmt, params, paramTypes); if (pstmt != null) return pstmt; } } finally { sessionMonitor.leaveStage(); } throw new UnsupportedSQLException ("", stmt); } protected PostgresStatement finishGenerating(PostgresQueryContext context, PostgresStatement pstmt, String sql, StatementNode stmt, List<ParameterNode> params, int[] paramTypes) { try { sessionMonitor.enterStage(MonitorStage.OPTIMIZE); updateAIS(context); PostgresStatement newpstmt = pstmt.finishGenerating(this, sql, stmt, params, paramTypes); if (!newpstmt.hasAISGeneration()) newpstmt.setAISGeneration(ais.getGeneration()); return newpstmt; } finally { sessionMonitor.leaveStage(); } } protected int executeStatementWithAutoTxn(PostgresStatement pstmt, PostgresQueryContext context, QueryBindings bindings, int maxrows) throws IOException { boolean localTransaction = beforeExecute(pstmt); int rowsProcessed; boolean success = false; try { rowsProcessed = executeStatement(pstmt, context, bindings, maxrows); success = true; } finally { afterExecute(pstmt, localTransaction, success); sessionMonitor.leaveStage(); } return rowsProcessed; } protected int executeStatement(PostgresStatement pstmt, PostgresQueryContext context, QueryBindings bindings, int maxrows) throws IOException { int rowsProcessed; try { if (pstmt.getAISGenerationMode() == ServerStatement.AISGenerationMode.NOT_ALLOWED) { updateAIS(context); if (pstmt.getAISGeneration() != ais.getGeneration()) throw new StaleStatementException(); } session.setTimeoutAfterMillis(getQueryTimeoutMilli()); sessionMonitor.enterStage(MonitorStage.EXECUTE); rowsProcessed = pstmt.execute(context, bindings, maxrows); } finally { sessionMonitor.leaveStage(); } return rowsProcessed; } protected void emptyQuery() throws IOException { messenger.beginMessage(PostgresMessages.EMPTY_QUERY_RESPONSE_TYPE.code()); messenger.sendMessage(); readyForQuery(); } @Override public void prepareStatement(String name, String sql, StatementNode stmt, List<ParameterNode> params, int[] paramTypes) { long prepareTime = System.currentTimeMillis(); PostgresQueryContext context = new PostgresQueryContext(this); PostgresStatement pstmt = generateStatementStub(sql, stmt, params, paramTypes); boolean local = beforeExecute(pstmt); boolean success = false; try { pstmt = finishGenerating(context, pstmt, sql, stmt, params, paramTypes); success = true; } finally { afterExecute(pstmt, local, success); } PostgresPreparedStatement ppstmt = new PostgresPreparedStatement(this, name, sql, pstmt, prepareTime); synchronized (preparedStatements) { preparedStatements.put(name, ppstmt); } } @Override public int executePreparedStatement(PostgresExecuteStatement estmt, int maxrows) throws IOException { PostgresPreparedStatement pstmt = preparedStatements.get(estmt.getName()); if (pstmt == null) throw new NoSuchPreparedStatementException(estmt.getName()); PostgresQueryContext context = new PostgresQueryContext(this); QueryBindings bindings = context.createBindings(); estmt.setParameters(bindings); sessionMonitor.startStatement(pstmt.getSQL(), pstmt.getName()); pstmt.getStatement().sendDescription(context, false, false); int nrows = executeStatementWithAutoTxn(pstmt.getStatement(), context, bindings, maxrows); sessionMonitor.endStatement(nrows); return nrows; } @Override public void deallocatePreparedStatement(String name) { PostgresPreparedStatement pstmt; synchronized (preparedStatements) { pstmt = preparedStatements.remove(name); } } @Override public void declareStatement(String name, String sql, StatementNode stmt) { PostgresQueryContext context = new PostgresQueryContext(this); PostgresStatement pstmt = generateStatementStub(sql, stmt, null, null); boolean local = beforeExecute(pstmt); boolean success = false; try { pstmt = finishGenerating(context, pstmt, sql, stmt, null, null); success = true; } finally { afterExecute(pstmt, local, success); } PostgresPreparedStatement ppstmt; PostgresExecuteStatement estmt = null; if (pstmt instanceof PostgresExecuteStatement) { // DECLARE ... EXECUTE ... gets spliced out rather than // making a second prepared statement. estmt = (PostgresExecuteStatement)pstmt; ppstmt = preparedStatements.get(estmt.getName()); if (ppstmt == null) throw new NoSuchPreparedStatementException(estmt.getName()); pstmt = ppstmt.getStatement(); } else { ppstmt = new PostgresPreparedStatement(this, null, sql, pstmt, System.currentTimeMillis()); } if (!(pstmt instanceof PostgresCursorGenerator)) { throw new UnsupportedSQLException("DECLARE can only be used with a result-generating statement", stmt); } if (!((PostgresCursorGenerator<?>)pstmt).canSuspend(this)) { throw new UnsupportedSQLException("DECLARE can only be used within a transaction", stmt); } PostgresBoundQueryContext bound = new PostgresBoundQueryContext(this, ppstmt, name, true, false); QueryBindings bindings = bound.createBindings(); if (estmt != null) { estmt.setParameters(bindings); } bound.setBindings(bindings); PostgresBoundQueryContext prev; synchronized (boundPortals) { prev = boundPortals.put(name, bound); } if (prev != null) prev.close(); } @Override public int fetchStatement(String name, int count) throws IOException { PostgresBoundQueryContext bound = boundPortals.get(name); if (bound == null) throw new NoSuchCursorException(name); QueryBindings bindings = bound.getBindings(); PostgresPreparedStatement pstmt = bound.getStatement(); sessionMonitor.startStatement(pstmt.getSQL(), pstmt.getName()); pstmt.getStatement().sendDescription(bound, false, false); int nrows = executeStatementWithAutoTxn(pstmt.getStatement(), bound, bindings, count); sessionMonitor.endStatement(nrows); return nrows; } @Override public void closeBoundPortal(String name) { PostgresBoundQueryContext bound; synchronized (boundPortals) { bound = boundPortals.remove(name); } if (bound != null) bound.close(); } @Override public Date currentTime() { Date override = server.getOverrideCurrentTime(); if (override != null) return override; else return super.currentTime(); } @Override public void notifyClient(QueryContext.NotificationLevel level, ErrorCode errorCode, String message) throws IOException { if (shouldNotify(level)) { Object state = messenger.suspendMessage(); messenger.beginMessage(PostgresMessages.NOTICE_RESPONSE_TYPE.code()); messenger.write('S'); switch (level) { case WARNING: messenger.writeString("WARN"); break; case INFO: messenger.writeString("INFO"); break; case DEBUG: messenger.writeString("DEBUG"); break; // Other possibilities are "NOTICE" and "LOG". } if (errorCode != null) { messenger.write('C'); messenger.writeString(errorCode.getFormattedValue()); } messenger.write('M'); messenger.writeString(message); messenger.write(0); messenger.sendMessage(true); messenger.resumeMessage(state); } } /* PostgresServerSession */ @Override public int getVersion() { return version; } @Override public PostgresMessenger getMessenger() { return messenger; } @Override public OutputFormat getOutputFormat() { return outputFormat; } @Override public ServerValueEncoder getValueEncoder() { if (valueEncoder == null) valueEncoder = new ServerValueEncoder(typesTranslator(), messenger.getEncoding(), getZeroDateTimeBehavior(), getFormatOptions()); return valueEncoder; } /* ServerSession */ @Override protected boolean propertySet(String key, String value) { if ("client_encoding".equals(key)) { messenger.setEncoding(value); valueEncoder = null; // These depend on the encoding. valueDecoder = null; return true; } if ("OutputFormat".equals(key) || "parserInfixBit".equals(key) || "parserInfixLogical".equals(key) || "parserDoubleQuoted".equals(key) || "columnAsFunc".equals(key) || "optimizerDummySetting".equals(key)) { if (parsedGenerators != null) rebuildCompiler(); return true; } if ("zeroDateTimeBehavior".equals(key)) { valueEncoder = null; // Also depends on this. } if ("binary_output".equals(key) || "jsonbinary_output".equals(key)){ valueEncoder = null; } return super.propertySet(key, value); } @Override public String getSessionSetting(String key) { String prop = super.getSessionSetting(key); if (prop != null) return prop; if ("client_encoding".equals(key)) return "UTF8"; else if ("server_encoding".equals(key)) return messenger.getEncoding(); else if ("server_version".equals(key)) return "8.4.7"; // Latest of the 8.x series used to flag client(s) for supported functionality else if ("session_authorization".equals(key)) return properties.getProperty("user"); else if ("DateStyle".equals(key)) return "ISO, MDY"; else if ("transaction_isolation".equals(key)) return "serializable"; else if ("integer_datetimes".equals(key)) return "on"; else if ("standard_conforming_strings".equals(key)) return "on"; else if ("foundationdb_server".equals(key)) return reqs.layerInfo().getVersionInfo().versionShort; else return null; } public PostgresServer getServer() { return server; } }
package com.github.liosha2007.groupdocs.common; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import android.util.Base64; import com.google.gson.Gson; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.*; import org.apache.http.entity.InputStreamEntity; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; import org.json.JSONObject; import java.io.InputStream; import java.net.URI; import java.net.URL; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; public class ApiClient { private static final String ENC = "UTF-8"; private static final String SIGN_ALG = "HmacSHA1"; private String cid = null; private String pkey = null; private String bpath = "https://api.groupdocs.com/v2.0"; private Map<String, String> defaultHeaderMap = new HashMap<String, String>(); public ApiClient() { } public ApiClient(String pkey) { this.pkey = pkey; } public ApiClient(String pkey, String bpath) { this.pkey = pkey; this.bpath = bpath; } public ApiClient(String pkey, String bpath, String cid) { this.pkey = pkey; this.bpath = bpath; this.cid = cid; } public static String sign(String pkey, String toSign) throws Exception { Mac mac = Mac.getInstance(SIGN_ALG); mac.init(new SecretKeySpec(pkey.getBytes(ENC), SIGN_ALG)); String signature = new String(Base64.encode(mac.doFinal(toSign.getBytes(ENC)), Base64.NO_WRAP), ENC); if (signature.endsWith("=")) { signature = signature.substring(0, signature.length() - 1); } return signature; } public static String signUrl(String pkey, String url) throws Exception { StringBuilder temp = new StringBuilder(url); URL resourceURL = new URL(url); String pathAndQuery = resourceURL.getFile(); if (url.lastIndexOf(" ") == url.length() - 1) { pathAndQuery = pathAndQuery + " "; } String signature = sign(pkey, encodeURI(pathAndQuery)); temp.append((resourceURL.getQuery() == null ? "?" : "&")).append("signature=").append(encodeURIComponent(signature)); return temp.toString(); } public static String encodeURI(String uri) throws Exception { return encodeURIComponent(uri) .replace("%3B", ";") .replace("%2C", ",") .replace("%2F", "/") .replace("%3F", "?") .replace("%3A", ":") .replace("%40", "@") .replace("%26", "&") .replace("%3D", "=") // .replace("%2B", "+") .replace("%24", "$") .replace("%25", "%") .replace("%23", " } public static String encodeURIComponent(String str) throws Exception { return URLEncoder.encode(str, ENC) .replace("+", "%20") .replace("%21", "!") .replace("%27", "'") .replace("%28", "(") .replace("%29", ")") .replace("%7E", "~"); } public String escapeString(String str) throws Exception { return encodeURIComponent(str); } public String getCid() { return this.cid; } public void setCid(String cid) { this.cid = cid; } public void setPkey(String pkey) { this.pkey = pkey; } public String getBpath() { return bpath; } public void setBpath(String bpath) { this.bpath = bpath; } public <T> T invokeAPI(String path, String method, Map<String, String> queryParams, Object body, Map<String, String> headerParams, Class<T> returnType) throws Exception { StringBuilder stringBuilder = new StringBuilder(); for (String key : queryParams.keySet()) { String value = queryParams.get(key); if (value != null) { if (stringBuilder.toString().length() == 0) { stringBuilder.append("?"); } else { stringBuilder.append("&"); } stringBuilder.append(escapeString(key)).append("=").append(escapeString(value)); } } String queryString = stringBuilder.toString(); HttpClient httpClient = new DefaultHttpClient(); boolean isFileUpload = body instanceof FileStream; String requestUri = encodeURI(ApiClient.signUrl(pkey, bpath + path + queryString)); // Redirect not worked HttpRequestBase httpRequest = null; if ("GET".equals(method)) { httpRequest = new HttpGet(); } else if ("POST".equals(method)) { httpRequest = new HttpPost(); if (isFileUpload) { InputStream inputStream = ((FileStream) body).getInputStream(); ((HttpPost) httpRequest).setEntity(new InputStreamEntity(inputStream, inputStream.available())); } else { ((HttpPost) httpRequest).setEntity(new StringEntity(serealize(body))); } } else if ("PUT".equals(method)) { httpRequest = new HttpPut(); if (isFileUpload) { InputStream inputStream = ((FileStream) body).getInputStream(); ((HttpPut) httpRequest).setEntity(new InputStreamEntity(inputStream, inputStream.available())); } else { ((HttpPut) httpRequest).setEntity(new StringEntity(serealize(body))); } } else if ("DELETE".equals(method)) { httpRequest = new HttpDelete(); } else { throw new ApiException("Unknown HTTP method '" + method + "'"); } for (String key : defaultHeaderMap.keySet()) { httpRequest.setHeader(key, defaultHeaderMap.get(key)); } for (String key : headerParams.keySet()) { httpRequest.setHeader(key, headerParams.get(key)); } if (body == null) { httpRequest.setHeader(HTTP.CONTENT_TYPE, "text/html"); } else if (body instanceof FileStream) { httpRequest.setHeader(HTTP.CONTENT_TYPE, "application/octet-stream"); } else { httpRequest.setHeader(HTTP.CONTENT_TYPE, "application/json"); } T toReturn = null; httpRequest.setURI(new URI(requestUri)); HttpResponse httpResponse = httpClient.execute(httpRequest); int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED || statusCode == HttpStatus.SC_ACCEPTED) { if (FileStream.class.equals(returnType)) { if (httpResponse.getFirstHeader("Transfer-Encoding") != null && httpResponse.getEntity().getContentLength() > 0) { toReturn = (T) new FileStream(requestUri, httpResponse); } else { toReturn = null; } } else { toReturn = (T) EntityUtils.toString(httpResponse.getEntity()); } } else { String errMsg = EntityUtils.toString(httpResponse.getEntity()); try { JSONObject jsonObject = new JSONObject(errMsg); if (jsonObject.has("error_message")) { errMsg = jsonObject.getString("error_message"); } } catch (Exception e) { } throw new Exception(errMsg); } return toReturn; } public static String serealize(Object object) { Gson gson = new Gson(); return gson.toJson(object); } public static <T> T deserealize(String json, Class clazz) { Gson gson = new Gson(); return (T) gson.fromJson(json, clazz); } public Map<String, String> getDefaultHeaderMap() { return defaultHeaderMap; } public void setDefaultHeaderMap(Map<String, String> defaultHeaderMap) { this.defaultHeaderMap = defaultHeaderMap; } }
package com.indeed.proctor.webapp.jobs; import com.google.common.base.CharMatcher; import com.google.common.base.Joiner; import com.google.common.base.Strings; import com.google.common.base.Throwables; import com.google.common.collect.ImmutableMap; import com.indeed.proctor.common.EnvironmentVersion; import com.indeed.proctor.common.IncompatibleTestMatrixException; import com.indeed.proctor.common.ProctorPromoter; import com.indeed.proctor.common.ProctorUtils; import com.indeed.proctor.common.model.Allocation; import com.indeed.proctor.common.model.ConsumableTestDefinition; import com.indeed.proctor.common.model.Payload; import com.indeed.proctor.common.model.Range; import com.indeed.proctor.common.model.TestBucket; import com.indeed.proctor.common.model.TestDefinition; import com.indeed.proctor.common.model.TestType; import com.indeed.proctor.store.GitNoAuthorizationException; import com.indeed.proctor.store.GitNoDevelperAccessLevelException; import com.indeed.proctor.store.GitNoMasterAccessLevelException; import com.indeed.proctor.store.ProctorStore; import com.indeed.proctor.store.Revision; import com.indeed.proctor.store.StoreException; import com.indeed.proctor.webapp.db.Environment; import com.indeed.proctor.webapp.extensions.DefinitionChangeLog; import com.indeed.proctor.webapp.extensions.PostDefinitionCreateChange; import com.indeed.proctor.webapp.extensions.PostDefinitionEditChange; import com.indeed.proctor.webapp.extensions.PostDefinitionPromoteChange; import com.indeed.proctor.webapp.extensions.PreDefinitionCreateChange; import com.indeed.proctor.webapp.extensions.PreDefinitionEditChange; import com.indeed.proctor.webapp.extensions.PreDefinitionPromoteChange; import com.indeed.proctor.webapp.model.RevisionDefinition; import com.indeed.proctor.webapp.tags.TestDefinitionFunctions; import com.indeed.proctor.webapp.tags.UtilityFunctions; import com.indeed.proctor.webapp.util.AllocationIdUtil; import com.indeed.proctor.webapp.util.TestDefinitionUtil; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; import javax.annotation.Nullable; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import static com.indeed.proctor.webapp.util.AllocationIdUtil.ALLOCATION_ID_COMPARATOR; //Todo: Separate EditAndPromoteJob to EditJob and PromoteJob @Component public class EditAndPromoteJob extends AbstractJob { private static final Logger LOGGER = Logger.getLogger(EditAndPromoteJob.class); private static final Pattern ALPHA_NUMERIC_END_RESTRICTION_JAVA_IDENTIFIER_PATTERN = Pattern.compile("^([a-z_][a-z0-9_]+)?[a-z_]+$", Pattern.CASE_INSENSITIVE); private static final Pattern ALPHA_NUMERIC_JAVA_IDENTIFIER_PATTERN = Pattern.compile("^[a-z_][a-z0-9_]*$", Pattern.CASE_INSENSITIVE); private static final Pattern VALID_TEST_NAME_PATTERN = ALPHA_NUMERIC_END_RESTRICTION_JAVA_IDENTIFIER_PATTERN; private static final Pattern VALID_BUCKET_NAME_PATTERN = ALPHA_NUMERIC_JAVA_IDENTIFIER_PATTERN; private static final double TOLERANCE = 1E-6; private List<PreDefinitionEditChange> preDefinitionEditChanges = Collections.emptyList(); private List<PostDefinitionEditChange> postDefinitionEditChanges = Collections.emptyList(); private List<PreDefinitionCreateChange> preDefinitionCreateChanges = Collections.emptyList(); private List<PostDefinitionCreateChange> postDefinitionCreateChanges = Collections.emptyList(); private List<PreDefinitionPromoteChange> preDefinitionPromoteChanges = Collections.emptyList(); private List<PostDefinitionPromoteChange> postDefinitionPromoteChanges = Collections.emptyList(); private final BackgroundJobFactory jobFactory; private final BackgroundJobManager jobManager; private final ProctorPromoter promoter; private final CommentFormatter commentFormatter; private final MatrixChecker matrixChecker; @Autowired public EditAndPromoteJob(@Qualifier("trunk") final ProctorStore trunkStore, @Qualifier("qa") final ProctorStore qaStore, @Qualifier("production") final ProctorStore productionStore, final BackgroundJobManager jobManager, final BackgroundJobFactory jobFactory, final ProctorPromoter promoter, final CommentFormatter commentFormatter, final MatrixChecker matrixChecker ) { super(trunkStore, qaStore, productionStore); this.jobManager = jobManager; this.jobFactory = jobFactory; this.promoter = promoter; this.commentFormatter = commentFormatter; this.matrixChecker = matrixChecker; } @Autowired(required = false) public void setDefinitionEditChanges(final List<PreDefinitionEditChange> preDefinitionEditChanges, final List<PostDefinitionEditChange> postDefinitionEditChanges) { this.preDefinitionEditChanges = preDefinitionEditChanges; this.postDefinitionEditChanges = postDefinitionEditChanges; } @Autowired(required = false) public void setDefinitionCreateChanges(final List<PreDefinitionCreateChange> preDefinitionCreateChanges, final List<PostDefinitionCreateChange> postDefinitionCreateChanges) { this.preDefinitionCreateChanges = preDefinitionCreateChanges; this.postDefinitionCreateChanges = postDefinitionCreateChanges; } @Autowired(required = false) public void setDefinitionPromoteChanges(final List<PreDefinitionPromoteChange> preDefinitionPromoteChanges, final List<PostDefinitionPromoteChange> postDefinitionPromoteChanges) { this.preDefinitionPromoteChanges = preDefinitionPromoteChanges; this.postDefinitionPromoteChanges = postDefinitionPromoteChanges; } public BackgroundJob doEdit( final String testName, final String username, final String password, final String author, final boolean isCreate, final String comment, final String testDefinitionJson, final String previousRevision, final boolean isAutopromote, final Map<String, String[]> requestParameterMap) { BackgroundJob<Object> backgroundJob = jobFactory.createBackgroundJob( String.format("(username:%s author:%s) %s %s", username, author, (isCreate ? "Creating" : "Editing"), testName), isCreate ? BackgroundJob.JobType.TEST_CREATION : BackgroundJob.JobType.TEST_EDIT, job -> { try { if (CharMatcher.WHITESPACE.matchesAllOf(Strings.nullToEmpty(testDefinitionJson))) { throw new IllegalArgumentException("No new test definition given"); } job.log("Parsing test definition json"); final TestDefinition testDefinitionToUpdate = TestDefinitionFunctions.parseTestDefinition(testDefinitionJson); doEditInternal(testName, username, password, author, isCreate, comment, testDefinitionToUpdate, previousRevision, isAutopromote, requestParameterMap, job); } catch (final GitNoAuthorizationException | GitNoDevelperAccessLevelException | IllegalArgumentException | IncompatibleTestMatrixException exp) { job.logFailedJob(exp); LOGGER.info("Edit Failed: " + job.getTitle(), exp); } catch (Exception exp) { job.logFailedJob(exp); LOGGER.error("Edit Failed: " + job.getTitle(), exp); } return null; } ); jobManager.submit(backgroundJob); return backgroundJob; } public BackgroundJob doEdit( final String testName, final String username, final String password, final String author, final boolean isCreate, final String comment, final TestDefinition testDefinitionToUpdate, final String previousRevision, final boolean isAutopromote, final Map<String, String[]> requestParameterMap) { BackgroundJob<Object> backgroundJob = jobFactory.createBackgroundJob( String.format("(username:%s author:%s) %s %s", username, author, (isCreate ? "Creating" : "Editing"), testName), isCreate ? BackgroundJob.JobType.TEST_CREATION : BackgroundJob.JobType.TEST_EDIT, job -> { try { doEditInternal(testName, username, password, author, isCreate, comment, testDefinitionToUpdate, previousRevision, isAutopromote, requestParameterMap, job); } catch (final GitNoAuthorizationException | GitNoDevelperAccessLevelException | IllegalArgumentException | IncompatibleTestMatrixException exp) { job.logFailedJob(exp); LOGGER.info("Edit Failed: " + job.getTitle(), exp); } catch (Exception exp) { job.logFailedJob(exp); LOGGER.error("Edit Failed: " + job.getTitle(), exp); } return null; } ); jobManager.submit(backgroundJob); return backgroundJob; } private Boolean doEditInternal( final String testName, final String username, final String password, final String author, final boolean isCreate, final String comment, final TestDefinition testDefinitionToUpdate, final String previousRevision, final boolean isAutopromote, final Map<String, String[]> requestParameterMap, final BackgroundJob job ) throws Exception { final Environment theEnvironment = Environment.WORKING; // only allow editing of TRUNK! final ProctorStore trunkStore = determineStoreFromEnvironment(theEnvironment); final EnvironmentVersion environmentVersion = promoter.getEnvironmentVersion(testName); final String qaRevision = environmentVersion == null ? EnvironmentVersion.UNKNOWN_REVISION : environmentVersion.getQaRevision(); final String prodRevision = environmentVersion == null ? EnvironmentVersion.UNKNOWN_REVISION : environmentVersion.getProductionRevision(); validateUsernamePassword(username, password); validateComment(comment); if (previousRevision.length() > 0) { job.log("(scm) getting history for '" + testName + "'"); final List<Revision> history = TestDefinitionUtil.getTestHistory(trunkStore, testName, 1); if (history.size() > 0) { final Revision prevVersion = history.get(0); if (!prevVersion.getRevision().equals(previousRevision)) { throw new IllegalArgumentException("Test has been updated since " + previousRevision + " currently at " + prevVersion.getRevision()); } } } else { // check that the test name is valid if (!isValidTestName(testName)) { throw new IllegalArgumentException("Test Name must be alpha-numeric underscore and not start/end with a number, found: '" + testName + "'"); } } job.log("(scm) loading existing test definition for '" + testName + "'"); // Getting the TestDefinition via currentTestMatrix instead of trunkStore.getTestDefinition because the test final TestDefinition existingTestDefinition = trunkStore.getCurrentTestMatrix() .getTestMatrixDefinition() .getTests() .entrySet() .stream() .filter(map -> testName.equalsIgnoreCase(map.getKey())) .map(Map.Entry::getValue) .findAny() .orElse(null); if (previousRevision.length() <= 0 && existingTestDefinition != null) { throw new IllegalArgumentException("Current tests exists with name : '" + testName + "'"); } if (testDefinitionToUpdate == null) { throw new IllegalArgumentException("Test to update is null"); } if (testDefinitionToUpdate.getTestType() == null && existingTestDefinition != null) { testDefinitionToUpdate.setTestType(existingTestDefinition.getTestType()); } if (isCreate) { testDefinitionToUpdate.setVersion("-1"); handleAllocationIdsForNewTest(testDefinitionToUpdate); } else if (existingTestDefinition != null) { testDefinitionToUpdate.setVersion(existingTestDefinition.getVersion()); handleAllocationIdsForEditTest(testName, existingTestDefinition, testDefinitionToUpdate); } job.log("verifying test definition and buckets"); validateBasicInformation(testDefinitionToUpdate, job); final ConsumableTestDefinition consumableTestDefinition = ProctorUtils.convertToConsumableTestDefinition(testDefinitionToUpdate); ProctorUtils.verifyInternallyConsistentDefinition(testName, "edit", consumableTestDefinition); //PreDefinitionEdit if (isCreate) { job.log("Executing pre create extension tasks."); for (final PreDefinitionCreateChange preDefinitionCreateChange : preDefinitionCreateChanges) { final DefinitionChangeLog definitionChangeLog = preDefinitionCreateChange.preCreate(testDefinitionToUpdate, requestParameterMap); logDefinitionChangeLog(definitionChangeLog, preDefinitionCreateChange.getClass().getSimpleName(), job); } } else { job.log("Executing pre edit extension tasks."); for (final PreDefinitionEditChange preDefinitionEditChange : preDefinitionEditChanges) { final DefinitionChangeLog definitionChangeLog = preDefinitionEditChange.preEdit(existingTestDefinition, testDefinitionToUpdate, requestParameterMap); logDefinitionChangeLog(definitionChangeLog, preDefinitionEditChange.getClass().getSimpleName(), job); } } final String fullComment = commentFormatter.formatFullComment(comment, requestParameterMap); //Change definition final Map<String, String> metadata = Collections.emptyMap(); if (existingTestDefinition == null) { job.log("(scm) adding test definition"); trunkStore.addTestDefinition(username, password, author, testName, testDefinitionToUpdate, metadata, fullComment); promoter.refreshWorkingVersion(testName); } else { job.log("(scm) updating test definition"); trunkStore.updateTestDefinition(username, password, author, previousRevision, testName, testDefinitionToUpdate, metadata, fullComment); promoter.refreshWorkingVersion(testName); } //PostDefinitionEdit if (isCreate) { job.log("Executing post create extension tasks."); for (final PostDefinitionCreateChange postDefinitionCreateChange : postDefinitionCreateChanges) { final DefinitionChangeLog definitionChangeLog = postDefinitionCreateChange.postCreate(testDefinitionToUpdate, requestParameterMap); logDefinitionChangeLog(definitionChangeLog, postDefinitionCreateChange.getClass().getSimpleName(), job); } } else { job.log("Executing post edit extension tasks."); for (final PostDefinitionEditChange postDefinitionEditChange : postDefinitionEditChanges) { final DefinitionChangeLog definitionChangeLog = postDefinitionEditChange.postEdit(existingTestDefinition, testDefinitionToUpdate, requestParameterMap); logDefinitionChangeLog(definitionChangeLog, postDefinitionEditChange.getClass().getSimpleName(), job); } } //Autopromote if necessary if (isAutopromote && existingTestDefinition != null && isAllocationOnlyChange(existingTestDefinition, testDefinitionToUpdate)) { job.log("allocation only change, checking against other branches for auto-promote capability for test " + testName + "\nat QA revision " + qaRevision + " and PRODUCTION revision " + prodRevision); final List<Revision> histories = TestDefinitionUtil.getTestHistory(trunkStore, testName, 2); if (histories.size() <= 1) { throw new IllegalStateException("Test hasn't been updated since " + previousRevision + ". Failed to find the version for autopromote."); } if (!histories.get(1).getRevision().equals(previousRevision)) { throw new IllegalStateException("Test has been updated more than once since " + previousRevision + ". Failed to find the version for autopromote."); } final Revision currentVersion = histories.get(0); final boolean isQaPromoted; final boolean isQaPromotable = qaRevision != EnvironmentVersion.UNKNOWN_REVISION && isAllocationOnlyChange(TestDefinitionUtil.getTestDefinition(determineStoreFromEnvironment(Environment.QA), promoter, Environment.QA, testName, qaRevision), testDefinitionToUpdate); if (isQaPromotable) { job.log("auto-promoting changes to QA"); isQaPromoted = doPromoteInternal(testName, username, password, author, Environment.WORKING, currentVersion.getRevision(), Environment.QA, qaRevision, requestParameterMap, job, true); } else { isQaPromoted = false; job.log("previous revision changes prevented auto-promote to QA"); } if (isQaPromotable && isQaPromoted && prodRevision != EnvironmentVersion.UNKNOWN_REVISION && isAllocationOnlyChange(TestDefinitionUtil.getTestDefinition(determineStoreFromEnvironment(Environment.PRODUCTION), promoter, Environment.PRODUCTION, testName, prodRevision), testDefinitionToUpdate)) { job.log("auto-promoting changes to PRODUCTION"); doPromoteInternal(testName, username, password, author, Environment.WORKING, currentVersion.getRevision(), Environment.PRODUCTION, prodRevision, requestParameterMap, job, true); } else { job.log("previous revision changes prevented auto-promote to PRODUCTION"); } } job.log("COMPLETE"); job.addUrl("/proctor/definition/" + UtilityFunctions.urlEncode(testName) + "?branch=" + theEnvironment.getName(), "View Result"); return true; } /** * @param testName the proctor test name * @param previous test definition before edit * @param current test definition after edit */ private void handleAllocationIdsForEditTest(final String testName, final TestDefinition previous, final TestDefinition current) { // Update allocation id if necessary final Set<Allocation> outdatedAllocations = AllocationIdUtil.getOutdatedAllocations(previous, current); for (final Allocation allocation : outdatedAllocations) { allocation.setId(AllocationIdUtil.getNextVersionOfAllocationId(allocation.getId())); } /* * Check whether has new allocations. * Doing this check to avoid getMaxUsedAllocationIdForTest when unnecessary because getMaxUsedAllocationIdForTest takes time */ final boolean needNewAllocId = current.getAllocations().stream().anyMatch( x -> StringUtils.isEmpty(x.getId()) ); // Generate new allocation id if any allocation id is empty if (needNewAllocId) { // Get the max allocation id ever used from test definition history, including deleted allocations in the format like " final Optional<String> maxAllocId = getMaxUsedAllocationIdForTest(testName); // Convert maxAllocId to base 10 integer, so that we can easily increment it int maxAllocIdInt = maxAllocId.isPresent() ? AllocationIdUtil.convertBase26ToDecimal(AllocationIdUtil.getAllocationName(maxAllocId.get()).toCharArray()) : -1; for (final Allocation allocation : current.getAllocations()) { // Only generate for new allocation if (StringUtils.isEmpty(allocation.getId())) { allocation.setId(AllocationIdUtil.generateAllocationId(++maxAllocIdInt, 1)); } } } } /** * @param testName the proctor test name * @return the max allocation id ever used in the format like "#Z1" */ @Nullable private Optional<String> getMaxUsedAllocationIdForTest(final String testName) { // Use trunk store final ProctorStore trunkStore = determineStoreFromEnvironment(Environment.WORKING); final List<RevisionDefinition> revisionDefinitions = TestDefinitionUtil.makeRevisionDefinitionList(trunkStore, testName, null, true); return getMaxAllocationId(revisionDefinitions); } static Optional<String> getMaxAllocationId(final List<RevisionDefinition> revisionDefinitions) { return revisionDefinitions.stream().map(RevisionDefinition::getDefinition) .filter(Objects::nonNull) .flatMap(x -> x.getAllocations().stream()) .map(Allocation::getId) .filter(StringUtils::isNotEmpty) .distinct() .max(ALLOCATION_ID_COMPARATOR); } /** * @param testDefinition the test definition to generate allocation ids for */ private void handleAllocationIdsForNewTest(final TestDefinition testDefinition) { for (int i = 0; i < testDefinition.getAllocations().size(); i++) { final Allocation allocation = testDefinition.getAllocations().get(i); allocation.setId(AllocationIdUtil.generateAllocationId(i, 1)); } } static boolean isAllocationOnlyChange(final TestDefinition existingTestDefinition, final TestDefinition testDefinitionToUpdate) { final List<Allocation> existingAllocations = existingTestDefinition.getAllocations(); final List<Allocation> allocationsToUpdate = testDefinitionToUpdate.getAllocations(); final boolean nullRule = existingTestDefinition.getRule() == null; if (nullRule && testDefinitionToUpdate.getRule() != null) { return false; } else if (!nullRule && !existingTestDefinition.getRule().equals(testDefinitionToUpdate.getRule())) { return false; } if (!existingTestDefinition.getConstants().equals(testDefinitionToUpdate.getConstants()) || !existingTestDefinition.getSpecialConstants().equals(testDefinitionToUpdate.getSpecialConstants()) || !existingTestDefinition.getTestType().equals(testDefinitionToUpdate.getTestType()) || !existingTestDefinition.getSalt().equals(testDefinitionToUpdate.getSalt()) || !existingTestDefinition.getBuckets().equals(testDefinitionToUpdate.getBuckets()) || existingAllocations.size() != allocationsToUpdate.size()) { return false; } /* * TestBucket .equals() override only checks name equality * loop below compares each attribute of a TestBucket */ for (int i = 0; i < existingTestDefinition.getBuckets().size(); i++) { final TestBucket bucketOne = existingTestDefinition.getBuckets().get(i); final TestBucket bucketTwo = testDefinitionToUpdate.getBuckets().get(i); if (bucketOne == null) { if (bucketTwo != null) { return false; } } else if (bucketTwo == null) { return false; } else { if (bucketOne.getValue() != bucketTwo.getValue()) { return false; } final Payload payloadOne = bucketOne.getPayload(); final Payload payloadTwo = bucketTwo.getPayload(); if (payloadOne == null) { if (payloadTwo != null) { return false; } } else if (!payloadOne.equals(payloadTwo)) { return false; } if (bucketOne.getDescription() == null) { if (bucketTwo.getDescription() != null) { return false; } } else if (!bucketOne.getDescription().equals(bucketTwo.getDescription())) { return false; } } } /* * Comparing everything in an allocation except the lengths */ for (int i = 0; i < existingAllocations.size(); i++) { final List<Range> existingAllocationRanges = existingAllocations.get(i).getRanges(); final List<Range> allocationToUpdateRanges = allocationsToUpdate.get(i).getRanges(); if (existingAllocations.get(i).getRule() == null && allocationsToUpdate.get(i).getRule() != null) { return false; } else if (existingAllocations.get(i).getRule() != null && !existingAllocations.get(i).getRule().equals(allocationsToUpdate.get(i).getRule())) { return false; } if (isNewBucketAdded(existingAllocationRanges, allocationToUpdateRanges)) { return false; } } return true; } private static boolean isNewBucketAdded(final List<Range> existingAllocationRanges, final List<Range> allocationToUpdateRanges ) { final Map<Integer, Double> existingAllocRangeMap = generateAllocationRangeMap(existingAllocationRanges); final Map<Integer, Double> allocToUpdateRangeMap = generateAllocationRangeMap(allocationToUpdateRanges); return allocToUpdateRangeMap.entrySet().stream() .filter(bucket -> bucket.getValue() > TOLERANCE) .filter(bucket -> bucket.getKey() != -1) .anyMatch(bucket -> existingAllocRangeMap.getOrDefault(bucket.getKey(), 0.0) < TOLERANCE); } private static Map<Integer, Double> generateAllocationRangeMap(final List<Range> ranges) { Map<Integer, Double> bucketToTotalAllocationMap = new HashMap<>(); for (Range range : ranges) { final int bucketVal = range.getBucketValue(); double sum = 0; if (bucketToTotalAllocationMap.containsKey(bucketVal)) { sum += bucketToTotalAllocationMap.get(bucketVal); } sum += range.getLength(); bucketToTotalAllocationMap.put(bucketVal, sum); } return bucketToTotalAllocationMap; } private void validateBasicInformation(final TestDefinition definition, final BackgroundJob backgroundJob) throws IllegalArgumentException { if (CharMatcher.WHITESPACE.matchesAllOf(Strings.nullToEmpty(definition.getDescription()))) { throw new IllegalArgumentException("Description is required."); } if (CharMatcher.WHITESPACE.matchesAllOf(Strings.nullToEmpty(definition.getSalt()))) { throw new IllegalArgumentException("Salt is required."); } if (definition.getTestType() == null) { throw new IllegalArgumentException("TestType is required."); } if (definition.getBuckets().isEmpty()) { throw new IllegalArgumentException("Buckets cannot be empty."); } if (definition.getAllocations().isEmpty()) { throw new IllegalArgumentException("Allocations cannot be empty."); } validateAllocationsAndBuckets(definition, backgroundJob); } private void validateAllocationsAndBuckets(final TestDefinition definition, final BackgroundJob backgroundJob) throws IllegalArgumentException { final Allocation allocation = definition.getAllocations().get(0); final List<Range> ranges = allocation.getRanges(); final TestType testType = definition.getTestType(); final int controlBucketValue = 0; final Map<Integer, Double> totalTestAllocationMap = new HashMap<Integer, Double>(); for (Range range : ranges) { final int bucketValue = range.getBucketValue(); double bucketAllocation = range.getLength(); if (totalTestAllocationMap.containsKey(bucketValue)) { bucketAllocation += totalTestAllocationMap.get(bucketValue); } totalTestAllocationMap.put(bucketValue, bucketAllocation); } final boolean hasControlBucket = totalTestAllocationMap.containsKey(controlBucketValue); /* The number of buckets with allocation greater than zero */ int numActiveBuckets = 0; for (Integer bucketValue : totalTestAllocationMap.keySet()) { final double totalBucketAllocation = totalTestAllocationMap.get(bucketValue); if (totalBucketAllocation > 0) { numActiveBuckets++; } } /* if there are 2 buckets with positive allocations, test and control buckets should be the same size */ if (numActiveBuckets > 1 && hasControlBucket) { final double totalControlBucketAllocation = totalTestAllocationMap.get(controlBucketValue); for (Integer bucketValue : totalTestAllocationMap.keySet()) { final double totalBucketAllocation = totalTestAllocationMap.get(bucketValue); if (totalBucketAllocation > 0) { numActiveBuckets++; } final double difference = totalBucketAllocation - totalControlBucketAllocation; if (bucketValue > 0 && totalBucketAllocation > 0 && Math.abs(difference) >= TOLERANCE) { backgroundJob.log("WARNING: Positive bucket total allocation size not same as control bucket total allocation size. \nBucket #" + bucketValue + "=" + totalBucketAllocation + ", Zero Bucket=" + totalControlBucketAllocation); } } } /* If there are 2 buckets with positive allocations, one should be control */ if (numActiveBuckets > 1 && !hasControlBucket) { backgroundJob.log("WARNING: You should have a zero bucket (control)."); } for (TestBucket bucket : definition.getBuckets()) { if (testType == TestType.PAGE && bucket.getValue() < 0) { throw new IllegalArgumentException("PAGE tests cannot contain negative buckets."); } } for (TestBucket bucket : definition.getBuckets()) { final String name = bucket.getName(); if (!isValidBucketName(name)) { throw new IllegalArgumentException("Bucket name must be alpha-numeric underscore and not start with a number, found: '" + name + "'"); } } } static boolean isValidTestName(final String testName) { final Matcher m = VALID_TEST_NAME_PATTERN.matcher(testName); return m.matches(); } static boolean isValidBucketName(final String bucketName) { final Matcher m = VALID_BUCKET_NAME_PATTERN.matcher(bucketName); return m.matches(); } public BackgroundJob doPromote(final String testName, final String username, final String password, final String author, final Environment source, final String srcRevision, final Environment destination, final String destRevision, final Map<String, String[]> requestParameterMap ) { BackgroundJob<Object> backgroundJob = jobFactory.createBackgroundJob( String.format("(username:%s author:%s) promoting %s %s %1.7s to %s", username, author, testName, source, srcRevision, destination), BackgroundJob.JobType.TEST_PROMOTION, job -> { /* Valid permutations: TRUNK -> QA TRUNK -> PRODUCTION QA -> PRODUCTION */ try { doPromoteInternal(testName, username, password, author, source, srcRevision, destination, destRevision, requestParameterMap, job, false); } catch (final GitNoAuthorizationException | GitNoMasterAccessLevelException | GitNoDevelperAccessLevelException | IllegalArgumentException exp) { job.logFailedJob(exp); LOGGER.info("Promotion Failed: " + job.getTitle(), exp); } catch (Exception exp) { job.logFailedJob(exp); LOGGER.error("Promotion Failed: " + job.getTitle(), exp); } return null; } ); jobManager.submit(backgroundJob); return backgroundJob; } private Boolean doPromoteInternal(final String testName, final String username, final String password, final String author, final Environment source, final String srcRevision, final Environment destination, final String destRevision, final Map<String, String[]> requestParameterMap, final BackgroundJob job, final boolean isAutopromote ) throws Exception { final Map<String, String> metadata = Collections.emptyMap(); validateUsernamePassword(username, password); // TODO (parker) 9/5/12 - Verify that promoting to the destination branch won't cause issues final TestDefinition testDefintion = TestDefinitionUtil.getTestDefinition(determineStoreFromEnvironment(source), promoter, source, testName, srcRevision); // if(d == null) { // return "could not find " + testName + " on " + source + " with revision " + srcRevision; final MatrixChecker.CheckMatrixResult result = matrixChecker.checkMatrix(destination, testName, testDefintion); if (!result.isValid()) { throw new IllegalArgumentException(String.format("Test Promotion not compatible, errors: %s", Joiner.on("\n").join(result.getErrors()))); } else { final Map<Environment, PromoteAction> actions = PROMOTE_ACTIONS.get(source); if (actions == null || !actions.containsKey(destination)) { throw new IllegalArgumentException("Invalid combination of source and destination: source=" + source + " dest=" + destination); } final PromoteAction action = actions.get(destination); //PreDefinitionPromoteChanges job.log("Executing pre promote extension tasks."); for (final PreDefinitionPromoteChange preDefinitionPromoteChange : preDefinitionPromoteChanges) { final DefinitionChangeLog definitionChangeLog = preDefinitionPromoteChange.prePromote(testDefintion, requestParameterMap, source, destination, isAutopromote); logDefinitionChangeLog(definitionChangeLog, preDefinitionPromoteChange.getClass().getSimpleName(), job); } //Promote Change final boolean success = action.promoteTest(job, testName, srcRevision, destRevision, username, password, author, metadata); //PostDefinitionPromoteChanges job.log("Executing post promote extension tasks."); for (final PostDefinitionPromoteChange postDefinitionPromoteChange : postDefinitionPromoteChanges) { final DefinitionChangeLog definitionChangeLog = postDefinitionPromoteChange.postPromote(requestParameterMap, source, destination, isAutopromote); logDefinitionChangeLog(definitionChangeLog, postDefinitionPromoteChange.getClass().getSimpleName(), job); } job.log(String.format("Promoted %s from %s (%1.7s) to %s (%1.7s)", testName, source.getName(), srcRevision, destination.getName(), destRevision)); job.addUrl("/proctor/definition/" + UtilityFunctions.urlEncode(testName) + "?branch=" + destination.getName(), "view " + testName + " on " + destination.getName()); return success; } } private interface PromoteAction { Environment getSource(); Environment getDestination(); boolean promoteTest(BackgroundJob job, final String testName, final String srcRevision, final String destRevision, final String username, final String password, final String author, final Map<String, String> metadata) throws IllegalArgumentException, ProctorPromoter.TestPromotionException, StoreException.TestUpdateException; } private abstract class PromoteActionBase implements PromoteAction { final Environment src; final Environment destination; protected PromoteActionBase(final Environment src, final Environment destination) { this.destination = destination; this.src = src; } @Override public boolean promoteTest(final BackgroundJob job, final String testName, final String srcRevision, final String destRevision, final String username, final String password, final String author, final Map<String, String> metadata) throws IllegalArgumentException, ProctorPromoter.TestPromotionException, StoreException.TestUpdateException, StoreException.TestUpdateException { try { doPromotion(job, testName, srcRevision, destRevision, username, password, author, metadata); return true; } catch (Exception t) { Throwables.propagateIfInstanceOf(t, ProctorPromoter.TestPromotionException.class); Throwables.propagateIfInstanceOf(t, StoreException.TestUpdateException.class); throw Throwables.propagate(t); } } @Override public final Environment getSource() { return src; } @Override public final Environment getDestination() { return destination; } abstract void doPromotion(BackgroundJob job, String testName, String srcRevision, String destRevision, String username, String password, String author, Map<String, String> metadata) throws ProctorPromoter.TestPromotionException, StoreException; } private final PromoteAction TRUNK_TO_QA = new PromoteActionBase(Environment.WORKING, Environment.QA) { @Override void doPromotion(final BackgroundJob job, final String testName, final String srcRevision, final String destRevision, final String username, final String password, final String author, final Map<String, String> metadata) throws ProctorPromoter.TestPromotionException, StoreException { job.log(String.format("(scm) promote %s %1.7s (trunk to qa)", testName, srcRevision)); promoter.promoteTrunkToQa(testName, srcRevision, destRevision, username, password, author, metadata); } }; private final PromoteAction TRUNK_TO_PRODUCTION = new PromoteActionBase(Environment.WORKING, Environment.PRODUCTION) { @Override void doPromotion(final BackgroundJob job, final String testName, final String srcRevision, final String destRevision, final String username, final String password, final String author, final Map<String, String> metadata) throws ProctorPromoter.TestPromotionException, StoreException { job.log(String.format("(scm) promote %s %1.7s (trunk to production)", testName, srcRevision)); promoter.promoteTrunkToProduction(testName, srcRevision, destRevision, username, password, author, metadata); } }; private final PromoteAction QA_TO_PRODUCTION = new PromoteActionBase(Environment.QA, Environment.PRODUCTION) { @Override void doPromotion(final BackgroundJob job, final String testName, final String srcRevision, final String destRevision, final String username, final String password, final String author, final Map<String, String> metadata) throws ProctorPromoter.TestPromotionException, StoreException { job.log(String.format("(scm) promote %s %1.7s (qa to production)", testName, srcRevision)); promoter.promoteQaToProduction(testName, srcRevision, destRevision, username, password, author, metadata); } }; private final Map<Environment, Map<Environment, PromoteAction>> PROMOTE_ACTIONS = ImmutableMap.<Environment, Map<Environment, PromoteAction>>builder() .put(Environment.WORKING, ImmutableMap.of(Environment.QA, TRUNK_TO_QA, Environment.PRODUCTION, TRUNK_TO_PRODUCTION)) .put(Environment.QA, ImmutableMap.of(Environment.PRODUCTION, QA_TO_PRODUCTION)).build(); }
package ru.job4j.start; import ru.job4j.models.Item; /** * * class StartUi. * auhtor IndyukovS * version 0.1 */ public class StartUi { /** * @param; */ private ConsoleInput input; /** * @param; */ private Tracker tracker; /** * @param add. */ private static final int ADD = 0; /** * @param add. */ private static final int SHOW = 1; /** * @param add. */ private static final int EDIT = 2; /** * @param add. */ private static final int DEL = 3; /** * @param add. */ private static final int FBI = 4; /** * @param add. */ private static final int FBN = 5; /** * @param add. */ private static final int EXIT = 6; public StartUi(ConsoleInput input, Tracker tracker) { this.input = input; this.tracker = tracker; } /** * method showMenu. */ public static void showMenu() { System.out.println("0. Add new Item"); System.out.println("1. Show all items"); System.out.println("2. Edit item"); System.out.println("3. Delete item"); System.out.println("4. Find item by Id"); System.out.println("5. Find items by name"); System.out.println("6. Exit Program"); System.out.print("Select: "); } /** * method showItems. * @param items first */ public static void showItems(Item[] items) { for (int i = 0; i < items.length; i++) { System.out.println(String.format("%s %s %s %s", items[i].getId(), items[i].getName(), items[i].getDescription(), items[i].getCreate())); } } /** * method showItem. * @param item first */ public static void showItem(Item item) { if (item != null) { System.out.println(String.format("%s %s %s %s", item.getId(), item.getName(), item.getDescription(), item.getCreate())); } } /** method init. */ public void init() { showMenu(); int select = this.input.select(); while (select < 0 || select > 6) { System.out.println("Введено некорректное значение"); } while (select != EXIT) { if (select == ADD) { String name = input.askName("Please, enter the item name: "); String id = input.askId("Please, enter the item id: "); String description = input.askDescription("Please, enter the item description: "); long create = input.askCreate("Please, enter the item Create: "); Item item = new Item(id, name, description, create); tracker.add(item); } if (select == SHOW) { showItems(tracker.findAll()); } if (select == EDIT) { String name = input.askName("Please, enter the item name(the names must match the name of the editabler application): "); String id = input.askId("Please, enter the item id: "); String description = input.askDescription("Please, enter the item description: "); long create = input.askCreate("Please, enter the item Create: "); Item item = new Item(id, name, description, create); tracker.update(item); } if (select == DEL) { String id = input.askId("Please, enter the item id: "); Item item = new Item(id, "off", "off", 0); tracker.delete(item); } if (select == FBI) { String id = input.askId("Please, enter the item id: "); showItem(tracker.findById(id)); } if (select == FBN) { String name = input.askName("Please, enter the item name: "); showItems(tracker.findByName(name)); } showMenu(); select = input.select(); } } /** * method mains. * @param args first */ public static void main(String[] args) { Tracker tracker = new Tracker(); ConsoleInput input = new ConsoleInput(); new StartUi(input, tracker).init(); } }
package gc; public class GcTest { // DisableExplicitGC gc API // -verbose:gc -XX:+DisableExplicitGC public static void main(String[] args) { { // 64M byte[] buff = new byte[1024 * 1024 * 64]; } System.gc(); } }
package com.laytonsmith.core.events.drivers; import com.laytonsmith.PureUtilities.Common.StringUtils; import com.laytonsmith.PureUtilities.Vector3D; import com.laytonsmith.PureUtilities.Version; import com.laytonsmith.abstraction.MCEntity; import com.laytonsmith.abstraction.MCHanging; import com.laytonsmith.abstraction.MCItemStack; import com.laytonsmith.abstraction.MCLivingEntity; import com.laytonsmith.abstraction.MCLocation; import com.laytonsmith.abstraction.MCPlayer; import com.laytonsmith.abstraction.MCProjectile; import com.laytonsmith.abstraction.MCProjectileSource; import com.laytonsmith.abstraction.MCWorld; import com.laytonsmith.abstraction.blocks.MCBlock; import com.laytonsmith.abstraction.blocks.MCBlockProjectileSource; import com.laytonsmith.abstraction.blocks.MCMaterial; import com.laytonsmith.abstraction.entities.MCFirework; import com.laytonsmith.abstraction.enums.MCDamageCause; import com.laytonsmith.abstraction.enums.MCEntityType; import com.laytonsmith.abstraction.enums.MCEquipmentSlot; import com.laytonsmith.abstraction.enums.MCRegainReason; import com.laytonsmith.abstraction.enums.MCRemoveCause; import com.laytonsmith.abstraction.enums.MCSpawnReason; import com.laytonsmith.abstraction.enums.MCTargetReason; import com.laytonsmith.abstraction.events.MCCreatureSpawnEvent; import com.laytonsmith.abstraction.events.MCEntityChangeBlockEvent; import com.laytonsmith.abstraction.events.MCEntityDamageByEntityEvent; import com.laytonsmith.abstraction.events.MCEntityDamageEvent; import com.laytonsmith.abstraction.events.MCEntityDeathEvent; import com.laytonsmith.abstraction.events.MCEntityEnterPortalEvent; import com.laytonsmith.abstraction.events.MCEntityExplodeEvent; import com.laytonsmith.abstraction.events.MCEntityInteractEvent; import com.laytonsmith.abstraction.events.MCEntityPortalEvent; import com.laytonsmith.abstraction.events.MCEntityRegainHealthEvent; import com.laytonsmith.abstraction.events.MCEntityTargetEvent; import com.laytonsmith.abstraction.events.MCEntityToggleGlideEvent; import com.laytonsmith.abstraction.events.MCFireworkExplodeEvent; import com.laytonsmith.abstraction.events.MCHangingBreakEvent; import com.laytonsmith.abstraction.events.MCItemDespawnEvent; import com.laytonsmith.abstraction.events.MCItemSpawnEvent; import com.laytonsmith.abstraction.events.MCPlayerDropItemEvent; import com.laytonsmith.abstraction.events.MCPlayerInteractAtEntityEvent; import com.laytonsmith.abstraction.events.MCPlayerInteractEntityEvent; import com.laytonsmith.abstraction.events.MCPlayerPickupItemEvent; import com.laytonsmith.abstraction.events.MCProjectileHitEvent; import com.laytonsmith.abstraction.events.MCProjectileLaunchEvent; import com.laytonsmith.annotations.api; import com.laytonsmith.core.CHVersion; import com.laytonsmith.core.ObjectGenerator; import com.laytonsmith.core.Static; import com.laytonsmith.core.constructs.CArray; import com.laytonsmith.core.constructs.CBoolean; import com.laytonsmith.core.constructs.CDouble; import com.laytonsmith.core.constructs.CInt; import com.laytonsmith.core.constructs.CNull; import com.laytonsmith.core.constructs.CString; import com.laytonsmith.core.constructs.Construct; import com.laytonsmith.core.constructs.Target; import com.laytonsmith.core.environments.Environment; import com.laytonsmith.core.events.AbstractEvent; import com.laytonsmith.core.events.BindableEvent; import com.laytonsmith.core.events.BoundEvent.ActiveEvent; import com.laytonsmith.core.events.Driver; import com.laytonsmith.core.events.EventBuilder; import com.laytonsmith.core.events.Prefilters; import com.laytonsmith.core.events.Prefilters.PrefilterType; import com.laytonsmith.core.exceptions.CRE.CREBadEntityException; import com.laytonsmith.core.exceptions.CRE.CRECastException; import com.laytonsmith.core.exceptions.CRE.CREFormatException; import com.laytonsmith.core.exceptions.ConfigRuntimeException; import com.laytonsmith.core.exceptions.EventException; import com.laytonsmith.core.exceptions.PrefilterNonMatchException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class EntityEvents { public static String docs(){ return "Contains events related to an entity"; } @api public static class item_despawn extends AbstractEvent { @Override public String getName() { return "item_despawn"; } @Override public String docs() { return "{item: <item match> the item id and data value to check}" + " Fires when an item entity is removed from the world because it has existed for 5 minutes." + " Cancelling the event will allow the item to exist for 5 more minutes." + " {location: where the item is | id: the item's entityID | item: the itemstack of the entity}" + " {}" + " {}"; } @Override public boolean matches(Map<String, Construct> prefilter, BindableEvent e) throws PrefilterNonMatchException { if (e instanceof MCItemDespawnEvent) { Prefilters.match(prefilter, "item", Static.ParseItemNotation( ((MCItemDespawnEvent) e).getEntity().getItemStack()), PrefilterType.ITEM_MATCH); return true; } return false; } @Override public BindableEvent convert(CArray manualObject, Target t) { throw ConfigRuntimeException.CreateUncatchableException("Unsupported Operation", Target.UNKNOWN); } @Override public Map<String, Construct> evaluate(BindableEvent e) throws EventException { if (e instanceof MCItemDespawnEvent) { Target t = Target.UNKNOWN; MCItemDespawnEvent event = (MCItemDespawnEvent) e; Map<String, Construct> ret = evaluate_helper(event); ret.put("location", ObjectGenerator.GetGenerator().location(event.getLocation(), false)); ret.put("id", new CString(event.getEntity().getUniqueId().toString(), t)); ret.put("item", ObjectGenerator.GetGenerator().item(event.getEntity().getItemStack(), t)); return ret; } else { throw new EventException("Could not convert to MCItemDespawnEvent"); } } @Override public Driver driver() { return Driver.ITEM_DESPAWN; } @Override public boolean modifyEvent(String key, Construct value, BindableEvent event) { return false; } @Override public Version since() { return CHVersion.V3_3_1; } } @api public static class item_spawn extends AbstractEvent { @Override public String getName() { return "item_spawn"; } @Override public String docs() { return "{item: <item match> the item id and data value to check}" + " Fires when an item entity comes into existance." + " {location: where the item spawns | id: the item's entityID | item}" + " {item: the itemstack of the entity}" + " {}"; } @Override public boolean matches(Map<String, Construct> prefilter, BindableEvent e) throws PrefilterNonMatchException { if (e instanceof MCItemSpawnEvent) { Prefilters.match(prefilter, "item", Static.ParseItemNotation( ((MCItemSpawnEvent) e).getEntity().getItemStack()), PrefilterType.ITEM_MATCH); return true; } return false; } @Override public BindableEvent convert(CArray manualObject, Target t) { throw ConfigRuntimeException.CreateUncatchableException("Unsupported Operation", Target.UNKNOWN); } @Override public Map<String, Construct> evaluate(BindableEvent e) throws EventException { if (e instanceof MCItemSpawnEvent) { Target t = Target.UNKNOWN; MCItemSpawnEvent event = (MCItemSpawnEvent) e; Map<String, Construct> ret = evaluate_helper(event); ret.put("location", ObjectGenerator.GetGenerator().location(event.getLocation(), false)); ret.put("id", new CString(event.getEntity().getUniqueId().toString(), t)); ret.put("item", ObjectGenerator.GetGenerator().item(event.getEntity().getItemStack(), t)); return ret; } else { throw new EventException("Could not convert to MCItemSpawnEvent"); } } @Override public Driver driver() { return Driver.ITEM_SPAWN; } @Override public boolean modifyEvent(String key, Construct value, BindableEvent event) { if (event instanceof MCItemSpawnEvent) { if ("item".equals(key)) { ((MCItemSpawnEvent) event).getEntity().setItemStack(ObjectGenerator.GetGenerator().item(value, value.getTarget())); return true; } } return false; } @Override public Version since() { return CHVersion.V3_3_1; } @Override public void preExecution(Environment env, ActiveEvent activeEvent) { if(activeEvent.getUnderlyingEvent() instanceof MCItemSpawnEvent){ // Static lookups of the entity don't work here, so we need to inject them MCEntity entity = ((MCItemSpawnEvent)activeEvent.getUnderlyingEvent()).getEntity(); Static.InjectEntity(entity); } } @Override public void postExecution(Environment env, ActiveEvent activeEvent) { if(activeEvent.getUnderlyingEvent() instanceof MCItemSpawnEvent){ MCEntity entity = ((MCItemSpawnEvent)activeEvent.getUnderlyingEvent()).getEntity(); Static.UninjectEntity(entity); } } } @api public static class entity_explode extends AbstractEvent { @Override public String getName() { return "entity_explode"; } @Override public String docs() { return "{id: <macro> The entityID. If null is used here, it will match events that lack a specific entity," + " such as using the explosion function. | type: <macro> The type of entity exploding. Can be null," + " as id.} Fires when an explosion occurs." + " The entity itself may not exist if triggered by a plugin. Cancelling this event only protects blocks," + " entities are handled in damage events. {id: entityID, or null if no entity" + " | type: entitytype, or null if no entity | location: where the explosion occurs | blocks | yield}" + " {blocks: An array of blocks destroyed by the explosion. | yield: Percent of the blocks destroyed" + " that should drop items. A value greater than 100 will cause more drops than the original blocks.}" + " {}"; } @Override public boolean matches(Map<String, Construct> prefilter, BindableEvent event) throws PrefilterNonMatchException { if (event instanceof MCEntityExplodeEvent) { MCEntityExplodeEvent e = (MCEntityExplodeEvent) event; if (prefilter.containsKey("id")) { if (e.getEntity() == null) { return prefilter.get("id") instanceof CNull; } Prefilters.match(prefilter, "id", e.getEntity().getUniqueId().toString(), PrefilterType.MACRO); } if (prefilter.containsKey("type")) { if (e.getEntity() == null) { return prefilter.get("type") instanceof CNull; } Prefilters.match(prefilter, "type", e.getEntity().getType().name(), PrefilterType.MACRO); } return true; } return false; } @Override public BindableEvent convert(CArray manualObject, Target t) { throw ConfigRuntimeException.CreateUncatchableException("Unsupported Operation", Target.UNKNOWN); } @Override public Map<String, Construct> evaluate(BindableEvent event) throws EventException { if (event instanceof MCEntityExplodeEvent) { Target t = Target.UNKNOWN; MCEntityExplodeEvent e = (MCEntityExplodeEvent) event; Map<String, Construct> ret = evaluate_helper(e); CArray blocks = new CArray(t); for (MCBlock b : e.getBlocks()) { blocks.push(ObjectGenerator.GetGenerator().location(b.getLocation()), t); } ret.put("blocks", blocks); Construct entity = CNull.NULL; Construct entitytype = CNull.NULL; if (e.getEntity() != null) { entity = new CString(e.getEntity().getUniqueId().toString(), t); entitytype = new CString(e.getEntity().getType().name(), t); } ret.put("id", entity); ret.put("type", entitytype); ret.put("location", ObjectGenerator.GetGenerator().location(e.getLocation())); ret.put("yield", new CDouble(e.getYield(), t)); return ret; } else { throw new EventException("Could not convert to MCEntityExplodeEvent"); } } @Override public Driver driver() { return Driver.ENTITY_EXPLODE; } @Override public boolean modifyEvent(String key, Construct value, BindableEvent event) { if (event instanceof MCEntityExplodeEvent) { MCEntityExplodeEvent e = (MCEntityExplodeEvent) event; if (key.equals("yield")) { e.setYield(Static.getDouble32(value, value.getTarget())); return true; } if (key.equals("blocks")) { if (value instanceof CArray) { CArray ba = (CArray) value; List<MCBlock> blocks = new ArrayList<MCBlock>(); for (String b : ba.stringKeySet()) { MCWorld w = e.getLocation().getWorld(); MCLocation loc = ObjectGenerator.GetGenerator().location(ba.get(b, value.getTarget()), w, value.getTarget()); blocks.add(loc.getWorld().getBlockAt(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())); } e.setBlocks(blocks); return true; } } } return false; } @Override public Version since() { return CHVersion.V3_3_1; } } @api public static class projectile_hit extends AbstractEvent { @Override public String getName() { return "projectile_hit"; } @Override public String docs() { return "{id: <macro> The entityID | type: <macro> the entity type of the projectile | hittype: <string>" + " the type of object hit, either ENTITY or BLOCK}" + " Fires when a projectile collides with something." + " {type | id: the entityID of the projectile |" + " location: where it makes contact | shooter | hittype (MC 1.11) | hit: the entity id or block" + " location array of the hit object. (MC 1.11)}" + " {shooter: the entityID of the mob/player that fired" + " the projectile, or null if it is from a dispenser}" + " {id}"; } @Override public boolean matches(Map<String, Construct> prefilter, BindableEvent event) throws PrefilterNonMatchException { if (event instanceof MCProjectileHitEvent) { MCProjectileHitEvent e = (MCProjectileHitEvent) event; if(prefilter.containsKey("hittype")) { String hittype = prefilter.get("hittype").val(); if(hittype.equals("ENTITY")) { if(e.getHitEntity() == null) { return false; } } else if(hittype.equals("BLOCK")) { if(e.getHitBlock() == null) { return false; } } else { return false; } } Prefilters.match(prefilter, "id", e.getEntity().getUniqueId().toString(), PrefilterType.MACRO); Prefilters.match(prefilter, "type", e.getEntityType().name(), PrefilterType.MACRO); return true; } return false; } @Override public BindableEvent convert(CArray manualObject, Target t) { MCEntity p = Static.getEntity(manualObject.get("id", Target.UNKNOWN), Target.UNKNOWN); if (!(p instanceof MCProjectile)) { throw new CREBadEntityException("The id was not a projectile", Target.UNKNOWN); } return EventBuilder.instantiate(MCProjectileHitEvent.class, p); } @Override public Map<String, Construct> evaluate(BindableEvent event) throws EventException { Target t = Target.UNKNOWN; MCProjectileHitEvent e = (MCProjectileHitEvent) event; Map<String, Construct> ret = evaluate_helper(e); MCProjectile pro = e.getEntity(); ret.put("id", new CString(pro.getUniqueId().toString(), t)); ret.put("type", new CString(pro.getType().name(), t)); CArray loc = ObjectGenerator.GetGenerator().location(pro.getLocation()); ret.put("location", loc); MCProjectileSource shooter = pro.getShooter(); if(shooter instanceof MCBlockProjectileSource) { ret.put("shooter", ObjectGenerator.GetGenerator().location( ((MCBlockProjectileSource) shooter).getBlock().getLocation())); } else if(shooter instanceof MCEntity) { ret.put("shooter", new CString(((MCEntity) shooter).getUniqueId().toString(), t)); } else { ret.put("shooter", CNull.NULL); } MCBlock hitblock = e.getHitBlock(); if(hitblock != null) { ret.put("hit", ObjectGenerator.GetGenerator().location(hitblock.getLocation(), false)); ret.put("hittype", new CString("BLOCK", t)); } else { MCEntity hitentity = e.getHitEntity(); if(hitentity != null) { ret.put("hit", new CString(hitentity.getUniqueId().toString(), t)); ret.put("hittype", new CString("ENTITY", t)); } } return ret; } @Override public Driver driver() { return Driver.PROJECTILE_HIT; } @Override public boolean modifyEvent(String key, Construct value, BindableEvent event) { if (event instanceof MCProjectileHitEvent) { MCProjectileHitEvent e = (MCProjectileHitEvent) event; if (key.equalsIgnoreCase("shooter")) { MCLivingEntity le; if (value instanceof CNull) { le = null; } else { le = Static.getLivingEntity(value, value.getTarget()); } e.getEntity().setShooter(le); } } return false; } @Override public CHVersion since() { return CHVersion.V3_3_1; } } @api public static class projectile_launch extends AbstractEvent { @Override public String getName() { return "projectile_launch"; } @Override public Driver driver() { return Driver.PROJECTILE_LAUNCH; } @Override public String docs() { return "{type: <macro> The entity type of the projectile | world: <macro>" + " | shootertype: <macro> The entity type of the shooter, or 'block', or 'null'}" + " This event is called when a projectile is launched." + " Cancelling the event will only cancel the launching of the projectile." + " For instance when a player shoots an arrow with a bow, if the event is cancelled the bow will still take damage from use." + " {id: The entityID of the projectile | type: The entity type of the projectile |" + " shooter: The entityID of the shooter (null if the projectile is launched by a dispenser) |" + " shootertype: The entity type of the shooter (null if the projectile is launched by a dispenser) |" + " player: the player which has launched the projectile (null if the shooter is not a player) |" + " location: from where the projectile is launched | velocity: the velocity of the projectile}" + " {velocity}" + " {}"; } @Override public CHVersion since() { return CHVersion.V3_3_1; } @Override public boolean matches(Map<String, Construct> prefilter, BindableEvent event) throws PrefilterNonMatchException { if (event instanceof MCProjectileLaunchEvent) { MCProjectileLaunchEvent projectileLaunchEvent = (MCProjectileLaunchEvent) event; Prefilters.match(prefilter, "type", projectileLaunchEvent.getEntityType().name(), PrefilterType.MACRO); MCProjectileSource shooter = projectileLaunchEvent.getEntity().getShooter(); if (shooter != null) { if (shooter instanceof MCBlockProjectileSource) { Prefilters.match(prefilter, "shootertype", "block", PrefilterType.MACRO); } else if (shooter instanceof MCEntity) { Prefilters.match(prefilter, "shootertype", ((MCEntity) shooter).getType().name(), PrefilterType.MACRO); } } else { Prefilters.match(prefilter, "shootertype", "null", PrefilterType.MACRO); } Prefilters.match(prefilter, "world", projectileLaunchEvent.getEntity().getWorld().getName(), PrefilterType.MACRO); return true; } else { return false; } } @Override public BindableEvent convert(CArray manualObject, Target t) { return null; } @Override public Map<String, Construct> evaluate(BindableEvent event) throws EventException { if (event instanceof MCProjectileLaunchEvent) { MCProjectileLaunchEvent projectileLaunchEvent = (MCProjectileLaunchEvent) event; Map<String, Construct> mapEvent = evaluate_helper(event); MCProjectile projectile = projectileLaunchEvent.getEntity(); mapEvent.put("id", new CString(projectile.getUniqueId().toString(), Target.UNKNOWN)); mapEvent.put("type", new CString(projectileLaunchEvent.getEntityType().name(), Target.UNKNOWN)); MCProjectileSource shooter = projectile.getShooter(); if (shooter instanceof MCEntity) { MCEntity es = (MCEntity) shooter; mapEvent.put("shooter", new CString(es.getUniqueId().toString(), Target.UNKNOWN)); mapEvent.put("shootertype", new CString(es.getType().name(), Target.UNKNOWN)); if (es instanceof MCPlayer) { mapEvent.put("player", new CString(((MCPlayer) es).getName(), Target.UNKNOWN)); } else { mapEvent.put("player", CNull.NULL); } } else if (shooter instanceof MCBlockProjectileSource) { mapEvent.put("shooter", ObjectGenerator.GetGenerator().location( ((MCBlockProjectileSource) shooter).getBlock().getLocation())); mapEvent.put("shootertype", new CString("BLOCK", Target.UNKNOWN)); mapEvent.put("player", CNull.NULL); } else { mapEvent.put("shooter", CNull.NULL); mapEvent.put("shootertype", CNull.NULL); mapEvent.put("player", CNull.NULL); } mapEvent.put("location", ObjectGenerator.GetGenerator().location(projectile.getLocation())); CArray velocity = ObjectGenerator.GetGenerator().vector(projectile.getVelocity(), Target.UNKNOWN); velocity.set("magnitude", new CDouble(projectile.getVelocity().length(), Target.UNKNOWN), Target.UNKNOWN); mapEvent.put("velocity", velocity); return mapEvent; } else { throw new EventException("Cannot convert event to ProjectileLaunchEvent"); } } @Override public boolean modifyEvent(String key, Construct value, BindableEvent event) { if (event instanceof MCProjectileLaunchEvent) { MCProjectileLaunchEvent projectileLaunchEvent = (MCProjectileLaunchEvent) event; if (key.equals("velocity")) { projectileLaunchEvent.getEntity().setVelocity(ObjectGenerator.GetGenerator().vector(value, value.getTarget())); return true; } } return false; } @Override public void preExecution(Environment env, ActiveEvent activeEvent) { if(activeEvent.getUnderlyingEvent() instanceof MCProjectileLaunchEvent){ // Static lookups of the entity don't work here, so we need to inject them MCEntity entity = ((MCProjectileLaunchEvent)activeEvent.getUnderlyingEvent()).getEntity(); Static.InjectEntity(entity); } } @Override public void postExecution(Environment env, ActiveEvent activeEvent) { if(activeEvent.getUnderlyingEvent() instanceof MCProjectileLaunchEvent){ MCEntity entity = ((MCProjectileLaunchEvent)activeEvent.getUnderlyingEvent()).getEntity(); Static.UninjectEntity(entity); } } } @api public static class entity_death extends AbstractEvent { @Override public String getName() { return "entity_death"; } @Override public String docs() { return "{id: <macro> The entityID | type: <macro> The type of entity dying.}" + " Fires when any living entity dies." + " {type | id: The entityID | drops: an array of item arrays of each stack" + " | xp | cause: the last entity_damage object for this entity" + " | location: where the entity was when it died}" + " {drops: an array of item arrays of what will be dropped," + " replaces the normal drops, can be null | xp: the amount of xp to drop}" + " {id|drops|xp}"; } @Override public boolean matches(Map<String, Construct> prefilter, BindableEvent e) throws PrefilterNonMatchException { if (e instanceof MCEntityDeathEvent) { MCEntityDeathEvent event = (MCEntityDeathEvent) e; Prefilters.match(prefilter, "id", event.getEntity().getUniqueId().toString(), PrefilterType.MACRO); Prefilters.match(prefilter, "type", event.getEntity().getType().name(), PrefilterType.MACRO); return true; } return false; } @Override public BindableEvent convert(CArray manualObject, Target t) { return null; } @Override public Map<String, Construct> evaluate(BindableEvent event) throws EventException { if (event instanceof MCEntityDeathEvent) { MCEntityDeathEvent e = (MCEntityDeathEvent) event; final Target t = Target.UNKNOWN; MCLivingEntity dead = e.getEntity(); Map<String, Construct> map = evaluate_helper(event); CArray drops = new CArray(t); for(MCItemStack is : e.getDrops()){ drops.push(ObjectGenerator.GetGenerator().item(is, t), t); } map.put("type", new CString(dead.getType().name(), t)); map.put("id", new CString(dead.getUniqueId().toString(), t)); map.put("drops", drops); map.put("xp", new CInt(e.getDroppedExp(), t)); CArray cod = CArray.GetAssociativeArray(t); Map<String, Construct> ldc = parseEntityDamageEvent(dead.getLastDamageCause(), new HashMap<String, Construct>()); for (Map.Entry<String, Construct> entry : ldc.entrySet()) { cod.set(entry.getKey(), entry.getValue(), t); } map.put("cause", cod); map.put("location", ObjectGenerator.GetGenerator().location(dead.getLocation())); return map; } else { throw new EventException("Cannot convert e to EntityDeathEvent"); } } @Override public Driver driver() { return Driver.ENTITY_DEATH; } @Override public boolean modifyEvent(String key, Construct value, BindableEvent event) { if (event instanceof MCEntityDeathEvent) { MCEntityDeathEvent e = (MCEntityDeathEvent) event; if (key.equals("xp")) { e.setDroppedExp(Static.getInt32(value, value.getTarget())); return true; } if(key.equals("drops")){ if(value instanceof CNull){ value = new CArray(value.getTarget()); } if(!(value instanceof CArray)){ throw new CRECastException("drops must be an array, or null", value.getTarget()); } e.clearDrops(); CArray drops = (CArray) value; for(String dropID : drops.stringKeySet()){ e.addDrop(ObjectGenerator.GetGenerator().item(drops.get(dropID, value.getTarget()), value.getTarget())); } return true; } } return false; } @Override public CHVersion since() { return CHVersion.V3_3_1; } } @api public static class creature_spawn extends AbstractEvent { @Override public String getName() { return "creature_spawn"; } @Override public String docs() { return "{type: <macro> | reason: <macro> One of " + StringUtils.Join(MCSpawnReason.values(), ", ", ", or ", " or ") + "}" + " Fired when a living entity spawns on the server." + " {type: the type of creature spawning | id: the entityID of the creature" + " | reason: the reason this creature is spawning | location: locationArray of the event}" + " {type: Spawn a different entity instead. This will fire a new event. If the entity type is living," + " it will fire creature_spawn event with a reason of 'CUSTOM'.}" + " {}"; } @Override public boolean matches(Map<String, Construct> prefilter, BindableEvent event) throws PrefilterNonMatchException { if(!(event instanceof MCCreatureSpawnEvent)) { return false; } MCCreatureSpawnEvent e = (MCCreatureSpawnEvent) event; Prefilters.match(prefilter, "type", e.getEntity().getType().name(), PrefilterType.MACRO); Prefilters.match(prefilter, "reason", e.getSpawnReason().name(), PrefilterType.MACRO); return true; } @Override public BindableEvent convert(CArray manualObject, Target t) { return null; } @Override public Map<String, Construct> evaluate(BindableEvent event) throws EventException { if(!(event instanceof MCCreatureSpawnEvent)) { throw new EventException("Could not convert to MCCreatureSpawnEvent"); } MCCreatureSpawnEvent e = (MCCreatureSpawnEvent) event; Target t = Target.UNKNOWN; Map<String, Construct> map = evaluate_helper(e); map.put("type", new CString(e.getEntity().getType().name(), t)); map.put("id", new CString(e.getEntity().getUniqueId().toString(), t)); map.put("reason", new CString(e.getSpawnReason().name(), t)); map.put("location", ObjectGenerator.GetGenerator().location(e.getLocation())); return map; } @Override public Driver driver() { return Driver.CREATURE_SPAWN; } @Override public boolean modifyEvent(String key, Construct value, BindableEvent event) { MCCreatureSpawnEvent e = (MCCreatureSpawnEvent) event; if (key.equals("type")) { MCEntityType type; try { type = MCEntityType.valueOf(value.val()); e.setType(type); } catch (IllegalArgumentException iae) { throw new CREFormatException(value.val() + " is not a valid entity type.", value.getTarget()); } return true; } return false; } @Override public CHVersion since() { return CHVersion.V3_3_1; } @Override public void preExecution(Environment env, ActiveEvent activeEvent) { if(activeEvent.getUnderlyingEvent() instanceof MCCreatureSpawnEvent){ // Static lookups of the entity don't work here, so we need to inject them MCEntity entity = ((MCCreatureSpawnEvent)activeEvent.getUnderlyingEvent()).getEntity(); Static.InjectEntity(entity); } } @Override public void postExecution(Environment env, ActiveEvent activeEvent) { if(activeEvent.getUnderlyingEvent() instanceof MCCreatureSpawnEvent){ MCEntity entity = ((MCCreatureSpawnEvent)activeEvent.getUnderlyingEvent()).getEntity(); Static.UninjectEntity(entity); } } } @api public static class entity_damage extends AbstractEvent { @Override public String getName() { return "entity_damage"; } @Override public String docs() { return "{id: <macro> The entityID | type: <macro> The type of entity being damaged" + " | cause: <macro> One of " + StringUtils.Join(MCDamageCause.values(), ", ", ", or ", " or ") + " | world: <string match>} Fires when any loaded entity takes damage." + " {type: The type of entity the got damaged | id: The entityID of the victim" + " | player: the player who got damaged (only present if type is PLAYER) | world | location" + " | cause: The type of damage | amount | finalamount: health entity will lose after modifiers" + " | damager: If the source of damage is a player this will contain their name, otherwise it will be" + " the entityID of the damager (only available when an entity causes damage)" + " | shooter: The name of the player who shot, otherwise the entityID" + " (only available when damager is a projectile)}" + " {amount: raw amount of damage (in half hearts)}" + " {}"; } @Override public boolean matches(Map<String, Construct> prefilter, BindableEvent event) throws PrefilterNonMatchException { if(event instanceof MCEntityDamageEvent){ MCEntityDamageEvent e = (MCEntityDamageEvent) event; Prefilters.match(prefilter, "id", e.getEntity().getUniqueId().toString(), Prefilters.PrefilterType.MACRO); Prefilters.match(prefilter, "type", e.getEntity().getType().name(), Prefilters.PrefilterType.MACRO); Prefilters.match(prefilter, "cause", e.getCause().name(), Prefilters.PrefilterType.MACRO); Prefilters.match(prefilter, "world", e.getEntity().getWorld().getName(), Prefilters.PrefilterType.STRING_MATCH); return true; } return false; } @Override public BindableEvent convert(CArray manualObject, Target t) { return null; } @Override public Map<String, Construct> evaluate(BindableEvent e) throws EventException { if (e instanceof MCEntityDamageEvent) { MCEntityDamageEvent event = (MCEntityDamageEvent) e; Map<String, Construct> map = evaluate_helper(e); map = parseEntityDamageEvent(event, map); return map; } else { throw new EventException("Cannot convert e to MCEntityDamageEvent"); } } @Override public Driver driver() { return Driver.ENTITY_DAMAGE; } @Override public boolean modifyEvent(String key, Construct value, BindableEvent event) { MCEntityDamageEvent e = (MCEntityDamageEvent) event; if (key.equals("amount")) { e.setDamage(Static.getDouble(value, value.getTarget())); return true; } return false; } @Override public CHVersion since() { return CHVersion.V3_3_1; } } @api public static class player_interact_entity extends AbstractEvent { @Override public String getName() { return "player_interact_entity"; } @Override public String docs() { return "{clicked: <macro> the type of entity being clicked" + " | hand: <string match> The hand the player clicked with, can be either main_hand or off_hand}" + " Fires when a player right clicks an entity. Note, not all entities are clickable." + " Interactions with Armor Stands do not trigger this event." + " {player: the player clicking | clicked | hand | id: the id of the entity" + " | data: if a player is clicked, this will contain their name}" + " {}" + " {player|clicked|id|data}"; } @Override public boolean matches(Map<String, Construct> prefilter, BindableEvent event) throws PrefilterNonMatchException { if(event instanceof MCPlayerInteractEntityEvent){ MCPlayerInteractEntityEvent e = (MCPlayerInteractEntityEvent) event; Prefilters.match(prefilter, "clicked", e.getEntity().getType().name(), Prefilters.PrefilterType.MACRO); if(e.getHand() == MCEquipmentSlot.WEAPON) { Prefilters.match(prefilter, "hand", "main_hand", PrefilterType.STRING_MATCH); } else { Prefilters.match(prefilter, "hand", "off_hand", PrefilterType.STRING_MATCH); } return true; } return false; } @Override public BindableEvent convert(CArray manualObject, Target t) { return null; } @Override public Map<String, Construct> evaluate(BindableEvent e) throws EventException { if (e instanceof MCPlayerInteractEntityEvent) { MCPlayerInteractEntityEvent event = (MCPlayerInteractEntityEvent) e; Map<String, Construct> map = evaluate_helper(e); map.put("player", new CString(event.getPlayer().getName(), Target.UNKNOWN)); map.put("clicked", new CString(event.getEntity().getType().name(), Target.UNKNOWN)); map.put("id", new CString(event.getEntity().getUniqueId().toString(), Target.UNKNOWN)); String data = ""; if(event.getEntity() instanceof MCPlayer) { data = ((MCPlayer)event.getEntity()).getName(); } map.put("data", new CString(data, Target.UNKNOWN)); if(event.getHand() == MCEquipmentSlot.WEAPON) { map.put("hand", new CString("main_hand", Target.UNKNOWN)); } else { map.put("hand", new CString("off_hand", Target.UNKNOWN)); } return map; } else { throw new EventException("Cannot convert e to MCPlayerInteractEntityEvent"); } } @Override public Driver driver() { return Driver.PLAYER_INTERACT_ENTITY; } @Override public boolean modifyEvent(String key, Construct value, BindableEvent event) { return false; } @Override public CHVersion since() { return CHVersion.V3_3_1; } } @api public static class player_interact_at_entity extends AbstractEvent { @Override public String getName() { return "player_interact_at_entity"; } @Override public String docs() { return "{clicked: <macro> the type of entity being clicked" + " | hand: <string match> The hand the player clicked with, can be either main_hand or off_hand" + " | x: <expression> offset of clicked location from entity location on the x axis" + " | y: <expression> | z: <expression> }" + " Fires when a player right clicks an entity. This event is like player_interact_entity but also" + " has the click position, and when cancelled only cancels interactions with Armor Stand entities." + " {player: the player clicking | clicked | hand | id: the id of the entity" + " | data: if a player is clicked, this will contain their name" + " | position: offset of clicked location from entity location in an xyz array.}" + " {}" + " {player|clicked|id|data}"; } @Override public boolean matches(Map<String, Construct> prefilter, BindableEvent event) throws PrefilterNonMatchException { if(event instanceof MCPlayerInteractAtEntityEvent){ MCPlayerInteractAtEntityEvent e = (MCPlayerInteractAtEntityEvent) event; Prefilters.match(prefilter, "clicked", e.getEntity().getType().name(), Prefilters.PrefilterType.MACRO); if(e.getHand() == MCEquipmentSlot.WEAPON) { Prefilters.match(prefilter, "hand", "main_hand", PrefilterType.STRING_MATCH); } else { Prefilters.match(prefilter, "hand", "off_hand", PrefilterType.STRING_MATCH); } Vector3D position = e.getClickedPosition(); Prefilters.match(prefilter, "x", position.X(), Prefilters.PrefilterType.EXPRESSION); Prefilters.match(prefilter, "y", position.Y(), Prefilters.PrefilterType.EXPRESSION); Prefilters.match(prefilter, "z", position.Z(), Prefilters.PrefilterType.EXPRESSION); return true; } return false; } @Override public BindableEvent convert(CArray manualObject, Target t) { return null; } @Override public Map<String, Construct> evaluate(BindableEvent e) throws EventException { if (e instanceof MCPlayerInteractAtEntityEvent) { MCPlayerInteractAtEntityEvent event = (MCPlayerInteractAtEntityEvent) e; Map<String, Construct> map = evaluate_helper(e); map.put("player", new CString(event.getPlayer().getName(), Target.UNKNOWN)); map.put("clicked", new CString(event.getEntity().getType().name(), Target.UNKNOWN)); map.put("id", new CString(event.getEntity().getUniqueId().toString(), Target.UNKNOWN)); map.put("position", ObjectGenerator.GetGenerator().vector(event.getClickedPosition(), Target.UNKNOWN)); String data = ""; if(event.getEntity() instanceof MCPlayer) { data = ((MCPlayer)event.getEntity()).getName(); } map.put("data", new CString(data, Target.UNKNOWN)); if(event.getHand() == MCEquipmentSlot.WEAPON) { map.put("hand", new CString("main_hand", Target.UNKNOWN)); } else { map.put("hand", new CString("off_hand", Target.UNKNOWN)); } return map; } else { throw new EventException("Cannot convert e to MCPlayerInteractAtEntityEvent"); } } @Override public Driver driver() { return Driver.PLAYER_INTERACT_AT_ENTITY; } @Override public boolean modifyEvent(String key, Construct value, BindableEvent event) { return false; } @Override public CHVersion since() { return CHVersion.V3_3_1; } } @api public static class item_drop extends AbstractEvent { @Override public String getName() { return "item_drop"; } @Override public String docs() { return "{player: <macro match> | item: <item match>} " + "This event is called when a player drops an item. " + "{player: The player | item: An item array representing " + "the item being dropped. } " + "{item: setting this to null removes the dropped item} " + "{player|item}"; } @Override public BindableEvent convert(CArray manualObject, Target t) { return null; } @Override public CHVersion since() { return CHVersion.V3_3_1; } @Override public Driver driver() { return Driver.ITEM_DROP; } @Override public boolean matches(Map<String, Construct> prefilter, BindableEvent e) throws PrefilterNonMatchException { if (e instanceof MCPlayerDropItemEvent) { MCPlayerDropItemEvent event = (MCPlayerDropItemEvent)e; Prefilters.match(prefilter, "item", Static.ParseItemNotation(event.getItemDrop().getItemStack()), Prefilters.PrefilterType.ITEM_MATCH); Prefilters.match(prefilter, "player", event.getPlayer().getName(), Prefilters.PrefilterType.MACRO); return true; } return false; } @Override public Map<String, Construct> evaluate(BindableEvent e) throws EventException { if (e instanceof MCPlayerDropItemEvent) { MCPlayerDropItemEvent event = (MCPlayerDropItemEvent) e; Map<String, Construct> map = evaluate_helper(e); map.put("player", new CString(event.getPlayer().getName(), Target.UNKNOWN)); map.put("item", ObjectGenerator.GetGenerator().item(event.getItemDrop().getItemStack(), Target.UNKNOWN)); map.put("id", new CString(event.getItemDrop().getUniqueId().toString(), Target.UNKNOWN)); return map; } else { throw new EventException("Cannot convert e to MCPlayerDropItemEvent"); } } @Override public boolean modifyEvent(String key, Construct value, BindableEvent event) { if (event instanceof MCPlayerDropItemEvent) { MCPlayerDropItemEvent e = (MCPlayerDropItemEvent)event; if (key.equalsIgnoreCase("item")) { MCItemStack stack = ObjectGenerator.GetGenerator().item(value, value.getTarget()); e.setItemStack(stack); return true; } } return false; } } @api public static class item_pickup extends AbstractEvent { @Override public String getName() { return "item_pickup"; } @Override public String docs() { return "{player: <macro match> | item: <item match>} " + "This event is called when a player picks up an item." + "{player: The player | item: An item array representing " + "the item being picked up | " + "remaining: Other items left on the ground. } " + "{item: setting this to null will remove the item from the world} " + "{player|item|remaining}"; } @Override public boolean matches(Map<String, Construct> prefilter, BindableEvent e) throws PrefilterNonMatchException { if (e instanceof MCPlayerPickupItemEvent) { MCPlayerPickupItemEvent event = (MCPlayerPickupItemEvent)e; Prefilters.match(prefilter, "item", Static.ParseItemNotation(event.getItem().getItemStack()), Prefilters.PrefilterType.ITEM_MATCH); Prefilters.match(prefilter, "player", event.getPlayer().getName(), Prefilters.PrefilterType.MACRO); return true; } return false; } @Override public BindableEvent convert(CArray manualObject, Target t) { return null; } @Override public Map<String, Construct> evaluate(BindableEvent e) throws EventException { if (e instanceof MCPlayerPickupItemEvent) { MCPlayerPickupItemEvent event = (MCPlayerPickupItemEvent) e; Map<String, Construct> map = evaluate_helper(e); //Fill in the event parameters map.put("player", new CString(event.getPlayer().getName(), Target.UNKNOWN)); map.put("id", new CString(event.getItem().getUniqueId().toString(), Target.UNKNOWN)); map.put("item", ObjectGenerator.GetGenerator().item(event.getItem().getItemStack(), Target.UNKNOWN)); map.put("remaining", new CInt(event.getRemaining(), Target.UNKNOWN)); return map; } else { throw new EventException("Cannot convert e to MCPlayerPickupItemEvent"); } } @Override public Driver driver() { return Driver.ITEM_PICKUP; } @Override public boolean modifyEvent(String key, Construct value, BindableEvent event) { if (event instanceof MCPlayerPickupItemEvent) { MCPlayerPickupItemEvent e = (MCPlayerPickupItemEvent)event; if (key.equalsIgnoreCase("item")) { MCItemStack stack = ObjectGenerator.GetGenerator().item(value, value.getTarget()); e.setItemStack(stack); return true; } } return false; } @Override public CHVersion since() { return CHVersion.V3_3_1; } } @api public static class entity_damage_player extends AbstractEvent { @Override public String getName() { return "entity_damage_player"; } @Override public String docs() { return "{id: <macro match> The entityID | damager: <macro match>} " + "This event is called when a player is damaged by another entity." + "{player: The player being damaged | damager: The type of entity causing damage" + " | amount: raw amount of damage caused | finalamount: health player will lose after modifiers" + " | cause: the cause of damage | data: the attacking player's name or the shooter if damager is a" + " projectile | id: EntityID of the damager | location} " + "{amount} " + "{player|amount|damager|cause|data|id}"; } @Override public boolean matches(Map<String, Construct> prefilter, BindableEvent e) throws PrefilterNonMatchException { if (e instanceof MCEntityDamageByEntityEvent) { MCEntityDamageByEntityEvent event = (MCEntityDamageByEntityEvent) e; Prefilters.match(prefilter, "id", event.getDamager().getUniqueId().toString(), PrefilterType.MACRO); Prefilters.match(prefilter, "damager", event.getDamager().getType().name(), PrefilterType.MACRO); return event.getEntity() instanceof MCPlayer; } return false; } @Override public BindableEvent convert(CArray manualObject, Target t) { throw ConfigRuntimeException.CreateUncatchableException("Unsupported Operation", Target.UNKNOWN); } @Override public Map<String, Construct> evaluate(BindableEvent e) throws EventException { if(e instanceof MCEntityDamageByEntityEvent){ MCEntityDamageByEntityEvent event = (MCEntityDamageByEntityEvent) e; Map<String, Construct> map = evaluate_helper(e); Target t = Target.UNKNOWN; // Guaranteed to be a player via matches String name = ((MCPlayer)event.getEntity()).getName(); map.put("player", new CString(name, t)); String dtype = event.getDamager().getType().name(); map.put("damager", new CString(dtype, t)); map.put("cause", new CString(event.getCause().name(), t)); map.put("amount", new CDouble(event.getDamage(), t)); map.put("finalamount", new CDouble(event.getFinalDamage(), t)); map.put("id", new CString(event.getDamager().getUniqueId().toString(), t)); map.put("location", ObjectGenerator.GetGenerator().location(event.getEntity().getLocation())); Construct data = CNull.NULL; if(event.getDamager() instanceof MCPlayer) { data = new CString(((MCPlayer)event.getDamager()).getName(), t); } else if (event.getDamager() instanceof MCProjectile) { MCProjectileSource shooter = ((MCProjectile)event.getDamager()).getShooter(); if(shooter instanceof MCPlayer) { data = new CString(((MCPlayer)shooter).getName(), t); } else if(shooter instanceof MCEntity) { data = new CString(((MCEntity)shooter).getType().name().toUpperCase(), t); } else if(shooter instanceof MCBlockProjectileSource) { data = ObjectGenerator.GetGenerator().location(((MCBlockProjectileSource) shooter).getBlock().getLocation()); } } map.put("data", data); return map; } else { throw new EventException("Cannot convert e to EntityDamageByEntityEvent"); } } @Override public Driver driver() { return Driver.ENTITY_DAMAGE_PLAYER; } @Override public boolean modifyEvent(String key, Construct value, BindableEvent e) { MCEntityDamageByEntityEvent event = (MCEntityDamageByEntityEvent)e; if (key.equals("amount")) { if (value instanceof CInt) { event.setDamage(Integer.parseInt(value.val())); return true; } } return false; } @Override public CHVersion since() { return CHVersion.V3_3_1; } } @api public static class target_player extends AbstractEvent{ @Override public String getName() { return "target_player"; } @Override public String docs() { return "{player: <macro> | mobtype: <macro> | reason: <macro>} " + "This event is called when a player is targeted by a mob." + "{player: The player's name | mobtype: The type of mob targeting " + "the player (this will be all capitals!) | id: The UUID of the mob" + " | reason: The reason the entity is targeting the player. Can be one of " + StringUtils.Join(MCTargetReason.values(), ", ", ", or ", " or ") + "}" + "{player: target a different player, or null to make the mob re-look for targets}" + "{player|mobtype|reason}"; } @Override public CHVersion since() { return CHVersion.V3_3_1; } @Override public Driver driver(){ return Driver.TARGET_ENTITY; } @Override public boolean matches(Map<String, Construct> prefilter, BindableEvent e) throws PrefilterNonMatchException { if(e instanceof MCEntityTargetEvent) { MCEntityTargetEvent ete = (MCEntityTargetEvent) e; Prefilters.match(prefilter, "mobtype", ete.getEntityType().name(), Prefilters.PrefilterType.MACRO); Prefilters.match(prefilter, "player", ((MCPlayer) ete.getTarget()).getName(), Prefilters.PrefilterType.MACRO); Prefilters.match(prefilter, "reason", ete.getReason().name(), Prefilters.PrefilterType.MACRO); return true; } return false; } @Override public Map<String, Construct> evaluate(BindableEvent e) throws EventException { if(e instanceof MCEntityTargetEvent){ MCEntityTargetEvent ete = (MCEntityTargetEvent) e; Map<String, Construct> map = evaluate_helper(e); map.put("player", new CString(((MCPlayer)ete.getTarget()).getName(), Target.UNKNOWN)); map.put("mobtype", new CString(ete.getEntityType().name(), Target.UNKNOWN)); map.put("id", new CString(ete.getEntity().getUniqueId().toString(), Target.UNKNOWN)); map.put("reason", new CString(ete.getReason().name(), Target.UNKNOWN)); return map; } else { throw new EventException("Cannot convert e to EntityTargetLivingEntityEvent"); } } @Override public boolean modifyEvent(String key, Construct value, BindableEvent event) { if(event instanceof MCEntityTargetEvent){ MCEntityTargetEvent ete = (MCEntityTargetEvent)event; if (key.equals("player")) { if (value instanceof CNull) { ete.setTarget(null); return true; } else if (value instanceof CString) { MCPlayer p = Static.GetPlayer(value.val(), value.getTarget()); if (p.isOnline()) { ete.setTarget((MCEntity)p); return true; } } } } return false; } @Override public BindableEvent convert(CArray manual, Target t){ MCEntityTargetEvent e = EventBuilder.instantiate(MCEntityTargetEvent.class, Static.GetPlayer(manual.get("player", Target.UNKNOWN).val(), Target.UNKNOWN)); return e; } } @api public static class entity_enter_portal extends AbstractEvent { @Override public String getName() { return "entity_enter_portal"; } @Override public String docs() { return "{type: <macro> the type of entity | block: <math match> the blockID of the portal" + " world: <macro> the world in which the portal was entered }" + " Fires when an entity touches a portal block." + " {id: the entityID of the entity | location: the location of the block touched | type | block}" + " {}" + " {}"; } @Override public boolean matches(Map<String, Construct> prefilter, BindableEvent e) throws PrefilterNonMatchException { if (e instanceof MCEntityEnterPortalEvent) { MCEntityEnterPortalEvent event = (MCEntityEnterPortalEvent) e; Prefilters.match(prefilter, "type", event.getEntity().getType().name(), PrefilterType.MACRO); Prefilters.match(prefilter, "block", event.getLocation().getBlock().getTypeId(), PrefilterType.MATH_MATCH); Prefilters.match(prefilter, "world", event.getLocation().getWorld().getName(), PrefilterType.MACRO); return true; } return false; } @Override public BindableEvent convert(CArray manualObject, Target t) { throw ConfigRuntimeException.CreateUncatchableException("Unsupported Operation", Target.UNKNOWN); } @Override public Map<String, Construct> evaluate(BindableEvent e) throws EventException { if (e instanceof MCEntityEnterPortalEvent) { MCEntityEnterPortalEvent event = (MCEntityEnterPortalEvent) e; Target t = Target.UNKNOWN; Map<String, Construct> ret = evaluate_helper(event); ret.put("id", new CString(event.getEntity().getUniqueId().toString(), t)); ret.put("type", new CString(event.getEntity().getType().name(), t)); ret.put("location", ObjectGenerator.GetGenerator().location(event.getLocation(), false)); ret.put("block", new CInt(event.getLocation().getBlock().getTypeId(), t)); return ret; } else { throw new EventException("Could not convert to MCPortalEnterEvent"); } } @Override public boolean modifyEvent(String key, Construct value, BindableEvent event) { return false; } @Override public Driver driver() { return Driver.ENTITY_ENTER_PORTAL; } @Override public CHVersion since() { return CHVersion.V3_3_1; } } @api public static class entity_change_block extends AbstractEvent { @Override public String getName() { return "entity_change_block"; } @Override public String docs() { return "{from: <math match> the block ID before the change | to: <math match> the block ID after change" + " | location: <location match> the location of the block changed}" + " Fires when an entity change block in some way." + " {entity: the entity ID of the entity which changed block | from: the block ID before the change" + " | data: the data value for the block being changed | to: the block ID after change" + " | location: the location of the block changed}" + " {}" + " {from|to|location}"; } @Override public boolean matches(Map<String, Construct> prefilter, BindableEvent e) throws PrefilterNonMatchException { if (e instanceof MCEntityChangeBlockEvent) { MCEntityChangeBlockEvent event = (MCEntityChangeBlockEvent) e; Prefilters.match(prefilter, "from", event.getBlock().getTypeId(), PrefilterType.MATH_MATCH); Prefilters.match(prefilter, "to", event.getTo().getType(), PrefilterType.MATH_MATCH); Prefilters.match(prefilter, "location", event.getBlock().getLocation(), PrefilterType.LOCATION_MATCH); return true; } return false; } @Override public BindableEvent convert(CArray manualObject, Target t) { return null; } @Override public Map<String, Construct> evaluate(BindableEvent e) throws EventException { if (e instanceof MCEntityChangeBlockEvent) { MCEntityChangeBlockEvent event = (MCEntityChangeBlockEvent) e; Target t = Target.UNKNOWN; Map<String, Construct> ret = evaluate_helper(event); ret.put("entity", new CString(event.getEntity().getUniqueId().toString(), t)); ret.put("from", new CInt(event.getBlock().getTypeId(), t)); ret.put("data", new CInt(event.getData(), t)); ret.put("to", new CInt(event.getTo().getType(), t)); ret.put("location", ObjectGenerator.GetGenerator().location(event.getBlock().getLocation(), false)); return ret; } else { throw new EventException("Could not convert to MCEntityChangeBlockEvent"); } } @Override public boolean modifyEvent(String key, Construct value, BindableEvent event) { return false; } @Override public Driver driver() { return Driver.ENTITY_CHANGE_BLOCK; } @Override public CHVersion since() { return CHVersion.V3_3_1; } } @api public static class entity_interact extends AbstractEvent { @Override public String getName() { return "entity_interact"; } @Override public String docs() { return "{type: <string match> the entity type" + " | blockname: <string match> The block name the entity is interacting with." + " | block: <item match> (deprecated) The numeric block id }" + " Fires when a non-player entity physically interacts with and triggers a block." + " (eg. pressure plates, redstone ore, farmland, tripwire, and wooden button)" + " {entity: the ID of the entity that interacted with the block | blockname | block (deprecated)" + " | location: the location of the interaction}" + " {}" + " {}"; } @Override public boolean matches(Map<String, Construct> prefilter, BindableEvent e) throws PrefilterNonMatchException { if (e instanceof MCEntityInteractEvent) { MCEntityInteractEvent event = (MCEntityInteractEvent) e; MCMaterial mat = event.getBlock().getType(); Prefilters.match(prefilter, "type", event.getEntity().getType().name(), PrefilterType.STRING_MATCH); Prefilters.match(prefilter, "blockname", mat.getName(), PrefilterType.STRING_MATCH); Prefilters.match(prefilter, "block", mat.getType(), PrefilterType.ITEM_MATCH); return true; } return false; } @Override public BindableEvent convert(CArray manualObject, Target t) { return null; } @Override public Map<String, Construct> evaluate(BindableEvent e) throws EventException { if (e instanceof MCEntityInteractEvent) { MCEntityInteractEvent event = (MCEntityInteractEvent) e; MCMaterial mat = event.getBlock().getType(); Target t = Target.UNKNOWN; Map<String, Construct> ret = evaluate_helper(event); ret.put("entity", new CString(event.getEntity().getUniqueId().toString(), t)); ret.put("blockname", new CString(mat.getName(), t)); ret.put("block", new CInt(mat.getType(), t)); ret.put("location", ObjectGenerator.GetGenerator().location(event.getBlock().getLocation(), false)); return ret; } else { throw new EventException("Could not convert to MCEntityInteractEvent"); } } @Override public boolean modifyEvent(String key, Construct value, BindableEvent event) { return false; } @Override public Driver driver() { return Driver.ENTITY_INTERACT; } @Override public CHVersion since() { return CHVersion.V3_3_1; } } public static Map<String, Construct> parseEntityDamageEvent(MCEntityDamageEvent event, Map<String, Construct> map) { if (event != null) { MCEntity victim = event.getEntity(); map.put("type", new CString(victim.getType().name(), Target.UNKNOWN)); map.put("id", new CString(victim.getUniqueId().toString(), Target.UNKNOWN)); map.put("cause", new CString(event.getCause().name(), Target.UNKNOWN)); map.put("amount", new CDouble(event.getDamage(), Target.UNKNOWN)); map.put("finalamount", new CDouble(event.getFinalDamage(), Target.UNKNOWN)); map.put("world", new CString(event.getEntity().getWorld().getName(), Target.UNKNOWN)); map.put("location", ObjectGenerator.GetGenerator().location(event.getEntity().getLocation())); if (event instanceof MCEntityDamageByEntityEvent) { MCEntity damager = ((MCEntityDamageByEntityEvent) event).getDamager(); if (damager instanceof MCPlayer) { map.put("damager", new CString(((MCPlayer) damager).getName(), Target.UNKNOWN)); } else { map.put("damager", new CString(damager.getUniqueId().toString(), Target.UNKNOWN)); } if (damager instanceof MCProjectile) { MCProjectileSource shooter = ((MCProjectile) damager).getShooter(); if (shooter instanceof MCPlayer) { map.put("shooter", new CString(((MCPlayer) shooter).getName(), Target.UNKNOWN)); } else if (shooter instanceof MCEntity) { map.put("shooter", new CString(((MCEntity) shooter).getUniqueId().toString(), Target.UNKNOWN)); } else if (shooter instanceof MCBlockProjectileSource) { map.put("shooter", ObjectGenerator.GetGenerator().location(((MCBlockProjectileSource) shooter).getBlock().getLocation())); } } } } return map; } @api public static class hanging_break extends AbstractEvent { @Override public String getName() { return "hanging_break"; } @Override public Driver driver() { return Driver.HANGING_BREAK; } @Override public String docs() { return "{type: <macro> The entity type of the hanging entity | cause: <macro> The cause of the removing | world: <macro>}" + " This event is called when a hanged entity is broken." + " {id: The entityID of the hanging entity | type: The entity type of the hanging entity, can be ITEM_FRAME, PAINTING or LEASH_HITCH |" + " cause: The cause of the removing, can be " + StringUtils.Join(MCRemoveCause.values(), ", ", ", or ", " or ") + " | location: Where was the hanging entity before the removing |" + " remover: If the hanging entity has been removed by an other entity, this will contain its entityID, otherwise null |" + " player: If the hanging entity has been removed by a player, this will contain their name, otherwise null}" + " {}" + " {}"; } @Override public CHVersion since() { return CHVersion.V3_3_1; } @Override public boolean matches(Map<String, Construct> prefilter, BindableEvent event) throws PrefilterNonMatchException { if (event instanceof MCHangingBreakEvent) { MCHangingBreakEvent hangingBreakEvent = (MCHangingBreakEvent) event; MCHanging hanging = hangingBreakEvent.getEntity(); Prefilters.match(prefilter, "type", hanging.getType().name(), PrefilterType.MACRO); Prefilters.match(prefilter, "cause", hangingBreakEvent.getCause().name(), PrefilterType.MACRO); Prefilters.match(prefilter, "world", hanging.getWorld().getName(), PrefilterType.MACRO); return true; } else { return false; } } @Override public BindableEvent convert(CArray manualObject, Target t) { return null; } @Override public Map<String, Construct> evaluate(BindableEvent event) throws EventException { if (event instanceof MCHangingBreakEvent) { MCHangingBreakEvent hangingBreakEvent = (MCHangingBreakEvent) event; Map<String, Construct> mapEvent = evaluate_helper(event); MCHanging hanging = hangingBreakEvent.getEntity(); mapEvent.put("id", new CString(hanging.getUniqueId().toString(), Target.UNKNOWN)); mapEvent.put("type", new CString(hanging.getType().name(), Target.UNKNOWN)); mapEvent.put("location", ObjectGenerator.GetGenerator().location(hanging.getLocation())); mapEvent.put("cause", new CString(hangingBreakEvent.getCause().name(), Target.UNKNOWN)); MCEntity remover = hangingBreakEvent.getRemover(); if (remover != null) { mapEvent.put("remover", new CString(remover.getUniqueId().toString(), Target.UNKNOWN)); if (remover instanceof MCPlayer) { mapEvent.put("player", new CString(((MCPlayer) remover).getName(), Target.UNKNOWN)); } else { mapEvent.put("player", CNull.NULL); } } else { mapEvent.put("remover", CNull.NULL); mapEvent.put("player", CNull.NULL); } return mapEvent; } else { throw new EventException("Cannot convert event to HangingBreakEvent"); } } @Override public boolean modifyEvent(String key, Construct value, BindableEvent event) { return false; } } @api public static class entity_toggle_glide extends AbstractEvent { public String getName() { return "entity_toggle_glide"; } public String docs() { return "{type: <macro> The entity type of the entity | id: <macro> The entity id of the entity | player: <macro> The player triggering the event}" + " This event is called when an entity toggles it's gliding state (Using Elytra)." + " {id: The entityID of the entity | type: The entity type of the entity |" + " gliding: true if the entity is entering gliding mode, false if the entity is leaving it |" + " player: If the entity is a player, this will contain their name, otherwise null}" + " {}" + " {}"; } public boolean matches(Map<String, Construct> filter, BindableEvent e) throws PrefilterNonMatchException { if (e instanceof MCEntityToggleGlideEvent) { MCEntityToggleGlideEvent evt = (MCEntityToggleGlideEvent) e; MCEntity entity = evt.getEntity(); Prefilters.match(filter, "type", entity.getType().name(), Prefilters.PrefilterType.MACRO); Prefilters.match(filter, "id", entity.getUniqueId().toString(), Prefilters.PrefilterType.MACRO); if (entity instanceof MCPlayer) { Prefilters.match(filter, "player", ((MCPlayer) entity).getName(), Prefilters.PrefilterType.MACRO); } return true; } return false; } public BindableEvent convert(CArray manualObject, Target t) { return null; } public Map<String, Construct> evaluate(BindableEvent e) throws EventException { if (e instanceof MCEntityToggleGlideEvent) { MCEntityToggleGlideEvent evt = (MCEntityToggleGlideEvent) e; Map<String, Construct> ret = evaluate_helper(evt); Target t = Target.UNKNOWN; ret.put("gliding", CBoolean.GenerateCBoolean(evt.isGliding(), t)); ret.put("id", new CString(evt.getEntity().getUniqueId().toString(), t)); ret.put("type", new CString(evt.getEntityType().name(), t)); if (evt.getEntity() instanceof MCPlayer) { ret.put("player", new CString(((MCPlayer) evt.getEntity()).getName(), t)); } else { ret.put("player", CNull.NULL); } return ret; } else { throw new EventException("Could not convert to MCEntityToggleGlideEvent"); } } public boolean modifyEvent(String key, Construct value, BindableEvent event) throws ConfigRuntimeException { return false; } public Version since() { return CHVersion.V3_3_2; } public Driver driver() { return Driver.ENTITY_TOGGLE_GLIDE; } } @api public static class firework_explode extends AbstractEvent { @Override public Version since() { return CHVersion.V3_3_2; } @Override public String getName() { return "firework_explode"; } @Override public String docs() { return "{}" + " Fires when a firework rocket explodes." + " {id: The entityID of the firework rocket" + " | location: Where the firework rocket is exploding}" + " {}" + " {}"; } @Override public boolean matches(Map<String, Construct> prefilter, BindableEvent e) throws PrefilterNonMatchException { return true; } @Override public BindableEvent convert(CArray manualObject, Target t) { return null; } @Override public Map<String, Construct> evaluate(BindableEvent event) throws EventException { if (event instanceof MCFireworkExplodeEvent) { MCFireworkExplodeEvent e = (MCFireworkExplodeEvent) event; Map<String, Construct> ret = new HashMap<>(); MCFirework firework = e.getEntity(); ret.put("id", new CString(firework.getUniqueId().toString(), Target.UNKNOWN)); ret.put("location", ObjectGenerator.GetGenerator().location(firework.getLocation())); return ret; } else { throw new EventException("Could not convert to MCFireworkExplodeEvent"); } } @Override public Driver driver() { return Driver.FIREWORK_EXPLODE; } @Override public boolean modifyEvent(String key, Construct value, BindableEvent event) { return false; } } @api public static class entity_regain_health extends AbstractEvent { @Override public Version since() { return CHVersion.V3_3_2; } @Override public String getName() { return "entity_regain_health"; } @Override public String docs() { return "{reason: <macro>}" + " Fired when an entity regained the health." + " {id: The entity ID of regained entity" + " amount: The amount of regained the health |" + " cause: The cause of regain, one of: " + StringUtils.Join(MCRegainReason.values(), ", ") + " player: The regained player}" + " {amount}" + " {}"; } @Override public boolean matches(Map<String, Construct> prefilter, BindableEvent e) throws PrefilterNonMatchException { if (e instanceof MCEntityRegainHealthEvent) { MCEntityRegainHealthEvent event = (MCEntityRegainHealthEvent) e; Prefilters.match(prefilter, "reason", event.getRegainReason().name(), PrefilterType.MACRO); return true; } return false; } @Override public BindableEvent convert(CArray manualObject, Target t) { return null; } @Override public Map<String, Construct> evaluate(BindableEvent e) throws EventException { if (e instanceof MCEntityRegainHealthEvent) { MCEntityRegainHealthEvent event = (MCEntityRegainHealthEvent) e; Map<String, Construct> ret = evaluate_helper(e); ret.put("id", new CString(event.getEntity().getUniqueId().toString(), Target.UNKNOWN)); ret.put("amount", new CDouble(event.getAmount(), Target.UNKNOWN)); ret.put("reason", new CString(event.getRegainReason().name(), Target.UNKNOWN)); return ret; } else { throw new EventException("Could not convert to MCEntityRegainHealthEvent"); } } @Override public Driver driver() { return Driver.ENTITY_REGAIN_HEALTH; } @Override public boolean modifyEvent(String key, Construct value, BindableEvent event) { if (event instanceof MCEntityRegainHealthEvent) { MCEntityRegainHealthEvent e = (MCEntityRegainHealthEvent) event; if (key.equalsIgnoreCase("amount")) { e.setAmount(Static.getDouble32(value, value.getTarget())); return true; } } return false; } } @api public static class entity_portal_travel extends AbstractEvent { @Override public Version since() { return CHVersion.V3_3_2; } @Override public String getName() { return "entity_portal_travel"; } @Override public String docs() { return "{type: <macro>}" + " Fired when an entity travels through a portal." + " {id: The UUID of entity | type: The type of entity" + " | from: The location the entity is coming from" + " | to: The location the entity is going to. Returns null when using Nether portal and " + " \"allow-nether\" in server.properties is set to false or when using Ender portal and " + " \"allow-end\" in bukkit.yml is set to false." + " | creationradius: The maximum radius from the given location to create a portal." + " | searchradius: The search radius value for finding an available portal.}" + " {to|creationradius|searchradius}" + " {}"; } @Override public boolean matches(Map<String, Construct> prefilter, BindableEvent e) throws PrefilterNonMatchException { if (e instanceof MCEntityPortalEvent) { MCEntityPortalEvent event = (MCEntityPortalEvent) e; Prefilters.match(prefilter, "type", event.getEntity().getType().name(), PrefilterType.MACRO); return true; } return false; } @Override public BindableEvent convert(CArray manualObject, Target t) { return null; } @Override public Map<String, Construct> evaluate(BindableEvent e) throws EventException { if (e instanceof MCEntityPortalEvent) { MCEntityPortalEvent event = (MCEntityPortalEvent) e; Map<String, Construct> ret = new HashMap<>(); Target t = Target.UNKNOWN; ret.put("id", new CString(event.getEntity().getUniqueId().toString(), t)); ret.put("type", new CString(event.getEntity().getType().name(), t)); ret.put("from", ObjectGenerator.GetGenerator().location(event.getFrom())); MCLocation to = event.getTo(); if(to == null) { ret.put("to", CNull.NULL); } else { ret.put("to", ObjectGenerator.GetGenerator().location(to)); } ret.put("creationradius", new CInt(event.getPortalTravelAgent().getCreationRadius(), t)); ret.put("searchradius", new CInt(event.getPortalTravelAgent().getSearchRadius(), t)); return ret; } else { throw new EventException("Could not convert to MCEntityPortalEvent"); } } @Override public Driver driver() { return Driver.ENTITY_PORTAL_TRAVEL; } @Override public boolean modifyEvent(String key, Construct value, BindableEvent event) { if (event instanceof MCEntityPortalEvent) { MCEntityPortalEvent e = (MCEntityPortalEvent)event; if (key.equalsIgnoreCase("to")) { e.useTravelAgent(true); MCLocation loc = ObjectGenerator.GetGenerator().location(value, null, value.getTarget()); e.setTo(loc); return true; } if (key.equalsIgnoreCase("creationradius")) { e.useTravelAgent(true); e.getPortalTravelAgent().setCreationRadius(Static.getInt32(value, value.getTarget())); return true; } if (key.equalsIgnoreCase("searchradius")) { e.useTravelAgent(true); e.getPortalTravelAgent().setSearchRadius(Static.getInt32(value, value.getTarget())); return true; } } return false; } } }
package com.mcjty.rftools.dimension; import com.mcjty.rftools.RFTools; import com.mcjty.rftools.dimension.world.types.FeatureType; import com.mcjty.rftools.dimension.world.types.StructureType; import com.mcjty.rftools.dimension.world.types.TerrainType; import com.mcjty.rftools.items.dimlets.DimletType; import com.mcjty.rftools.items.dimlets.KnownDimletConfiguration; import com.mcjty.varia.Coordinate; import io.netty.buffer.ByteBuf; import net.minecraft.block.Block; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumChatFormatting; import net.minecraft.world.biome.BiomeGenBase; import org.apache.commons.lang3.tuple.Pair; import java.util.*; public class DimensionInformation { private final DimensionDescriptor descriptor; private final String name; private Coordinate spawnPoint = null; private TerrainType terrainType = TerrainType.TERRAIN_VOID; private Block baseBlockForTerrain = null; private Block fluidForTerrain = null; private Block baseFeatureBlock = null; // Block used for some of the features like tendrils or spheres. @todo private Set<FeatureType> featureTypes = new HashSet<FeatureType>(); private Block[] extraOregen = new Block[] {}; private Block[] fluidsForLakes = new Block[] {}; private Set<StructureType> structureTypes = new HashSet<StructureType>(); private List<BiomeGenBase> biomes = new ArrayList<BiomeGenBase>(); private String digitString = ""; private SkyDescriptor skyDescriptor; public DimensionInformation(String name, DimensionDescriptor descriptor) { this.name = name; this.descriptor = descriptor; List<Pair<DimensionDescriptor.DimletDescriptor,List<DimensionDescriptor.DimletDescriptor>>> dimlets = descriptor.getDimletsWithModifiers(); Random random = new Random(descriptor.calculateSeed()); calculateTerrainType(dimlets, random); calculateFeatureType(dimlets, random); calculateStructureType(dimlets, random); calculateBiomes(dimlets, random); calculateDigitString(dimlets); calculateSky(dimlets, random); } private void logDebug(EntityPlayer player, String message) { RFTools.message(player, EnumChatFormatting.YELLOW + message); } public void dump(EntityPlayer player) { String digits = getDigitString(); if (!digits.isEmpty()) { logDebug(player, " Digits: " + digits); } TerrainType terrainType = getTerrainType(); logDebug(player, " Terrain: " + terrainType.toString()); logDebug(player, " Base block: " + new ItemStack(baseBlockForTerrain).getDisplayName()); logDebug(player, " Base feature block: " + new ItemStack(baseFeatureBlock).getDisplayName()); logDebug(player, " Base fluid: " + new ItemStack(fluidForTerrain).getDisplayName()); for (BiomeGenBase biome : getBiomes()) { logDebug(player, " Biome: " + biome.biomeName); } for (FeatureType featureType : getFeatureTypes()) { logDebug(player, " Feature: " + featureType.toString()); } for (Block block : extraOregen) { logDebug(player, " Extra ore: " + new ItemStack(block).getDisplayName()); } for (Block block : fluidsForLakes) { logDebug(player, " Lake fluid: " + new ItemStack(block).getDisplayName()); } for (StructureType structureType : getStructureTypes()) { logDebug(player, " Structure: " + structureType.toString()); } logDebug(player, " Sun brightness: " + skyDescriptor.getSunBrightnessFactor()); logDebug(player, " Star brightness: " + skyDescriptor.getStarBrightnessFactor()); } public void toBytes(ByteBuf buf) { if (terrainType == null) { buf.writeInt(TerrainType.TERRAIN_VOID.ordinal()); } else { buf.writeInt(terrainType.ordinal()); } buf.writeInt(featureTypes.size()); for (FeatureType type : featureTypes) { buf.writeInt(type.ordinal()); } buf.writeInt(structureTypes.size()); for (StructureType type : structureTypes) { buf.writeInt(type.ordinal()); } buf.writeInt(biomes.size()); for (BiomeGenBase entry : biomes) { buf.writeInt(entry.biomeID); } buf.writeInt(digitString.length()); buf.writeBytes(digitString.getBytes()); buf.writeInt(Block.blockRegistry.getIDForObject(baseBlockForTerrain)); buf.writeInt(Block.blockRegistry.getIDForObject(baseFeatureBlock)); buf.writeInt(Block.blockRegistry.getIDForObject(fluidForTerrain)); buf.writeInt(extraOregen.length); for (Block block : extraOregen) { buf.writeInt(Block.blockRegistry.getIDForObject(block)); } buf.writeInt(fluidsForLakes.length); for (Block block : fluidsForLakes) { buf.writeInt(Block.blockRegistry.getIDForObject(block)); } skyDescriptor.toBytes(buf); } public void fromBytes(ByteBuf buf) { terrainType = TerrainType.values()[buf.readInt()]; int size = buf.readInt(); featureTypes.clear(); for (int i = 0 ; i < size ; i++) { featureTypes.add(FeatureType.values()[buf.readInt()]); } structureTypes.clear(); size = buf.readInt(); for (int i = 0 ; i < size ; i++) { structureTypes.add(StructureType.values()[buf.readInt()]); } biomes.clear(); size = buf.readInt(); for (int i = 0 ; i < size ; i++) { biomes.add(BiomeGenBase.getBiome(buf.readInt())); } byte[] dst = new byte[buf.readInt()]; buf.readBytes(dst); digitString = new String(dst); baseBlockForTerrain = (Block) Block.blockRegistry.getObjectById(buf.readInt()); baseFeatureBlock = (Block) Block.blockRegistry.getObjectById(buf.readInt()); fluidForTerrain = (Block) Block.blockRegistry.getObjectById(buf.readInt()); size = buf.readInt(); List<Block> blocks = new ArrayList<Block>(); for (int i = 0 ; i < size ; i++) { blocks.add((Block) Block.blockRegistry.getObjectById(buf.readInt())); } extraOregen = blocks.toArray(new Block[blocks.size()]); size = buf.readInt(); blocks = new ArrayList<Block>(); for (int i = 0 ; i < size ; i++) { blocks.add((Block) Block.blockRegistry.getObjectById(buf.readInt())); } fluidsForLakes = blocks.toArray(new Block[blocks.size()]); skyDescriptor = new SkyDescriptor.Builder().fromBytes(buf).build(); } public Coordinate getSpawnPoint() { return spawnPoint; } public void setSpawnPoint(Coordinate spawnPoint) { this.spawnPoint = spawnPoint; } private void calculateDigitString(List<Pair<DimensionDescriptor.DimletDescriptor,List<DimensionDescriptor.DimletDescriptor>>> dimlets) { dimlets = extractType(DimletType.DIMLET_DIGIT, dimlets); digitString = ""; for (Pair<DimensionDescriptor.DimletDescriptor, List<DimensionDescriptor.DimletDescriptor>> dimletWithModifiers : dimlets) { int id = dimletWithModifiers.getKey().getId(); digitString += KnownDimletConfiguration.idToDigit.get(id); } } private void calculateSky(List<Pair<DimensionDescriptor.DimletDescriptor,List<DimensionDescriptor.DimletDescriptor>>> dimlets, Random random) { dimlets = extractType(DimletType.DIMLET_SKY, dimlets); if (random.nextFloat() < 0.5f && dimlets.isEmpty()) { // If nothing was specified then there is random chance we get random sky stuff. List<Integer> skyIds = new ArrayList<Integer>(KnownDimletConfiguration.idToSkyDescriptor.keySet()); for (int i = 0 ; i < 1+random.nextInt(3) ; i++) { int id = skyIds.get(random.nextInt(skyIds.size())); List<DimensionDescriptor.DimletDescriptor> modifiers = Collections.emptyList(); dimlets.add(Pair.of(new DimensionDescriptor.DimletDescriptor(DimletType.DIMLET_SKY,id), modifiers)); } } SkyDescriptor.Builder builder = new SkyDescriptor.Builder(); for (Pair<DimensionDescriptor.DimletDescriptor, List<DimensionDescriptor.DimletDescriptor>> dimletWithModifiers : dimlets) { int id = dimletWithModifiers.getKey().getId(); builder.combine(KnownDimletConfiguration.idToSkyDescriptor.get(id)); } skyDescriptor = builder.build(); } private List<Pair<DimensionDescriptor.DimletDescriptor,List<DimensionDescriptor.DimletDescriptor>>> extractType(DimletType type, List<Pair<DimensionDescriptor.DimletDescriptor,List<DimensionDescriptor.DimletDescriptor>>> dimlets) { List<Pair<DimensionDescriptor.DimletDescriptor,List<DimensionDescriptor.DimletDescriptor>>> result = new ArrayList<Pair<DimensionDescriptor.DimletDescriptor, List<DimensionDescriptor.DimletDescriptor>>>(); for (Pair<DimensionDescriptor.DimletDescriptor, List<DimensionDescriptor.DimletDescriptor>> dimlet : dimlets) { if (dimlet.getLeft().getType() == type) { result.add(dimlet); } } return result; } private void calculateTerrainType(List<Pair<DimensionDescriptor.DimletDescriptor,List<DimensionDescriptor.DimletDescriptor>>> dimlets, Random random) { dimlets = extractType(DimletType.DIMLET_TERRAIN, dimlets); List<DimensionDescriptor.DimletDescriptor> modifiers; terrainType = TerrainType.TERRAIN_VOID; if (dimlets.isEmpty()) { // Pick a random terrain type with a seed that is generated from all the // dimlets so we always get the same random value for these dimlets. terrainType = TerrainType.values()[random.nextInt(TerrainType.values().length)]; modifiers = Collections.emptyList(); } else { int index = random.nextInt(dimlets.size()); terrainType = KnownDimletConfiguration.idToTerrainType.get(dimlets.get(index).getLeft().getId()); modifiers = dimlets.get(index).getRight(); } List<Block> blocks = new ArrayList<Block>(); List<Block> fluids = new ArrayList<Block>(); getMaterialAndFluidModifiers(modifiers, blocks, fluids); if (!blocks.isEmpty()) { baseBlockForTerrain = blocks.get(random.nextInt(blocks.size())); if (baseBlockForTerrain == null) { baseBlockForTerrain = Blocks.stone; // This is the default in case None was specified. } } else { // Nothing was specified. With a relatively big chance we use stone. But there is also a chance that the material will be something else. if (random.nextFloat() < 0.6f) { baseBlockForTerrain = Blocks.stone; } else { baseBlockForTerrain = KnownDimletConfiguration.getRandomMaterialBlock(random); } } if (!fluids.isEmpty()) { fluidForTerrain = fluids.get(random.nextInt(fluids.size())); if (fluidForTerrain == null) { fluidForTerrain = Blocks.water; // This is the default. } } else { if (random.nextFloat() < 0.6f) { fluidForTerrain = Blocks.water; } else { fluidForTerrain = KnownDimletConfiguration.getRandomFluidBlock(random); } } } private void getMaterialAndFluidModifiers(List<DimensionDescriptor.DimletDescriptor> modifiers, List<Block> blocks, List<Block> fluids) { if (modifiers != null) { for (DimensionDescriptor.DimletDescriptor modifier : modifiers) { if (modifier.getType() == DimletType.DIMLET_MATERIAL) { Block block = KnownDimletConfiguration.idToBlock.get(modifier.getId()); blocks.add(block); } else if (modifier.getType() == DimletType.DIMLET_LIQUID) { Block fluid = KnownDimletConfiguration.idToFluid.get(modifier.getId()); fluids.add(fluid); } } } } private void calculateFeatureType(List<Pair<DimensionDescriptor.DimletDescriptor,List<DimensionDescriptor.DimletDescriptor>>> dimlets, Random random) { dimlets = extractType(DimletType.DIMLET_FEATURE, dimlets); if (dimlets.isEmpty()) { for (Map.Entry<Integer, FeatureType> entry : KnownDimletConfiguration.idToFeatureType.entrySet()) { // @Todo make this chance configurable? if (random.nextFloat() < .4f) { featureTypes.add(entry.getValue()); List<DimensionDescriptor.DimletDescriptor> modifiers = Collections.emptyList(); // @todo randomize those? dimlets.add(Pair.of(new DimensionDescriptor.DimletDescriptor(DimletType.DIMLET_FEATURE, entry.getKey()), modifiers)); } } } Map<FeatureType,List<DimensionDescriptor.DimletDescriptor>> modifiersForFeature = new HashMap<FeatureType, List<DimensionDescriptor.DimletDescriptor>>(); for (Pair<DimensionDescriptor.DimletDescriptor, List<DimensionDescriptor.DimletDescriptor>> dimlet : dimlets) { FeatureType featureType = KnownDimletConfiguration.idToFeatureType.get(dimlet.getLeft().getId()); featureTypes.add(featureType); modifiersForFeature.put(featureType, dimlet.getRight()); } if (featureTypes.contains(FeatureType.FEATURE_LAKES)) { List<Block> blocks = new ArrayList<Block>(); List<Block> fluids = new ArrayList<Block>(); getMaterialAndFluidModifiers(modifiersForFeature.get(FeatureType.FEATURE_LAKES), blocks, fluids); // If no fluids are specified we will usually have default fluid generation (water+lava). Otherwise some random selection. if (fluids.isEmpty()) { while (random.nextFloat() < 0.2f) { fluids.add(KnownDimletConfiguration.getRandomFluidBlock(random)); } } else if (fluids.size() == 1 && fluids.get(0) == null) { fluids.clear(); } fluidsForLakes = fluids.toArray(new Block[fluids.size()]); } else { fluidsForLakes = new Block[0]; } if (featureTypes.contains(FeatureType.FEATURE_OREGEN)) { List<Block> blocks = new ArrayList<Block>(); List<Block> fluids = new ArrayList<Block>(); getMaterialAndFluidModifiers(modifiersForFeature.get(FeatureType.FEATURE_OREGEN), blocks, fluids); // If no blocks for oregen are specified we have a small chance that some extra oregen is generated anyway. if (blocks.isEmpty()) { while (random.nextFloat() < 0.2f) { blocks.add(KnownDimletConfiguration.getRandomMaterialBlock(random)); } } else if (blocks.size() == 1 && blocks.get(0) == null) { blocks.clear(); } extraOregen = blocks.toArray(new Block[blocks.size()]); } else { extraOregen = new Block[0]; } if (featureTypes.contains(FeatureType.FEATURE_TENDRILS) || featureTypes.contains(FeatureType.FEATURE_SPHERES)) { List<Block> blocks = new ArrayList<Block>(); List<Block> fluids = new ArrayList<Block>(); getMaterialAndFluidModifiers(modifiersForFeature.get(FeatureType.FEATURE_TENDRILS), blocks, fluids); if (!blocks.isEmpty()) { baseFeatureBlock = blocks.get(random.nextInt(blocks.size())); if (baseFeatureBlock == null) { baseFeatureBlock = Blocks.stone; // This is the default in case None was specified. } } else { // Nothing was specified. With a relatively big chance we use stone. But there is also a chance that the material will be something else. if (random.nextFloat() < 0.6f) { baseFeatureBlock = Blocks.stone; } else { baseFeatureBlock = KnownDimletConfiguration.getRandomMaterialBlock(random); } } } else { baseFeatureBlock = Blocks.stone; } } private void calculateStructureType(List<Pair<DimensionDescriptor.DimletDescriptor,List<DimensionDescriptor.DimletDescriptor>>> dimlets, Random random) { dimlets = extractType(DimletType.DIMLET_STRUCTURE, dimlets); if (dimlets.isEmpty()) { for (StructureType type : StructureType.values()) { // @Todo make this chance configurable? if (random.nextFloat() < .2f) { structureTypes.add(type); } } } else { for (Pair<DimensionDescriptor.DimletDescriptor, List<DimensionDescriptor.DimletDescriptor>> dimletWithModifier : dimlets) { structureTypes.add(KnownDimletConfiguration.idToStructureType.get(dimletWithModifier.getLeft().getId())); } } } private void calculateBiomes(List<Pair<DimensionDescriptor.DimletDescriptor,List<DimensionDescriptor.DimletDescriptor>>> dimlets, Random random) { dimlets = extractType(DimletType.DIMLET_BIOME, dimlets); // @@@ TODO: distinguish between random overworld biome, random nether biome, random biome and specific biomes for (Pair<DimensionDescriptor.DimletDescriptor, List<DimensionDescriptor.DimletDescriptor>> dimletWithModifiers : dimlets) { int id = dimletWithModifiers.getKey().getId(); biomes.add(KnownDimletConfiguration.idToBiome.get(id)); } } public DimensionDescriptor getDescriptor() { return descriptor; } public String getName() { return name; } public TerrainType getTerrainType() { return terrainType; } public boolean hasFeatureType(FeatureType type) { return featureTypes.contains(type); } public Set<FeatureType> getFeatureTypes() { return featureTypes; } public boolean hasStructureType(StructureType type) { return structureTypes.contains(type); } public Set<StructureType> getStructureTypes() { return structureTypes; } public List<BiomeGenBase> getBiomes() { return biomes; } public String getDigitString() { return digitString; } public Block getBaseBlockForTerrain() { return baseBlockForTerrain; } public Block getBaseFeatureBlock() { return baseFeatureBlock; } public Block[] getExtraOregen() { return extraOregen; } public Block getFluidForTerrain() { return fluidForTerrain; } public Block[] getFluidsForLakes() { return fluidsForLakes; } public SkyDescriptor getSkyDescriptor() { return skyDescriptor; } }
package com.netflix.priam.defaultimpl; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Properties; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.services.ec2.AmazonEC2; import com.amazonaws.services.ec2.AmazonEC2Client; import com.amazonaws.services.ec2.model.AvailabilityZone; import com.amazonaws.services.ec2.model.DescribeAvailabilityZonesRequest; import com.amazonaws.services.ec2.model.DescribeAvailabilityZonesResult; import com.amazonaws.services.ec2.model.DescribeInstancesRequest; import com.amazonaws.services.ec2.model.DescribeInstancesResult; import com.amazonaws.services.ec2.model.Instance; import com.amazonaws.services.ec2.model.Reservation; import com.amazonaws.services.simpledb.AmazonSimpleDBClient; import com.amazonaws.services.simpledb.model.Attribute; import com.amazonaws.services.simpledb.model.Item; import com.amazonaws.services.simpledb.model.SelectRequest; import com.amazonaws.services.simpledb.model.SelectResult; import com.google.inject.Inject; import com.google.inject.Singleton; import com.google.common.collect.Lists; import com.netflix.priam.IConfiguration; import com.netflix.priam.ICredential; import com.netflix.priam.utils.SystemUtils; @Singleton public class PriamConfiguration implements IConfiguration { private static final String PRIAM_PRE = "priam"; private static final String CONFIG_CASS_HOME_DIR = PRIAM_PRE + ".cass.home"; private static final String CONFIG_CASS_START_SCRIPT = PRIAM_PRE + ".cass.startscript"; private static final String CONFIG_CASS_STOP_SCRIPT = PRIAM_PRE + ".cass.stopscript"; private static final String CONFIG_CLUSTER_NAME = PRIAM_PRE + ".clustername"; private static final String CONFIG_SEED_PROVIDER_NAME = PRIAM_PRE + ".seed.provider"; private static final String CONFIG_LOAD_LOCAL_PROPERTIES = PRIAM_PRE + ".localbootstrap.enable"; private static final String CONFIG_MAX_HEAP_SIZE = PRIAM_PRE + ".heap.size."; private static final String CONFIG_DATA_LOCATION = PRIAM_PRE + ".data.location"; private static final String CONFIG_MR_ENABLE = PRIAM_PRE + ".multiregion.enable"; private static final String CONFIG_CL_LOCATION = PRIAM_PRE + ".commitlog.location"; private static final String CONFIG_JMX_LISTERN_PORT_NAME = PRIAM_PRE + ".jmx.port"; private static final String CONFIG_AVAILABILITY_ZONES = PRIAM_PRE + ".zones.available"; private static final String CONFIG_SAVE_CACHE_LOCATION = PRIAM_PRE + ".cache.location"; private static final String CONFIG_NEW_MAX_HEAP_SIZE = PRIAM_PRE + ".heap.newgen.size."; private static final String CONFIG_DIRECT_MAX_HEAP_SIZE = PRIAM_PRE + ".direct.memory.size."; private static final String CONFIG_THRIFT_LISTERN_PORT_NAME = PRIAM_PRE + ".thrift.port"; private static final String CONFIG_STORAGE_LISTERN_PORT_NAME = PRIAM_PRE + ".storage.port"; private static final String CONFIG_CL_BK_LOCATION = PRIAM_PRE + ".backup.commitlog.location"; private static final String CONFIG_THROTTLE_UPLOAD_PER_SECOND = PRIAM_PRE + ".upload.throttle"; private static final String CONFIG_IN_MEMORY_COMPACTION_LIMIT = PRIAM_PRE + ".memory.compaction.limit"; private static final String CONFIG_COMPACTION_THROUHPUT = PRIAM_PRE + ".compaction.throughput"; private static final String CONFIG_MAX_HINT_WINDOW_IN_MS = PRIAM_PRE + ".hint.window"; private static final String CONFIG_HINT_DELAY = PRIAM_PRE + ".hint.delay"; private static final String CONFIG_BOOTCLUSTER_NAME = PRIAM_PRE + ".bootcluster"; private static final String CONFIG_ENDPOINT_SNITCH = PRIAM_PRE + ".endpoint_snitch"; // Backup and Restore private static final String CONFIG_BACKUP_THREADS = PRIAM_PRE + ".backup.threads"; private static final String CONFIG_RESTORE_PREFIX = PRIAM_PRE + ".restore.prefix"; private static final String CONFIG_INCR_BK_ENABLE = PRIAM_PRE + ".backup.incremental.enable"; private static final String CONFIG_CL_BK_ENABLE = PRIAM_PRE + ".backup.commitlog.enable"; private static final String CONFIG_AUTO_RESTORE_SNAPSHOTNAME = PRIAM_PRE + ".restore.snapshot"; private static final String CONFIG_BUCKET_NAME = PRIAM_PRE + ".s3.bucket"; private static final String CONFIG_BACKUP_HOUR = PRIAM_PRE + ".backup.hour"; private static final String CONFIG_S3_BASE_DIR = PRIAM_PRE + ".s3.base_dir"; private static final String CONFIG_RESTORE_THREADS = PRIAM_PRE + ".restore.threads"; private static final String CONFIG_RESTORE_CLOSEST_TOKEN = PRIAM_PRE + ".restore.closesttoken"; private static final String CONFIG_RESTORE_KEYSPACES = PRIAM_PRE + ".restore.keyspaces"; private static final String CONFIG_BACKUP_CHUNK_SIZE = PRIAM_PRE + ".backup.chunksizemb"; private static final String CONFIG_BACKUP_RETENTION = PRIAM_PRE + ".backup.retention"; private static final String CONFIG_BACKUP_RACS = PRIAM_PRE + ".backup.racs"; // Amazon specific private static final String CONFIG_ASG_NAME = PRIAM_PRE + ".az.asgname"; private static final String CONFIG_REGION_NAME = PRIAM_PRE + ".az.region"; private final String RAC = SystemUtils.getDataFromUrl("http://169.254.169.254/latest/meta-data/placement/availability-zone"); private final String PUBLIC_HOSTNAME = SystemUtils.getDataFromUrl("http://169.254.169.254/latest/meta-data/public-hostname"); private final String PUBLIC_IP = SystemUtils.getDataFromUrl("http://169.254.169.254/latest/meta-data/public-ipv4"); private final String INSTANCE_ID = SystemUtils.getDataFromUrl("http://169.254.169.254/latest/meta-data/instance-id"); private final String INSTANCE_TYPE = SystemUtils.getDataFromUrl("http://169.254.169.254/latest/meta-data/instance-type"); private static String ASG_NAME = System.getenv("ASG_NAME"); private static String REGION = System.getenv("EC2_REGION"); // Defaults private final String DEFAULT_CLUSTER_NAME = "cass_cluster"; private final String DEFAULT_DATA_LOCATION = "/var/lib/cassandra/data"; private final String DEFAULT_COMMIT_LOG_LOCATION = "/var/lib/cassandra/commitlog"; private final String DEFAULT_CACHE_LOCATION = "/var/lib/cassandra/saved_caches"; private final String DEFULT_ENDPOINT_SNITCH = "org.apache.cassandra.locator.Ec2Snitch"; private final String DEFAULT_SEED_PROVIDER = "com.netflix.priam.cassandra.NFSeedProvider"; // rpm based. Can be modified for tar based. private final String DEFAULT_CASS_HOME_DIR = "/etc/cassandra"; private final String DEFAULT_CASS_START_SCRIPT = "/etc/init.d/cassandra start"; private final String DEFAULT_CASS_STOP_SCRIPT = "/etc/init.d/cassandra stop"; private final String DEFAULT_BACKUP_LOCATION = "backup"; private final String DEFAULT_BUCKET_NAME = "cassandra-archive"; private String DEFAULT_AVAILABILITY_ZONES = ""; private final String DEFAULT_MAX_DIRECT_MEM = "50G"; private final String DEFAULT_MAX_HEAP = "8G"; private final String DEFAULT_MAX_NEWGEN_HEAP = "2G"; private final int DEFAULT_JMX_PORT = 7199; private final int DEFAULT_THRIFT_PORT = 9160; private final int DEFAULT_STORAGE_PORT = 7000; private final int DEFAULT_BACKUP_HOUR = 12; private final int DEFAULT_BACKUP_THREADS = 2; private final int DEFAULT_RESTORE_THREADS = 8; private final int DEFAULT_BACKUP_CHUNK_SIZE = 10; private final int DEFAULT_BACKUP_RETENTION = 0; private PriamProperties config; private static final Logger logger = LoggerFactory.getLogger(PriamConfiguration.class); private static class Attributes { public final static String APP_ID = "appId"; // ASG public final static String PROPERTY = "property"; public final static String PROPERTY_VALUE = "value"; public final static String REGION = "region"; } private static final String DOMAIN = "PriamProperties"; private static String ALL_QUERY = "select * from " + DOMAIN + " where " + Attributes.APP_ID + "='%s'"; private final ICredential provider; @Inject public PriamConfiguration(ICredential provider) { this.provider = provider; } @Override public void intialize() { setupEnvVars(); setDefaultRACList(REGION); populateProps(); SystemUtils.createDirs(getBackupCommitLogLocation()); SystemUtils.createDirs(getCommitLogLocation()); SystemUtils.createDirs(getCacheLocation()); SystemUtils.createDirs(getDataFileLocation()); } private void setupEnvVars() { // Search in java opt properties REGION = StringUtils.isBlank(REGION) ? System.getProperty("EC2_REGION") : REGION; // Infer from zone if (StringUtils.isBlank(REGION)) REGION = RAC.substring(0, RAC.length() - 1); ASG_NAME = StringUtils.isBlank(ASG_NAME) ? System.getProperty("ASG_NAME") : ASG_NAME; if (StringUtils.isBlank(ASG_NAME)) ASG_NAME = populateASGName(REGION, INSTANCE_ID); logger.info(String.format("REGION set to %s, ASG Name set to %s", REGION, ASG_NAME)); } /** * Query amazon to get ASG name. Currently not available as part of instance * info api. */ private String populateASGName(String region, String instanceId) { AmazonEC2 client = new AmazonEC2Client(new BasicAWSCredentials(provider.getAccessKeyId(), provider.getSecretAccessKey())); client.setEndpoint("ec2." + region + ".amazonaws.com"); DescribeInstancesRequest desc = new DescribeInstancesRequest().withInstanceIds(instanceId); DescribeInstancesResult res = client.describeInstances(desc); for (Reservation resr : res.getReservations()) { for (Instance ins : resr.getInstances()) { for (com.amazonaws.services.ec2.model.Tag tag : ins.getTags()) { if (tag.getKey().equals("aws:autoscaling:groupName")) return tag.getValue(); } } } return null; } /** * Get the fist 3 available zones in the region */ public void setDefaultRACList(String region){ AmazonEC2 client = new AmazonEC2Client(new BasicAWSCredentials(provider.getAccessKeyId(), provider.getSecretAccessKey())); client.setEndpoint("ec2." + region + ".amazonaws.com"); DescribeAvailabilityZonesResult res = client.describeAvailabilityZones(); List<String> zone = Lists.newArrayList(); for(AvailabilityZone reg : res.getAvailabilityZones()){ if( reg.getState().equals("available") ) zone.add(reg.getZoneName()); if( zone.size() == 3) break; } DEFAULT_AVAILABILITY_ZONES = StringUtils.join(zone, ","); } private void populateProps() { // End point is us-east-1 AmazonSimpleDBClient simpleDBClient = new AmazonSimpleDBClient(new BasicAWSCredentials(provider.getAccessKeyId(), provider.getSecretAccessKey())); config = new PriamProperties(); config.put(CONFIG_ASG_NAME, ASG_NAME); config.put(CONFIG_REGION_NAME, REGION); String nextToken = null; String appid = ASG_NAME.lastIndexOf('-') > 0 ? ASG_NAME.substring(0, ASG_NAME.lastIndexOf('-')): ASG_NAME; do { SelectRequest request = new SelectRequest(String.format(ALL_QUERY, appid)); request.setNextToken(nextToken); SelectResult result = simpleDBClient.select(request); nextToken = result.getNextToken(); Iterator<Item> itemiter = result.getItems().iterator(); while (itemiter.hasNext()) addProperty(itemiter.next()); } while (nextToken != null); } private void addProperty(Item item) { Iterator<Attribute> attrs = item.getAttributes().iterator(); String prop = ""; String value = ""; String dc = ""; while (attrs.hasNext()) { Attribute att = attrs.next(); if (att.getName().equals(Attributes.PROPERTY)) prop = att.getValue(); else if (att.getName().equals(Attributes.PROPERTY_VALUE)) value = att.getValue(); else if (att.getName().equals(Attributes.REGION)) dc = att.getValue(); } // Ignore, if not this region if (StringUtils.isNotBlank(dc) && !dc.equals(REGION)) return; // Override only if region is specified if (config.contains(prop) && StringUtils.isBlank(dc)) return; config.put(prop, value); } @Override public String getCassStartupScript() { return config.getProperty(CONFIG_CASS_START_SCRIPT, DEFAULT_CASS_START_SCRIPT); } @Override public String getCassStopScript() { return config.getProperty(CONFIG_CASS_STOP_SCRIPT, DEFAULT_CASS_STOP_SCRIPT); } @Override public String getCassHome() { return config.getProperty(CONFIG_CASS_HOME_DIR, DEFAULT_CASS_HOME_DIR); } @Override public String getBackupLocation() { return config.getProperty(CONFIG_S3_BASE_DIR, DEFAULT_BACKUP_LOCATION); } @Override public String getBackupPrefix() { return config.getProperty(CONFIG_BUCKET_NAME, DEFAULT_BUCKET_NAME); } @Override public int getBackupRetentionDays() { return config.getInteger(CONFIG_BACKUP_RETENTION, DEFAULT_BACKUP_RETENTION); } @Override public List<String> getBackupRacs() { return config.getList(CONFIG_BACKUP_RACS); } @Override public String getRestorePrefix() { return config.getProperty(CONFIG_RESTORE_PREFIX); } @Override public List<String> getRestoreKeySpaces() { return config.getList(CONFIG_RESTORE_KEYSPACES); } @Override public String getDataFileLocation() { return config.getProperty(CONFIG_DATA_LOCATION, DEFAULT_DATA_LOCATION); } @Override public String getCacheLocation() { return config.getProperty(CONFIG_SAVE_CACHE_LOCATION, DEFAULT_CACHE_LOCATION); } @Override public String getCommitLogLocation() { return config.getProperty(CONFIG_CL_LOCATION, DEFAULT_COMMIT_LOG_LOCATION); } @Override public String getBackupCommitLogLocation() { return config.getProperty(CONFIG_CL_BK_LOCATION, ""); } @Override public long getBackupChunkSize() { long size = config.getLong(CONFIG_BACKUP_CHUNK_SIZE, DEFAULT_BACKUP_CHUNK_SIZE); return size*1024*1024L; } @Override public boolean isCommitLogBackup() { return config.getBoolean(CONFIG_CL_BK_ENABLE, false); } @Override public int getJmxPort() { return config.getInteger(CONFIG_JMX_LISTERN_PORT_NAME, DEFAULT_JMX_PORT); } @Override public int getThriftPort() { return config.getInteger(CONFIG_THRIFT_LISTERN_PORT_NAME, DEFAULT_THRIFT_PORT); } @Override public int getStoragePort() { return config.getInteger(CONFIG_STORAGE_LISTERN_PORT_NAME, DEFAULT_STORAGE_PORT); } @Override public String getSnitch() { return config.getProperty(CONFIG_ENDPOINT_SNITCH, DEFULT_ENDPOINT_SNITCH); } @Override public String getAppName() { return config.getProperty(CONFIG_CLUSTER_NAME, DEFAULT_CLUSTER_NAME); } @Override public String getRac() { return RAC; } @Override public List<String> getRacs() { return config.getList(CONFIG_AVAILABILITY_ZONES, DEFAULT_AVAILABILITY_ZONES); } @Override public String getHostname() { return PUBLIC_HOSTNAME; } @Override public String getInstanceName() { return INSTANCE_ID; } @Override public String getHeapSize() { return config.getProperty(CONFIG_MAX_HEAP_SIZE + INSTANCE_TYPE, DEFAULT_MAX_HEAP); } @Override public String getHeapNewSize() { return config.getProperty(CONFIG_NEW_MAX_HEAP_SIZE + INSTANCE_TYPE, DEFAULT_MAX_NEWGEN_HEAP); } @Override public String getMaxDirectMemory() { return config.getProperty(CONFIG_DIRECT_MAX_HEAP_SIZE + INSTANCE_TYPE, DEFAULT_MAX_DIRECT_MEM); } @Override public int getBackupHour() { return config.getInteger(CONFIG_BACKUP_HOUR, DEFAULT_BACKUP_HOUR); } @Override public String getRestoreSnapshot() { return config.getProperty(CONFIG_AUTO_RESTORE_SNAPSHOTNAME, ""); } @Override public String getDC() { return config.getProperty(CONFIG_REGION_NAME, ""); } @Override public void setDC(String region) { config.setProperty(CONFIG_REGION_NAME, region); } @Override public boolean isMultiDC() { return config.getBoolean(CONFIG_MR_ENABLE, false); } @Override public int getMaxBackupUploadThreads() { return config.getInteger(CONFIG_BACKUP_THREADS, DEFAULT_BACKUP_THREADS); } @Override public int getMaxBackupDownloadThreads() { return config.getInteger(CONFIG_RESTORE_THREADS, DEFAULT_RESTORE_THREADS); } @Override public boolean isRestoreClosestToken() { return config.getBoolean(CONFIG_RESTORE_CLOSEST_TOKEN, false); } @Override public String getASGName() { return config.getProperty(CONFIG_ASG_NAME, ""); } @Override public boolean isIncrBackup() { return config.getBoolean(CONFIG_INCR_BK_ENABLE, true); } @Override public String getHostIP() { return PUBLIC_IP; } @Override public int getUploadThrottle() { return config.getInteger(CONFIG_THROTTLE_UPLOAD_PER_SECOND, Integer.MAX_VALUE); } @Override public boolean isLocalBootstrapEnabled() { return config.getBoolean(CONFIG_LOAD_LOCAL_PROPERTIES, false); } @Override public int getInMemoryCompactionLimit() { return config.getInteger(CONFIG_IN_MEMORY_COMPACTION_LIMIT, 128); } @Override public int getCompactionThroughput() { return config.getInteger(CONFIG_COMPACTION_THROUHPUT, 8); } @Override public int getMaxHintWindowInMS() { return config.getInteger(CONFIG_MAX_HINT_WINDOW_IN_MS, 8); } @Override public int getHintHandoffDelay() { return config.getInteger(CONFIG_HINT_DELAY, 1); } @Override public String getBootClusterName() { return config.getProperty(CONFIG_BOOTCLUSTER_NAME, ""); } @Override public String getSeedProviderName() { return config.getProperty(CONFIG_SEED_PROVIDER_NAME, DEFAULT_SEED_PROVIDER); } private class PriamProperties extends Properties { private static final long serialVersionUID = 1L; public int getInteger(String prop, int defaultValue) { return getProperty(prop) == null ? defaultValue : Integer.parseInt(getProperty(prop)); } public long getLong(String prop, long defaultValue) { return getProperty(prop) == null ? defaultValue : Long.parseLong(getProperty(prop)); } public boolean getBoolean(String prop, boolean defaultValue) { return getProperty(prop) == null ? defaultValue : Boolean.parseBoolean(getProperty(prop)); } public List<String> getList(String prop) { if (getProperty(prop) == null) return Lists.newArrayList(); return Arrays.asList(getProperty(prop).split(",")); } public List<String> getList(String prop, String defaultValue) { if (getProperty(prop) == null) return Lists.newArrayList(defaultValue.split(",")); return getList(prop); } } }
package com.nirmata.workflow.details; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.nirmata.workflow.WorkflowManager; import com.nirmata.workflow.details.internalmodels.RunnableTask; import com.nirmata.workflow.executor.TaskExecution; import com.nirmata.workflow.executor.TaskExecutionStatus; import com.nirmata.workflow.models.TaskExecutionResult; import com.nirmata.workflow.executor.TaskExecutor; import com.nirmata.workflow.models.ExecutableTask; import com.nirmata.workflow.models.RunId; import com.nirmata.workflow.models.Task; import com.nirmata.workflow.models.TaskId; import com.nirmata.workflow.queue.QueueConsumer; import com.nirmata.workflow.queue.QueueFactory; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.utils.CloseableUtils; import org.apache.curator.utils.EnsurePath; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.time.LocalDateTime; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; import java.util.stream.IntStream; public class WorkflowManagerImpl implements WorkflowManager { private final Logger log = LoggerFactory.getLogger(getClass()); private final CuratorFramework curator; private final String instanceName; private final List<QueueConsumer> consumers; private final SchedulerSelector schedulerSelector; private final EnsurePath ensureRunPath; private final EnsurePath ensureCompletedTaskPath; private final AtomicReference<State> state = new AtomicReference<>(State.LATENT); private enum State { LATENT, STARTED, CLOSED } public WorkflowManagerImpl(CuratorFramework curator, QueueFactory queueFactory, String instanceName, List<TaskExecutorSpec> specs) { this.curator = Preconditions.checkNotNull(curator, "curator cannot be null"); queueFactory = Preconditions.checkNotNull(queueFactory, "queueFactory cannot be null"); this.instanceName = Preconditions.checkNotNull(instanceName, "instanceName cannot be null"); specs = Preconditions.checkNotNull(specs, "specs cannot be null"); ensureRunPath = curator.newNamespaceAwareEnsurePath(ZooKeeperConstants.getRunParentPath()); ensureCompletedTaskPath = curator.newNamespaceAwareEnsurePath(ZooKeeperConstants.getCompletedTaskParentPath()); consumers = makeTaskConsumers(queueFactory, specs); schedulerSelector = new SchedulerSelector(this, queueFactory, specs); } public CuratorFramework getCurator() { return curator; } @Override public void start() { Preconditions.checkState(state.compareAndSet(State.LATENT, State.STARTED), "Already started"); consumers.forEach(QueueConsumer::start); schedulerSelector.start(); } @Override public RunId submitTask(Task task) { Preconditions.checkState(state.get() == State.STARTED, "Not started"); return submitSubTask(task, null, null); } @Override public RunId submitSubTask(Task task, RunId mainRunId, TaskId mainTaskId) { // TODO handle mainRunId and mainTaskId try { ensureRunPath.ensure(curator.getZookeeperClient()); ensureCompletedTaskPath.ensure(curator.getZookeeperClient()); } catch ( Exception e ) { throw new RuntimeException(e); } Preconditions.checkState(state.get() == State.STARTED, "Not started"); RunId runId = new RunId(); RunnableTaskDagBuilder builder = new RunnableTaskDagBuilder(runId, task); RunnableTask runnableTask = new RunnableTask(builder.getExecutableTasks(), builder.getEntries(), LocalDateTime.now(), null); TaskExecutionResult taskExecutionResult = new TaskExecutionResult(TaskExecutionStatus.SUCCESS, ""); byte[] runnableTaskJson = JsonSerializer.toBytes(JsonSerializer.newRunnableTask(runnableTask)); byte[] taskExecutionResultJson = JsonSerializer.toBytes(JsonSerializer.newTaskExecutionResult(taskExecutionResult)); String runPath = ZooKeeperConstants.getRunPath(runId); String completedTaskPath = ZooKeeperConstants.getCompletedTaskPath(runId, new TaskId("")); try { curator.inTransaction() .create().forPath(runPath, runnableTaskJson) .and() .create().forPath(completedTaskPath, taskExecutionResultJson) // a fake completed task to kick-off task creation .and() .commit(); } catch ( Exception e ) { throw new RuntimeException(e); } return runId; } @Override public void cancelRun(RunId runId, String message) { // TODO } @Override public Map<String, String> getTaskData(RunId runId, TaskId taskId) { return null; } public String getInstanceName() { return instanceName; } @Override public void close() throws IOException { if ( state.compareAndSet(State.STARTED, State.CLOSED) ) { consumers.forEach(CloseableUtils::closeQuietly); CloseableUtils.closeQuietly(schedulerSelector); } } private void excecuteTask(TaskExecutor taskExecutor, ExecutableTask executableTask) { log.info("Executing task: " + executableTask); TaskExecution taskExecution = null;//taskExecutor.newTaskExecution() TaskExecutionResult result = taskExecution.execute(); String json = "";// TODO nodeToString(newTaskExecutionResult(result)); try { String path = "";// TODO ZooKeeperConstants.getCompletedTaskPath(executableTask.getRunId(), executableTask.getTask().getTaskId()); curator.create().creatingParentsIfNeeded().forPath(path, json.getBytes()); } catch ( Exception e ) { log.error("Could not set completed data for executable task: " + executableTask, e); throw new RuntimeException(e); } } private List<QueueConsumer> makeTaskConsumers(QueueFactory queueFactory, List<TaskExecutorSpec> specs) { ImmutableList.Builder<QueueConsumer> builder = ImmutableList.builder(); specs.forEach(spec -> { IntStream.range(0, spec.getQty()).forEach(i -> { QueueConsumer consumer = queueFactory.createQueueConsumer(this, t -> excecuteTask(spec.getTaskExecutor(), t), spec.getTaskType()); builder.add(consumer); }); }); return builder.build(); } }
package com.ociweb.gl.impl.http.server; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ociweb.gl.api.FailablePayloadReading; import com.ociweb.gl.api.HeaderReader; import com.ociweb.gl.api.Payloadable; import com.ociweb.gl.impl.PayloadReader; import com.ociweb.pronghorn.network.config.HTTPContentType; import com.ociweb.pronghorn.network.config.HTTPHeader; import com.ociweb.pronghorn.network.config.HTTPRevision; import com.ociweb.pronghorn.network.config.HTTPSpecification; import com.ociweb.pronghorn.network.config.HTTPVerb; import com.ociweb.pronghorn.pipe.MessageSchema; import com.ociweb.pronghorn.pipe.Pipe; import com.ociweb.pronghorn.pipe.StructuredReader; import com.ociweb.pronghorn.util.TrieParser; public class HTTPPayloadReader<S extends MessageSchema<S>> extends PayloadReader<S> implements HeaderReader { protected HTTPSpecification< ? extends Enum<? extends HTTPContentType>, ? extends Enum<? extends HTTPRevision>, ? extends Enum<? extends HTTPVerb>, ? extends Enum<? extends HTTPHeader>> httpSpec; private static final Logger logger = LoggerFactory.getLogger(HTTPPayloadReader.class); public HTTPPayloadReader(Pipe<S> pipe) { super(pipe); } public HTTPSpecification< ? extends Enum<? extends HTTPContentType>, ? extends Enum<? extends HTTPRevision>, ? extends Enum<? extends HTTPVerb>, ? extends Enum<? extends HTTPHeader>> getSpec() { return this.httpSpec; } public boolean openPayloadData(Payloadable reader) { if (hasRemainingBytes()) { position(this, readFromEndLastInt(StructuredReader.PAYLOAD_INDEX_LOCATION)); reader.read(this);//even when we have zero length... return true; } else { return false; } } public boolean openPayloadDataFailable(FailablePayloadReading reader) { if (hasRemainingBytes()) { position(this, readFromEndLastInt(StructuredReader.PAYLOAD_INDEX_LOCATION)); return reader.read(this);//even when we have zero length... } else { return false; } } }
package com.primetoxinz.stacksonstacks.logic; import com.primetoxinz.stacksonstacks.SoS; import com.primetoxinz.stacksonstacks.capability.IIngotCount; import com.primetoxinz.stacksonstacks.capability.IngotCapabilities; import com.primetoxinz.stacksonstacks.capability.IngotCountProvider; import com.primetoxinz.stacksonstacks.ingot.DummyStack; import com.primetoxinz.stacksonstacks.ingot.IngotLocation; import com.primetoxinz.stacksonstacks.ingot.IngotType; import com.primetoxinz.stacksonstacks.ingot.PartIngot; import lib.utils.RenderUtils; import mcmultipart.block.TileMultipartContainer; import mcmultipart.multipart.IMultipart; import mcmultipart.multipart.IMultipartContainer; import mcmultipart.multipart.MultipartHelper; import mcmultipart.multipart.MultipartRegistry; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumActionResult; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; import net.minecraft.world.World; import net.minecraftforge.client.event.DrawBlockHighlightEvent; import net.minecraftforge.event.AttachCapabilitiesEvent; import net.minecraftforge.event.entity.player.PlayerInteractEvent; import net.minecraftforge.fml.common.eventhandler.EventPriority; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.UUID; import static mcmultipart.multipart.MultipartHelper.getPartContainer; import static net.minecraft.util.EnumActionResult.FAIL; import static net.minecraft.util.EnumActionResult.SUCCESS; public class IngotPlacer { public static ArrayList<DummyStack> ingotRegistry = new ArrayList<>(); @SubscribeEvent(priority = EventPriority.LOW) @SideOnly(Side.CLIENT) public final void onDrawBlockHighlight(DrawBlockHighlightEvent event) { EntityPlayer player = event.getPlayer(); if (canBeIngot(player.getHeldItemMainhand()) || canBeIngot(player.getHeldItemOffhand())) { RenderUtils.drawSelectionBox(player, event.getTarget(), 0, event.getPartialTicks()); } } @SubscribeEvent(priority = EventPriority.HIGH) public final void placeIngot(PlayerInteractEvent.RightClickBlock e) { onItemUse(e.getItemStack(), e.getEntityPlayer(), e.getWorld(), e.getPos(), e.getHand(), e.getFace(), e.getHitVec()); } @SubscribeEvent(priority = EventPriority.HIGH) public void attachCapability(AttachCapabilitiesEvent.TileEntity e) { if (e.getTileEntity() instanceof TileMultipartContainer) { TileMultipartContainer container = (TileMultipartContainer) e.getTileEntity(); if (!container.hasCapability(IngotCapabilities.CAPABILITY_INGOT, null)) { e.addCapability(new ResourceLocation(SoS.MODID, "ingot_capability"), new IngotCountProvider()); } } } private static EnumActionResult onItemUse(final ItemStack stack, EntityPlayer player, World world, BlockPos pos, EnumHand hand, EnumFacing side, Vec3d hit) { if (canBeIngot(stack) && player.canPlayerEdit(pos, side, stack)) { place(world, pos, side, hit, stack, player); return SUCCESS; } return FAIL; } public static boolean canBeIngot(ItemStack stack) { if (stack != null) { DummyStack dummy = new DummyStack(stack); if(ingotRegistry.contains(dummy)) { return true; } else { String ingotName = OreDictUtil.getOreDictionaryNameStartingWith(stack, "ingot"); if(ingotName != null) { ingotRegistry.add(dummy); return true; } } } return false; } private static boolean canAddPart(World world, BlockPos pos, PartIngot ingot) { IMultipartContainer container = getPartContainer(world, pos); if (container == null) { List<AxisAlignedBB> list = new ArrayList<AxisAlignedBB>(); for (AxisAlignedBB bb : list) if (!world.checkNoEntityCollision(bb.offset(pos.getX(), pos.getY(), pos.getZ()))) return false; Collection<? extends IMultipart> parts = MultipartRegistry.convert(world, pos, true); if (parts != null && !parts.isEmpty()) { TileMultipartContainer tmp = new TileMultipartContainer(); for (IMultipart p : parts) tmp.getPartContainer().addPart(p, false, false, false, false, UUID.randomUUID()); return tmp.canAddPart(ingot); } return true; } else { return container.canAddPart(ingot); } } private static Vec3d nextHit(Vec3d hit) { double x = hit.xCoord; double y = hit.yCoord; double z = hit.zCoord; if(x>.5f) { z+=.25f; if(z > .75f) { y+=.125f; z=0; } x=0; } else { x+=.5f; } return new Vec3d(x,y,z); } private static void place(World world, BlockPos pos, EnumFacing side, Vec3d hit, ItemStack stack, EntityPlayer player) { IMultipartContainer container = MultipartHelper.getPartContainer(world, pos); BlockPos place = pos; boolean full = isContainerFull((TileMultipartContainer) container); if (container != null) { if(full) { place=pos.up(); IMultipartContainer next = MultipartHelper.getPartContainer(world, place); if(next != null) { place(world,place,side,hit,stack,player); } } } else { if(world.getTileEntity(pos) != null) return; place=pos.offset(side); } if (player.isSneaking()) { placeAll(world, place, stack, player); } else if(!full){ place(world, place, hit, stack, player); } } private static void placeAll(World world, BlockPos pos, ItemStack stack, EntityPlayer player) { new Thread(() -> { long startTime = System.currentTimeMillis(); Vec3d hit = new Vec3d(0, 0, 0); while (stack.stackSize > 0 && (System.currentTimeMillis() - startTime) < 2000) { place(world, pos, hit, stack, player); hit = nextHit(hit); } }).start(); } private static void place(World world, BlockPos pos, Vec3d hit, ItemStack stack, EntityPlayer player) { IngotLocation location = IngotLocation.fromHit(hit, player.getHorizontalFacing().getAxis()); PartIngot part = new PartIngot(location, new IngotType(stack)); if (canAddPart(world, pos, part)) { if (!world.isRemote) { try { MultipartHelper.addPart(world, pos, part); } catch (Throwable e) { } } consumeItem(player, stack); } } public static boolean isContainerFull(TileMultipartContainer container) { if (container != null && container.hasCapability(IngotCapabilities.CAPABILITY_INGOT, null)) { IIngotCount cap = container.getCapability(IngotCapabilities.CAPABILITY_INGOT, null); System.out.println(cap.isFull()); return cap.isFull(); } return false; } private static void consumeItem(EntityPlayer player, ItemStack stack) { if (!player.isCreative()) stack.stackSize if (stack.stackSize <= 0 && player.getActiveHand() != null) { player.setHeldItem(player.getActiveHand(), null); } } }
package com.slyak.spring.jpa; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; import org.springframework.aop.AfterAdvice; import org.springframework.aop.framework.ProxyFactory; import org.springframework.core.annotation.AnnotationUtils; import org.springframework.core.annotation.OrderUtils; import org.springframework.data.jpa.provider.PersistenceProvider; import org.springframework.data.jpa.repository.support.JpaRepositoryFactory; import org.springframework.data.repository.core.RepositoryInformation; import org.springframework.data.repository.core.support.RepositoryProxyPostProcessor; import org.springframework.data.repository.query.EvaluationContextProvider; import org.springframework.data.repository.query.QueryLookupStrategy; import org.springframework.util.CollectionUtils; import javax.persistence.Entity; import javax.persistence.EntityManager; import java.lang.reflect.ParameterizedType; import java.util.*; import java.util.concurrent.ConcurrentHashMap; /** * . * <p/> * * @author <a href="mailto:stormning@163.com">stormning</a> * @version V1.0, 2015/8/9. */ public class GenericJpaRepositoryFactory extends JpaRepositoryFactory { private final EntityManager entityManager; private final PersistenceProvider extractor; private Map<Class<?>, List<EntityAssembler>> assemblers = new ConcurrentHashMap<Class<?>, List<EntityAssembler>>(); /** * Creates a new {@link JpaRepositoryFactory}. * * @param entityManager must not be {@literal null} */ public GenericJpaRepositoryFactory(EntityManager entityManager) { super(entityManager); this.entityManager = entityManager; this.extractor = PersistenceProvider.fromEntityManager(entityManager); final AssmblerInterceptor assmblerInterceptor = new AssmblerInterceptor(); addRepositoryProxyPostProcessor(new RepositoryProxyPostProcessor() { @Override public void postProcess(ProxyFactory factory, RepositoryInformation repositoryInformation) { factory.addAdvice(assmblerInterceptor); } }); } @Override protected QueryLookupStrategy getQueryLookupStrategy(QueryLookupStrategy.Key key, EvaluationContextProvider evaluationContextProvider) { return TemplateQueryLookupStrategy.create(entityManager, key, extractor, evaluationContextProvider); } private List<EntityAssembler> getEntityAssemblers(Class<?> clazz) { if (assemblers.isEmpty()) { Collection<EntityAssembler> abs = ContextHolder.getBeansOfType(EntityAssembler.class); if (abs.isEmpty()) { return Collections.emptyList(); } else { for (EntityAssembler ab : abs) { Class p0 = getGenericParameter0(ab.getClass()); List<EntityAssembler> ass = this.assemblers.get(p0); if (ass == null) { ass = new ArrayList<EntityAssembler>(); assemblers.put(p0, ass); } ass.add(ab); } for (List<EntityAssembler> ess : assemblers.values()) { Collections.sort(ess, new Comparator<EntityAssembler>() { @Override public int compare(EntityAssembler o1, EntityAssembler o2) { return OrderUtils.getOrder(o2.getClass()) - OrderUtils.getOrder(o1.getClass()); } }); } } } return assemblers.get(clazz); } private void massemble(Iterable iterable) { if (!iterable.iterator().hasNext()) { return; } Object object = iterable.iterator().next(); if (isEntityObject(object)) { List<EntityAssembler> entityAssemblers = getEntityAssemblers(object.getClass()); if (!CollectionUtils.isEmpty(entityAssemblers)) { for (EntityAssembler assembler : entityAssemblers) { assembler.massemble(iterable); } } } } private boolean isEntityObject(Object object) { return object != null && AnnotationUtils.findAnnotation(object.getClass(), Entity.class) != null; } private Class getGenericParameter0(Class clzz) { return (Class) ((ParameterizedType) clzz.getGenericSuperclass()).getActualTypeArguments()[0]; } public class AssmblerInterceptor implements MethodInterceptor, AfterAdvice { @Override public Object invoke(MethodInvocation invocation) throws Throwable { Object proceed = invocation.proceed(); if (!"save".equals(invocation.getMethod().getName())) { if (proceed != null) { //EntityAssembler if (proceed instanceof Iterable) { massemble((Iterable) proceed); } else if (proceed instanceof Map) { massemble(((Map) proceed).values()); } else if (isEntityObject(proceed)) { List<EntityAssembler> entityAssemblers = getEntityAssemblers(proceed.getClass()); if (!entityAssemblers.isEmpty()) { for (EntityAssembler assembler : entityAssemblers) { assembler.assemble(proceed); } } } } } return proceed; } } }
package com.sri.ai.grinder.sgdpllt.library.bounds; import static com.sri.ai.expresso.helper.Expressions.apply; import static com.sri.ai.expresso.helper.Expressions.makeSymbol; import static com.sri.ai.expresso.helper.Expressions.parse; import static com.sri.ai.grinder.helper.GrinderUtil.getIndexExpressionsOfFreeVariablesIn; import static com.sri.ai.grinder.sgdpllt.library.FunctorConstants.AND; import static com.sri.ai.grinder.sgdpllt.library.FunctorConstants.EQUAL; import static com.sri.ai.grinder.sgdpllt.library.FunctorConstants.GREATER_THAN_OR_EQUAL_TO; import static com.sri.ai.grinder.sgdpllt.library.FunctorConstants.IF_THEN_ELSE; import static com.sri.ai.grinder.sgdpllt.library.FunctorConstants.IN; import static com.sri.ai.grinder.sgdpllt.library.FunctorConstants.PLUS; import static com.sri.ai.grinder.sgdpllt.library.FunctorConstants.SUM; import static com.sri.ai.grinder.sgdpllt.library.FunctorConstants.TIMES; import static com.sri.ai.grinder.sgdpllt.library.set.extensional.ExtensionalSets.getElements; import static com.sri.ai.grinder.sgdpllt.library.set.extensional.ExtensionalSets.removeNonDestructively; import static com.sri.ai.util.Util.in; import static com.sri.ai.util.Util.mapIntoArrayList; import static com.sri.ai.util.Util.println; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import com.sri.ai.expresso.api.Expression; import com.sri.ai.expresso.api.ExtensionalSet; import com.sri.ai.expresso.api.IndexExpressionsSet; import com.sri.ai.expresso.api.IntensionalSet; import com.sri.ai.expresso.core.DefaultExistentiallyQuantifiedFormula; import com.sri.ai.expresso.core.DefaultExtensionalUniSet; import com.sri.ai.expresso.core.DefaultSymbol; import com.sri.ai.expresso.core.ExtensionalIndexExpressionsSet; //import com.sri.ai.expresso.helper.Expressions; import com.sri.ai.grinder.sgdpllt.anytime.Model; import com.sri.ai.grinder.sgdpllt.api.Context; import com.sri.ai.grinder.sgdpllt.api.Theory; import com.sri.ai.grinder.sgdpllt.core.TrueContext; //import com.sri.ai.grinder.sgdpllt.library.FunctorConstants; import com.sri.ai.grinder.sgdpllt.library.set.extensional.ExtensionalSets; import com.sri.ai.grinder.sgdpllt.theory.compound.CompoundTheory; import com.sri.ai.grinder.sgdpllt.theory.differencearithmetic.DifferenceArithmeticTheory; import com.sri.ai.grinder.sgdpllt.theory.equality.EqualityTheory; import com.sri.ai.grinder.sgdpllt.theory.linearrealarithmetic.LinearRealArithmeticTheory; import com.sri.ai.grinder.sgdpllt.theory.propositional.PropositionalTheory; import com.sri.ai.grinder.sgdpllt.theory.tuple.TupleTheory; import com.sri.ai.util.base.NullaryFunction; import com.sri.ai.util.collect.CartesianProductIterator; public class Bounds { // a bound is a set of expressions representing its extreme points static boolean debug = false; public static Expression simplex(List<Expression> Variables, Model model){ ArrayList<Expression> simplexList = new ArrayList<>(); Expression one = makeSymbol("1"); Expression zero= makeSymbol("0"); for(Expression var : Variables){ Expression values = model.getValues(var); //TODO getValues should return the right //Expression rather than a string to be parsed. //By the way, that expression should represent a UniSet List<Expression> listOfValues = getElements(values); for (Expression value : listOfValues){ simplexList.add(apply(IF_THEN_ELSE, apply(EQUAL, var, value), one, zero)); } //simplexList.add(apply(IF_THEN_ELSE, apply(EQUAL, var, true ), one, zero)); //simplexList.add(apply(IF_THEN_ELSE, apply(EQUAL, var, false), one, zero)); } Expression result = new DefaultExtensionalUniSet(simplexList); return result; } /** * Assumes that each element of the bound is a factor with the same domain * Normalizes each factor of the bound. In latex notation: * {\phi/sum_{var(\phi)}\phi : \phi in bound} * @param bound * @param theory * @param context * @return bound of normalized factors */ public static Expression normalize(Expression bound, Theory theory, Context context){ List<Expression> listOfBound = ExtensionalSets.getElements(bound); if(listOfBound.size() == 0){ return null; } Expression phi = makeSymbol("phi"); Expression phi1 = listOfBound.get(0); IndexExpressionsSet indices = getIndexExpressionsOfFreeVariablesIn(bound, context); println(indices); Expression noCondition = makeSymbol(true); Expression setOfFactorInstantiations = IntensionalSet.makeMultiSet( indices, phi,//head noCondition); Expression sumOnPhi = apply(SUM, setOfFactorInstantiations); Expression f = apply("/", phi, sumOnPhi); Expression result = applyFunctionToBound(f, phi, bound, theory, context); return result; } /** * Computes the product of each term of a list of bounds * @param theory * @param context * @param listOfBounds * @return bound resulting from the product of bounds */ public static Expression boundProduct(Theory theory, Context context, Expression...listOfBounds){ ArrayList<NullaryFunction<Iterator<Expression>>> iteratorForBoundList = mapIntoArrayList(listOfBounds, bound -> () -> getElements(bound).iterator()); Iterator<ArrayList<Expression>> cartesianProduct = new CartesianProductIterator<Expression>(iteratorForBoundList); ArrayList<Expression> resultList = new ArrayList<>(); for (ArrayList<Expression> element : in(cartesianProduct)){ Expression product = apply("*",element); Expression evaluation = theory.evaluate(product,context); resultList.add(evaluation); } Expression result = new DefaultExtensionalUniSet(resultList); // Updating extreme points result = updateExtremes(result, theory, context); return result; } /*public static Expression boundProduct(Theory theory, Context context, Expression...listOfBounds){ if(listOfBounds.length == 0){ return null; } Expression result= boundProduct (0, theory, context, listOfBounds); return result; } private static Expression boundProduct(int i, Theory theory, Context context, Expression...listOfBounds){ if(listOfBounds.length - 1 == i){ return listOfBounds[i]; } Expression productOfOthers = boundProduct(i + 1, theory, context, listOfBounds); Expression b = listOfBounds[i]; List<Expression> listOfb = ExtensionalSet.getElements(b); List<Expression> listOfProductOfOthers = ExtensionalSet.getElements(productOfOthers); ArrayList<Expression> elements = new ArrayList<>(listOfb.size()*listOfProductOfOthers.size()); for (Expression phi1 : listOfb){ for (Expression phi2 : listOfProductOfOthers){ Expression product = apply("*",phi1,phi2); Expression evaluation = theory.evaluate(product,context); elements.add(evaluation); } } DefaultExtensionalUniSet productBound = new DefaultExtensionalUniSet(elements); //Updating extreme points Expression result = updateExtremes(productBound,theory,context); return result; }*/ public static Expression applyFunctionToBound(Expression f, Expression variableName, Expression b, Theory theory, Context context){ ExtensionalSet bAsExtensionalSet = (ExtensionalSet) b; int numberOfExtremes = bAsExtensionalSet.getArguments().size(); ArrayList<Expression> elements = new ArrayList<>(numberOfExtremes); for(Expression phi : ExtensionalSets.getElements(bAsExtensionalSet)){ Expression substitution = f.replaceAllOccurrences(variableName, phi, context); //debuging if (debug) println("evaluating: " + substitution); Expression evaluation = theory.evaluate(substitution, context); // problem in evaluation method... //debuging if (debug) println("result: " + evaluation); elements.add(evaluation); } DefaultExtensionalUniSet fOfb = new DefaultExtensionalUniSet(elements); //Updating extreme points Expression result = updateExtremes(fOfb,theory,context); return result; } /** * Eliminate factors not in Ext(C.Hull(B)) * @param B * @return */ private static Expression updateExtremes(Expression B,Theory theory, Context context){ List<Expression> listOfB = getElements(B); ArrayList<Expression> elements = new ArrayList<>(listOfB.size()); int indexPhi = 0; for(Expression phi : listOfB){ if (isExtremePoint(phi,indexPhi,B,theory,context)){ elements.add(phi); } indexPhi++; } DefaultExtensionalUniSet result = new DefaultExtensionalUniSet(elements); return result; } /** * Checks if \phi is a convex combination of the elements in bound * @param phi * factor * @param bound * @return */ public static boolean isExtremePoint(Expression phi,int indexPhi, Expression bound, Theory theory, Context context){ //TODO Expression boundWithoutPhi = removeNonDestructively(bound, indexPhi);//caro pq recopia a lista toda List<Expression> listOfB = getElements(boundWithoutPhi); int n = listOfB.size(); Expression[] c = new Expression[n]; for(int i = 0;i<n;i++){ c[i] = makeSymbol("c" + i); context = context.extendWithSymbolsAndTypes("c" + i,"Real"); } // 0<=ci<=1 ArrayList<Expression> listOfC = new ArrayList<>(listOfB.size()); for(int i = 0;i<n;i++){ Expression cibetwen0And1 = apply(AND,apply(GREATER_THAN_OR_EQUAL_TO,1,c[i]), apply(GREATER_THAN_OR_EQUAL_TO,c[i],0) ); listOfC.add(cibetwen0And1); } Expression allcibetwen0And1 = apply(AND, listOfC); //sum over ci =1 listOfC = new ArrayList<>(Arrays.asList(c)); Expression sumOverCiEqualsOne = apply(EQUAL,1,apply(PLUS,listOfC)); //sum of ci*phi1 = phi ArrayList<Expression> prodciphii = new ArrayList<>(listOfB.size()); int i = 0; for(Expression phii : listOfB){ prodciphii.add(apply(TIMES,phii,c[i])); i++; } Expression convexSum = apply(EQUAL,phi,apply(PLUS, prodciphii)); ArrayList<Expression> listOfCiInReal = new ArrayList<>(listOfB.size()); for(i = 0; i <n; i++){ listOfCiInReal.add(apply(IN,c[i],"Real")); } IndexExpressionsSet thereExistsCiInReal = new ExtensionalIndexExpressionsSet(listOfCiInReal); Expression body = apply(AND, allcibetwen0And1, sumOverCiEqualsOne, convexSum); Expression isExtreme = new DefaultExistentiallyQuantifiedFormula(thereExistsCiInReal,body); if (debug) println(isExtreme); //Expression result = theory.evaluate(isExtreme, context); return true; } public static void main(String[] args) { Theory theory = new CompoundTheory( new EqualityTheory(false, true), new DifferenceArithmeticTheory(false, false), new LinearRealArithmeticTheory(false, false), new TupleTheory(), new PropositionalTheory()); Context context = new TrueContext(theory); context = context.extendWithSymbolsAndTypes("X","Boolean"); context = context.extendWithSymbolsAndTypes("Y","Boolean"); context = context.extendWithSymbolsAndTypes("A","Boolean"); context = context.extendWithSymbolsAndTypes("B","Boolean"); //Set of numbers Expression one = DefaultSymbol.createSymbol(1); Expression two = DefaultSymbol.createSymbol(2); Expression three = DefaultSymbol.createSymbol(3); Expression setOFNumbers = ExtensionalSets.makeUniSet(one, two, three); //Set of functions Expression phi1 = parse("if X = true then 1 else if Y = true then 2 else 3"); Expression phi2 = parse("if X = true then if Y = true then 4 else 5 else 6"); Expression phi3 = parse("if A = true then 7 else if B = true then 8 else 9"); Expression phi4 = parse("if X = true then 10 else if Y = true then 11 else 12"); Expression setOfFactors = ExtensionalSets.makeUniSet(phi1, phi2, phi3, phi4); Bounds.normalize(setOfFactors, theory, context).toString(); } }
package com.tickets.web.controller; import com.tickets.business.entities.MovieOnShow; import com.tickets.business.services.MovieOnShowService; import com.tickets.web.controller.response.RestResponse; import com.tickets.web.util.DateUtil; import com.tickets.web.util.LogUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.sql.Date; import java.sql.Time; import java.util.*; import com.tickets.web.controller.response.CollectionResponse; import com.tickets.web.controller.response.ErrorResponse; /** * RESTFul API of on-show movie resources. */ @RestController @RequestMapping("/resource/movie_on_show") public class MovieOnShowController { @Autowired private MovieOnShowService movieOnShowService; private static final Logger LOG = LoggerFactory.getLogger(MovieOnShowController.class); @RequestMapping(path = "", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) public RestResponse getMovieOnShowByDetails( @RequestParam("movieID") Integer movieID, @RequestParam("cinemaHallID") Integer cinemaHallID, @RequestParam("showDate") Date showDate, @RequestParam("showTime") Time showTime, HttpServletRequest request, HttpServletResponse response) { LogUtil.logReq(LOG, request); RestResponse result = new RestResponse(); MovieOnShow movieOnShow = movieOnShowService.getMovieOnShow(movieID, cinemaHallID, showDate, showTime); if (movieOnShow == null) { response.setStatus(404); return new ErrorResponse("Resource not found"); } result.put("movieOnShowID", movieOnShow.getMovieOnShowID()); result.put("movieID", movieOnShow.getMovie().getMovieID()); result.put("cinemaHallID", movieOnShow.getCinemaHall().getCinemaHallID()); result.put("lang", movieOnShow.getLang()); result.put("showDate", movieOnShow.getShowDate().toString()); result.put("showTime", movieOnShow.getShowTime().toString()); result.put("price", movieOnShow.getPrice()); response.setStatus(200); return result; } @RequestMapping(path = "/{movieOnShowID}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) public RestResponse getMovieOnShowByID(@PathVariable Integer movieOnShowID, HttpServletRequest request, HttpServletResponse response) { LogUtil.logReq(LOG, request); RestResponse result = new RestResponse(); MovieOnShow movieOnShow = movieOnShowService.getMovieOnShow(movieOnShowID); if (movieOnShow == null) { response.setStatus(404); return new ErrorResponse("Resource not found"); } result.put("movieOnShowID", movieOnShow.getMovieOnShowID()); result.put("movieID", movieOnShow.getMovie().getMovieID()); result.put("cinemaHallID", movieOnShow.getCinemaHall().getCinemaHallID()); result.put("lang", movieOnShow.getLang()); result.put("showDate", movieOnShow.getShowDate().toString()); result.put("showTime", movieOnShow.getShowTime().toString()); result.put("price", movieOnShow.getPrice()); response.setStatus(200); return result; } @RequestMapping(path = "/recent", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) public RestResponse getRecentMovieOnShow(@RequestParam("movieID") Integer movieID, HttpServletRequest request, HttpServletResponse response) { LogUtil.logReq(LOG, request); int range = 3; // Date date = Calendar.getInstance().getTime(); Date date = Date.valueOf("2017-04-04"); List<Date> dates = new ArrayList<Date>(); for (int i = 0; i < range; i++) { dates.add(date); date = DateUtil.getNextDate(date); } Map<Date, List<Integer>> resultMap = movieOnShowService.getCinemaIDsShowAtDates(movieID, dates); List<LinkedHashMap<String, Object>> dataList = new LinkedList<LinkedHashMap<String, Object>>(); for (int i = 0; i < dates.size(); i++) { if (resultMap.get(dates.get(i)).size() != 0) { RestResponse data = new RestResponse(); data.put("date", dates.get(i).toString()); data.put("cinemaID", resultMap.get(dates.get(i))); dataList.add(data); } } CollectionResponse result = new CollectionResponse(dataList); response.setStatus(200); return result; } @RequestMapping(path = "/day", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) public RestResponse getMovieOnShowByDay( @RequestParam("movieID") Integer movieID, @RequestParam("cinemaID") Integer cinemaID, @RequestParam("date") Date date, HttpServletRequest request, HttpServletResponse response) { LogUtil.logReq(LOG, request); List<Integer> idsList = movieOnShowService.getShowsIDADay(movieID, date, cinemaID); CollectionResponse result = new CollectionResponse(idsList); response.setStatus(200); return result; } @RequestMapping(path = "/day/brief", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) public RestResponse getBriefMovieOnShowByDay( @RequestParam("movieID") Integer movieID, @RequestParam("cinemaID") Integer cinemaID, @RequestParam("date") Date date, HttpServletRequest request, HttpServletResponse response) { LogUtil.logReq(LOG, request); RestResponse result = new RestResponse(); // TODO Construct MovieOnShow only with 'showTime' attribute // TODO Using MIN() of SQL to get the minimum price List<MovieOnShow> showList = movieOnShowService.getShowsADay(movieID, date, cinemaID); List<String> timeList = new LinkedList<String>(); float minPrice = Float.MAX_VALUE; for (MovieOnShow show : showList) { if (show.getPrice() < minPrice) minPrice = show.getPrice(); timeList.add(show.getShowTime().toString()); } if (timeList.size() == 0) minPrice = 0.00F; result.put("minPrice", minPrice); result.put("showTime", timeList); response.setStatus(200); return result; } }
package com.tinkerpop.rexster.extension; import com.tinkerpop.blueprints.pgm.Edge; import com.tinkerpop.blueprints.pgm.Element; import com.tinkerpop.blueprints.pgm.Graph; import com.tinkerpop.blueprints.pgm.Vertex; import com.tinkerpop.gremlin.jsr223.GremlinScriptEngine; import com.tinkerpop.rexster.ElementJSONObject; import com.tinkerpop.rexster.RexsterResourceContext; import com.tinkerpop.rexster.Tokens; import org.apache.log4j.Logger; import org.codehaus.jettison.json.JSONArray; import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; import javax.script.Bindings; import javax.script.ScriptEngine; import javax.script.SimpleBindings; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; @ExtensionNaming(namespace = "tp", name = "gremlin") public class GremlinExtension extends AbstractRexsterExtension { protected static Logger logger = Logger.getLogger(GremlinExtension.class); private final static ScriptEngine engine = new GremlinScriptEngine(); private static final String GRAPH_VARIABLE = "g"; private static final String VERTEX_VARIABLE = "v"; private static final String EDGE_VARIABLE = "e"; private static final String WILDCARD = "*"; private static final String SCRIPT = "script"; private static final String API_SHOW_TYPES = "displays the properties of the elements with their native data type (default is false)"; private static final String API_SCRIPT = "the Gremlin script to be evaluated"; private static final String API_RETURN_KEYS = "the element property keys to return (default is to return all element properties)"; @ExtensionDefinition(extensionPoint = ExtensionPoint.EDGE) @ExtensionDescriptor(description = "evaluate an ad-hoc Gremlin script for an edge.") public ExtensionResponse evaluateOnEdge(@RexsterContext RexsterResourceContext rexsterResourceContext, @RexsterContext Graph graph, @RexsterContext Edge edge, @ExtensionRequestParameter(name = Tokens.SHOW_TYPES, description = API_SHOW_TYPES) Boolean showTypesParam, @ExtensionRequestParameter(name = SCRIPT, description = API_SCRIPT) String script, @ExtensionRequestParameter(name = Tokens.RETURN_KEYS, description = API_RETURN_KEYS) JSONArray returnKeysParam) { return tryExecuteGremlinScript(rexsterResourceContext, graph, null, edge, showTypesParam, script, returnKeysParam); } @ExtensionDefinition(extensionPoint = ExtensionPoint.VERTEX) @ExtensionDescriptor(description = "evaluate an ad-hoc Gremlin script for a vertex.") public ExtensionResponse evaluateOnVertex(@RexsterContext RexsterResourceContext rexsterResourceContext, @RexsterContext Graph graph, @RexsterContext Vertex vertex, @ExtensionRequestParameter(name = Tokens.SHOW_TYPES, description = API_SHOW_TYPES) Boolean showTypesParam, @ExtensionRequestParameter(name = SCRIPT, description = API_SCRIPT) String script, @ExtensionRequestParameter(name = Tokens.RETURN_KEYS, description = API_RETURN_KEYS) JSONArray returnKeysParam) { return tryExecuteGremlinScript(rexsterResourceContext, graph, vertex, null, showTypesParam, script, returnKeysParam); } @ExtensionDefinition(extensionPoint = ExtensionPoint.GRAPH) @ExtensionDescriptor(description = "evaluate an ad-hoc Gremlin script for a graph.") public ExtensionResponse evaluateOnGraph(@RexsterContext RexsterResourceContext rexsterResourceContext, @RexsterContext Graph graph, @ExtensionRequestParameter(name = Tokens.SHOW_TYPES, description = API_SHOW_TYPES) Boolean showTypesParam, @ExtensionRequestParameter(name = SCRIPT, description = API_SCRIPT) String script, @ExtensionRequestParameter(name = Tokens.RETURN_KEYS, description = API_RETURN_KEYS) JSONArray returnKeysParam) { return tryExecuteGremlinScript(rexsterResourceContext, graph, null, null, showTypesParam, script, returnKeysParam); } private ExtensionResponse tryExecuteGremlinScript(RexsterResourceContext rexsterResourceContext, Graph graph, Vertex vertex, Edge edge, Boolean showTypesParam, String script, JSONArray returnKeysParam) { ExtensionResponse extensionResponse; boolean showTypes = showTypesParam != null ? showTypesParam.booleanValue() : false; Bindings bindings = new SimpleBindings(); bindings.put(GRAPH_VARIABLE, graph); bindings.put(VERTEX_VARIABLE, vertex); bindings.put(EDGE_VARIABLE, edge); // read the return keys from the request object List<String> returnKeys = this.parseReturnKeys(returnKeysParam); ExtensionMethod extensionMethod = rexsterResourceContext.getExtensionMethod(); try { if (script != null && !script.isEmpty()) { JSONArray results = new JSONArray(); Object result = engine.eval(script, bindings); if (result == null) { // for example a script like g.clear() results = null; } else if (result instanceof Iterable) { for (Object o : (Iterable) result) { results.put(prepareOutput(o, returnKeys, showTypes)); } } else if (result instanceof Iterator) { Iterator itty = (Iterator) result; while (itty.hasNext()) { results.put(prepareOutput(itty.next(), returnKeys, showTypes)); } } else { results.put(prepareOutput(result, returnKeys, showTypes)); } HashMap<String, Object> resultMap = new HashMap<String, Object>(); resultMap.put(Tokens.SUCCESS, true); resultMap.put(Tokens.RESULTS, results); JSONObject resultObject = new JSONObject(resultMap); extensionResponse = ExtensionResponse.ok(resultObject); } else { extensionResponse = ExtensionResponse.error( "no script provided", generateErrorJson(extensionMethod.getExtensionApiAsJson())); } } catch (Exception e) { extensionResponse = ExtensionResponse.error(e, generateErrorJson(extensionMethod.getExtensionApiAsJson())); } return extensionResponse; } private List<String> parseReturnKeys(JSONArray returnKeysJson) { List<String> returnKeys = null; if (returnKeysJson != null) { returnKeys = new ArrayList<String>(); if (returnKeysJson != null) { for (int ix = 0; ix < returnKeysJson.length(); ix++) { returnKeys.add(returnKeysJson.optString(ix)); } } else { returnKeys = null; } if (returnKeys != null && returnKeys.size() == 1 && returnKeys.get(0).equals(WILDCARD)) { returnKeys = null; } } return returnKeys; } private Object prepareOutput(Object object, List<String> returnKeys, boolean showTypes) throws JSONException { if (object instanceof Element) { if (returnKeys == null) { return new ElementJSONObject((Element) object, showTypes); } else { return new ElementJSONObject((Element) object, returnKeys, showTypes); } } else if (object instanceof Number || object instanceof Boolean) { return object; } else { return object.toString(); } } }
package com.twocentsforthoughts.dropzone.client; import com.google.gwt.core.shared.GWT; import com.google.gwt.dom.client.Element; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.HTML; import com.twocentsforthoughts.dropzone.client.event.DropzoneEventHandler; import com.twocentsforthoughts.dropzone.client.injector.ResourceInjector; import com.twocentsforthoughts.dropzone.client.injector.resources.Resources; import com.twocentsforthoughts.dropzone.client.interfaces.DropzoneDictonary; import com.twocentsforthoughts.dropzone.client.interfaces.DropzoneOptions; public class Dropzone extends Composite { /** * Create the object that contains the Dictonary used by {@link Dropzone} * * @return a default (en-us) {@link DropzoneDictonary} instance */ public static DropzoneDictonary dictionary() { return Dictionary.create(); } /** * Create the object that contains the Options used by {@link Dropzone} * * @return a default {@link DropzoneOptions} instance */ public static DropzoneOptions options() { return Options.create(); } private DropzoneOptions options; private DropzoneEventHandler handler; private DropzoneDictonary dictionary; public Dropzone(DropzoneOptions options) { this(options, null, null, (Resources) GWT.create(Resources.class)); } public Dropzone(DropzoneOptions options, DropzoneDictonary dictionary) { this(options, null, dictionary, (Resources) GWT.create(Resources.class)); } public Dropzone(DropzoneOptions options, DropzoneEventHandler handler) { this(options, handler, null, (Resources) GWT.create(Resources.class)); } public Dropzone(DropzoneOptions options, DropzoneEventHandler handler, DropzoneDictonary dictionary) { this(options, handler, dictionary, (Resources) GWT .create(Resources.class)); } public Dropzone(DropzoneOptions options, DropzoneEventHandler handler, DropzoneDictonary dictionary, Resources resources) { this.options = options; this.handler = handler; this.dictionary = dictionary; injectResources(resources); initWidget(); } private native void initDropzone(Element e, DropzoneOptions options, DropzoneEventHandler handler, DropzoneDictonary dictionary) /*-{ //if there is a dictionary, iterate over it and transfer the values if (dictionary) { for ( var key in dictionary) { if (dictionary.hasOwnProperty(key)) { options[key] = dictionary[key]; } } } var dropzone = new $wnd.Dropzone(e, options); //If not loaded, don't add the handlers. if (!(dropzone instanceof $wnd.Dropzone)) { return; } //I'm loaded, add the eventHandlers //TODO: refactor this to another method if (this.@com.twocentsforthoughts.dropzone.client.Dropzone::handler) { dropzone .on( "addedfile", function(file) { handler.@com.twocentsforthoughts.dropzone.client.event.DropzoneEventHandler::onAddedFile(Lcom/twocentsforthoughts/dropzone/client/interfaces/File;)(file); }); dropzone .on( "removedfile", function(file) { handler.@com.twocentsforthoughts.dropzone.client.event.DropzoneEventHandler::onRemovedfile(Lcom/twocentsforthoughts/dropzone/client/interfaces/File;)(file); }); dropzone .on( "thumbnail", function(file, dataUri) { handler.@com.twocentsforthoughts.dropzone.client.event.DropzoneEventHandler::onThumbnail(Lcom/twocentsforthoughts/dropzone/client/interfaces/File;Ljava/lang/String;)(file,dataUri); }); dropzone .on( "error", function(file, message, xhrObject) { handler.@com.twocentsforthoughts.dropzone.client.event.DropzoneEventHandler::onError(Lcom/twocentsforthoughts/dropzone/client/interfaces/File;Ljava/lang/String;Lcom/twocentsforthoughts/dropzone/client/interfaces/XHRObjet;)(file,message,xhrObject); }); dropzone .on( "processing", function(file) { handler.@com.twocentsforthoughts.dropzone.client.event.DropzoneEventHandler::onProcessing(Lcom/twocentsforthoughts/dropzone/client/interfaces/File;)(file); }); dropzone .on( "uploadprogress", function(file, progress, bytesSent) { handler.@com.twocentsforthoughts.dropzone.client.event.DropzoneEventHandler::onUploadProgress(Lcom/twocentsforthoughts/dropzone/client/interfaces/File;II)(file,progress,bytesSent); }); dropzone .on( "sending", function(file, xhrObject, formData) { handler.@com.twocentsforthoughts.dropzone.client.event.DropzoneEventHandler::onSending(Lcom/twocentsforthoughts/dropzone/client/interfaces/File;Lcom/twocentsforthoughts/dropzone/client/interfaces/FormData;Lcom/twocentsforthoughts/dropzone/client/interfaces/XHRObjet;)(file,xhrObject,formData); }); dropzone .on( "success", function(file, response) { handler.@com.twocentsforthoughts.dropzone.client.event.DropzoneEventHandler::onSuccess(Lcom/twocentsforthoughts/dropzone/client/interfaces/File;Ljava/lang/String;)(file,response); }); dropzone .on( "complete", function(file) { handler.@com.twocentsforthoughts.dropzone.client.event.DropzoneEventHandler::onComplete(Lcom/twocentsforthoughts/dropzone/client/interfaces/File;)(file); }); dropzone .on( "canceled", function(file) { handler.@com.twocentsforthoughts.dropzone.client.event.DropzoneEventHandler::onCancelled(Lcom/twocentsforthoughts/dropzone/client/interfaces/File;)(file); }); dropzone .on( "maxfilesreached", function(file) { handler.@com.twocentsforthoughts.dropzone.client.event.DropzoneEventHandler::onMaxFilesReached(Lcom/twocentsforthoughts/dropzone/client/interfaces/File;)(file); }); dropzone .on( "maxfilesexceeded", function(file) { handler.@com.twocentsforthoughts.dropzone.client.event.DropzoneEventHandler::onMaxFilesExceeded(Lcom/twocentsforthoughts/dropzone/client/interfaces/File;)(file); }); } }-*/; private void initWidget() { HTML widget = new HTML(); widget.setStylePrimaryName("dropzone"); initWidget(widget); }; private void injectResources(Resources resources) { ResourceInjector.configure(resources); } @Override protected void onAttach() { initDropzone(getElement(), options, handler, dictionary); super.onAttach(); } }
package com.xtremelabs.robolectric.shadows; import android.app.Application; import android.content.Context; import android.content.res.Resources; import android.content.res.TypedArray; import android.util.AttributeSet; import com.xtremelabs.robolectric.internal.Implementation; import com.xtremelabs.robolectric.internal.Implements; import com.xtremelabs.robolectric.internal.RealObject; import com.xtremelabs.robolectric.res.ResourceLoader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.util.UUID; import static com.xtremelabs.robolectric.Robolectric.shadowOf; /** * Calls through to the {@code resourceLoader} to actually load resources. */ @SuppressWarnings({"UnusedDeclaration"}) @Implements(Context.class) abstract public class ShadowContext { public static final File CACHE_DIR = new File(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString() + "android-cache"); public static final File EXTERNAL_CACHE_DIR = new File(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString() + "android-external-cache"); public static final File FILES_DIR = new File(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString() + "android-tmp"); public static final File DOWNLOADS_DIR = new File(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString() + "android-dls"); @RealObject private Context realContext; @Implementation public String getString(int resId) { return realContext.getResources().getString(resId); } @Implementation public CharSequence getText(int resId) { return realContext.getResources().getText(resId); } @Implementation public String getString(int resId, Object... formatArgs) { return realContext.getResources().getString(resId, formatArgs); } @Implementation abstract public Resources.Theme getTheme(); @Implementation public final TypedArray obtainStyledAttributes( int[] attrs) { return getTheme().obtainStyledAttributes(attrs); } @Implementation public final TypedArray obtainStyledAttributes( int resid, int[] attrs) throws Resources.NotFoundException { return getTheme().obtainStyledAttributes(resid, attrs); } @Implementation public final TypedArray obtainStyledAttributes( AttributeSet set, int[] attrs) { return getTheme().obtainStyledAttributes(set, attrs, 0, 0); } @Implementation public final TypedArray obtainStyledAttributes( AttributeSet set, int[] attrs, int defStyleAttr, int defStyleRes) { return getTheme().obtainStyledAttributes( set, attrs, defStyleAttr, defStyleRes); } @Implementation public File getCacheDir() { CACHE_DIR.mkdirs(); return CACHE_DIR; } @Implementation public File getFilesDir() { FILES_DIR.mkdirs(); return FILES_DIR; } @Implementation public File getExternalCacheDir() { EXTERNAL_CACHE_DIR.mkdir(); return EXTERNAL_CACHE_DIR; } @Implementation public FileInputStream openFileInput(String path) throws FileNotFoundException { return new FileInputStream(getFileStreamPath(path)); } @Implementation public FileOutputStream openFileOutput(String path, int mode) throws FileNotFoundException { return new FileOutputStream(getFileStreamPath(path)); } @Implementation public File getFileStreamPath(String name) { if (name.contains(File.separator)) { throw new IllegalArgumentException("File " + name + " contains a path separator"); } return new File(getFilesDir(), name); } /** * Non-Android accessor. * * @return the {@code ResourceLoader} associated with this {@code Context} */ public ResourceLoader getResourceLoader() { return shadowOf((Application) realContext.getApplicationContext()).getResourceLoader(); } public static void clearFilesAndCache() { clearFiles(FILES_DIR); clearFiles(CACHE_DIR); clearFiles(EXTERNAL_CACHE_DIR); } public static void clearFiles(File dir) { if (dir != null && dir.isDirectory()) { File[] files = dir.listFiles(); if (files != null) { for (File f : files) { if (f.isDirectory()) { clearFiles(f); } f.delete(); } } } } }
package com.yahoo.sketches.quantiles; import com.yahoo.memory.Memory; import com.yahoo.memory.WritableMemory; /** * @author Jon Malkin */ public abstract class UpdateDoublesSketch extends DoublesSketch { UpdateDoublesSketch(final int k) { super(k); } /** * Wrap this sketch around the given non-compact Memory image of a DoublesSketch. * * @param srcMem the given Memory image of a DoublesSketch that may have data, * @return a sketch that wraps the given srcMem */ public static UpdateDoublesSketch wrap(final WritableMemory srcMem) { return DirectUpdateDoublesSketch.wrapInstance(srcMem); } /** * Updates this sketch with the given double data item * * @param dataItem an item from a stream of items. NaNs are ignored. */ public abstract void update(double dataItem); /** * Resets this sketch to the empty state, but retains the original value of k. */ public abstract void reset(); public static UpdateDoublesSketch heapify(final Memory srcMem) { return HeapUpdateDoublesSketch.heapifyInstance(srcMem); } public CompactDoublesSketch compact() { return compact(null); } /** * Returns a compact version of this sketch. If passing in a Memory object, the compact sketch * will use that direct memory; otherwise, an on-heap sketch will be returned. * @param dstMem An optional target memory to hold the sketch. * @return A compact version of this sketch */ public CompactDoublesSketch compact(final WritableMemory dstMem) { if (dstMem == null) { return HeapCompactDoublesSketch.createFromUpdateSketch(this); } return DirectCompactDoublesSketch.createFromUpdateSketch(this, dstMem); } @Override boolean isCompact() { return false; } //Puts /** * Puts the min value * * @param minValue the given min value */ abstract void putMinValue(double minValue); /** * Puts the max value * * @param maxValue the given max value */ abstract void putMaxValue(double maxValue); /** * Puts the value of <i>n</i> * * @param n the given value of <i>n</i> */ abstract void putN(long n); /** * Puts the combined, non-compact buffer. * * @param combinedBuffer the combined buffer array */ abstract void putCombinedBuffer(double[] combinedBuffer); /** * Puts the base buffer count * * @param baseBufCount the given base buffer count */ abstract void putBaseBufferCount(int baseBufCount); /** * Puts the bit pattern * * @param bitPattern the given bit pattern */ abstract void putBitPattern(long bitPattern); /** * Grows the combined buffer to the given spaceNeeded * * @param currentSpace the current allocated space * @param spaceNeeded the space needed * @return the enlarged combined buffer with data from the original combined buffer. */ abstract double[] growCombinedBuffer(int currentSpace, int spaceNeeded); }