Example usage for java.util Set toArray

List of usage examples for java.util Set toArray

Introduction

In this page you can find the example usage for java.util Set toArray.

Prototype

<T> T[] toArray(T[] a);

Source Link

Document

Returns an array containing all of the elements in this set; the runtime type of the returned array is that of the specified array.

Usage

From source file:org.thevortex.lighting.jinks.client.PubNubServiceNotifier.java

/**
 * Sets up client and subscribes to channels.
 *
 * @param serviceSubscription service level
 * @param itemSubscriptions   all the bits
 *///from   w ww  .  j a v  a2 s.  c  o m
synchronized void init(Subscription serviceSubscription, Set<Subscription> itemSubscriptions) {
    // if nothing's changed and already running, ignore this
    if (pnClient != null && Objects.equals(this.serviceSubscription, serviceSubscription)
            && Objects.equals(this.itemSubscriptions, itemSubscriptions)) {
        logger.debug("Client for {} already initialized.", serviceType);
        return;
    }

    close();
    this.serviceSubscription = serviceSubscription;
    this.itemSubscriptions = itemSubscriptions;

    logger.info("Starting notification client for {}", serviceType);
    // subscribe with appropriate call-backs
    if (start()) {
        try {
            // over-all service listening
            if (serviceSubscription == null) {
                logger.warn("No type subscriptions for {}", serviceType);
            } else {
                String serviceChannel = serviceSubscription.getPubnub().getChannel();
                logger.debug("Subscribing to {}", serviceChannel);
                pnClient.subscribe(serviceChannel, typeCallback);
            }

            // item subscriptions
            if (itemSubscriptions == null || itemSubscriptions.isEmpty()) {
                logger.warn("No item subscriptions for {}", serviceType);
            } else {
                Set<String> itemChannels = itemSubscriptions.stream()
                        .map(subscription -> subscription.getPubnub().getChannel()).collect(Collectors.toSet());

                String[] channels = itemChannels.toArray(new String[itemChannels.size()]);
                logger.debug("Subscribing to {}", itemChannels);
                pnClient.subscribe(channels, itemCallback);
            }
        } catch (Exception e) {
            close();
            throw new SubscriptionException("Cannot subscribe to channels", e);
        }
    }
}

From source file:io.cloudslang.runtime.impl.java.JavaExecutor.java

JavaExecutor(Set<String> filePaths) {
    logger.info("Creating java classloader with [" + filePaths.size() + "] dependencies [" + filePaths + "]");
    if (!filePaths.isEmpty()) {
        Set<URL> result = Sets.newHashSet();
        for (String filePath : filePaths) {
            try {
                result.add(new File(filePath).toURI().toURL());
            } catch (MalformedURLException e) {
                logger.error("Failed to add to the classloader path [" + filePath + "]", e);
            }/*w ww  .j  a  v a  2s.  c  om*/
        }
        classLoader = new URLClassLoader(result.toArray(new URL[result.size()]), PARENT_CLASS_LOADER);
    } else {
        // no dependencies - use application classloader
        classLoader = getClass().getClassLoader();
    }
}

From source file:com.bstek.dorado.core.io.SpringResourceLoaderAdapter.java

public Resource[] getResources(String locationPattern) throws IOException {
    Set<Resource> resourceSet = new LinkedHashSet<Resource>();
    String[] patterns = locationPattern.split(LOCATION_SEPARATOR);
    for (String pattern : patterns) {
        if (StringUtils.isNotBlank(pattern)) {
            pattern = transformLocation(pattern);
            resourceSet.addAll(getResourcesBySinglePattern(pattern));
        }//from   w ww  . java  2s.  c om
    }

    Resource[] resources = new Resource[resourceSet.size()];
    resourceSet.toArray(resources);
    return resources;
}

From source file:com.espertech.esper.dataflow.ops.BeaconSource.java

