Exemplo n.º 1
0
  @Test
  public void testBatchWithoutProject() throws Exception {
    Event.EventContext api = Event.EventContext.apiKey(apiKeys.writeKey());
    ImmutableMap<String, Object> props =
        ImmutableMap.of("test0", "test", "test1", ImmutableList.of("test"), "test2", false);
    byte[] bytes =
        mapper.writeValueAsBytes(
            ImmutableMap.of(
                "api",
                api,
                "events",
                ImmutableList.of(
                    ImmutableMap.of("collection", "test", "properties", props),
                    ImmutableMap.of("collection", "test", "properties", props))));

    EventList events = mapper.readValue(bytes, EventList.class);

    assertEquals("test", events.project);
    assertEquals(api, events.api);

    for (Event event : events.events) {
      assertEquals("test", event.collection());

      assertEquals(eventBuilder.createEvent("test", props).properties(), event.properties());
    }
  }
Exemplo n.º 2
0
  @Test
  public void testHttp() throws Exception {
    // Verify that http_proxy and HTTP_PROXY are used for http requests
    assertExpectedProxyConfig(
        proxyConfigFromEnv(
                "http",
                ImmutableMap.of(
                    "http_proxy", PROXY_URL,
                    "HTTP_PROXY", "http://ignore",
                    "https_proxy", "http://ignore",
                    "HTTPS_PROXY", "http://ignore"))
            .get());
    assertExpectedProxyConfig(
        proxyConfigFromEnv(
                "http",
                ImmutableMap.of(
                    "HTTP_PROXY", PROXY_URL,
                    "https_proxy", "http://ignore",
                    "HTTPS_PROXY", "http://ignore"))
            .get());

    // Verify that https_proxy and HTTPS_PROXY are not used for http requests
    assertThat(
        proxyConfigFromEnv(
            "http", ImmutableMap.of("https_proxy", PROXY_URL, "HTTPS_PROXY", "http://ignore")),
        is(Optional.absent()));

    assertThat(
        proxyConfigFromEnv("http", ImmutableMap.of("HTTPS_PROXY", PROXY_URL)),
        is(Optional.absent()));
  }
  public void test_presentValue() {
    Currency ccy1 = TRADE.getProduct().getNonDeliverableCurrency();
    Currency ccy2 = TRADE.getProduct().getSettlementCurrency();
    LocalDate valDate = TRADE.getProduct().getPaymentDate().plusDays(7);

    FunctionConfig<FxNdfTrade> config =
        FxNdfFunctionGroups.discounting().functionConfig(TRADE, Measure.PRESENT_VALUE).get();
    CalculationSingleFunction<FxNdfTrade, ?> function = config.createFunction();
    FunctionRequirements reqs = function.requirements(TRADE);
    assertThat(reqs.getOutputCurrencies()).containsOnly(ccy1, ccy2);
    assertThat(reqs.getSingleValueRequirements())
        .isEqualTo(ImmutableSet.of(DiscountCurveKey.of(ccy1), DiscountCurveKey.of(ccy2)));
    assertThat(reqs.getTimeSeriesRequirements()).isEqualTo(ImmutableSet.of());
    assertThat(function.defaultReportingCurrency(TRADE)).hasValue(GBP);
    DiscountFactors df1 =
        SimpleDiscountFactors.of(
            ccy1, valDate, ConstantNodalCurve.of(Curves.discountFactors("Test", ACT_360), 0.99));
    DiscountFactors df2 =
        SimpleDiscountFactors.of(
            ccy2, valDate, ConstantNodalCurve.of(Curves.discountFactors("Test", ACT_360), 0.99));
    TestMarketDataMap md =
        new TestMarketDataMap(
            valDate,
            ImmutableMap.of(DiscountCurveKey.of(ccy1), df1, DiscountCurveKey.of(ccy2), df2),
            ImmutableMap.of());
    assertThat(function.execute(TRADE, md))
        .isEqualTo(FxConvertibleList.of(ImmutableList.of(CurrencyAmount.zero(GBP))));
  }
Exemplo n.º 4
0
 private ImmutableMap<ConfigurationKeys, String> getPushParameters() {
   ImmutableMap<Factory.ConfigurationKeys, String> response = null;
   if (Push.PUSH_SANDBOX_ENABLE.getValueAsBoolean()) {
     response =
         ImmutableMap.of(
             ConfigurationKeys.ANDROID_API_KEY,
                 "" + Push.SANDBOX_ANDROID_API_KEY.getValueAsString(),
             ConfigurationKeys.APPLE_TIMEOUT, "" + Push.PUSH_APPLE_TIMEOUT.getValueAsString(),
             ConfigurationKeys.IOS_CERTIFICATE,
                 "" + Push.SANDBOX_IOS_CERTIFICATE.getValueAsString(),
             ConfigurationKeys.IOS_CERTIFICATE_PASSWORD,
                 "" + Push.SANDBOX_IOS_CERTIFICATE_PASSWORD.getValueAsString(),
             ConfigurationKeys.IOS_SANDBOX, "" + Boolean.TRUE.toString());
   } else {
     response =
         ImmutableMap.of(
             ConfigurationKeys.ANDROID_API_KEY,
                 "" + Push.PRODUCTION_ANDROID_API_KEY.getValueAsString(),
             ConfigurationKeys.APPLE_TIMEOUT, "" + Push.PUSH_APPLE_TIMEOUT.getValueAsString(),
             ConfigurationKeys.IOS_CERTIFICATE,
                 "" + Push.PRODUCTION_IOS_CERTIFICATE.getValueAsString(),
             ConfigurationKeys.IOS_CERTIFICATE_PASSWORD,
                 "" + Push.PRODUCTION_IOS_CERTIFICATE_PASSWORD.getValueAsString(),
             ConfigurationKeys.IOS_SANDBOX, "" + Boolean.FALSE.toString());
   }
   return response;
 }
