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

The following are Jave code examples for showing how to use add() of the java.util.List 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: GitHub   File: RecyclerViewFragment.java   View Source Code Vote up 14 votes
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    ButterKnife.bind(this, view);

    final List<Object> items = new ArrayList<>();

    for (int i = 0; i < ITEM_COUNT; ++i) {
        items.add(new Object());
    }


    //setup materialviewpager

    if (GRID_LAYOUT) {
        mRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 2));
    } else {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    }
    mRecyclerView.setHasFixedSize(true);

    //Use this now
    mRecyclerView.addItemDecoration(new MaterialViewPagerHeaderDecorator());
    mRecyclerView.setAdapter(new TestRecyclerViewAdapter(items));
}
 
Example 2
Project: urule   File: DecisionTreeRulesBuilder.java   View Source Code Vote up 9 votes
private void buildCriterion(And and,ConditionTreeNode node){
	if(node==null)return;
	List<ConditionTreeNode> nodes=new ArrayList<ConditionTreeNode>();
	nodes.add(node);
	VariableTreeNode varNode=null;
	TreeNode parentNode=node.getParentNode();
	while(parentNode!=null){
		if(parentNode instanceof VariableTreeNode){
			varNode=(VariableTreeNode)parentNode;
			buildCriterion(and,(ConditionTreeNode)parentNode.getParentNode());
			break;
		}else if(parentNode instanceof ConditionTreeNode){
			ConditionTreeNode parentConditionTreeNode=(ConditionTreeNode)parentNode;
			nodes.add(parentConditionTreeNode);
			parentNode=parentConditionTreeNode.getParentNode();
		}
	}
	if(varNode==null){
		throw new RuleException("Decision tree is invalid.");
	}
	for(ConditionTreeNode cn:nodes){
		and.addCriterion(buildCriteria(cn,varNode));
	}
}
 
Example 3
Project: otter-G   File: PropertyPlaceholderConfigurer.java   View Source Code Vote up 7 votes
public void afterPropertiesSet() throws Exception {
    Assert.notNull(loader, "no resourceLoader");

    if (locationNames != null) {
        for (int i = 0; i < locationNames.length; i++) {
            locationNames[i] = resolveSystemPropertyPlaceholders(locationNames[i]);
        }
    }

    if (locationNames != null) {
        List<Resource> resources = new ArrayList<Resource>(locationNames.length);

        for (String location : locationNames) {
            location = trimToNull(location);

            if (location != null) {
                resources.add(loader.getResource(location));
            }
        }

        super.setLocations(resources.toArray(new Resource[resources.size()]));
    }
}
 
Example 4
Project: youtube-chat-for-minecraft   File: Main.java   View Source Code Vote up 7 votes
public static void main(String[] args) throws IOException {
  if (args.length == 0) {
    showUsage();
    return;
  }

  switch (args[0]) {
    case "login":
      System.out.print("Paste the client ID JSON from the Google API console:");
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
      String clientSecret = br.readLine();
      List<String> scopes = new ArrayList<String>();
      scopes.add(YouTubeScopes.YOUTUBE_FORCE_SSL);
      scopes.add(YouTubeScopes.YOUTUBE);
      Auth.authorize(scopes, clientSecret, YouTubeChat.MODID);
      break;
    case "logout":
      Auth.clearCredentials();
      break;
    default:
      showUsage();
  }
}
 
Example 5
Project: sub2cards   File: Line.java   View Source Code Vote up 6 votes
/**
 *
 * @param lines lines to be translated
 * @param lang src-dest languages
 * @return a new collection containing the original words and their translation
 */
public static List<Line> translateLinesParallel(List<Line> lines, String lang)  {

    List<Line> translatedLines = new ArrayList<>(lines.size());
    final ExecutorService pool = Executors.newFixedThreadPool(NB_PROCS * FACTOR);
    final ExecutorCompletionService<Line> completionService = new ExecutorCompletionService<>(pool);
    for (final Line l : lines) {
        completionService.submit(() -> l.setTranslation(
                Word.getTranslation(
                        URLEncoder.encode(l.getText(), Constants.DEFAULT_ENCODING),
                        lang)));
    }

    for (int i = 0; i < lines.size(); i++) {
        try {
            final Future<Line> future = completionService.take();
            final Line translation = future.get();
            translatedLines.add(translation);

        } catch (InterruptedException | ExecutionException e) {
        }
    }

    pool.shutdown();
    return translatedLines;
}
 
