Example usage for java.util Collection toArray

List of usage examples for java.util Collection toArray

Introduction

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

Prototype

Object[] toArray();

Source Link

Document

Returns an array containing all of the elements in this collection.

Usage

From source file:de.kp.ames.web.function.domain.model.JsonProductor.java

/**
 * A helper method to retrieve the transformators
 * from a service object//from   ww w .  j  av  a  2  s  .  c om
 * 
 * @param service
 * @return
 * @throws JAXRException
 * @throws JSONException
 */
private JSONArray getSpecifications(ServiceImpl service) throws JAXRException, JSONException {

    Map<Integer, JSONObject> collector = new TreeMap<Integer, JSONObject>(new Comparator<Integer>() {
        public int compare(Integer seqno1, Integer seqno2) {
            return seqno1.compareTo(seqno2);
        }
    });

    /* 
      * Specifications
      */
    Collection<?> bindings = service.getServiceBindings();
    if ((bindings == null) || (bindings.size() == 0))
        return new JSONArray();

    /*
     * Take the first binding of the respective service into account
     */
    ServiceBindingImpl binding = (ServiceBindingImpl) bindings.toArray()[0];

    /* 
     * Next the specification links of the respective binding are determined
     */
    Collection<?> specs = binding.getSpecificationLinks();
    if ((specs == null) || (specs.size() == 0))
        return new JSONArray();

    Iterator<?> iterator = specs.iterator();
    while (iterator.hasNext()) {

        SpecificationLinkImpl spec = (SpecificationLinkImpl) iterator.next();

        Object[] values = spec.getSlot(JaxrConstants.SLOT_SEQNO).getValues().toArray();
        int seqNo = Integer.parseInt((String) values[0]);

        RegistryObjectImpl ro = (RegistryObjectImpl) spec.getSpecificationObject();

        JSONObject jTransformator = new JSONObject();

        jTransformator.put(JaxrConstants.RIM_SEQNO, (new Integer(seqNo)).toString());

        jTransformator.put(JaxrConstants.RIM_ID, ro.getId());
        String name = jaxrBase.getName(ro);
        /*
         * If no matching locale string exists, get the closest match
         */
        name = (name == "") ? ro.getDisplayName() : name;

        jTransformator.put(JaxrConstants.RIM_NAME, name);

        collector.put(seqNo, jTransformator);

    }

    return new JSONArray(collector.values());

}

From source file:com.anrisoftware.prefdialog.fields.listbox.AbstractListBoxField.java

/**
 * Sets the values as the selected values of the list.
 * //w  w w .  ja v a 2s .com
 * @param values
 *            the {@link Collection} values.
 * 
 * @throws PropertyVetoException
 */
@SuppressWarnings("rawtypes")
public void setValues(Collection values) throws PropertyVetoException {
    Object value = getValue();
    if (value.getClass().isArray()) {
        setValue(values.toArray());
    } else if (value instanceof Collection) {
        setValue(values);
    }
}

From source file:com.espertech.esper.client.scopetest.EPAssertionUtil.java

/**
 * Compare the objects in the expected arrays and actual collection assuming the exact same order.
 * @param expected is the expected values
 * @param actual is the actual values/*from   www.j  a v  a  2  s  .  c o m*/
 */
public static void assertEqualsExactOrder(Object[] expected, Collection actual) {
    Object[] actualArray = null;
    if (actual != null) {
        actualArray = actual.toArray();
    }
    assertEqualsExactOrder(expected, actualArray);
}

From source file:com.github.pjungermann.config.specification.constraint.AbstractConstraint.java

@Nullable
protected ConfigError validateCollection(@NotNull final Config config, @NotNull final CollectionKey key) {
    final Object collectionObject = config.get(key.collectionKey);
    if (collectionObject == null && skipNullValues()) {
        return null;
    }/*from   w w  w  .j  a va2 s.c om*/

    if (!(collectionObject instanceof Collection)) {
        return new NoCollectionError(key, collectionObject);
    }

    final Collection collection = (Collection) config.get(key.collectionKey);
    if (collection.isEmpty()) {
        return null;
    }

    final Object[] array = collection.toArray();

    RangeInfo rangeInfo = key.entrySelection.subListBorders(array.length);
    int from = rangeInfo.from;
    int to = rangeInfo.to;

    // adjust the collection size
    // TODO: use strict mode to create errors here as well? could also be covered by specifying the size
    if (array.length - 1 < from) {
        // no entry to check
        return null;
    }
    if (array.length < to) {
        to = array.length;
    }

    final ArrayList<ConfigError> errors = new ArrayList<>();
    for (int i = from; i < to; i++) {
        ConfigError error;
        Object entry = array[i];
        if (key.propertyKey == null) {
            error = validateValue(config, entry);

        } else if (entry instanceof Config) {
            error = validate(config, key.propertyKey);

        } else if (entry instanceof Map) {
            error = validateValue(config, ((Map) entry).get(key.propertyKey));

        } else {
            error = validateObjectProperty(config, key, entry, key.propertyKey);
        }

        if (error != null) {
            errors.add(error);
        }
    }

    if (errors.isEmpty()) {
        return null;
    }

    return new MultiConfigError(key, errors);
}

