示例#1
0
  public String invokeAction(
      State state, String instanceId, ProvisioningSettings settings, InstanceStatus status)
      throws StateMachineException {

    logger.info(
        "Invoking action '"
            + state.getAction()
            + "' of state '"
            + state.getId()
            + "' for instance '"
            + instanceId
            + "'");

    try {
      Class<?> c = Class.forName(clazz);
      Object o = c.newInstance();

      Class<?>[] paramTypes = new Class[3];
      paramTypes[0] = String.class;
      paramTypes[1] = ProvisioningSettings.class;
      paramTypes[2] = InstanceStatus.class;

      String methodName = state.getAction();
      Method m;
      try {
        m = c.getMethod(methodName, paramTypes);
      } catch (NoSuchMethodException e) {
        m = c.getSuperclass().getMethod(methodName, paramTypes);
      }
      return (String) m.invoke(o, instanceId, settings, status);
    } catch (InvocationTargetException e) {
      throw new StateMachineException(
          e.getCause().getMessage(), e.getCause(), instanceId, clazz, state.getAction());
    } catch (Exception e) {
      logger.error(
          "Failed to call action method '"
              + state.getAction()
              + "' of state '"
              + state.getId()
              + "' for class '"
              + clazz
              + "' and instance "
              + instanceId,
          e);
      throw new StateMachineException(
          "Runtime error in action method: " + e.getMessage(),
          e,
          instanceId,
          clazz,
          state.getAction());
    }
  }
示例#2
0
 public void testStateEnter() {
   assertEquals("myState", state.getId());
   MockRequestControlContext context = new MockRequestControlContext(flow);
   state.enter(context);
   assertEquals(state, context.getCurrentState());
   assertTrue(entered);
 }
示例#3
0
  @Test
  public void testOnEntry() throws Exception {
    State s1 = new State("s1");
    State s2 = new State("s2");

    s1.addTransition(new SuccessTransition("foo", s2));
    s1.addOnExitSelfTransaction(new SampleSelfTransition());
    s2.addOnEntrySelfTransaction(new SampleSelfTransition());

    StateContext context = new DefaultStateContext();
    StateMachine sm = new StateMachine(new State[] {s1, s2}, "s1");
    sm.handle(new Event("foo", context));
    assertEquals(true, context.getAttribute("success"));
    assertEquals(true, context.getAttribute("SelfSuccess" + s1.getId()));
    assertEquals(true, context.getAttribute("SelfSuccess" + s2.getId()));
  }
示例#4
0
  @Override
  public void format(HtmlWriter writer) throws IOException {
    writer.writeStart("pre");

    State state = getState();
    ObjectType type = state.getType();
    if (type != null) {
      writer.writeHtml(type.getInternalName());
      writer.writeHtml(": ");
    }

    writer.writeStart(
        "a",
        "target",
        "_blank",
        "href",
        StringUtils.addQueryParameters(
            "/_debug/query", "where", "id = " + state.getId(), "action", "Run"));
    writer.writeHtml(getLabel());
    writer.writeEnd();
    writer.writeElement("br");

    writer.writeHtml(ObjectUtils.toJson(state.getSimpleValues(), true));

    writer.writeEnd();
  }
 static {
   for (State state : State.values()) {
     mapping.put(state.getNodeName(), state);
     mapping2.put(state.getName(), state);
     mapping3.put(state.getId(), state);
   }
 }
示例#6
0
  //	public void start() {
  //		if(currentState != null)
  //			throw new IllegalStateException(String.format("State machine: %s is already started. Currnet
  // state id is %s", name, currentState.getId()));
  //
  //		currentState = startState;
  //	}
  //
  private State findState(String id) {
    for (State state : states) {
      if (state.getId().equalsIgnoreCase(id)) return state;
    }

    throw new NoSuchElementException(String.format("The given state id: %s is not found", id));
  }
示例#7
0
  public boolean notify(Event event) {
    State source = currentState;

    if (!currentState.isAcceptable(event)) return false;

    Transition trans = currentState.getTransition(event);
    State target = findState(trans.getTargetStateId());

    if (!gaurd.isTransitAllowed(source.getId(), target.getId(), event)) return false;

    currentState.exist(event);
    trans.transit(event);
    target.enter(event);
    currentState = target;

    return true;
  }