Example 6
Project: pnc-repressurized   File: GuiAdvancedLiquidCompressor.java   View Source Code Vote up 5 votes
@Override
public void addProblems(List<String> curInfo) {
    super.addProblems(curInfo);
    if (te.getEfficiency() < 100) {
        curInfo.add(I18n.format("gui.tab.problems.advancedAirCompressor.efficiency", te.getEfficiency() + "%%"));
    }
}
 
Example 7
Project: yphoto   File: StatusDetailView.java   View Source Code Vote up 5 votes
private List<Map<String, Object>> getPhotos() {

        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("photo", R.drawable.sign_in_background2);

        map = new HashMap<String, Object>();
        map.put("photo", R.drawable.sign_in_background);
        list.add(map);

        map = new HashMap<String, Object>();
        map.put("photo", R.drawable.sign_in_background2);
        list.add(map);

        map = new HashMap<String, Object>();
        map.put("photo", R.drawable.sign_in_background);
        list.add(map);

        map = new HashMap<String, Object>();
        map.put("photo", R.drawable.sign_in_background2);
        list.add(map);

        map = new HashMap<String, Object>();
        map.put("photo", R.drawable.background3);
        list.add(map);

        return list;
    }
 
Example 8
Project: Pogamut3   File: MyCollections.java   View Source Code Vote up 5 votes
/**
 * Adds 'objects' that satisfies 'filter' to 'list'.
 * @param <T>
 * @param objects
 * @param list
 * @param filter
 */
public static <T> void toList(T[] objects, List<T> list, ObjectFilter filter) {
	if (filter == null) {
		toList(objects, list);
		return;
	}
	if (objects == null) return;
	if (list == null) return;		
	for (T obj : objects) {			
		if (filter.accept(obj)) {
			list.add(obj);
		}
	}
}
 
Example 9
Project: oscm   File: UserImportBean.java   View Source Code Vote up 5 votes
/**
 * Get list of roles which the new user can be.
 * 
 * @return list with user's roles of the selected user
 * @throws ObjectNotFoundException
 * @throws OperationNotPermittedException
 */
private List<UserRole> getUserRoles() throws ObjectNotFoundException,
        OperationNotPermittedException {

    List<UserRole> result = new ArrayList<>();
    List<UserRoleType> availableRoles = getIdentityService()
            .getAvailableUserRoles(getIdentityService().getCurrentUserDetails());
    Set<UserRoleType> selectedRoles = new HashSet<>();
    if (userRolesForNewUser != null) {
        for (UserRole role : userRolesForNewUser) {
            if (role.isSelected()) {
                selectedRoles.add(role.getUserRoleType());
            }
        }
    }

    for (UserRoleType availableRole : availableRoles) {
        UserRole roleObj = new UserRole();
        roleObj.setUserRoleType(availableRole);
        if (selectedRoles.contains(availableRole)) {
            roleObj.setSelected(true);
        } else {
            roleObj.setSelected(false);
        }
        result.add(roleObj);
    }
    return result;
}
 
Example 10
Project: gitplex-mit   File: AbstractUserChoiceProvider.java   View Source Code Vote up 5 votes
@Override
public Collection<UserFacade> toChoices(Collection<String> ids) {
	List<UserFacade> users = Lists.newArrayList();
	CacheManager cacheManager = GitPlex.getInstance(CacheManager.class);
	for (String each : ids) {
		Long id = Long.valueOf(each);
		users.add(cacheManager.getUser(id));
	}

	return users;
}
 
Example 11
Project: fresco_floodlight   File: KeyedValues.java   View Source Code Vote up 5 votes
/**
   * Performs a deep copy on <i>other</i>.
   */
  public KeyedValues(KeyedValues other) {
    if (other.isSetKey()) {
      this.key = org.apache.thrift.TBaseHelper.copyBinary(other.key);
;
    }
    if (other.isSetValues()) {
      List<VersionedValue> __this__values = new ArrayList<VersionedValue>();
      for (VersionedValue other_element : other.values) {
        __this__values.add(new VersionedValue(other_element));
      }
      this.values = __this__values;
    }
  }
 
Example 12
Project: aws-sdk-java-v2   File: UuidSetToStringSetMarshaller.java   View Source Code Vote up 5 votes
@Override
public AttributeValue marshall(Object obj) {
    @SuppressWarnings("unchecked")
    Set<UUID> uuids = (Set<UUID>) obj;

    List<String> strings = new ArrayList<String>(uuids.size());
    for (UUID uuid : uuids) {
        strings.add(uuid.toString());
    }

    return AttributeValue.builder().ss(strings).build();
}
 
