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 add storage", help = "adds a new storage to fact")
public String addNewFactStorage(
        @CliOption(key = { "", "table" }, mandatory = true, help = "<table> <storage-spec>") 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 add storage <table> <storage spec path>";
    }/* w w  w .j  a  va 2s  . 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.addStorageToFact(pair[0], pair[1]);
    if (result.getStatus() == APIResult.Status.SUCCEEDED) {
        return "Fact table storage addition completed";
    } else {
        return "Fact table storage addition failed";
    }
}

From source file:org.dcache.gridsite.BouncyCastleCredentialDelegation.java

@Override
public GSSCredential acceptCertificate(String encodedCertificate) throws DelegationException {
    X509Certificate certificate;/*from w  w  w .j a  v a  2  s . co  m*/

    try {
        certificate = pemDecodeCertificate(encodedCertificate);
        verifyCertificate(certificate);
    } catch (CertificateException e) {
        LOG.debug("Bad certificate: {}", e.getMessage());
        throw new DelegationException("Supplied certificate is " + "unacceptable: " + e.getMessage());
    }

    X509Certificate[] newCertificates = Iterables.toArray(
            transform(concat(singleton(certificate), _certificates), AS_BC_CERTIFICATE), X509Certificate.class);

    X509Credential proxy = new X509Credential(_keyPair.getPrivate(), newCertificates);

    try {
        return new GlobusGSSCredentialImpl(proxy, INITIATE_AND_ACCEPT);
    } catch (GSSException e) {
        LOG.error("Failed to create delegated credential: {}", e.getMessage());
        throw new DelegationException("Unable to create delegated" + " credential: " + e.getMessage());
    }
}

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

/**
 * Adds the new dim storage./*from w w w  . j ava 2 s.  c om*/
 *
 * @param tablepair the tablepair
 * @return the string
 */
@CliCommand(value = "dimtable add storage", help = "adds a new storage to dimension")
public String addNewDimStorage(@CliOption(key = { "",
        "table" }, mandatory = true, help = "<dim-table-name> <path to storage-spec>") 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>";
    }

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

    APIResult result = getClient().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:com.nike.cerberus.auth.connector.onelogin.OneLoginAuthConnector.java

/**
 * Takes the list of ldapGroups received from OneLogin and parses them in to a set of Strings
 * @param ldapGroups A string consisting of ldap groups received from OneLogin
 * @return A set of Strings consisting of the ldap groups that were parsed from the provided string
 *///  w  ww  .  j  av a 2 s  .  com
protected Set<String> parseLdapGroups(final String ldapGroups) {
    Set<String> groups = new HashSet<>();
    if (ldapGroups == null) {
        return groups;
    }

    // One Login double xml escapes entries
    String escapedLdapGroups = StringEscapeUtils.unescapeXml(StringEscapeUtils.unescapeXml(ldapGroups));

    Iterable<String> canonicalNameIterable;
    Iterable<String> piecesIterable;
    Iterable<String> canonicalNames = Splitter.on(";").split(escapedLdapGroups);
    for (String canonicalName : canonicalNames) {
        canonicalNameIterable = Splitter.on(",").split(canonicalName);
        String[] pieces = Iterables.toArray(canonicalNameIterable, String.class);

        piecesIterable = Splitter.on("=").split(pieces[0]);
        String[] parts = Iterables.toArray(piecesIterable, String.class);
        if (parts.length >= 2) {
            groups.add(parts[1]);
        } else {
            throw ApiException.newBuilder().withApiErrors(DefaultApiError.SERVICE_UNAVAILABLE)
                    .withExceptionMessage("OneLogin user info member-of field is malformed!").build();
        }
    }

    return groups;
}

From source file:org.polymap.core.mapeditor.tooling.edit.SnapTool.java

