Java Code Examples for com.google.common.collect.Lists.newArrayList()

The following are Jave code examples for showing how to use newArrayList() of the com.google.common.collect.Lists class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: hadoop   File: Checkpointer.java   View Source Code Vote up 7 votes
static void rollForwardByApplyingLogs(
    RemoteEditLogManifest manifest,
    FSImage dstImage,
    FSNamesystem dstNamesystem) throws IOException {
  NNStorage dstStorage = dstImage.getStorage();

  List<EditLogInputStream> editsStreams = Lists.newArrayList();    
  for (RemoteEditLog log : manifest.getLogs()) {
    if (log.getEndTxId() > dstImage.getLastAppliedTxId()) {
      File f = dstStorage.findFinalizedEditsFile(
          log.getStartTxId(), log.getEndTxId());
      editsStreams.add(new EditLogFileInputStream(f, log.getStartTxId(), 
                                                  log.getEndTxId(), true));
    }
  }
  LOG.info("Checkpointer about to load edits from " +
      editsStreams.size() + " stream(s).");
  dstImage.loadEdits(editsStreams, dstNamesystem);
}
 
Example 2
Project: dremio-oss   File: TestFunctionsWithTypeExpoQueries.java   View Source Code Vote up 6 votes
@Test
public void testDate_Part() throws Exception {
  final String query = "select date_part('year', date '2008-2-23') as col \n" +
      "from cp.`tpch/region.parquet` \n" +
      "limit 0";

  List<Pair<SchemaPath, MajorType>> expectedSchema = Lists.newArrayList();
  MajorType majorType = Types.required(MinorType.BIGINT);
  expectedSchema.add(Pair.of(SchemaPath.getSimplePath("col"), majorType));

  testBuilder()
      .sqlQuery(query)
      .schemaBaseLine(expectedSchema)
      .build()
      .run();
}
 
Example 3
Project: MMall_JAVA   File: OrderServiceImpl.java   View Source Code Vote up 6 votes
public ServerResponse getOrderCartProduct(Integer userId) {
    OrderProductVo orderProductVo = new OrderProductVo();

    List<Cart> cartList = cartMapper.selectCheckedCartByUserId(userId);
    ServerResponse serverResponse = this.getCartOrderItem(userId, cartList);

    if (!serverResponse.isSuccess()) {
        return serverResponse;
    }
    List<OrderItem> orderItemList = (List<OrderItem>) serverResponse.getData();

    List<OrderItemVo> orderItemVoList = Lists.newArrayList();

    BigDecimal payment = new BigDecimal("0");
    for (OrderItem orderItem : orderItemList) {
        payment = BigDecimalUtil.add(payment.doubleValue(), orderItem.getTotalPrice().doubleValue());
        orderItemVoList.add(assembleOrderItemVo(orderItem));
    }
    orderProductVo.setProductTotalPrice(payment);
    orderProductVo.setOrderItemVoList(orderItemVoList);
    orderProductVo.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix"));

    return ServerResponse.createBySuccess(orderProductVo);
}
 
Example 4
Project: DecompiledMinecraft   File: CommandTrigger.java   View Source Code Vote up 6 votes
public List<String> addTabCompletionOptions(ICommandSender sender, String[] args, BlockPos pos)
{
    if (args.length == 1)
    {
        Scoreboard scoreboard = MinecraftServer.getServer().worldServerForDimension(0).getScoreboard();
        List<String> list = Lists.<String>newArrayList();

        for (ScoreObjective scoreobjective : scoreboard.getScoreObjectives())
        {
            if (scoreobjective.getCriteria() == IScoreObjectiveCriteria.TRIGGER)
            {
                list.add(scoreobjective.getName());
            }
        }

        return getListOfStringsMatchingLastWord(args, (String[])list.toArray(new String[list.size()]));
    }
    else
    {
        return args.length == 2 ? getListOfStringsMatchingLastWord(args, new String[] {"add", "set"}): null;
    }
}
 