public DataFlowOpInitializeResult initialize(DataFlowOpInitializateContext context) throws Exception {
    initialDelayMSec = (long) (initialDelay * 1000);
    periodDelayMSec = (long) (interval * 1000);

    if (context.getOutputPorts().size() != 1) {
        throw new IllegalArgumentException("BeaconSource operator requires one output stream but produces "
                + context.getOutputPorts().size() + " streams");
    }//from w ww  .j  av a  2 s . c om

    // Check if a type is declared
    DataFlowOpOutputPort port = context.getOutputPorts().get(0);
    if (port.getOptionalDeclaredType() != null && port.getOptionalDeclaredType().getEventType() != null) {
        EventType outputEventType = port.getOptionalDeclaredType().getEventType();
        produceEventBean = port.getOptionalDeclaredType() != null
                && !port.getOptionalDeclaredType().isUnderlying();

        // compile properties to populate
        Set<String> props = allProperties.keySet();
        props.removeAll(PARAMETER_PROPERTIES);
        WriteablePropertyDescriptor[] writables = setupProperties(props.toArray(new String[props.size()]),
                outputEventType, context.getStatementContext());
        manufacturer = context.getServicesContext().getEventAdapterService().getManufacturer(outputEventType,
                writables, context.getServicesContext().getEngineImportService(), false);

        int index = 0;
        evaluators = new ExprEvaluator[writables.length];
        for (WriteablePropertyDescriptor writeable : writables) {

            final Object providedProperty = allProperties.get(writeable.getPropertyName());
            if (providedProperty instanceof ExprNode) {
                ExprNode exprNode = (ExprNode) providedProperty;
                ExprNode validated = ExprNodeUtility.validateSimpleGetSubtree(exprNode,
                        context.getStatementContext(), null);
                final ExprEvaluator exprEvaluator = validated.getExprEvaluator();
                final TypeWidener widener = TypeWidenerFactory.getCheckPropertyAssignType(
                        validated.toExpressionString(), exprEvaluator.getType(), writeable.getType(),
                        writeable.getPropertyName());
                if (widener != null) {
                    evaluators[index] = new ExprEvaluator() {
                        public Object evaluate(EventBean[] eventsPerStream, boolean isNewData,
                                ExprEvaluatorContext context) {
                            Object value = exprEvaluator.evaluate(eventsPerStream, isNewData, context);
                            return widener.widen(value);
                        }

                        public Class getType() {
                            return null;
                        }
                    };
                } else {
                    evaluators[index] = exprEvaluator;
                }
            } else if (providedProperty == null) {
                evaluators[index] = new ExprEvaluator() {
                    public Object evaluate(EventBean[] eventsPerStream, boolean isNewData,
                            ExprEvaluatorContext context) {
                        return null;
                    }

                    public Class getType() {
                        return null;
                    }
                };
            } else {
                evaluators[index] = new ExprEvaluator() {
                    public Object evaluate(EventBean[] eventsPerStream, boolean isNewData,
                            ExprEvaluatorContext context) {
                        return providedProperty;
                    }

                    public Class getType() {
                        return providedProperty.getClass();
                    }
                };
            }
            index++;
        }

        return null; // no changing types
    }

    // No type has been declared, we can create one
    String anonymousTypeName = context.getDataflowName() + "-beacon";
    Map<String, Object> types = new LinkedHashMap<String, Object>();
    Set<String> props = allProperties.keySet();
    props.removeAll(PARAMETER_PROPERTIES);

    int count = 0;
    evaluators = new ExprEvaluator[props.size()];
    for (String propertyName : props) {
        ExprNode exprNode = (ExprNode) allProperties.get(propertyName);
        ExprNode validated = ExprNodeUtility.validateSimpleGetSubtree(exprNode, context.getStatementContext(),
                null);
        final Object value = validated.getExprEvaluator().evaluate(null, true,
                context.getAgentInstanceContext());
        if (value == null) {
            types.put(propertyName, null);
        } else {
            types.put(propertyName, value.getClass());
        }
        evaluators[count] = new ExprEvaluator() {
            public Object evaluate(EventBean[] eventsPerStream, boolean isNewData,
                    ExprEvaluatorContext context) {
                return value;
            }

            public Class getType() {
                return null;
            }
        };
        count++;
    }

    EventType type = context.getServicesContext().getEventAdapterService()
            .createAnonymousObjectArrayType(anonymousTypeName, types);
    return new DataFlowOpInitializeResult(new GraphTypeDesc[] { new GraphTypeDesc(false, true, type) });
}

