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

The following examples show how to use java.util.List#replaceAll() .
Example 1
Project: nifi   File: TestCSVRecordReader.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testMultipleRecordsEscapedWithSpecialChar() throws IOException, MalformedRecordException {

    char delimiter = StringEscapeUtils.unescapeJava("\u0001").charAt(0);

    final CSVFormat format = CSVFormat.DEFAULT.withFirstRecordAsHeader().withTrim().withQuote('"').withDelimiter(delimiter);
    final List<RecordField> fields = getDefaultFields();
    fields.replaceAll(f -> f.getFieldName().equals("balance") ? new RecordField("balance", doubleDataType) : f);

    final RecordSchema schema = new SimpleRecordSchema(fields);

    try (final InputStream fis = new FileInputStream(new File("src/test/resources/csv/multi-bank-account_escapedchar.csv"));
        final CSVRecordReader reader = createReader(fis, schema, format)) {

        final Object[] firstRecord = reader.nextRecord().getValues();
        final Object[] firstExpectedValues = new Object[] {"1", "John Doe", 4750.89D, "123 My Street", "My City", "MS", "11111", "USA"};
        Assert.assertArrayEquals(firstExpectedValues, firstRecord);

        final Object[] secondRecord = reader.nextRecord().getValues();
        final Object[] secondExpectedValues = new Object[] {"2", "Jane Doe", 4820.09D, "321 Your Street", "Your City", "NY", "33333", "USA"};
        Assert.assertArrayEquals(secondExpectedValues, secondRecord);

        assertNull(reader.nextRecord());
    }
}
 
Example 2
Project: openemm   File: ComWorkflowServiceImpl.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
public String getTargetExpression() {
    List<String> expressions = new ArrayList<>(recipients.size());

    for (WorkflowRecipient recipient : recipients) {
        List<Integer> targetIds = recipient.getTargets();
        if (CollectionUtils.isNotEmpty(targetIds)) {
            expressions.add(TargetExpressionUtils.makeTargetExpression(targetIds, recipient.getTargetsOption()));
        }
    }

    if (expressions.size() > 1) {
        // Wrap separate expressions with brackets if they use OR operator.
        expressions.replaceAll(e -> e.contains("|") ? ("(" + e + ")") : (e));
    }

    return StringUtils.join(expressions, '&');
}
 
Example 3
Project: jdk8u-jdk   File: ListDefaults.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testReplaceAllThrowsCME() {
    @SuppressWarnings("unchecked")
    final CollectionSupplier<List<Integer>> supplier = new CollectionSupplier(LIST_CME_SUPPLIERS, SIZE);
    for (final CollectionSupplier.TestCase<List<Integer>> test : supplier.get()) {
        final List<Integer> list = test.collection;

        if (list.size() <= 1) {
            continue;
        }
        boolean gotException = false;
        try {
            // bad predicate that modifies its list, should throw CME
            list.replaceAll(x -> {int n = 3 * x; list.add(n); return n;});
        } catch (ConcurrentModificationException cme) {
            gotException = true;
        }
        if (!gotException) {
            fail("expected CME was not thrown from " + test);
        }
    }
}
 
Example 4
Project: jdk8u60   File: ListDefaults.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testReplaceAllThrowsCME() {
    @SuppressWarnings("unchecked")
    final CollectionSupplier<List<Integer>> supplier = new CollectionSupplier(LIST_CME_SUPPLIERS, SIZE);
    for (final CollectionSupplier.TestCase<List<Integer>> test : supplier.get()) {
        final List<Integer> list = test.collection;

        if (list.size() <= 1) {
            continue;
        }
        boolean gotException = false;
        try {
            // bad predicate that modifies its list, should throw CME
            list.replaceAll(x -> {int n = 3 * x; list.add(n); return n;});
        } catch (ConcurrentModificationException cme) {
            gotException = true;
        }
        if (!gotException) {
            fail("expected CME was not thrown from " + test);
        }
    }
}
 
Example 5
Project: nifi   File: TestCSVRecordReader.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testMultipleRecords() throws IOException, MalformedRecordException {
    final List<RecordField> fields = getDefaultFields();
    fields.replaceAll(f -> f.getFieldName().equals("balance") ? new RecordField("balance", doubleDataType) : f);

    final RecordSchema schema = new SimpleRecordSchema(fields);

    try (final InputStream fis = new FileInputStream(new File("src/test/resources/csv/multi-bank-account.csv"));
        final CSVRecordReader reader = createReader(fis, schema, format)) {

        final Object[] firstRecord = reader.nextRecord().getValues();
        final Object[] firstExpectedValues = new Object[] {"1", "John Doe", 4750.89D, "123 My Street", "My City", "MS", "11111", "USA"};
        Assert.assertArrayEquals(firstExpectedValues, firstRecord);

        final Object[] secondRecord = reader.nextRecord().getValues();
        final Object[] secondExpectedValues = new Object[] {"2", "Jane Doe", 4820.09D, "321 Your Street", "Your City", "NY", "33333", "USA"};
        Assert.assertArrayEquals(secondExpectedValues, secondRecord);

        assertNull(reader.nextRecord());
    }
}
 