Example 5
Project: storm-dynamic-spout   File: AbstractSchemeTest.java   View Source Code Vote up 6 votes
@Override
public List<Object> deserialize(ByteBuffer ser) {
    // If this flag is true, return null.
    if (returnNull) {
        return null;
    }

    // Probably a better way to do this juggling.
    if (ser == null) {
        return null;
    }
    ser.rewind();
    byte[] bytes = new byte[ser.remaining()];
    ser.get(bytes, 0, bytes.length);

    return Lists.newArrayList(new String(bytes, Charsets.UTF_8));
}
 
Example 6
Project: dremio-oss   File: TestTimedRunnable.java   View Source Code Vote up 6 votes
@Test
public void withTasksExceedingTimeout() throws Exception {
  UserException ex = null;

  try {
    List<TimedRunnable<Void>> tasks = Lists.newArrayList();

    for (int i = 0; i < 100; i++) {
      if ((i & (i + 1)) == 0) {
        tasks.add(new TestTask(2000));
      } else {
        tasks.add(new TestTask(20000));
      }
    }

    TimedRunnable.run("Execution with some tasks triggering timeout", logger, tasks, 16);
  } catch (UserException e) {
    ex = e;
  }

  assertNotNull("Expected a UserException", ex);
  assertThat(ex.getMessage(),
      containsString("Waited for 93750ms, but tasks for 'Execution with some tasks triggering timeout' are not " +
          "complete. Total runnable size 100, parallelism 16."));
}
 
Example 7
Project: circus-train   File: PartitionedTableMetadataUpdateReplicationTest.java   View Source Code Vote up 5 votes
@Test
public void nonExistingPartitionsAreFiltered() throws Exception {
  List<Partition> filteredPartitions = Lists.newArrayList(sourcePartition1);
  when(source.getLocationManager(sourceTable, filteredPartitions, EVENT_ID, copierOptions))
      .thenReturn(sourceLocationManager);
  when(source.getPartitions(sourceTable, PARTITION_PREDICATE, MAX_PARTITIONS)).thenReturn(partitionsAndStatistics);
  when(replica.getTable(replicaClient, DATABASE, TABLE)).thenReturn(Optional.of(previousReplicaTable));
  when(previousReplicaTable.getSd()).thenReturn(sd);
  when(sd.getLocation()).thenReturn(tableLocation);
  // mimics that the first partitions exist but second partition didn't so it will be filtered
  when(replicaClient.getPartition(DATABASE, TABLE, sourcePartition2.getValues()))
      .thenThrow(new NoSuchObjectException());

  PartitionedTableMetadataUpdateReplication replication = new PartitionedTableMetadataUpdateReplication(DATABASE,
      TABLE, partitionPredicate, source, replica, eventIdFactory, replicaLocation, DATABASE, TABLE);
  replication.replicate();

  InOrder replicationOrder = inOrder(sourceLocationManager, replica);
  replicationOrder.verify(replica).validateReplicaTable(DATABASE, TABLE);
  ArgumentCaptor<PartitionsAndStatistics> partitionsAndStatisticsCaptor = ArgumentCaptor
      .forClass(PartitionsAndStatistics.class);
  replicationOrder.verify(replica).updateMetadata(eq(EVENT_ID), eq(sourceTableAndStatistics),
      partitionsAndStatisticsCaptor.capture(), eq(sourceLocationManager), eq(DATABASE), eq(TABLE),
      any(ReplicaLocationManager.class));
  PartitionsAndStatistics value = partitionsAndStatisticsCaptor.getValue();
  assertThat(value.getPartitions().size(), is(1));
  assertThat(value.getPartitionNames().get(0), is("a=1"));
}
 