Exemplo n.º 5
0
  public static LocalQueryRunner createLocalQueryRunner(ExecutorService executor) {
    ConnectorSession session =
        new ConnectorSession(
            "user", "test", "default", "default", UTC_KEY, Locale.ENGLISH, null, null);
    LocalQueryRunner localQueryRunner = new LocalQueryRunner(session, executor);

    // add tpch
    InMemoryNodeManager nodeManager = localQueryRunner.getNodeManager();
    localQueryRunner.createCatalog(
        "tpch", new TpchConnectorFactory(nodeManager, 1), ImmutableMap.<String, String>of());

    // add raptor
    RaptorConnectorFactory raptorConnectorFactory =
        createRaptorConnectorFactory(TPCH_CACHE_DIR, nodeManager);
    localQueryRunner.createCatalog(
        "default", raptorConnectorFactory, ImmutableMap.<String, String>of());

    MetadataManager metadata = localQueryRunner.getMetadata();
    if (!metadata
        .getTableHandle(session, new QualifiedTableName("default", "default", "orders"))
        .isPresent()) {
      localQueryRunner.execute("CREATE TABLE orders AS SELECT * FROM tpch.sf1.orders");
    }
    if (!metadata
        .getTableHandle(session, new QualifiedTableName("default", "default", "lineitem"))
        .isPresent()) {
      localQueryRunner.execute("CREATE TABLE lineitem AS SELECT * FROM tpch.sf1.lineitem");
    }
    return localQueryRunner;
  }
Exemplo n.º 6
0
 @ResponseBody
 @RequestMapping(value = "/delete", method = RequestMethod.POST)
 public ImmutableMap<String, String> linkDelete(Long[] linkIds, HttpSession session) {
   try {
     if (linkIds == null || linkIds.length == 0) {
       LOGGER.warn("要删除链接的ID为空!");
       return ImmutableMap.of("status", "0", "message", getMessage("link.deletefailed.message"));
     }
     List<Link> links = linkService.findAll(linkIds);
     String realPath = session.getServletContext().getRealPath("");
     List<File> deleteFiles = Lists.newArrayList();
     File deleteFile;
     for (Link link : links) {
       if (link.getLinkPic() == null || "".equals(link.getLinkPic())) continue;
       deleteFile = new File(realPath + link.getLinkPic());
       deleteFiles.add(deleteFile);
     }
     linkService.deleteInBatch(links);
     deleteLinkRes(deleteFiles);
   } catch (Exception e) {
     LOGGER.error("链接信息删除失败,失败原因:{}", e.getMessage());
     return ImmutableMap.of("status", "0", "message", getMessage("link.deletefailed.message"));
   }
   LOGGER.info("链接信息删除成功,ID为{}", StringUtils.join(linkIds, ","));
   return ImmutableMap.of("status", "1", "message", getMessage("link.deletesuccess.message"));
 }
