Java Code Examples for java.util.ArrayList

The following are top voted examples for showing how to use java.util.ArrayList. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: esup-ecandidat   File: I18nField.java   View source code 7 votes vote down vote up
/**
 * Constructeur, initialisation du champs
 * @param listeLangueEnService 
 * @param langueParDefaut 
 * @param libelleBtnPlus 
 */
public I18nField(Langue langueParDefaut, List<Langue> listeLangueEnService, String libelleBtnPlus) {
	super();
	setRequired(false);			
	this.langueParDefaut = langueParDefaut;
	this.listeLangueEnService = listeLangueEnService;
	
	listLayoutTraductions = new ArrayList<HorizontalLayout>();
	listeTraduction = new ArrayList<I18nTraduction>();
	layoutComplet = new VerticalLayout();
	layoutComplet.setSpacing(true);
	layoutLangue = new VerticalLayout();
	layoutLangue.setSpacing(true);
	layoutComplet.addComponent(layoutLangue);
	
	btnAddLangue = new OneClickButton(libelleBtnPlus,FontAwesome.PLUS_SQUARE_O);
	btnAddLangue.setVisible(false);
	btnAddLangue.addStyleName(ValoTheme.BUTTON_TINY);
	layoutComplet.addComponent(btnAddLangue);
	btnAddLangue.addClickListener(e->{
		layoutLangue.addComponent(getLangueLayout(null));
		checkVisibleAddLangue();
		centerWindow();
	});		
}
 
Example 2
Project: guava-mock   File: TypeTokenTest.java   View source code 7 votes vote down vote up
public <N1 extends Number, N2 extends Number, N11 extends N1>
    void testisSupertypeOf_wildcardType_upperBoundMatch() {
  // ? extends T
  assertAssignable(new TypeToken<List<N11>>() {},
      new TypeToken<List<? extends N1>>() {});
  assertNotAssignable(new TypeToken<List<N1>>() {},
      new TypeToken<List<? extends N11>>() {});
  assertNotAssignable(new TypeToken<List<Number>>() {},
      new TypeToken<List<? extends N11>>() {});

  // ? extends Number
  assertAssignable(new TypeToken<List<N1>>() {},
      new TypeToken<List<? extends Number>>() {});
  assertAssignable(new TypeToken<ArrayList<N1>>() {},
      new TypeToken<List<? extends Number>>() {});
  assertAssignable(new TypeToken<List<? extends N11>>() {},
      new TypeToken<List<? extends Number>>() {});
}
 
Example 3
Project: jwala   File: GroupServiceRestImplTest.java   View source code 7 votes vote down vote up
@Test
public void testGetStoppedWebServersAndJvmsCount() {
    when(mockGroupService.getGroups()).thenReturn(new ArrayList<>(groups));
    when(mockJvmService.getJvmStoppedCount(anyString())).thenReturn(0L);
    when(mockJvmService.getJvmForciblyStoppedCount(anyString())).thenReturn(0L);
    when(mockJvmService.getJvmCount(anyString())).thenReturn(1L);
    when(mockWebServerService.getWebServerStoppedCount(anyString())).thenReturn(0L);
    when(mockWebServerService.getWebServerCount(anyString())).thenReturn(1L);

    Response response = groupServiceRest.getStoppedWebServersAndJvmsCount();
    assertNotNull(response);

    response = groupServiceRest.getStoppedWebServersAndJvmsCount("testGroup");
    assertNotNull(response);

}
 
Example 4
Project: SixBox   File: UploadFile.java   View source code 6 votes vote down vote up
public String execute() throws IOException {
    UserEntity user = (UserEntity) httpSession.get("userEntity");
    String pwd = httpServletRequest.getParameter("pwd");
    if (pwd == null || pwd.isEmpty()) {
        pwd = folderRepository.getUserRootFolder(user.getUsername(), user.getId()).getId();
    }

    for (int i = 0; i < file.length; i++) {
        FileEntity fileEntity = new FileEntity();
        fileEntity.setOwnerId(user.getId());
        fileEntity.setFilename(fileFileName[i]);
        fileEntity.setContentType(fileContentType[i]);
        fileEntity = boxService.upload(fileEntity, file[i]);

        System.out.println("1 " + pwd);
        FolderEntity folder = folderRepository.findById(pwd);
        System.out.println("2 " + folder);
        List<String> files = (folder.getFiles() == null) ? new ArrayList<>() : folder.getFiles();
        files.add(fileEntity.getId());
        folder.setFiles(files);
        folderRepository.save(folder);
    }
    return SUCCESS;
}
 
