/**
  * Load fixtures and send it to the {@link SolrServer}.
  *
  * @param server The solr server.
  * @param core The core's name.
  * @param fixturesDir The fixtures directory.
  * @param async True for using a thread.
  */
 private static void populate(
     final SolrServer server, final String core, final File fixturesDir, final boolean async) {
   final Collection<File> xmlFiles = FileUtils.listFiles(fixturesDir, new String[] {"xml"}, true);
   if (xmlFiles.size() > 0) {
     Runnable post =
         new Runnable() {
           @Override
           public void run() {
             try {
               for (File xmlFile : xmlFiles) {
                 logger.info("[{}]: sending: {}...", core, xmlFile);
                 // Ensure it's in UTF-8 encoding
                 Reader reader = new InputStreamReader(new FileInputStream(xmlFile), "UTF-8");
                 String body = IOUtils.toString(reader);
                 SolrRequest request = new DirectXmlRequest("/update", body);
                 /** Post the document to the Index */
                 request.process(server);
                 IOUtils.closeQuietly(reader);
               }
               // Commit the changes
               server.commit();
             } catch (Exception ex) {
               logger.error("Unable to initialize data", ex);
             }
           }
         };
     if (async) {
       Thread thread = new Thread(post, core + "-postData");
       thread.setDaemon(true);
       thread.start();
     } else {
       post.run();
     }
   }
 }
  private void listAll() {
    ViewGroup root = mList;
    root.removeAllViews();

    // 列出所有已经安装的插件
    Collection<PluginDescriptor> plugins = PluginLoader.getPlugins();
    Iterator<PluginDescriptor> itr = plugins.iterator();
    while (itr.hasNext()) {
      final PluginDescriptor pluginDescriptor = itr.next();
      Button button = new Button(this);
      button.setPadding(10, 10, 10, 10);
      button.setText("插件id:" + pluginDescriptor.getPackageName() + ",点击查看");
      button.setOnClickListener(
          new View.OnClickListener() {

            @Override
            public void onClick(View v) {
              Intent intent = new Intent(PluginListActivity.this, PluginDetailActivity.class);
              intent.putExtra("plugin_id", pluginDescriptor.getPackageName());
              startActivity(intent);
            }
          });

      LayoutParams layoutParam =
          new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
      layoutParam.topMargin = 10;
      layoutParam.bottomMargin = 10;
      layoutParam.gravity = Gravity.LEFT;
      root.addView(button, layoutParam);
    }
  }
  @Test
  public void shouldGetVdbConditions() throws Exception {
    loadVdbs();

    // get
    Properties settings =
        _uriBuilder.createSettings(
            SettingNames.VDB_NAME, TestUtilities.ALL_ELEMENTS_EXAMPLE_VDB_NAME);
    _uriBuilder.addSetting(settings, SettingNames.DATA_ROLE_ID, "roleOne");
    _uriBuilder.addSetting(settings, SettingNames.PERMISSION_ID, "myTable.T2");
    URI uri = _uriBuilder.buildVdbPermissionUri(LinkType.CONDITIONS, settings);
    this.response = request(uri).get();
    final String entity = this.response.readEntity(String.class);
    assertThat(entity, is(notNullValue()));

    // System.out.println("Response:\n" + entity);

    RestVdbCondition[] conditions =
        KomodoJsonMarshaller.unmarshallArray(entity, RestVdbCondition[].class);
    assertNotNull(conditions);
    assertEquals(1, conditions.length);

    RestVdbCondition condition = conditions[0];
    assertEquals("col1 = user()", condition.getName());
    assertFalse(condition.isConstraint());

    Collection<RestLink> links = condition.getLinks();
    assertEquals(3, links.size());
  }
Example #4
1
  @Test
  public void testChildrenRIMsDifferentEntity() {
    ResourceState initial = new ResourceState("Note", "initial", mockActions(), "/note/{id}");
    ResourceState comment =
        new ResourceState("Comment", "draft", mockActions(), "/comments/{noteid}");

    // example uri linkage uses 'id' from Note entity to transition to 'noteid' of comments resource
    Map<String, String> uriLinkageMap = new HashMap<String, String>();
    uriLinkageMap.put("noteid", "id");
    // create comment for note
    initial.addTransition(
        new Transition.Builder()
            .method("PUT")
            .target(comment)
            .uriParameters(uriLinkageMap)
            .build());
    // update comment
    comment.addTransition(new Transition.Builder().method("PUT").target(comment).build());

    // supply a transformer to check that this is copied into child resource
    BeanTransformer transformer = new BeanTransformer();

    ResourceStateMachine stateMachine = new ResourceStateMachine(initial, transformer);
    HTTPHypermediaRIM parent =
        new HTTPHypermediaRIM(mockCommandController(), stateMachine, createMockMetadata());
    Collection<ResourceInteractionModel> resources = parent.getChildren();
    assertEquals(1, resources.size());
    assertEquals(comment.getPath(), resources.iterator().next().getResourcePath());
    assertEquals(
        transformer,
        ((HTTPHypermediaRIM) resources.iterator().next()).getHypermediaEngine().getTransformer());
  }
