List of usage examples for java.util Collection clear
void clear();
From source file:com.datatorrent.lib.dedup.Deduper.java
@Override @SuppressWarnings({ "BroadCatchBlock", "TooBroadCatch", "UseSpecificCatch" }) public Collection<Partition<Deduper<INPUT, OUTPUT>>> definePartitions( Collection<Partition<Deduper<INPUT, OUTPUT>>> partitions, PartitioningContext context) { final int finalCapacity = DefaultPartition.getRequiredPartitionCount(context, this.partitionCount); //Collect the state here List<BucketManager<INPUT>> oldStorageManagers = Lists.newArrayList(); Map<Long, List<INPUT>> allWaitingEvents = Maps.newHashMap(); for (Partition<Deduper<INPUT, OUTPUT>> partition : partitions) { //collect all bucketStorageManagers oldStorageManagers.add(partition.getPartitionedInstance().bucketManager); //collect all waiting events for (Map.Entry<Long, List<INPUT>> awaitingList : partition.getPartitionedInstance().waitingEvents .entrySet()) {//from w ww . ja v a 2 s .c o m if (awaitingList.getValue().size() > 0) { List<INPUT> existingList = allWaitingEvents.get(awaitingList.getKey()); if (existingList == null) { existingList = Lists.newArrayList(); allWaitingEvents.put(awaitingList.getKey(), existingList); } existingList.addAll(awaitingList.getValue()); } } partition.getPartitionedInstance().waitingEvents.clear(); } partitions.clear(); Collection<Partition<Deduper<INPUT, OUTPUT>>> newPartitions = Lists.newArrayListWithCapacity(finalCapacity); Map<Integer, BucketManager<INPUT>> partitionKeyToStorageManagers = Maps.newHashMap(); for (int i = 0; i < finalCapacity; i++) { try { @SuppressWarnings("unchecked") Deduper<INPUT, OUTPUT> deduper = this.getClass().newInstance(); DefaultPartition<Deduper<INPUT, OUTPUT>> partition = new DefaultPartition<Deduper<INPUT, OUTPUT>>( deduper); newPartitions.add(partition); } catch (Throwable cause) { DTThrowable.rethrow(cause); } } DefaultPartition.assignPartitionKeys(Collections.unmodifiableCollection(newPartitions), input); int lPartitionMask = newPartitions.iterator().next().getPartitionKeys().get(input).mask; //transfer the state here for (Partition<Deduper<INPUT, OUTPUT>> deduperPartition : newPartitions) { Deduper<INPUT, OUTPUT> deduperInstance = deduperPartition.getPartitionedInstance(); deduperInstance.partitionKeys = deduperPartition.getPartitionKeys().get(input).partitions; deduperInstance.partitionMask = lPartitionMask; logger.debug("partitions {},{}", deduperInstance.partitionKeys, deduperInstance.partitionMask); deduperInstance.bucketManager = bucketManager.cloneWithProperties(); for (int partitionKey : deduperInstance.partitionKeys) { partitionKeyToStorageManagers.put(partitionKey, deduperInstance.bucketManager); } //distribute waiting events for (long bucketKey : allWaitingEvents.keySet()) { for (Iterator<INPUT> iterator = allWaitingEvents.get(bucketKey).iterator(); iterator.hasNext();) { INPUT event = iterator.next(); int partitionKey = event.getEventKey().hashCode() & lPartitionMask; if (deduperInstance.partitionKeys.contains(partitionKey)) { List<INPUT> existingList = deduperInstance.waitingEvents.get(bucketKey); if (existingList == null) { existingList = Lists.newArrayList(); deduperInstance.waitingEvents.put(bucketKey, existingList); } existingList.add(event); iterator.remove(); } } } } //let storage manager and subclasses distribute state as well bucketManager.definePartitions(oldStorageManagers, partitionKeyToStorageManagers, lPartitionMask); return newPartitions; }
From source file:com.evolveum.midpoint.repo.sql.ModifyTest.java
@Test public void test032ModifyTaskObjectRef() throws Exception { OperationResult result = new OperationResult("MODIFY"); File taskFile = new File(TEST_DIR, "task.xml"); System.out.println("ADD"); PrismObject<TaskType> task = prismContext.parseObject(taskFile); repositoryService.addObject(task, null, result); final String taskOid = "00000000-0000-0000-0000-123450000001"; AssertJUnit.assertNotNull(taskOid);// w w w . j a v a 2s .c o m System.out.println("GET"); PrismObject<TaskType> getTask = null; getTask = repositoryService.getObject(TaskType.class, taskOid, null, result); String lastVersion = getTask.getVersion(); AssertJUnit.assertTrue(task.equivalent(getTask)); TaskType taskType = null; taskType = getTask.asObjectable(); AssertJUnit.assertNull(taskType.getObjectRef()); Collection modifications = new ArrayList(); PrismObjectDefinition objectDef = prismContext.getSchemaRegistry() .findObjectDefinitionByCompileTimeClass(TaskType.class); PrismReferenceDefinition def = objectDef.findReferenceDefinition(TaskType.F_OBJECT_REF); System.out.println("MODIFY"); ObjectReferenceType objectRef = null; ReferenceDelta delta = new ReferenceDelta(def, prismContext); delta.addValueToAdd(new PrismReferenceValue("1", ResourceType.COMPLEX_TYPE)); modifications.add(delta); repositoryService.modifyObject(TaskType.class, taskOid, modifications, result); System.out.println("GET"); getTask = repositoryService.getObject(TaskType.class, taskOid, null, result); taskType = getTask.asObjectable(); AssertJUnit.assertNotNull(taskType.getObjectRef()); objectRef = taskType.getObjectRef(); AssertJUnit.assertEquals("1", objectRef.getOid()); SqlRepoTestUtil.assertVersionProgress(lastVersion, getTask.getVersion()); lastVersion = getTask.getVersion(); checkReference(taskOid); System.out.println("MODIFY"); modifications.clear(); delta = new ReferenceDelta(def, prismContext); delta.addValueToDelete(new PrismReferenceValue("1", ResourceType.COMPLEX_TYPE)); delta.addValueToAdd(new PrismReferenceValue("2", ResourceType.COMPLEX_TYPE)); modifications.add(delta); repositoryService.modifyObject(TaskType.class, taskOid, modifications, result); checkReference(taskOid); getTask = repositoryService.getObject(TaskType.class, taskOid, null, result); taskType = getTask.asObjectable(); AssertJUnit.assertNotNull(taskType.getObjectRef()); objectRef = taskType.getObjectRef(); AssertJUnit.assertEquals("2", objectRef.getOid()); LOGGER.info(PrismTestUtil.serializeObjectToString(taskType.asPrismObject())); SqlRepoTestUtil.assertVersionProgress(lastVersion, getTask.getVersion()); lastVersion = getTask.getVersion(); modifications.clear(); delta = new ReferenceDelta(def, prismContext); delta.addValueToDelete(new PrismReferenceValue("2", ResourceType.COMPLEX_TYPE)); delta.addValueToAdd(new PrismReferenceValue("1", ResourceType.COMPLEX_TYPE)); modifications.add(delta); repositoryService.modifyObject(TaskType.class, taskOid, modifications, result); checkReference(taskOid); getTask = repositoryService.getObject(TaskType.class, taskOid, null, result); taskType = getTask.asObjectable(); AssertJUnit.assertNotNull(taskType.getObjectRef()); objectRef = taskType.getObjectRef(); AssertJUnit.assertEquals("1", objectRef.getOid()); SqlRepoTestUtil.assertVersionProgress(lastVersion, getTask.getVersion()); lastVersion = getTask.getVersion(); }
From source file:storm.mesos.schedulers.StormSchedulerImpl.java
private List<MesosWorkerSlot> getMesosWorkerSlots(Map<String, AggregatedOffers> aggregatedOffersPerNode, Collection<String> nodesWithExistingSupervisors, TopologyDetails topologyDetails) { double requestedWorkerCpu = MesosCommon.topologyWorkerCpu(mesosStormConf, topologyDetails); double requestedWorkerMem = MesosCommon.topologyWorkerMem(mesosStormConf, topologyDetails); int requestedWorkerMemInt = (int) requestedWorkerMem; List<MesosWorkerSlot> mesosWorkerSlots = new ArrayList<>(); boolean slotFound = false; int slotsNeeded = topologyDetails.getNumWorkers(); /* XXX(erikdw): For now we clear out our knowledge of pre-existing supervisors while searching for slots * for this topology, to make the behavior of allSlotsAvailableForScheduling() mimic that of assignSlots(). *//w w w . java 2s . co m * See this issue: https://github.com/mesos/storm/issues/160 * * Until that issue is fixed, we must not discount the resources used by pre-existing supervisors. * Otherwise we will under-represent the resources needed as compared to what the more ignorant * assignSlots() will believe is needed, and thus may prevent MesosWorkerSlots from actually being * used. i.e., assignSlots() doesn't know if supervisors already exist, since it doesn't receive the * existingSupervisors input parameter that allSlotsAvailableForScheduling() does. */ nodesWithExistingSupervisors.clear(); do { slotFound = false; List<String> hostsWithOffers = new ArrayList<String>(aggregatedOffersPerNode.keySet()); Collections.shuffle(hostsWithOffers); for (String currentNode : hostsWithOffers) { AggregatedOffers aggregatedOffers = aggregatedOffersPerNode.get(currentNode); boolean supervisorExists = nodesWithExistingSupervisors.contains(currentNode); if (!aggregatedOffers.isFit(mesosStormConf, topologyDetails, supervisorExists)) { if (!supervisorExists) { log.info( "{} with requestedWorkerCpu {} and requestedWorkerMem {} plus the requirements to launch a supervisor does not fit onto {} with resources {}", topologyDetails.getId(), requestedWorkerCpu, requestedWorkerMemInt, aggregatedOffers.getHostname(), aggregatedOffers.toString()); } else { log.info( "{} with requestedWorkerCpu {} and requestedWorkerMem {} does not fit onto {} with resources {}", topologyDetails.getId(), requestedWorkerCpu, requestedWorkerMemInt, aggregatedOffers.getHostname(), aggregatedOffers.toString()); } continue; } log.info( "{} with requestedWorkerCpu {} and requestedWorkerMem {} does fit onto {} with resources {}", topologyDetails.getId(), requestedWorkerCpu, requestedWorkerMemInt, aggregatedOffers.getHostname(), aggregatedOffers.toString()); MesosWorkerSlot mesosWorkerSlot; try { mesosWorkerSlot = SchedulerUtils.createMesosWorkerSlot(mesosStormConf, aggregatedOffers, topologyDetails, supervisorExists); } catch (ResourceNotAvailableException rexp) { log.warn(rexp.getMessage()); continue; } nodesWithExistingSupervisors.add(currentNode); mesosWorkerSlots.add(mesosWorkerSlot); slotFound = true; if (--slotsNeeded == 0) { break; } } } while (slotFound && slotsNeeded > 0); return mesosWorkerSlots; }
From source file:ubic.gemma.persistence.service.expression.arrayDesign.ArrayDesignDaoImpl.java
@Override public ArrayDesign thaw(final ArrayDesign arrayDesign) { if (arrayDesign.getId() == null) { throw new IllegalArgumentException("Cannot thaw a non-persistent array design"); }//from w ww . jav a 2s.c o m /* * Thaw basic stuff */ StopWatch timer = new StopWatch(); timer.start(); ArrayDesign result = this.thawLite(arrayDesign); if (timer.getTime() > 1000) { AbstractDao.log.info("Thaw array design stage 1: " + timer.getTime() + "ms"); } timer.stop(); timer.reset(); timer.start(); /* * Thaw the composite sequences. */ AbstractDao.log.info("Start initialize composite sequences"); Hibernate.initialize(result.getCompositeSequences()); if (timer.getTime() > 1000) { AbstractDao.log.info("Thaw array design stage 2: " + timer.getTime() + "ms"); } timer.stop(); timer.reset(); timer.start(); /* * Thaw the biosequences in batches */ Collection<CompositeSequence> thawed = new HashSet<>(); Collection<CompositeSequence> batch = new HashSet<>(); long lastTime = timer.getTime(); for (CompositeSequence cs : result.getCompositeSequences()) { batch.add(cs); if (batch.size() == 1000) { long t = timer.getTime(); if (t > 10000 && t - lastTime > 1000) { AbstractDao.log.info("Thaw Batch : " + t); } List bb = this.thawBatchOfProbes(batch); //noinspection unchecked thawed.addAll((Collection<? extends CompositeSequence>) bb); lastTime = timer.getTime(); batch.clear(); } this.getSessionFactory().getCurrentSession().evict(cs); } if (!batch.isEmpty()) { // tail end List bb = this.thawBatchOfProbes(batch); //noinspection unchecked thawed.addAll((Collection<? extends CompositeSequence>) bb); } result.getCompositeSequences().clear(); result.getCompositeSequences().addAll(thawed); /* * This is a bit ugly, but necessary to avoid 'dirty collection' errors later. */ if (result.getCompositeSequences() instanceof PersistentCollection) ((PersistentCollection) result.getCompositeSequences()).clearDirty(); if (timer.getTime() > 1000) { AbstractDao.log.info("Thaw array design stage 3: " + timer.getTime()); } return result; }
From source file:org.infoscoop.service.TabService.java
private void obsoleteStaticTabToDynamicTab(Map tabLayoutMap, Collection tabList, String uid) { // Create tab id list to allocate tab id again. List dynamicTabIdList = createDynamicTabIdList(tabList); Collection temp = new ArrayList(); Collection obsolutes = new ArrayList(); for (Iterator it = tabList.iterator(); it.hasNext();) { Tab tab = (Tab) it.next();/*from w w w . jav a 2 s .co m*/ //Transform static tab to dynamic tab. if ("static".equals(tab.getType().toLowerCase())) { if (!tabLayoutMap.containsKey(tab.getTabId())) { obsolutes.add(tab); } else { temp.add(tab); } } } for (Iterator ite = obsolutes.iterator(); ite.hasNext();) { Tab tab = convertStaticToDynamic(dynamicTabIdList, (Tab) ite.next()); tab.setOrder(new Integer(temp.size())); tabDAO.updateTab(tab); temp.add(tab); } for (Iterator it = tabList.iterator(); it.hasNext();) { Tab tab = (Tab) it.next(); if (!"static".equals(tab.getType().toLowerCase())) { tab.setOrder(new Integer(temp.size())); tabDAO.updateTab(tab); temp.add(tab); } } tabList.clear(); tabList.addAll(temp); }
From source file:influent.server.clustering.EntityClustererTest.java
@Test public void testClusterByGeoIncremental() { GeneralEntityClusterer clusterer = createClusterer("GEO:geo", 2); Collection<FL_Entity> entities = new LinkedList<FL_Entity>(); entities.add(createEntity("Amanda", FL_EntityTag.ACCOUNT, "Toronto", "CAN", 43.653226, -79.38318429999998, 2000, 3));//ww w . ja v a 2 s . com entities.add(createEntity("Bob", FL_EntityTag.ACCOUNT, "Vancouver", "CAN", 49.2827, -123.1207, 5, 7)); entities.add(createEntity("Alf", FL_EntityTag.ACCOUNT, "London", "GBR", 51.5072, -0.1275, 8, 7)); entities.add(createEntity("Zulu", FL_EntityTag.ACCOUNT, "NYC", "USA", 40.7143528, -74.0059731, 6, 13)); ClusterContext context = new ClusterContext(); context.addEntities(entities); context = clusterer.clusterEntities(entities, context); assertClusterEquals("c.cluster.1", "{c.cluster.1:[Alf][]}", context); // Europe assertClusterEquals("c.cluster.2", "{c.cluster.2:[][c.cluster.3]}", context); // North America assertClusterEquals("c.cluster.3", "{c.cluster.3:[][c.cluster.4,c.cluster.5]}", context); // USA and CAN assertClusterEquals("c.cluster.4", "{c.cluster.4:[Zulu][]}", context); // USA assertClusterEquals("c.cluster.5", "{c.cluster.5:[Amanda,Bob][]}", context); // CAN // cluster new entities entities.clear(); entities.add(createEntity("Steve", FL_EntityTag.ACCOUNT, "Victoria", "CAN", 48.4222, -123.3657, 5, 7)); entities.add(createEntity("Dan", FL_EntityTag.ACCOUNT, "Montreal", "CAN", 45.5017, -73.5673, 5, 7)); context.addEntities(entities); context = clusterer.clusterEntities(entities, context); for (FL_Cluster c : context.clusters.values()) { System.out.println(this.clusterToString(c)); } assertClusterEquals("c.cluster.1", "{c.cluster.1:[Alf][]}", context); // Europe assertClusterEquals("c.cluster.2", "{c.cluster.2:[][c.cluster.3]}", context); // North America assertClusterEquals("c.cluster.3", "{c.cluster.3:[][c.cluster.4,c.cluster.5]}", context); // USA and CAN assertClusterEquals("c.cluster.4", "{c.cluster.4:[Zulu][]}", context); // USA assertClusterEquals("c.cluster.5", "{c.cluster.5:[][c.cluster.8,c.cluster.7,c.cluster.6]}", context); // CAN assertClusterEquals("c.cluster.6", "{c.cluster.6:[Amanda][]}", context); // Toronto assertClusterEquals("c.cluster.7", "{c.cluster.7:[Bob,Steve][]}", context); // Vancouver and Victoria assertClusterEquals("c.cluster.8", "{c.cluster.8:[Dan][]}", context); // Montreal }
From source file:org.j2free.admin.ReflectionMarshaller.java
/** * //ww w . j a v a 2 s.c om * @param entity * @param parameterMap * @param controller * @return * @throws MarshallingException */ public Object marshallIn(Object entity, Map<String, String[]> parameterMap, Controller controller) throws MarshallingException { Field field; Converter converter; Method setter; String[] newValues; log.debug("Marshalling in instance of " + entity.getClass().getSimpleName()); boolean error = false, success = false, isEntity = false, isCollection = false; Class collectionType; Class fieldType; for (Map.Entry<Field, Converter> ent : instructions.entrySet()) { // reset flags error = success = isEntity = isCollection = false; field = ent.getKey(); converter = ent.getValue(); if (converter.isReadOnly()) { log.debug("Skipping read-only field " + field.getName()); continue; } newValues = parameterMap.get(field.getName()); if (newValues == null || newValues.length == 0) { log.debug("Skipping field " + field.getName() + ", no new value set."); continue; } isEntity = converter.isEntity(); isCollection = converter.isCollection(); fieldType = field.getType(); collectionType = isCollection ? converter.getType() : null; log.debug("Marshalling in field " + field.getName()); // try to get the original value try { if (!field.isAccessible()) { field.setAccessible(true); } if (field.isAccessible()) { log.debug(field.getName() + " is accessible"); if (!isEntity && !isCollection) { log.debug("!isEntity && !isCollection"); // if it's an array, it needs special treatment if (fieldType.isArray()) { log.debug(field.getName() + " is an Array"); Class arrayType = fieldType.getComponentType(); // If we can, just convert with a cast() if (arrayType.isAssignableFrom(String.class)) { log.debug(arrayType.getName() + " is assignable from String.class"); Object[] newArray = new Object[newValues.length]; for (int i = 0; i < newValues.length; i++) { newArray[i] = arrayType.cast(newValues[i]); } field.set(entity, newArray); } else { if (isInteger(fieldType)) { Integer[] newArray = new Integer[newValues.length]; for (int i = 0; i < newValues.length; i++) { newArray[i] = Integer.valueOf(newValues[i]); } field.set(entity, newArray); } else if (isFloat(fieldType)) { Float[] newArray = new Float[newValues.length]; for (int i = 0; i < newValues.length; i++) { newArray[i] = Float.valueOf(newValues[i]); } field.set(entity, newArray); } else if (isDouble(fieldType)) { Double[] newArray = new Double[newValues.length]; for (int i = 0; i < newValues.length; i++) { newArray[i] = Double.valueOf(newValues[i]); } field.set(entity, newArray); } else if (isShort(fieldType)) { Short[] newArray = new Short[newValues.length]; for (int i = 0; i < newValues.length; i++) { newArray[i] = Short.valueOf(newValues[i]); } field.set(entity, newArray); } else if (isChar(fieldType)) { field.set(entity, ServletUtils.join(newValues, "").toCharArray()); } else if (isLong(fieldType)) { Long[] newArray = new Long[newValues.length]; for (int i = 0; i < newValues.length; i++) { newArray[i] = Long.valueOf(newValues[i]); } field.set(entity, newArray); } else if (isBoolean(fieldType)) { Boolean[] newArray = new Boolean[newValues.length]; for (int i = 0; i < newValues.length; i++) { newArray[i] = Boolean.valueOf(newValues[i]); } field.set(entity, newArray); } else if (isByte(fieldType)) { Byte[] newArray = new Byte[newValues.length]; for (int i = 0; i < newValues.length; i++) { newArray[i] = Byte.valueOf(newValues[i]); } field.set(entity, newArray); } else { throw new MarshallingException( "Don't know how to marshall an array of a non-primitive, and non-assignable type! field = " + field.getName()); } } } else { // Check out if it's assignable via a straight cast, // that could save time if (fieldType.isAssignableFrom(String.class)) { log.debug(fieldType.getName() + " is assignable from String.class"); // this might throw an exception, but we're going // to ignore it because there are other ways of // setting the value if this doesn't work. try { field.set(entity, fieldType.cast(newValues[0])); log.debug("Assigned via cast"); } catch (Exception e) { log.debug("Error setting field by cast", e); } success = true; } // if it wasn't assignable via a straight cast, try // working around it. if (!success) { if (isInteger(fieldType) && !newValues[0].equals("")) { field.setInt(entity, Integer.valueOf(newValues[0])); } else if (isFloat(fieldType) && !newValues[0].equals("")) { field.setFloat(entity, Float.valueOf(newValues[0])); } else if (isDouble(fieldType) && !newValues[0].equals("")) { field.setDouble(entity, Double.valueOf(newValues[0])); } else if (isShort(fieldType) && !newValues[0].equals("")) { field.setShort(entity, Short.valueOf(newValues[0])); } else if (isChar(fieldType)) { field.setChar(entity, newValues[0].charAt(0)); } else if (isLong(fieldType) && !newValues[0].equals("")) { field.setLong(entity, Long.valueOf(newValues[0])); } else if (isBoolean(fieldType) && !newValues[0].equals("")) { field.setBoolean(entity, Boolean.valueOf(newValues[0])); } else if (isByte(fieldType) && !newValues[0].equals("")) { field.setByte(entity, Byte.valueOf(newValues[0])); } else if (isDate(fieldType)) { if (newValues[0].equals("")) { field.set(entity, null); } else { try { field.set(entity, asDate(newValues[0])); } catch (ParseException pe) { log.warn("Error parsing date: " + newValues[0], pe); } } } else if (!newValues[0].equals("")) { log.debug("Not sure how to set " + field.getName() + " of type " + fieldType.getName() + ", attemping cast."); field.set(entity, fieldType.cast(newValues[0])); } else if (newValues[0].equals("")) { log.debug("Skipping field " + field.getName() + ", empty string value passed in."); } } } } else if (isEntity && !isCollection) { log.debug("isEntity && !isCollection"); ReflectionMarshaller innerMarshaller = ReflectionMarshaller.getForClass(fieldType); field.set(entity, controller.proxy(fieldType, innerMarshaller.asIdType(newValues[0]))); } else if (!isEntity && isCollection) { log.debug("!isEntity && isCollection"); throw new MarshallingException("Error, collections of non-entities are not yet supported."); } else if (isEntity && isCollection) { log.debug("isEntity && isCollection"); // for now, this is going to expect the parameter to be a // comma-delimited string of entity ids String[] idsString = newValues[0].toString().split(","); Collection collection = (Collection) field.get(entity); log.debug("newValues.length = " + newValues.length); log.debug("newValues[0] = " + newValues[0]); log.debug("idsString.length = " + idsString.length); if (collection == null) collection = new LinkedList(); collection.clear(); if (idsString.length > 0) { ReflectionMarshaller collectionMarshaller = ReflectionMarshaller .getForClass(collectionType); log.debug("CollectionType = " + collectionType.getName()); for (String idString : idsString) { if (idString.equals("")) { log.debug("Skipping empty idString"); continue; } collection.add( controller.proxy(collectionType, collectionMarshaller.asIdType(idString))); } } field.set(entity, collection); } } else { error = true; } } catch (IllegalAccessException iae) { log.error("Unable to set " + field.getName() + " directly.", iae); error = true; } catch (ClassCastException cce) { log.error("Error setting " + field.getName() + ".", cce); error = true; } // if we hit an error getting it directly, try via the getter if (error) { error = false; try { setter = converter.getSetter(); if (setter != null) { if (!setter.isAccessible()) { setter.setAccessible(true); } if (setter.isAccessible()) { if (!isEntity && !isCollection) { // if it's an array, it needs special treatment if (fieldType.isArray()) { log.debug(field.getName() + " is an Array"); Class arrayType = fieldType.getComponentType(); // If we can, just convert with a cast() if (arrayType.isAssignableFrom(String.class)) { log.debug(arrayType.getName() + " is assignable from String.class"); Object[] newArray = new Object[newValues.length]; for (int i = 0; i < newValues.length; i++) { newArray[i] = arrayType.cast(newValues[i]); } setter.invoke(entity, newArray); } else { if (isInteger(fieldType)) { Integer[] newArray = new Integer[newValues.length]; for (int i = 0; i < newValues.length; i++) { newArray[i] = Integer.valueOf(newValues[i]); } setter.invoke(entity, (Object[]) newArray); } else if (isFloat(fieldType)) { Float[] newArray = new Float[newValues.length]; for (int i = 0; i < newValues.length; i++) { newArray[i] = Float.valueOf(newValues[i]); } setter.invoke(entity, (Object[]) newArray); } else if (isDouble(fieldType)) { Double[] newArray = new Double[newValues.length]; for (int i = 0; i < newValues.length; i++) { newArray[i] = Double.valueOf(newValues[i]); } setter.invoke(entity, (Object[]) newArray); } else if (isShort(fieldType)) { Short[] newArray = new Short[newValues.length]; for (int i = 0; i < newValues.length; i++) { newArray[i] = Short.valueOf(newValues[i]); } setter.invoke(entity, (Object[]) newArray); } else if (isChar(fieldType)) { setter.invoke(entity, ServletUtils.join(newValues, "").toCharArray()); } else if (isLong(fieldType)) { Long[] newArray = new Long[newValues.length]; for (int i = 0; i < newValues.length; i++) { newArray[i] = Long.valueOf(newValues[i]); } field.set(entity, (Object[]) newArray); } else if (isBoolean(fieldType)) { Boolean[] newArray = new Boolean[newValues.length]; for (int i = 0; i < newValues.length; i++) { newArray[i] = Boolean.valueOf(newValues[i]); } setter.invoke(entity, (Object[]) newArray); } else if (isByte(fieldType)) { Byte[] newArray = new Byte[newValues.length]; for (int i = 0; i < newValues.length; i++) { newArray[i] = Byte.valueOf(newValues[i]); } setter.invoke(entity, (Object[]) newArray); } else { throw new MarshallingException( "Don't know how to marshall an array of a non-primitive, and non-assignable type! field = " + field.getName()); } } } else { // Check out if it's assignable via a straight cast, // that could save time if (fieldType.isAssignableFrom(String.class)) { log.debug(fieldType.getName() + " is assignable from String.class"); // this might throw an exception, but we're going // to ignore it because there are other ways of // setting the value if this doesn't work. try { setter.invoke(entity, fieldType.cast(newValues[0])); } catch (Exception e) { log.debug("Error setting field by cast", e); } success = true; } // if it wasn't assignable via a straight cast, try // working around it. if (!success) { if (isInteger(fieldType)) { setter.invoke(entity, Integer.valueOf(newValues[0])); } else if (isFloat(fieldType)) { setter.invoke(entity, Float.valueOf(newValues[0])); } else if (isDouble(fieldType)) { setter.invoke(entity, Double.valueOf(newValues[0])); } else if (isShort(fieldType)) { setter.invoke(entity, Short.valueOf(newValues[0])); } else if (isChar(fieldType)) { setter.invoke(entity, newValues[0].charAt(0)); } else if (isLong(fieldType)) { setter.invoke(entity, Long.valueOf(newValues[0])); } else if (isBoolean(fieldType)) { setter.invoke(entity, Boolean.valueOf(newValues[0])); } else if (isByte(fieldType)) { setter.invoke(entity, Byte.valueOf(newValues[0])); } else if (isDate(fieldType)) { if (newValues[0].equals("")) { field.set(entity, null); } else { try { setter.invoke(entity, asDate(newValues[0])); } catch (ParseException pe) { log.warn("Error parsing date: " + newValues[0], pe); } } } else { log.debug("Not sure how to set " + field.getName() + " of type " + fieldType.getName() + ", attemping cast."); setter.invoke(entity, fieldType.cast(newValues[0])); } } } } else if (isEntity && !isCollection) { ReflectionMarshaller innerMarshaller = ReflectionMarshaller.getForClass(fieldType); setter.invoke(entity, controller.proxy(fieldType, innerMarshaller.asIdType(newValues[0]))); } else if (!isEntity && isCollection) { throw new MarshallingException( "Error, collections of non-entities are not yet supported."); } else if (isEntity && isCollection) { // for now, this is going to expect the parameter to be a // comma-delimited string of entity ids String[] idsString = newValues[0].toString().split(","); Collection collection = (Collection) field.get(entity); if (collection == null) collection = new LinkedList(); if (idsString.length == 0 && collection.isEmpty()) continue; collection.clear(); if (idsString.length > 0) { ReflectionMarshaller collectionMarshaller = ReflectionMarshaller .getForClass(collectionType); for (String idString : idsString) { if (idString.equals("")) { log.debug("Skipping empty idString"); continue; } collection.add(controller.proxy(collectionType, collectionMarshaller.asIdType(idString))); } } setter.invoke(entity, collection); } } else { error = true; } } else { error = true; } } catch (IllegalAccessException iae) { log.error("Error accessing setter", iae); error = true; } catch (InvocationTargetException ite) { log.error("Error invoking setter", ite); error = true; } } if (error) { throw new MarshallingException("Unable to marshall in field " + field.getName() + "."); } } return entity; }
From source file:io.datalayer.conf.XmlConfigurationTest.java
/** * Tests adding an attribute node using the addNodes() method. *//* w ww . j av a2 s . c o m*/ @Test public void testAddNodesAttributeNode() { conf.addProperty("testAddNodes.property[@name]", "prop1"); conf.addProperty("testAddNodes.property(0).value", "value1"); conf.addProperty("testAddNodes.property(-1)[@name]", "prop2"); conf.addProperty("testAddNodes.property(1).value", "value2"); Collection<ConfigurationNode> nodes = new ArrayList<ConfigurationNode>(); nodes.add(new HierarchicalConfiguration.Node("property")); conf.addNodes("testAddNodes", nodes); nodes.clear(); ConfigurationNode nd = new HierarchicalConfiguration.Node("name", "prop3"); nd.setAttribute(true); nodes.add(nd); conf.addNodes("testAddNodes.property(2)", nodes); assertEquals("Attribute not added", "prop3", conf.getString("testAddNodes.property(2)[@name]")); }
From source file:com.moviejukebox.model.Library.java
public void setPeople(Collection<Person> people) { people.clear(); for (Person person : people) { addPerson(person);// www .ja va 2s .c o m } }