Example 13
Project: albedo-thrift   File: EchoSerivce.java   View Source Code Vote up 5 votes
@Override
public int hashCode() {
  List<Object> list = new ArrayList<Object>();

  boolean present_msg = true && (isSetMsg());
  list.add(present_msg);
  if (present_msg)
    list.add(msg);

  return list.hashCode();
}
 
Example 14
Project: okwallet   File: MySQLFullPrunedBlockStore.java   View Source Code Vote up 5 votes
@Override
protected List<String> getCreateTablesSQL() {
    List<String> sqlStatements = new ArrayList<>();
    sqlStatements.add(CREATE_SETTINGS_TABLE);
    sqlStatements.add(CREATE_HEADERS_TABLE);
    sqlStatements.add(CREATE_UNDOABLE_TABLE);
    sqlStatements.add(CREATE_OPEN_OUTPUT_TABLE);
    return sqlStatements;
}
 
Example 15
Project: nifi-atlas   File: TestNiFiRemotePort.java   View Source Code Vote up 5 votes
@Test
public void testRemoteInputPort() {
    final String componentType = "Remote Input Port";
    final String transitUri = "http://0.example.com:8080/nifi-api/data-transfer/input-ports/port-guid/transactions/tx-guid/flow-files";
    final ProvenanceEventRecord sendEvent = Mockito.mock(ProvenanceEventRecord.class);
    when(sendEvent.getEventId()).thenReturn(123L);
    when(sendEvent.getComponentId()).thenReturn("port-guid");
    when(sendEvent.getFlowFileUuid()).thenReturn("file-guid");
    when(sendEvent.getComponentType()).thenReturn(componentType);
    when(sendEvent.getTransitUri()).thenReturn(transitUri);
    when(sendEvent.getEventType()).thenReturn(ProvenanceEventType.SEND);

    final ProvenanceEventRecord createEvent = Mockito.mock(ProvenanceEventRecord.class);
    when(createEvent.getEventId()).thenReturn(456L);
    when(createEvent.getComponentId()).thenReturn("processor-guid");
    when(createEvent.getComponentType()).thenReturn("GenerateFlowFile");
    when(createEvent.getEventType()).thenReturn(ProvenanceEventType.CREATE);

    final ClusterResolvers clusterResolvers = Mockito.mock(ClusterResolvers.class);
    when(clusterResolvers.fromHostname(matches(".+\\.example\\.com"))).thenReturn("cluster1");

    final List<ConnectionStatus> connections = new ArrayList<>();
    final ConnectionStatus connection = new ConnectionStatus();
    connection.setDestinationId("port-guid");
    connection.setDestinationName("inputPortA");
    connections.add(connection);

    final AnalysisContext context = Mockito.mock(AnalysisContext.class);
    when(context.getClusterResolver()).thenReturn(clusterResolvers);
    when(context.findConnectionTo(matches("port-guid"))).thenReturn(connections);
    when(context.getProvenanceEvent(eq(456L))).thenReturn(createEvent);

    final ComputeLineageResult lineage = Mockito.mock(ComputeLineageResult.class);
    when(context.queryLineage(eq(123L))).thenReturn(lineage);

    final LineageNode sendEventNode = createLineageNode(PROVENANCE_EVENT_NODE, "123");
    final LineageNode flowFileNode = createLineageNode(FLOWFILE_NODE, "flowfile-uuid-1234");
    final LineageNode createEventNode = createLineageNode(PROVENANCE_EVENT_NODE, "456");

    final List<LineageEdge> edges = new ArrayList<>();
    edges.add(createLineageEdge(createEventNode, flowFileNode));
    edges.add(createLineageEdge(flowFileNode, sendEventNode));
    when(lineage.getEdges()).thenReturn(edges);

    final NiFiProvenanceEventAnalyzer analyzer = NiFiProvenanceEventAnalyzerFactory.getAnalyzer(componentType, transitUri, sendEvent.getEventType());
    assertNotNull(analyzer);

    final DataSetRefs refs = analyzer.analyze(context, sendEvent);
    assertEquals(0, refs.getInputs().size());
    assertEquals(1, refs.getOutputs().size());
    assertEquals(1, refs.getComponentIds().size());
    // Should report connected componentId.
    assertTrue(refs.getComponentIds().contains("processor-guid"));

    Referenceable ref = refs.getOutputs().iterator().next();
    assertEquals(TYPE_NIFI_INPUT_PORT, ref.getTypeName());
    assertEquals("inputPortA", ref.get(ATTR_NAME));
    assertEquals("file-guid", ref.get(ATTR_QUALIFIED_NAME));
}
 