Example #5
1
  public void turlRetrievalFailed(
      String surl, String reason, String remoteRequestId, String remoteFileId) {
    synchronized (remoteSurlToFileReqIds) {
      Collection<Long> fileRequestSet = remoteSurlToFileReqIds.get(surl);
      if (fileRequestSet == null || fileRequestSet.isEmpty()) {
        LOG.error("turlArrived for unknown SURL = " + surl);
        return;
      }
      for (long id : fileRequestSet) {
        CopyFileRequest cfr = getFileRequest(id);

        try {
          String type = isSourceSrm() && !isSourceLocal() ? "source" : "destination";
          String error = "retrieval of " + type + " TURL failed with error " + reason;
          LOG.error(error);
          cfr.setState(State.FAILED, error);
        } catch (IllegalStateTransition ist) {
          LOG.error("Illegal State Transition : " + ist.getMessage());
        }
        cfr.saveJob();

        remoteSurlToFileReqIds.remove(surl, id);
      }
    }
    remoteFileRequestDone(surl, remoteRequestId, remoteFileId);
  }
Example #6
1
  public SelectMany05Bean() {

    HobbitBean[] hobbits = {
      new HobbitBean("Bilbo", "Ring Finder"),
      new HobbitBean("Frodo", "Ring Bearer"),
      new HobbitBean("Merry", "Trouble Maker"),
      new HobbitBean("Pippin", "Trouble Maker")
    };

    Set<SelectItem> items = new LinkedHashSet<SelectItem>();
    for (HobbitBean hobbit : hobbits) {
      items.add(new SelectItem(hobbit.getName()));
    }
    hobbitCollection = new TreeSet<HobbitBean>();
    hobbitCollection.addAll(Arrays.asList(hobbits));
    possibleValues = Collections.unmodifiableSet(items);
    initialSortedSetValues = new TreeSet<String>(Collections.reverseOrder());
    initialSortedSetValues.add("Pippin");
    initialSortedSetValues.add("Frodo");
    initialCollectionValues = new LinkedHashSet<String>(2);
    initialCollectionValues.add("Bilbo");
    initialCollectionValues.add("Merry");
    initialSetValues = new CopyOnWriteArraySet<String>(); // not Cloneable
    initialSetValues.add("Frodo");
    initialListValues = new Vector<String>();
    initialListValues.add("Bilbo");
    initialListValues.add("Pippin");
    initialListValues.add("Merry");
    hobbitDataModel =
        new ListDataModel<HobbitBean>(new ArrayList<HobbitBean>(Arrays.asList(hobbits)));
  }
Example #7
1
  public double getNormalizedActivatedRate() {
    LoadUnloadEdge labeledEdge = (LoadUnloadEdge) this.getEdge();

    Node source = labeledEdge.getA();
    PacketStyleTransportSystem transSystem =
        (PacketStyleTransportSystem)
            ((labeledEdge.isLoadingEdge()) ? (labeledEdge.getB()) : (labeledEdge.getA()));

    Collection<NodeLabel> lbls = source.getLabels();
    double sourcePop = 0;

    // Get the population size of the source node
    for (Iterator<NodeLabel> it = lbls.iterator(); it.hasNext(); ) {
      NodeLabel lbl = it.next();
      if (lbl instanceof PopulationLabel) {
        sourcePop = ((PopulationLabelValue) ((PopulationLabel) lbl).getCurrentValue()).getCount();
        break;
      }
    }
    assert sourcePop > 0;

    lbls = transSystem.getLabels();
    double transCapacity = 0;

    // Get the capacity of the packet transport label
    for (Iterator<NodeLabel> it = lbls.iterator(); it.hasNext(); ) {
      NodeLabel lbl = it.next();
      if (lbl instanceof PacketTransportLabel) {
        transCapacity = ((PacketTransportLabel) lbl).getCurrentValue().getCapacity();
        break;
      }
    }

    return getActivatedRate() * transCapacity / sourcePop;
  }
