@Override
  public void drawScreen(int x, int y, float f) {
    super.drawScreen(x, y, f);

    String text1 =
        this.machine.storage.getEnergyStored()
            + "/"
            + this.machine.storage.getMaxEnergyStored()
            + " RF";
    if (x >= guiLeft + 16 && y >= guiTop + 5 && x <= guiLeft + 23 && y <= guiTop + 89) {
      this.func_146283_a(Collections.singletonList(text1), x, y);
    }
    String text3 =
        this.machine.tank.getFluidAmount()
            + "/"
            + this.machine.tank.getCapacity()
            + " mB "
            + FluidRegistry.WATER.getLocalizedName(this.machine.tank.getFluid());
    if (x >= guiLeft + 27 && y >= guiTop + 5 && x <= guiLeft + 33 && y <= guiTop + 70) {
      this.func_146283_a(Collections.singletonList(text3), x, y);
    }

    String text2 =
        this.machine.coffeeCacheAmount
            + "/"
            + this.machine.coffeeCacheMaxAmount
            + " "
            + StatCollector.translateToLocal("info." + ModUtil.MOD_ID_LOWER + ".gui.coffee");
    if (x >= guiLeft + 40 && y >= guiTop + 25 && x <= guiLeft + 49 && y <= guiTop + 56) {
      this.func_146283_a(Collections.singletonList(text2), x, y);
    }
  }
  @SuppressWarnings("unchecked")
  @Before
  public void setUp() throws Exception {
    messageConverter = createMock(HttpMessageConverter.class);
    expect(messageConverter.getSupportedMediaTypes())
        .andReturn(Collections.singletonList(MediaType.TEXT_PLAIN));
    replay(messageConverter);

    processor =
        new RequestResponseBodyMethodProcessor(
            Collections.<HttpMessageConverter<?>>singletonList(messageConverter));
    reset(messageConverter);

    Method handle = getClass().getMethod("handle1", String.class, Integer.TYPE);
    paramRequestBodyString = new MethodParameter(handle, 0);
    paramInt = new MethodParameter(handle, 1);
    returnTypeString = new MethodParameter(handle, -1);
    returnTypeInt = new MethodParameter(getClass().getMethod("handle2"), -1);
    returnTypeStringProduces = new MethodParameter(getClass().getMethod("handle3"), -1);
    paramValidBean = new MethodParameter(getClass().getMethod("handle4", SimpleBean.class), 0);

    mavContainer = new ModelAndViewContainer();

    servletRequest = new MockHttpServletRequest();
    servletResponse = new MockHttpServletResponse();
    webRequest = new ServletWebRequest(servletRequest, servletResponse);
  }
  /** Test for creating zobjects with relationships */
  @Test
  @SuppressWarnings("serial")
  public void createAndDeleteRelated() throws Exception {
    SaveResult saveResult =
        module.create(ZObjectType.Account, Collections.singletonList(testAccount())).get(0);
    assertTrue(saveResult.isSuccess());

    final String accountId = saveResult.getId();
    try {
      SaveResult result =
          module
              .create(
                  ZObjectType.Contact,
                  Collections.<Map<String, Object>>singletonList(
                      new HashMap<String, Object>() {
                        {
                          put("Country", "US");
                          put("FirstName", "John");
                          put("LastName", "Doe");
                          put("AccountId", accountId);
                        }
                      }))
              .get(0);
      assertTrue(result.isSuccess());

      DeleteResult deleteResult =
          module.delete(ZObjectType.Contact, Arrays.asList(result.getId())).get(0);
      assertTrue(deleteResult.isSuccess());
    } finally {
      module.delete(ZObjectType.Account, Arrays.asList(accountId)).get(0);
    }
  }
  public void testConfigureRequestGoals() throws Exception {
    Properties props = new Properties();
    InvokerProperties facade = new InvokerProperties(props);

    InvocationRequest request = new DefaultInvocationRequest();

    request.setGoals(Collections.singletonList("test"));
    facade.configureInvocation(request, 0);
    assertEquals(Collections.singletonList("test"), request.getGoals());

    props.setProperty("invoker.goals", "verify");
    facade.configureInvocation(request, 0);
    assertEquals(Collections.singletonList("verify"), request.getGoals());

    props.setProperty("invoker.goals", "   ");
    facade.configureInvocation(request, 0);
    assertEquals(Arrays.asList(new String[0]), request.getGoals());

    props.setProperty("invoker.goals", "  clean , test   verify  ");
    facade.configureInvocation(request, 0);
    assertEquals(Arrays.asList(new String[] {"clean", "test", "verify"}), request.getGoals());

    props.setProperty("invoker.goals", "");
    facade.configureInvocation(request, 0);
    assertEquals(Arrays.asList(new String[0]), request.getGoals());
  }
  private static List<XmlElementDescriptor> computeRequiredSubTags(XmlElementsGroup group) {

    if (group.getMinOccurs() < 1) return Collections.emptyList();
    switch (group.getGroupType()) {
      case LEAF:
        XmlElementDescriptor descriptor = group.getLeafDescriptor();
        return descriptor == null
            ? Collections.<XmlElementDescriptor>emptyList()
            : Collections.singletonList(descriptor);
      case CHOICE:
        LinkedHashSet<XmlElementDescriptor> set = null;
        for (XmlElementsGroup subGroup : group.getSubGroups()) {
          List<XmlElementDescriptor> descriptors = computeRequiredSubTags(subGroup);
          if (set == null) {
            set = new LinkedHashSet<XmlElementDescriptor>(descriptors);
          } else {
            set.retainAll(descriptors);
          }
        }
        if (set == null || set.isEmpty()) {
          return Collections.singletonList(null); // placeholder for smart completion
        }
        return new ArrayList<XmlElementDescriptor>(set);

      default:
        ArrayList<XmlElementDescriptor> list = new ArrayList<XmlElementDescriptor>();
        for (XmlElementsGroup subGroup : group.getSubGroups()) {
          list.addAll(computeRequiredSubTags(subGroup));
        }
        return list;
    }
  }
 protected OutboundEndpoint createTestOutboundEndpoint(
     String uri,
     Filter filter,
     SecurityFilter securityFilter,
     Transformer transformer,
     Transformer responseTransformer,
     MessageExchangePattern exchangePattern,
     TransactionConfig txConfig)
     throws EndpointException, InitialisationException {
   EndpointURIEndpointBuilder endpointBuilder = new EndpointURIEndpointBuilder(uri, muleContext);
   if (filter != null) {
     endpointBuilder.addMessageProcessor(new MessageFilter(filter));
   }
   if (securityFilter != null) {
     endpointBuilder.addMessageProcessor(new SecurityFilterMessageProcessor(securityFilter));
   }
   if (transformer != null) {
     endpointBuilder.setMessageProcessors(
         Collections.<MessageProcessor>singletonList(transformer));
   }
   if (responseTransformer != null) {
     endpointBuilder.setResponseMessageProcessors(
         Collections.<MessageProcessor>singletonList(responseTransformer));
   }
   endpointBuilder.setExchangePattern(exchangePattern);
   endpointBuilder.setTransactionConfig(txConfig);
   customizeEndpointBuilder(endpointBuilder);
   return endpointBuilder.buildOutboundEndpoint();
 }
  public void testTwoPlatformsoverSameSDK() throws Exception {
    final File binDir = new File(getWorkDir(), "boot"); // NOI18N
    binDir.mkdir();
    final File jdocFile1 = new File(getWorkDir(), "jdoc1"); // NOI18N
    jdocFile1.mkdir();
    final File jdocFile2 = new File(getWorkDir(), "jdoc2"); // NOI18N
    jdocFile2.mkdir();
    JavaPlatformProviderImpl provider = Lookup.getDefault().lookup(JavaPlatformProviderImpl.class);
    final URL binRoot = Utilities.toURI(binDir).toURL();
    final ClassPath bootCp = ClassPathSupport.createClassPath(binRoot);
    final List<URL> javadoc1 = Collections.singletonList(Utilities.toURI(jdocFile1).toURL());
    final List<URL> javadoc2 = Collections.singletonList(Utilities.toURI(jdocFile2).toURL());
    final TestJavaPlatform platform1 = new TestJavaPlatform("platform1", bootCp); // NOI18N
    final TestJavaPlatform platform2 = new TestJavaPlatform("platform2", bootCp); // NOI18N
    platform2.setJavadoc(javadoc2);
    provider.addPlatform(platform1);
    provider.addPlatform(platform2);

    final JavadocForBinaryQuery.Result result1 = JavadocForBinaryQuery.findJavadoc(binRoot);
    assertEquals(javadoc2, Arrays.asList(result1.getRoots()));

    platform1.setJavadoc(javadoc1);
    assertEquals(javadoc1, Arrays.asList(result1.getRoots()));

    final JavadocForBinaryQuery.Result result2 = JavadocForBinaryQuery.findJavadoc(binRoot);
    assertEquals(javadoc1, Arrays.asList(result2.getRoots()));

    platform1.setJavadoc(Collections.<URL>emptyList());
    assertEquals(javadoc2, Arrays.asList(result1.getRoots()));
    assertEquals(javadoc2, Arrays.asList(result2.getRoots()));
  }
 private Optional<IdentifyResponse> detectedType(
     final String fileName, final ContentFileType fileType, final float confidence) {
   IdentifyResponse response =
       new IdentifyResponse(
           fileName, Collections.singletonList(fileType), Collections.singletonList(confidence));
   return Optional.of(response);
 }
