Example #1
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());
 }
Example #2
0
 @ConstructorProperties({
   "id",
   "links",
   "orderedSelfReferences",
   "name",
   "progress",
   "serverRef",
   "status",
   "metadata",
   "created",
   "updated"
 })
 protected Image(
     int id,
     List<Map<String, String>> links,
     @Nullable Map<LinkType, URI> orderedSelfReferences,
     @Nullable String name,
     @Nullable Integer progress,
     @Nullable String serverRef,
     @Nullable ImageStatus status,
     @Nullable Map<String, String> metadata,
     @Nullable Date created,
     @Nullable Date updated) {
   super(id, links, orderedSelfReferences);
   this.name = name;
   this.progress = progress;
   this.serverRef = serverRef;
   this.status = status == null ? ImageStatus.UNKNOWN : status;
   this.metadata =
       metadata == null
           ? ImmutableMap.<String, String>of()
           : ImmutableMap.copyOf(checkNotNull(metadata, "metadata"));
   this.created = created;
   this.updated = updated;
 }
Example #3
0
  /** 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);
  }
Example #4
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");
  }
Example #5
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());
  }
Example #6
0
  @Test
  public void shouldBePossibleToCreateMap() {
    ImmutableMap<String, Address> map = addressMapBuilder().asAddressMap();

    assertThat(map.get("a").isFromUppsala(), is(true));
    assertThat(map.get("b").isFromUppsala(), is(false));
  }
  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;
  }
  private void invalidateIfProjectBuildFileParserStateChanged(Cell cell) {
    ImmutableMap<String, String> cellEnv = cell.getBuckConfig().getEnvironment();
    Iterable<String> defaultIncludes = new ParserConfig(cell.getBuckConfig()).getDefaultIncludes();

    boolean invalidateCaches = false;
    try (AutoCloseableLock updateLock = cachedStateLock.updateLock()) {
      Iterable<String> expected = cachedIncludes.get(cell.getRoot());

      if (!cellEnv.equals(cachedEnvironment)) {
        // Contents of System.getenv() have changed. Cowardly refuse to accept we'll parse
        // everything the same way.
        invalidateCaches = true;
      } else if (expected == null || !Iterables.elementsEqual(defaultIncludes, expected)) {
        // Someone's changed the default includes. That's almost definitely caused all our lovingly
        // cached data to be enormously wonky.
        invalidateCaches = true;
      }

      if (!invalidateCaches) {
        return;
      }

      try (AutoCloseableLock writeLock = cachedStateLock.writeLock()) {
        cachedEnvironment = cellEnv;
        cachedIncludes.put(cell.getRoot(), defaultIncludes);
      }
    }
    synchronized (this) {
      invalidateAllCaches();
      knownCells.add(cell);
    }
  }
Example #9
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")));
  }
  /**
   * 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);
    }
  }
Example #11
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());
  }
 @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"))))));
 }
  @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);
  }
  @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")));
  }
Example #15
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;
 }
 @Test(dataProvider = "name")
 public void test_extendedEnum(ThreeLegBasisSwapConvention convention, String name) {
   ThreeLegBasisSwapConvention.of(name); // ensures map is populated
   ImmutableMap<String, ThreeLegBasisSwapConvention> map =
       ThreeLegBasisSwapConvention.extendedEnum().lookupAll();
   assertEquals(map.get(name), convention);
 }
  @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));
  }
Example #18
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));
  }
Example #19
0
  @Test
  public void shouldBePossibleToCreateStateMap() {
    ImmutableMap<String, AddressState> map = addressMapBuilder().asStateMap();

    assertThat(map.get("a").city, equalTo("Uppsala"));
    assertThat(map.get("b").city, equalTo("Stockholm"));
  }
Example #20
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"));
 }
  @Test
  public void shouldConvertFromMutableMapOfMutableMapOfIntegerToMutableMap() {
    Map map1 = new HashMap();
    Map map2 = new HashMap();
    map1.put("a", 123);
    map2.put("b", 456);
    Map mutableMap = new HashMap();
    mutableMap.put("c", map1);
    mutableMap.put("d", map2);

    ImmutableMap<String, ImmutableMap<String, Integer>> immutableMap =
        asImmutableMap(mutableMap, toImmutableMap);

    ImmutableMap<String, Integer> expected1 =
        ImmutableMap.<String, Integer>builder().put("a", 123).build();
    ImmutableMap<String, Integer> expected2 =
        ImmutableMap.<String, Integer>builder().put("b", 456).build();
    ImmutableMap<String, ImmutableMap<String, Integer>> expectedMap =
        ImmutableMap.<String, ImmutableMap<String, Integer>>builder()
            .put("c", expected1)
            .put("d", expected2)
            .build();

    assertThat(immutableMap, equalTo(expectedMap));
  }
Example #22
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"));
  }
Example #23
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()));
  }
Example #24
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"));
  }
  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))));
  }
  @Test
  public void testSettingOfSdkPipelineOptions() throws IOException {
    DataflowPipelineOptions options = buildPipelineOptions();
    options.setRunner(DataflowPipelineRunner.class);

    Pipeline p = buildPipeline(options);
    p.traverseTopologically(new RecordingPipelineVisitor());
    Job job =
        DataflowPipelineTranslator.fromOptions(options)
            .translate(p, Collections.<DataflowPackage>emptyList())
            .getJob();

    // Note that the contents of this materialized map may be changed by the act of reading an
    // option, which will cause the default to get materialized whereas it would otherwise be
    // left absent. It is permissible to simply alter this test to reflect current behavior.
    assertEquals(
        ImmutableMap.of(
            "options",
            ImmutableMap.builder()
                .put("appName", "DataflowPipelineTranslatorTest")
                .put("project", "some-project")
                .put(
                    "pathValidatorClass",
                    "com.google.cloud.dataflow.sdk.util.DataflowPathValidator")
                .put("runner", "com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner")
                .put("jobName", "some-job-name")
                .put("tempLocation", "gs://somebucket/some/path")
                .put("stagingLocation", "gs://somebucket/some/path/staging")
                .put("stableUniqueNames", "WARNING")
                .put("streaming", false)
                .put("numberOfWorkerHarnessThreads", 0)
                .build()),
        job.getEnvironment().getSdkPipelineOptions());
  }
  /** 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);
  }
Example #28
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());
  }
Example #29
0
  /**
   * Creates a new attribute service using the given providers and user provided default attribute
   * values.
   */
  public AttributeService(
      Iterable<? extends AttributeProvider> providers, Map<String, ?> userProvidedDefaults) {
    ImmutableMap.Builder<String, AttributeProvider> byViewNameBuilder = ImmutableMap.builder();
    ImmutableMap.Builder<Class<?>, AttributeProvider> byViewTypeBuilder = ImmutableMap.builder();
    ImmutableMap.Builder<Class<?>, AttributeProvider> byAttributesTypeBuilder =
        ImmutableMap.builder();

    ImmutableList.Builder<FileAttribute<?>> defaultAttributesBuilder = ImmutableList.builder();

    for (AttributeProvider provider : providers) {
      byViewNameBuilder.put(provider.name(), provider);
      byViewTypeBuilder.put(provider.viewType(), provider);
      if (provider.attributesType() != null) {
        byAttributesTypeBuilder.put(provider.attributesType(), provider);
      }

      for (Map.Entry<String, ?> entry : provider.defaultValues(userProvidedDefaults).entrySet()) {
        defaultAttributesBuilder.add(new SimpleFileAttribute<>(entry.getKey(), entry.getValue()));
      }
    }

    this.providersByName = byViewNameBuilder.build();
    this.providersByViewType = byViewTypeBuilder.build();
    this.providersByAttributesType = byAttributesTypeBuilder.build();
    this.defaultValues = defaultAttributesBuilder.build();
  }
    private void installSecondaryDexFiles() throws Exception {
      final ImmutableMap<String, Path> hashToSources = getRequiredDexFiles();
      final ImmutableSet<String> requiredHashes = hashToSources.keySet();
      final ImmutableSet<String> presentHashes = prepareSecondaryDexDir(requiredHashes);
      final Set<String> hashesToInstall = Sets.difference(requiredHashes, presentHashes);

      Map<String, Path> filesToInstallByHash =
          Maps.filterKeys(hashToSources, Predicates.in(hashesToInstall));

      // This is a bit gross.  It was a late addition.  Ideally, we could eliminate this, but
      // it wouldn't be terrible if we don't.  We store the dexed jars on the device
      // with the full SHA-1 hashes in their names.  This is the format that the loader uses
      // internally, so ideally we would just load them in place.  However, the code currently
      // expects to be able to copy the jars from a directory that matches the name in the
      // metadata file, like "secondary-1.dex.jar".  We don't want to give up putting the
      // hashes in the file names (because we use that to skip re-uploads), so just hack
      // the metadata file to have hash-like names.
      String metadataContents =
          com.google.common.io.Files.toString(
                  projectFilesystem
                      .resolve(exopackageInfo.getDexInfo().get().getMetadata())
                      .toFile(),
                  Charsets.UTF_8)
              .replaceAll(
                  "secondary-(\\d+)\\.dex\\.jar (\\p{XDigit}{40}) ", "secondary-$2.dex.jar $2 ");

      installFiles(
          "secondary_dex",
          ImmutableMap.copyOf(filesToInstallByHash),
          metadataContents,
          "secondary-%s.dex.jar",
          SECONDARY_DEX_DIR);
    }