Example #8
1
  private void displayFriendCount() {
    Collection<GraphUser> selectedFriends = HushApp.getSelectedUsers();

    if (selectedFriends == null || selectedFriends.size() == 0) {
      return;
    }
    numFriendsSelected = selectedFriends.size();

    Chatter chatter;
    final ArrayList<String> fbChatterIds = new ArrayList<String>();
    Collection<GraphUser> selection = HushApp.getSelectedUsers();
    for (GraphUser user : selection) {
      chatter = new Chatter(user.getId(), user.getName());
      fbChatterIds.add(user.getId());
      chatter.saveToParse();
      chat.addChatter(chatter);
    }

    // Send a push notification
    chat.saveToParseWithPush(
        this,
        HushPushNotifReceiver.PushType.NEW_CHAT.toString(),
        getString(R.string.new_chat_push_notif_message),
        fbChatterIds);
  }
 public void setSwingDataCollection(Collection<ICFSecurityISOCountryObj> value) {
   final String S_ProcName = "setSwingDataCollection";
   swingDataCollection = value;
   if (swingDataCollection == null) {
     arrayOfISOCountry = new ICFSecurityISOCountryObj[0];
   } else {
     int len = value.size();
     arrayOfISOCountry = new ICFSecurityISOCountryObj[len];
     Iterator<ICFSecurityISOCountryObj> iter = swingDataCollection.iterator();
     int idx = 0;
     while (iter.hasNext() && (idx < len)) {
       arrayOfISOCountry[idx++] = iter.next();
     }
     if (idx < len) {
       throw CFLib.getDefaultExceptionFactory()
           .newRuntimeException(
               getClass(),
               S_ProcName,
               "Collection iterator did not fully populate the array copy");
     }
     if (iter.hasNext()) {
       throw CFLib.getDefaultExceptionFactory()
           .newRuntimeException(
               getClass(),
               S_ProcName,
               "Collection iterator had left over items when done populating array copy");
     }
     Arrays.sort(arrayOfISOCountry, compareISOCountryByQualName);
   }
   PickerTableModel tblDataModel = getDataModel();
   if (tblDataModel != null) {
     tblDataModel.fireTableDataChanged();
   }
 }
 /**
  * This constructs an instance.
  * <!-- begin-user-doc -->
  * <!-- end-user-doc -->
  *
  * @generated
  */
 public TypeconfigurationItemProviderAdapterFactory() {
   supportedTypes.add(IEditingDomainItemProvider.class);
   supportedTypes.add(IStructuredItemContentProvider.class);
   supportedTypes.add(ITreeItemContentProvider.class);
   supportedTypes.add(IItemLabelProvider.class);
   supportedTypes.add(IItemPropertySource.class);
 }
    @Override
    public void join(
        IntPair rec1, Tuple2<Integer, String> rec2, Collector<Tuple2<Integer, String>> out)
        throws Exception {
      final int k = rec1.getKey();
      final int v = rec1.getValue();

      final Integer key = rec2.f0;
      final String value = rec2.f1;

      Assert.assertTrue("Key does not match for matching IntPair Tuple combination.", k == key);

      Collection<TupleIntPairMatch> matches = this.toRemoveFrom.get(key);
      if (matches == null) {
        Assert.fail("Match " + key + " - " + v + ":" + value + " is unexpected.");
      }

      Assert.assertTrue(
          "Produced match was not contained: " + key + " - " + v + ":" + value,
          matches.remove(new TupleIntPairMatch(v, value)));

      if (matches.isEmpty()) {
        this.toRemoveFrom.remove(key);
      }
    }
  protected static Object evaluateExpression(
      ActivityNode self, String body, Iterable<? extends InputPin> pins, ActivityInstance context) {
    ExecutionEnvironment env = context.getEnv();

    Object contextValue = context.getOclContext();
    Collection<ContextExtensionPin> extensions = new Vector<ContextExtensionPin>();
    for (InputPin pin : pins) {
      if (pin instanceof ContextExtensionPin) {
        extensions.add((ContextExtensionPin) pin);
      } else if (pin instanceof ContextPin) {
        contextValue = ((PinInstance) context.getPlaces(pin)).getValue();
      } else {
        throw new SemanticException("no non context input pins for expressions allowed.");
      }
    }

    for (ContextExtensionPin pin : extensions) {
      Object contextExtensionValue = ((PinInstance) context.getPlaces(pin)).getValue();
      env.addAdditionalContextAttribute(
          pin.getExtensionName(),
          contextExtensionValue,
          OpaqueActionCustom.getTypeForObject(contextExtensionValue),
          OpaqueActionCustom.getTypeForObject(contextValue));
    }
    Object result =
        env.evaluateInvariant(
            body, OpaqueActionCustom.getTypeForObject(contextValue), contextValue);
    for (ContextExtensionPin pin : extensions) {
      env.removeAdditionalContextAttribute(
          pin.getExtensionName(), OpaqueActionCustom.getTypeForObject(contextValue));
    }
    return result;
  }
 /**
  * Returns the currently open editors for the given type in order of most recently focused
  *
  * @throws MapperException
  */
 public Collection<ResourceEditor> getOpenEditors(ResourceType type) throws MapperException {
   Collection<ResourceEditor> editors = new ArrayList<ResourceEditor>();
   for (ResourceEditor editor : openEditors.values()) {
     if (type == ResourceType.forId(getResourceForEditor(editor).getType())) editors.add(editor);
   }
   return editors;
 }
 @Nullable
 private static PyGenericType getGenericType(
     @NotNull PsiElement element, @NotNull Context context) {
   if (element instanceof PyCallExpression) {
     final PyCallExpression assignedCall = (PyCallExpression) element;
     final PyExpression callee = assignedCall.getCallee();
     if (callee != null) {
       final Collection<String> calleeQNames =
           resolveToQualifiedNames(callee, context.getTypeContext());
       if (calleeQNames.contains("typing.TypeVar")) {
         final PyExpression[] arguments = assignedCall.getArguments();
         if (arguments.length > 0) {
           final PyExpression firstArgument = arguments[0];
           if (firstArgument instanceof PyStringLiteralExpression) {
             final String name = ((PyStringLiteralExpression) firstArgument).getStringValue();
             if (name != null) {
               return new PyGenericType(name, getGenericTypeBound(arguments, context));
             }
           }
         }
       }
     }
   }
   return null;
 }
 @Nullable
 private static PyType getCallableType(@NotNull PsiElement resolved, @NotNull Context context) {
   if (resolved instanceof PySubscriptionExpression) {
     final PySubscriptionExpression subscriptionExpr = (PySubscriptionExpression) resolved;
     final PyExpression operand = subscriptionExpr.getOperand();
     final Collection<String> operandNames =
         resolveToQualifiedNames(operand, context.getTypeContext());
     if (operandNames.contains("typing.Callable")) {
       final PyExpression indexExpr = subscriptionExpr.getIndexExpression();
       if (indexExpr instanceof PyTupleExpression) {
         final PyTupleExpression tupleExpr = (PyTupleExpression) indexExpr;
         final PyExpression[] elements = tupleExpr.getElements();
         if (elements.length == 2) {
           final PyExpression parametersExpr = elements[0];
           final PyExpression returnTypeExpr = elements[1];
           if (parametersExpr instanceof PyListLiteralExpression) {
             final List<PyCallableParameter> parameters = new ArrayList<>();
             final PyListLiteralExpression listExpr = (PyListLiteralExpression) parametersExpr;
             for (PyExpression argExpr : listExpr.getElements()) {
               parameters.add(new PyCallableParameterImpl(null, getType(argExpr, context)));
             }
             final PyType returnType = getType(returnTypeExpr, context);
             return new PyCallableTypeImpl(parameters, returnType);
           }
           if (isEllipsis(parametersExpr)) {
             return new PyCallableTypeImpl(null, getType(returnTypeExpr, context));
           }
         }
       }
     }
   }
   return null;
 }
  protected List<SelectItem> readExecutionYearItems() {
    final List<SelectItem> result = new ArrayList<SelectItem>();

    final Collection<ExecutionDegree> executionDegrees =
        getDegreeCurricularPlan().getExecutionDegreesSet();

    if (executionDegrees.isEmpty()) {
      final ExecutionYear executionYear =
          getDegreeCurricularPlan().getRoot().getMinimumExecutionPeriod().getExecutionYear();
      result.add(new SelectItem(executionYear.getExternalId(), executionYear.getYear()));
      return result;
    }

    for (ExecutionDegree executionDegree : executionDegrees) {
      result.add(
          new SelectItem(
              executionDegree.getExecutionYear().getExternalId(),
              executionDegree.getExecutionYear().getYear()));
    }

    if (getExecutionYearID() == null) {
      setExecutionYearID(
          getDegreeCurricularPlan()
              .getMostRecentExecutionDegree()
              .getExecutionYear()
              .getExternalId());
    }

    return result;
  }
