Java Code Examples for java.util.List#add()

The following examples show how to use java.util.List#add() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BaseStoreRequest.java    From aptoide-client with GNU General Public License v2.0 11 votes vote down vote up
private List<Displayable> createCategoryList(List<ListViewItems.DisplayList> list) {
    List<Displayable> displayables = new ArrayList<>();

    for (ListViewItems.DisplayList display : list) {
        if (isKnownType(display.event.type) && isKnownName(display.event.name)) {
            CategoryRow categ = new CategoryRow(numColumns);
            if (display.event.type.equals(Action.Event.API_EXTERNAL_TYPE) && (display.event.name.equals(Action.Event.EVENT_FACEBOOK_TYPE)||display.event.name.equals(Action.Event
                    .EVENT_YOUTUBE_TYPE))) {
                categ.setSpanSize(totalSpanSize);
            } else {
                categ.setSpanSize(totalSpanSize / 2);
            }
            categ.setLabel(display.label);
            categ.setGraphic(display.graphic);
            categ.setEventType(display.event.type);
            categ.setEventName(display.event.name);
            categ.setEventActionUrl(display.event.action);
            displayables.add(categ);
        }
    }

    return displayables;
}
 
Example 2
Source File: LecturerMappingReaderTest.java    From olat with Apache License 2.0 9 votes vote down vote up
@Test
public void read_twoLecturersList() throws UnexpectedInputException, ParseException, NonTransientResourceException, Exception {
    List<Lecturer> twoLecturersList = new ArrayList<Lecturer>();
    Lecturer lecturerMock1 = mock(Lecturer.class);
    Lecturer lecturerMock2 = mock(Lecturer.class);
    twoLecturersList.add(lecturerMock1);
    twoLecturersList.add(lecturerMock2);
    when(daoManagerMock.getAllLecturers()).thenReturn(twoLecturersList);
    lecturerMappingReaderTestObject.init();
    // The first read delivers the first lecturer
    assertNotNull(lecturerMappingReaderTestObject.read());
    // The second read delivers the second lecturer
    assertNotNull(lecturerMappingReaderTestObject.read());
    // The third read delivers null
    assertNull(lecturerMappingReaderTestObject.read());
}
 
Example 3
Source File: DistinctCursorTest.java    From tddl with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetOrderBysAfterNext() throws TddlException {

    MockArrayCursor mockCursor1 = this.getCursor("T1", new Integer[] { 1, 3, 5, 8, 8, 9, 10 });
    MockArrayCursor mockCursor2 = this.getCursor("T1", new Integer[] { 2, 2, 4, 5, 6, 7, 7, 9, 9, 10, 13 });
    IOrderBy order = new OrderBy();
    order.setColumn(new Column().setColumnName("ID").setTableName("T1").setDataType(DataType.IntegerType));
    List<IOrderBy> orderBys = new ArrayList();

    orderBys.add(order);

    List<ISchematicCursor> cursors = new ArrayList();
    cursors.add(new SchematicCursor(mockCursor1, orderBys));
    cursors.add(new SchematicCursor(mockCursor2, orderBys));
    DistinctCursor c = new DistinctCursor(new MergeSortedCursors(cursors, true), orderBys);

    c.next();

    Assert.assertEquals("[T1.ID, T1.NAME, T1.SCHOOL]", c.getReturnColumns().toString());
    Assert.assertEquals("[OrderBy [columnName=T1.ID, direction=true]]", c.getOrderBy().toString());

}
 
Example 4
Source File: ErrataHandler.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
/**
 * private helper method to publish the errata
 * @param errata the errata to publish
 * @param channels A list of channel objects
 * @return The published Errata
 */
private Errata publish(Errata errata, List<Channel> channels, User user,
        boolean inheritPackages) {
    Errata published = ErrataFactory.publish(errata);
    for (Channel chan : channels) {
        List<Errata> list = new ArrayList<Errata>();
        list.add(published);
        published = ErrataFactory.publishToChannel(list, chan, user,
                inheritPackages).get(0);

    }
    return published;
}
 
