Example usage for com.google.common.collect Iterables find

List of usage examples for com.google.common.collect Iterables find

Introduction

In this page you can find the example usage for com.google.common.collect Iterables find.

Prototype

public static <T> T find(Iterable<T> iterable, Predicate<? super T> predicate) 

Source Link

Document

Returns the first element in iterable that satisfies the given predicate; use this method only when such an element is known to exist.

Usage

From source file:brooklyn.entity.waratek.cloudvm.JavaVirtualMachineSshDriver.java

@Override
public Map<String, String> getCustomJavaSystemProperties() {
    MutableMap.Builder<String, String> builder = MutableMap.<String, String>builder()
            .putAll(super.getCustomJavaSystemProperties());
    if (installed.get()) {
        // Java options needed for launch only
        builder.put("com.waratek.jvm.name", getEntity().getAttribute(JavaVirtualMachine.JVM_NAME));
        builder.put("com.waratek.rootdir", getRootDirectory());
        // TODO JMXRMI debugging
        // builder.put("sun.rmi.transport.logLevel", "VERBOSE");
        // builder.put("sun.rmi.transport.tcp.logLevel", "VERBOSE");
        // builder.put("sun.rmi.server.logLevel", "VERBOSE");
        // builder.put("sun.rmi.client.logCalls", "true");
        if (getEntity().getConfig(JavaVirtualMachine.DEBUG)) {
            builder.put("com.waratek.debug.log", "guest.log");
            builder.put("com.waratek.debug.log_level", "debug");
        }/*  www  . j av a  2 s.co  m*/
        if (getEntity().getConfig(JavaVirtualMachine.SSH_ADMIN_ENABLE)) {
            builder.put("com.waratek.ssh.server", "on");
            builder.put("com.waratek.ssh.port",
                    getEntity().getAttribute(JavaVirtualMachine.SSH_PORT).toString());
            builder.put("com.waratek.ssh.ip", getMachine().getAddress().getHostAddress());
        } else {
            builder.put("com.waratek.ssh.server", "off");
        }
        if (getEntity().getConfig(JavaVirtualMachine.HTTP_ADMIN_ENABLE)) {
            // TODO extra properties and configuration required?
            builder.put("com.waratek.jmxhttp.jolokia",
                    "port=" + getEntity().getAttribute(JavaVirtualMachine.HTTP_PORT).toString());
        }
        String javaagent = Iterables.find(super.getJmxJavaConfigOptions(),
                Predicates.containsPattern("javaagent"));
        builder.put("com.waratek.javaagent", javaagent);

    }
    return builder.build();
}

From source file:org.apache.brooklyn.entity.database.mysql.InitSlaveTaskBody.java

