コード例 #1
0
  private Entity addOperationComponent(
      final Entity technology,
      final Entity parent,
      final Entity operation,
      final int productsComponentsQuantity) {
    Preconditions.checkNotNull(technology, "Technology entity is null");
    Entity operationComponent =
        dataDefinitionService
            .get(L_TECHNOLOGIES_PLUGIN_IDENTIFIER, "technologyOperationComponent")
            .create();

    int productInComponentQuantity = RANDOM.nextInt(productsComponentsQuantity);
    int productOutComponentQuantity = productsComponentsQuantity - productInComponentQuantity;

    operationComponent.setField(
        L_NAME, "operationComponent" + generateString(CHARS_AND_DIGITS, 15));
    operationComponent.setField(L_NUMBER, generateString(CHARS_AND_DIGITS, 20));
    operationComponent.setField(L_TECHNOLOGY_MODEL_TECHNOLOGY, technology);
    operationComponent.setField("parent", parent);
    operationComponent.setField(L_TECHNOLOGY_MODEL_OPERATION, operation);
    operationComponent.setField("entityType", L_TECHNOLOGY_MODEL_OPERATION);
    operationComponent.setField(L_TPZ, operation.getField(L_TPZ));
    operationComponent.setField(L_TJ, operation.getField(L_TJ));
    operationComponent.setField("machineUtilization", operation.getField("machineUtilization"));
    operationComponent.setField("laborUtilization", operation.getField("laborUtilization"));
    operationComponent.setField("productionInOneCycle", operation.getField("productionInOneCycle"));
    operationComponent.setField(
        L_NEXT_OPERATION_AFTER_PRODUCED_TYPE,
        operation.getField(L_NEXT_OPERATION_AFTER_PRODUCED_TYPE));
    operationComponent.setField("nextOperationAfterProducedQuantity", "0");
    operationComponent.setField("timeNextOperation", operation.getField("timeNextOperation"));

    operationComponent = operationComponent.getDataDefinition().save(operationComponent);
    List<Entity> listOut = new LinkedList<Entity>();
    Entity productOut = null;
    for (int i = 0; i < productOutComponentQuantity; i++) {
      productOut = getRandomProduct();

      while (listOut.contains(productOut)) {
        productOut = getRandomProduct();
      }
      listOut.add(productOut);
      generateAndAddOperationProductOutComponent(
          operationComponent, new BigDecimal(RANDOM.nextInt(50) + 5), productOut);
    }
    List<Entity> listIn = new LinkedList<Entity>();
    Entity productIn = null;
    for (int i = 0; i < productInComponentQuantity; i++) {
      productIn = getRandomProduct();

      while (listIn.contains(productIn)) {
        productIn = getRandomProduct();
      }
      listIn.add(productIn);
      generateAndAddOperationProductInComponent(
          operationComponent, new BigDecimal(RANDOM.nextInt(50) + 5), productIn);
    }

    return operationComponent;
  }
  private void setPublicRenderParameterPortlets(
      Map<PortletID, List<PublicRenderParameterHolder>> portletPublicRenderParametersFromDescriptor,
      Map<PublicRenderParameterHolder, List<PortletID>> publicRenderParameterSupportingPortlets) {
    Set<Map.Entry<PortletID, List<PublicRenderParameterHolder>>> entries =
        portletPublicRenderParametersFromDescriptor.entrySet();
    for (Map.Entry<PortletID, List<PublicRenderParameterHolder>> mapEntry : entries) {
      for (PublicRenderParameterHolder publicRenderParameterHolder : mapEntry.getValue()) {
        List<PublicRenderParameterHolder> supportingPublicRenderParameterHolders =
            portletSupportingPublicRenderParameters.get(mapEntry.getKey());
        if (supportingPublicRenderParameterHolders == null) {
          supportingPublicRenderParameterHolders = new ArrayList<PublicRenderParameterHolder>();
        }
        if (!supportingPublicRenderParameterHolders.contains(publicRenderParameterHolder)) {
          supportingPublicRenderParameterHolders.add(publicRenderParameterHolder);
        }
        this.portletSupportingPublicRenderParameters.put(
            mapEntry.getKey(), supportingPublicRenderParameterHolders);

        List<PortletID> portletIDs =
            publicRenderParameterSupportingPortlets.get(publicRenderParameterHolder);
        if (portletIDs == null) {
          portletIDs = new ArrayList<PortletID>();
        }
        if (!portletIDs.contains(mapEntry.getKey())) {
          portletIDs.add(mapEntry.getKey());
        }
        publicRenderParameterSupportingPortlets.put(publicRenderParameterHolder, portletIDs);
      }
    }
  }