From source file:net.solarnetwork.node.power.enasolar.ws.EnaSolarXMLDatumDataSource.java

/**
 * Set the URL list as a comma-delimited string.
 * /*from   w ww.  j  av a  2  s.c o  m*/
 * @param list
 *        the comma-delimited list of URLs
 */
public void setUrlList(String list) {
    Set<String> set = StringUtils.delimitedStringToSet(list, ",");
    setUrls(set.toArray(new String[set.size()]));
}

From source file:hoot.services.controllers.osm.OSMTestUtils.java

private static void verifyTestNodesUnmodified(Set<Long> nodeIds, long changesetId, BoundingBox originalBounds,
        boolean verifyTags) {

    Long[] nodeIdsArr = nodeIds.toArray(new Long[nodeIds.size()]);
    Map<Long, CurrentNodes> nodes = createQuery(getMapId()).from(currentNodes)
            .where((currentNodes.changesetId.eq(changesetId)))
            .transform(groupBy(currentNodes.id).as(currentNodes));

    assertEquals(5, nodes.size());//from   ww  w  . java2 s  .c  o m

    CurrentNodes nodeRecord = nodes.get(nodeIdsArr[0]);
    assertEquals(new Long(changesetId), nodeRecord.getChangesetId());
    assertEquals(new Double(originalBounds.getMinLat()), nodeRecord.getLatitude());
    assertEquals(new Double(originalBounds.getMinLon()), nodeRecord.getLongitude());
    assertEquals(nodeIdsArr[0], nodeRecord.getId());
    assertEquals(new Long(1), nodeRecord.getVersion());

    if (verifyTags) {
        Map<String, String> tags = PostgresUtils.postgresObjToHStore(nodeRecord.getTags());
        assertEquals(2, tags.size());
        // System.out.println(tags.get("key 1"));
        assertEquals("val 1", tags.get("key 1"));
        // System.out.println(tags.get("key 2"));
        assertEquals("val 2", tags.get("key 2"));
    }

    nodeRecord = nodes.get(nodeIdsArr[1]);
    assertEquals(new Long(changesetId), nodeRecord.getChangesetId());
    assertEquals(new Double(originalBounds.getMaxLat()), nodeRecord.getLatitude());
    assertEquals(new Double(originalBounds.getMaxLon()), nodeRecord.getLongitude());
    assertEquals(nodeIdsArr[1], nodeRecord.getId());
    assertEquals(new Long(1), nodeRecord.getVersion());
    if (verifyTags) {
        assertTrue((nodeRecord.getTags() == null)
                || PostgresUtils.postgresObjToHStore(nodeRecord.getTags()).isEmpty());
    }

    nodeRecord = nodes.get(nodeIdsArr[2]);
    assertEquals(new Long(changesetId), nodeRecord.getChangesetId());
    assertEquals(new Double(originalBounds.getMinLat()), nodeRecord.getLatitude());
    assertEquals(new Double(originalBounds.getMinLon()), nodeRecord.getLongitude());
    assertEquals(nodeIdsArr[2], nodeRecord.getId());
    assertEquals(new Long(1), nodeRecord.getVersion());
    if (verifyTags) {
        assertTrue((nodeRecord.getTags() == null)
                || PostgresUtils.postgresObjToHStore(nodeRecord.getTags()).isEmpty());
    }

    nodeRecord = nodes.get(nodeIdsArr[3]);
    assertEquals(new Long(changesetId), nodeRecord.getChangesetId());
    assertEquals(new Double(originalBounds.getMinLat()), nodeRecord.getLatitude());
    assertEquals(new Double(originalBounds.getMinLon()), nodeRecord.getLongitude());
    assertEquals(nodeIdsArr[3], nodeRecord.getId());
    assertEquals(new Long(1), nodeRecord.getVersion());
    if (verifyTags) {
        Map<String, String> tags = PostgresUtils.postgresObjToHStore(nodeRecord.getTags());
        assertEquals(1, tags.size());
        assertEquals("val 3", tags.get("key 3"));
    }

    nodeRecord = nodes.get(nodeIdsArr[4]);
    assertEquals(new Long(changesetId), nodeRecord.getChangesetId());
    assertEquals(new Double(originalBounds.getMinLat()), nodeRecord.getLatitude());
    assertEquals(new Double(originalBounds.getMinLon()), nodeRecord.getLongitude());
    assertEquals(nodeIdsArr[4], nodeRecord.getId());
    assertEquals(new Long(1), nodeRecord.getVersion());
    if (verifyTags) {
        Map<String, String> tags = PostgresUtils.postgresObjToHStore(nodeRecord.getTags());
        assertEquals(1, tags.size());
        assertEquals("val 4", tags.get("key 4"));
    }
}