示例#8
0
  private void iterateEquipments(final State state, final AccessMode mode) throws Exception {
    _queryEquipment.bind(state.getId());
    QueryResults results = _queryEquipment.execute(mode);

    while (results.hasMore()) {
      iterateServices((Equipment) results.next(), mode);
    }
  }
示例#9
0
  public Object store(String id, State voobj) {
    State obj;

    if (id.equals("0")) {
      obj = new State();

    } else {
      obj = State.DAO().findById(id);
    }

    boolean isNewStateN65961 = obj.getId() == null || obj.getId().equals(0L);

    obj.setName(voobj.getName());
    obj.setCountry(Country.DAO().findBy(voobj.getCountry()));

    return obj.store();
  }
示例#10
0
 public void removeState(State state) {
   try {
     synchronized (_sessions) {
       _sessions.remove(state.getId());
     }
   } catch (Exception e) {
     Log.warn("could not remove session", e);
   }
 }
示例#11
0
 public void storeState(State state) {
   try {
     synchronized (_sessions) {
       _sessions.put(state.getId(), state);
     }
   } catch (Exception e) {
     Log.warn("could not store session");
   }
 }
示例#12
0
  private void iterateEquipmentsOID(final State state, final AccessMode mode) throws Exception {
    _queryEquipmentOID.bind(state.getId());
    QueryResults results = _queryEquipmentOID.execute(Database.ReadOnly);

    while (results.hasMore()) {
      OID oid = (OID) results.next();
      iterateServicesOID((Equipment) _db.load(Equipment.class, oid.getId(), mode), mode);
    }
  }
示例#13
0
  public void testHandledException() {
    state
        .getExceptionHandlerSet()
        .add(
            new FlowExecutionExceptionHandler() {
              public boolean canHandle(FlowExecutionException exception) {
                return true;
              }

              public void handle(FlowExecutionException exception, RequestControlContext context) {
                handled = true;
              }
            });
    FlowExecutionException e = new FlowExecutionException(flow.getId(), state.getId(), "Whatev");
    MockRequestControlContext context = new MockRequestControlContext(flow);
    assertTrue(state.handleException(e, context));
    assertTrue(handled);
  }
示例#14
0
 @Override
 public String getProcessUrl(
     String path, Map<String, ?> parameters, Parameters frameworkParameters, boolean escapeAmps)
     throws FrameworkException {
   HttpServletRequest request =
       BasicUrlConverter.getUserRequest(frameworkParameters.get(Parameter.REQUEST));
   State state = State.getState(request);
   frameworkParameters.set(ACTION, state.getId());
   Url url = urlConverter.getProcessUrl(path, parameters, frameworkParameters, escapeAmps);
   if (url == Url.NOT) {
     log.debug("Fall back url");
     return fallbackConverter
         .getProcessUrl(path, parameters, frameworkParameters, escapeAmps)
         .getUrl();
   } else {
     log.debug("Url converter url " + url);
     return url.getUrl();
   }
 }
 /**
  * Translates the LTS object to its TGF representation.
  *
  * @return The TGF content.
  */
 public String translate() {
   StringBuffer sb = new StringBuffer("");
   Iterator<State<S, T>> si = lts.getStates();
   while (si.hasNext()) {
     State s = si.next();
     sb.append(s.getId());
     sb.append(" ");
     sb.append(s.getValue().toString());
     sb.append("\n");
   }
   sb.append("#\n");
   Iterator<Transition<T, S>> ti = lts.getTransitions();
   while (ti.hasNext()) {
     Transition t = ti.next();
     sb.append(t.getFrom().getId());
     sb.append(" ");
     sb.append(t.getTo().getId());
     sb.append(" ");
     sb.append(t.getValue().toString());
     sb.append("\n");
   }
   return sb.toString();
 }
