Example usage for java.util.function Function identity

List of usage examples for java.util.function Function identity

Introduction

In this page you can find the example usage for java.util.function Function identity.

Prototype

static <T> Function<T, T> identity() 

Source Link

Document

Returns a function that always returns its input argument.

Usage

From source file:Main.java

public static void main(String[] args) {
    Map<Employee.Gender, Employee> highestEarnerByGender = Employee.persons().stream().collect(Collectors.toMap(
            Employee::getGender, Function.identity(),
            (oldPerson, newPerson) -> newPerson.getIncome() > oldPerson.getIncome() ? newPerson : oldPerson));
    System.out.println(highestEarnerByGender);
}

From source file:com.github.horrorho.inflatabledonkey.Main.java

/**
 * @param args the command line arguments
 * @throws IOException/*  ww  w.ja v a2s.  co m*/
 */
public static void main(String[] args) throws IOException {
    try {
        if (!PropertyLoader.instance().test(args)) {
            return;
        }
    } catch (IllegalArgumentException ex) {
        System.out.println("Argument error: " + ex.getMessage());
        System.out.println("Try '" + Property.APP_NAME.value() + " --help' for more information.");
        System.exit(-1);
    }

    // SystemDefault HttpClient.
    // TODO concurrent
    CloseableHttpClient httpClient = HttpClients.custom().setUserAgent("CloudKit/479 (13A404)")
            .useSystemProperties().build();

    // Auth
    // TODO rework when we have UncheckedIOException for Authenticator
    Auth auth = Property.AUTHENTICATION_TOKEN.value().map(Auth::new).orElse(null);

    if (auth == null) {
        auth = Authenticator.authenticate(httpClient, Property.AUTHENTICATION_APPLEID.value().get(),
                Property.AUTHENTICATION_PASSWORD.value().get());
    }
    logger.debug("-- main() - auth: {}", auth);
    logger.info("-- main() - dsPrsID:mmeAuthToken: {}:{}", auth.dsPrsID(), auth.mmeAuthToken());

    if (Property.ARGS_TOKEN.booleanValue().orElse(false)) {
        System.out.println("DsPrsID:mmeAuthToken " + auth.dsPrsID() + ":" + auth.mmeAuthToken());
        return;
    }

    logger.info("-- main() - Apple ID: {}", Property.AUTHENTICATION_APPLEID.value());
    logger.info("-- main() - password: {}", Property.AUTHENTICATION_PASSWORD.value());
    logger.info("-- main() - token: {}", Property.AUTHENTICATION_TOKEN.value());

    // Account
    Account account = Accounts.account(httpClient, auth);

    // Backup
    Backup backup = Backup.create(httpClient, account);

    // BackupAccount
    BackupAccount backupAccount = backup.backupAccount(httpClient);
    logger.debug("-- main() - backup account: {}", backupAccount);

    // Devices
    List<Device> devices = backup.devices(httpClient, backupAccount.devices());
    logger.debug("-- main() - device count: {}", devices.size());

    // Snapshots
    List<SnapshotID> snapshotIDs = devices.stream().map(Device::snapshots).flatMap(Collection::stream)
            .collect(Collectors.toList());
    logger.info("-- main() - total snapshot count: {}", snapshotIDs.size());

    Map<String, Snapshot> snapshots = backup.snapshot(httpClient, snapshotIDs).stream().collect(
            Collectors.toMap(s -> s.record().getRecordIdentifier().getValue().getName(), Function.identity()));

    boolean repeat = false;
    do {

        for (int i = 0; i < devices.size(); i++) {
            Device device = devices.get(i);
            List<SnapshotID> deviceSnapshotIDs = device.snapshots();

            System.out.println(i + " " + device.info());

            for (int j = 0; j < deviceSnapshotIDs.size(); j++) {
                SnapshotID sid = deviceSnapshotIDs.get(j);
                System.out.println("\t" + j + snapshots.get(sid.id()).info() + "   " + sid.timestamp());
            }
        }
        if (Property.PRINT_SNAPSHOTS.booleanValue().orElse(false)) {
            return;
        }
        // Selection
        Scanner input = new Scanner(System.in);

        int deviceIndex;
        int snapshotIndex = Property.SELECT_SNAPSHOT_INDEX.intValue().get();

        if (devices.size() > 1) {
            System.out.printf("Select a device [0 - %d]: ", devices.size() - 1);
            deviceIndex = input.nextInt();
        } else
            deviceIndex = Property.SELECT_DEVICE_INDEX.intValue().get();

        if (deviceIndex >= devices.size() || deviceIndex < 0) {
            System.out.println("No such device: " + deviceIndex);
            System.exit(-1);
        }

        Device device = devices.get(deviceIndex);
        System.out.println("Selected device: " + deviceIndex + ", " + device.info());

        if (device.snapshots().size() > 1) {
            System.out.printf("Select a snapshot [0 - %d]: ", device.snapshots().size() - 1);
            snapshotIndex = input.nextInt();
        } else
            snapshotIndex = Property.SELECT_SNAPSHOT_INDEX.intValue().get();

        if (snapshotIndex >= devices.get(deviceIndex).snapshots().size() || snapshotIndex < 0) {
            System.out.println("No such snapshot for selected device: " + snapshotIndex);
            System.exit(-1);
        }

        logger.info("-- main() - arg device index: {}", deviceIndex);
        logger.info("-- main() - arg snapshot index: {}", snapshotIndex);

        String selected = devices.get(deviceIndex).snapshots().get(snapshotIndex).id();
        Snapshot snapshot = snapshots.get(selected);
        System.out.println("Selected snapshot: " + snapshotIndex + ", " + snapshot.info());

        // Asset list.
        List<Assets> assetsList = backup.assetsList(httpClient, snapshot);
        logger.info("-- main() - assets count: {}", assetsList.size());

        // Domains filter --domain option
        String chosenDomain = Property.FILTER_DOMAIN.value().orElse("").toLowerCase(Locale.US);
        logger.info("-- main() - arg domain substring filter: {}", Property.FILTER_DOMAIN.value());
        // Output domains --domains option
        if (Property.PRINT_DOMAIN_LIST.booleanValue().orElse(false)) {
            System.out.println("Domains / file count:");
            assetsList.stream().filter(a -> a.domain().isPresent())
                    .map(a -> a.domain().get() + " / " + a.files().size()).sorted()
                    .forEach(System.out::println);

            System.out.print("Type a domain ('null' to exit): ");
            chosenDomain = input.next().toLowerCase(Locale.US);
            if (chosenDomain.equals("null"))
                return;
            // TODO check Assets without domain information.
        }

        String domainSubstring = chosenDomain;

        Predicate<Optional<String>> domainFilter = domain -> domain.map(d -> d.toLowerCase(Locale.US))
                .map(d -> d.contains(domainSubstring)).orElse(false);

        List<String> files = Assets.files(assetsList, domainFilter);
        logger.info("-- main() - domain filtered file count: {}", files.size());

        // Output folders.
        Path outputFolder = Paths.get(Property.OUTPUT_FOLDER.value().orElse("output"));
        Path assetOutputFolder = outputFolder.resolve("assets"); // TODO assets value injection
        Path chunkOutputFolder = outputFolder.resolve("chunks"); // TODO chunks value injection
        logger.info("-- main() - output folder chunks: {}", chunkOutputFolder);
        logger.info("-- main() - output folder assets: {}", assetOutputFolder);

        // Download tools.
        AuthorizeAssets authorizeAssets = AuthorizeAssets.backupd();
        DiskChunkStore chunkStore = new DiskChunkStore(chunkOutputFolder);
        StandardChunkEngine chunkEngine = new StandardChunkEngine(chunkStore);
        AssetDownloader assetDownloader = new AssetDownloader(chunkEngine);
        KeyBagManager keyBagManager = backup.newKeyBagManager();

        // Mystery Moo. 
        Moo moo = new Moo(authorizeAssets, assetDownloader, keyBagManager);

        // Filename extension filter.
        String filenameExtension = Property.FILTER_EXTENSION.value().orElse("").toLowerCase(Locale.US);
        logger.info("-- main() - arg filename extension filter: {}", Property.FILTER_EXTENSION.value());

        Predicate<Asset> assetFilter = asset -> asset.relativePath().map(d -> d.toLowerCase(Locale.US))
                .map(d -> d.endsWith(filenameExtension)).orElse(false);

        // Batch process files in groups of 100.
        // TODO group files into batches based on file size.
        List<List<String>> batches = ListUtils.partition(files, 100);

        for (List<String> batch : batches) {
            List<Asset> assets = backup.assets(httpClient, batch).stream().filter(assetFilter::test)
                    .collect(Collectors.toList());
            logger.info("-- main() - filtered asset count: {}", assets.size());
            moo.download(httpClient, assets, assetOutputFolder);
        }
        System.out.print("Download other snapshot (Y/N)? ");
        repeat = input.next().toLowerCase(Locale.US).charAt(0) == 'y';
    } while (repeat == true);
}