Example 8
Project: mynlp   File: FstMainTest.java   View Source Code Vote up 5 votes
@Test
public void test1() {
    List<String> list = Lists.newArrayList("我 3 公斤 ipad 30 公斤".split(" "));

    FST<String> fst = new FST<String>();

    fst.start()
            .edge(FstCondition.pattern("\\d+"), "数字")
            .edge(FstCondition.in(Sets.newHashSet("公斤")), "$$");

    fst.start()
            .edge(FstCondition.pattern("\\w+"), "单词").
            edge(FstCondition.pattern("\\d+"), "$$");


    fst.fluze();

    FstMatcher<String, String> m = fst.newMatcher(list);

    while (m.find()) {
        System.out.println(m.getStart() + "-" + m.getLength() + " " + list.subList(m.getStart(), m.getStart() + m.getLength()));
    }

    //
    // long t1 = System.currentTimeMillis();
    // for(int i=0;i<1000000;i++){
    // int j=0;
    // FstMatcher<Integer,Vertex> m1 = fst.newMatcher();
    // for(Vertex v : list){
    // m1.input(j++, v, fp);
    // }
    // }
    // long t2 = System.currentTimeMillis();
    // System.out.println(t2-t1);
}
 
Example 9
Project: businessworks   File: Elements.java   View Source Code Vote up 5 votes
private RecordingBinder(Stage stage) {
  this.stage = stage;
  this.modules = Maps.newLinkedHashMap();
  this.scanners = Sets.newLinkedHashSet();
  this.elements = Lists.newArrayList();
  this.source = null;
  this.sourceProvider = SourceProvider.DEFAULT_INSTANCE.plusSkippedClasses(
      Elements.class, RecordingBinder.class, AbstractModule.class,
      ConstantBindingBuilderImpl.class, AbstractBindingBuilder.class, BindingBuilder.class);
  this.parent = null;
  this.privateElements = null;
  this.privateBinders = Lists.newArrayList();
}
 
Example 10
Project: Equella   File: BulkEditMetadataSection.java   View Source Code Vote up 5 votes
@Override
public List<HtmlTreeNode> getChildNodes(SectionInfo info, String xpath)
{
	final List<HtmlTreeNode> list = Lists.newArrayList();
	Long schemaId = getModel(info).getSelectedSchema();
	if( schemaId == 0 )
	{
		return Collections.emptyList();
	}
	Schema schema = schemaService.get(schemaId);

	if( xpath == null )
	{
		xpath = "";
	}

	final PropBagEx schemaXml = schema.getDefinitionNonThreadSafe();
	for( PropBagEx child : schemaXml.iterator(xpath + "/*") )
	{
		String name = child.getNodeName();
		if( isAttribute(child) )
		{
			name = "@" + name;
		}
		String fullpath = Check.isEmpty(xpath) ? name : MessageFormat.format("{0}/{1}", xpath, name);
		list.add(new SchemaTreeNode(name, fullpath, isLeaf(child), isSelected(info, fullpath)));
	}

	return list;
}
 
Example 11
Project: Reer   File: DefaultDependentBinariesResolver.java   View Source Code Vote up 5 votes
private DependentBinariesResolvedResult mergeResults(Collection<DependentBinariesResolvedResult> results) {
    DependentBinariesResolvedResult first = results.iterator().next();
    if (results.size() == 1) {
        return first;
    }
    boolean hasNotBuildables = false;
    boolean hasTestSuites = false;
    LinkedListMultimap<LibraryBinaryIdentifier, DependentBinariesResolvedResult> index = LinkedListMultimap.create();
    List<DependentBinariesResolvedResult> allChildren = Lists.newArrayList();
    for (DependentBinariesResolvedResult result : results) {
        if (!result.isBuildable()) {
            hasNotBuildables = true;
        }
        if (result.isTestSuite()) {
            hasTestSuites = true;
        }
        allChildren.addAll(result.getChildren());
        for (DependentBinariesResolvedResult child : result.getChildren()) {
            index.put(child.getId(), child);
        }
    }
    List<DependentBinariesResolvedResult> children = Lists.newArrayList();
    for (Collection<DependentBinariesResolvedResult> childResults : index.asMap().values()) {
        children.add(mergeResults(childResults));
    }
    return new DefaultDependentBinariesResolvedResult(first.getId(), first.getProjectScopedName(), !hasNotBuildables, hasTestSuites, children);
}
 