Example 5
Project: Exoplayer2Radio   File: Mp4WebvttDecoder.java   View source code 6 votes vote down vote up
@Override
protected Mp4WebvttSubtitle decode(byte[] bytes, int length, boolean reset)
    throws SubtitleDecoderException {
  // Webvtt in Mp4 samples have boxes inside of them, so we have to do a traditional box parsing:
  // first 4 bytes size and then 4 bytes type.
  sampleData.reset(bytes, length);
  List<Cue> resultingCueList = new ArrayList<>();
  while (sampleData.bytesLeft() > 0) {
    if (sampleData.bytesLeft() < BOX_HEADER_SIZE) {
      throw new SubtitleDecoderException("Incomplete Mp4Webvtt Top Level box header found.");
    }
    int boxSize = sampleData.readInt();
    int boxType = sampleData.readInt();
    if (boxType == TYPE_vttc) {
      resultingCueList.add(parseVttCueBox(sampleData, builder, boxSize - BOX_HEADER_SIZE));
    } else {
      // Peers of the VTTCueBox are still not supported and are skipped.
      sampleData.skipBytes(boxSize - BOX_HEADER_SIZE);
    }
  }
  return new Mp4WebvttSubtitle(resultingCueList);
}
 
Example 6
Project: q-mail   File: SettingsImporter.java   View source code 6 votes vote down vote up
private static List<ImportedIdentity> parseIdentities(XmlPullParser xpp)
        throws XmlPullParserException, IOException {
    List<ImportedIdentity> identities = null;

    int eventType = xpp.next();
    while (!(eventType == XmlPullParser.END_TAG && SettingsExporter.IDENTITIES_ELEMENT.equals(xpp.getName()))) {
        if (eventType == XmlPullParser.START_TAG) {
            String element = xpp.getName();
            if (SettingsExporter.IDENTITY_ELEMENT.equals(element)) {
                if (identities == null) {
                    identities = new ArrayList<>();
                }

                ImportedIdentity identity = parseIdentity(xpp);
                identities.add(identity);
            } else {
                Timber.w("Unexpected start tag: %s", xpp.getName());
            }
        }
        eventType = xpp.next();
    }

    return identities;
}
 
Example 7
Project: xray   File: RunawayReport.java   View source code 6 votes vote down vote up
@Override
public String recommendations() {
	List<Metric> metrics = data.entrySet().stream()
			.map(entry -> entry.getValue().entrySet().stream()
					.map(data -> new Metric(entry.getKey(), data.getKey(), data.getValue()))
					.collect(Collectors.toList()))
			.collect(ArrayList::new, List::addAll, List::addAll);

	Map<String, List<Metric>> runaways = new HashMap<>();
	metrics.stream().collect(Collectors.groupingBy(Metric::name)).entrySet().forEach(entry -> {
		LongSummaryStatistics statistics = entry.getValue().stream()
				.collect(Collectors.summarizingLong(Metric::value));
		runaways.put(entry.getKey(),
				entry.getValue().stream().filter(metric -> metric.value() <= statistics.getAverage())
						.sorted((m1, m2) -> (int) (m1.value() - m2.value())).collect(Collectors.toList()));
	});

	return this.buildRunaways(runaways);
}
 
Example 8
Project: android-autofittextview   File: AutofitHelper.java   View source code 6 votes vote down vote up
/**
 * Adds an {@link OnTextSizeChangeListener} to the list of those whose methods are called
 * whenever the {@link TextView}'s {@code textSize} changes.
 */
public AutofitHelper addOnTextSizeChangeListener(OnTextSizeChangeListener listener) {
    if (mListeners == null) {
        mListeners = new ArrayList<OnTextSizeChangeListener>();
    }
    mListeners.add(listener);
    return this;
}
 
Example 9
Project: shibboleth-idp-oidc-extension   File: OIDCScopedStringAttributeEncoderTest.java   View source code 6 votes vote down vote up
@Test
public void testEncoding() throws ComponentInitializationException, AttributeEncodingException {
    init();
    IdPAttribute attribute = new IdPAttribute("test");
    List<ScopedStringAttributeValue> stringAttributeValues = new ArrayList<ScopedStringAttributeValue>();
    stringAttributeValues.add(new ScopedStringAttributeValue("value1", "scope"));
    stringAttributeValues.add(new ScopedStringAttributeValue("value2", "scope"));
    attribute.setValues(stringAttributeValues);
    JSONObject object = encoder.encode(attribute);
    Assert.assertTrue(((String) object.get("attributeName")).split(" ")[0].equals("[email protected]"));
    Assert.assertTrue(((String) object.get("attributeName")).split(" ")[1].equals("[email protected]"));
    Assert.assertTrue(((String) object.get("attributeName")).split(" ").length == 2);
    encoder.setScopeDelimiter(":");
    encoder.setStringDelimiter(";");
    object = encoder.encode(attribute);
    Assert.assertTrue(((String) object.get("attributeName")).split(";")[0].equals("value1:scope"));
    Assert.assertTrue(((String) object.get("attributeName")).split(";")[1].equals("value2:scope"));
    Assert.assertTrue(((String) object.get("attributeName")).split(";").length == 2);
}
 