Esempio n. 9
0
  @org.junit.Test
  public void testIdentityMappingRealmB2A() throws Exception {

    ClaimsManager claimsManager = new ClaimsManager();

    claimsManager.setIdentityMapper(new CustomIdentityMapper());

    RealmSupportClaimsHandler realmAHandler = new RealmSupportClaimsHandler();
    realmAHandler.setRealm("A");
    realmAHandler.setSupportedClaimTypes(Collections.singletonList(URI.create("Claim-A")));

    RealmSupportClaimsHandler realmBHandler = new RealmSupportClaimsHandler();
    realmBHandler.setRealm("B");
    realmBHandler.setSupportedClaimTypes(Collections.singletonList(URI.create("Claim-B")));

    RealmSupportClaimsHandler realmCHandler = new RealmSupportClaimsHandler();
    realmCHandler.setRealm("B");
    realmCHandler.setSupportedClaimTypes(Collections.singletonList(URI.create("Claim-C")));

    List<ClaimsHandler> claimHandlers = new ArrayList<ClaimsHandler>();
    claimHandlers.add(realmAHandler);
    claimHandlers.add(realmBHandler);
    claimHandlers.add(realmCHandler);
    claimsManager.setClaimHandlers(Collections.unmodifiableList(claimHandlers));

    ClaimCollection requestedClaims = createClaimCollection();

    ClaimsParameters parameters = new ClaimsParameters();
    parameters.setRealm("B");
    parameters.setPrincipal(new CustomTokenPrincipal("ALICE"));
    ProcessedClaimCollection claims =
        claimsManager.retrieveClaimValues(requestedClaims, parameters);
    Assert.assertEquals("Number of claims incorrect", 3, claims.size());
  }
  private Expression generateCopyExpression(
      DefinedParamType type,
      String inputParmId,
      int inputIndex,
      String outputParamId,
      int outputIndex) {
    // GOAL: ((InputSocket<Mat>) inputs[0]).getValue().assignTo(((OutputSocket<Mat>)
    // outputs[0]).getValue());
    final ClassOrInterfaceType outputType = new ClassOrInterfaceType("OutputSocket");
    final ClassOrInterfaceType inputType = new ClassOrInterfaceType("InputSocket");
    outputType.setTypeArgs(Collections.singletonList(type.getType()));
    inputType.setTypeArgs(Collections.singletonList(type.getType()));

    final MethodCallExpr copyExpression =
        new MethodCallExpr(
            getOrSetValueExpression(
                new EnclosedExpr(new CastExpr(inputType, arrayAccessExpr(inputParmId, inputIndex))),
                null),
            "assignTo",
            Collections.singletonList(
                getOrSetValueExpression(
                    new EnclosedExpr(
                        new CastExpr(outputType, arrayAccessExpr(outputParamId, outputIndex))),
                    null)));
    copyExpression.setComment(
        new BlockComment(
            " Sets the value of the input Mat to the output because this operation does not have a destination Mat. "));
    return copyExpression;
  }
