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

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

Introduction

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

Prototype

static <T> T[] toArray(Iterable<? extends T> iterable, T[] array) 

Source Link

Usage

From source file:com.inmobi.grill.cli.commands.GrillFactCommands.java

@CliCommand(value = "fact drop storage", help = "drop a storage from fact")
public String dropStorageFromFact(
        @CliOption(key = { "", "table" }, mandatory = true, help = "<table> <storage>") String tablepair) {
    Iterable<String> parts = Splitter.on(' ').trimResults().omitEmptyStrings().split(tablepair);
    String[] pair = Iterables.toArray(parts, String.class);
    if (pair.length != 2) {
        return "Syntax error, please try in following " + "format. fact drop storage <table> <storage>";
    }//from ww w  .j  a va 2  s.  com

    File f = new File(pair[0]);

    if (!f.exists()) {
        return "Fact spec path" + f.getAbsolutePath() + " does not exist. Please check the path";
    }
    f = new File(pair[1]);
    if (!f.exists()) {
        return "Storage spech path " + f.getAbsolutePath() + " does not exist. Please check the path";
    }

    APIResult result = client.dropStorageFromFact(pair[0], pair[1]);
    if (result.getStatus() == APIResult.Status.SUCCEEDED) {
        return "Fact table storage removal successful";
    } else {
        return "Fact table storage removal failed";
    }
}

From source file:edu.mayo.cts2.framework.plugin.service.bioportal.transform.AbstractBioportalOntologyVersionTransformTemplate.java

/**
 * Transform resource version.// w w  w .  j  a v a  2  s .  com
 *
 * @param xml the xml
 * @return the r
 */
public R transformResourceVersion(String xml) {

    Node node = TransformUtils.getNamedChildWithPath(BioportalRestUtils.getDocument(xml), ONTOLOGY_BEAN);

    String abbreviation = TransformUtils.getNamedChildText(node, ABBREVIATION);
    String ontologyVersionId = TransformUtils.getNamedChildText(node, ONTOLOGY_VERSION_ID);
    String ontologyId = TransformUtils.getNamedChildText(node, ONTOLOGY_ID);
    String displayLabel = TransformUtils.getNamedChildText(node, DISPLAY_LABEL);
    String description = TransformUtils.getNamedChildText(node, DESCRIPTION);
    String format = TransformUtils.getNamedChildText(node, FORMAT);
    String downloadLocation = TransformUtils.getNamedChildText(node, DOWNLOAD_LOCATION);

    String resourceName = this.getResourceName(ontologyId);

    String resourceVersionName = this.getResourceVersionName(ontologyId, ontologyVersionId);

    String about = this.getAbout(ontologyVersionId, resourceName);

    R resourceVersion = this.createNewResourceVersion();
    resourceVersion.setAbout(about);
    resourceVersion = this.setName(resourceVersion, resourceVersionName);
    resourceVersion.setFormalName(displayLabel);
    resourceVersion.setResourceSynopsis(new EntryDescription());
    resourceVersion.getResourceSynopsis().setValue(ModelUtils.toTsAnyType(description));
    resourceVersion.setOfficialResourceVersionId(this.getOfficialResourceVersionId(node));
    resourceVersion.addKeyword(abbreviation);
    resourceVersion.addKeyword(ontologyId);
    resourceVersion.addKeyword(ontologyVersionId);
    resourceVersion.setSourceAndNotation(new SourceAndNotation());
    resourceVersion.getSourceAndNotation().setSourceDocumentSyntax(new OntologySyntaxReference());
    resourceVersion.getSourceAndNotation().getSourceDocumentSyntax().setContent(format);

    resourceVersion.getSourceAndNotation().setSourceDocument(downloadLocation);

    resourceVersion.setOfficialReleaseDate(this.getDateReleased(node));

    resourceVersion.setProperty(Iterables.toArray(this.getProperties(node, resourceName), Property.class));

    resourceVersion.addSourceAndRole(this.getSourceAndRoleReference(node));

    resourceVersion.setDocumentURI(this.getIdentityConverter().getDocumentUri(ontologyVersionId));

    resourceVersion = this.decorateResourceVersion(node, resourceName, resourceVersion);

    resourceVersion.addProperty(this.createOntologyIdProperty(ontologyId));
    resourceVersion.addProperty(this.createOntologyVersionIdProperty(ontologyVersionId));

    return resourceVersion;
}