Example #17
0
  /**
   * Converts WorkingUser to Actors
   *
   * @return an object implementing Actor interface
   */
  public Collection<Actor> toActors() throws WorkflowException {
    State state = processInstance.getProcessModel().getState(this.state);
    Collection<Actor> actors = new ArrayList<>();

    // first add user by id
    if (this.getUserId() != null) {
      User user = WorkflowHub.getUserManager().getUser(this.getUserId());
      actors.add(new ActorImpl(user, role, state));
    }

    // then add users by group or role
    if (StringUtil.isDefined(getGroupId())) {
      User[] users = WorkflowHub.getUserManager().getUsersInGroup(getGroupId());
      for (User anUser : users) {
        actors.add(new ActorImpl(anUser, role, state));
      }
    } else {
      // then add users by role
      if (this.usersRole != null) {
        User[] users =
            WorkflowHub.getUserManager().getUsersInRole(usersRole, processInstance.getModelId());
        for (User anUser : users) {
          actors.add(new ActorImpl(anUser, role, state));
        }
      }
    }

    return actors;
  }
Example #18
0
  @Test
  public void shouldGetVdbMask() throws Exception {
    loadVdbs();

    // get
    Properties settings =
        _uriBuilder.createSettings(
            SettingNames.VDB_NAME, TestUtilities.ALL_ELEMENTS_EXAMPLE_VDB_NAME);
    _uriBuilder.addSetting(settings, SettingNames.DATA_ROLE_ID, "roleOne");
    _uriBuilder.addSetting(settings, SettingNames.PERMISSION_ID, "myTable.T2.col1");
    _uriBuilder.addSetting(settings, SettingNames.PERMISSION_CHILD_TYPE, LinkType.MASKS.uriName());
    _uriBuilder.addSetting(settings, SettingNames.PERMISSION_CHILD_ID, "col2");
    URI uri = _uriBuilder.buildVdbPermissionChildUri(LinkType.SELF, settings);
    this.response = request(uri).get();
    final String entity = this.response.readEntity(String.class);
    assertThat(entity, is(notNullValue()));

    // System.out.println("Response:\n" + entity);

    RestVdbMask mask = KomodoJsonMarshaller.unmarshall(entity, RestVdbMask.class);
    assertNotNull(mask);

    assertEquals("col2", mask.getName());
    assertEquals("1", mask.getOrder());

    Collection<RestLink> links = mask.getLinks();
    assertEquals(3, links.size());
  }
Example #19
0
  @Override
  public DataModel read() throws DataModelException, TMException, SQLException {
    UserData user = (UserData) datamodel;

    ResultSet rst = null;
    try {
      String sql = READ_USER;
      Collection<SQLValue> bindVars = new ArrayList<SQLValue>();
      if (user.getId() > 0) {
        sql += AND + "`ID` = ? ";
        bindVars.add(SQLValue.Long(user.getId()));
      }
      if (user.getUserName() != null) {
        sql += AND + "`USER_NAME` = ? ";
        bindVars.add(SQLValue.String(user.getUserName()));
      }
      if (user.getPassword() != null) {
        sql += AND + "`PASSWORD` = ? ";
        bindVars.add(SQLValue.String(user.getPassword()));
      }
      logger.debug("QUERY - Loading Address :" + sql);
      rst = executeQuery(sql, bindVars);

      return loadUserVO(user, rst);
    } catch (SQLException sql) {
      logger.error("SQL-Exception", sql);
      throw new TMException("SQL-Exception", sql.getLocalizedMessage());
    } finally {
      close(null, rst);
    }
  }