private void bootstrapSlaveAsync(final Future<ReplicationSnapshot> replicationInfoFuture,
        final MySqlNode slave) {
    DynamicTasks.queue("bootstrap slave replication", new Runnable() {
        @Override/* w  w w .j a v  a 2  s .c o  m*/
        public void run() {
            ReplicationSnapshot replicationSnapshot;
            try {
                replicationSnapshot = replicationInfoFuture.get();
            } catch (InterruptedException | ExecutionException e) {
                throw Exceptions.propagate(e);
            }

            MySqlNode master = getMaster();
            String masterAddress = MySqlClusterUtils
                    .validateSqlParam(master.getAttribute(MySqlNode.SUBNET_ADDRESS));
            Integer masterPort = master.getAttribute(MySqlNode.MYSQL_PORT);
            String slaveAddress = MySqlClusterUtils
                    .validateSqlParam(slave.getAttribute(MySqlNode.SUBNET_ADDRESS));
            String username = MySqlClusterUtils
                    .validateSqlParam(cluster.getConfig(MySqlCluster.SLAVE_USERNAME));
            String password = MySqlClusterUtils
                    .validateSqlParam(cluster.getAttribute(MySqlCluster.SLAVE_PASSWORD));

            if (replicationSnapshot.getEntityId() != null) {
                Entity sourceEntity = Iterables.find(cluster.getMembers(),
                        EntityPredicates.idEqualTo(replicationSnapshot.getEntityId()));
                String dumpId = FilenameUtils.removeExtension(replicationSnapshot.getSnapshotPath());
                copyDumpAsync(sourceEntity, slave, replicationSnapshot.getSnapshotPath(), dumpId);
                DynamicTasks.queue(Effectors.invocation(slave, MySqlNode.IMPORT_DUMP,
                        ImmutableMap.of("path", replicationSnapshot.getSnapshotPath())));
                //The dump resets the password to whatever is on the source instance, reset it back.
                //We are able to still login because privileges are not flushed, so we just set the password to the same value.
                DynamicTasks.queue(Effectors.invocation(slave, MySqlNode.CHANGE_PASSWORD,
                        ImmutableMap.of("password", slave.getAttribute(MySqlNode.PASSWORD)))); //
                //Flush privileges to load new users coming from the dump
                MySqlClusterUtils.executeSqlOnNodeAsync(slave, "FLUSH PRIVILEGES;");
            }

            MySqlClusterUtils.executeSqlOnNodeAsync(master,
                    String.format(
                            "CREATE USER '%s'@'%s' IDENTIFIED BY '%s';\n"
                                    + "GRANT REPLICATION SLAVE ON *.* TO '%s'@'%s';\n",
                            username, slaveAddress, password, username, slaveAddress));

            // Executing this will unblock SERVICE_UP wait in the start effector
            String slaveCmd = String.format(
                    "CHANGE MASTER TO " + "MASTER_HOST='%s', " + "MASTER_PORT=%d, " + "MASTER_USER='%s', "
                            + "MASTER_PASSWORD='%s', " + "MASTER_LOG_FILE='%s', " + "MASTER_LOG_POS=%d;\n"
                            + "START SLAVE;\n",
                    masterAddress, masterPort, username, password, replicationSnapshot.getBinLogName(),
                    replicationSnapshot.getBinLogPosition());
            MySqlClusterUtils.executeSqlOnNodeAsync(slave, slaveCmd);
        }
    });
}

From source file:elaborate.editor.model.orm.User.java

private String userSetting(final String key) {
    UserSetting setting = Iterables.find(Lists.newArrayList(getUserSettings()), userSettingWithKey(key));
    return setting.getValue();
}

From source file:org.apache.calcite.sql.validate.TableNamespace.java

/**
 * Ensures that extended columns that have the same name as a base column also
 * have the same data-type.//from   ww w  . jav a 2s.  c  o  m
 */
private void checkExtendedColumnTypes(SqlNodeList extendList) {
    final List<RelDataTypeField> extendedFields = SqlValidatorUtil
            .getExtendedColumns(validator.getTypeFactory(), table, extendList);
    final List<RelDataTypeField> baseFields = getBaseRowType().getFieldList();
    final Map<String, Integer> nameToIndex = SqlValidatorUtil.mapNameToIndex(baseFields);

    for (final RelDataTypeField extendedField : extendedFields) {
        final String extFieldName = extendedField.getName();
        if (nameToIndex.containsKey(extFieldName)) {
            final Integer baseIndex = nameToIndex.get(extFieldName);
            final RelDataType baseType = baseFields.get(baseIndex).getType();
            final RelDataType extType = extendedField.getType();

            if (!extType.equals(baseType)) {
                // Get the extended column node that failed validation.
                final Predicate<SqlNode> nameMatches = new Predicate<SqlNode>() {
                    @Override
                    public boolean apply(SqlNode sqlNode) {
                        if (sqlNode instanceof SqlIdentifier) {
                            final SqlIdentifier identifier = (SqlIdentifier) sqlNode;
                            return Util.last(identifier.names).equals(extendedField.getName());
                        }
                        return false;
                    }
                };
                final SqlNode extColNode = Iterables.find(extendList.getList(), nameMatches);

                throw validator.getValidationErrorFunction().apply(extColNode,
                        RESOURCE.typeNotAssignable(baseFields.get(baseIndex).getName(),
                                baseType.getFullTypeString(), extendedField.getName(),
                                extType.getFullTypeString()));
            }
        }
    }
}