@Override
public void onActivate() {
    super.onActivate();

    // create snapLayers
    snapLayers = new ArrayList();
    final Predicate<ILayer> isVector = BaseLayerEditorTool.isVector();
    parentTool.getSelectedLayer().getMap().visit(new LayerVisitor() {
        public boolean visit(ILayer layer) {
            if (layer.isVisible() && isVector.apply(layer)) {
                try {
                    SnapVectorLayer snapLayer = new SnapVectorLayer(getSite(), layer);
                    snapLayer.activate();

                    ReferencedEnvelope bounds = getSite().getEditor().getMap().getExtent();
                    snapLayer.selectFeatures(bounds, false);

                    snapLayers.add(snapLayer);
                    getSite().getEditor().addLayer(snapLayer.getVectorLayer());
                } catch (Exception e) {
                    log.warn("", e);
                }//from   www  .  j a  va2  s  .c om
            }
            return true;
        }
    });

    // control
    VectorLayer[] targetLayers = Iterables.toArray(Lists.transform(snapLayers, BaseVectorLayer.toVectorLayer()),
            VectorLayer.class);
    control = new SnappingControl(parentTool.getVectorLayer().getVectorLayer(), targetLayers, false, tolerance);
    getSite().getEditor().addControl(control);
    control.activate();

    parentTool.addListener(this);
}

From source file:ch.ge.ve.commons.properties.PropertyConfigurationService.java

/**
 * Gets a property value as an array of String.
 * The property values have to be formatted with each value separated by a comma,
 * e.g "value1,value2"//from  w  ww. j  a  v a  2 s  .com
 *
 * @param key the property key
 * @return the property value
 * @throws PropertyConfigurationException if fails to find or convert the property
 */
public String[] getConfigValueAsArray(String key) throws PropertyConfigurationException {
    String configValue = properties.getProperty(key);
    if (configValue == null) {
        throw new PropertyConfigurationException("The property [" + key + "] does not exist");
    }
    ArrayList<String> elementList = Lists.newArrayList();
    Iterable<String> elements = Splitter.on(",").split(configValue);
    for (String element : elements) {
        elementList.add(element.trim());
    }
    return Iterables.toArray(elementList, String.class);
}

From source file:org.gradle.api.internal.tasks.compile.ApiGroovyCompiler.java