From source file:com.inmobi.grill.cli.commands.GrillDimensionCommands.java

@CliCommand(value = "dim add storage", help = "adds a new storage to dimension")
public String addNewDimStorage(
        @CliOption(key = { "", "table" }, mandatory = true, help = "<table> <storage>") String tablepair) {
    Iterable<String> parts = Splitter.on(' ').trimResults().omitEmptyStrings().split(tablepair);
    String[] pair = Iterables.toArray(parts, String.class);
    if (pair.length != 2) {
        return "Syntax error, please try in following "
                + "format. create fact <fact spec path> <storage spec path>";
    }//  w  w  w  .ja v a 2  s.  c  om

    File f = new File(pair[0]);

    if (!f.exists()) {
        return "Fact spec path" + f.getAbsolutePath() + " does not exist. Please check the path";
    }
    f = new File(pair[1]);
    if (!f.exists()) {
        return "Storage spech path " + f.getAbsolutePath() + " does not exist. Please check the path";
    }

    APIResult result = client.addStorageToDim(pair[0], pair[1]);
    if (result.getStatus() == APIResult.Status.SUCCEEDED) {
        return "Dim table storage addition completed";
    } else {
        return "Dim table storage addition failed";
    }
}

From source file:org.apache.lens.cli.commands.LensDimensionTableCommands.java

/**
 * Drop storage from dim.//from  w  w  w.j  a  va2  s. c  o  m
 *
 * @param tablepair the tablepair
 * @return the string
 */
@CliCommand(value = "dimtable drop storage", help = "drop storage to dimension table")
public String dropStorageFromDim(@CliOption(key = { "",
        "table" }, mandatory = true, help = "<dimension-table-name> <storage-name>") String tablepair) {
    Iterable<String> parts = Splitter.on(' ').trimResults().omitEmptyStrings().split(tablepair);
    String[] pair = Iterables.toArray(parts, String.class);
    if (pair.length != 2) {
        return "Syntax error, please try in following "
                + "format. create dimtable <dimtable spec path> <storage spec path>";
    }
    APIResult result = getClient().dropStorageFromDim(pair[0], pair[1]);
    if (result.getStatus() == APIResult.Status.SUCCEEDED) {
        return "Dim table storage removal successful";
    } else {
        return "Dim table storage removal failed";
    }
}

From source file:com.android.build.gradle.internal.incremental.IncrementalVisitor.java

protected static void main(@NonNull String[] args, @NonNull VisitorBuilder visitorBuilder) throws IOException {

    if (args.length != 3) {
        throw new IllegalArgumentException(
                "Needs to be given an input and output directory " + "and a classpath");
    }//from  w  w w.  jav  a2 s.c  o  m

    File srcLocation = new File(args[0]);
    File baseInstrumentedCompileOutputFolder = new File(args[1]);
    FileUtils.cleanOutputDir(baseInstrumentedCompileOutputFolder);

    Iterable<String> classPathStrings = Splitter.on(File.pathSeparatorChar).split(args[2]);
    List<URL> classPath = Lists.newArrayList();
    for (String classPathString : classPathStrings) {
        File path = new File(classPathString);
        if (!path.exists()) {
            throw new IllegalArgumentException(String.format("Invalid class path element %s", classPathString));
        }
        classPath.add(path.toURI().toURL());
    }
    classPath.add(srcLocation.toURI().toURL());
    URL[] classPathArray = Iterables.toArray(classPath, URL.class);

    ClassLoader classesToInstrumentLoader = new URLClassLoader(classPathArray, null) {
        @Override
        public URL getResource(String name) {
            // Never delegate to bootstrap classes.
            return findResource(name);
        }
    };

    ClassLoader originalThreadContextClassLoader = Thread.currentThread().getContextClassLoader();
    try {
        Thread.currentThread().setContextClassLoader(classesToInstrumentLoader);
        instrumentClasses(srcLocation, baseInstrumentedCompileOutputFolder, visitorBuilder);
    } finally {
        Thread.currentThread().setContextClassLoader(originalThreadContextClassLoader);
    }
}