示例#16
0
  @Override
  public void saveState(State state, String activityId, Agent agent, UUID registration)
      throws Exception {
    HashMap<String, String> params = new HashMap<String, String>();
    params.put("stateId", state.getId());
    params.put("activityId", activityId);
    params.put("agent", agent.toJSON(this.getVersion(), this.usePrettyJSON()));
    if (registration != null) {
      params.put("registration", registration.toString());
    }

    String queryString = "?";
    Boolean first = true;
    for (Map.Entry<String, String> parameter : params.entrySet()) {
      queryString +=
          (first ? "" : "&")
              + URLEncoder.encode(parameter.getKey(), "UTF-8")
              + "="
              + URLEncoder.encode(parameter.getValue(), "UTF-8").replace("+", "%20");
      first = false;
    }

    HTTPRequest request = new HTTPRequest();
    request.setMethod(HttpMethods.PUT);
    request.setURL(this.getEndpoint() + "activities/state" + queryString);
    request.setRequestContent(new ByteArrayBuffer(state.getContents()));

    // TODO: need to set the 'updated' property based on header
    HTTPResponse response = this.sendRequest(request);
    int status = response.getStatus();

    if (status == 204) {
      return;
    }
    throw new UnexpectedHTTPResponse(response);
  }
示例#17
0
 @Override
 protected boolean doExecute(StateContext stateContext, State state) {
   stateContext.setAttribute("SelfSuccess" + state.getId(), true);
   return true;
 }
示例#18
0
  /**
   * Basic Framework implicitely also processes, i'm not sure if we should require any framework to
   * do that (perhaps we could say, that the render method must process, if that is necessary, and
   * not yet done).
   */
  @Override
  public void render(
      Renderer renderer,
      Parameters blockParameters,
      Parameters frameworkParameters,
      Writer w,
      WindowState windowState)
      throws FrameworkException {
    ServletRequest request = frameworkParameters.get(Parameter.REQUEST);
    if (request == null) {
      throw new IllegalArgumentException("No request object given");
    }

    State state = State.getState(request);
    if (state
        .isRendering()) { // mm:component used during rending of a component, that's fine, but use a
                          // new State.
      state = new State(request);
      log.debug("Alreadying rendering, taking a new state for sub-block-rendering: " + state);
    }

    log.debug("Rendering " + renderer.getBlock() + " " + renderer);
    Object prevHints = request.getAttribute(RenderHints.KEY);
    try {

      request.setAttribute(COMPONENT_CLASS_KEY, getComponentClass());
      request.setAttribute(COMPONENT_CURRENTUSER_KEY, getUserNode(frameworkParameters));

      Renderer actualRenderer = state.startBlock(frameworkParameters, renderer);
      if (!actualRenderer.equals(renderer)) {
        Parameters newBlockParameters = actualRenderer.getBlock().createParameters();
        newBlockParameters.setAllIfDefined(blockParameters);
        blockParameters = newBlockParameters;
      }
      state.setAction(request.getParameter(ACTION.getName()));
      if (state.needsProcess()) {
        log.service("Performing action on " + actualRenderer.getBlock());
        Processor processor = actualRenderer.getBlock().getProcessor();
        state.process(processor);
        log.service("Processing " + actualRenderer.getBlock() + " " + processor);
        setBlockParametersForProcess(state, blockParameters);
        processor.process(blockParameters);
        state.endProcess();
      }

      state.render(actualRenderer);

      setBlockParametersForRender(state, blockParameters);

      RenderHints hints =
          new RenderHints(
              actualRenderer,
              windowState,
              state.getId(),
              getComponentClass(),
              RenderHints.Mode.NORMAL);
      request.setAttribute(RenderHints.KEY, hints);
      actualRenderer.render(blockParameters, w, hints);
      request.setAttribute("org.mmbase.framework.hints", hints);
    } catch (FrameworkException fe) {
      log.debug(fe);
      URI uri = renderer.getUri();
      Renderer error =
          new ErrorRenderer(
              renderer.getType(),
              renderer.getBlock(),
              (uri != null) ? uri.toString() : null,
              500,
              fe);
      RenderHints hints =
          new RenderHints(
              error, windowState, state.getId(), getComponentClass(), RenderHints.Mode.NORMAL);
      error.render(blockParameters, w, hints);
    } finally {
      request.setAttribute(RenderHints.KEY, prevHints);
      state.endBlock();
    }
  }
示例#19
0
 protected String getPrefix(final State state) {
   // return "_" + renderer.getBlock().getComponent().getName() + "_" +
   // renderer.getBlock().getName() + "_" + count + "_";
   return state.getId() + ":";
 }