Exemplo n.º 7
0
  @Test
  public void test7() {
    // Subscribers(guid1)/accounts(acc1)/subscribers(guid1)/preferences

    SIGPathSegment preferences = SIGPathSegment.newSegment("Preferences");

    GenericKey guid1 = newSubscriberKey();
    guid1.inferValues(ImmutableMap.of("guid", "guid1"));
    SIGPathSegment subscriber2 = SIGPathSegment.newSegment("Subscribers", guid1);

    GenericKey acc1 = newAccountKey();
    acc1.inferValues(ImmutableMap.of("accId", "acc1"));
    SIGPathSegment accounts = SIGPathSegment.newSegment("Accounts", acc1);

    SIGPathSegment subscriber1 = SIGPathSegment.newSegment("Subscribers", guid1);
    preferences.setPrev(subscriber2);
    subscriber2.setPrev(accounts);
    accounts.setPrev(subscriber1);

    SIGSegmentExecutor accountsExecutor = SIGSegmentExecutor.newExecutor(gateway, preferences);
    @SuppressWarnings("unchecked")
    Map<GenericKey, GenericData> result = (Map<GenericKey, GenericData>) accountsExecutor.execute();
    assertNotNull(result);
    GenericData obj = (GenericData) result.values().iterator().next();
    assertEquals("off", obj.get("pin_flag"));
  }
  @Test
  public void ruleKeyChangesIfInputContentsFromPathSourcePathInRuleKeyAppendableChanges() {
    BuildRuleResolver resolver =
        new BuildRuleResolver(TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer());
    SourcePathResolver pathResolver = new SourcePathResolver(resolver);
    final FakeProjectFilesystem filesystem = new FakeProjectFilesystem();
    final Path output = Paths.get("output");

    BuildRuleParams params =
        new FakeBuildRuleParamsBuilder("//:rule").setProjectFilesystem(filesystem).build();
    BuildRule rule =
        new NoopBuildRule(params, pathResolver) {
          @AddToRuleKey
          RuleKeyAppendableWithInput input =
              new RuleKeyAppendableWithInput(new PathSourcePath(filesystem, output));
        };

    // Build a rule key with a particular hash set for the output for the above rule.
    FakeFileHashCache hashCache =
        new FakeFileHashCache(ImmutableMap.of(filesystem.resolve(output), HashCode.fromInt(0)));

    RuleKey inputKey1 = new InputBasedRuleKeyBuilderFactory(0, hashCache, pathResolver).build(rule);

    // Now, build a rule key with a different hash for the output for the above rule.
    hashCache =
        new FakeFileHashCache(ImmutableMap.of(filesystem.resolve(output), HashCode.fromInt(1)));

    RuleKey inputKey2 = new InputBasedRuleKeyBuilderFactory(0, hashCache, pathResolver).build(rule);

    assertThat(inputKey1, Matchers.not(Matchers.equalTo(inputKey2)));
  }
  @Test
  public void ruleKeyChangesIfInputContentsFromPathSourceChanges() throws Exception {
    BuildRuleResolver resolver =
        new BuildRuleResolver(TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer());
    SourcePathResolver pathResolver = new SourcePathResolver(resolver);
    FakeProjectFilesystem filesystem = new FakeProjectFilesystem();
    Path output = Paths.get("output");

    BuildRule rule =
        ExportFileBuilder.newExportFileBuilder(BuildTargetFactory.newInstance("//:rule"))
            .setOut("out")
            .setSrc(new PathSourcePath(filesystem, output))
            .build(resolver, filesystem);

    // Build a rule key with a particular hash set for the output for the above rule.
    FakeFileHashCache hashCache =
        new FakeFileHashCache(ImmutableMap.of(filesystem.resolve(output), HashCode.fromInt(0)));

    RuleKey inputKey1 = new InputBasedRuleKeyBuilderFactory(0, hashCache, pathResolver).build(rule);

    // Now, build a rule key with a different hash for the output for the above rule.
    hashCache =
        new FakeFileHashCache(ImmutableMap.of(filesystem.resolve(output), HashCode.fromInt(1)));

    RuleKey inputKey2 = new InputBasedRuleKeyBuilderFactory(0, hashCache, pathResolver).build(rule);

    assertThat(inputKey1, Matchers.not(Matchers.equalTo(inputKey2)));
  }
 @Override
 public Map<String, Org> get() {
   return ImmutableMap.<String, Org>of(
       "org",
       new TerremarkOrgImpl(
           "org",
           null,
           URI.create("https://vcloud.safesecureweb.com/api/v0.8/org/1"),
           null,
           ImmutableMap.<String, ReferenceType>of(
               "catalog",
               new ReferenceTypeImpl(
                   "catalog",
                   TerremarkVCloudExpressMediaType.CATALOG_XML,
                   URI.create("https://vcloud.safesecureweb.com/api/v0.8/catalog/1"))),
           ImmutableMap.<String, ReferenceType>of(
               "vdc",
               new ReferenceTypeImpl(
                   "vdc",
                   TerremarkVCloudExpressMediaType.VDC_XML,
                   URI.create("https://vcloud.safesecureweb.com/api/v0.8/vdc/1"))),
           ImmutableMap.<String, ReferenceType>of(),
           new ReferenceTypeImpl(
               "tasksList",
               TerremarkVCloudExpressMediaType.TASKSLIST_XML,
               URI.create("https://vcloud.safesecureweb.com/api/v0.8/tasksList/1")),
           new ReferenceTypeImpl(
               "keysList",
               TerremarkVCloudExpressMediaType.KEYSLIST_XML,
               URI.create("https://vcloud.safesecureweb.com/api/v0.8/keysList/1"))));
 }
 /** Matches the contents of instances-response.json */
 private List<InstanceInfo> getExpectedInstances() {
   return ImmutableList.of(
       new InstanceInfo(
           "10.1.100.78",
           "analytics-service",
           60000,
           false,
           "2014-02-05T17:05:39.000Z",
           "2014-02-05T18:46:48.000Z",
           ImmutableMap.of(
               "ami-id",
               "ami-133cb31d",
               "availability-zone",
               "us-east-1d",
               "local-ipv4",
               "10.1.100.78",
               "instance-type",
               "m1.small")),
       new InstanceInfo(
           "10.1.100.79",
           "analytics-service",
           50000,
           true,
           "2014-03-05T17:05:39.000Z",
           "2014-03-05T18:46:48.000Z",
           ImmutableMap.of(
               "ami-id",
               "ami-133cb31d",
               "availability-zone",
               "us-east-1d",
               "local-ipv4",
               "10.1.100.79",
               "instance-type",
               "m1.small")));
 }