From source file:org.polarsys.reqcycle.styling.ui.providers.StylingContentProvider.java

@Override
public Object[] getChildren(final Object object) {
    Collection<AbstractElement> elements = Collections.emptyList();

    if (object instanceof RequirementSource) {
        RequirementSource requirementSource = (RequirementSource) object;
        if ((displayType.equals(RequirementViewDisplayType.FILTERBYPREDICATE)) && (predicates.size() == 1)) {
            IPredicate predicate = predicates.get(0);

            return Iterators.toArray(
                    Iterators.filter(requirementSource.getRequirements().iterator(), new PPredicate(predicate)),
                    Object.class);
        } else if (displayType.equals(RequirementViewDisplayType.FILTERBYNAME)) {
            final Pattern p = Pattern.compile(".*" + reqFilter + ".*", Pattern.DOTALL);
            final Predicate<Object> attPredicate = new Predicate<Object>() {
                @Override//from   w w  w.  j  a va2 s.co  m
                public boolean apply(Object arg0) {
                    if (arg0 instanceof Requirement) {
                        Requirement req = (Requirement) arg0;
                        return req.getId() != null && p.matcher(req.getId()).matches();
                    }
                    return false;
                }
            };
            return Iterators.toArray(Iterators.filter(new Source2Reqs().apply(requirementSource), attPredicate),
                    Object.class);
        } else {
            if (displayType.equals(RequirementViewDisplayType.REQONLY)) {
                return Iterators.toArray(
                        Iterators.concat(Iterators.transform(
                                Collections.singletonList(requirementSource).iterator(), new Source2Reqs())),
                        Object.class);
            } else {
                elements = requirementSource.getRequirements();
            }
        }
    } else if (object instanceof IPredicate) {
        return Iterators.toArray(Iterators.filter(
                Iterators.concat(Iterators.transform(navigatorRoot.getSources().iterator(), new Source2Reqs())),
                new PPredicate((IPredicate) object)), Object.class);
    } else if (object instanceof Section) {
        if ((displayType.equals(RequirementViewDisplayType.FILTERBYPREDICATE)) && (predicates.size() == 1)) {
            IPredicate predicate = predicates.get(0);
            return Iterators.toArray(
                    Iterators.filter(((Section) object).getChildren().iterator(), new PPredicate(predicate)),
                    Object.class);
        } else {
            elements = ((Section) object).getChildren();
        }
    } else if (object instanceof Scope) {
        return ((Scope) object).getRequirements().toArray();
    }

    if (elements.size() != 0) {
        return Iterables.toArray(elements, Object.class);
    } else {
        return null;
    }
}

From source file:com.icosilune.fn.processor.FnProcessor.java

private void generateIndex(String packageName, Collection<String> classes,
        Iterable<? extends TypeElement> originatingTypes) {
    StringBuilder indexText = new StringBuilder();

    indexText.append("package " + packageName + ";\n");
    indexText.append("\n");
    indexText.append("import com.google.common.collect.ImmutableClassToInstanceMap;\n");
    indexText.append("import com.icosilune.fn.AbstractFn;\n");
    indexText.append("\n");
    indexText.append("public class " + INDEX_NAME + " {\n");
    indexText.append("  public static final ImmutableClassToInstanceMap<AbstractFn> INSTANCES =\n");
    indexText.append("      ImmutableClassToInstanceMap.<AbstractFn>builder()\n");
    for (String instanceClass : classes) {
        indexText.append("          .put(" + instanceClass + ".class, new " + instanceClass + "())\n");
    }//from w w w .j  a  v  a 2 s . co m
    indexText.append("          .build();\n");
    indexText.append("}\n");

    writeSourceFile(packageName + "." + INDEX_NAME, indexText.toString(),
            Iterables.toArray(originatingTypes, TypeElement.class));
}

From source file:org.eclipselabs.spray.xtext.ui.wizard.MetamodelSelectionComposite.java

/**
 * Create the composite.//from   w  w  w . jav  a 2  s .co m
 * 
 * @param parent
 * @param style
 */