Example 10
Project: oscm   File: MarketplaceBeanTest.java   View source code 6 votes vote down vote up
@Test
public void testGetMarketplacesForService() throws Exception {
    returnedCatalogEntries = new ArrayList<VOCatalogEntry>();
    returnedCatalogEntries.add(localMarketplaceCE);
    returnedCatalogEntries.add(globalMarketplaceCE);
    VOService service = new VOService();

    List<VOCatalogEntry> catalogEntries = bean
            .getMarketplacesForService(service);

    Assert.assertEquals(service, passedService);
    Assert.assertTrue(serviceCalled);
    Assert.assertEquals(2, catalogEntries.size());
    Assert.assertEquals(localMarketplaceCE.getMarketplace()
            .getMarketplaceId(), catalogEntries.get(0).getMarketplace()
            .getMarketplaceId());
    Assert.assertEquals(globalMarketplaceCE.getMarketplace()
            .getMarketplaceId(), catalogEntries.get(1).getMarketplace()
            .getMarketplaceId());

    serviceCalled = true;
    returnedMarketplaces = new ArrayList<VOMarketplace>();
    bean.getMarketplacesForSupplier();
    Assert.assertTrue(serviceCalled);
}
 
Example 11
Project: McrmbCore_Sponge   File: McrmbPluginInfo.java   View source code 6 votes vote down vote up
public static void initMcrmbCore() {
    commentedConfig = ConfigManager.get().getConfig();
    config.sid = commentedConfig.getNode("sid").getString();
    if (config.sid.equalsIgnoreCase("null")) {
        config.sid = null;
    }
    config.key = commentedConfig.getNode("key").getString();
    if (config.key.equalsIgnoreCase("null")) {
        config.key = null;
    }

    config.logApi = commentedConfig.getNode("logApi").getBoolean();
    config.renewOnJoin = commentedConfig.getNode("renewOnJoin").getBoolean();
    config.opModifyWhiteList = new ArrayList<>();
    try {
        config.opModifyWhiteList.addAll(commentedConfig.getNode("opModifyWhiteList").getList(TypeToken.of(String.class)));
    } catch (ObjectMappingException e) {
    }
    config.point = commentedConfig.getNode("point").getString().replace("&", "§");
    config.prefix = commentedConfig.getNode("prefix").getString().replace("&", "§");
    config.command = commentedConfig.getNode("command").getString();

}
 
Example 12
Project: fabric8-build   File: MavenEnricherManager.java   View source code 6 votes vote down vote up
private static ClassLoader[] createProjectClassLoader(MavenProjectContext projectContext) {
    try {
        List<URL> compileJars = new ArrayList<>();

        for (String element : projectContext.getProject().getCompileClasspathElements()) {
            compileJars.add(new File(element).toURI().toURL());
        }
        return new ClassLoader[]{
            new URLClassLoader(compileJars.toArray(new URL[compileJars.size()]),
                               MavenEnricherManager.class.getClassLoader())
        };

    } catch (Exception e) {
        projectContext.getLogger().warn("Instructed to use project classpath, but cannot. Continuing build if we can: ", e);
        return new ClassLoader[0];
    }
}
 
Example 13
Project: incubator-netbeans   File: SuiteProject.java   View source code 6 votes vote down vote up
private PropertyEvaluator createEvaluator() {
    PropertyProvider predefs = helper.getStockPropertyPreprovider();
    File dir = getProjectDirectoryFile();
    List<PropertyProvider> providers = new ArrayList<PropertyProvider>();
    providers.add(helper.getPropertyProvider("nbproject/private/platform-private.properties")); // NOI18N
    providers.add(helper.getPropertyProvider("nbproject/platform.properties")); // NOI18N
    PropertyEvaluator baseEval = PropertyUtils.sequentialPropertyEvaluator(predefs, providers.toArray(new PropertyProvider[providers.size()]));
    providers.add(new ApisupportAntUtils.UserPropertiesFileProvider(baseEval, dir));
    baseEval = PropertyUtils.sequentialPropertyEvaluator(predefs, providers.toArray(new PropertyProvider[providers.size()]));
    providers.add(new DestDirProvider(baseEval));
    providers.add(helper.getPropertyProvider(AntProjectHelper.PRIVATE_PROPERTIES_PATH));
    providers.add(helper.getPropertyProvider(AntProjectHelper.PROJECT_PROPERTIES_PATH));
    Map<String,String> fixedProps = new HashMap<String,String>();
    // synchronize with suite.xml
    fixedProps.put(SuiteProperties.ENABLED_CLUSTERS_PROPERTY, "");
    fixedProps.put(SuiteProperties.DISABLED_CLUSTERS_PROPERTY, "");
    fixedProps.put(SuiteProperties.DISABLED_MODULES_PROPERTY, "");
    fixedProps.put(SuiteBrandingModel.BRANDING_DIR_PROPERTY, "branding"); // NOI18N
    fixedProps.put("suite.build.dir", "build"); // NOI18N
    fixedProps.put("cluster", "${suite.build.dir}/cluster"); // NOI18N
    fixedProps.put("dist.dir", "dist"); // NOI18N
    fixedProps.put("test.user.dir", "${suite.build.dir}/testuserdir"); // NOI18N
    providers.add(PropertyUtils.fixedPropertyProvider(fixedProps));
    return PropertyUtils.sequentialPropertyEvaluator(predefs, providers.toArray(new PropertyProvider[providers.size()]));
}
 