コード例 #3
0
  /**
   * Creates this from a JDOM element.
   *
   * @param jdom input
   */
  public UserQueryInput(Element jdom) {

    // Done in LuceneSearcher#computeQuery
    // protectRequest(jdom);

    for (Object e : jdom.getChildren()) {
      if (e instanceof Element) {
        Element node = (Element) e;
        String nodeName = node.getName();
        String nodeValue = StringUtils.trim(node.getText());
        if (SearchParameter.SIMILARITY.equals(nodeName)) {
          setSimilarity(jdom.getChildText(SearchParameter.SIMILARITY));
        } else {
          if (StringUtils.isNotBlank(nodeValue)) {

            if (SECURITY_FIELDS.contains(nodeName) || nodeName.contains("_op")) {
              addValues(searchPrivilegeCriteria, nodeName, nodeValue);
            } else if (RESERVED_FIELDS.contains(nodeName)) {
              searchOption.put(nodeName, nodeValue);
            } else {
              // addValues(searchCriteria, nodeName, nodeValue);
              // Rename search parameter to lucene index field
              // when needed
              addValues(
                  searchCriteria,
                  (searchParamToLuceneField.containsKey(nodeName)
                      ? searchParamToLuceneField.get(nodeName)
                      : nodeName),
                  nodeValue);
            }
          }
        }
      }
    }
  }
コード例 #4
0
  @Test
  public void testGetMemberShardNames() {
    List<String> memberShardNames = configuration.getMemberShardNames("member-1");

    assertTrue(memberShardNames.contains("people-1"));
    assertTrue(memberShardNames.contains("cars-1"));
  }
 public List<PublicRenderParameterHolder> getSupportedPublicRenderParameterHolders(
     EntityID portletEntityId, Map<String, String[]> renderParameters) {
   PortletID portletID = portletEntityId.getPortletID();
   List<PublicRenderParameterHolder> publicRenderParameterHolders =
       new ArrayList<PublicRenderParameterHolder>();
   if (portletID != null) {
     List<PublicRenderParameterHolder> supportingPublicRenderParameterHolders =
         this.portletSupportingPublicRenderParameters.get(portletID);
     Set<Map.Entry<String, List<PublicRenderParameterHolder>>> entries =
         this.appPublicRenderParameterHolders.entrySet();
     for (Map.Entry<String, List<PublicRenderParameterHolder>> mapEntry : entries) {
       if (supportingPublicRenderParameterHolders != null) {
         if (renderParameters == null) {
           for (PublicRenderParameterHolder publicRenderParameterHolder : mapEntry.getValue()) {
             if (supportingPublicRenderParameterHolders.contains(publicRenderParameterHolder)) {
               publicRenderParameterHolders.add(publicRenderParameterHolder);
             }
           }
         } else {
           for (PublicRenderParameterHolder publicRenderParameterHolder : mapEntry.getValue()) {
             if (renderParameters.containsKey(publicRenderParameterHolder.getIdentifier())
                 && supportingPublicRenderParameterHolders.contains(publicRenderParameterHolder)) {
               publicRenderParameterHolders.add(publicRenderParameterHolder);
             }
           }
         }
       }
     }
   }
   return publicRenderParameterHolders;
 }
コード例 #6
0
ファイル: UIMessagesTest.java プロジェクト: nuxeo/richfaces
 /** Test method for {@link org.richfaces.component.UIRichMessages#getSeverenities()}. */
 public void testGetSeverenities() {
   uiMessages.setLevel("ALL,ERROR");
   List<String> severenities = uiMessages.getSeverenities();
   assertEquals(2, severenities.size());
   assertTrue(severenities.contains("ALL"));
   assertTrue(severenities.contains("ERROR"));
 }
コード例 #7
0
 @Override
 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) throws RemoteException {
   waitForReadyInner();
   try {
     enforcePluginFileExists();
     List<PermissionGroupInfo> list = new ArrayList<PermissionGroupInfo>();
     if (shouldNotBlockOtherInfo()) {
       for (PluginPackageParser pluginPackageParser : mPluginCache.values()) {
         List<PermissionGroupInfo> permissionGroupInfos =
             pluginPackageParser.getPermissionGroups();
         for (PermissionGroupInfo permissionGroupInfo : permissionGroupInfos) {
           if (!list.contains(permissionGroupInfo)) {
             list.add(permissionGroupInfo);
           }
         }
       }
     } else {
       List<String> pkgs = mActivityManagerService.getPackageNamesByPid(Binder.getCallingPid());
       for (PluginPackageParser pluginPackageParser : mPluginCache.values()) {
         List<PermissionGroupInfo> permissionGroupInfos =
             pluginPackageParser.getPermissionGroups();
         for (PermissionGroupInfo permissionGroupInfo : permissionGroupInfos) {
           if (!list.contains(permissionGroupInfo)
               && pkgs.contains(permissionGroupInfo.packageName)) {
             list.add(permissionGroupInfo);
           }
         }
       }
     }
     return list;
   } catch (Exception e) {
     handleException(e);
   }
   return null;
 }