From source file:org.apache.brooklyn.entity.brooklynnode.effector.SelectMasterEffectorBody.java

private Entity getMember(String memberId) {
    Group cluster = (Group) entity();
    try {//from   w  w  w  .java 2  s .c o  m
        return Iterables.find(cluster.getMembers(), EntityPredicates.idEqualTo(memberId));
    } catch (NoSuchElementException e) {
        throw new IllegalStateException(memberId + " is not an ID of brooklyn node in this cluster");
    }
}

From source file:dynamite.zafroshops.app.fragment.OpeningsDialogFragment.java

@NonNull
@Override/*www . j  av  a 2s .c  o m*/
public Dialog onCreateDialog(Bundle savedInstanceState) {
    data = (ArrayList<MobileOpeningHourData>) getArguments().get(NEW_ZOP_OPENINGS);
    tempData = new ArrayList();

    for (int i = 0; i < data.size(); i++) {
        tempData.add(data.get(i).Copy());
    }

    // set spinners
    ArrayAdapter<String> openingsDayAdapter;
    ArrayAdapter<String> openingsHoursAdapter;
    ArrayAdapter<String> openingsMinutesAdapter;

    Activity activity = getActivity();
    AlertDialog.Builder builder = new AlertDialog.Builder(activity);
    final LayoutInflater inflater = activity.getLayoutInflater();
    View view = inflater.inflate(R.layout.openings_dialog, null);

    builder.setView(view).setTitle(R.string.openings_editing)
            .setPositiveButton(R.string.button_submit, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    data.clear();
                    for (int i = 0; i < tempData.size(); i++) {
                        data.add(tempData.get(i).Copy());
                    }

                    Intent intent = new Intent();
                    intent.putExtra(NEW_ZOP_OPENINGS_COUNT_KEY, OpeningsDialogFragment.this.data.size());
                    getTargetFragment().onActivityResult(getTargetRequestCode(), NEW_ZOP_OPENINGS_RESULT_CODE,
                            intent);
                }
            }).setNegativeButton(R.string.button_cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                }
            });

    final Spinner ohd = (Spinner) view.findViewById(R.id.openingsDay);
    final Spinner ohsh = (Spinner) view.findViewById(R.id.openingsStartHour);
    final Spinner ohsm = (Spinner) view.findViewById(R.id.openingsStartMinute);
    final Spinner oheh = (Spinner) view.findViewById(R.id.openingsEndHour);
    final Spinner ohem = (Spinner) view.findViewById(R.id.openingsEndMinute);

    if (days == null) {
        days = new ArrayList();
        for (int i = 0; i < 7; i++) {
            try {
                days.add(getString(R.string.class.getField("day" + i).getInt(null)));
            } catch (IllegalAccessException ignored) {
            } catch (NoSuchFieldException e) {
            }
        }
    }

    if (hours == null) {
        hours = new ArrayList();
        for (int i = 0; i < 24; i++) {
            hours.add(String.format("%02d", i));
        }
    }

    if (minutes == null) {
        minutes = new ArrayList();
        for (int i = 0; i < 4; i++) {
            minutes.add(String.format("%02d", i * 15));
        }
    }

    openingsDayAdapter = new ArrayAdapter<>(activity, android.R.layout.simple_spinner_item, days);
    openingsDayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    ohd.setAdapter(openingsDayAdapter);

    openingsHoursAdapter = new ArrayAdapter<>(activity, android.R.layout.simple_spinner_item, hours);
    openingsHoursAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    ohsh.setAdapter(openingsHoursAdapter);
    oheh.setAdapter(openingsHoursAdapter);

    openingsMinutesAdapter = new ArrayAdapter<>(activity, android.R.layout.simple_spinner_item, minutes);
    openingsMinutesAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    ohsm.setAdapter(openingsMinutesAdapter);
    ohem.setAdapter(openingsMinutesAdapter);

    // set current openings
    openingHoursContainer = (LinearLayout) view.findViewById(R.id.openingHours);
    openingHoursLabel = (TextView) view.findViewById(R.id.openingHoursLabel);
    openingHoursDeleteButton = (Button) view.findViewById(R.id.openingsHoursDelete);

    ZopItemFragment.setOpeningsList(tempData, openingHoursContainer, inflater, openingHoursLabel);

    // set buttons
    view.findViewById(R.id.openingsHoursAdd).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // get data
            final int position = ohd.getSelectedItemPosition();
            MobileOpeningHourData item = null;
            try {
                item = Iterables.find(tempData, new Predicate<MobileOpeningHourData>() {
                    @Override
                    public boolean apply(MobileOpeningHourData input) {
                        return input.Day == position;
                    }
                });
            } catch (NoSuchElementException ignored) {
            }

            // update data
            if (item == null) {
                item = new MobileOpeningHourData((byte) position);
                tempData.add(item);
            }

            final MobileOpeningHour moh = new MobileOpeningHour();
            moh.StartTimeHour = (byte) ohsh.getSelectedItemPosition();
            moh.StartTimeMinute = (byte) (ohsm.getSelectedItemPosition() * 15);
            moh.EndTimeHour = (byte) oheh.getSelectedItemPosition();
            moh.EndTimeMinute = (byte) (ohem.getSelectedItemPosition() * 15);

            MobileOpeningHour temp = null;
            try {
                temp = Iterables.find(item.Hours, new Predicate<MobileOpeningHour>() {
                    @Override
                    public boolean apply(MobileOpeningHour input) {
                        return input.compareTo(moh) == 0;
                    }
                });
            } catch (NoSuchElementException ignored) {
            }

            if (temp == null) {
                item.Hours.add(moh);
            }

            // sort data
            Collections.sort(item.Hours);
            Collections.sort(tempData);

            // update view
            ZopItemFragment.setOpeningsList(tempData, openingHoursContainer, inflater, openingHoursLabel);
            openingHoursDeleteButton.setEnabled(true);
        }
    });
    openingHoursDeleteButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // get data
            final int position = ohd.getSelectedItemPosition();
            MobileOpeningHourData item = null;
            try {
                item = Iterables.find(tempData, new Predicate<MobileOpeningHourData>() {
                    @Override
                    public boolean apply(MobileOpeningHourData input) {
                        return input.Day == position;
                    }
                });
            } catch (NoSuchElementException ignored) {
            }
            // update data
            if (item != null) {
                tempData.remove(item);
                openingHoursDeleteButton.setEnabled(false);
            }
            // update view
            ZopItemFragment.setOpeningsList(tempData, openingHoursContainer, inflater, openingHoursLabel);
        }
    });
    ohd.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, final int position, long id) {
            MobileOpeningHourData item = null;
            // get data
            try {
                item = Iterables.find(tempData, new Predicate<MobileOpeningHourData>() {
                    @Override
                    public boolean apply(MobileOpeningHourData input) {
                        return input.Day == position;
                    }
                });
            } catch (NoSuchElementException ignored) {
            }
            // update view
            if (item != null) {
                openingHoursDeleteButton.setEnabled(true);
            } else {
                openingHoursDeleteButton.setEnabled(false);
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });

    return builder.create();
}