Example 14
Project: loom   File: FileUtils.java   View source code 6 votes vote down vote up
protected static List<File> getAllAncestors(File base, File file) {
    List<File> files = new ArrayList<>();
    if (file != null) {
        boolean stop = false;
        file = file.getParentFile();
        while (!stop) {
            if (file == null || !file.toPath().startsWith(base.toPath())) {
                stop = true;
            } else {
                files.add(file);
                file = file.getParentFile();
            }
        }
    }
    return files;
}
 
Example 15
Project: jol-samples   File: JOLSample_16_AL_LL.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    out.println(VM.current().details());

    ArrayList<Integer> al = new ArrayList<Integer>();
    LinkedList<Integer> ll = new LinkedList<Integer>();

    for (int i = 0; i < 1000; i++) {
        Integer io = i; // box once
        al.add(io);
        ll.add(io);
    }

    al.trimToSize();

    PrintWriter pw = new PrintWriter(out);
    pw.println(GraphLayout.parseInstance(al).toFootprint());
    pw.println(GraphLayout.parseInstance(ll).toFootprint());
    pw.println(GraphLayout.parseInstance(al, ll).toFootprint());
    pw.close();
}
 
Example 16
Project: central-medic-center   File: DatabaseHelper.java   View source code 6 votes vote down vote up
public ArrayList<Lab> getLab() {
	try {
		PreparedStatement ps = connection.prepareStatement("select * from lab");
		ResultSet rs = ps.executeQuery();
		ArrayList<Lab> labs = new ArrayList<Lab>();
		while (rs.next()) {
			Lab lab = new Lab(rs.getInt("labId"), rs.getString("labName"), rs.getString("testFor"),rs.getString("labResult"),
					rs.getString("reportFile"),rs.getInt("itemId"),getDoctor(rs.getInt("doctorId")));
			labs.add(lab);
		}
		return labs;
	} catch (SQLException e) {
		e.printStackTrace();
		return null;
	}
}
 
Example 17
Project: defense-solutions-proofs-of-concept   File: TcpSquirtOutboundTransportDefinition.java   View source code 6 votes vote down vote up
public TcpSquirtOutboundTransportDefinition()
{
	super(TransportType.OUTBOUND);
	try
	{
		propertyDefinitions.put("host", new PropertyDefinition("host", PropertyType.String, "localhost", "${com.esri.geoevent.solutions.transport.tcpsquirt.tcpsquirt-transport.LBL_HOST}", "${com.esri.geoevent.solutions.transport.tcpsquirt.tcpsquirt-transport.DESC_HOST}", false, false));
		propertyDefinitions.put("port", new PropertyDefinition("port", PropertyType.Integer, new Integer(5000), "${com.esri.geoevent.solutions.transport.tcpsquirt.tcpsquirt-transport.LBL_PORT}", "${com.esri.geoevent.solutions.transport.tcpsquirt.tcpsquirt-transport.DESC_PORT}", true, false));
		List<LabeledValue> allowedModes = new ArrayList<LabeledValue>();
		allowedModes.add(new LabeledValue("${com.esri.geoevent.solutions.transport.tcpsquirt.tcpsquirt-transport.ALLOWED_MODE_SERVER}", "SERVER"));
		allowedModes.add(new LabeledValue("${com.esri.geoevent.solutions.transport.tcpsquirt.tcpsquirt-transport.ALLOWED_MODE_CLIENT}", "CLIENT"));
		propertyDefinitions.put("mode", new PropertyDefinition("mode", PropertyType.String, "${com.esri.geoevent.solutions.transport.tcpsquirt.tcpsquirt-transport.MODE_SERVER_LBL}", "${com.esri.geoevent.solutions.transport.tcpsquirt.tcpsquirt-transport.LBL_MODE}", "${com.esri.geoevent.solutions.transport.tcpsquirt.tcpsquirt-transport.DESC_MODE}", true, false, allowedModes));
		propertyDefinitions.put("clientConnectionTimeout", new PropertyDefinition("clientConnectionTimeout", PropertyType.Integer, new Integer(60), "{com.esri.geoevent.solutions.transport.tcpsquirt.tcpsquirt-transport.LBL_TIMEOUT}", "{com.esri.geoevent.solutions.transport.tcpsquirt.tcpsquirt-transport.DESC_TIMEOUT}", "mode=CLIENT", false, false));
	}
	catch (PropertyException e)
	{
		LOG.error("Failed to define properties of TCPSquirtOutboundTransportDefinition: ", e);
		throw new RuntimeException(e);
	}
}
 