From source file:org.jax.bham.test.HaplotypeAssociationTestGraphPanel.java

private List<JComponent> createContextMenuItems() {
    List<JComponent> menuItems = new ArrayList<JComponent>();

    // TODO is getSelectedIntervals thread safe here? probably not
    int[] chromosomes = this.getSelectedChromosomes();
    if (this.lastClickedIntervalIndex >= 0 && chromosomes.length == 1) {
        RealValuedBasePairInterval[] selectedIntervals = this.chromosomeToNegLogValueMap.get(chromosomes[0]);
        RealValuedBasePairInterval selectedInterval = selectedIntervals[this.lastClickedIntervalIndex];
        menuItems.add(new JMenuItem(new GoToMouseIntervalInCGDSnpDatabaseAction(selectedInterval,
                BhamApplication.getInstance().getBhamFrame())));
        menuItems.add(new JMenuItem(new GoToMouseIntervalInCGDGBrowseAction(selectedInterval,
                BhamApplication.getInstance().getBhamFrame())));
        menuItems.add(new JMenuItem(new GoToMouseIntervalInUCSCBrowserAction(selectedInterval,
                BhamApplication.getInstance().getBhamFrame())));
        menuItems.add(new JSeparator());

        if (selectedInterval instanceof CompositeRealValuedBasePairInterval) {
            CompositeRealValuedBasePairInterval selectedCompositeInterval = (CompositeRealValuedBasePairInterval) selectedInterval;
            if (selectedCompositeInterval.getDelegateInterval() instanceof BinaryStrainPartition) {
                BinaryStrainPartition partition = (BinaryStrainPartition) selectedCompositeInterval
                        .getDelegateInterval();
                Set<String> strains = this.testToPlot.getCommonStrains();
                String[] sortedStrains = strains.toArray(new String[strains.size()]);
                Arrays.sort(sortedStrains);

                Set<String> inStrains = new HashSet<String>();
                Set<String> outStrains = new HashSet<String>();
                Map<String, Set<String>> strainGroups = new HashMap<String, Set<String>>();
                strainGroups.put("Strains Inside Haplotype Block", inStrains);
                strainGroups.put("Strains Outside Haplotype Block", outStrains);

                BitSet bits = partition.getStrainBitSet();
                for (int i = 0; i < sortedStrains.length; i++) {
                    if (bits.get(i)) {
                        inStrains.add(sortedStrains[i]);
                    } else {
                        outStrains.add(sortedStrains[i]);
                    }/* w  w  w.j  a v  a 2s.  com*/
                }

                menuItems.add(new JMenuItem(new ShowPhenotypeEffectPlotAction(
                        this.testToPlot.getPhenotypeDataSource(), strainGroups)));
                menuItems.add(new JSeparator());
            }
        }
    }

    return menuItems;
}