From source file:org.opendaylight.controller.sal.connect.netconf.schema.mapping.NetconfMessageTransformer.java

private static XmlElement stripNotification(final NetconfMessage message) {
    final XmlElement xmlElement = XmlElement.fromDomDocument(message.getDocument());
    final List<XmlElement> childElements = xmlElement.getChildElements();
    Preconditions.checkArgument(childElements.size() == 2, "Unable to parse notification %s, unexpected format",
            message);//ww  w . j av  a2s. c  o  m
    try {
        return Iterables.find(childElements, new Predicate<XmlElement>() {
            @Override
            public boolean apply(final XmlElement xmlElement) {
                return !xmlElement.getName().equals("eventTime");
            }
        });
    } catch (final NoSuchElementException e) {
        throw new IllegalArgumentException(
                "Unable to parse notification " + message + ", cannot strip notification metadata", e);
    }
}

From source file:org.yakindu.sct.examples.wizard.pages.SelectExamplePage.java

protected void filterAndSelectExampleToInstall(TableViewer viewer, List<ExampleData> input) {
    final ExampleData exampleToInstall = Iterables.find(input, new Predicate<ExampleData>() {
        @Override//from   w w  w  .  j a va  2 s .c  o m
        public boolean apply(ExampleData input) {
            if (exampleIdToInstall != null) {
                return exampleIdToInstall.equals(input.getId());
            }
            return true;
        }

    });
    if (exampleToInstall != null) {
        viewer.addFilter(new ViewerFilter() {

            @Override
            public boolean select(Viewer viewer, Object parentElement, Object element) {
                if (exampleIdToInstall == null) {
                    return true;
                }
                if (element instanceof ExampleData) {
                    return exampleIdToInstall.equals(((ExampleData) element).getId());
                }
                if (element instanceof ExampleContentProvider.Category) {
                    return ((ExampleContentProvider.Category) element).getChildren().contains(exampleToInstall);
                }
                return true;
            }
        });
        viewer.setSelection(new StructuredSelection(exampleToInstall), true);
    }
}