Example 6
Project: nifi   File: TestJacksonCSVRecordReader.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testExtraWhiteSpace() throws IOException, MalformedRecordException {
    final List<RecordField> fields = getDefaultFields();
    fields.replaceAll(f -> f.getFieldName().equals("balance") ? new RecordField("balance", doubleDataType) : f);

    final RecordSchema schema = new SimpleRecordSchema(fields);

    try (final InputStream fis = new FileInputStream(new File("src/test/resources/csv/extra-white-space.csv"));
        final JacksonCSVRecordReader reader = createReader(fis, schema, format)) {

        final Object[] firstRecord = reader.nextRecord().getValues();
        final Object[] firstExpectedValues = new Object[] {"1", "John Doe", 4750.89D, "123 My Street", "My City", "MS", "11111", "USA"};
        Assert.assertArrayEquals(firstExpectedValues, firstRecord);

        final Object[] secondRecord = reader.nextRecord().getValues();
        final Object[] secondExpectedValues = new Object[] {"2", "Jane Doe", 4820.09D, "321 Your Street", "Your City", "NY", "33333", "USA"};
        Assert.assertArrayEquals(secondExpectedValues, secondRecord);

        assertNull(reader.nextRecord());
    }
}
 
Example 7
Project: auto   File: AutoFactoryProcessorTest.java    License: Apache License 2.0 6 votes vote down vote up
private static void replaceGeneratedImport(List<String> sourceLines) {
  int i = 0;
  int firstImport = Integer.MAX_VALUE;
  int lastImport = -1;
  for (String line : sourceLines) {
    if (line.startsWith("import ") && !line.startsWith("import static ")) {
      firstImport = Math.min(firstImport, i);
      lastImport = Math.max(lastImport, i);
    }
    i++;
  }
  if (lastImport >= 0) {
    List<String> importLines = sourceLines.subList(firstImport, lastImport + 1);
    importLines.replaceAll(
        line ->
            line.startsWith("import javax.annotation.processing.Generated;")
                ? "import javax.annotation.Generated;"
                : line);
    Collections.sort(importLines);
  }
}
 
Example 8
Project: jdk8u-jdk   File: ListDefaults.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testReplaceAllThrowsCME() {
    @SuppressWarnings("unchecked")
    final CollectionSupplier<List<Integer>> supplier = new CollectionSupplier(LIST_CME_SUPPLIERS, SIZE);
    for (final CollectionSupplier.TestCase<List<Integer>> test : supplier.get()) {
        final List<Integer> list = test.collection;

        if (list.size() <= 1) {
            continue;
        }
        boolean gotException = false;
        try {
            // bad predicate that modifies its list, should throw CME
            list.replaceAll(x -> {int n = 3 * x; list.add(n); return n;});
        } catch (ConcurrentModificationException cme) {
            gotException = true;
        }
        if (!gotException) {
            fail("expected CME was not thrown from " + test);
        }
    }
}
 
Example 9
Project: openjdk-8-source   File: ListDefaults.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testReplaceAllThrowsCME() throws Exception {
    final CollectionSupplier<List<Integer>> supplier = new CollectionSupplier((Supplier<List<Integer>>[])LIST_CME_CLASSES, SIZE);
    for (final CollectionSupplier.TestCase<List<Integer>> test : supplier.get()) {
        final List<Integer> list = ((List<Integer>) test.collection);

        if (list.size() <= 1) {
            continue;
        }
        boolean gotException = false;
        try {
            // bad predicate that modifies its list, should throw CME
            list.replaceAll(x -> {int n = 3 * x; list.add(n); return n;});
        } catch (ConcurrentModificationException cme) {
            gotException = true;
        }
        if (!gotException) {
            fail("expected CME was not thrown from " + test);
        }
    }
}
 