Exemplo n.º 12
0
 /**
  * @param params
  * @param request
  * @param response
  * @return
  * @throws RepositoryException
  * @throws JCRNodeFactoryServiceException
  * @throws IOException
  */
 private Map<String, Object> doRequestConnect(
     FriendsParams params, HttpServletRequest request, HttpServletResponse response)
     throws JCRNodeFactoryServiceException, RepositoryException, IOException {
   FriendsBean myFriends = friendsResolverService.resolve(params.uuid);
   FriendsBean friendFriends = friendsResolverService.resolve(params.friendUuid);
   if (myFriends.hasFriend(params.friendUuid) || friendFriends.hasFriend(params.uuid)) {
     throw new RestServiceFaultException(
         HttpServletResponse.SC_CONFLICT,
         "There is already a connection invited, pending or accepted ");
   }
   FriendBean friend = new FriendBean(params.uuid, params.friendUuid, FriendStatus.PENDING);
   FriendBean me = new FriendBean(params.friendUuid, params.uuid, FriendStatus.INVITED);
   if (!StringUtils.isEmpty(params.type)) {
     me.setProperties(ImmutableMap.of("type", params.type, "message", params.message));
     friend.setProperties(ImmutableMap.of("type", params.type, "message", params.message));
   }
   myFriends.addFriend(friend);
   friendFriends.addFriend(me);
   authzResolverService.setRequestGrant("Saving Request Connect");
   try {
     myFriends.save();
     friendFriends.save();
     jcrService.getSession().save();
   } finally {
     authzResolverService.clearRequestGrant();
   }
   return OK;
 }
Exemplo n.º 13
0
  @Test
  public void create() throws Exception {
    Map<String, String> attrs = ImmutableMap.of("x", "X");
    Map<String, String> attrsToSave =
        ImmutableMap.of(
            "x", "X",
            "_accessedAt", "2",
            "_createdAt", "1",
            "_savedAt", "3");
    new MockUnit(JedisPool.class, Session.class)
        .expect(
            unit -> {
              Session session = unit.get(Session.class);
              expect(session.id()).andReturn("1234");
              expect(session.attributes()).andReturn(attrs);
              expect(session.createdAt()).andReturn(1L);
              expect(session.accessedAt()).andReturn(2L);
              expect(session.savedAt()).andReturn(3L);
            })
        .expect(
            unit -> {
              Jedis jedis = unit.mock(Jedis.class);
              expect(jedis.hmset("sessions:1234", attrsToSave)).andReturn("sessions:1234");
              expect(jedis.expire("sessions:1234", 1800)).andReturn(1L);
              jedis.close();

              JedisPool pool = unit.get(JedisPool.class);
              expect(pool.getResource()).andReturn(jedis);
            })
        .run(
            unit -> {
              new RedisSessionStore(unit.get(JedisPool.class), "sessions", "30m")
                  .create(unit.get(Session.class));
            });
  }
Exemplo n.º 14
0
 @Override
 public void bindToRequest(HttpRequest request, Object toBind) {
   checkArgument(toBind instanceof String, "this binder is only valid for Strings!");
   super.bindToRequest(
       request,
       ImmutableMap.of("server", ImmutableMap.of("adminPass", checkNotNull(toBind, "adminPass"))));
 }
Exemplo n.º 15
0
  @Test
  public void structuredAndUnstructuredOptions() throws Exception {
    // From https://developers.google.com/protocol-buffers/docs/proto#options
    Schema schema =
        new SchemaBuilder()
            .add(
                "foo.proto",
                ""
                    + "import \"google/protobuf/descriptor.proto\";\n"
                    + "message FooOptions {\n"
                    + "  optional int32 opt1 = 1;\n"
                    + "  optional string opt2 = 2;\n"
                    + "}\n"
                    + "\n"
                    + "extend google.protobuf.FieldOptions {\n"
                    + "  optional FooOptions foo_options = 1234;\n"
                    + "}\n"
                    + "\n"
                    + "message Bar {\n"
                    + "  optional int32 a = 1 [(foo_options).opt1 = 123, (foo_options).opt2 = \"baz\"];\n"
                    + "  optional int32 b = 2 [(foo_options) = { opt1: 456 opt2: \"quux\" }];\n"
                    + "}\n")
            .add("google/protobuf/descriptor.proto")
            .build();

    ProtoMember fooOptions = ProtoMember.get(Options.FIELD_OPTIONS, "foo_options");
    ProtoMember opt1 = ProtoMember.get(ProtoType.get("FooOptions"), "opt1");
    ProtoMember opt2 = ProtoMember.get(ProtoType.get("FooOptions"), "opt2");

    MessageType bar = (MessageType) schema.getType("Bar");
    assertThat(bar.field("a").options().map())
        .isEqualTo(ImmutableMap.of(fooOptions, ImmutableMap.of(opt1, "123", opt2, "baz")));
    assertThat(bar.field("b").options().map())
        .isEqualTo(ImmutableMap.of(fooOptions, ImmutableMap.of(opt1, "456", opt2, "quux")));
  }
  @Test
  public void testOnlyChild() {
    Archetype parent =
        TestAdlParser.parseAdl(
            "adl15/reference/features/annotations/openEHR-EHR-EVALUATION.annotations_parent.v1.adls");
    Archetype specialized =
        TestAdlParser.parseAdl(
            "adl15/reference/features/annotations/openEHR-EHR-EVALUATION.annotations_only_child.v1.adls");

    Archetype flattened = flatten(parent, specialized);

    assertThat(flattened.getAnnotations().getItems()).hasSize(1);
    ResourceAnnotationNodes annotations = flattened.getAnnotations().getItems().get(0);
    assertThat(annotations.getLanguage()).isEqualTo("en");
    assertThat(annotations.getItems()).hasSize(2);

    assertThat(getAnnotation(annotations, "/data[id2]"))
        .isEqualTo(ImmutableMap.of("ui", "passthrough"));
    assertThat(getAnnotation(annotations, "/data[id2]/items[id3]"))
        .isEqualTo(
            ImmutableMap.of(
                "requirements note", "this is a requirements note on Statement",
                "medline ref", "this is a medline ref on Statement",
                "design note", "this is a SPECIALISED design note on Statement",
                "NEW TAG", "this is a SPECIALISED design note on Statement"));
  }