コード例 #8
0
  /**
   * Verifies that a user is allowed to update a campaign's XML.
   *
   * @param request The Request that is performing this service.
   * @param username The username of the user.
   * @param campaignId The campaign's unique identifier.
   * @throws ServiceException Thrown if the user isn't allowed to modify the campaign, if the user
   *     is allowed to modify the campaign but responses exist, or if there is an error.
   */
  public static void verifyUserCanUpdateCampaignXml(
      Request request, String username, String campaignId) throws ServiceException {
    try {
      List<CampaignRoleCache.Role> roles =
          UserCampaignDaos.getUserCampaignRoles(username, campaignId);

      if (roles.contains(CampaignRoleCache.Role.SUPERVISOR)
          || roles.contains(CampaignRoleCache.Role.AUTHOR)) {
        if (CampaignSurveyResponseDaos.getNumberOfSurveyResponsesForCampaign(campaignId) == 0) {
          return;
        }

        request.setFailed(
            ErrorCodes.CAMPAIGN_INSUFFICIENT_PERMISSIONS,
            "Survey responses exist; therefore the XML can no longer be modified.");
        throw new ServiceException(
            "Survey responses exist; therefore the XML can no longer be modified.");
      }

      request.setFailed(
          ErrorCodes.CAMPAIGN_INSUFFICIENT_PERMISSIONS,
          "The user is not allowed to modify the campaign's XML.");
      throw new ServiceException("The user is not allowed to modify the campaign's XML.");
    } catch (DataAccessException e) {
      request.setFailed();
      throw new ServiceException(e);
    }
  }
コード例 #9
0
  /**
   * Verifies that the user is allowed to grant or revoke all of the roles in the collection.
   *
   * @param request The Request that is performing this service.
   * @param username The username of the user.
   * @param campaignId The unique identifier for the campaign where the user is attempting to add or
   *     revoke roles.
   * @param roles The roles to check if the user can grant or revoke.
   * @throws ServiceException Thrown if the user is not allowed to grant or revoke some role or if
   *     there is an error.
   */
  public static void verifyUserCanGrantOrRevokeRoles(
      Request request, String username, String campaignId, Collection<CampaignRoleCache.Role> roles)
      throws ServiceException {
    try {
      List<CampaignRoleCache.Role> usersRoles =
          UserCampaignDaos.getUserCampaignRoles(username, campaignId);

      if (usersRoles.contains(CampaignRoleCache.Role.SUPERVISOR)) {
        return;
      }

      if (usersRoles.contains(CampaignRoleCache.Role.AUTHOR)) {
        if (!roles.contains(CampaignRoleCache.Role.SUPERVISOR)) {
          return;
        }

        request.setFailed(
            ErrorCodes.CAMPAIGN_INSUFFICIENT_PERMISSIONS,
            "The user is not allowed to grant the supervisor privilege.");
        throw new ServiceException("The user is not allowed to grant the supervisor privilege.");
      }

      request.setFailed(
          ErrorCodes.CAMPAIGN_INSUFFICIENT_PERMISSIONS,
          "The user is not allowed to grant privileges.");
      throw new ServiceException("The user is not allowed to grant privileges.");
    } catch (DataAccessException e) {
      request.setFailed();
      throw new ServiceException(e);
    }
  }
コード例 #10
0
ファイル: Bitstream.java プロジェクト: BinitaShakya/DSpace
  public void setup(org.dspace.content.Bitstream bitstream, String expand) throws SQLException {
    List<String> expandFields = new ArrayList<String>();
    if (expand != null) {
      expandFields = Arrays.asList(expand.split(","));
    }

    // A logo bitstream might not have a bundle...
    if (bitstream.getBundles() != null & bitstream.getBundles().length >= 0) {
      if (bitstream.getParentObject().getType() == Constants.ITEM) {
        bundleName = bitstream.getBundles()[0].getName();
      }
    }

    description = bitstream.getDescription();
    format = bitstream.getFormatDescription();
    sizeBytes = bitstream.getSize();
    retrieveLink = "/bitstreams/" + bitstream.getID() + "/retrieve";
    mimeType = bitstream.getFormat().getMIMEType();
    sequenceId = bitstream.getSequenceID();
    CheckSum checkSum = new CheckSum();
    checkSum.setCheckSumAlgorith(bitstream.getChecksumAlgorithm());
    checkSum.setValue(bitstream.getChecksum());
    this.setCheckSum(checkSum);

    if (expandFields.contains("parent") || expandFields.contains("all")) {
      parentObject = new DSpaceObject(bitstream.getParentObject());
    } else {
      this.addExpand("parent");
    }

    if (!expandFields.contains("all")) {
      this.addExpand("all");
    }
  }