From source file:com.example.listsync.WebDavRepository.java

private void waitForLockFileToBecomeTop(final String lockFileName) throws IOException, InterruptedException {
    LOGGER.info("waiting for {} to become top", lockFileName);
    while (true) {
        MultiStatusResponse[] multiStatusResponses = doPropFind(getFullWatchURL());
        List<MultiStatusResponse> lockFiles = Lists.newArrayList(
                Collections2.filter(Arrays.asList(multiStatusResponses), new Predicate<MultiStatusResponse>() {
                    @Override/*from w w w  .  j av  a  2s  .c om*/
                    public boolean apply(MultiStatusResponse input) {
                        return input.getHref().contains(lockFileName);
                    }
                }));
        Collections.sort(lockFiles, new Comparator<MultiStatusResponse>() {
            @Override
            public int compare(MultiStatusResponse o1, MultiStatusResponse o2) {
                return getLastModified(o1).compareTo(getLastModified(o2));
            }
        });
        MultiStatusResponse myself = Iterables.find(lockFiles, new Predicate<MultiStatusResponse>() {
            @Override
            public boolean apply(MultiStatusResponse input) {
                return input.getHref().contains(clientId.toString());
            }
        });
        removeOldLockFiles(lockFiles, getLastModified(myself).getTime());
        if (lockFiles.isEmpty()) {
            throw new IllegalStateException("expected there to be lock-files");
        }
        if (lockFiles.get(0) == myself) {
            LOGGER.info("{} now on top", lockFileName);
            return;
        } else {
            LOGGER.info("{} on top", lockFiles.get(0).getHref());
            Thread.sleep(1000);
        }
    }
}

From source file:com.google.enterprise.adaptor.secmgr.servlets.ResponseParser.java

/**
 * Get the expiration time for the subject verification.
 * Must satisfy {@link #areAssertionsValid} prior to calling.
 *
 * @return The expiration time, or null if there is none.
 *///from w w  w . j  av  a2s  . co  m
public DateTime getExpirationTime() {
    DateTime time1 = assertion.getConditions().getNotOnOrAfter();
    List<SubjectConfirmation> confirmations = assertion.getSubject().getSubjectConfirmations();
    if (confirmations.isEmpty()) {
        return time1;
    }
    DateTime time2 = Iterables.find(confirmations, bearerPredicate).getSubjectConfirmationData()
            .getNotOnOrAfter();
    return (time1 == null || dtComparator.compare(time1, time2) > 0) ? time2 : time1;
}