Example 5
Source File: StreamWorkSlotQueueTest.java    From eagle with Apache License 2.0 5 votes vote down vote up
@Test
public void testStreamWorkSlotQueue() {
    StreamGroup streamGroup = new StreamGroup();
    StreamSortSpec streamSortSpec = new StreamSortSpec();
    streamSortSpec.setWindowPeriod("PT10S");
    StreamPartition streamPartition = new StreamPartition();
    List<String> columns = new ArrayList<>();
    columns.add("jobId");
    streamPartition.setColumns(columns);
    streamPartition.setSortSpec(streamSortSpec);
    streamPartition.setStreamId("test");
    streamPartition.setType(StreamPartition.Type.GROUPBY);
    streamGroup.addStreamPartition(streamPartition);
    WorkSlot workSlot = new WorkSlot("setTopologyName", "setBoltId");
    List<WorkSlot> workSlots = new ArrayList<>();
    workSlots.add(workSlot);
    StreamWorkSlotQueue streamWorkSlotQueue = new StreamWorkSlotQueue(streamGroup, false, new HashMap<>(), workSlots);

    Assert.assertTrue(streamWorkSlotQueue.getQueueId().startsWith("SG[test-]"));
    Assert.assertTrue(streamWorkSlotQueue.getDedicateOption().isEmpty());
    Assert.assertEquals(0, streamWorkSlotQueue.getNumberOfGroupBolts());
    Assert.assertEquals(1, streamWorkSlotQueue.getQueueSize());
    Assert.assertTrue(streamWorkSlotQueue.getTopoGroupStartIndex().isEmpty());
    Assert.assertEquals(-1, streamWorkSlotQueue.getTopologyGroupStartIndex(""));
    Assert.assertEquals(workSlot, streamWorkSlotQueue.getWorkingSlots().get(0));

    StreamWorkSlotQueue streamWorkSlotQueue1 = new StreamWorkSlotQueue(streamGroup, false, new HashMap<>(), workSlots);
    Assert.assertFalse(streamWorkSlotQueue.equals(streamWorkSlotQueue1));
    Assert.assertFalse(streamWorkSlotQueue == streamWorkSlotQueue1);
    Assert.assertFalse(streamWorkSlotQueue.hashCode() == streamWorkSlotQueue1.hashCode());
}
 
Example 6
Source File: ExpandSelectMock.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
private static UriInfoResource mockResourceOnAction(
    EdmEntitySet edmEntitySet, EdmAction action) {
  List<UriResource> elements = new ArrayList<UriResource>();
  UriResourceAction element = Mockito.mock(UriResourceAction.class);
  Mockito.when(element.getAction()).thenReturn(action);
  elements.add(element);
  
  UriInfoResource resource = Mockito.mock(UriInfoResource.class);
  Mockito.when(resource.getUriResourceParts()).thenReturn(elements);
  return resource;
}
 
Example 7
Source File: DecisionTreeRegressionTrainerTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/** Test parameters. */
@Parameterized.Parameters(name = "Data divided on {0} partitions. Use index = {1}.")
public static Iterable<Integer[]> data() {
    List<Integer[]> res = new ArrayList<>();
    for (int i = 0; i < 2; i++) {
        for (int part : partsToBeTested)
            res.add(new Integer[] {part, i});
    }

    return res;
}
 
Example 8
Source File: MetricsBuilder.java    From vespa with Apache License 2.0 5 votes vote down vote up
private MetricSet buildMetricSet(String consumerId, Element consumerElement) {
    List<Metric> metrics = XML.getChildren(consumerElement, "metric").stream()
            .map(MetricsBuilder::metricFromElement)
            .collect(Collectors.toCollection(LinkedList::new));

    List<MetricSet> metricSets = XML.getChildren(consumerElement, "metric-set").stream()
            .map(metricSetElement -> getMetricSetOrThrow(metricSetElement.getAttribute(ID_ATTRIBUTE)))
            .collect(Collectors.toCollection(LinkedList::new));

    metricSets.add(defaultVespaMetricSet);
    metricSets.add(systemMetricSet);

    return new MetricSet(metricSetId(consumerId), metrics, metricSets);
}
 