コード例 #11
0
 @Test
 public void moveSubObjectPropertyTest() {
   ontology.getOntologyDeployObjectProperty().addObjectProperty(objectPropertyName);
   ontology.getOntologyDeployObjectProperty().addObjectProperty(toObjectPropertyName);
   ontology
       .getOntologyDeployObjectProperty()
       .addSubObjectProperty(subObjectPropertyName, objectPropertyName);
   ontology.saveChanges();
   ontology
       .getOntologyDeployObjectProperty()
       .moveSubObjectProperty(subObjectPropertyName, objectPropertyName, toObjectPropertyName);
   ontology.saveChanges();
   List<String> strList =
       ontology
           .getOntologyReasoner()
           .getSubObjectPropertiesFromObjectProperty(objectPropertyName, true);
   Assert.assertFalse(strList.contains(subObjectPropertyName));
   strList =
       ontology
           .getOntologyReasoner()
           .getSubObjectPropertiesFromObjectProperty(toObjectPropertyName, true);
   Assert.assertTrue(strList.contains(subObjectPropertyName));
   ontology.getOntologyUndeployObjectProperty().removeObjectProperty(objectPropertyName);
   ontology.getOntologyUndeployObjectProperty().removeObjectProperty(toObjectPropertyName);
   ontology
       .getOntologyUndeployObjectProperty()
       .removeSubObjectProperty(subObjectPropertyName, objectPropertyName);
   ontology.saveChanges();
 }
コード例 #12
0
  public void testListTubesWatched() {
    Client client = new ClientImpl(TEST_HOST, TEST_PORT);
    List<String> list = client.listTubesWatched();
    assertNotNull(list);
    int initialWatchCount = list.size();
    assertTrue(initialWatchCount >= 1);

    String tubeName = "tube-" + UUID.randomUUID().toString();
    int watchCount = client.watch(tubeName);
    assertEquals(initialWatchCount + 1, watchCount);

    list = client.listTubesWatched();
    assertNotNull(list);
    assertEquals(watchCount, list.size());
    assertTrue(list.contains(tubeName));

    boolean dump = false;
    if (dump) {
      for (String tube : list) {
        System.out.println("watching tube: " + tube);
      }
    }

    watchCount = client.ignore(tubeName);
    assertEquals(initialWatchCount, watchCount);
    list = client.listTubesWatched();
    assertNotNull(list);
    assertEquals(initialWatchCount, list.size());
    assertFalse(list.contains(tubeName));
  }
コード例 #13
0
  @Override
  public IWizardPage getPreviousPage(IWizardPage page) {
    IWizardPage previousPage = null;

    if (currentAdditionalPages == null) {
      if (page.equals(scriptPage)) {
        previousPage = toolPage;
      } else {
        previousPage = super.getPreviousPage(page);
      }
    } else {
      if (page.equals(scriptPage)) {
        previousPage = currentAdditionalPages.get(currentAdditionalPages.size() - 1);
      } else if (currentAdditionalPages.contains(page)
          && currentAdditionalPages.indexOf(page) > 0) {
        previousPage = currentAdditionalPages.get(currentAdditionalPages.indexOf(page) - 1);
      } else if (currentAdditionalPages.contains(page)
          && currentAdditionalPages.indexOf(page) == 0) {
        previousPage = scriptPage;
      } else if (page.equals(editConfigurationPage)) {
        return null;
      } else {
        previousPage = super.getPreviousPage(page);
      }
    }

    if (previousPage != null) {
      ((ToolIntegrationWizardPage) previousPage).updatePage();
    }
    return previousPage;
  }
コード例 #14
0
ファイル: MarkingTest.java プロジェクト: mduduzik/flowframe
  @Test
  public void testEquals() {
    IEPC epc = new EPC();
    IControlFlow cf = epc.addControlFlow(new Event(), new Event());
    cf.setId("blub");

    Marking m1 = new Marking();
    m1.applyContext(cf, Marking.Context.DEAD);
    m1.applyState(cf, Marking.State.NEG_TOKEN);

    Marking m2 = new Marking();
    m2.applyContext(cf, Marking.Context.DEAD);
    m2.applyState(cf, Marking.State.NEG_TOKEN);

    Marking m3 = m2.clone();
    m3.applyContext(cf, Marking.Context.WAIT);

    assertTrue(m1.equals(m2));
    assertTrue(m2.equals(m1));
    assertFalse(m1.equals(m3));
    assertFalse(m1.equals(new Marking()));

    List<Marking> list = new LinkedList<Marking>();
    list.add(m2);
    assertTrue(list.contains(m2));
    assertTrue(list.contains(m1));
    assertFalse(list.contains(new Marking()));
    assertFalse(list.contains(m3));
  }