Example 12
Project: redirector   File: StacksService.java   View Source Code Vote up 5 votes
List<PathItem> getStacksPathItems(Map<XreStackPath, Integer> stackToNodesCount, final Map<XreStackPath, Integer> whitelistedStackToNodesCount) {
    return Lists.newArrayList(Collections2.transform(stackToNodesCount.entrySet(), new Function<Map.Entry<XreStackPath, Integer>, PathItem>() {
        @Override
        public PathItem apply(Map.Entry<XreStackPath, Integer> input) {
            XreStackPath stack = input.getKey();
            int count = input.getValue();
            int whitelistedCount = whitelistedStackToNodesCount.containsKey(stack)
                    ? whitelistedStackToNodesCount.get(stack) : 0;

            return new PathItem(stack.getStackAndFlavorPath(), count, whitelistedCount);
        }
    }));
}
 
Example 13
Project: QDrill   File: MongoRecordReader.java   View Source Code Vote up 5 votes
@Override
public void setup(OperatorContext context, OutputMutator output) throws ExecutionSetupException {
  this.operatorContext = context;
  this.writer = new VectorContainerWriter(output);
  this.jsonReader = new JsonReader(fragmentContext.getManagedBuffer(), Lists.newArrayList(getColumns()), enableAllTextMode, false, readNumbersAsDouble);

}
 
Example 14
Project: BaseClient   File: StructureStrongholdPieces.java   View Source Code Vote up 5 votes
/**
 * sets up Arrays with the Structure pieces and their weights
 */
public static void prepareStructurePieces()
{
    structurePieceList = Lists.<StructureStrongholdPieces.PieceWeight>newArrayList();

    for (StructureStrongholdPieces.PieceWeight structurestrongholdpieces$pieceweight : pieceWeightArray)
    {
        structurestrongholdpieces$pieceweight.instancesSpawned = 0;
        structurePieceList.add(structurestrongholdpieces$pieceweight);
    }

    strongComponentType = null;
}
 
Example 15
Project: spring2ts   File: TSRequestBuilder.java   View Source Code Vote up 5 votes
private String[] defaultArgs(Param param) {
    List<String> res = Lists.newArrayList();
    if(param.hasPathVar()) res.add(param.pathVar);
    if(param.hasName()) res.add(String.format("'%s'", param.name));
    res.add(param.value);
    return res.toArray(new String[res.size()]);
}
 
Example 16
Project: Equella   File: NavigationNodeSerializerProvider.java   View Source Code Vote up 4 votes
@Override
public void writeItemBeanResult(EquellaItemBean equellaItemBean, ItemSerializerState state, long itemId)
{
	if( state.hasCategory(CATEGORY_NAVIGATION) && state.hasPrivilege(itemId, ItemSecurityConstants.VIEW_ITEM) )
	{
		final Collection<ItemNavigationNode> navigaton = state.getData(itemId, KEY_NAVIGATION_NODES);
		final boolean manualNavigation = (Boolean) state.getData(itemId, ALIAS_MANUAL_NAVIGATION);
		final boolean showSplit = (Boolean) state.getData(itemId, ALIAS_SHOW_SPLIT);

		final List<NavigationNodeBean> rootNodes = Lists.newArrayList();

		final NavigationTreeBean tree = new NavigationTreeBean();
		// TODO: add a link
		tree.setHideUnreferencedAttachments(manualNavigation);
		tree.setShowSplitOption(showSplit);
		tree.setNodes(rootNodes);

		final ListMultimap<String, NavigationNodeBean> childMap = ArrayListMultimap.create();
		final List<NavigationNodeBean> allNodeBeans = Lists.newArrayList();

		if( navigaton != null )
		{
			for( ItemNavigationNode node : navigaton )
			{
				final NavigationNodeBean bean = new NavigationNodeBean();
				// TODO: add a link
				bean.setUuid(node.getUuid());
				bean.setImsId(node.getIdentifier());
				bean.setIcon(node.getIcon());
				bean.setName(node.getName());

				final List<ItemNavigationTab> tabs = node.getTabs();
				if( tabs != null )
				{
					final List<NavigationTabBean> tabBeans = Lists.newArrayList();
					for( ItemNavigationTab tab : tabs )
					{
						final NavigationTabBean tabBean = new NavigationTabBean();
						// TODO: add a link
						tabBean.setName(tab.getName());
						tabBean.setViewer(tab.getViewer());

						// FIXME: what do we do here? It *is* just a
						// reference
						final Attachment attachment = tab.getAttachment();
						if( attachment != null )
						{
							// TODO: add a link
							tabBean.setAttachment(new UuidReference(attachment.getUuid()));
						}
						tabBeans.add(tabBean);
					}
					bean.setTabs(tabBeans);
				}

				final ItemNavigationNode parent = node.getParent();
				if( parent != null )
				{
					childMap.put(parent.getUuid(), bean);
				}
				else
				{
					rootNodes.add(bean);
				}
				allNodeBeans.add(bean);
			}
		}

		for( NavigationNodeBean nodeBean : allNodeBeans )
		{
			nodeBean.setNodes(childMap.get(nodeBean.getUuid()));
		}

		equellaItemBean.setNavigation(tree);
	}
}
 