public WorkResult execute(final GroovyJavaJointCompileSpec spec) {
    GroovySystemLoaderFactory groovySystemLoaderFactory = new GroovySystemLoaderFactory();
    ClassLoader compilerClassLoader = this.getClass().getClassLoader();
    GroovySystemLoader compilerGroovyLoader = groovySystemLoaderFactory.forClassLoader(compilerClassLoader);

    CompilerConfiguration configuration = new CompilerConfiguration();
    configuration.setVerbose(spec.getGroovyCompileOptions().isVerbose());
    configuration.setSourceEncoding(spec.getGroovyCompileOptions().getEncoding());
    configuration.setTargetBytecode(spec.getTargetCompatibility());
    configuration.setTargetDirectory(spec.getDestinationDir());
    canonicalizeValues(spec.getGroovyCompileOptions().getOptimizationOptions());
    if (spec.getGroovyCompileOptions().getConfigurationScript() != null) {
        applyConfigurationScript(spec.getGroovyCompileOptions().getConfigurationScript(), configuration);
    }/* ww w .  jav a  2 s  .co  m*/
    try {
        configuration.setOptimizationOptions(spec.getGroovyCompileOptions().getOptimizationOptions());
    } catch (NoSuchMethodError ignored) {
        /* method was only introduced in Groovy 1.8 */ }
    Map<String, Object> jointCompilationOptions = new HashMap<String, Object>();
    final File stubDir = spec.getGroovyCompileOptions().getStubDir();
    stubDir.mkdirs();
    jointCompilationOptions.put("stubDir", stubDir);
    jointCompilationOptions.put("keepStubs", spec.getGroovyCompileOptions().isKeepStubs());
    configuration.setJointCompilationOptions(jointCompilationOptions);

    ClassLoader classPathLoader;
    VersionNumber version = parseGroovyVersion();
    if (version.compareTo(VersionNumber.parse("2.0")) < 0) {
        // using a transforming classloader is only required for older buggy Groovy versions
        classPathLoader = new GroovyCompileTransformingClassLoader(getExtClassLoader(),
                new DefaultClassPath(spec.getClasspath()));
    } else {
        classPathLoader = new DefaultClassLoaderFactory()
                .createIsolatedClassLoader(new DefaultClassPath(spec.getClasspath()));
    }
    GroovyClassLoader compileClasspathClassLoader = new GroovyClassLoader(classPathLoader, null);
    GroovySystemLoader compileClasspathLoader = groovySystemLoaderFactory.forClassLoader(classPathLoader);

    FilteringClassLoader groovyCompilerClassLoader = new FilteringClassLoader(
            GroovyClassLoader.class.getClassLoader());
    groovyCompilerClassLoader.allowPackage("org.codehaus.groovy");
    groovyCompilerClassLoader.allowPackage("groovy");
    // Disallow classes from Groovy Jar that reference external classes. Such classes must be loaded from astTransformClassLoader,
    // or a NoClassDefFoundError will occur. Essentially this is drawing a line between the Groovy compiler and the Groovy
    // library, albeit only for selected classes that run a high risk of being statically referenced from a transform.
    groovyCompilerClassLoader.disallowClass("groovy.util.GroovyTestCase");
    groovyCompilerClassLoader.disallowPackage("groovy.servlet");

    // AST transforms need their own class loader that shares compiler classes with the compiler itself
    final GroovyClassLoader astTransformClassLoader = new GroovyClassLoader(groovyCompilerClassLoader, null);
    // can't delegate to compileClasspathLoader because this would result in ASTTransformation interface
    // (which is implemented by the transform class) being loaded by compileClasspathClassLoader (which is
    // where the transform class is loaded from)
    for (File file : spec.getClasspath()) {
        astTransformClassLoader.addClasspath(file.getPath());
    }
    JavaAwareCompilationUnit unit = new JavaAwareCompilationUnit(configuration, compileClasspathClassLoader) {
        @Override
        public GroovyClassLoader getTransformLoader() {
            return astTransformClassLoader;
        }
    };

    final boolean shouldProcessAnnotations = shouldProcessAnnotations(astTransformClassLoader, spec);
    if (shouldProcessAnnotations) {
        // If an annotation processor is detected, we need to force Java stub generation, so the we can process annotations on Groovy classes
        // We are forcing stub generation by tricking the groovy compiler into thinking there are java files to compile.
        // All java files are just passed to the compile method of the JavaCompiler and aren't processed internally by the Groovy Compiler.
        // Since we're maintaining our own list of Java files independent what's passed by the Groovy compiler, adding a non-existant java file
        // to the sources won't cause any issues.
        unit.addSources(new File[] { new File("ForceStubGeneration.java") });
    }

    unit.addSources(Iterables.toArray(spec.getSource(), File.class));
    unit.setCompilerFactory(new JavaCompilerFactory() {
        public JavaCompiler createCompiler(final CompilerConfiguration config) {
            return new JavaCompiler() {
                public void compile(List<String> files, CompilationUnit cu) {
                    if (shouldProcessAnnotations) {
                        // In order for the Groovy stubs to have annotation processors invoked against them, they must be compiled as source.
                        // Classes compiled as a result of being on the -sourcepath do not have the annotation processor run against them
                        spec.setSource(
                                spec.getSource().plus(new SimpleFileCollection(stubDir).getAsFileTree()));
                    } else {
                        // When annotation processing isn't required, it's better to add the Groovy stubs as part of the source path.
                        // This allows compilations to complete faster, because only the Groovy stubs that are needed by the java source are compiled.
                        FileCollection sourcepath = new SimpleFileCollection(stubDir);
                        if (spec.getCompileOptions().getSourcepath() != null) {
                            sourcepath = spec.getCompileOptions().getSourcepath().plus(sourcepath);
                        }
                        spec.getCompileOptions().setSourcepath(sourcepath);
                    }

                    spec.setSource(spec.getSource().filter(new Spec<File>() {
                        public boolean isSatisfiedBy(File file) {
                            return file.getName().endsWith(".java");
                        }
                    }));

                    try {
                        javaCompiler.execute(spec);
                    } catch (CompilationFailedException e) {
                        cu.getErrorCollector().addFatalError(new SimpleMessage(e.getMessage(), cu));
                    }
                }
            };
        }
    });

    try {
        unit.compile();
    } catch (org.codehaus.groovy.control.CompilationFailedException e) {
        System.err.println(e.getMessage());
        throw new CompilationFailedException();
    } finally {
        // Remove compile and AST types from the Groovy loader
        compilerGroovyLoader.discardTypesFrom(classPathLoader);
        compilerGroovyLoader.discardTypesFrom(astTransformClassLoader);
        //Discard the compile loader
        compileClasspathLoader.shutdown();
    }

    return new SimpleWorkResult(true);
}

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