From source file:ca.uviccscu.lp.server.main.ShutdownListener.java

@Deprecated
public void releaseLocks() {
    l.trace("Trying to check file locks ");
    try {//from  w  ww.j  a v a  2s  . co m
        Collection c = FileUtils.listFiles(new File(Shared.workingDirectory), null, true);
        Object[] arr = c.toArray();
        for (int i = 0; i < arr.length; i++) {
            l.trace("Trying lock for: " + ((File) arr[i]).getAbsolutePath());
            // Get a file channel for the file
            File file = ((File) arr[i]);
            FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
            // Use the file channel to create a lock on the file.
            // This method blocks until it can retrieve the lock.
            //FileLock lock = channel.lock();
            // Try acquiring the lock without blocking. This method returns
            // null or throws an exception if the file is already locked.
            FileLock lock = null;
            try {
                lock = channel.lock();
            } catch (OverlappingFileLockException ex) {
                l.trace("Lock already exists", ex);
            }
            if (lock == null) {
                l.trace("Lock failed - someone else holds lock");
            } else {
                l.trace("Lock shared: " + lock.isShared() + " Lock valid: " + lock.isValid());
                lock.release();
                l.trace("Lock release OK");
                try {
                    if (!file.delete()) {
                        throw new IOException();
                    }
                } catch (Exception e) {
                    l.trace("Delete failed", e);
                }
            }
        }
        //Thread.sleep(25000);

    } catch (Exception e) {
        // File is already locked in this thread or virtual machine
        l.trace("File lock problem", e);
    }
}

From source file:com.sfs.whichdoctor.beans.WhichDoctorCoreIdentityBean.java

/**
 * Sets the address./*from   w w w  .  j a va  2 s .  c  o  m*/
 *
 * @param addressesVal the new address
 */
public final void setAddress(final Collection<AddressBean> addressesVal) {
    if (addressesVal != null && addressesVal.size() > 0) {
        Object[] addressArray = addressesVal.toArray();
        this.primaryAddress = (AddressBean) addressArray[0];
    }
    this.addresses = addressesVal;
}

From source file:com.sfs.whichdoctor.beans.WhichDoctorCoreIdentityBean.java

/**
 * Sets the phone./*  w ww.j a  v  a2 s  .  c om*/
 *
 * @param phoneNumbersVal the new phone
 */
public final void setPhone(final Collection<PhoneBean> phoneNumbersVal) {
    if (phoneNumbersVal != null && phoneNumbersVal.size() > 0) {
        Object[] phoneArray = phoneNumbersVal.toArray();
        this.primaryPhone = (PhoneBean) phoneArray[0];
    }
    this.phoneNumbers = phoneNumbersVal;
}

From source file:com.example.office365sample.MainActivity.java

private void updateList(final List<IMessage> messages) {
    runOnUiThread(new Runnable() {
        public void run() {
            try {
                ArrayAdapter<IMessage> adapter = new ArrayAdapter<IMessage>(MainActivity.this,
                        android.R.layout.simple_list_item_activated_2, android.R.id.text1, messages) {
                    @Override/*  www  .j  av  a2s.  c  om*/
                    public View getView(int position, View convertView, ViewGroup parent) {
                        View view = super.getView(position, convertView, parent);
                        TextView text1 = (TextView) view.findViewById(android.R.id.text1);
                        TextView text2 = (TextView) view.findViewById(android.R.id.text2);

                        // get list of recipients and just display first one
                        Collection<Recipient> recipients = messages.get(position).getToRecipients();
                        if (recipients != null && recipients.size() > 0) {
                            Recipient first = ((Recipient) recipients.toArray()[0]);
                            String recipientEmail = first.getAddress();
                            text1.setText("To: " + recipientEmail);
                        } else {
                            text1.setText("<no recipients>");
                        }

                        // show subject
                        text2.setText("Subject: " + messages.get(position).getSubject());
                        return view;
                    }
                };

                listViewMessages.setAdapter(adapter);
                if (!adapter.isEmpty()) {
                    btnSendMessage.setEnabled(true);
                } else {
                    btnSendMessage.setEnabled(false);
                }
            } catch (Exception e) {
                Log.e(TAG, "error", e);
            }
        }
    });
}

From source file:gov.nih.nci.rembrandt.web.taglib.HCPlotReport.java