Example 9
Source File: PrintUtil4.java    From yshopmall with Apache License 2.0 5 votes vote down vote up
/**
 * 编辑打印机信息
 *
 * @param sn     编号
 * @param remark 备注
 * @param phone  电话
 * @return 结果
 */
public static String editPrintEquip(String sn, String remark, String phone) {
    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    nvps.add(new BasicNameValuePair("user", USER));
    String STIME = String.valueOf(System.currentTimeMillis() / 1000);
    nvps.add(new BasicNameValuePair("stime", STIME));
    nvps.add(new BasicNameValuePair("sig", signature(USER, UKEY, STIME)));
    nvps.add(new BasicNameValuePair("apiname", "Open_printerEdit"));
    nvps.add(new BasicNameValuePair("sn", sn));
    nvps.add(new BasicNameValuePair("name", remark));
    nvps.add(new BasicNameValuePair("phonenum", phone));
    return sendHttpRequest(nvps);
}
 
Example 10
Source File: IFengTabResultParse.java    From TigerVideo with Apache License 2.0 5 votes vote down vote up
@Override
public List<VideoTabData> parseTab(JSONObject json) throws JSONException {

    List<VideoTabData> list = new ArrayList<>();

    JSONArray array = json.getJSONArray(KEY_TAB_LIST);
    JSONObject item;
    for(int i = 0; i < array.length(); i++) {
        item = array.getJSONObject(i);
        int tabId = item.optInt(KEY_TAB_ID);
        String tabName = item.optString(KEY_TAB_NAME);
        list.add(new VideoTabData(tabId, tabName, DataType.IFENG.value()));
    }
    return list;
}
 
Example 11
Source File: SystemCmdlet.java    From HongsCORE with MIT License 5 votes vote down vote up
/**
 * 设置命令
 * @param args
 * @throws HongsException
 */
@Cmdlet( "setup" )
public static void setup(String[] args) throws HongsException {
    List<String> argz = Synt.listOf((Object[]) args);
                 argz.add( 0, "setup" );
    exec( argz.toArray(new String[0]) );
}
 
Example 12
Source File: LithoStartupLoggerTest.java    From litho with Apache License 2.0 5 votes vote down vote up
@Test
public void lastmount_withDataAttributionNonLastAdapterItemLastVisibleItem() {
  mTestLithoStartupLogger.setDataAttribution("myquery");
  final RecyclerView recyclerView = new RecyclerView(mComponentContext.getAndroidContext());

  final List<RenderInfo> components = new ArrayList<>();
  for (int i = 0; i < 3; i++) {
    components.add(
        ComponentRenderInfo.create()
            .component(
                SimpleMountSpecTester.create(mComponentContext)
                    .widthPx(100)
                    .heightPx(100)
                    .build())
            .build());
  }
  mRecyclerBinder.mount(recyclerView);
  mRecyclerBinder.insertRangeAt(0, components);
  mRecyclerBinder.measure(
      new Size(), makeSizeSpec(1000, EXACTLY), makeSizeSpec(150, EXACTLY), null);

  assertThat(mTestLithoStartupLogger.tracePointCount()).isEqualTo(2); // first_layout points

  mRecyclerBinder.notifyChangeSetComplete(true, NO_OP_CHANGE_SET_COMPLETE_CALLBACK);

  createBindAndMountLithoView(recyclerView, 0);

  assertThat(mTestLithoStartupLogger.tracePointCount()).isEqualTo(4); // first_mount points

  createBindAndMountLithoView(recyclerView, 1);
  assertThat(mTestLithoStartupLogger.tracePointCount()).isEqualTo(6);

  assertThat(mTestLithoStartupLogger.getTracedPointAt(4))
      .isEqualTo("litho_myquery_lastmount_start");
  assertThat(mTestLithoStartupLogger.getTracedPointAt(5))
      .isEqualTo("litho_myquery_lastmount_end");
}
 