public MetamodelSelectionComposite(Composite parent, int style, SprayProjectInfo projectInfo) {
    super(parent, style);
    this.projectInfo = projectInfo;
    setLayout(new GridLayout(1, false));

    Group grpMetamodel = new Group(this, SWT.NONE);
    GridData gd_grpMetamodel = new GridData(SWT.LEFT, SWT.CENTER, true, false, 1, 1);
    gd_grpMetamodel.widthHint = 600;
    grpMetamodel.setLayoutData(gd_grpMetamodel);
    grpMetamodel.setText("Metamodel");
    grpMetamodel.setLayout(new GridLayout(2, false));

    Label lblEpackage = new Label(grpMetamodel, SWT.NONE);
    lblEpackage.setText("EPackage URI");

    txtUri = new Text(grpMetamodel, SWT.BORDER);
    txtUri.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));

    Composite composite = new Composite(grpMetamodel, SWT.NONE);
    composite.setLayout(new GridLayout(2, false));
    composite.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1));

    Button btnNewButton = new Button(composite, SWT.NONE);
    btnNewButton.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
            RegisteredPackageDialog registeredPackageDialog = new RegisteredPackageDialog(shell) {
                @Override
                protected void setListElements(Object[] elements) {
                    if (elements == null)
                        return;
                    List<String> pckUris = new LinkedList<String>();
                    for (Object element : elements) {
                        if (!getProjectInfo().getFilterSystemEPackages()
                                || !ePackageUriFilter.apply(element.toString()))
                            pckUris.add(element.toString());
                    }
                    super.setListElements(pckUris.toArray());
                }
            };
            registeredPackageDialog.setMultipleSelection(false);
            registeredPackageDialog.open();
            Object[] result = registeredPackageDialog.getResult();
            if (result != null) {
                List<?> nsURIs = Arrays.asList(result);
                setNsURIs(nsURIs, txtUri, registeredPackageDialog.isDevelopmentTimeVersion(), false);
            }
        }
    });
    btnNewButton.setText("Browse Registered Packages...");

    Button btnBrowseWorkspace = new Button(composite, SWT.NONE);
    btnBrowseWorkspace.setText("Browse Workspace...");

    btnFilterSystemEPackages = new Button(composite, SWT.CHECK);
    btnFilterSystemEPackages.setSelection(true);
    btnFilterSystemEPackages.setText("Filter System EPackages");
    new Label(composite, SWT.NONE);
    btnBrowseWorkspace.addSelectionListener(new BrowseResourceSelectionAdapter(txtUri, "ecore"));

    Label lblGenmodelUri = new Label(grpMetamodel, SWT.NONE);
    lblGenmodelUri.setText("GenModel URI");

    txtGenmodelUri = new Text(grpMetamodel, SWT.BORDER);
    txtGenmodelUri.setEnabled(true);
    txtGenmodelUri.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));

    Composite composite_1 = new Composite(grpMetamodel, SWT.NONE);
    composite_1.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1));
    composite_1.setLayout(new RowLayout(SWT.HORIZONTAL));

    Button btnBrowseWorkspace_1 = new Button(composite_1, SWT.NONE);
    btnBrowseWorkspace_1.setText("Browse Workspace...");
    btnBrowseWorkspace_1.addSelectionListener(new BrowseResourceSelectionAdapter(txtGenmodelUri, "genmodel"));

    Label lblModelEclass = new Label(grpMetamodel, SWT.NONE);
    lblModelEclass.setText("Model EClass");

    txtModelType = new Text(grpMetamodel, SWT.BORDER);
    txtModelType.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));

    Button btnNewButton_1 = new Button(grpMetamodel, SWT.NONE);
    btnNewButton_1.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            ResourceSet rs = new ResourceSetImpl();
            Resource res = rs.getResource(URI.createURI(txtUri.getText()), true);

            EPackage pck = (EPackage) res.getContents().get(0);
            ElementListSelectionDialog dlg = new ElementListSelectionDialog(getShell(), labelProvider);
            dlg.setElements(
                    Iterables.toArray(Iterables.filter(pck.getEClassifiers(), EClass.class), Object.class));
            if (dlg.open() == Dialog.OK) {
                EClass cls = (EClass) dlg.getFirstResult();
                txtModelType.setText(qnProvider.getFullyQualifiedName(cls).toString());
                txtFileExtension.setText(genmodelHelper.getFileExtension(cls));
            }
        }
    });
    btnNewButton_1.setText("Select Type");
    new Label(grpMetamodel, SWT.NONE);

    Label lblFileExtension = new Label(grpMetamodel, SWT.NONE);
    lblFileExtension.setText("File Extension");

    txtFileExtension = new Text(grpMetamodel, SWT.BORDER);
    GridData gd_txtFileExtension = new GridData(SWT.LEFT, SWT.CENTER, true, false, 1, 1);
    gd_txtFileExtension.widthHint = 130;
    txtFileExtension.setLayoutData(gd_txtFileExtension);

    m_bindingContext = initDataBindings();

    txtUri.addModifyListener(new ModifyListener() {
        public void modifyText(ModifyEvent e) {
            URI ePackageUri = URI.createURI(txtUri.getText());
            if (ePackageUri.isPlatformPlugin()) {
                ResourceSetImpl rs = new ResourceSetImpl();
                try {
                    Resource r = rs.getResource(ePackageUri, true);
                    EPackage pck = (EPackage) r.getContents().get(0);
                    URI genModelUri = EcorePlugin.getEPackageNsURIToGenModelLocationMap().get(pck.getNsURI());
                    if (genModelUri != null) {
                        txtGenmodelUri.setText(genModelUri.toString());
                    } else {
                        txtGenmodelUri.setText("");
                    }
                } catch (Exception ex) {
                    txtGenmodelUri.setText("");
                }
            } else {
                // platform resource; clear genmodel
                if (txtGenmodelUri.getText().length() > 0
                        && URI.createURI(txtGenmodelUri.getText()).isPlatformPlugin()) {
                    txtGenmodelUri.setText("");
                }
                if (ePackageUri.isPlatformResource()) {
                    // try to find a sibling genmodel
                    IPath path = new Path(ePackageUri.toString().replace("platform:/resource", ""))
                            .removeFileExtension().addFileExtension("genmodel");
                    if (ResourcesPlugin.getWorkspace().getRoot().findMember(path) != null) {
                        txtGenmodelUri.setText(URI.createPlatformResourceURI(path.toString(), true).toString());
                    }
                }
            }

        }
    });
}