Example 10
Project: nifi   File: TestJacksonCSVRecordReader.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testMultipleRecords() throws IOException, MalformedRecordException {
    final List<RecordField> fields = getDefaultFields();
    fields.replaceAll(f -> f.getFieldName().equals("balance") ? new RecordField("balance", doubleDataType) : f);

    final RecordSchema schema = new SimpleRecordSchema(fields);

    try (final InputStream fis = new FileInputStream(new File("src/test/resources/csv/multi-bank-account.csv"));
        final JacksonCSVRecordReader reader = createReader(fis, schema, format)) {

        final Object[] firstRecord = reader.nextRecord().getValues();
        final Object[] firstExpectedValues = new Object[] {"1", "John Doe", 4750.89D, "123 My Street", "My City", "MS", "11111", "USA"};
        Assert.assertArrayEquals(firstExpectedValues, firstRecord);

        final Object[] secondRecord = reader.nextRecord().getValues();
        final Object[] secondExpectedValues = new Object[] {"2", "Jane Doe", 4820.09D, "321 Your Street", "Your City", "NY", "33333", "USA"};
        Assert.assertArrayEquals(secondExpectedValues, secondRecord);

        assertNull(reader.nextRecord());
    }
}
 
Example 11
Project: openjdk-jdk8u-backup   File: ListDefaults.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testReplaceAllThrowsCME() {
    @SuppressWarnings("unchecked")
    final CollectionSupplier<List<Integer>> supplier = new CollectionSupplier(LIST_CME_SUPPLIERS, SIZE);
    for (final CollectionSupplier.TestCase<List<Integer>> test : supplier.get()) {
        final List<Integer> list = test.collection;

        if (list.size() <= 1) {
            continue;
        }
        boolean gotException = false;
        try {
            // bad predicate that modifies its list, should throw CME
            list.replaceAll(x -> {int n = 3 * x; list.add(n); return n;});
        } catch (ConcurrentModificationException cme) {
            gotException = true;
        }
        if (!gotException) {
            fail("expected CME was not thrown from " + test);
        }
    }
}
 
Example 12
Project: scava   File: HtmlParser.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * 
 * @param ParsedHtmlWithTags is a {@code List<Map.Entry<String,String>>} containing pairs composed of an HTML tag and the content. 
 * @param tags array indicating which tags should be used in the filtering
 * @param negation if {@code true}, it stipulates that it should be used to filter only the tags different from {@code tags}   
 * @return A {@code List<String>} with the filters designated previously 
 */
public static List<String> filterParsedHtmlWithTags (List<Map.Entry<String,String>> ParsedHtmlWithTags, String [] tags, Boolean negation)
{
	List<String> tagsList = Arrays.asList(tags);
	tagsList.replaceAll(tag->tag.toLowerCase());
	if(negation)
	{
		return ParsedHtmlWithTags.stream().filter(pair->!tagsList.contains(pair.getKey())).map(pair->pair.getValue()).collect(Collectors.toList());
	}
	else
	{
		return ParsedHtmlWithTags.stream().filter(pair->tagsList.contains(pair.getKey())).map(pair->pair.getValue()).collect(Collectors.toList());
	}
	
}
 
Example 13
Project: connector-sdk   File: ContentTemplate.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Trims, checks, and copies the fields for later template building.
 *
 * @param fields the content fields of a specific quality level
 * @return a sanitized copy of the content fields
 */
private LinkedHashSet<String> getFields(List<String> fields) {
  checkArgument((fields != null) && !fields.contains(null),
      "Template content fields cannot be null.");
  List<String> trimFields = new ArrayList<>(fields);
  trimFields.replaceAll(String::trim);
  LinkedHashSet<String> content = new LinkedHashSet<>(trimFields);
  checkArgument(!content.contains(""), "Template content fields cannot be empty: " + content);
  return content;
}
 
Example 14
Project: TrMenu   File: JsonItem.java    License: MIT License 5 votes vote down vote up
public static String toJson(ItemStack item) {
    JsonObject json = new JsonObject();
    String type = item.getType().name();
    byte data = item.getData().getData();
    int amount = item.getAmount();

    json.addProperty("type", item.getType().name());
    if (data > 0) {
        json.addProperty("data", data);
    }
    if (amount > 1) {
        json.addProperty("amount", amount);
    }
    if (item.hasItemMeta()) {
        // Uncolor
        ItemMeta meta = item.getItemMeta();
        if (meta.hasDisplayName()) {
            meta.setDisplayName(meta.getDisplayName().replace('§', '&'));
        }
        if (meta.hasLore()) {
            List<String> lore = meta.getLore();
            lore.replaceAll(s -> s.replace('§', '&'));
            meta.setLore(lore);
        }
        item.setItemMeta(meta);
        json.add("meta", new JsonParser().parse(NMS.handle().loadNBT(item).toJson()));
    }
    return json.toString();
}
 