Example #20
0
 protected InterMineBag createEmployeeList() throws Exception {
   ObjectStoreWriter osw = null;
   try {
     Profile superUser = im.getProfileManager().getSuperuserProfile();
     osw = ObjectStoreWriterFactory.getObjectStoreWriter("osw.unittest");
     Employee e1 = new Employee();
     e1.setName("Employee1");
     Employee e2 = new Employee();
     e2.setName("Employee2");
     Department d1 = new Department();
     d1.setName("department");
     Company company = new CompanyShadow();
     company.setName("company");
     Contractor contractor = new Contractor();
     contractor.setName("contractor");
     osw.store(contractor);
     company.addContractors(contractor);
     osw.store(company);
     d1.setCompany(company);
     osw.store(d1);
     e1.setDepartment(d1);
     e2.setDepartment(d1);
     osw.store(e1);
     osw.store(e2);
     InterMineBag list = superUser.createBag("employeeList", "Employee", "", im.getClassKeys());
     Collection<Integer> ids = new ArrayList<Integer>();
     ids.add(e1.getId());
     ids.add(e2.getId());
     list.addIdsToBag(ids, "Employee");
     return list;
   } finally {
     osw.close();
   }
 }
 @Override
 public boolean addAll(final Collection<? extends E> c) {
   if (c.isEmpty()) {
     return false;
   }
   boolean modified = false;
   if (c instanceof SortedListSet && this.comparator == ((SortedListSet<?>) c).getComparator()) {
     int index = 0;
     for (final Iterator<? extends E> iter = c.iterator(); iter.hasNext(); ) {
       index = addE(index, iter.next());
       if (index >= 0) {
         modified = true;
         index++;
       } else {
         index = -(index + 1);
       }
     }
   } else {
     for (final Iterator<? extends E> iter = c.iterator(); iter.hasNext(); ) {
       if (addE(iter.next()) >= 0) {
         modified = true;
       }
     }
   }
   return modified;
 }
Example #22
0
  /** Test de lecture du fichier d'historique simple */
  @Test
  public void testLectureFichierHistoriqueSimple() {

    construireHistoriqueSimple();

    Collection lesHistoriques = rHistoriqueSimple.getlisteHistoriques();
    Iterator it = lesHistoriques.iterator();
    Historique unHistoriqueLu;
    int nbHisto = 0;
    int nbVert = 0;
    int nbTestsTotaux = 0;
    long tempsExecutionTotal = 0;

    while (it.hasNext()) {

      unHistoriqueLu = (Historique) it.next();
      nbHisto++;

      if (unHistoriqueLu.getEtat().equalsIgnoreCase(Historique.ETAT_VERT)) nbVert++;

      nbTestsTotaux += unHistoriqueLu.getNombreTests();
      tempsExecutionTotal += unHistoriqueLu.getVitesse();
    }

    assertTrue(nbHisto == 3);
    assertTrue(nbVert == 2);
    assertTrue(nbTestsTotaux == 60); // 10+20+30
    assertTrue(tempsExecutionTotal == 360000); // 1 + 2 + 3 minutes
  }
 @Override
 public Collection<IborIndex> visitSwapDefinition(final SwapDefinition definition) {
   final Collection<IborIndex> indices = new HashSet<>();
   indices.addAll(definition.getFirstLeg().accept(this));
   indices.addAll(definition.getSecondLeg().accept(this));
   return indices;
 }
 /**
  * Get all objects (as representend by their IDs) in the subtree including the objects located
  * directly at this node. Note that objects can occur more than once.
  *
  * @return Iterator of String
  */
 public Collection<Object> getExampleIdsInSubtree() {
   Collection<Object> examples = new LinkedList<Object>();
   for (HierarchicalClusterNode subNode : subNodes) {
     examples.addAll(subNode.getExampleIdsInSubtree());
   }
   return examples;
 }