Exemplo n.º 17
0
  @ResponseBody
  @RequestMapping(value = "/upload", method = RequestMethod.POST)
  public ImmutableMap<String, String> linkImgUpload(
      MultipartFile file, HttpServletRequest request) {
    if (file.isEmpty()) {
      return ImmutableMap.of("status", "0", "message", getMessage("global.uploadempty.message"));
    }
    Site site = (Site) (SystemUtils.getSessionSite());
    String linkPath = PathFormat.parseSiteId(SystemConstant.LINK_RES_PATH, site.getSiteId() + "");
    String realPath = HttpUtils.getRealPath(request, linkPath);

    SystemUtils.isNotExistCreate(realPath);

    String timeFileName = SystemUtils.timeFileName(file.getOriginalFilename());
    try {
      file.transferTo(new File(realPath + "/" + timeFileName));
    } catch (IOException e) {
      LOGGER.error("链接图片添加失败,错误:{}", e.getMessage());
      return ImmutableMap.of("status", "0", "message", getMessage("link.uploaderror.message"));
    }
    return ImmutableMap.of(
        "status",
        "1",
        "message",
        getMessage("link.uploadsuccess.message"),
        "filePath",
        (linkPath + "/" + timeFileName),
        "contentPath",
        HttpUtils.getBasePath(request));
  }
Exemplo n.º 18
0
 public void test_toUI_LinkedCorrectionProposal() throws Exception {
   Source source = createTestFileSource();
   // fill SourceChange
   SourceChange sourceChange = new SourceChange("My linked change", source);
   sourceChange.addEdit(new Edit(10, 1, "a"));
   sourceChange.addEdit(new Edit(20, 1, "a"));
   sourceChange.addEdit(new Edit(30, 3, "b"));
   // create SourceCorrectionProposal
   SourceCorrectionProposal proposal =
       new SourceCorrectionProposal(sourceChange, CorrectionKind.QA_ADD_TYPE_ANNOTATION);
   {
     List<SourceRange> ranges = ImmutableList.of(new SourceRange(10, 1), new SourceRange(20, 1));
     Map<String, List<SourceRange>> linkedPositons = ImmutableMap.of("a", ranges);
     proposal.setLinkedPositions(linkedPositons);
   }
   {
     List<LinkedPositionProposal> proposals =
         ImmutableList.of(
             new LinkedPositionProposal(CorrectionImage.IMG_CORRECTION_CHANGE, "proposalA"));
     Map<String, List<LinkedPositionProposal>> linkedProposals = ImmutableMap.of("a", proposals);
     proposal.setLinkedPositionProposals(linkedProposals);
   }
   //
   LinkedCorrectionProposal uiProposal = ServiceUtils.toUI(proposal);
   CompilationUnitChange ltkChange = (CompilationUnitChange) uiProposal.getChange();
   assertEquals("My linked change", ltkChange.getName());
 }