From source file:com.threewks.thundr.gmail.GmailMailer.java

private MimeMessage createMime(String bodyText, String subject, Map<String, String> to, List<Attachment> pdfs)
        throws MessagingException {
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);
    MimeMessage email = new MimeMessage(session);
    Set<InternetAddress> toAddresses = getInternetAddresses(to);

    if (!toAddresses.isEmpty()) {
        email.addRecipients(javax.mail.Message.RecipientType.TO,
                toAddresses.toArray(new InternetAddress[to.size()]));
    }/* w w w . j  ava 2  s .c om*/

    email.setSubject(subject);

    MimeBodyPart mimeBodyPart = new MimeBodyPart();
    mimeBodyPart.setContent(bodyText, "text/html");
    mimeBodyPart.setHeader("Content-Type", "text/html; charset=\"UTF-8\"");

    Multipart multipart = new MimeMultipart();
    for (Attachment attachmentPdf : pdfs) {
        MimeBodyPart attachment = new MimeBodyPart();
        DataSource source = new ByteArrayDataSource(attachmentPdf.getData(), "application/pdf");
        attachment.setDataHandler(new DataHandler(source));
        attachment.setFileName(attachmentPdf.getFileName());
        multipart.addBodyPart(mimeBodyPart);
        multipart.addBodyPart(attachment);
    }
    email.setContent(multipart);
    return email;
}

From source file:org.openvpms.component.business.service.security.ArchetypeAwareVoter.java

/**
 * Examine the method and return the archetype short names.
 *
 * @param method the method to examine.//from   w ww.ja  va 2  s.c  o  m
 * @return the archetype short names or null
 */
@SuppressWarnings("unchecked")
private String[] getArchetypeShortNames(MethodInvocation method) {
    String[] result = {};

    if (method != null) {
        String methodName = method.getMethod().getName();
        Class declaring = method.getMethod().getDeclaringClass();
        if (declaring.getName().equals(IArchetypeService.class.getName())) {
            Object arg = method.getArguments()[0];
            if (methodName.equals("create")) {
                if (arg instanceof String) {
                    result = new String[] { (String) arg };
                } else {
                    result = new String[] { ((ArchetypeId) arg).getShortName() };
                }
            } else if (methodName.equals("save")) {
                if (arg instanceof IMObject) {
                    ArchetypeId id = ((IMObject) arg).getArchetypeId();
                    result = new String[] { id.getShortName() };
                } else {
                    Collection<IMObject> objects = (Collection<IMObject>) arg;
                    Set<String> shortNames = new HashSet<String>();
                    for (IMObject object : objects) {
                        ArchetypeId id = object.getArchetypeId();
                        shortNames.add(id.getShortName());
                    }
                    result = shortNames.toArray(new String[shortNames.size()]);
                }
            } else if (methodName.equals("remove")) {
                ArchetypeId id = ((IMObject) arg).getArchetypeId();
                result = new String[] { id.getShortName() };
            } else {
                // we need to handle the other methods here
            }
        }
    }

    return result;
}

From source file:hudson.security.GlobalMatrixAuthorizationStrategy.java

/**
 * Returns all SIDs configured in this matrix, minus "anonymous"
 *
 * @return/*from  ww  w .j a  v a2  s.c o m*/
 *      Always non-null.
 */
public List<String> getAllSIDs() {
    Set<String> r = new HashSet<String>();
    for (Set<String> set : grantedPermissions.values())
        r.addAll(set);
    r.remove("anonymous");

    String[] data = r.toArray(new String[r.size()]);
    Arrays.sort(data);
    return Arrays.asList(data);
}