Example 18
Project: alfresco-repository   File: DbNodeServiceImpl.java   View source code 6 votes vote down vote up
public Collection<NodeRef> getParents(NodeRef nodeRef) throws InvalidNodeRefException
{
    List<ChildAssociationRef> parentAssocs = getParentAssocs(
            nodeRef,
            RegexQNamePattern.MATCH_ALL,
            RegexQNamePattern.MATCH_ALL);
    
    // Copy into the set to avoid duplicates
    Set<NodeRef> parentNodeRefs = new HashSet<NodeRef>(parentAssocs.size());
    for (ChildAssociationRef parentAssoc : parentAssocs)
    {
        NodeRef parentNodeRef = parentAssoc.getParentRef();
        parentNodeRefs.add(parentNodeRef);
    }
    // Done
    return new ArrayList<NodeRef>(parentNodeRefs);
}
 
Example 19
Project: incubator-netbeans   File: InstalledFileLocatorImpl.java   View source code 6 votes vote down vote up
public InstalledFileLocatorImpl() {
    super();
    File endorsedDir = new File(System.getProperty("java.endorsed.dirs"));
    for (int i = 0; i < 5; i++) {
        endorsedDir = endorsedDir.getParentFile();
    }

    File installRoot = endorsedDir;
    File[] subdirs = installRoot.listFiles();
    baseDirs = new ArrayList<File>();

    for (int i = 0; subdirs != null && i < subdirs.length; i++) {
        if (subdirs[i].isDirectory()) {
            baseDirs.add(subdirs[i]);
        }
    }
}
 
Example 20
Project: lemon   File: TaskDefinitionConnectorImpl.java   View source code 6 votes vote down vote up
/**
 * 提醒.
 */
public List<TaskNotificationDTO> findTaskNotifications(
        String taskDefinitionKey, String processDefinitionId,
        String eventName) {
    String hql = "from TaskDefNotification where taskDefBase.code=? and taskDefBase.processDefinitionId=? and eventName=?";
    List<TaskDefNotification> taskDefNotifications = taskDefNotificationManager
            .find(hql, taskDefinitionKey, processDefinitionId, eventName);

    if (taskDefNotifications.isEmpty()) {
        return Collections.emptyList();
    }

    List<TaskNotificationDTO> taskNotifications = new ArrayList<TaskNotificationDTO>();

    for (TaskDefNotification taskDefNotification : taskDefNotifications) {
        TaskNotificationDTO taskNotification = new TaskNotificationDTO();
        taskNotification.setEventName(eventName);
        taskNotification.setType(taskDefNotification.getType());
        taskNotification.setReceiver(taskDefNotification.getReceiver());
        taskNotification.setTemplateCode(taskDefNotification
                .getTemplateCode());
        taskNotifications.add(taskNotification);
    }

    return taskNotifications;
}
 
Example 21
Project: WordLing   File: WordpackParser.java   View source code 6 votes vote down vote up
public WordpackList getWordpackListFromText(String text) {

        try {
            ArrayList<WordpackEntry> entriesList = new ArrayList<>();
            JSONArray wordpackList = new JSONArray(text);

            for (int i = 0; i < wordpackList.length(); i++) {
                JSONObject jsonEntry = wordpackList.getJSONObject(i);

                if (jsonEntry.has("title") && jsonEntry.has("key") && jsonEntry.has("description")) {
                    WordpackEntry singleEntry = new WordpackEntry(
                            jsonEntry.getString("key"),
                            jsonEntry.getString("title"),
                            jsonEntry.getString("description")
                    );
                    entriesList.add(singleEntry);
                }
            }
            return new WordpackList(entriesList);
        } catch (JSONException e) {
            Log.v("WordLing", "Error occured when parsing wordpack list");
            e.printStackTrace();
        }

        return null;
    }
 
Example 22
Project: commercetools-sync-java   File: CategoryITUtils.java   View source code 6 votes vote down vote up
/**
 * Builds a list of the supplied number ({@code numberOfCategories}) of CategoryDraft objects that can be used for
 * integration tests to mimic existing categories in a target CTP project for example. All the newly created
 * category drafts will have {@code parentCategory} as a parent.
 *
 * @param numberOfCategories the number of category drafts to create.
 * @param parentCategory     the parent of the drafts.
 * @return a list of CategoryDrafts.
 */