Example #25
0
  /*
  	@Test
  	public void testBootstrapRIMsCRUD() {
  		String ENTITY_NAME = "NOTE";
  		String resourcePath = "/notes/{id}";
  		ResourceState initial = new ResourceState(ENTITY_NAME, "initial", mockActions(), resourcePath);
  		ResourceState exists = new ResourceState(ENTITY_NAME, "exists", mockActions(), resourcePath);
  		ResourceState deleted = new ResourceState(ENTITY_NAME, "deleted", mockActions(), resourcePath);

  		// create
  		initial.addTransition(new Transition.Builder().method("PUT").target(exists);
  		// update
  		exists.addTransition(new Transition.Builder().method("PUT").target(exists);
  		// delete
  		exists.addTransition("DELETE", deleted);

  		// mock command controller to do nothing
  		NewCommandController cc = mock(NewCommandController.class);
  		when(cc.fetchCommand(anyString(), anyString())).thenReturn(mock(InteractionCommand.class));

  		HTTPHypermediaRIM parent = new HTTPHypermediaRIM(cc, new ResourceStateMachine(initial));
  		verify(cc).fetchCommand("GET", resourcePath);
  		Collection<ResourceInteractionModel> resources = parent.getChildren();
  		assertEquals(0, resources.size());
  		verify(cc, times(1)).fetchCommand("GET", resourcePath);
  		verify(cc, times(1)).fetchCommand("PUT", resourcePath);
  		verify(cc, times(1)).fetchCommand("DELETE", resourcePath);
  	}

  	@Test
  	public void testBootstrapRIMsSubstate() {
  		String ENTITY_NAME = "DraftNote";
  		String resourcePath = "/notes/{id}";
    		ResourceState initial = new ResourceState(ENTITY_NAME, "initial", resourcePath);
  		ResourceState exists = new ResourceState(initial, "exists", "/exists");
  		ResourceState deleted = new ResourceState(exists, "deleted", null);
  		ResourceState draft = new ResourceState(ENTITY_NAME, "draft", "/notes/{id}/draft");
  		ResourceState deletedDraft = new ResourceState(draft, "deleted");

  		// create
  		initial.addTransition(new Transition.Builder().method("PUT").target(exists);
  		// create draft
  		initial.addTransition(new Transition.Builder().method("PUT").target(draft);
  		// updated draft
  		draft.addTransition(new Transition.Builder().method("PUT").target(draft);
  		// publish
  		draft.addTransition(new Transition.Builder().method("PUT").target(exists);
  		// delete draft
  		draft.addTransition("DELETE", deletedDraft);
  		// delete published
  		exists.addTransition("DELETE", deleted);

  		// mock command controller to do nothing
  		NewCommandController cc = mock(NewCommandController.class);
  		when(cc.fetchCommand(anyString(), anyString())).thenReturn(mock(InteractionCommand.class));

  		ResourceStateMachine stateMachine = new ResourceStateMachine(initial);
  		HTTPHypermediaRIM parent = new HTTPHypermediaRIM(cc, stateMachine);
  		verify(cc).fetchCommand("GET", "/notes/{id}");
  		Collection<ResourceInteractionModel> resources = parent.getChildren();
  		assertEquals(2, resources.size());
  		assertEquals(draft, resources.iterator().next().getCurrentState());
  		verify(cc, times(1)).fetchCommand("GET", "/notes/{id}/exists");
  		verify(cc).fetchCommand("DELETE", "/notes/{id}/exists");
  		verify(cc).fetchCommand("PUT", "/notes/{id}/exists");
  		verify(cc, times(1)).fetchCommand("GET", "/notes/{id}/draft");
  		verify(cc).fetchCommand("DELETE", "/notes/{id}/draft");
  		verify(cc).fetchCommand("PUT", "/notes/{id}/draft");
  	}

  	@Test
  	public void testBootstrapRIMsMultipleSubstates() {
  		String ENTITY_NAME = "PublishNote";
  		String resourcePath = "/notes/{id}";
    		ResourceState initial = new ResourceState(ENTITY_NAME, "initial", resourcePath);
  		ResourceState published = new ResourceState(ENTITY_NAME, "published", "/notes/{id}/published");
  		ResourceState publishedDeleted = new ResourceState(published, "publishedDeleted", null);
  		ResourceState draft = new ResourceState(ENTITY_NAME, "draft", "/notes/{id}/draft");
  		ResourceState deletedDraft = new ResourceState(draft, "draftDeleted");

  		// create draft
  		initial.addTransition(new Transition.Builder().method("PUT").target(draft);
  		// updated draft
  		draft.addTransition(new Transition.Builder().method("PUT").target(draft);
  		// publish
  		draft.addTransition(new Transition.Builder().method("PUT").target(published);
  		// delete draft
  		draft.addTransition("DELETE", deletedDraft);
  		// delete published
  		published.addTransition("DELETE", publishedDeleted);

  		// mock command controller to do nothing
  		NewCommandController cc = mock(NewCommandController.class);
  		when(cc.fetchCommand(anyString(), anyString())).thenReturn(mock(InteractionCommand.class));

  		ResourceStateMachine stateMachine = new ResourceStateMachine(initial);
  		HTTPHypermediaRIM parent = new HTTPHypermediaRIM(cc, stateMachine);
  		verify(cc).fetchCommand("GET", "/notes/{id}");
  		Collection<ResourceInteractionModel> resources = parent.getChildren();
  		assertEquals(2, resources.size());
  		verify(cc, times(1)).fetchCommand("GET", "/notes/{id}");
  		verify(cc, times(1)).fetchCommand("GET", "/notes/{id}/draft");
  		verify(cc).fetchCommand("PUT", "/notes/{id}/draft");
  		verify(cc).fetchCommand("DELETE", "/notes/{id}/draft");
  		verify(cc, times(1)).fetchCommand("GET", "/notes/{id}/published");
  		verify(cc).fetchCommand("DELETE", "/notes/{id}/published");
  		verify(cc).fetchCommand("PUT", "/notes/{id}/published");
  	}

  	@Test
  	public void testBootstrapRIMsMultipleSubstates1() {
  		String ENTITY_NAME = "BOOKING";
  		String resourcePath = "/bookings";

  		// the booking
  		ResourceState begin = new ResourceState(ENTITY_NAME, "begin", resourcePath);
    		ResourceState bookingCreated = new ResourceState(begin, "bookingCreated", "/{id}");
    		ResourceState bookingCancellation = new ResourceState(bookingCreated, "cancellation", "/cancellation");
    		ResourceState deleted = new ResourceState(bookingCancellation, "deleted", null);

  		begin.addTransition(new Transition.Builder().method("PUT").target(bookingCreated);
  		bookingCreated.addTransition(new Transition.Builder().method("PUT").target(bookingCancellation);
  		bookingCancellation.addTransition("DELETE", deleted);

  		// the payment
  		ResourceState payment = new ResourceState(bookingCreated, "payment", "/payment");
  		ResourceState confirmation = new ResourceState(payment, "pconfirmation", "/pconfirmation");
  		ResourceState waitingForConfirmation = new ResourceState(payment, "pwaiting", "/pwaiting");

  		payment.addTransition(new Transition.Builder().method("PUT").target(waitingForConfirmation);
  		payment.addTransition(new Transition.Builder().method("PUT").target(confirmation);
  		waitingForConfirmation.addTransition(new Transition.Builder().method("PUT").target(confirmation);

  		// linking the two state machines together
  		bookingCreated.addTransition(new Transition.Builder().method("PUT").target(payment);  // TODO needs to be conditional
  		confirmation.addTransition(new Transition.Builder().method("PUT").target(bookingCancellation);

  		// mock command controller to do nothing
  		NewCommandController cc = mock(NewCommandController.class);
  		when(cc.fetchCommand(anyString(), anyString())).thenReturn(mock(InteractionCommand.class));

  		HTTPHypermediaRIM parent = new HTTPHypermediaRIM(cc, new ResourceStateMachine(begin));
  		verify(cc, times(1)).fetchCommand("GET", "/bookings");
  		Collection<ResourceInteractionModel> resources = parent.getChildren();
  		assertEquals(5, resources.size());
  		verify(cc, times(1)).fetchCommand("GET", "/bookings/{id}");
  		verify(cc).fetchCommand("PUT", "/bookings/{id}");
  		verify(cc, times(1)).fetchCommand("GET", "/bookings/{id}/cancellation");
  		verify(cc).fetchCommand("DELETE", "/bookings/{id}/cancellation");
  		verify(cc).fetchCommand("PUT", "/bookings/{id}/cancellation");
  		verify(cc, times(1)).fetchCommand("GET", "/bookings/{id}/payment");
  		verify(cc).fetchCommand("PUT", "/bookings/{id}/payment");
  		verify(cc, times(1)).fetchCommand("GET", "/bookings/{id}/payment/pconfirmation");
  		verify(cc).fetchCommand("PUT", "/bookings/{id}/payment/pconfirmation");
  		verify(cc, times(1)).fetchCommand("GET", "/bookings/{id}/payment/pwaiting");
  		verify(cc).fetchCommand("PUT", "/bookings/{id}/payment/pwaiting");
  	}
  */
  @Test
  public void testChildrenRIMsSubstate() {
    String ENTITY_NAME = "DraftNote";
    String resourcePath = "/notes/{id}";
    ResourceState initial = new ResourceState(ENTITY_NAME, "initial", mockActions(), resourcePath);
    ResourceState draft = new ResourceState(ENTITY_NAME, "draft", mockActions(), "/draft");

    // create draft
    initial.addTransition(new Transition.Builder().method("PUT").target(draft).build());
    // updated draft
    draft.addTransition(new Transition.Builder().method("PUT").target(draft).build());

    // supply a transformer to check that this is copied into child resource
    BeanTransformer transformer = new BeanTransformer();

    ResourceStateMachine stateMachine = new ResourceStateMachine(initial, transformer);
    HTTPHypermediaRIM parent =
        new HTTPHypermediaRIM(mockCommandController(), stateMachine, createMockMetadata());
    Collection<ResourceInteractionModel> resources = parent.getChildren();
    assertEquals(1, resources.size());
    assertEquals(draft.getPath(), resources.iterator().next().getResourcePath());
    assertEquals(
        transformer,
        ((HTTPHypermediaRIM) resources.iterator().next()).getHypermediaEngine().getTransformer());
  }
  private boolean removePartial(
      Collection master, Collection c, boolean isRemove, boolean byKey, boolean byValue) {
    int sz = c.size();
    int removed = 0;
    int retained = 0;
    int index = 0;
    int begin = -1;
    for (final Iterator it = master.iterator();
        it.hasNext() && (!isRemove || removed < sz) && (isRemove || retained < sz);
        ++index) {
      Object item = it.next();
      if (c.contains(item) == isRemove) {
        if (begin < 0) {
          begin = index;
        }
        ++removed;
        if (byKey) removeSelectionByKey(item);
        else if (byValue) removeSelectionByValue(item);
        else removeSelection(item);
        it.remove();
      } else {
        ++retained;
        if (begin >= 0) {
          fireEvent(ListDataEvent.INTERVAL_REMOVED, begin, index - 1);
          index = begin; // this range removed, the index is reset to begin
          begin = -1;
        }
      }
    }
    if (begin >= 0) {
      fireEvent(ListDataEvent.INTERVAL_REMOVED, begin, index - 1);
    }

    return removed > 0;
  }