/**
 * Transform entity node for relationships.
 *
 * @param codeSystemName the code system name
 * @param codeSystemVersionName the code system version name
 * @param predicateName the predicate name
 * @param node the node/*www .  ja v  a2 s  . c o m*/
 * @return the list
 */
public URIAndEntityName[] transformURIAndEntityNameForRelationships(String xml, final String codeSystemName,
        final String codeSystemVersionName, final String predicateName) {

    Node xmlNode = TransformUtils.getNamedChildWithPath(BioportalRestUtils.getDocument(xml), NODE);

    List<URIAndEntityName> returnList = this
            .doTransformEntityNodeForRelationships(new Transform<URIAndEntityName>() {

                @Override
                public URIAndEntityName transform(Node entryNode) {
                    URIAndEntityName entityName = new URIAndEntityName();

                    String about = getAbout(entryNode);
                    String name = getName(entryNode);

                    entityName.setName(name);
                    entityName.setNamespace(codeSystemName);
                    String version = getIdentityConverter()
                            .codeSystemVersionNameToVersion(codeSystemVersionName);
                    entityName.setHref(getUrlConstructor().createEntityUrl(codeSystemName, version, name));
                    entityName.setUri(about);

                    return entityName;
                }
            }, codeSystemName, codeSystemVersionName, predicateName, xmlNode);

    return Iterables.toArray(returnList, URIAndEntityName.class);
}

From source file:co.cask.cdap.internal.app.runtime.ProgramRuntimeProviderLoader.java

/**
 * Creates a {@link ServiceLoader} from the {@link ClassLoader} created by all jar files under the given directory.
 */// w ww  . j  av  a  2  s .co  m
private ServiceLoader<ProgramRuntimeProvider> createServiceLoader(File dir) {
    List<File> files = new ArrayList<>(DirUtils.listFiles(dir, "jar"));
    Collections.sort(files);

    URL[] urls = Iterables.toArray(Iterables.transform(files, new Function<File, URL>() {
        @Override
        public URL apply(File input) {
            try {
                return input.toURI().toURL();
            } catch (MalformedURLException e) {
                // Shouldn't happen
                throw Throwables.propagate(e);
            }
        }
    }), URL.class);

    URLClassLoader classLoader = new URLClassLoader(urls, DefaultProgramRunnerFactory.class.getClassLoader());
    return ServiceLoader.load(ProgramRuntimeProvider.class, classLoader);
}

From source file:eu.interedition.text.repository.JdbcStore.java

@Override
public void deleteTexts(Iterable<Long> ids) {
    if (Iterables.isEmpty(ids)) {
        return;/*ww  w.  j a  va  2 s. c o  m*/
    }
    ResultSet rs = null;
    try {
        final Long[] idArray = Iterables.toArray(ids, Long.class);
        final List<Long> annotationIds = Lists.newLinkedList();

        if (selectAnnotationsByTexts == null) {
            selectAnnotationsByTexts = connection
                    .prepareStatement("select distinct at.annotation_id " + "from table(id bigint = ?) text "
                            + "join interedition_text_annotation_target at on text.id = at.text_id");
        }
        selectAnnotationsByTexts.setObject(1, idArray);
        rs = selectAnnotationsByTexts.executeQuery();
        while (rs.next()) {
            annotationIds.add(rs.getLong(1));
        }

        deleteAnnotations(annotationIds);

        if (deleteTexts == null) {
            deleteTexts = connection.prepareStatement("delete from interedition_text where id in "
                    + "(select id from table(id bigint = ?) text)");
        }
        deleteTexts.setObject(1, idArray);
        deleteTexts.executeUpdate();

        txLog.textsRemoved(idArray);
    } catch (SQLException e) {
        throw Throwables.propagate(e);
    } finally {
        Database.closeQuietly(rs);
    }
}