Example 16
Project: traccar-service   File: At2000Protocol.java   View Source Code Vote up 5 votes
@Override
public void initTrackerServers(List<TrackerServer> serverList) {
    TrackerServer server = new TrackerServer(new ServerBootstrap(), getName()) {
        @Override
        protected void addSpecificHandlers(ChannelPipeline pipeline) {
            pipeline.addLast("frameDecoder", new At2000FrameDecoder());
            pipeline.addLast("objectDecoder", new At2000ProtocolDecoder(At2000Protocol.this));
        }
    };
    server.setEndianness(ByteOrder.LITTLE_ENDIAN);
    serverList.add(server);
}
 
Example 17
Project: full-javaee-app   File: Twilio.java   View Source Code Vote up 4 votes
public static boolean sendText(String number, String email, String password, String name, String type) throws TwilioRestException, InterruptedException {

        if (number != null && number.length() == 10) {
            TwilioRestClient client = new TwilioRestClient(accountSID, authToken);

            if (email.length() < 6) {
                email = number;
            }

            String welcomeBody = "Hi " + name
                    + ", it's Laura from WorkAmerica. Your job seeker profile has been created, employers can now contact you with available job opportunities! "
                    + "Your login is " + email + " and password is " + password + ". Log in to update your profile at www.workamerica.co/login or contact us at [email protected] with any issues";

            String forgotBody = "Hi " + name
                    + ", Your new password is " + password + " . Login at www.workamerica.co/login to update your profile!";

            // Build a filter for the MessageList
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("To", number));
            params.add(new BasicNameValuePair("From", "+1NUMBER_HERE"));
            params.add(new BasicNameValuePair("MessagingServiceSid", welcomeMessageSid));

            if (type != null && type.equalsIgnoreCase("forgot")) {
                params.add(new BasicNameValuePair("Body", forgotBody));
            } else {
                params.add(new BasicNameValuePair("Body", welcomeBody));
            }
            MessageFactory messageFactory = client.getAccount().getMessageFactory();

            try {
                Message response = messageFactory.create(params);
                if (response.getErrorCode() == null) {
                    return true;
                }
            } catch (TwilioRestException e) {
                e.printStackTrace();

                try {
                    String simpleNumber = CustomUtilities.cleanNumber(number.substring(2));
                    Candidates candidate = CandidatePersistence.getCandidateByPhone(simpleNumber);

                    if (candidate != null) {
                        TwilioWelcomeEvents event = new TwilioWelcomeEvents();
                        TwilioWelcome twilioWelcome = new TwilioWelcome();
                        APILogs apiLogs = candidate.getApiLogs();

                        if (apiLogs != null) {
                            twilioWelcome.setPhone(simpleNumber);
                            twilioWelcome.setBody(welcomeBody);
                            twilioWelcome.setMessageID("");
                            twilioWelcome.setSuccess("False");

                            event.setTime(Clock.getCurrentTime());
                            event.setDate(Clock.getCurrentDate());
                            event.setStatus("Failed");
                            event.setError("Exception");

                            twilioWelcome.addToTwilioWelcomeEvents(event);
                            apiLogs.addToTwilioWelcome(twilioWelcome);
                            candidate.setApiLogs(apiLogs);
                            CandidatePersistence.merge(candidate);
                        }
                    }
                } catch (Exception f) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }
 
Example 18
Project: logistimo-web-service   File: EntitiesServiceImpl.java   View Source Code Vote up 4 votes
@Override
public List<LocationSuggestionModel> getCitySuggestions(Long domainId, String text) {
  PersistenceManager pm = PMF.get().getPersistenceManager();
  Query query = null;
  List<LocationSuggestionModel> states = new ArrayList<>(8);
  try {
    query =
        pm.newQuery("javax.jdo.query.SQL",
            "SELECT DISTINCT COUNTRY, STATE, DISTRICT, TALUK, CITY FROM KIOSK WHERE CITY COLLATE UTF8_GENERAL_CI LIKE '%" + text + "%' AND KIOSKID IN " +
                "( SELECT KIOSKID_OID FROM KIOSK_DOMAINS WHERE DOMAIN_ID=" + domainId
                + ") LIMIT 8");
    List stateList = (List) query.execute();
    for (Object st : stateList) {
      String country = (String)((Object[])st)[0];
      String state = (String)((Object[])st)[1];
      String district = (String)((Object[])st)[2];
      String taluk = (String)((Object[])st)[3];
      String city = (String)((Object[])st)[4];
      LocationSuggestionModel model = new LocationSuggestionModel();
      model.label = city;
      StringBuilder sl = new StringBuilder();
      if(StringUtils.isNotBlank(taluk)) {
        sl.append(taluk).append(CharacterConstants.COMMA).append(CharacterConstants.SPACE);
      }
      if(StringUtils.isNotBlank(district)) {
        sl.append(district).append(CharacterConstants.COMMA).append(CharacterConstants.SPACE);
      }
      model.subLabel = sl.append(state).toString();
      model.state = state;
      model.country = country;
      model.district = district;
      model.taluk = taluk;
      states.add(model);
    }
    return states;
  } catch (Exception e) {
    xLogger.severe("Error while fetching taluk suggestions from domain {0}", domainId, e);
  } finally {
    if (query != null) {
      try {
        query.closeAll();
      } catch (Exception ignored) {
        xLogger.warn("Exception while closing query", ignored);
      }
    }
    pm.close();
  }
  return null;
}
 
Example 19
Project: BEAST   File: CBMCResult.java   View Source Code Vote up 4 votes
/**
 * extracts a long variable out of the output from cbmc
 * 
 * @param name
 *            the name of the variable
 * @param toExtract
 *            all the lines that should get checked, it they contain the
 *            searched var
 * @return a list of all occurrences
 */
protected List<CBMCResultWrapperLong> readLongs(String name, List<String> toExtract) {

	List<CBMCResultWrapperLong> toReturn = new ArrayList<CBMCResultWrapperLong>();

	Pattern correctChecker = Pattern.compile("(\\b" + name + "[0-9]+=[0-9]+u*)(.*)");

	Pattern longExtractor = Pattern.compile("(\\b" + name + "[0-9]+)(.*)");

	Iterator<String> iterator = getResult().iterator();
	String line = mergeLinesToOne(iterator, segmentEnder);

	line = mergeLinesToOne(iterator, segmentEnder);

	while (line.length() > 0) {

		Matcher checkerMatcher = correctChecker.matcher(line);
		if (checkerMatcher.find()) {
		    
			Matcher longMatcher = longExtractor.matcher(checkerMatcher.group(0));
			if (longMatcher.find()) {

				String longLine = longMatcher.group(1);
				// replace all no number characters
				String number = longLine.replaceAll(("[^-?0-9]*"), "");
				int electIndex = Integer.parseInt(number);

				// split at the "(" and ")" to extract the bit value
				String valueAsString = line.split("\\(")[1].split("\\)")[0];
				// prase the binary value to a long
				Long value = Long.parseLong(valueAsString, 2);

				boolean added = false;

				for (Iterator<CBMCResultWrapperLong> innerIterator = toReturn.iterator(); innerIterator
						.hasNext();) {
					CBMCResultWrapperLong wrapper = (CBMCResultWrapperLong) innerIterator.next();
					if (wrapper.getMainIndex() == electIndex) {
						wrapper.setValue(value);
						added = true;
					}
				}

				if (!added) {
					toReturn.add(new CBMCResultWrapperLong(electIndex, name));
					toReturn.get(toReturn.size() - 1).setValue(value);
				}
			}
		}
		line = mergeLinesToOne(iterator, segmentEnder);
	}
	return toReturn;
}
 
Example 20
Project: BiglyBT   File: TextWithHistory.java   View Source Code Vote up 3 votes
public void
addHistory(
	String		str )
{
	if ( disabled ){

		return;
	}

	str = str.trim();

	String key = config_prefix + ".data";

	List<String> sl = COConfigurationManager.getStringListParameter( key );

	sl.clear();

	sl.add( str );

	for ( String h: history ){

		if ( !str.startsWith( h )){

			sl.add( h );

			if ( sl.size() == MAX_HISTORY ){

				break;
			}
		}
	}

	COConfigurationManager.setParameter( key, sl );

	COConfigurationManager.setDirty();
}