コード例 #15
0
  @Override
  public boolean select(Viewer viewer, Object parentElement, Object element) {
    if (element instanceof IFile) return !hiddenFiles.contains(((IFile) element).getName());
    if (element instanceof IFolder) return !hiddenFolders.contains(((IFolder) element).getName());

    return !hiddenClasses.contains(element.getClass());
  }
コード例 #16
0
  /**
   * Ensures that the user can delete the campaign. At least one of the following must be true to
   * delete a campaign:
   *
   * <ul>
   *   <li>The user is a supervisor.
   *   <li>The user is an author and there are no responses.
   * </ul>
   *
   * <br>
   *
   * @param request The Request that is performing this service.
   * @param username The user's username.
   * @param campaignId The campaign's unique identifier.
   * @throws ServiceException Thrown if the user doesn't have sufficient permissions to delete the
   *     campaign or if there is an error.
   */
  public static void userCanDeleteCampaign(Request request, String username, String campaignId)
      throws ServiceException {
    try {
      List<CampaignRoleCache.Role> roles =
          UserCampaignDaos.getUserCampaignRoles(username, campaignId);

      if (roles.contains(CampaignRoleCache.Role.SUPERVISOR)) {
        return;
      }

      if (roles.contains(CampaignRoleCache.Role.AUTHOR)) {
        long numberOfResponses =
            CampaignSurveyResponseDaos.getNumberOfSurveyResponsesForCampaign(campaignId);

        if (numberOfResponses == 0) {
          return;
        } else {
          request.setFailed(
              ErrorCodes.CAMPAIGN_INSUFFICIENT_PERMISSIONS,
              "The campaign has responses; therefore, you can no longer delete it.");
          throw new ServiceException(
              "The campaign has responses; therefore, you can no longer delete it.");
        }
      }

      request.setFailed(
          ErrorCodes.CAMPAIGN_INSUFFICIENT_PERMISSIONS,
          "You do not have sufficient permissoins to delete this campaign.");
      throw new ServiceException("You do not have sufficient permissoins to delete this campaign.");
    } catch (DataAccessException e) {
      request.setFailed();
      throw new ServiceException(e);
    }
  }
コード例 #17
0
ファイル: OptUtil.java プロジェクト: arifiswise/egene
  public static String generateOptStrExcl(List<String> opts, List<String> excl) {

    if (null == opts || opts.size() == 0) return null;

    if (null == excl || excl.size() == 0) return OptUtil.generateOptStr(opts);

    Set<String> setOpts = new HashSet<String>(opts);
    int allSetCount = setOpts.size();
    Set<String> setExcl = new HashSet<String>(excl);
    int exclSetCount = 0;
    Iterator<String> iterator = setExcl.iterator();
    while (iterator.hasNext()) {
      String str = iterator.next();
      if (null != str) {
        if (opts.contains(str)) exclSetCount++;
      }
    }

    if (exclSetCount >= allSetCount) {
      throw new OptUtilException(
          "NO possible int to be generated. allPossibleSetSize="
              + allSetCount
              + ", exclSet="
              + exclSetCount);
    }

    String res = null;
    boolean got = false;
    while (!got) {
      res = OptUtil.generateOptStr(opts);
      if (!excl.contains(res)) got = true;
    }

    return res;
  }
コード例 #18
0
ファイル: Database.java プロジェクト: fedor4ever/linux_build
    private void extractUsedProperties(String text) {
      Pattern p1 = Pattern.compile("\\$\\{([^@$}]*)\\}");
      Matcher m1 = p1.matcher(text);
      log(text, Project.MSG_DEBUG);
      while (m1.find()) {
        String group = m1.group(1);
        if (!propertyList.contains(group)) {
          propertyList.add(group);
        }
        log("property matches: " + group, Project.MSG_DEBUG);
      }

      Pattern p2 = Pattern.compile("\\$\\{([^\n]*\\})\\}");
      Matcher m2 = p2.matcher(text);
      log(text, Project.MSG_DEBUG);
      while (m2.find()) {
        String group = m2.group(1);
        if (!propertyList.contains(group)) {
          propertyList.add(group);
        }
        log("property matches: " + group, Project.MSG_DEBUG);
      }

      Pattern p3 = Pattern.compile("\\$\\{(\\@\\{[^\n]*)\\}");
      Matcher m3 = p3.matcher(text);
      log(text, Project.MSG_DEBUG);
      while (m3.find()) {
        String group = m3.group(1);
        if (!propertyList.contains(group)) {
          propertyList.add(group);
        }
        log("property matches: " + group, Project.MSG_DEBUG);
      }
    }