Exemplo n.º 19
0
  @ResponseBody
  @RequestMapping(value = "/edit", method = RequestMethod.POST)
  public ImmutableMap<String, Object> linkEdit(@Valid Link link, BindingResult bindingResult) {
    if (bindingResult.hasErrors()) {
      Map<String, Object> errorMessage = Maps.newHashMap();
      errorMessage.put("status", 0);
      List<FieldError> fes = bindingResult.getFieldErrors();
      for (FieldError fe : fes) {
        errorMessage.put(fe.getField(), fe.getDefaultMessage());
      }
      return ImmutableMap.<String, Object>builder().putAll(errorMessage).build();
    }

    if (link.getLinkId() == null || link.getLinkId() == 0) {
      Link result = linkService.save(link);
      if (result == null || result.getLinkId() == null || result.getLinkId() == 0) {
        LOGGER.warn("内容链接失败,链接{}", result);
        return ImmutableMap.<String, Object>of(
            "status", "0", "message", getMessage("link.addfailed.message"));
      }
      LOGGER.info("内容添加成功,链接ID{}", result.getLinkId());
      return ImmutableMap.<String, Object>of(
          "status", "1", "message", getMessage("link.addsuccess.message"));
    }
    try {
      linkService.save(link);
    } catch (Exception e) {
      LOGGER.error("链接修改失败,{}", e);
      return ImmutableMap.<String, Object>of(
          "status", "0", "message", getMessage("link.updatefailed.message"));
    }
    LOGGER.info("链接添加成功,{}", link);
    return ImmutableMap.<String, Object>of(
        "status", "1", "message", getMessage("link.updatesuccess.message"));
  }
  @Test
  @SuppressWarnings("unchecked")
  public void twoHits() {
    setup(
        "The quick brown fox jumped over the lazy dog.", ImmutableMap.of("lazy", 10f, "brown", 1f));
    List<Snippet> snippets = chooser.choose(segmenter, hitEnum, 2);
    assertThat(
        snippets,
        contains(
            extracted(extracter, "over the lazy dog."),
            extracted(extracter, "quick brown fox jumped")));
    assertThat(snippets.get(0).hits(), contains(extracted(extracter, "lazy")));
    assertThat(snippets.get(1).hits(), contains(extracted(extracter, "brown")));

    chooser = new BasicScoreBasedSnippetChooser(false);
    setup(
        "The quick brown fox jumped over the lazy dog.", ImmutableMap.of("lazy", 10f, "brown", 1f));
    snippets = chooser.choose(segmenter, hitEnum, 2);
    assertThat(
        snippets,
        contains(
            extracted(extracter, "quick brown fox jumped"),
            extracted(extracter, "over the lazy dog.")));
    assertThat(snippets.get(0).hits(), contains(extracted(extracter, "brown")));
    assertThat(snippets.get(1).hits(), contains(extracted(extracter, "lazy")));
  }
Exemplo n.º 21
0
  @Test
  public void testMoveTaskSerde() throws Exception {
    final MoveTask task =
        new MoveTask(
            null,
            "foo",
            new Interval("2010-01-01/P1D"),
            ImmutableMap.<String, Object>of("bucket", "hey", "baseKey", "what"),
            null,
            null);

    final String json = jsonMapper.writeValueAsString(task);

    Thread.sleep(100); // Just want to run the clock a bit to make sure the task id doesn't change
    final MoveTask task2 = (MoveTask) jsonMapper.readValue(json, Task.class);

    Assert.assertEquals("foo", task.getDataSource());
    Assert.assertEquals(new Interval("2010-01-01/P1D"), task.getInterval());
    Assert.assertEquals(
        ImmutableMap.<String, Object>of("bucket", "hey", "baseKey", "what"),
        task.getTargetLoadSpec());

    Assert.assertEquals(task.getId(), task2.getId());
    Assert.assertEquals(task.getGroupId(), task2.getGroupId());
    Assert.assertEquals(task.getDataSource(), task2.getDataSource());
    Assert.assertEquals(task.getInterval(), task2.getInterval());
    Assert.assertEquals(task.getTargetLoadSpec(), task2.getTargetLoadSpec());
  }
  @Test
  public void testUnassignedShardAndEmptyNodesInRoutingTable() throws Exception {
    internalCluster().startNode();
    createIndex("a");
    ensureSearchable("a");
    ClusterState current = clusterService().state();
    GatewayAllocator allocator = internalCluster().getInstance(GatewayAllocator.class);

    AllocationDeciders allocationDeciders =
        new AllocationDeciders(Settings.EMPTY, new AllocationDecider[0]);
    RoutingNodes routingNodes =
        new RoutingNodes(
            ClusterState.builder(current)
                .routingTable(
                    RoutingTable.builder(current.routingTable())
                        .remove("a")
                        .addAsRecovery(current.metaData().index("a")))
                .nodes(DiscoveryNodes.EMPTY_NODES)
                .build());
    ClusterInfo clusterInfo =
        new ClusterInfo(ImmutableMap.<String, DiskUsage>of(), ImmutableMap.<String, Long>of());

    RoutingAllocation routingAllocation =
        new RoutingAllocation(allocationDeciders, routingNodes, current.nodes(), clusterInfo);
    allocator.allocateUnassigned(routingAllocation);
  }