Example 13
Source File: CodecInfo.java    From mtas with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the positioned terms by prefixes and position range.
 *
 * @param field
 *          the field
 * @param docId
 *          the doc id
 * @param prefixes
 *          the prefixes
 * @param startPosition
 *          the start position
 * @param endPosition
 *          the end position
 * @return the positioned terms by prefixes and position range
 * @throws IOException
 *           Signals that an I/O exception has occurred.
 */
public List<MtasTreeHit<String>> getPositionedTermsByPrefixesAndPositionRange(
    String field, int docId, List<String> prefixes, int startPosition,
    int endPosition) throws IOException {
  IndexDoc doc = getDoc(field, docId);
  IndexInput inIndexObjectPosition = indexInputList
      .get("indexObjectPosition");
  if (doc != null) {
    ArrayList<MtasTreeHit<?>> hitItems = CodecSearchTree.searchMtasTree(
        startPosition, endPosition, inIndexObjectPosition,
        doc.fpIndexObjectPosition, doc.smallestObjectFilepointer);
    List<MtasTreeHit<String>> hits = new ArrayList<>();
    Map<String, Integer> prefixIds = getPrefixesIds(field, prefixes);
    if (prefixIds != null && prefixIds.size() > 0) {
      ArrayList<MtasTreeHit<?>> filteredHitItems = new ArrayList<MtasTreeHit<?>>();

      for (MtasTreeHit<?> hitItem : hitItems) {
        if (prefixIds.containsValue(hitItem.additionalId)) {
          filteredHitItems.add(hitItem);
        }
      }
      if (filteredHitItems.size() > 0) {
        ArrayList<MtasTokenString> objects = getObjects(filteredHitItems);
        for (MtasTokenString token : objects) {
          MtasTreeHit<String> hit = new MtasTreeHit<String>(
              token.getPositionStart(), token.getPositionEnd(),
              token.getTokenRef(), 0, 0, token.getValue());
          hits.add(hit);
        }
      }
    }
    return hits;
  } else {
    return new ArrayList<MtasTreeHit<String>>();
  }
}
 
Example 14
Source File: GridPattern.java    From Carcassonne with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Removes all players from the list of involved players which have not the maximum amount of meeples on this pattern.
 */
private void determineDominantPlayers() {
    List<Player> removalList = new LinkedList<>();
    int maximum = Collections.max(involvedPlayers.values()); // most meeples on pattern
    for (Player player : involvedPlayers.keySet()) { // for all involved players
        if (involvedPlayers.get(player) != maximum) { // if has not enough meeples
            removalList.add(player); // add to removal list (remove later)
        }
    }
    removalList.forEach(it -> involvedPlayers.remove(it)); // remove players who don't get points
}
 
Example 15
Source File: DocumentationUtil.java    From arma-intellij-plugin with MIT License 5 votes vote down vote up
/**
 * Annotates the given comment so that tags like @command, @bis, and @fnc (Arma Intellij Plugin specific tags) are properly annotated
 *
 * @param annotator the annotator
 * @param comment   the comment
 */