Example 15
Project: n4js   File: N4IDLTranspiler.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected Transformation[] computeTransformationsToBeExecuted(TranspilerState state) {
	List<Transformation> transformations = new ArrayList<>(
			Arrays.asList(super.computeTransformationsToBeExecuted(state)));

	// add additional N4IDL-specific transformations
	transformations.addAll(0, Arrays.asList(
			// add versioned types transformation as first step
			versionedTypesTransformation.get(),
			// add versioned imports transformation as second step
			versionedImportsTransformationProvider.get(),
			// add migration transformation
			migrationTransformation.get()));

	// replace some N4JS transformations with N4IDL-specific transformations
	transformations.replaceAll(t -> {
		if (t instanceof ClassDeclarationTransformation) {
			return classDeclarationTransformation.get();
		}

		if (t instanceof InterfaceDeclarationTransformation) {
			return interfaceDeclarationTransformation.get();
		}

		if (t instanceof EnumDeclarationTransformation) {
			return enumDeclarationTransformation.get();
		}

		// otherwise, keep the existing transformation
		return t;
	});

	return transformations.toArray(new Transformation[0]);
}
 
Example 16
Project: openjdk-systemtest   File: ClassLibraryLambdaTests.java    License: Apache License 2.0 5 votes vote down vote up
void runReplaceAll(List<StringHolder> a, List<StringHolder> b) {
	a.replaceAll((StringHolder t)->{t.concat("@JJ17r");return new StringHolder(t.getString() + "@417b");});
	int x = 0;
	while (x<b.size()) {
		assertTrue("Expected \"" + b.get(x).getString() + "[email protected]@417b\" but found \"" + a.get(x).getString(),a.get(x).getString().equals(b.get(x).getString() + "[email protected]@417b"));
		x++;
	}
}
 
Example 17
Project: nifi   File: TestCSVRecordReader.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testMissingField() throws IOException, MalformedRecordException {
    final List<RecordField> fields = getDefaultFields();
    fields.replaceAll(f -> f.getFieldName().equals("balance") ? new RecordField("balance", doubleDataType) : f);

    final RecordSchema schema = new SimpleRecordSchema(fields);

    final String headerLine = "id, name, balance, address, city, state, zipCode, country";
    final String inputRecord = "1, John, 40.80, 123 My Street, My City, MS, 11111";
    final String csvData = headerLine + "\n" + inputRecord;
    final byte[] inputData = csvData.getBytes();

    try (final InputStream bais = new ByteArrayInputStream(inputData);
        final CSVRecordReader reader = createReader(bais, schema, format)) {

        final Record record = reader.nextRecord();
        assertNotNull(record);

        assertEquals("1", record.getValue("id"));
        assertEquals("John", record.getValue("name"));
        assertEquals(40.8D, record.getValue("balance"));
        assertEquals("123 My Street", record.getValue("address"));
        assertEquals("My City", record.getValue("city"));
        assertEquals("MS", record.getValue("state"));
        assertEquals("11111", record.getValue("zipCode"));
        assertNull(record.getValue("country"));

        assertNull(reader.nextRecord());
    }
}
 
Example 18
Project: sunbird-lms-service   File: UserBulkMigrationActor.java    License: MIT License 5 votes vote down vote up
private List<MigrationUser> getMigrationUsers(
    String channel, String processId, byte[] fileData, Map<String, Object> fieldsMap) {
  Map<String, List<String>> columnsMap =
      (Map<String, List<String>>) fieldsMap.get(JsonKey.FILE_TYPE_CSV);
  List<String[]> csvData = readCsv(fileData);
  List<String> csvHeaders = getCsvHeadersAsList(csvData);
  List<String> mandatoryHeaders = columnsMap.get(JsonKey.MANDATORY_FIELDS);
  List<String> supportedHeaders = columnsMap.get(JsonKey.SUPPORTED_COlUMNS);
  mandatoryHeaders.replaceAll(String::toLowerCase);
  supportedHeaders.replaceAll(String::toLowerCase);
  checkCsvHeader(csvHeaders, mandatoryHeaders, supportedHeaders);
  List<String> mappedCsvHeaders = mapCsvColumn(csvHeaders);
  List<MigrationUser> migrationUserList =
      parseCsvRows(channel, getCsvRowsAsList(csvData), mappedCsvHeaders);
  ShadowUserUpload migration =
      new ShadowUserUpload.ShadowUserUploadBuilder()
          .setHeaders(csvHeaders)
          .setMappedHeaders(mappedCsvHeaders)
          .setProcessId(processId)
          .setFileData(fileData)
          .setFileSize(fileData.length + "")
          .setMandatoryFields(columnsMap.get(JsonKey.MANDATORY_FIELDS))
          .setSupportedFields(columnsMap.get(JsonKey.SUPPORTED_COlUMNS))
          .setValues(migrationUserList)
          .validate();
  ProjectLogger.log(
      "UserBulkMigrationActor:validateRequestAndReturnMigrationUsers: the migration object formed "
          .concat(migration.toString()),
      LoggerEnum.INFO.name());
  return migrationUserList;
}
 