Esempio n. 11
0
 private ExportTable convert(OutputDescription output) {
   assert output != null;
   BulkLoadExporterDescription desc = extract(output);
   DuplicateRecordCheck duplicate = desc.getDuplicateRecordCheck();
   if (duplicate == null) {
     return new ExportTable(
         desc.getModelType(),
         desc.getTableName(),
         desc.getColumnNames(),
         desc.getTargetColumnNames(),
         null,
         Collections.singletonList(getOutputLocation(output)));
   } else {
     return new ExportTable(
         desc.getModelType(),
         desc.getTableName(),
         desc.getColumnNames(),
         desc.getTargetColumnNames(),
         new DuplicateRecordErrorTable(
             duplicate.getTableName(),
             duplicate.getColumnNames(),
             duplicate.getCheckColumnNames(),
             duplicate.getErrorCodeColumnName(),
             duplicate.getErrorCodeValue()),
         Collections.singletonList(getOutputLocation(output)));
   }
 }
  @Override
  public List<Short> check(Environment env, Mutation mutation) {
    List<ColumnUpdate> updates = mutation.getUpdates();

    HashSet<String> ok = null;
    if (updates.size() > 1) ok = new HashSet<String>();

    VisibilityEvaluator ve = null;

    for (ColumnUpdate update : updates) {

      byte[] cv = update.getColumnVisibility();
      if (cv.length > 0) {
        String key = null;
        if (ok != null && ok.contains(key = new String(cv, UTF_8))) continue;

        try {

          if (ve == null) ve = new VisibilityEvaluator(env);

          if (!ve.evaluate(new ColumnVisibility(cv)))
            return Collections.singletonList(Short.valueOf((short) 2));

        } catch (BadArgumentException bae) {
          return Collections.singletonList(new Short((short) 1));
        } catch (VisibilityParseException e) {
          return Collections.singletonList(new Short((short) 1));
        }

        if (ok != null) ok.add(key);
      }
    }

    return null;
  }
  public void testMixedStrategyTableNoExist() throws Exception {

    String template = "SELECT #result('id' 'int') FROM SUS1";
    SQLTemplate query = new SQLTemplate(Object.class, template);
    DataMap map = node.getEntityResolver().getDataMap("sus-map");
    DataNode dataNode = createDataNode(map);
    int sizeDB = getNameTablesInDB(dataNode).size();
    MockOperationObserver observer = new MockOperationObserver();

    setStrategy(ThrowOnPartialOrCreateSchemaStrategy.class.getName(), dataNode);

    try {
      dataNode.performQueries(Collections.singletonList((Query) query), observer);
      Map<String, Boolean> nameTables = getNameTablesInDB(dataNode);
      assertTrue(nameTables.get("sus1") != null || nameTables.get("SUS1") != null);
      int sizeDB2 = getNameTablesInDB(dataNode).size();
      assertEquals(2, sizeDB2 - sizeDB);
      dataNode.performQueries(Collections.singletonList((Query) query), observer);
      int sizeDB3 = getNameTablesInDB(dataNode).size();
      assertEquals(sizeDB2, sizeDB3);
    } finally {
      DataNode dataNode2 = createDataNode(map);
      dataNode2.setSchemaUpdateStrategy(
          (SchemaUpdateStrategy)
              Class.forName(dataNode2.getSchemaUpdateStrategyName()).newInstance());
      dropTables(map, dataNode2, observer);
    }
    assertEquals(getNameTablesInDB(dataNode).size(), sizeDB);
  }
  @Test
  public void testWithAlgorithmOverrides() throws ResolverException {
    roleDesc
        .getKeyDescriptors()
        .add(buildKeyDescriptor(rsaCred1KeyName, UsageType.ENCRYPTION, rsaCred1.getPublicKey()));

    config2.setDataEncryptionAlgorithms(
        Collections.singletonList(EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES256));
    config2.setKeyTransportEncryptionAlgorithms(
        Collections.singletonList(EncryptionConstants.ALGO_ID_KEYTRANSPORT_RSA15));

    EncryptionParameters params = resolver.resolveSingle(criteriaSet);

    Assert.assertNotNull(params);
    Assert.assertEquals(
        params.getKeyTransportEncryptionCredential().getPublicKey(), rsaCred1.getPublicKey());
    Assert.assertEquals(
        params.getKeyTransportEncryptionAlgorithm(),
        EncryptionConstants.ALGO_ID_KEYTRANSPORT_RSA15);
    Assert.assertNotNull(params.getKeyTransportKeyInfoGenerator());

    Assert.assertNull(params.getDataEncryptionCredential());
    Assert.assertEquals(
        params.getDataEncryptionAlgorithm(), EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES256);
    Assert.assertNull(params.getDataKeyInfoGenerator());
  }
  /**
   * Adds the "new" coiDisclosureAttachment to the CoiDisclosure Document. Before adding this method
   * executes validation. If the validation fails the attachment is not added.
   */
  public void addNewCoiDisclosureAttachment() {
    this.refreshAttachmentReferences(
        Collections.singletonList(this.getNewCoiDisclosureAttachment()));
    this.syncNewFiles(Collections.singletonList(this.getNewCoiDisclosureAttachment()));

    final AddCoiDisclosureAttachmentRule rule = new AddCoiDisclosureAttachmentRuleImpl();
    final AddCoiDisclosureAttachmentEvent event =
        new AddCoiDisclosureAttachmentEvent(
            coiDisclosureForm.getDocument(), newCoiDisclosureAttachment);

    assignDocumentId(
        Collections.singletonList(this.getNewCoiDisclosureAttachment()),
        this.createTypeToMaxDocNumber(getCoiDisclosure().getCoiDisclosureAttachments()));
    if (rule.processAddCoiDisclosureAttachmentRules(event)) {
      this.newCoiDisclosureAttachment.setCoiDisclosureId(getCoiDisclosure().getCoiDisclosureId());
      newCoiDisclosureAttachment.setSequenceNumber(getCoiDisclosure().getSequenceNumber());
      newCoiDisclosureAttachment.setEventTypeCode(getCoiDisclosure().getEventTypeCode() + "");
      if (getCoiDisclosure().getCoiDisclProjects().size() > 0) {
        newCoiDisclosureAttachment.setProjectId(
            getCoiDisclosure().getCoiDisclProjects().get(0).getProjectId());
      }
      this.getCoiDisclosure().addAttachment(newCoiDisclosureAttachment);
      getBusinessObjectService().save(newCoiDisclosureAttachment);
      this.initCoiDisclosureAttachment();
    }
  }
 protected IRExpression pushOuterForOuterSymbol() {
   IRExpression root = pushOuter();
   IType currentClass = getGosuClass();
   while (currentClass instanceof IBlockClass) {
     currentClass = currentClass.getEnclosingType();
     IRMethod irMethod =
         IRMethodFactory.createIRMethod(
             currentClass,
             OUTER_ACCESS,
             currentClass.getEnclosingType(),
             new IType[] {currentClass},
             AccessibilityUtil.forOuterAccess(),
             true);
     root = callMethod(irMethod, null, Collections.singletonList(root));
   }
   IType outer = currentClass.getEnclosingType();
   while (outer instanceof IBlockClass) {
     IType enclosing = getRuntimeEnclosingType(outer);
     IRMethod irMethod =
         IRMethodFactory.createIRMethod(
             outer,
             OUTER_ACCESS,
             enclosing,
             new IType[] {outer},
             AccessibilityUtil.forOuterAccess(),
             true);
     root = callMethod(irMethod, null, Collections.singletonList(root));
     outer = enclosing;
   }
   return root;
 }
 public List<ApiObject> requestList(int method, ApiObject[] parameters) {
   try {
     switch (method) {
       case LIST_OPTION_GROUPS:
         return ApiObject.envelopeStringList(getOptionGroups());
       case LIST_OPTION_NAMES:
         return ApiObject.envelopeStringList(
             getOptionNames(((ApiObject.String) parameters[0]).Value));
       case LIST_BOOK_TAGS:
         return ApiObject.envelopeStringList(getBookTags());
       case LIST_ACTIONS:
         return ApiObject.envelopeStringList(listActions());
       case LIST_ACTION_NAMES:
         {
           final ArrayList<String> actions = new ArrayList<String>(parameters.length);
           for (ApiObject o : parameters) {
             actions.add(((ApiObject.String) o).Value);
           }
           return ApiObject.envelopeStringList(listActionNames(actions));
         }
       case LIST_ZONEMAPS:
         return ApiObject.envelopeStringList(listZoneMaps());
       case GET_PARAGRAPH_WORDS:
         return ApiObject.envelopeStringList(
             getParagraphWords(((ApiObject.Integer) parameters[0]).Value));
       case GET_PARAGRAPH_WORD_INDICES:
         return ApiObject.envelopeIntegerList(
             getParagraphWordIndices(((ApiObject.Integer) parameters[0]).Value));
       default:
         return Collections.<ApiObject>singletonList(unsupportedMethodError(method));
     }
   } catch (Throwable e) {
     return Collections.<ApiObject>singletonList(exceptionInMethodError(method, e));
   }
 }
  @Nullable
  public VcsCommittedViewAuxiliary createActions(
      final DecoratorManager manager, @Nullable final RepositoryLocation location) {
    final RootsAndBranches rootsAndBranches = new RootsAndBranches(myProject, manager, location);
    refreshMergeInfo(rootsAndBranches);

    final DefaultActionGroup popup = new DefaultActionGroup(myVcs.getDisplayName(), true);
    popup.add(rootsAndBranches.getIntegrateAction());
    popup.add(rootsAndBranches.getUndoIntegrateAction());
    popup.add(new ConfigureBranchesAction());

    final ShowHideMergePanel action =
        new ShowHideMergePanel(manager, rootsAndBranches.getStrategy());

    return new VcsCommittedViewAuxiliary(
        Collections.<AnAction>singletonList(popup),
        new Runnable() {
          public void run() {
            if (myMergeInfoUpdatesListener != null) {
              myMergeInfoUpdatesListener.removePanel(rootsAndBranches);
              rootsAndBranches.dispose();
            }
          }
        },
        Collections.<AnAction>singletonList(action));
  }