public static List<CategoryDraft> getCategoryDrafts(@Nullable final Category parentCategory,
                                                    final int numberOfCategories) {
    List<CategoryDraft> categoryDrafts = new ArrayList<>();
    for (int i = 0; i < numberOfCategories; i++) {
        final LocalizedString name = LocalizedString.of(Locale.ENGLISH, format("draft%s", i + 1));
        final LocalizedString slug = LocalizedString.of(Locale.ENGLISH, format("slug%s", i + 1));
        final LocalizedString description = LocalizedString.of(Locale.ENGLISH, format("desc%s", i + 1));
        final String key = format("key%s", i + 1);
        final String orderHint = format("0.%s", i + 1);
        final CategoryDraft categoryDraft = CategoryDraftBuilder.of(name, slug)
                                                                .parent(parentCategory)
                                                                .description(description)
                                                                .key(key)
                                                                .orderHint(orderHint)
                                                                .custom(getCustomFieldsDraft())
                                                                .build();
        categoryDrafts.add(categoryDraft);
    }
    return categoryDrafts;
}
 
Example 23
Project: incubator-netbeans   File: CopyPathToClipboardActionTest.java   View source code 5 votes vote down vote up
@Test
public void testGetSelectedPathsForProjects() {
    List<String> paths = new ArrayList<String>(
            action.getSelectedPathsForProjects());
    assertTrue(paths.get(0).endsWith("projectDir1")); // path for project 1
    assertTrue(paths.get(1).endsWith("projectDir2")); // path for project 2
}
 
Example 24
Project: JRediClients   File: RedissonScoredSortedSet.java   View source code 5 votes vote down vote up
@Override
public RFuture<Integer> unionAsync(Aggregate aggregate, String... names) {
    List<Object> args = new ArrayList<Object>(names.length + 4);
    args.add(getName());
    args.add(names.length);
    args.addAll(Arrays.asList(names));
    args.add("AGGREGATE");
    args.add(aggregate.name());
    return commandExecutor.writeAsync(getName(), LongCodec.INSTANCE, RedisCommands.ZUNIONSTORE_INT, args.toArray());
}
 
Example 25
Project: oscm   File: VatBean.java   View source code 5 votes vote down vote up
public void setVatEnabled(Boolean vatEnabled) {
    reset();
    dirty = !vatEnabled.equals(getVatEnabled());
    if (vatEnabled.booleanValue()) {
        if (getDefaultVat() == null) {
            defaultVat = new VOVatRate();
            addToVatStrings(defaultVat);
        }
    } else {
        defaultVat = null;
        try {
            countryVats = new ArrayList<>();
            countries = getAccountingService().getSupportedCountryCodes();
            if (countries.size() > 0) {
                countryVats.add(new VOCountryVatRate());
            }
            customerVats = new ArrayList<>();
            customers = getAccountingService().getMyCustomersOptimization();
            if (customers.size() > 0) {
                customerVats.add(new VOOrganizationVatRate());
            }
            customerNames = new HashMap<>();
        } catch (SaaSApplicationException e) {
            ExceptionHandler.execute(e);
        }
    }
    this.vatEnabled = vatEnabled;
}
 
Example 26
Project: kafka-connect-hdfs   File: ParquetHiveUtilTest.java   View source code 5 votes vote down vote up
@Test
public void testCreateTable() throws Exception {
  prepareData(TOPIC, PARTITION);
  Partitioner partitioner = HiveTestUtils.getPartitioner();

  Schema schema = createSchema();
  hive.createTable(hiveDatabase, TOPIC, schema, partitioner);
  String location = "partition=" + String.valueOf(PARTITION);
  hiveMetaStore.addPartition(hiveDatabase, TOPIC, location);

  List<String> expectedColumnNames = new ArrayList<>();
  for (Field field: schema.fields()) {
    expectedColumnNames.add(field.name());
  }

  Table table = hiveMetaStore.getTable(hiveDatabase, TOPIC);
  List<String> actualColumnNames = new ArrayList<>();
  for (FieldSchema column: table.getSd().getCols()) {
    actualColumnNames.add(column.getName());
  }

  assertEquals(expectedColumnNames, actualColumnNames);
  List<FieldSchema> partitionCols = table.getPartitionKeys();
  assertEquals(1, partitionCols.size());
  assertEquals("partition", partitionCols.get(0).getName());

  String[] expectedResult = {"true", "12", "12", "12.2", "12.2", "12"};
  String result = HiveTestUtils.runHive(hiveExec, "SELECT * FROM " + TOPIC);
  String[] rows = result.split("\n");
  // Only 6 of the 7 records should have been delivered due to flush_size = 3
  assertEquals(6, rows.length);
  for (String row: rows) {
    String[] parts = HiveTestUtils.parseOutput(row);
    for (int j = 0; j < expectedResult.length; ++j) {
      assertEquals(expectedResult[j], parts[j]);
    }
  }
}
 