Example 19
Project: fdb-record-layer   File: MetaDataProtoEditor.java    License: Apache License 2.0 4 votes vote down vote up
private static void renameTopLevelRecordType(@Nonnull RecordMetaDataProto.MetaData.Builder metaDataBuilder,
                                             @Nonnull String recordTypeName, @Nonnull String newRecordTypeName) {
    List<RecordMetaDataProto.RecordType> recordTypes;
    boolean foundRecordType = false;
    recordTypes = new ArrayList<>(metaDataBuilder.getRecordTypesBuilderList().size());
    for (RecordMetaDataProto.RecordType recordType : metaDataBuilder.getRecordTypesList()) {
        if (recordType.getName().equals(newRecordTypeName)) {
            // Despite the earlier check in this method, this can still be triggered if there is an imported record with the given name
            throw new MetaDataException("Cannot rename record type to " + newRecordTypeName + " as an imported record type of that name already exists");
        } else if (recordType.getName().equals(recordTypeName)) {
            recordTypes.add(recordType.toBuilder().setName(newRecordTypeName).build());
            foundRecordType = true;
        } else {
            recordTypes.add(recordType);
        }
    }
    if (!foundRecordType) {
        // This shouldn't happen, but if somehow the record type was in the union but not the record type list, throw an error
        throw new MetaDataException("Missing " + recordTypeName + " in record type list");
    }
    // Rename the record type within any indexes
    List<RecordMetaDataProto.Index> indexes = new ArrayList<>(metaDataBuilder.getIndexesList());
    indexes.replaceAll(index -> {
        if (index.getRecordTypeList().contains(recordTypeName)) {
            List<String> indexRecordTypes = new ArrayList<>(index.getRecordTypeList());
            indexRecordTypes.replaceAll(indexRecordType -> indexRecordType.equals(recordTypeName) ? newRecordTypeName : indexRecordType);
            return index.toBuilder().clearRecordType().addAllRecordType(indexRecordTypes).build();
        } else {
            return index;
        }
    });
    // Update the metaDataBuilder with all of the renamed things
    metaDataBuilder.clearRecordTypes();
    metaDataBuilder.addAllRecordTypes(recordTypes);
    metaDataBuilder.clearIndexes();
    metaDataBuilder.addAllIndexes(indexes);
    metaDataBuilder.clearRecordTypes();
    metaDataBuilder.addAllRecordTypes(recordTypes);
    metaDataBuilder.clearIndexes();
    metaDataBuilder.addAllIndexes(indexes);
}
 
Example 20
Project: ripme   File: ThechiveRipper.java    License: MIT License 4 votes vote down vote up
private List<String> getUrlsFromThechive(Document doc) {
    /*
     * The image urls are stored in a <script> tag of the document. This script
     * contains a single array var by name CHIVE_GALLERY_ITEMS.
     * 
     * We grab all the <img> tags from the particular script, combine them in a
     * string, parse it, and grab all the img/gif urls.
     * 
     */
    List<String> result = new ArrayList<>();
    Elements scripts = doc.getElementsByTag("script");

    for (Element script : scripts) {
        String data = script.data();

        if (!data.contains("CHIVE_GALLERY_ITEMS")) {
            continue;
        }

        /*
         * We add all the <img/> tags in a single StringBuilder and parse as HTML for
         * easy sorting of img/ gifs.
         */
        StringBuilder allImgTags = new StringBuilder();
        Matcher matcher = imagePattern.matcher(data);
        while (matcher.find()) {
            // Unescape '\' from the img tags, which also unescape's img url as well.
            allImgTags.append(matcher.group(0).replaceAll("\\\\", ""));
        }

        // Now we parse and sort links.
        Document imgDoc = Jsoup.parse(allImgTags.toString());
        Elements imgs = imgDoc.getElementsByTag("img");
        for (Element img : imgs) {
            if (img.hasAttr("data-gifsrc")) {
                // For gifs.
                result.add(img.attr("data-gifsrc"));
            } else {
                // For jpeg images.
                result.add(img.attr("src"));
            }
        }
    }

    // strip all GET parameters from the links( such as quality, width, height as to
    // get the original image.).
    result.replaceAll(s -> s.substring(0, s.indexOf("?")));

    return result;
}