From source file:Main.java

public static <T> Map<String, T> toMap(List<T> list, Function<T, String> getId) {
    return stream(list).collect(Collectors.toMap(getId, Function.identity()));
}

From source file:Main.java

/**
 * Returns a collector that computes the distribution of the provided elements. This effectively counts how many
 * times an item has appeared in a stream.
 *
 * @param <T>//from   w ww .  ja va 2 s.  c om
 *            the counted type
 * @return the distribution collector
 */
public static <T> Collector<T, ?, Map<T, Long>> distribution() {
    return Collectors.groupingBy(Function.identity(), Collectors.counting());
}

From source file:Main.java

public static <T, K, M extends Map<K, T>> M toMap(Collection<T> entities, Function<T, K> keyMapper,
        Supplier<M> supplier) {
    return entities.stream().collect(Collectors.toMap(keyMapper, Function.identity(), (a, b) -> b, supplier));
}

From source file:org.niord.core.message.MessagePrintParams.java

/**
 * Returns a MessagePrintParams initialized with parameter values from a request using "default" parameter names
 * @param req the servlet request//from  w  w  w .  j  a  va 2 s .  com
 * @return the MessageSearchParams initialized with parameter values
 */
public static MessagePrintParams instantiate(HttpServletRequest req) {
    MessagePrintParams params = new MessagePrintParams();
    params.report(req.getParameter("report"))
            .pageSize(checkNull(req.getParameter("pageSize"), "A4", Function.identity()))
            .pageOrientation(checkNull(req.getParameter("pageOrientation"), "portrait", Function.identity()))
            .mapThumbnails(checkNull(req.getParameter("mapThumbnails"), false, Boolean::valueOf))
            .fileName(checkNull(req.getParameter("fileName"), null, Function.identity()))
            .debug(checkNull(req.getParameter("debug"), false, Boolean::valueOf)).readReportParams(req);

    return params;
}