Example 17
Project: zeratul   File: HandleExcel.java   View Source Code Vote up 4 votes
private List<List<String>> read(Workbook wb, int sheetIndex) {
    List<List<String>> dataLst = Lists.newArrayList();
    Sheet sheet = wb.getSheetAt(sheetIndex);
    this.totalRows = sheet.getPhysicalNumberOfRows();
    if ((this.totalRows >= 1) && (sheet.getRow(0) != null)) {
        this.totalCells = sheet.getRow(0).getLastCellNum(); // 获取最后一个不为空的列是第几个
    }
    for (int r = 0; r < this.totalRows; r++) {
        Row row = sheet.getRow(r);
        if (row != null) {
            List<String> rowLst = Lists.newArrayList();
            for (int c = 0; c < getTotalCells(); c++) {
                Cell cell = row.getCell(c);

                String cellValue = "";
                if (cell != null) {
                    switch (cell.getCellType()) {
                        case 0:
                            if (HSSFDateUtil.isCellDateFormatted(cell)) {
                                Date date = cell.getDateCellValue();

                                cellValue = DateUtils.dateToStr(date,
                                        "yyyy-MM-dd HH:mm:ss");

                            } else {
                                Integer num = (int) cell.getNumericCellValue();
                                cellValue = String.valueOf(num);
                            }
                            break;
                        case 1:
                            cellValue = cell.getStringCellValue().trim();
                            break;
                        case 4:
                            cellValue = String.valueOf(cell.getBooleanCellValue());
                            break;
                        case 2:
                            cellValue = cell.getCellFormula();
                            break;
                        case 3:
                            cellValue = "";
                            break;
                        case 5:
                            cellValue = "非法字符";
                            break;
                        default:
                            cellValue = "未知类型";
                    }
                }
                rowLst.add(cellValue);
            }
            dataLst.add(rowLst);
        }
    }
    return dataLst;
}
 
Example 18
Project: QDrill   File: ListSchema.java   View Source Code Vote up 4 votes
public ListSchema() {
    this.fields = Lists.newArrayList();
}
 
Example 19
Project: Equella   File: METSTreeBuilder.java   View Source Code Vote up 4 votes
/**
 * Assumes you have invoked canHandle with this builder.
 */
@Override
public List<String> determinePackageTypes(SectionInfo info, FileHandle staging, String packageFilepath)
{
	return Lists.<String> newArrayList("METS");
}
 
Example 20
Project: dragoman   File: AbstractWhereClauseListener.java   View Source Code Vote up 4 votes
public AbstractWhereClauseListener() {
  this.predicates = Lists.newArrayList();
}