コード例 #19
0
ファイル: PostemTool.java プロジェクト: philsawa/sakai
  private boolean hasADuplicateUsername(CSV studentGrades) {
    List usernameList = studentGrades.getStudentUsernames();
    List duplicatesList = new ArrayList();

    while (usernameList.size() > 0) {
      String username = (String) usernameList.get(0);
      usernameList.remove(username);
      if (usernameList.contains(username) && !duplicatesList.contains(username)) {
        duplicatesList.add(username);
      }
    }

    if (duplicatesList.size() <= 0) {
      return false;
    }

    if (duplicatesList.size() == 1) {
      PostemTool.populateMessage(
          FacesMessage.SEVERITY_ERROR, "single_duplicate_username", new Object[] {});
    } else {
      PostemTool.populateMessage(
          FacesMessage.SEVERITY_ERROR, "mult_duplicate_usernames", new Object[] {});
    }

    for (int i = 0; i < duplicatesList.size(); i++) {
      PostemTool.populateMessage(
          FacesMessage.SEVERITY_ERROR, "duplicate_username", new Object[] {duplicatesList.get(i)});
    }

    PostemTool.populateMessage(
        FacesMessage.SEVERITY_ERROR, "duplicate_username_dir", new Object[] {});

    return true;
  }
コード例 #20
0
  public static String removeDuplicateLines(String text, boolean ignoreCase) {

    // Break into separate lines.
    String[] lineList = split(text);

    List<String> finishedList = new ArrayList<String>();
    List<String> dupeList = new ArrayList<String>();

    for (String line : lineList) {

      if (ignoreCase) {

        String lcLine = line.toLowerCase();
        if (!dupeList.contains(lcLine)) {
          dupeList.add(lcLine);
          finishedList.add(line);
        }
      } else {

        if (!finishedList.contains(line)) {
          finishedList.add(line);
        }
      }
    }

    return StringUtils.join(finishedList.toArray(), '\n').trim();
  }