Esempio n. 19
0
  public static void convertFormToConfiguration(
      final StoredConfigurationImpl storedConfiguration,
      final Map<String, String> ldapForm,
      final Map<String, String> incomingLdapForm)
      throws PwmUnrecoverableException {
    {
      final String newLdapURI = getLdapUrlFromFormConfig(ldapForm);
      final StringArrayValue newValue = new StringArrayValue(Collections.singletonList(newLdapURI));
      storedConfiguration.writeSetting(
          PwmSetting.LDAP_SERVER_URLS, LDAP_PROFILE_KEY, newValue, null);
    }

    { // proxy/admin account
      final String ldapAdminDN = ldapForm.get(PARAM_LDAP_PROXY_DN);
      final String ldapAdminPW = ldapForm.get(PARAM_LDAP_PROXY_PW);
      storedConfiguration.writeSetting(
          PwmSetting.LDAP_PROXY_USER_DN, LDAP_PROFILE_KEY, new StringValue(ldapAdminDN), null);
      final PasswordValue passwordValue =
          new PasswordValue(PasswordData.forStringValue(ldapAdminPW));
      storedConfiguration.writeSetting(
          PwmSetting.LDAP_PROXY_USER_PASSWORD, LDAP_PROFILE_KEY, passwordValue, null);
    }

    storedConfiguration.writeSetting(
        PwmSetting.LDAP_CONTEXTLESS_ROOT,
        LDAP_PROFILE_KEY,
        new StringArrayValue(Collections.singletonList(ldapForm.get(PARAM_LDAP_CONTEXT))),
        null);

    {
      final String ldapContext = ldapForm.get(PARAM_LDAP_CONTEXT);
      storedConfiguration.writeSetting(
          PwmSetting.LDAP_CONTEXTLESS_ROOT,
          LDAP_PROFILE_KEY,
          new StringArrayValue(Collections.singletonList(ldapContext)),
          null);
    }

    {
      final String ldapTestUserDN = ldapForm.get(PARAM_LDAP_TEST_USER);
      storedConfiguration.writeSetting(
          PwmSetting.LDAP_TEST_USER_DN, LDAP_PROFILE_KEY, new StringValue(ldapTestUserDN), null);
    }

    { // set admin query
      final String groupDN = ldapForm.get(PARAM_LDAP_ADMIN_GROUP);
      final List<UserPermission> userPermissions =
          Collections.singletonList(
              new UserPermission(UserPermission.Type.ldapGroup, null, null, groupDN));
      storedConfiguration.writeSetting(
          PwmSetting.QUERY_MATCH_PWM_ADMIN, new UserPermissionValue(userPermissions), null);
    }

    // set context based on ldap dn
    if (incomingLdapForm.containsKey(PARAM_APP_SITEURL)) {
      ldapForm.put(PARAM_APP_SITEURL, incomingLdapForm.get(PARAM_APP_SITEURL));
    }
    storedConfiguration.writeSetting(
        PwmSetting.PWM_SITE_URL, new StringValue(ldapForm.get(PARAM_APP_SITEURL)), null);
  }