public static void annotateDocumentationWithArmaPluginTags(@NotNull AnnotationHolder annotator, @NotNull PsiComment comment) {
	List<String> allowedTags = new ArrayList<>(3);
	allowedTags.add("command");
	allowedTags.add("bis");
	allowedTags.add("fnc");
	Pattern patternTag = Pattern.compile("@([a-zA-Z]+) ([a-zA-Z_0-9]+)");
	Matcher matcher = patternTag.matcher(comment.getText());
	String tag;
	Annotation annotation;
	int startTag, endTag, startArg, endArg;
	while (matcher.find()) {
		if (matcher.groupCount() < 2) {
			continue;
		}
		tag = matcher.group(1);
		if (!allowedTags.contains(tag)) {
			continue;
		}
		startTag = matcher.start(1);
		endTag = matcher.end(1);
		startArg = matcher.start(2);
		endArg = matcher.end(2);
		annotation = annotator.createAnnotation(HighlightSeverity.INFORMATION, TextRange.create(comment.getTextOffset() + startTag - 1, comment.getTextOffset() + endTag), null);
		annotation.setTextAttributes(DefaultLanguageHighlighterColors.DOC_COMMENT_TAG);
		annotation = annotator.createAnnotation(HighlightSeverity.INFORMATION, TextRange.create(comment.getTextOffset() + startArg, comment.getTextOffset() + endArg), null);
		annotation.setTextAttributes(DefaultLanguageHighlighterColors.DOC_COMMENT_TAG_VALUE);
	}
}
 
Example 16
Source File: TestCustomPartitioner.java    From spork with Apache License 2.0 4 votes vote down vote up
@Test
public void testCustomPartitionerParseJoins() throws Exception{
    String[] input = {
            "1\t3",
            "1\t2"
    };
    Util.createInputFile(cluster, "table_testCustomPartitionerParseJoins", input);

    // Custom Partitioner is not allowed for skewed joins, will throw a ExecException
    try {
        pigServer.registerQuery("A = LOAD 'table_testCustomPartitionerParseJoins' as (a0:int, a1:int);");
        pigServer.registerQuery("B = ORDER A by $0;");
        pigServer.registerQuery("skewed = JOIN A by $0, B by $0 USING 'skewed' PARTITION BY org.apache.pig.test.utils.SimpleCustomPartitioner;");
        //control should not reach here
        Assert.fail("Skewed join cannot accept a custom partitioner");
    } catch(FrontendException e) {
        Assert.assertTrue( e.getMessage().contains( "Custom Partitioner is not supported for skewed join" ) );
    }

    pigServer.registerQuery("hash = JOIN A by $0, B by $0 USING 'hash' PARTITION BY org.apache.pig.test.utils.SimpleCustomPartitioner;");
    Iterator<Tuple> iter = pigServer.openIterator("hash");

    List<String> expected = new ArrayList<String>();
    expected.add("(1,3,1,2)");
    expected.add("(1,3,1,3)");
    expected.add("(1,2,1,2)");
    expected.add("(1,2,1,3)");
    Collections.sort(expected);

    List<String> actual = new ArrayList<String>();
    while (iter.hasNext()) {
        actual.add(iter.next().toString());
    }
    Collections.sort(actual);

    Assert.assertEquals(expected, actual);

    // No checks are made for merged and replicated joins as they are compiled to a map only job
    // No frontend error checking has been added for these jobs, hence not adding any test cases
    // Manually tested the sanity once. Above test should cover the basic sanity of the scenario

    Util.deleteFile(cluster, "table_testCustomPartitionerParseJoins");
}
 