public StringBuffer quickReporterReport(List<String> reporters, ArrayPlatformType arrayPlatform) {
    StringBuffer html = new StringBuffer();
    Document document = DocumentHelper.createDocument();
    Element table = document.addElement("table").addAttribute("id", "reportTable").addAttribute("class",
            "report");
    Element tr = null;/*from w ww . j  a  v  a  2s .  c  o  m*/
    Element td = null;

    tr = table.addElement("tr").addAttribute("class", "header");
    td = tr.addElement("td").addAttribute("class", "header").addText("Reporter");
    td = tr.addElement("td").addAttribute("class", "header").addText("Gene Symbol");
    td = tr.addElement("td").addAttribute("class", "header").addText("GenBank AccId");
    td = tr.addElement("td").addAttribute("class", "header").addText("LocusLink");

    if (reporters != null) {
        try {
            Map reporterResultsetMap = AnnotationHandler.getAllAnnotationsFor(reporters, arrayPlatform);
            for (String reporterId : reporters) {
                if (reporterResultsetMap != null) {
                    ReporterAnnotations ra = (ReporterAnnotations) reporterResultsetMap.get(reporterId);
                    tr = table.addElement("tr").addAttribute("class", "data");

                    String reporter = ra.getReporterName() != null ? ra.getReporterName() : "N/A";

                    td = tr.addElement("td").addText(reporter);
                    //html.append("ReporterID :" +reporterResultset.getReporter().getValue().toString() + "<br/>");
                    String geneSymbols = ra.getGeneSymbol();
                    String genes = "";
                    if (geneSymbols != null)
                        genes = geneSymbols;

                    td = tr.addElement("td").addText(genes);

                    Collection genBank_AccIDS = ra.getAccessions();
                    String accs = "";
                    if (genBank_AccIDS != null) {
                        accs = StringUtils.join(genBank_AccIDS.toArray(), ",");
                    }

                    td = tr.addElement("td").addText(accs);

                    Collection locusLinkIDs = ra.getLocusLinks();
                    String ll = "";
                    if (locusLinkIDs != null) {
                        ll = StringUtils.join(locusLinkIDs.toArray(), ",");
                    }

                    td = tr.addElement("td").addText(ll);

                    /*
                    Collection<String> goIds = (Collection<String>)reporterResultset.getAssociatedGOIds();
                    if(goIds != null){
                       for(String goId: goIds){
                          html.append("Associtaed GO Id :" +goId + "<br/>");
                       }
                    }
                    Collection<String> pathways = (Collection<String>)reporterResultset.getAssociatedPathways();
                    if(pathways != null){
                       for(String pathway: pathways){
                          html.append("Associated Pathway :" +pathway + "<br/>");
                       }
                    }
                    */
                }
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    //return html;
    return html.append(document.asXML());
}

From source file:org.ambraproject.admin.flags.service.FlagServiceTest.java

@Test
public void testGetFlaggedComments() {
    //make sure there aren't any other flags in the db stored by other tests
    dummyDataStore.deleteAll(Flag.class);

    //set up data
    UserProfile commentCreator = new UserProfile("id:creatorForFlagManagementServiceTest",
            "email@FlagManagementServiceTest.org", "displaynameForFlagManagementServiceTest");
    dummyDataStore.store(commentCreator);

    UserProfile flagCreator = new UserProfile("flagCreatorForFlagManagementServiceTest",
            "flagCreator@FlagManagementServiceTest.org", "flagCreatorForFlagManagementServiceTest");
    dummyDataStore.store(flagCreator);/*from  w  w w. j  ava 2 s .co  m*/

    Annotation comment = new Annotation(commentCreator, AnnotationType.COMMENT, 123l);
    comment.setTitle("test title for flagManagementServiceTest");
    dummyDataStore.store(comment);

    Annotation reply = new Annotation(commentCreator, AnnotationType.REPLY, 123l);
    reply.setTitle("test title for reply on flagManagementServiceTest");
    dummyDataStore.store(reply);

    Annotation correction = new Annotation(commentCreator, AnnotationType.MINOR_CORRECTION, 123l);
    correction.setTitle("test title for minorCorrection on flagManagementServiceTest");
    dummyDataStore.store(correction);

    Calendar lastYear = Calendar.getInstance();
    lastYear.add(Calendar.YEAR, -1);

    Calendar lastMonth = Calendar.getInstance();
    lastMonth.add(Calendar.MONTH, -1);

    Flag firstFlag = new Flag(flagCreator, FlagReasonCode.SPAM, comment);
    firstFlag.setComment("Spamalot");
    firstFlag.setCreated(lastYear.getTime());
    dummyDataStore.store(firstFlag);

    Flag secondFlag = new Flag(flagCreator, FlagReasonCode.INAPPROPRIATE, reply);
    secondFlag.setComment("inappropriate");
    secondFlag.setCreated(lastMonth.getTime());
    dummyDataStore.store(secondFlag);

    Flag thirdFlag = new Flag(flagCreator, FlagReasonCode.SPAM, correction);
    thirdFlag.setComment("More spam");
    dummyDataStore.store(thirdFlag);

    //call the service method
    Collection<FlagView> list = flagService.getFlaggedComments();

    assertNotNull(list, "returned null list of flagged comments");
    assertEquals(list.toArray(),
            new Object[] { new FlagView(firstFlag), new FlagView(secondFlag), new FlagView(thirdFlag) },
            "Incorrect flags");

}