From source file:ec.nbdemetra.ui.demo.impl.TsCollectionHandler.java

static JButton createSelectionButton(final ITsCollectionView view) {
    final Action[] selectionActions = { new AbstractAction("All") {
        @Override// www. j  a  v  a  2s.c  o  m
        public void actionPerformed(ActionEvent e) {
            view.setSelection(view.getTsCollection().toArray());
        }
    }, new AbstractAction("None") {
        @Override
        public void actionPerformed(ActionEvent e) {
            view.setSelection(null);
        }
    }, new AbstractAction("Alternate") {
        @Override
        public void actionPerformed(ActionEvent e) {
            List<Ts> tmp = new ArrayList<>();
            for (int i = 0; i < view.getTsCollection().getCount(); i += 2) {
                tmp.add(view.getTsCollection().get(i));
            }
            view.setSelection(Iterables.toArray(tmp, Ts.class));
        }
    }, new AbstractAction("Inverse") {
        @Override
        public void actionPerformed(ActionEvent e) {
            List<Ts> tmp = Lists.newArrayList(view.getTsCollection());
            tmp.removeAll(Arrays.asList(view.getSelection()));
            view.setSelection(Iterables.toArray(tmp, Ts.class));
        }
    } };
    JPopupMenu menu = new JPopupMenu();
    for (Action o : selectionActions) {
        menu.add(o);
    }
    JButton result = DropDownButtonFactory.createDropDownButton(DemetraUiIcon.PUZZLE_16, menu);
    result.addActionListener(new ActionListener() {
        int i = 0;

        @Override
        public void actionPerformed(ActionEvent e) {
            selectionActions[i++ % selectionActions.length].actionPerformed(e);
        }
    });
    return result;
}

From source file:org.blip.workflowengine.transferobject.ModifiablePropertyNode.java

@Override
public PropertyNode add(final String key, final Double value, final Collection<Attribute> attributes) {
    return internalAdd(true, key, value, Iterables.toArray(attributes, Attribute.class));
}