コード例 #21
0
  /** Rewrite "/css/jeeeyul-custom.css" with user preference. */
  public void rewrite() {
    try {
      CSSEngine cssEngine = WidgetElement.getEngine(display);
      ExtendedDocumentCSS documentCSS = (ExtendedDocumentCSS) cssEngine.getDocumentCSS();

      StyleSheet customThemeSheet = findCustomThemeSheet(documentCSS);

      CustomThemeGenerator generator =
          new CustomThemeGenerator(JThemesCore.getDefault().getPreferenceStore());

      String newCSSContent = generator.generate().toString();
      StyleSheet newSheet = cssEngine.parseStyleSheet(new StringReader(newCSSContent));

      StyleSheetList oldSheetList = documentCSS.getStyleSheets();
      List<StyleSheet> newSheetList = new ArrayList<StyleSheet>();

      for (int i = 0; i < oldSheetList.getLength(); i++) {
        StyleSheet oldSheet = oldSheetList.item(i);
        if (oldSheet != customThemeSheet) {
          if (!newSheetList.contains(oldSheet)) newSheetList.add(oldSheet);
        } else {
          if (!newSheetList.contains(newSheet)) newSheetList.add(newSheet);
        }
      }

      documentCSS.removeAllStyleSheets();
      for (StyleSheet each : newSheetList) {
        documentCSS.addStyleSheet(each);
      }

      cssEngine.reapply();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  public void testGetAssetsZipFileSuccess() throws Exception {
    String userId = "1";
    long projectId = 2;
    byte[] data = {0, 0, 0};
    List<String> sourceFiles = new ArrayList<String>();
    sourceFiles.add("assets/kitty.png");
    sourceFiles.add("assets/meow.mp3");
    sourceFiles.add("src/appinventor/ai_user/HelloPurr/Screen1.blk");
    sourceFiles.add("src/appinventor/ai_user/HelloPurr/Screen1.scm");
    sourceFiles.add("youngandroidproject/project.properties");

    EasyMock.expect(storageIo.getProjectSourceFiles(userId, projectId)).andReturn(sourceFiles);
    EasyMock.expect(
            storageIo.downloadRawFile(
                EasyMock.eq(userId), EasyMock.eq(projectId), EasyMock.eq("assets/kitty.png")))
        .andReturn(data);
    EasyMock.expect(
            storageIo.downloadRawFile(
                EasyMock.eq(userId), EasyMock.eq(projectId), EasyMock.eq("assets/meow.mp3")))
        .andReturn(data);

    control.replay();

    List<String> zipEntries = getZipEntries(yaWebStart.getAssetsZipFile(userId, projectId));
    assert (zipEntries.contains("assets/meow.mp3"));
    assert (zipEntries.contains("assets/kitty.png"));
  }
 public EventHolder verifySupportedProcessingEvent(
     EntityID portletEntityId, EventHolder supportedEventHolder) {
   List<PortletID> portlets =
       getEventPublishingProcessingPortlets(
           this.eventProcessingPortlets, supportedEventHolder.getQName());
   PortletID portletID = portletEntityId.getPortletID();
   if (portlets.contains(portletID)) {
     return supportedEventHolder;
   } else {
     // Check whether supportedEventQName is present in the aliases of any event definition
     // or whether the supportedEventQName is same as the qname of any event definition
     // or whether aliases of the supportedEvent contains the eventQName
     // or whether any qname is common in both aliases
     // if yes use the event qname of that event definition to get the portlet list
     for (List<EventHolder> allEventHolders : this.appEventHolders.values()) {
       for (EventHolder eventHolder : allEventHolders) {
         if (eventHolder.getAliases().contains(supportedEventHolder.getQName())
             || eventHolder.getQName().equals(supportedEventHolder.getQName())
             || supportedEventHolder.getAliases().contains(eventHolder.getQName())
             || checkAliases(eventHolder, supportedEventHolder)) {
           portlets =
               getEventPublishingProcessingPortlets(
                   this.eventProcessingPortlets, eventHolder.getQName());
           if (portlets != null && portlets.contains(portletID)) {
             return eventHolder;
           }
         }
       }
     }
   }
   return null;
 }
コード例 #24
0
ファイル: OneToManyTest.java プロジェクト: satyan/sugar
  @Test
  public void shouldNotAddRelation() {
    List<Long> relationIds = Arrays.asList(1l, 2l, 3l, 4l);
    OneToManyModel model = new OneToManyModel(1l);
    save(model);

    for (long i : relationIds) {
      save(new OneToManyRelationModel(i, model));
    }

    save(new OneToManyRelationModel(5l, null));

    OneToManyModel result = findById(OneToManyModel.class, 1l);

    Assert.assertEquals(4, result.getModels().size());

    Assert.assertTrue(relationIds.contains(result.getModels().get(0).getId()));
    Assert.assertTrue(relationIds.contains(result.getModels().get(1).getId()));
    Assert.assertTrue(relationIds.contains(result.getModels().get(2).getId()));
    Assert.assertTrue(relationIds.contains(result.getModels().get(3).getId()));

    Assert.assertEquals(result, result.getModels().get(0).getModel());
    Assert.assertEquals(result, result.getModels().get(1).getModel());
    Assert.assertEquals(result, result.getModels().get(2).getModel());
    Assert.assertEquals(result, result.getModels().get(3).getModel());
  }
  /**
   * Generates a list of portlets that are processing events or publishing the events
   *
   * @param portletProcessingPublishingEventsFromDescriptor Map where portlet id is the key and list
   *     of events is the value
   * @param eventProcessingPublishingPortlets Map where event is the key and list of portlets is the
   *     value
   */
  private void setEventPortlets(
      Map<PortletID, List<EventHolder>> portletProcessingPublishingEventsFromDescriptor,
      Map<QName, List<PortletID>> eventProcessingPublishingPortlets,
      Map<PortletID, List<EventHolder>> portletSupportingProcessingPublishingEvents) {
    Set<Map.Entry<PortletID, List<EventHolder>>> entries =
        portletProcessingPublishingEventsFromDescriptor.entrySet();
    for (Map.Entry<PortletID, List<EventHolder>> mapEntry : entries) {
      for (EventHolder eventHolder : mapEntry.getValue()) {
        List<EventHolder> supportingEventHolders =
            portletSupportingProcessingPublishingEvents.get(mapEntry.getKey());
        if (supportingEventHolders == null) {
          supportingEventHolders = new ArrayList<EventHolder>();
        }
        if (!supportingEventHolders.contains(eventHolder)) {
          supportingEventHolders.add(eventHolder);
        }
        portletSupportingProcessingPublishingEvents.put(mapEntry.getKey(), supportingEventHolders);

        List<PortletID> portletIDs = eventProcessingPublishingPortlets.get(eventHolder.getQName());
        if (portletIDs == null) {
          portletIDs = new ArrayList<PortletID>();
        }
        if (!portletIDs.contains(mapEntry.getKey())) {
          portletIDs.add(mapEntry.getKey());
        }
        eventProcessingPublishingPortlets.put(eventHolder.getQName(), portletIDs);
      }
    }
  }
コード例 #26
0
  public ShapeWrappers extractFeatureProperties(Feature f) {
    HashMap<String, String> propMap = new HashMap<String, String>();
    String shapeText = f.getDefaultGeometryProperty().getValue().toString();

    Collection<Property> props = f.getProperties();
    Iterator<Property> pi = props.iterator();

    while (pi.hasNext()) {
      Property p = pi.next();
      String name = p.getName().toString();
      // System.out.println(name);
      if (pattern != null) {
        if (propNames.contains(name) || pattern.matcher(name).find()) {
          propMap.put(p.getName().toString(), p.getValue().toString());
        }
      } else {
        if (propNames.contains(name)) {
          try {
            propMap.put(p.getName().toString(), p.getValue().toString());
          } catch (Exception e) {
            log.log(Level.WARNING, "{0} prop name  {1}", new Object[] {e.getMessage(), name});
          }
        }
      }
    }
    return new ShapeWrappers(shapeText, propMap);
  }
コード例 #27
0
  @Test
  public void returnsConnections() {
    Set<Layer> layers = new HashSet<Layer>();
    Layer topLayer = new Layer();
    Layer middleLayer = new Layer();
    Layer bottomLayer = new Layer();

    Connections firstConnection = new FullyConnected(topLayer, middleLayer, 0, 0);
    Connections secondConnection = new FullyConnected(middleLayer, bottomLayer, 0, 0);

    topLayer.addConnection(firstConnection);
    middleLayer.addConnection(firstConnection);

    middleLayer.addConnection(secondConnection);
    bottomLayer.addConnection(secondConnection);

    layers.add(topLayer);
    layers.add(middleLayer);
    layers.add(bottomLayer);
    network.setLayers(layers);

    List<Connections> connections = network.getConnections();
    assertTrue(connections.contains(firstConnection));
    assertTrue(connections.contains(secondConnection));
  }
コード例 #28
0
  @Override
  public void drawActive(
      Graphics2D g,
      Position canvasCenter,
      Position mousePosition,
      List<Inputs> inputs,
      Position canvasSize,
      double scale) {
    drawCircle(g, canvasCenter, Color.red);
    if ((isOnEdge(mousePosition, canvasCenter) || adjustingRadius) && moveCircleStart == null) {
      if (!adjustingRadius) adjustingRadius = true;
      g.setStroke(new BasicStroke(5));
      Position upperLeft = canvasCenter.add(center).subtract(new Position(radius, radius));
      Position lowerRight = new Position(radius, radius).scale(2);
      g.drawOval(
          (int) upperLeft.getX(),
          (int) upperLeft.getY(),
          (int) lowerRight.getX(),
          (int) lowerRight.getY());
      if (inputs.contains(Inputs.leftMouse))
        radius = Math.sqrt(mousePosition.distanceSquared(canvasCenter.add(center)));
    } else if ((mousePosition.distanceSquared(canvasCenter.add(center)) < radius * radius
            && inputs.contains(Inputs.leftMouse))
        || moveCircleStart != null) {
      if (moveCircleStart == null) moveCircleStart = mousePosition;
      else {
        center = center.subtract(moveCircleStart.subtract(mousePosition));
        moveCircleStart = mousePosition;
      }
    }

    if (!inputs.contains(Inputs.leftMouse)) moveCircleStart = null;
    if (!isOnEdge(mousePosition, canvasCenter) && adjustingRadius) adjustingRadius = false;
  }
コード例 #29
0
ファイル: AttributeService.java プロジェクト: noctarius/jimfs
  /** Implements {@link Files#readAttributes(Path, String, LinkOption...)}. */
  public ImmutableMap<String, Object> readAttributes(File file, String attributes) {
    String view = getViewName(attributes);
    List<String> attrs = getAttributeNames(attributes);

    if (attrs.size() > 1 && attrs.contains(ALL_ATTRIBUTES)) {
      // attrs contains * and other attributes
      throw new IllegalArgumentException("invalid attributes: " + attributes);
    }

    Map<String, Object> result = new HashMap<>();
    if (attrs.size() == 1 && attrs.contains(ALL_ATTRIBUTES)) {
      // for 'view:*' format, get all keys for all providers for the view
      AttributeProvider provider = providersByName.get(view);
      readAll(file, provider, result);

      for (String inheritedView : provider.inherits()) {
        AttributeProvider inheritedProvider = providersByName.get(inheritedView);
        readAll(file, inheritedProvider, result);
      }
    } else {
      // for 'view:attr1,attr2,etc'
      for (String attr : attrs) {
        result.put(attr, getAttribute(file, view, attr));
      }
    }

    return ImmutableMap.copyOf(result);
  }
コード例 #30
0
ファイル: ListUtilsTest.java プロジェクト: TwoStone/ipscrum
  /**
   * Test method for {@link fhdw.ipscrum.shared.utils.ListUtils#filter(java.util.List,
   * fhdw.ipscrum.shared.utils.ListUtils.Predicate)} .
   */
  @Test
  public final void testFilter() {
    final Integer one = Integer.valueOf(1);
    final Integer two = Integer.valueOf(2);
    final Integer three = Integer.valueOf(3);
    final Integer four = Integer.valueOf(4);

    final List<Integer> first = new ArrayList<Integer>();
    first.add(one);
    first.add(two);
    first.add(three);
    first.add(four);

    final List<Integer> list =
        ListUtils.filter(
            first,
            new ListUtils.Predicate<Integer>() {

              @Override
              public boolean test(final Integer element) {
                return element.compareTo(Integer.valueOf(3)) > 0;
              }
            });
    Assert.assertEquals(1, list.size());
    Assert.assertTrue(list.contains(four));
    Assert.assertFalse(list.contains(three));
  }