Example #27
0
  private void playOutExplosion(GlowPlayer player, Iterable<BlockVector> blocks) {
    Collection<ExplosionMessage.Record> records = new ArrayList<>();

    Location clientLoc = location.clone();
    clientLoc.setX((int) clientLoc.getX());
    clientLoc.setY((int) clientLoc.getY());
    clientLoc.setZ((int) clientLoc.getZ());

    for (BlockVector block : blocks) {
      byte x = (byte) (block.getBlockX() - clientLoc.getBlockX());
      byte y = (byte) (block.getBlockY() - clientLoc.getBlockY());
      byte z = (byte) (block.getBlockZ() - clientLoc.getBlockZ());
      records.add(new ExplosionMessage.Record(x, y, z));
    }

    Vector velocity = player.getVelocity();
    ExplosionMessage message =
        new ExplosionMessage(
            (float) location.getX(),
            (float) location.getY(),
            (float) location.getZ(),
            5,
            (float) velocity.getX(),
            (float) velocity.getY(),
            (float) velocity.getZ(),
            records);

    player.getSession().send(message);
  }
Example #28
0
  @Test
  public void testCreateAndDropManyDatabases() throws Exception {
    List<String> createdDatabases = new ArrayList<>();
    InfoSchemaMetadataDictionary dictionary = new InfoSchemaMetadataDictionary();
    String namePrefix = "database_";
    final int NUM = 10;
    for (int i = 0; i < NUM; i++) {
      String databaseName = namePrefix + i;
      assertFalse(catalog.existDatabase(databaseName));
      catalog.createDatabase(databaseName, TajoConstants.DEFAULT_TABLESPACE_NAME);
      assertTrue(catalog.existDatabase(databaseName));
      createdDatabases.add(databaseName);
    }

    Collection<String> allDatabaseNames = catalog.getAllDatabaseNames();
    for (String databaseName : allDatabaseNames) {
      assertTrue(
          databaseName.equals(DEFAULT_DATABASE_NAME)
              || createdDatabases.contains(databaseName)
              || dictionary.isSystemDatabase(databaseName));
    }
    // additional ones are 'default' and 'system' databases.
    assertEquals(NUM + 2, allDatabaseNames.size());

    Collections.shuffle(createdDatabases);
    for (String tobeDropped : createdDatabases) {
      assertTrue(catalog.existDatabase(tobeDropped));
      catalog.dropDatabase(tobeDropped);
      assertFalse(catalog.existDatabase(tobeDropped));
    }
  }