Esempio n. 20
0
 public static MutableSimpleModuleDeclaration declaration() {
   return new MutableSimpleModuleDeclaration()
       .setSimpleName(BinarySum.class.getSimpleName())
       .setPorts(
           Arrays.<MutablePort<?>>asList(
               new MutableInPort()
                   .setSimpleName("num1")
                   .setType(MutableDeclaredType.fromType(Integer.class)),
               new MutableInPort()
                   .setSimpleName("num2")
                   .setType(MutableDeclaredType.fromType(Integer.class)),
               new MutableOutPort()
                   .setSimpleName("result")
                   .setType(MutableDeclaredType.fromType(Integer.class))
                   .setDeclaredAnnotations(
                       Collections.singletonList(
                           new MutableAnnotation()
                               .setDeclaration(CloudKeeperSerialization.class.getName())
                               .setEntries(
                                   Collections.singletonList(
                                       new MutableAnnotationEntry()
                                           .setKey("value")
                                           .setValue(
                                               new String[] {
                                                 IntegerMarshaler.class.getName()
                                               })))))))
       .setDeclaredAnnotations(
           Collections.singletonList(
               MutableAnnotation.fromAnnotation(BinarySum.class.getAnnotation(Memory.class))));
 }
Esempio n. 21
0
  @Test
  public void canCreateEnumerationType() {
    MockitoAnnotations.initMocks(this);

    QName qName = QName.create("TestQName");
    SchemaPath schemaPath = SchemaPath.create(Collections.singletonList(qName), true);

    List<EnumTypeDefinition.EnumPair> listEnumPair = Collections.singletonList(enumPair);
    Optional<EnumTypeDefinition.EnumPair> defaultValue = Optional.of(enumPair);

    EnumerationType enumerationType =
        EnumerationType.create(schemaPath, listEnumPair, defaultValue);

    assertNotEquals("Description is not null", null, enumerationType.getDescription());
    assertEquals("QName", BaseTypes.ENUMERATION_QNAME, enumerationType.getQName());
    assertEquals("Should be empty string", "", enumerationType.getUnits());
    assertNotEquals("Description should not be null", null, enumerationType.toString());
    assertNotEquals("Reference is not null", null, enumerationType.getReference());
    assertEquals("BaseType should be null", null, enumerationType.getBaseType());
    assertEquals("Default value should be enumPair", enumPair, enumerationType.getDefaultValue());
    assertEquals("getPath should equal schemaPath", schemaPath, enumerationType.getPath());
    assertEquals("Status should be CURRENT", Status.CURRENT, enumerationType.getStatus());
    assertEquals(
        "Should be empty list", Collections.EMPTY_LIST, enumerationType.getUnknownSchemaNodes());
    assertEquals("Values should be [enumPair]", listEnumPair, enumerationType.getValues());

    assertEquals(
        "Hash code of enumerationType should be equal",
        enumerationType.hashCode(),
        enumerationType.hashCode());
    assertNotEquals("EnumerationType shouldn't equal to null", null, enumerationType);
    assertEquals("EnumerationType should equals to itself", enumerationType, enumerationType);
    assertNotEquals(
        "EnumerationType shouldn't equal to object of other type", "str", enumerationType);
  }
  private void setRandomTripMode(final Trip trip, final Plan plan, boolean ffcard, boolean owcard) {

    // carsharing is the new trip
    if (possibleModes.length == 2) {
      if (rng.nextBoolean()) {
        if (owcard)
          TripRouter.insertTrip(
              plan,
              trip.getOriginActivity(),
              Collections.singletonList(new LegImpl("onewaycarsharing")),
              trip.getDestinationActivity());
      } else {
        if (ffcard)
          TripRouter.insertTrip(
              plan,
              trip.getOriginActivity(),
              Collections.singletonList(new LegImpl("freefloating")),
              trip.getDestinationActivity());
      }
    } else if (possibleModes.length == 1 && possibleModes[0] != null) {
      if ((possibleModes[0].equals("freefloating") && ffcard)
          || (possibleModes[0].equals("onewaycarsharing") && owcard))
        TripRouter.insertTrip(
            plan,
            trip.getOriginActivity(),
            Collections.singletonList(new LegImpl(possibleModes[0])),
            trip.getDestinationActivity());
    } else
      TripRouter.insertTrip(
          plan, trip.getOriginActivity(), trip.getTripElements(), trip.getDestinationActivity());
  }