Example 27
Project: SoftUni   File: Main.java   View source code 5 votes vote down vote up
public static void main(String[] args) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    List<Box> objects = new ArrayList<>();

    int count = Integer.parseInt(reader.readLine());

    for (int i = 0; i < count; i++) {
        objects.add(new Box(Double.parseDouble(reader.readLine())));
    }

    int greaterElements = Box.countOfGreaterElements(objects, Double.parseDouble(reader.readLine()));

    System.out.println(greaterElements);
}
 
Example 28
Project: convertigo-engine   File: Connector.java   View source code 5 votes vote down vote up
@Override
public Connector clone() throws CloneNotSupportedException {
	Connector clonedObject = (Connector) super.clone();
	clonedObject.defaultTransaction = null;
	clonedObject.connectorListeners = new EventListenerList();
	clonedObject.vTransactions = new ArrayList<Transaction>();
	clonedObject.vPools = new ArrayList<Pool>();
	clonedObject.vDocuments = new ArrayList<com.twinsoft.convertigo.beans.core.Document>();
	clonedObject.vListeners = new ArrayList<com.twinsoft.convertigo.beans.core.Listener>();
	clonedObject.debugging = false;
	return clonedObject;
}
 
Example 29
Project: OpenJSharp   File: AbstractQueuedLongSynchronizer.java   View source code 5 votes vote down vote up
/**
 * Returns a collection containing threads that may be waiting to
 * acquire in shared mode. This has the same properties
 * as {@link #getQueuedThreads} except that it only returns
 * those threads waiting due to a shared acquire.
 *
 * @return the collection of threads
 */
public final Collection<Thread> getSharedQueuedThreads() {
    ArrayList<Thread> list = new ArrayList<Thread>();
    for (Node p = tail; p != null; p = p.prev) {
        if (p.isShared()) {
            Thread t = p.thread;
            if (t != null)
                list.add(t);
        }
    }
    return list;
}
 
Example 30
Project: ditb   File: Hbase.java   View source code 5 votes vote down vote up
@Override
public int hashCode() {
  List<Object> list = new ArrayList<Object>();

  boolean present_success = true && (isSetSuccess());
  list.add(present_success);
  if (present_success)
    list.add(success);

  boolean present_io = true && (isSetIo());
  list.add(present_io);
  if (present_io)
    list.add(io);

  return list.hashCode();
}
 
Example 31
Project: parabuild-ci   File: Bag.java   View source code 5 votes vote down vote up
public Bag(SessionImplementor session, java.util.Collection coll) {
	super(session);
	if (coll instanceof java.util.List) {
		bag = (java.util.List) coll;
	}
	else {
		bag = new ArrayList();
		Iterator iter = coll.iterator();
		while ( iter.hasNext() ) {
			bag.add( iter.next() );
		}
	}
	setInitialized();
	setDirectlyAccessible(true);
}
 
Example 32
Project: LaunchTime   File: DB.java   View source code 5 votes vote down vote up
public void setAppCategoryOrder(String catID, List<AppLauncher> apps) {
    List<ComponentName> actvnames = new ArrayList<>();
    for (AppLauncher app : apps) {
        actvnames.add(new ComponentName(app.getPackageName(), app.getActivityName()));
    }
    setAppCategoryOrder(catID, actvnames, true);
}
 
Example 33
Project: GitHub   File: FlexibleAdapter.java   View source code 5 votes vote down vote up
/**
 * Provides all the items that belongs to the section represented by the provided header.
 *
 * @param header the {@code IHeader} item that represents the section
 * @return NonNull list of all items in the provided section
 * @since 5.0.0-b6
 */
@NonNull
public List<ISectionable> getSectionItems(@NonNull IHeader header) {
	List<ISectionable> sectionItems = new ArrayList<>();
	int startPosition = getGlobalPositionOf(header);
	T item = getItem(++startPosition);
	while (hasSameHeader(item, header)) {
		sectionItems.add((ISectionable) item);
		item = getItem(++startPosition);
	}
	return sectionItems;
}
 