From source file:org.decampo.examples.collections.MoreCollectors.java

public static <T, K> Collector<T, SetValuedMap<K, T>, SetValuedMap<K, T>> groupingByDistinct(
        Function<T, K> classifier) {

    return toSetValuedMap(classifier, Function.identity());
}

From source file:ConcurrentTest.java

@BeforeClass
public static void setUpClass() throws IOException {

    List<HashResultHolder> list = new ObjectMapper().readValue(
            JacksonJacksumTest.class.getResourceAsStream("/jacksum_image.json"),
            new TypeReference<List<HashResultHolder>>() {
            });//from  w w  w .j a va 2s  .  c  o  m

    IMAGE_FILE_RESULTS = list.stream()
            .collect(Collectors.toMap(HashResultHolder::getAlgorithm, Function.identity()));

}

From source file:com.civprod.util.stream.SummaryStatisticCollector.java

@Override
public Function<SummaryStatistics, SummaryStatistics> finisher() {
    return Function.identity();
}

From source file:com.vsct.dt.strowgr.admin.gui.mapping.json.EntryPointBackendMappingJson.java

public EntryPointBackendMappingJson(@JsonProperty("id") String id,
        @JsonProperty("servers") Set<EntryPointBackendServerMappingJson> servers,
        @JsonProperty("context") Map<String, String> context) {
    super(id, servers.stream().map(Function.identity()).collect(Collectors.toSet()), context);
}