Esempio n. 23
0
  private SyndFeed createFeed() {

    SyndFeed feed = new SyndFeedImpl();

    SyndPerson auteur = new SyndPersonImpl();
    auteur.setName("Gildas Cuisinier");
    auteur.setEmail("*****@*****.**");

    feed.setTitle("RSS Veille Techno");
    feed.setAuthors(Collections.singletonList(auteur));
    feed.setDescription("RSS d'exemple !");
    feed.setLink("http://svn.cyg.be/");
    feed.setPublishedDate(new Date());
    feed.setLanguage("fr");

    SyndEntry entry = new SyndEntryImpl();
    entry.setTitle("Ajout du projet Rome sur le SVN");
    entry.setLink("https://rome.dev.java.net/");

    SyndContent description = new SyndContentImpl();
    description.setValue("Ajout d'un projet Rome sur le SVN afin de voir comment creer un RSS");
    description.setType("text");
    entry.setDescription(description);
    entry.setAuthors(Collections.singletonList(auteur));

    feed.getEntries().add(entry);

    return feed;
  }
  /**
   * Test method for {@link
   * net.sf.hajdbc.balancer.AbstractBalancer#containsAll(java.util.Collection)}.
   */
  @Test
  public void containsAll() {
    Balancer<Void, MockDatabase> balancer =
        this.factory.createBalancer(Collections.<MockDatabase>emptySet());

    assertTrue(balancer.containsAll(Collections.emptyList()));
    assertFalse(balancer.containsAll(Collections.singletonList(this.databases[0])));
    assertFalse(balancer.containsAll(Arrays.asList(this.databases[0], this.databases[1])));
    assertFalse(balancer.containsAll(Arrays.asList(this.databases)));

    balancer = this.factory.createBalancer(Collections.singleton(this.databases[0]));

    assertTrue(balancer.containsAll(Collections.emptyList()));
    assertTrue(balancer.containsAll(Collections.singletonList(this.databases[0])));
    assertFalse(balancer.containsAll(Arrays.asList(this.databases[0], this.databases[1])));
    assertFalse(balancer.containsAll(Arrays.asList(this.databases)));

    balancer =
        this.factory.createBalancer(
            new HashSet<MockDatabase>(Arrays.asList(this.databases[0], this.databases[1])));

    assertTrue(balancer.containsAll(Collections.emptyList()));
    assertTrue(balancer.containsAll(Collections.singletonList(this.databases[0])));
    assertTrue(balancer.containsAll(Arrays.asList(this.databases[0], this.databases[1])));
    assertFalse(balancer.containsAll(Arrays.asList(this.databases)));

    balancer =
        this.factory.createBalancer(new HashSet<MockDatabase>(Arrays.asList(this.databases)));

    assertTrue(balancer.containsAll(Collections.emptyList()));
    assertTrue(balancer.containsAll(Collections.singletonList(this.databases[0])));
    assertTrue(balancer.containsAll(Arrays.asList(this.databases[0], this.databases[1])));
    assertTrue(balancer.containsAll(Arrays.asList(this.databases)));
  }
