protected State createNewState(State parent, char letter) { String newStateName = ((parent.getName().equals("'root'")) ? "" : parent.getName()) + letter; State newState; try { newState = addNewState(newStateName); } catch (StateException e) { return getTransition(parent, letter); } addTransition(parent, letter, newState); if (parent.equals(root)) { fallbacks.put(newState, root); } else { State state = parent, stateForLetter = null; do { state = fallbacks.get(state); stateForLetter = getTransition(state, letter); } while (stateForLetter == null && !root.equals(state)); if (stateForLetter != null) { fallbacks.put(newState, stateForLetter); if (isAccepting(stateForLetter)) { setAccepting(newState); } } else { fallbacks.put(newState, root); } } return newState; }
@Override public String toString() { if (state.equals(State.STOPED)) return name + ": " + getElapsedTime(); if (state.equals(State.STARTED)) return name + ": " + getElapsedTime() + " (still running)"; if (state.equals(State.ZERO)) return name + " is not started yet"; return ""; };
@Override public void close() { Preconditions.checkState( Thread.currentThread().getId() == initialThreadId, "close() called from different thread than getTransaction()!"); Preconditions.checkState( state.equals(State.NEW) || state.equals(State.COMPLETED), "close() called when transaction is %s" + " - you must either commit or rollback first", state); state = State.CLOSED; doClose(); }
/** {@inheritDoc} */ @Override public boolean setRecording(String from, String token, State doRecord, String path) { if (!StringUtils.isNullOrEmpty(this.token) && !this.token.equals(token)) { return false; } if (!isRecording() && doRecord.equals(State.ON)) { // Send start recording IQ JireconIq recording = new JireconIq(); recording.setTo(recorderComponentJid); recording.setType(IQ.Type.SET); recording.setFrom(from); recording.setMucJid(mucRoomJid); recording.setAction(JireconIq.Action.START); recording.setOutput(path); Packet reply = xmpp.getXmppConnection().sendPacketAndGetReply(recording); if (reply instanceof JireconIq) { JireconIq recResponse = (JireconIq) reply; if (JireconIq.Status.INITIATING.equals(recResponse.getStatus())) { recordingId = recResponse.getRid(); logger.info("Received recording ID: " + recordingId); status = JireconIq.Status.INITIATING; } else { logger.error("Unexpected status received: " + recResponse.toXML()); } } else { logger.error("Unexpected response: " + IQUtils.responseToXML(reply)); } } else if (isRecording() && doRecord.equals(State.OFF)) { // Send stop recording IQ JireconIq recording = new JireconIq(); recording.setTo(recorderComponentJid); recording.setType(IQ.Type.SET); recording.setFrom(from); recording.setRid(recordingId); recording.setMucJid(mucRoomJid); recording.setAction(JireconIq.Action.STOP); xmpp.getXmppConnection().sendPacket(recording); status = JireconIq.Status.STOPPING; } return true; }
/** * Builds a Trellis over a sentence, by starting at the state State, and advancing through all * legal extensions of each state already in the trellis. You should not have to modify this * code (or even read it, really). */ private Trellis<State> buildTrellis(List<String> sentence) { Trellis<State> trellis = new Trellis<State>(); trellis.setStartState(State.getStartState()); State stopState = State.getStopState(sentence.size() + 2); trellis.setStopState(stopState); Set<State> states = Collections.singleton(State.getStartState()); for (int position = 0; position <= sentence.size() + 1; position++) { Set<State> nextStates = new HashSet<State>(); for (State state : states) { if (state.equals(stopState)) continue; LocalTrigramContext localTrigramContext = new LocalTrigramContext( sentence, position, state.getPreviousPreviousTag(), state.getPreviousTag()); Counter<String> tagScores = localTrigramScorer.getLogScoreCounter(localTrigramContext); for (String tag : tagScores.keySet()) { double score = tagScores.getCount(tag); State nextState = state.getNextState(tag); trellis.setTransitionCount(state, nextState, score); nextStates.add(nextState); } } // System.out.println("States: "+nextStates); states = nextStates; } return trellis; }
public long getElapsedTime() { if (state.equals(State.ZERO)) throw new RuntimeException( "Invalid call when the time has never been started or has been reseted whitout beaing started again."); if (end == NOT_INITIALISED_LONG) return getCurrentTime() - start; return end - start; }
/** Wait until given service has entered specific state. */ public static void waitForState(String service, State state, long timeoutMillis) throws TimeoutException { final long endMillis = SystemClock.elapsedRealtime() + timeoutMillis; while (true) { synchronized (sPropertyLock) { final State currentState = getState(service); if (state.equals(currentState)) { return; } if (SystemClock.elapsedRealtime() >= endMillis) { throw new TimeoutException( "Service " + service + " currently " + currentState + "; waited " + timeoutMillis + "ms for " + state); } try { sPropertyLock.wait(timeoutMillis); } catch (InterruptedException e) { } } } }
@Override public double getActivityEndTime() { if (isArriving && agentState.equals(MobsimAgent.State.ACTIVITY)) { return Double.POSITIVE_INFINITY; } return this.actEndTime; }
@Override public boolean equals(Object obj) { if (obj instanceof Transition) return labelIn.equals(((Transition) obj).labelIn) && labelOut.equals(((Transition) obj).labelOut) && to.equals(((Transition) obj).to); else return false; }
@Override public boolean equals(Object obj) { if (obj == null) { return false; } if (!(obj instanceof View)) { return false; } View other = (View) obj; return state.equals(other.state) && expired == other.expired; }
/** {@inheritDoc} */ @Override public void channelContentChanged() { synchronized (getTreeLock()) { State state = new State(); EcoIdentity entity; EcoIdentity previousEcoEntity; for (CubeEcoChannel channel : this.channels) { if (channel.getAgentType() == AgentType.CUBE) { entity = channel.getEcoEntity(); assert (entity != null); state.ecoStates.put(entity, channel.getEcoState()); for (EcoRelation relation : channel.getAcquaintances()) { if (relation instanceof DownwardRelation) { DownwardRelation dr = (DownwardRelation) relation; if (dr.getMaster().equals(entity)) { if (this.planeEntity.equals(dr.getSlave())) { // on ground if (!state.onGround.add(entity)) { state.isInconsistent = true; } } else { // on other previousEcoEntity = state.map.put(dr.getSlave(), entity); if (previousEcoEntity != null && !entity.equals(previousEcoEntity)) { state.isInconsistent = true; } } } } } state.isInitialization = state.isInitialization || channel.getEcoState().isInitializationState(); } } if (!state.onGround.isEmpty()) { State lastState = getLastState(); if (lastState == null || !lastState.equals(state)) { this.worldStates.add(state); int oldIndex = this.currentStateIndex; if (this.currentStateIndex < 0) { this.currentStateIndex = 0; } else if (this.currentStateIndex >= this.worldStates.size()) { this.currentStateIndex = this.worldStates.size() - 1; } updateUIComponents(); if (this.currentStateIndex != oldIndex) repaint(); } } } }
@Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof User)) return false; User user = (User) o; if (name != null ? !name.equals(user.name) : user.name != null) return false; if (role != null ? !role.equals(user.role) : user.role != null) return false; if (state != null ? !state.equals(user.state) : user.state != null) return false; return true; }
protected void completeAutomaton() { for (State state : getStates()) { for (Character letter : usedAlphabet()) { if (getTransition(state, letter) == null) { if (state.equals(root)) { addTransition(state, letter, root); } else { addTransition(state, letter, getTransition(fallbacks.get(state), letter)); } } } } }
/** The method to which {@link BasicChannelSemantics} delegates calls to <code>take</code>. */ protected Event take() { Preconditions.checkState( Thread.currentThread().getId() == initialThreadId, "take() called from different thread than getTransaction()!"); Preconditions.checkState( state.equals(State.OPEN), "take() called when transaction is %s!", state); try { return doTake(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return null; } }
/** The method to which {@link BasicChannelSemantics} delegates calls to <code>put</code>. */ protected void put(Event event) { Preconditions.checkState( Thread.currentThread().getId() == initialThreadId, "put() called from different thread than getTransaction()!"); Preconditions.checkState( state.equals(State.OPEN), "put() called when transaction is %s!", state); Preconditions.checkArgument(event != null, "put() called with null event!"); try { doPut(event); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new ChannelException(e.toString(), e); } }
@Override public boolean equals(Object o) { if (o == this) { return true; } if (!(o instanceof Device)) { return false; } Device d = (Device) o; return mName.equals(d.getName()) && mManufacturer.equals(d.getManufacturer()) && mSoftware.equals(d.getAllSoftware()) && mState.equals(d.getAllStates()) && mMeta.equals(d.getMeta()) && mDefaultState.equals(d.getDefaultState()); }
@Override public void rollback() { Preconditions.checkState( Thread.currentThread().getId() == initialThreadId, "rollback() called from different thread than getTransaction()!"); Preconditions.checkState( state.equals(State.OPEN), "rollback() called when transaction is %s!", state); state = State.COMPLETED; try { doRollback(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new ChannelException(e.toString(), e); } }
@Override public void begin() { Preconditions.checkState( Thread.currentThread().getId() == initialThreadId, "begin() called from different thread than getTransaction()!"); Preconditions.checkState( state.equals(State.NEW), "begin() called when transaction is " + state + "!"); try { doBegin(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new ChannelException(e.toString(), e); } state = State.OPEN; }
@Nullable private State checkAndAdvanceState( MethodInvocationTree mit, State requiredState, State nextState) { ExpressionTree methodSelect = mit.methodSelect(); if (methodSelect.is(Tree.Kind.MEMBER_SELECT)) { ExpressionTree expressionTree = ((MemberSelectExpressionTree) methodSelect).expression(); if (expressionTree.is(Tree.Kind.IDENTIFIER)) { Symbol symbol = ((IdentifierTree) expressionTree).symbol(); Map<Symbol, State> symbolStateMap = symbolStack.peek(); if (symbolStateMap != null && symbolStateMap.containsKey(symbol) && requiredState.equals(symbolStateMap.get(symbol))) { symbolStateMap.put(symbol, nextState); return nextState; } } } return null; }
public void drawPlayer(Batch batch) { if (spriteState.equals(State.Walking)) { stateTime += Gdx.graphics.getDeltaTime(); switch (spriteDirection) { case n: currentFrame = Assets.instance.player.getNorthAnimation().getKeyFrame(stateTime, true); break; case s: currentFrame = Assets.instance.player.getSouthAnimation().getKeyFrame(stateTime, true); break; case w: currentFrame = Assets.instance.player.getWestAnimation().getKeyFrame(stateTime, true); break; case e: currentFrame = Assets.instance.player.getEastAnimation().getKeyFrame(stateTime, true); break; default: break; } } else { switch (spriteDirection) { case n: currentFrame = Assets.instance.player.getNorthAnimation().getKeyFrame(0); break; case s: currentFrame = Assets.instance.player.getSouthAnimation().getKeyFrame(0); break; case w: currentFrame = Assets.instance.player.getWestAnimation().getKeyFrame(0); break; case e: currentFrame = Assets.instance.player.getEastAnimation().getKeyFrame(0); break; default: break; } } sprite.setRegion(currentFrame); batch.begin(); sprite.draw(batch); batch.end(); }
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Field<?> other = (Field<?>) obj; if (remarks == null) { if (other.remarks != null) return false; } else if (!remarks.equals(other.remarks)) return false; if (state == null) { if (other.state != null) return false; } else if (!state.equals(other.state)) return false; if (symbol == null) { if (other.symbol != null) return false; } else if (!symbol.equals(other.symbol)) return false; if (value == null) { if (other.value != null) return false; } else if (!value.equals(other.value)) return false; if (valueType == null) { if (other.valueType != null) return false; } else if (!valueType.equals(other.valueType)) return false; return true; }
private boolean isFinalStates(State s, List<State> finalStates) { for (State state : finalStates) { if (state.equals(s)) return true; } return false; }
public static boolean inEndState() { for (State s : endStates) if (s.equals(current)) return true; return false; }
private void setInternalStates() { if (writeOnFirstStateEntry) { // First time after service is started writeOnFirstStateEntry = false; // Make sure a item is written to cache stateChange = true; resolved = false; notify = false; } else if (previousFSM.equals(State.OKAY_HARD) && fsm.equals(State.PROBLEM_SOFT)) { resolved = false; notify = false; stateChange = true; } else if (previousFSM.equals(State.PROBLEM_SOFT) && fsm.equals(State.PROBLEM_HARD)) { // This means its a new incident nextIncidentId(); // new incident and not resolved resolved = false; notify = true; stateChange = true; } else if (previousFSM.equals(State.PROBLEM_SOFT) && fsm.equals(State.OKAY_HARD)) { resolved = true; notify = false; stateChange = true; } else if (previousFSM.equals(State.PROBLEM_HARD) && fsm.equals(State.OKAY_HARD)) { resolved = true; notify = true; stateChange = true; } else if (previousFSM.equals(State.OKAY_HARD) && fsm.equals(State.OKAY_HARD)) { resolved = true; notify = false; stateChange = false; } else if (previousFSM.equals(State.PROBLEM_HARD) && fsm.equals(State.PROBLEM_HARD)) { if ((getState() == NAGIOSSTAT.CRITICAL && previousState == NAGIOSSTAT.WARNING) || (getState() == NAGIOSSTAT.CRITICAL && previousState == NAGIOSSTAT.UNKNOWN) || (getState() == NAGIOSSTAT.WARNING && previousState == NAGIOSSTAT.CRITICAL) || (getState() == NAGIOSSTAT.WARNING && previousState == NAGIOSSTAT.UNKNOWN) || (getState() == NAGIOSSTAT.UNKNOWN && previousState == NAGIOSSTAT.WARNING) || (getState() == NAGIOSSTAT.UNKNOWN && previousState == NAGIOSSTAT.CRITICAL)) { // This means its an update on existing incident resolved = false; notify = true; stateChange = true; } else if ((getState() == NAGIOSSTAT.CRITICAL && previousState == NAGIOSSTAT.CRITICAL) || (getState() == NAGIOSSTAT.WARNING && previousState == NAGIOSSTAT.WARNING) || (getState() == NAGIOSSTAT.UNKNOWN && previousState == NAGIOSSTAT.UNKNOWN)) { resolved = false; notify = false; stateChange = false; } } else if (isSoftState() && isSoftCountInc()) { resolved = false; notify = false; stateChange = true; } }
public boolean isState(State s) { return state.equals(s); }
/** * Check that table in given states * * @param states state list * @return true if satisfies */ public boolean inStates(State... states) { for (State s : states) { if (s.equals(this.state)) return true; } return false; }
/** * Static version of state checker * * @param state desired * @param target equals to any of * @return true if satisfies */ public static boolean isInStates(State state, State... target) { for (State tableState : target) { if (state.equals(tableState)) return true; } return false; }
/** * Ensures the requested amount of resources are going to be available in the foreseeable future * on this physical machine. * * @param requested The amount of resources needed by the caller * @return With a time limited offer on the requested resources. If the requested * resourceconstraints cannot be met by the function then it returns with the maximum amount * of resources it can serve. If there are no available resources it returns with <i>null</i>! * If the requested resources are available then the original requested resourceconstraints * object is stored in the returned resource allocation. If the resourceconstraints only * specified a minimum resource limit, then a new resourceconstraints object is returned with * details of the maximum possible resource constraints that can fit into the machine. */ public ResourceAllocation allocateResources( final ResourceConstraints requested, final boolean strict, final int allocationValidityLength) throws VMManagementException { if (!currentState.equals(State.RUNNING)) { throw new VMManagementException("The PM is not running and thus cannot offer resources yet"); } // Basic tests for resource availability for the host if (internalReallyFreeCaps.getRequiredCPUs() == 0 || internalReallyFreeCaps.getRequiredMemory() == 0 || requested.getRequiredProcessingPower() > internalReallyFreeCaps.getRequiredProcessingPower()) { return null; } // Allocation type test (i.e. do we allow underprovisioning?) for (int i = 0; i < promisedResources.length; i++) { ResourceAllocation olderAllocation = promisedResources[i]; if (olderAllocation != null) { if (olderAllocation.allocated.isRequiredProcessingIsMinimum() == requested.isRequiredProcessingIsMinimum()) { break; } else { return null; } } } // Promised resources for the virtual machine double vmCPU = requested.getRequiredCPUs(); long vmMem = requested.getRequiredMemory(); final double vmPrPow = requested.isRequiredProcessingIsMinimum() ? totalCapacities.getRequiredProcessingPower() : requested.getRequiredProcessingPower(); // Actually allocated resources (memory is equivalent in both cases) final double allocPrPow = totalCapacities.getRequiredProcessingPower(); final double allocCPU = vmCPU * requested.getRequiredProcessingPower() / allocPrPow; if (0 <= internalReallyFreeCaps.getRequiredCPUs() - allocCPU) { if (0 <= internalReallyFreeCaps.getRequiredMemory() - requested.getRequiredMemory()) { return new ResourceAllocation( new ConstantConstraints(allocCPU, allocPrPow, vmMem), requested.isRequiredProcessingIsMinimum() ? new ConstantConstraints(vmCPU, vmPrPow, true, vmMem) : requested, allocationValidityLength); } else { vmMem = internalReallyFreeCaps.getRequiredMemory(); } } else if (0 <= internalReallyFreeCaps.getRequiredMemory() - requested.getRequiredMemory()) { vmCPU = internalReallyFreeCaps.getRequiredCPUs(); } else { vmCPU = internalReallyFreeCaps.getRequiredCPUs(); vmMem = internalReallyFreeCaps.getRequiredMemory(); } if (strict) { return null; } else { final ResourceConstraints updatedConstraints = new ConstantConstraints(vmCPU, vmPrPow, requested.isRequiredProcessingIsMinimum(), vmMem); return new ResourceAllocation( updatedConstraints, updatedConstraints, allocationValidityLength); } }
/** * Determines if the machine can be used for VM instantiation. * * @return * <ul> * <li>true if the machine is ready to accept VM requests * <li>false otherwise * </ul> */ public boolean isRunning() { return currentState.equals(State.RUNNING); }
public void work() { if (!state.equals(State.IDLE)) { throw new IllegalStateException( "Can not call work while worker " + "is running or shutting down"); } state = State.RUNNING; // a map keeping track of sessions with connection errors // (to avoid printing an error about them in every reconnect attempt) Map<GearmanJobServerSession, Boolean> havingConnectionError = new HashMap<GearmanJobServerSession, Boolean>(); while (isRunning()) { // look for sessions which have been disconnected and attempt to reconnect. for (Iterator<GearmanJobServerSession> iter = sessionMap.values().iterator(); iter.hasNext(); ) { GearmanJobServerSession sess = iter.next(); if (!sess.isInitialized()) { try { // reconnect, unregister old selection key and register new one SelectionKey oldKey = sess.isInitialized() ? sess.getSelectionKey() : null; sess.initSession(ioAvailable, this); if (oldKey != null) { iter.remove(); } sessionMap.put(sess.getSelectionKey(), sess); // register all functions with the newly reconnected server for (FunctionDefinition d : functionMap.values()) { GearmanTask gsr = new GearmanTask(null, generateCanDoPacket(d)); sess.submitTask(gsr); } GearmanPacket p = new GearmanPacketImpl( GearmanPacketMagic.REQ, GearmanPacketType.SET_CLIENT_ID, ByteUtils.toUTF8Bytes(id)); sess.submitTask(new GearmanTask(p)); GearmanTask sessTask = new GearmanTask( new GrabJobEventHandler(sess), new GearmanPacketImpl( GearmanPacketMagic.REQ, getGrabJobPacketType(), new byte[0])); sess.submitTask(sessTask); sess.driveSessionIO(); // log reconnection message if (havingConnectionError.get(sess)) { LOG.info("Re-established connection to " + sess.getConnection().toString()); } havingConnectionError.put(sess, false); } catch (IOException e) { if (!havingConnectionError.get(sess)) { LOG.warn("Error connecting to " + sess + ", will keep trying.."); } havingConnectionError.put(sess, true); try { Thread.sleep(50); } catch (InterruptedException e1) { } } } else { havingConnectionError.put(sess, false); } } for (GearmanJobServerSession sess : sessionMap.values()) { // if still disconnected, skip if (!sess.isInitialized()) { continue; } int interestOps = SelectionKey.OP_READ; if (sess.sessionHasDataToWrite()) { interestOps |= SelectionKey.OP_WRITE; } sess.getSelectionKey().interestOps(interestOps); } try { ioAvailable.select(1); } catch (IOException io) { LOG.warn("Receieved IOException while" + " selecting for IO", io); } for (SelectionKey key : ioAvailable.selectedKeys()) { GearmanJobServerSession sess = sessionMap.get(key); if (sess == null) { LOG.warn("Worker does not have " + "session for key " + key); continue; } if (!sess.isInitialized()) { continue; } try { GearmanTask sessTask = taskMap.get(sess); if (sessTask == null) { sessTask = new GearmanTask( // NOPMD new GrabJobEventHandler(sess), new GearmanPacketImpl( GearmanPacketMagic.REQ, getGrabJobPacketType(), new byte[0])); taskMap.put(sess, sessTask); sess.submitTask(sessTask); LOG.debug( "Worker: " + this + " submitted a " + sessTask.getRequestPacket().getPacketType() + " to session: " + sess); } sess.driveSessionIO(); // For the time being we will execute the jobs synchronously // in the future, I expect to change this. if (!functionList.isEmpty()) { GearmanFunction fun = functionList.remove(); submitFunction(fun); statistics(); } } catch (IOException ioe) { LOG.warn("Received IOException while driving" + " IO on session " + sess, ioe); sess.closeSession(); continue; } } } shutDownWorker(true); }