Exemplo n.º 23
0
  @Test
  public void shouldMatchHeaderWithMultipleValues() {
    ignoringNotifier();

    RequestPattern requestPattern1 =
        new RequestPattern(
            RequestMethod.GET, "/multi/header", ImmutableMap.of("X-Multi", equalTo("one")));
    RequestPattern requestPattern2 =
        new RequestPattern(
            RequestMethod.GET, "/multi/header", ImmutableMap.of("X-Multi", equalTo("two")));

    Request request =
        aRequest(context)
            .withUrl("/multi/header")
            .withMethod(GET)
            .withHeader("X-Multi", "one")
            .withHeader("X-Multi", "two")
            .build();

    assertTrue(
        "Request should match request pattern with header X-Multi:one",
        requestPattern1.isMatchedBy(request));
    assertTrue(
        "Request should match request pattern with header X-Multi:two",
        requestPattern2.isMatchedBy(request));
  }
 @Override
 public Map<String, Map<String, ? extends org.jclouds.trmk.vcloud_0_8.domain.Catalog>> get() {
   return ImmutableMap
       .<String, Map<String, ? extends org.jclouds.trmk.vcloud_0_8.domain.Catalog>>of(
           ORG_REF.getName(),
           ImmutableMap.<String, org.jclouds.trmk.vcloud_0_8.domain.Catalog>of(
               CATALOG_REF.getName(),
               new CatalogImpl(
                   CATALOG_REF.getName(),
                   CATALOG_REF.getType(),
                   CATALOG_REF.getHref(),
                   null,
                   ImmutableMap.<String, ReferenceType>of(
                       "item",
                       new ReferenceTypeImpl(
                           "item",
                           "application/vnd.vmware.vcloud.catalogItem+xml",
                           URI.create(
                               "https://vcloud.safesecureweb.com/api/v0.8/catalogItem/1")),
                       "template",
                       new ReferenceTypeImpl(
                           "template",
                           "application/vnd.vmware.vcloud.vAppTemplate+xml",
                           URI.create(
                               "https://vcloud.safesecureweb.com/api/v0.8/catalogItem/2"))))));
 }
Exemplo n.º 25
0
  @Test
  public void test_loading_of_module_settings() {
    BatchSettings batchSettings = mock(BatchSettings.class);
    when(batchSettings.getDefinitions()).thenReturn(new PropertyDefinitions());
    when(batchSettings.getProperties())
        .thenReturn(
            ImmutableMap.of(
                "overridding", "batch",
                "on-batch", "true"));
    when(batchSettings.getModuleProperties("struts-core"))
        .thenReturn(
            ImmutableMap.of(
                "on-module", "true",
                "overridding", "module"));

    ProjectDefinition module = ProjectDefinition.create().setKey("struts-core");
    Configuration deprecatedConf = new PropertiesConfiguration();

    ModuleSettings moduleSettings = new ModuleSettings(batchSettings, module, deprecatedConf);

    assertThat(moduleSettings.getString("overridding")).isEqualTo("module");
    assertThat(moduleSettings.getString("on-batch")).isEqualTo("true");
    assertThat(moduleSettings.getString("on-module")).isEqualTo("true");

    assertThat(deprecatedConf.getString("overridding")).isEqualTo("module");
    assertThat(deprecatedConf.getString("on-batch")).isEqualTo("true");
    assertThat(deprecatedConf.getString("on-module")).isEqualTo("true");
  }
Exemplo n.º 26
0
  /**
   * Merge the dag acls with the AM acls in the configuration object. The config object will contain
   * the updated acls.
   *
   * @param conf The AM config.
   */
  @Private
  public synchronized void mergeIntoAmAcls(Configuration conf) {
    ACLConfigurationParser parser = new ACLConfigurationParser(conf, false);
    parser.addAllowedGroups(
        ImmutableMap.of(
            ACLType.AM_VIEW_ACL, groupsWithViewACLs, ACLType.AM_MODIFY_ACL, groupsWithModifyACLs));
    parser.addAllowedUsers(
        ImmutableMap.of(
            ACLType.AM_VIEW_ACL, usersWithViewACLs, ACLType.AM_MODIFY_ACL, usersWithModifyACLs));

    Set<String> viewUsers = parser.getAllowedUsers().get(ACLType.AM_VIEW_ACL);
    Set<String> viewGroups = parser.getAllowedGroups().get(ACLType.AM_VIEW_ACL);
    if (viewUsers.contains(ACLManager.WILDCARD_ACL_VALUE)) {
      conf.set(TezConfiguration.TEZ_AM_VIEW_ACLS, ACLManager.WILDCARD_ACL_VALUE);
    } else {
      String userList = ACLManager.toCommaSeparatedString(viewUsers);
      String groupList = ACLManager.toCommaSeparatedString(viewGroups);
      conf.set(TezConfiguration.TEZ_AM_VIEW_ACLS, userList + " " + groupList);
    }

    Set<String> modifyUsers = parser.getAllowedUsers().get(ACLType.AM_MODIFY_ACL);
    Set<String> modifyGroups = parser.getAllowedGroups().get(ACLType.AM_MODIFY_ACL);
    if (modifyUsers.contains(ACLManager.WILDCARD_ACL_VALUE)) {
      conf.set(TezConfiguration.TEZ_AM_MODIFY_ACLS, ACLManager.WILDCARD_ACL_VALUE);
    } else {
      String userList = ACLManager.toCommaSeparatedString(modifyUsers);
      String groupList = ACLManager.toCommaSeparatedString(modifyGroups);
      conf.set(TezConfiguration.TEZ_AM_MODIFY_ACLS, userList + " " + groupList);
    }
  }