Example 17
Source File: ConsumeMessageOrderlyService.java    From rocketmq with Apache License 2.0 4 votes vote down vote up
@Override
public ConsumeMessageDirectlyResult consumeMessageDirectly(MessageExt msg, String brokerName) {
    ConsumeMessageDirectlyResult result = new ConsumeMessageDirectlyResult();
    result.setOrder(true);

    List<MessageExt> msgs = new ArrayList<MessageExt>();
    msgs.add(msg);
    MessageQueue mq = new MessageQueue();
    mq.setBrokerName(brokerName);
    mq.setTopic(msg.getTopic());
    mq.setQueueId(msg.getQueueId());

    ConsumeOrderlyContext context = new ConsumeOrderlyContext(mq);

    final long beginTime = System.currentTimeMillis();

    log.info("consumeMessageDirectly receive new messge: {}", msg);

    try {
        ConsumeOrderlyStatus status = this.messageListener.consumeMessage(msgs, context);
        if (status != null) {
            switch (status) {
                case COMMIT:
                    result.setConsumeResult(CMResult.CR_COMMIT);
                    break;
                case ROLLBACK:
                    result.setConsumeResult(CMResult.CR_ROLLBACK);
                    break;
                case SUCCESS:
                    result.setConsumeResult(CMResult.CR_SUCCESS);
                    break;
                case SUSPEND_CURRENT_QUEUE_A_MOMENT:
                    result.setConsumeResult(CMResult.CR_LATER);
                    break;
                default:
                    break;
            }
        } else {
            result.setConsumeResult(CMResult.CR_RETURN_NULL);
        }
    } catch (Throwable e) {
        result.setConsumeResult(CMResult.CR_THROW_EXCEPTION);
        result.setRemark(RemotingHelper.exceptionSimpleDesc(e));

        log.warn(String.format("consumeMessageDirectly exception: %s Group: %s Msgs: %s MQ: %s", //
                RemotingHelper.exceptionSimpleDesc(e), //
                ConsumeMessageOrderlyService.this.consumerGroup, //
                msgs, //
                mq), e);
    }

    result.setAutoCommit(context.isAutoCommit());
    result.setSpentTimeMills(System.currentTimeMillis() - beginTime);

    log.info("consumeMessageDirectly Result: {}", result);

    return result;
}
 
Example 18
Source File: SearchTimeSpliter.java    From SeQL with Apache License 2.0 4 votes vote down vote up
public static List<Map<String, String>> makeSearchListDay(String start_date, String end_date, int interval) throws Exception {
	List<Map<String, String>> schList = new ArrayList<Map<String, String>>();
	
	try {
		Map<String, String> param = null;
		if(start_date==null && end_date==null) {
			param = new HashMap<String, String>();
			param.put("sdt", null);
			param.put("ddt", null);
			param.put("pSearch", "false");
			schList.add(param);
			return schList;
		}
		
		String last_ddt = null;
		String sdt   = null;
		String ddt   = null;
		
		String sec = end_date.substring(10);
		if(sec.equals("5959")) {
			end_date = DateTime.addTimes(end_date, 1, "yyyyMMddHHmmss");
		}
		String min_sec = end_date.substring(8);
		if(!min_sec.equals("000000")) {
			last_ddt = end_date;
			if(end_date.substring(10).equals("0000")) {
				ddt = DateTime.addTimes(last_ddt, -1, "yyyyMMddHHmmss");
			} else ddt = last_ddt;
			sdt = ddt.substring(0, 8) + "000000";
			if(Long.parseLong(sdt) < Long.parseLong(start_date)) {
				sdt = start_date;
			}
			//System.out.println("> sdt="+sdt+", ddt=" + ddt);
			
			param = new HashMap<String, String>();
			param.put("sdt", sdt);
			param.put("ddt", ddt);
			param.put("pSearch", "false");
			schList.add(param);
		}
		
		boolean isWorking = true;
		while(isWorking) {
			last_ddt = (last_ddt==null?end_date:sdt);
			ddt = DateTime.addTimes(last_ddt, -1, "yyyyMMddHHmmss");
			sdt = DateTime.addTimes(last_ddt, -1*interval*60*60*24, "yyyyMMddHHmmss");
			if(Long.parseLong(sdt) <= Long.parseLong(start_date)) {
				isWorking = false;
				sdt = start_date;
			}
			if(Long.parseLong(ddt) < Long.parseLong(start_date)) continue;
			//logger.debug("> sdt="+sdt+", ddt=" + ddt);
			
			param = new HashMap<String, String>();
			param.put("sdt", sdt);
			param.put("ddt", ddt);
			param.put("pSearch", String.valueOf(sdt.substring(10).equals("0000")));
			
			schList.add(param);
		}
	} catch(Exception e) {
		throw e;
	}
	return schList;
}
 
