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:ezbake.amino.cli.Main.java

public Callable<Integer> getCommand() {

    try {//from ww w .  j  a v  a 2  s  .com
        final Set<Class<? extends Command>> types = getAllCommands();
        Class<? extends Command> cmd = Iterables.find(types, new Predicate<Class<? extends Command>>() {
            @Override
            public boolean apply(@Nullable Class<? extends Command> aClass) {
                return aClass != null && aClass.getName().endsWith(commandName);

            }
        });

        Command cmdInstance = cmd.newInstance();
        cmdInstance.initialize(this, arguments, client, getSecurityToken(), System.out);
        return cmdInstance;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.infinities.nova.volumes.api.DaseinVolumesApi.java

@Override
public Volume createVolume(OpenstackRequestContext context, String projectId,
        final VolumeForCreateTemplate volumeForCreateTemplate) throws Exception {
    if (context == null) {
        context = Context.getAdminContext("no");
    }/*from www .j  av  a 2 s. c o m*/

    Storage<Gigabyte> size = new Storage<Gigabyte>(volumeForCreateTemplate.getVolume().getSize(),
            Storage.GIGABYTE);
    String name = volumeForCreateTemplate.getVolume().getName();
    String description = volumeForCreateTemplate.getVolume().getDescription();
    VolumeCreateOptions options = VolumeCreateOptions.getInstance(size, name, description);

    if (!Strings.isNullOrEmpty(volumeForCreateTemplate.getVolume().getAvailabilityZone())) {
        AsyncResult<Iterable<DataCenter>> result = getServices(context.getProjectId())
                .listDataCenters(getRegionId(context.getProjectId()));
        try {
            DataCenter dc = Iterables.find(result.get(), new Predicate<DataCenter>() {

                @Override
                public boolean apply(DataCenter input) {
                    return input.getProviderDataCenterId()
                            .equals(volumeForCreateTemplate.getVolume().getAvailabilityZone());
                }
            });
            options.setDataCenterId(dc.getProviderDataCenterId());
        } catch (NoSuchElementException e) {
            throw new AvailabilityZoneNotFoundException(null,
                    volumeForCreateTemplate.getVolume().getAvailabilityZone());
        }
    }

    options.setVolumeProductId(volumeForCreateTemplate.getVolume().getVolumeType());
    Map<String, Object> map = new HashMap<String, Object>();
    for (String key : volumeForCreateTemplate.getVolume().getMetadata().keySet()) {
        map.put(key, volumeForCreateTemplate.getVolume().getMetadata().get(key));
    }
    options.setMetaData(map);
    AsyncResult<String> ret = this.getSupport(context.getProjectId()).createVolume(options);
    return getVolume(context, projectId, ret.get());
}

From source file:google.registry.testing.TaskQueueHelper.java

/**
 * Ensures that the only tasks in the named queue are exactly those that match the expected
 * matchers.//from w  ww  .  ja va 2 s  .  c o  m
 */
public static void assertTasksEnqueued(String queueName, List<TaskMatcher> taskMatchers) throws Exception {
    QueueStateInfo qsi = getQueueInfo(queueName);
    assertThat(qsi.getTaskInfo()).hasSize(taskMatchers.size());
    LinkedList<TaskStateInfo> taskInfos = new LinkedList<>(qsi.getTaskInfo());
    for (final TaskMatcher taskMatcher : taskMatchers) {
        try {
            taskInfos.remove(Iterables.find(taskInfos, taskMatcher));
        } catch (NoSuchElementException e) {
            final Map<String, Object> taskMatcherMap = taskMatcher.expected.toMap();
            assert_().fail("Task not found in queue %s:\n\n%s\n\nPotential candidate match diffs:\n\n%s",
                    queueName, taskMatcher,
                    FluentIterable.from(taskInfos).transform(new Function<TaskStateInfo, String>() {
                        @Override
                        public String apply(TaskStateInfo input) {
                            return prettyPrintEntityDeepDiff(taskMatcherMap, Maps.filterKeys(
                                    new MatchableTaskInfo(input).toMap(), in(taskMatcherMap.keySet())));
                        }
                    }).join(Joiner.on('\n')));
        }
    }
}

From source file:org.sonar.server.debt.DebtModelBackup.java

private static RuleDto rule(int id, List<RuleDto> rules) {
    return Iterables.find(rules, new RuleDtoMatchId(id));
}

From source file:org.gradle.plugins.signing.Sign.java

/**
 * Configures the task to sign every artifact of the given configurations
 *//* w w  w  .ja va  2 s. co  m*/
public void sign(Configuration... configurations) {
    for (Configuration configuration : configurations) {
        configuration.getAllArtifacts().all(new Action<PublishArtifact>() {
            @Override
            public void execute(PublishArtifact artifact) {
                if (artifact instanceof Signature) {
                    return;
                }

                signArtifact(artifact);
            }
        });
        configuration.getAllArtifacts().whenObjectRemoved(new Action<PublishArtifact>() {
            @Override
            public void execute(final PublishArtifact publishArtifact) {
                signatures.remove(Iterables.find(signatures, new Predicate<Signature>() {
                    @Override
                    public boolean apply(Signature input) {
                        return input.getToSignArtifact().equals(publishArtifact);
                    }
                }));
            }
        });
    }

}

From source file:org.obiba.onyx.quartz.editor.questionnaire.UploadQuestionnairePanel.java

public UploadQuestionnairePanel(String id, final ModalWindow uploadWindow,
        IModel<Questionnaire> questionnaireModel) {
    super(id);/*from w w w . j a v a 2 s .  c o m*/

    final Questionnaire updatedQuestionnaire = questionnaireModel == null ? null
            : questionnaireModel.getObject();

    feedbackPanel = new FeedbackPanel("content");
    feedbackWindow = new FeedbackWindow("feedback");
    feedbackWindow.setOutputMarkupId(true);
    add(feedbackWindow);

    zipFile = new FileUploadField("zip");
    zipFile.setLabel(new ResourceModel("File.ZIP"));
    zipFile.setRequired(true);

    Form<?> form = new Form<Void>("form") {
        @Override
        protected void onSubmit() {
            FileUpload zip = zipFile.getFileUpload();
            if (zip == null) {
                error(getLocalizer().getString("Error.NoFileUploaded", UploadQuestionnairePanel.this));
                return;
            }
            String clientFileName = zip.getClientFileName();
            if (!clientFileName.endsWith(".zip")) {
                error(getLocalizer().getString("Error.NotAZipFile", UploadQuestionnairePanel.this));
                return;
            }
            try {
                ZipInputStream zis = new ZipInputStream(zip.getInputStream());
                ZipEntry entry = null;
                Questionnaire questionnaire = null;
                List<File> localeProperties = new ArrayList<File>();
                while ((entry = zis.getNextEntry()) != null) {
                    if (!entry.isDirectory()) {
                        String name = entry.getName();
                        // ONYX-1534 lookup for files anywhere in the file hierarchy
                        if (name.contains("/")) {
                            name = name.substring(name.lastIndexOf('/') + 1);
                        }
                        int n;
                        if ("questionnaire.xml".equals(name)) {
                            ByteArrayOutputStream out = new ByteArrayOutputStream();
                            while ((n = zis.read(BUFFER, 0, BUFFER_SIZE)) > -1) {
                                out.write(BUFFER, 0, n);
                            }
                            questionnaire = questionnaireBundleManager
                                    .load(new ByteArrayInputStream(out.toByteArray()));
                            try {
                                out.close();
                            } catch (Exception e) {
                            }

                            if (updatedQuestionnaire == null) {
                                for (QuestionnaireBundle bundle : questionnaireBundleManager.bundles()) {
                                    if (questionnaire.getName().equals(bundle.getName())) {
                                        error(new StringResourceModel("Error.QuestionnaireAlreadyExists",
                                                UploadQuestionnairePanel.this, null,
                                                new Object[] { questionnaire.getName() }).getString());
                                        return;
                                    }
                                }
                            } else {
                                if (!questionnaire.getName().equals(updatedQuestionnaire.getName())) {
                                    error(new StringResourceModel(
                                            "Error.NameDifferentFromQuestionnaireToUpdate",
                                            UploadQuestionnairePanel.this, null, new Object[] {
                                                    questionnaire.getName(), updatedQuestionnaire.getName() })
                                                            .getString());
                                    return;
                                }
                            }

                        } else if (name.endsWith(".properties")) {
                            File tmp = new File(name);
                            FileOutputStream out = new FileOutputStream(tmp);
                            while ((n = zis.read(BUFFER, 0, BUFFER_SIZE)) > -1) {
                                out.write(BUFFER, 0, n);
                            }
                            localeProperties.add(tmp);
                            try {
                                out.close();
                            } catch (Exception e) {
                            }
                        }
                    }
                    zis.closeEntry();
                }

                if (questionnaire == null) {
                    error(new StringResourceModel("Error.MissingFile", UploadQuestionnairePanel.this, null,
                            new Object[] { "questionnaire.xml" }).getString());
                } else {
                    for (Locale locale : questionnaire.getLocales()) {
                        final String fileName = "language_" + locale.getLanguage() + ".properties";
                        File localeFile = Iterables.find(localeProperties, new Predicate<File>() {
                            public boolean apply(File file) {
                                return file.getName().equals(fileName);
                            }
                        });
                        if (localeFile == null) {
                            error(new StringResourceModel("Error.MissingFile", UploadQuestionnairePanel.this,
                                    null, new Object[] { fileName }).getString());
                        }
                        if (hasError())
                            return;
                    }
                    QuestionnaireBundle bundle = questionnaireBundleManager.createBundle(questionnaire,
                            localeProperties.toArray(new File[localeProperties.size()]));
                    questionnaireBundleManager.flushBundle(bundle);
                    questionnaireRegister.register(questionnaire);
                }

                // cleanup
                new File(clientFileName).delete();
                for (File f : localeProperties) {
                    f.delete();
                }
            } catch (IOException e) {
                log.error("IOException", e);
                error(getLocalizer().getString("Error.CannotReadFile", UploadQuestionnairePanel.this) + ": "
                        + e.getMessage());
            }
        }
    };
    form.setMultiPart(true);
    add(form);
    form.add(zipFile).add(new SimpleFormComponentLabel("zipLabel", zipFile))
            .add(new HelpTooltipPanel("zipHelp", new ResourceModel("File.ZIP.Tooltip")));

    form.add(new SaveCancelPanel("saveCancel", form) {

        @Override
        protected void onSave(AjaxRequestTarget target, Form<?> form1) {
            UploadQuestionnairePanel.this.onSave(target);
            uploadWindow.close(target);
        }

        @Override
        protected void onCancel(AjaxRequestTarget target, @SuppressWarnings("hiding") Form<?> form) {
            uploadWindow.close(target);
        }

        @Override
        protected void onError(AjaxRequestTarget target, @SuppressWarnings("hiding") Form<?> form) {
            feedbackWindow.setContent(feedbackPanel);
            feedbackWindow.show(target);
        }
    });
}

From source file:com.eviware.loadui.ui.fx.control.NotificationPanel.java

public void listenOnDetachedTabs() {
    tabsHolder.addOnDetachCallback(new Callback<StackPane, Boolean>() {
        @Override//from w w  w . jav a2 s. c o m
        public Boolean call(StackPane tabContents) {
            NotificationPanel clone = new NotificationPanel();
            clone.setOnShowLog(showLogHandler);
            clone.setMainWindowView(tabContents);
            tabContents.getChildren().add(clone);
            return true;
        }
    });

    tabsHolder.addOnReattachCallback(new Callback<StackPane, Boolean>() {
        @Override
        public Boolean call(StackPane tabContents) {
            Node panel = Iterables.find(tabContents.getChildren(), new Predicate<Node>() {
                @Override
                public boolean apply(@Nullable Node input) {
                    return input != null && input.getClass().isAssignableFrom(NotificationPanel.class);
                }
            });
            tabContents.getChildren().remove(panel);
            allPanels.remove(panel);
            return true;
        }
    });

}

From source file:com.netxforge.netxstudio.screens.editing.DirtyStateMessageDialog.java

public CDOID objectFor(final CDOFeatureDelta delta) {
    CDOID result = null;//from w w  w .  j av  a2s .com
    if (transaction.getRevisionDeltas() != null) {
        Set<Entry<CDOID, CDORevisionDelta>> entrySet = transaction.getRevisionDeltas().entrySet();

        Entry<CDOID, CDORevisionDelta> find = Iterables.find(entrySet,
                new Predicate<Entry<CDOID, CDORevisionDelta>>() {

                    public boolean apply(Entry<CDOID, CDORevisionDelta> input) {

                        return input.getValue().getFeatureDelta(delta.getFeature()) != null;
                    }

                });
        if (find != null) {
            result = find.getKey();
        }
    }
    return result;
}

From source file:io.redlink.sdk.impl.analysis.model.Enhancements.java

/**
 * Returns an {@link EntityAnnotation} by its associated dereferenced {@link Entity} URI
 *
 * @param entityUri/*from  ww w  . ja v a  2 s .co m*/
 * @return
 */
public EntityAnnotation getEntityAnnotation(final String entityUri) {
    return Iterables.find(getEntityAnnotations(), new Predicate<EntityAnnotation>() {

        @Override
        public boolean apply(EntityAnnotation ea) {
            return ea.getEntityReference().getUri().equals(entityUri);
        }

    });
}

From source file:com.eucalyptus.ws.EmpyreanService.java

public static ServiceConfiguration findService(final String name) {
    assertThat(name, notNullValue());/*  ww w.java 2s  . co  m*/
    Predicate<ServiceConfiguration> nameOrFullName = new Predicate<ServiceConfiguration>() {

        @Override
        public boolean apply(ServiceConfiguration input) {
            return name.equals(input.getName()) || name.equals(input.getFullName().toString());
        }
    };
    for (final ComponentId compId : ComponentIds.list()) {
        ServiceConfiguration a;
        try {
            return Iterables.find(Components.lookup(compId).services(), nameOrFullName);
        } catch (NoSuchElementException ex) {
            if (compId.isRegisterable()) {
                try {
                    return ServiceConfigurations.lookupByName(compId.getClass(), name);
                } catch (Exception ex1) {
                }
            }
        }
    }
    throw new NoSuchElementException("Failed to lookup service named: " + name);
}