Example 34
Project: kafka-0.11.0.0-src-with-comment   File: KafkaBasedLog.java   View source code 5 votes vote down vote up
public void start() {
    log.info("Starting KafkaBasedLog with topic " + topic);

    initializer.run();
    producer = createProducer();
    consumer = createConsumer();

    List<TopicPartition> partitions = new ArrayList<>();

    // We expect that the topics will have been created either manually by the user or automatically by the herder
    List<PartitionInfo> partitionInfos = null;
    long started = time.milliseconds();
    while (partitionInfos == null && time.milliseconds() - started < CREATE_TOPIC_TIMEOUT_MS) {
        partitionInfos = consumer.partitionsFor(topic);
        Utils.sleep(Math.min(time.milliseconds() - started, 1000));
    }
    if (partitionInfos == null)
        throw new ConnectException("Could not look up partition metadata for offset backing store topic in" +
                " allotted period. This could indicate a connectivity issue, unavailable topic partitions, or if" +
                " this is your first use of the topic it may have taken too long to create.");

    for (PartitionInfo partition : partitionInfos)
        partitions.add(new TopicPartition(partition.topic(), partition.partition()));
    consumer.assign(partitions);

    readToLogEnd();

    thread = new WorkThread();
    thread.start();

    log.info("Finished reading KafkaBasedLog for topic " + topic);

    log.info("Started KafkaBasedLog for topic " + topic);
}
 
Example 35
Project: stock-api-sdk   File: StockFileTest.java   View source code 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test(groups = { "Setters" })
void setKeywords_sets_localised_list_of_keywords_from_file()
        throws NoSuchFieldException, IllegalAccessException {
    ArrayList<StockFileKeyword> list = new ArrayList<StockFileKeyword>();
    StockFileKeyword keyword = new StockFileKeyword();
    keyword.setName("Text");
    list.add(keyword);
    stockFile.setKeywords(list);
    Field f = stockFile.getClass().getDeclaredField("mKeywords");
    f.setAccessible(true);
    list = (ArrayList<StockFileKeyword>) f.get(stockFile);
    // Assert.assertTrue(list.get(0).equals("Text"));

}
 
Example 36
Project: Pogamut3   File: Bvh.java   View source code 5 votes vote down vote up
public float getAverageNodeVolume(ArrayList<BvhNodeT> nodes, int depth){
  int count = 0;
  float volume = 0;
  for(BvhNodeT n : nodes){
    if( n._getDepth() == depth){
      count++;     
      volume+=n._getAABB().getVolume();
    }
  }
  return volume/count;
}
 
Example 37
Project: ditb   File: IllegalArgument.java   View source code 5 votes vote down vote up
@Override
public int hashCode() {
  List<Object> list = new ArrayList<Object>();

  boolean present_message = true && (isSetMessage());
  list.add(present_message);
  if (present_message)
    list.add(message);

  return list.hashCode();
}
 
Example 38
Project: Proyecto-DASI   File: MalmoModClient.java   View source code 5 votes vote down vote up
/** Set up some handy extra keys:
 * @param settings Minecraft's original GameSettings object
 */
private void setUpExtraKeys(GameSettings settings)
{
    // Create extra key bindings here and pass them to the KeyManager.
    ArrayList<InternalKey> extraKeys = new ArrayList<InternalKey>();
    // Create a key binding to toggle between player and Malmo control:
    extraKeys.add(new InternalKey("key.toggleMalmo", 28, "key.categories.malmo")	// 28 is the keycode for enter.
    {
        @Override
        public void onPressed()
        {
            InputType it = (inputType != InputType.AI) ? InputType.AI : InputType.HUMAN;
            System.out.println("Toggling control between human and AI - now " + it);
            setInputType(it);
            super.onPressed();
        }
    });

    extraKeys.add(new InternalKey("key.handyTestHook", 22, "key.categories.malmo")
    {
        @Override
        public void onPressed()
        {
            // Use this if you want to test some code with a handy key press
            try
            {
                CraftingHelper.dumpRecipes("recipe_dump.txt");
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    });
    this.keyManager = new KeyManager(settings, extraKeys);
}
 
Example 39
Project: ta4j   File: AbstractAnalysisCriterionTest.java   View source code 5 votes vote down vote up
@Before
public void setUp() {
    alwaysStrategy = new BaseStrategy(BooleanRule.TRUE, BooleanRule.TRUE);
    buyAndHoldStrategy = new BaseStrategy(new FixedRule(0), new FixedRule(4));
    strategies = new ArrayList<Strategy>();
    strategies.add(alwaysStrategy);
    strategies.add(buyAndHoldStrategy);
}
 
Example 40
Project: com.zsmartsystems.zigbee   File: ZigBeeNetworkManager.java   View source code 5 votes vote down vote up
public void removeNetworkNodeListener(final ZigBeeNetworkNodeListener networkNodeListener) {
    synchronized (this) {
        final List<ZigBeeNetworkNodeListener> modifiedListeners = new ArrayList<ZigBeeNetworkNodeListener>(
                nodeListeners);
        modifiedListeners.remove(networkNodeListener);
        nodeListeners = Collections.unmodifiableList(modifiedListeners);
    }
}