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

The following examples show how to use java.util.List#replaceAll() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ComWorkflowServiceImpl.java    From openemm with 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 2
Source File: TestCSVRecordReader.java    From nifi with 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 3
Source File: ListDefaults.java    From jdk8u-jdk with 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
Source File: ListDefaults.java    From openjdk-jdk8u-backup with 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
Source File: ListDefaults.java    From jdk8u60 with 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 6
Source File: TestCSVRecordReader.java    From nifi with 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 7
Source File: TestJacksonCSVRecordReader.java    From nifi with 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 8
Source File: AutoFactoryProcessorTest.java    From auto with 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 9
Source File: ListDefaults.java    From jdk8u-jdk with 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 10
Source File: ListDefaults.java    From openjdk-8-source with 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 11
Source File: TestJacksonCSVRecordReader.java    From nifi with 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 12
Source File: UserBulkMigrationActor.java    From sunbird-lms-service with 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 13
Source File: TestCSVRecordReader.java    From nifi with 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 14
Source File: ClassLibraryLambdaTests.java    From openjdk-systemtest with 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() + "success@JJ17r@417b\" but found \"" + a.get(x).getString(),a.get(x).getString().equals(b.get(x).getString() + "success@JJ17r@417b"));
		x++;
	}
}
 
Example 15
Source File: N4IDLTranspiler.java    From n4js with 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
Source File: JsonItem.java    From TrMenu with 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 17
Source File: ContentTemplate.java    From connector-sdk with 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 18
Source File: HtmlParser.java    From scava with 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 19
Source File: ThechiveRipper.java    From ripme with 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;
}
 
Example 20
Source File: MetaDataProtoEditor.java    From fdb-record-layer with 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);
}