Example 19
Source File: AddExampleUser.java    From aws-doc-sdk-examples with Apache License 2.0 4 votes vote down vote up
public static void updatePinpointEndpoint(PinpointClient pinpoint,String applicationId, String endPointId) {


        try{
            List<String> wangXiList = new ArrayList<String>();
            wangXiList.add("cooking");
            wangXiList.add("running");
            wangXiList.add("swimming");

            Map myMapWang = new HashMap<String, List>();
            myMapWang.put("interests", wangXiList);

            List<String> myNameWang = new ArrayList<String>();
            myNameWang.add("Wang ");
            myNameWang.add("Xiulan");

            Map wangName = new HashMap<String, List>();
            wangName.put("name",myNameWang );

            EndpointUser wangMajor = EndpointUser.builder()
                .userId("example_user_10")
                .userAttributes(wangName)
                .build();

            // Create an EndpointBatchItem object for Mary Major
            EndpointRequest wangXiulanEndpoint = EndpointRequest.builder()
                .channelType(ChannelType.EMAIL)
                .address("[email protected]")
                .attributes(myMapWang)
                .user(wangMajor)
                .build();

            // Adds multiple endpoint definitions to a single request object.
            UpdateEndpointRequest endpointList = UpdateEndpointRequest.builder()
               .applicationId(applicationId)
                .endpointRequest(wangXiulanEndpoint)
                .endpointId(endPointId)
                .build();

            UpdateEndpointResponse result = pinpoint.updateEndpoint(endpointList);

            System.out.format("Update endpoint result: %s\n", result.messageBody().message());

    } catch (PinpointException e) {
        System.err.println(e.awsErrorDetails().errorMessage());
        System.exit(1);
    }
    //snippet-end:[pinpoint.java2.update_endpoint.main]
  }
 
Example 20
Source File: TestTopology.java    From helix with Apache License 2.0 4 votes vote down vote up
@Test
public void testCreateClusterTopologyWithDefaultTopology() {
  ClusterConfig clusterConfig = new ClusterConfig("Test_Cluster");
  clusterConfig.setTopologyAwareEnabled(true);

  List<String> allNodes = new ArrayList<String>();
  List<String> liveNodes = new ArrayList<String>();
  Map<String, InstanceConfig> instanceConfigMap = new HashMap<String, InstanceConfig>();

  Map<String, Integer> nodeToWeightMap = new HashMap<String, Integer>();

  for (int i = 0; i < 100; i++) {
    String instance = "localhost_" + i;
    InstanceConfig config = new InstanceConfig(instance);
    String zoneId = "rack_" + i / 10;
    config.setZoneId(zoneId);
    config.setHostName(instance);
    config.setPort("9000");
    allNodes.add(instance);

    int weight = 0;
    if (i % 10 != 0) {
      liveNodes.add(instance);
      weight = 1000;
      if (i % 3 == 0) {
        // set random instance weight.
        weight = (i + 1) * 100;
        config.setWeight(weight);
      }
    }

    instanceConfigMap.put(instance, config);

    if (!nodeToWeightMap.containsKey(zoneId)) {
      nodeToWeightMap.put(zoneId, 0);
    }
    nodeToWeightMap.put(zoneId, nodeToWeightMap.get(zoneId) + weight);
  }

  Topology topo = new Topology(allNodes, liveNodes, instanceConfigMap, clusterConfig);

  Assert.assertTrue(topo.getEndNodeType().equals(Topology.Types.INSTANCE.name()));
  Assert.assertTrue(topo.getFaultZoneType().equals(Topology.Types.ZONE.name()));

  List<Node> faultZones = topo.getFaultZones();
  Assert.assertEquals(faultZones.size(), 10);

  Node root = topo.getRootNode();

  Assert.assertEquals(root.getChildrenCount(Topology.Types.ZONE.name()), 10);
  Assert.assertEquals(root.getChildrenCount(topo.getEndNodeType()), 100);

  // validate weights.
  for (Node rack : root.getChildren()) {
    Assert.assertEquals(rack.getWeight(), (long) nodeToWeightMap.get(rack.getName()));
  }
}