Exemplo n.º 27
0
  @Test
  public void testHttps() throws Exception {
    assertExpectedProxyConfig(
        proxyConfigFromEnv(
                "https",
                ImmutableMap.of(
                    "https_proxy", PROXY_URL,
                    "HTTPS_PROXY", "http://ignore",
                    "http_proxy", "http://ignore",
                    "HTTP_PROXY", "http://ignore"))
            .get());

    assertExpectedProxyConfig(
        proxyConfigFromEnv(
                "https",
                ImmutableMap.of(
                    "HTTPS_PROXY", PROXY_URL,
                    "http_proxy", "http://ignore",
                    "HTTP_PROXY", "http://ignore"))
            .get());

    assertExpectedProxyConfig(
        proxyConfigFromEnv(
                "https", ImmutableMap.of("http_proxy", PROXY_URL, "HTTP_PROXY", "http://ignore"))
            .get());

    assertExpectedProxyConfig(
        proxyConfigFromEnv("https", ImmutableMap.of("HTTP_PROXY", PROXY_URL)).get());
  }
Exemplo n.º 28
0
  /**
   * Tests that {@link Type#selectableConvert} returns either the native type or a selector on that
   * type, in accordance with the provided input.
   */
  @SuppressWarnings("unchecked")
  @Test
  public void testSelectableConvert() throws Exception {
    Object nativeInput = Arrays.asList("//a:a1", "//a:a2");
    Object selectableInput =
        SelectorList.of(
            new SelectorValue(
                ImmutableMap.of(
                    "//conditions:a",
                    nativeInput,
                    Type.Selector.DEFAULT_CONDITION_KEY,
                    nativeInput)));
    List<Label> expectedLabels = ImmutableList.of(Label.create("a", "a1"), Label.create("a", "a2"));

    // Conversion to direct type:
    Object converted = Type.LABEL_LIST.selectableConvert(nativeInput, null, currentRule);
    assertTrue(converted instanceof List<?>);
    assertSameContents(expectedLabels, (List<Label>) converted);

    // Conversion to selectable type:
    converted = Type.LABEL_LIST.selectableConvert(selectableInput, null, currentRule);
    Type.SelectorList<?> selectorList = (Type.SelectorList<?>) converted;
    assertSameContents(
        ImmutableMap.of(
                Label.parseAbsolute("//conditions:a"), expectedLabels,
                Label.parseAbsolute(Type.Selector.DEFAULT_CONDITION_KEY), expectedLabels)
            .entrySet(),
        ((Type.Selector<Label>) selectorList.getSelectors().get(0)).getEntries().entrySet());
  }
  /** Main method. */
  public static void main(String[] args) throws Exception {
    // Alice init cluster
    ICluster alice = Cluster.joinAwait(ImmutableMap.of("name", "Alice"));
    System.out.println(now() + " Alice join members: " + alice.members());
    alice
        .listenMembership()
        .subscribe(event -> System.out.println(now() + " Alice received: " + event));

    // Bob join cluster
    ICluster bob = Cluster.joinAwait(ImmutableMap.of("name", "Bob"), alice.address());
    System.out.println(now() + " Bob join members: " + bob.members());
    bob.listenMembership()
        .subscribe(event -> System.out.println(now() + " Bob received: " + event));

    // Carol join cluster
    ICluster carol =
        Cluster.joinAwait(ImmutableMap.of("name", "Carol"), alice.address(), bob.address());
    System.out.println(now() + " Carol join members: " + carol.members());
    carol
        .listenMembership()
        .subscribe(event -> System.out.println(now() + " Carol received: " + event));

    // Bob leave cluster
    Future<Void> shutdownFuture = bob.shutdown();
    shutdownFuture.get();

    // Avoid exit main thread immediately ]:->
    long maxRemoveTimeout =
        MembershipConfig.DEFAULT_SUSPECT_TIMEOUT + 3 * FailureDetectorConfig.DEFAULT_PING_INTERVAL;
    Thread.sleep(maxRemoveTimeout);
  }
Exemplo n.º 30
0
  @Test
  public void testEmptyMap() throws Exception {
    Event.EventContext api = Event.EventContext.apiKey(apiKeys.writeKey());
    byte[] bytes =
        mapper.writeValueAsBytes(
            ImmutableMap.of(
                "collection",
                "test",
                "api",
                api,
                "properties",
                ImmutableMap.of(
                    "test",
                    1,
                    "test2",
                    new HashMap<String, String>() {
                      {
                        put("a", null);
                      }
                    }),
                "test20",
                ImmutableMap.of(),
                "test3",
                true));

    Event event = mapper.readValue(bytes, Event.class);

    assertEquals("test", event.project());
    assertEquals("test", event.collection());
    assertEquals(api, event.api());
    assertEquals(
        eventBuilder.createEvent("test", ImmutableMap.of("test", 1.0, "test3", true)).properties(),
        event.properties());
  }