Example #29
0
  @Test
  public void testDropDatabaseWithAllTables() throws Exception {
    Map<String, List<String>> createdTablesMap = createBaseDatabaseAndTables();

    // Each time we drop one database, check all databases and their tables.
    for (String databaseName : new ArrayList<>(createdTablesMap.keySet())) {
      // drop one database
      assertTrue(catalog.existDatabase(databaseName));
      catalog.dropDatabase(databaseName);
      createdTablesMap.remove(databaseName);

      // check all tables which belong to other databases
      for (Map.Entry<String, List<String>> entry : createdTablesMap.entrySet()) {
        assertTrue(catalog.existDatabase(entry.getKey()));

        // checking all tables for this database
        Collection<String> tablesForThisDatabase = catalog.getAllTableNames(entry.getKey());
        assertEquals(createdTablesMap.get(entry.getKey()).size(), tablesForThisDatabase.size());
        for (String tableName : tablesForThisDatabase) {
          assertTrue(
              createdTablesMap
                  .get(entry.getKey())
                  .contains(IdentifierUtil.extractSimpleName(tableName)));
        }
      }
    }

    // Finally, default and system database will remain. So, its result is 1.
    assertEquals(2, catalog.getAllDatabaseNames().size());
  }
Example #30
0
  @Test
  public void shouldGetVdbPermission() throws Exception {
    loadVdbs();

    // get
    Properties settings =
        _uriBuilder.createSettings(
            SettingNames.VDB_NAME, TestUtilities.ALL_ELEMENTS_EXAMPLE_VDB_NAME);
    _uriBuilder.addSetting(settings, SettingNames.DATA_ROLE_ID, "roleOne");
    _uriBuilder.addSetting(settings, SettingNames.PERMISSION_ID, "myTable.T1");
    URI uri = _uriBuilder.buildVdbPermissionUri(LinkType.SELF, settings);
    this.response = request(uri).get();
    final String entity = this.response.readEntity(String.class);
    assertThat(entity, is(notNullValue()));

    // System.out.println("Response from uri " + uri + ":\n" + entity);

    RestVdbPermission permission = KomodoJsonMarshaller.unmarshall(entity, RestVdbPermission.class);
    assertNotNull(permission);

    assertEquals(KomodoType.VDB_PERMISSION, permission.getkType());
    assertEquals("myTable.T1", permission.getId());
    assertFalse(permission.hasChildren());
    assertFalse(permission.isAllowAlter());
    assertFalse(permission.isAllowCreate());
    assertFalse(permission.isAllowDelete());
    assertFalse(permission.isAllowExecute());
    assertFalse(permission.isAllowLanguage());
    assertTrue(permission.isAllowRead());
    assertFalse(permission.isAllowUpdate());

    Collection<RestLink> links = permission.getLinks();
    assertEquals(5, links.size());
  }