Esempio n. 25
0
 public void testURIIllegal() {
   try {
     new DefaultGraphInfo(null, MediaType.XTM);
     fail("Expected an exception for URI == null");
   } catch (IllegalArgumentException ex) {
     // noop.
   }
   try {
     new DefaultGraphInfo(null, MediaType.XTM, -1);
     fail("Expected an exception for URI == null");
   } catch (IllegalArgumentException ex) {
     // noop.
   }
   try {
     new DefaultGraphInfo(null, Collections.singletonList(MediaType.XTM));
     fail("Expected an exception for URI == null");
   } catch (IllegalArgumentException ex) {
     // noop.
   }
   try {
     new DefaultGraphInfo(null, Collections.singletonList(MediaType.XTM), -1);
     fail("Expected an exception for URI == null");
   } catch (IllegalArgumentException ex) {
     // noop.
   }
 }
  @Test
  public void testLabeledNetworkAttachedToThisInterfaceWhenNetworkIsAssignedToWrongInterface()
      throws Exception {
    String networkName = "networkA";
    Network network = new Network();
    network.setName(networkName);

    VdsNetworkInterface nicToWhichLabeledNetworkShouldBeAttached =
        createVdsNetworkInterfaceWithName("nicA");
    VdsNetworkInterface nicImproperlyAssignedToNetwork = createVdsNetworkInterfaceWithName("nicB");
    nicImproperlyAssignedToNetwork.setNetworkName(networkName);

    List<VdsNetworkInterface> hostInterfaces =
        Arrays.asList(nicToWhichLabeledNetworkShouldBeAttached, nicImproperlyAssignedToNetwork);

    HostInterfaceValidator validator =
        new HostInterfaceValidator(nicToWhichLabeledNetworkShouldBeAttached);
    assertThat(
        validator.networksAreAttachedToThisInterface(
            hostInterfaces, Collections.singletonList(network)),
        failsWith(
            EngineMessage.LABELED_NETWORK_ATTACHED_TO_WRONG_INTERFACE,
            ReplacementUtils.replaceWith(
                HostInterfaceValidator.VAR_ASSIGNED_NETWORKS,
                Collections.singletonList(networkName))));
  }