示例#20
0
 public void testCouldNotHandleException() {
   FlowExecutionException e = new FlowExecutionException(flow.getId(), state.getId(), "Whatev");
   MockRequestControlContext context = new MockRequestControlContext(flow);
   assertFalse(state.handleException(e, context));
 }
示例#21
0
  /** Immediately refreshes all types using the backing database. */
  public synchronized void refreshTypes() {
    bootstrapOnce.ensure();

    Database database = getDatabase();
    try {

      TypesCache temporaryTypes = temporaryTypesLocal.get();
      if (temporaryTypes == null) {
        temporaryTypes = new TypesCache();
        temporaryTypesLocal.set(temporaryTypes);
      }

      List<ObjectType> types = Query.from(ObjectType.class).using(database).selectAll();
      int typesSize = types.size();
      LOGGER.info("Loading [{}] types from [{}]", typesSize, database.getName());

      // Load all types from the database first.
      for (ObjectType type : types) {
        type.getFields().size(); // Pre-fetch.
        temporaryTypes.add(type);
      }

      if (initializeClasses) {

        // Make sure that the root type exists.
        ObjectType rootType = getRootType();
        State rootTypeState;

        if (rootType != null) {
          rootTypeState = rootType.getState();

        } else {
          rootType = new ObjectType();
          rootTypeState = rootType.getState();
          rootTypeState.setDatabase(database);
        }

        Map<String, Object> rootTypeOriginals = rootTypeState.getSimpleValues();
        UUID rootTypeId = rootTypeState.getId();
        rootTypeState.setTypeId(rootTypeId);
        rootTypeState.clear();
        rootType.setObjectClassName(ObjectType.class.getName());
        rootType.initialize();
        temporaryTypes.add(rootType);

        try {
          database.beginWrites();

          // Make the new root type available to other types.
          temporaryTypes.add(rootType);
          if (rootTypeState.isNew()) {
            State globals = getGlobals();
            globals.put(ROOT_TYPE_FIELD, rootType);
            globals.save();

          } else if (!rootTypeState.getSimpleValues().equals(rootTypeOriginals)) {
            temporaryTypes.changed.add(rootTypeId);
          }

          Set<Class<? extends Recordable>> objectClasses =
              ClassFinder.findClasses(Recordable.class);

          for (Iterator<Class<? extends Recordable>> i = objectClasses.iterator(); i.hasNext(); ) {
            Class<? extends Recordable> objectClass = i.next();

            try {
              if (objectClass.isAnonymousClass()
                  || Substitution.class.isAssignableFrom(objectClass)) {
                i.remove();
              }

            } catch (IncompatibleClassChangeError error) {
              i.remove();
            }
          }

          Set<Class<?>> globalModifications = new HashSet<Class<?>>();
          Map<ObjectType, List<Class<?>>> typeModifications =
              new HashMap<ObjectType, List<Class<?>>>();

          // Make sure all types are accessible to the rest of the
          // system as soon as possible, so that references can be
          // resolved properly later.
          for (Class<?> objectClass : objectClasses) {
            ObjectType type = getTypeByClass(objectClass);

            if (type == null) {
              type = new ObjectType();
              type.getState().setDatabase(database);

            } else {
              type.getState().clear();
            }

            type.setObjectClassName(objectClass.getName());
            typeModifications.put(type, new ArrayList<Class<?>>());
            temporaryTypes.add(type);
          }

          // Separate out all modifications from regular types.
          for (Class<?> objectClass : objectClasses) {
            if (!Modification.class.isAssignableFrom(objectClass)) {
              continue;
            }

            @SuppressWarnings("unchecked")
            Set<Class<?>> modifiedClasses =
                Modification.Static.getModifiedClasses(
                    (Class<? extends Modification<?>>) objectClass);
            if (modifiedClasses.contains(Object.class)) {
              globalModifications.add(objectClass);
              continue;
            }

            for (Class<?> modifiedClass : modifiedClasses) {
              List<Class<?>> assignableClasses = new ArrayList<Class<?>>();

              for (Class<?> c : objectClasses) {
                if (modifiedClass.isAssignableFrom(c)) {
                  assignableClasses.add(c);
                }
              }

              for (Class<?> assignableClass : assignableClasses) {
                ObjectType type = getTypeByClass(assignableClass);

                if (type != null) {
                  List<Class<?>> modifications = typeModifications.get(type);
                  if (modifications == null) {
                    modifications = new ArrayList<Class<?>>();
                    typeModifications.put(type, modifications);
                  }
                  modifications.add(objectClass);
                }
              }
            }
          }

          // Apply global modifications.
          for (Class<?> modification : globalModifications) {
            ObjectType.modifyAll(database, modification);
          }

          // Initialize all types.
          List<Class<?>> rootTypeModifications = typeModifications.remove(rootType);
          initializeAndModify(temporaryTypes, rootType, rootTypeModifications);

          if (rootTypeModifications != null) {
            for (Class<?> modification : rootTypeModifications) {
              ObjectType t = getTypeByClass(modification);
              initializeAndModify(temporaryTypes, t, typeModifications.remove(t));
            }
          }

          ObjectType fieldType = getTypeByClass(ObjectField.class);
          List<Class<?>> fieldModifications = typeModifications.remove(fieldType);
          initializeAndModify(temporaryTypes, fieldType, fieldModifications);

          if (fieldModifications != null) {
            for (Class<?> modification : fieldModifications) {
              ObjectType t = getTypeByClass(modification);
              initializeAndModify(temporaryTypes, t, typeModifications.remove(t));
            }
          }

          for (Map.Entry<ObjectType, List<Class<?>>> entry : typeModifications.entrySet()) {
            initializeAndModify(temporaryTypes, entry.getKey(), entry.getValue());
          }

          database.commitWrites();

        } finally {
          database.endWrites();
        }
      }

      // Merge temporary types into new permanent types.
      TypesCache newPermanentTypes = new TypesCache();

      for (ObjectType type : permanentTypes.byId.values()) {
        newPermanentTypes.add(type);
      }

      for (ObjectType type : temporaryTypes.byId.values()) {
        newPermanentTypes.add(type);
      }

      newPermanentTypes.changed.addAll(temporaryTypes.changed);
      newPermanentTypes.changed.addAll(permanentTypes.changed);

      // If any types changed, clear all types' extras.
      if (!temporaryTypes.changed.isEmpty()) {
        for (ObjectType type : newPermanentTypes.byId.values()) {
          type.getState().getExtras().clear();
        }
      }

      permanentTypes = newPermanentTypes;
      lastTypesUpdate = new Date();

    } finally {
      temporaryTypesLocal.remove();
    }

    ObjectType singletonType = getTypeByClass(Singleton.class);

    if (singletonType != null) {
      for (ObjectType type : singletonType.findConcreteTypes()) {
        if (!Query.fromType(type).where("_type = ?", type).master().noCache().hasMoreThan(0)) {
          try {
            State.getInstance(type.createObject(null)).saveImmediately();
          } catch (Exception error) {
            LOGGER.warn(String.format("Can't save [%s] singleton!", type.getLabel()), error);
          }
        }
      }
    }

    for (ObjectType type : getTypes()) {
      Class<?> objectClass = type.getObjectClass();
      if (objectClass != null) {
        TypePostProcessorClasses tppcAnnotation =
            objectClass.getAnnotation(TypePostProcessorClasses.class);
        if (tppcAnnotation != null) {
          for (Class<? extends ObjectType.PostProcessor> processorClass : tppcAnnotation.value()) {
            ObjectType.PostProcessor processor =
                (ObjectType.PostProcessor) TYPE_POST_PROCESSORS.getUnchecked(processorClass);
            processor.process(type);
          }
        }
      }
    }
  }
  @Override
  public List<StateCity> getStateCityList(String customerUUId) {

    // Create test object
    //        StateCity scv;
    StateCity scv;
    List<StateCity> scvl = new ArrayList<StateCity>();

    //        StateCityList scvl = new StateCityList();
    int id = 1;

    // Kansas
    scv = new StateCityView();
    City city = new City();
    State state = new State();
    state.setId(1);
    state.setStateName("OH");
    city.setId(id);
    city.setCityName("COLUMBUS");
    city.setStateId(state.getId());
    city.setSummary(
        "Columbus, Ohio has a generally strong and diverse economy based on education, "
            + "insurance, banking, fashion, defense, aviation, food, logistics, steel, energy, medical research, health care, "
            + "hospitality, retail, and technology. Overall, it was ranked as one of the top 10 best big cities in the country in 2010, "
            + "according to Relocate America, a real estate research firm.  MarketWatch ranked Columbus and its metro area as the No. 7 best place in the country to operate a business in 2008.  In 2007, the cityId was ranked No. 3 in the United States by fDi magazine for “Cities of the Future”, and No. 4 for most business-friendly in the country. Columbus was ranked as the seventh strongest economy in the United States in 2006, and the best in Ohio, according to Policom Corp. In 2011, the Columbus metropolitan area’s GDP was $94.7 billion, "
            + "up from $90 billion in 2009, up from $85.5 billion in 2006, $75.43 billion in 2005, and $69.98 billion in 2001.");
    city.setImageUrl("columbus.jpg");
    scv.setCity(city);
    scvl.add(scv);

    scv = new StateCityView();
    state = new State();
    state.setId(2);
    state.setStateName("MO");
    city = new City();
    city.setId(id);
    city.setCityName(String.format("KANSAS CITY"));
    city.setStateId(state.getId());
    city.setSummary(
        "Kansas City, Missouri may seem to be well deserving of its “cow-town” reputation.  "
            + "After all, historically speaking, Kansas City grew up out of the prosperity created by the local "
            + "cattle markets strategically located at the crossroads of key national rail lines.  However, any local will tell you that it would be a mistake to reduce Kansas City to a stagnant creature of its historical origins.");
    city.setImageUrl("kansascvity.png");
    scv.setCity(city);
    scvl.add(scv);

    scv = new StateCityView();
    state = new State();
    state.setId(2);
    state.setStateName("IN");
    city = new City();
    city.setId(id);
    city.setCityName(String.format("INDIANAPOLIS"));
    city.setStateId(state.getId());
    city.setSummary(
        "Indianapolis, Indiana is the eleventh largest cityId in the United States, and it is by-far one of our country’s most livable big cities.  Indianapolis is a cityId located in the Great Lakes region of the United States. "
            + "Indianapolis is the capital of the US stateName of Indiana, and one of the fastest growing metropolitan areas in the United States.");
    city.setImageUrl("indy.png");
    scvl.add(scv);

    //        scv = new StateCityView();
    //        scv.setCityId(id);
    //        scv.setCity(String.format("INDIANAPOLIS"));
    //        scv.setState("IN");
    //        scv.setSummary("Indianapolis, Indiana is the eleventh largest cityId in the United
    // States, and it is by-far one of our country’s most livable big cities.  Indianapolis is a
    // cityId located in the Great Lakes region of the United States. " +
    //                "Indianapolis is the capital of the US stateName of Indiana, and one of the
    // fastest growing metropolitan areas in the United States.");
    //        scv.setImageUrl("kansascvity.png");
    //        scvl.add(scv);
    //
    //        scv = new StateCityView();
    //        scv.setCityId(id);
    //        scv.setCity(String.format("TOLEDO"));
    //        scv.setState("OH");
    //
    //        scv.setImageUrl("toledo.jpg");
    //        scv.setSummary("Toledo, Ohio  is the fourth most populous cityId in the U.S. stateName
    // of Ohio and is the county seat of Lucas County. Toledo is in northwest Ohio, located on the
    // Maumee River on the western end of Lake Erie, and borders the State of Michigan.  It is one
    // of the most productive Ports on the Great Lakes/St. Lawrence Seaway, and is a designated
    // Foreign Trade Zone area. The Port of Toledo handles coal, ore, general cargo, and ship
    // repairs, as well as having storage for over 22 million bushels of grain for export. The
    // diverse architecture of Toledo rivals larger cities like Chicago. " +
    //                "It is also home to Libby Glass, the founders of which had a tremendously
    // positive influence on the amenities of the City.");
    //        scvl.add(scv);
    //
    //        scv = new StateCityView();
    //        scv.setCityId(id);
    //        scv.setCity(String.format("BIRMINGHAM"));
    //        scv.setState("AL");
    //        scv.setImageUrl("birmingham.png");
    //        scv.setSummary("Birmingham, Alabama is a municipal corporation under the laws of the
    // State of Alabama. " +
    //                "Birmingham is the largest cityId in the stateName with a population currently
    // estimated at 242,820, and a metro population of 1,079,089.");
    //        scvl.add(scv);

    return scvl;
  }