Esempio n. 27
0
  @Override
  public List<Object> apply(List<Object> arguments) {
    Preconditions.checkArguments("string.match", arguments, expectedTypes);

    if (LuaType.getTypeOf(arguments.get(0)) == LuaType.NUMBER) {
      arguments.set(0, ToString.toString(arguments.get(0)));
      return apply(arguments);
    }

    if (LuaType.getTypeOf(arguments.get(1)) == LuaType.NUMBER) {
      arguments.set(1, ToString.toString(arguments.get(1)));
      return apply(arguments);
    }

    if (((String) arguments.get(1)).isEmpty()) {
      return Collections.singletonList(arguments.get(0));
    }

    Object[] index = new Find().apply(arguments).toArray();

    if (index[0] == null) {
      return Collections.singletonList((Object) null);
    }

    return Collections.singletonList(
        (Object)
            ((String) arguments.get(0))
                .substring(((Double) index[0]).intValue() - 1, ((Double) index[1]).intValue()));
  }
Esempio n. 28
0
    static List<Range> mergeRanges(final List<Range> ranges) {
      if (ranges.isEmpty()) {
        return Collections.emptyList();
      }

      final List<Range> result = new ArrayList<Range>();
      final Iterator<Range> it = ranges.iterator();

      Range leftRange = it.next();
      List<Range> merged = Collections.singletonList(leftRange);
      while (it.hasNext()) {
        // merge ranges as long as they're adjacent/overlapping
        while (merged.size() == 1 && it.hasNext()) {
          leftRange = merged.get(0);
          Range rightRange = it.next();
          merged = mergeRanges(leftRange, rightRange);
        }
        // when ranges weren't merge-able, add all but last, merge against last
        if (merged.size() > 1) {
          result.addAll(merged.subList(0, merged.size() - 1));
          merged = Collections.singletonList(merged.get(merged.size() - 1));
        }
      }
      result.addAll(merged);
      return result;
    }
  @Nullable
  private static List<String> getTasksTarget(Location location) {
    if (location instanceof GradleTaskLocation) {
      return ((GradleTaskLocation) location).getTasks();
    }

    PsiElement parent = location.getPsiElement();
    while (parent.getParent() != null && !(parent.getParent() instanceof PsiFile)) {
      parent = parent.getParent();
    }

    if (isCreateTaskMethod(parent)) {
      final GrExpression[] arguments = ((GrMethodCallExpression) parent).getExpressionArguments();
      if (arguments.length > 0
          && arguments[0] instanceof GrLiteral
          && ((GrLiteral) arguments[0]).getValue() instanceof String) {
        return Collections.singletonList((String) ((GrLiteral) arguments[0]).getValue());
      }
    } else if (parent instanceof GrApplicationStatement) {
      PsiElement shiftExpression = parent.getChildren()[1].getChildren()[0];
      if (shiftExpression instanceof GrShiftExpressionImpl) {
        PsiElement shiftiesChild = shiftExpression.getChildren()[0];
        if (shiftiesChild instanceof GrReferenceExpression) {
          return Collections.singletonList(shiftiesChild.getText());
        } else if (shiftiesChild instanceof GrMethodCallExpression) {
          return Collections.singletonList(shiftiesChild.getChildren()[0].getText());
        }
      } else if (shiftExpression instanceof GrMethodCallExpression) {
        return Collections.singletonList(shiftExpression.getChildren()[0].getText());
      }
    }

    return null;
  }
  @Before
  public void setUp() throws Exception {
    final CatalogManager catalogManager = CatalogManager.getInstance();

    final Catalog catalog = catalogManager.createCatalog("PartOfTest");
    srcCatalogVersion = catalogManager.createCatalogVersion(catalog, "ver1", null);
    srcCatalogVersion.setLanguages(Collections.singletonList(getOrCreateLanguage("de")));
    tgtCatalogVersion = catalogManager.createCatalogVersion(catalog, "ver2", null);
    tgtCatalogVersion.setLanguages(Collections.singletonList(getOrCreateLanguage("de")));

    LOG.info("Creating  product");
    final ComposedType composedType = TypeManager.getInstance().getComposedType(Product.class);

    final Product productOne = createProduct("Product-One", composedType);
    final Product productTwo = createProduct("Product-Two", composedType);

    LOG.info("Creating  product reference ");

    catalogManager.createProductReference("foo", productOne, productTwo, Integer.valueOf(1));

    LOG.info("Done catalog creation.");

    final Europe1PriceFactory europe1 = Europe1PriceFactory.getInstance();
    final Currency currency = C2LManager.getInstance().createCurrency("europe1/dr");
    final Unit unit = ProductManager.getInstance().createUnit(null, "europe1/u", "typ");
    final EnumerationValue enumValue =
        EnumerationManager.getInstance()
            .createEnumerationValue(Europe1Constants.TYPES.DISCOUNT_USER_GROUP, "test");

    priceRowSpy =
        Mockito.spy(
            europe1.createPriceRow(
                productTwo, null, null, enumValue, 0, currency, unit, 1, true, null, 0));
  }