/** * Method to convert a List of beans to a List of Array of Strings. * * @param beans the List of Beans. * @param addNewHeader the new String Array for the Header row. * @param <T> generic value. * @return the List of Array of String content of the csv. */ @SuppressWarnings("unchecked") public static <T> List<String[]> toStringArray(List<T> beans, String[] addNewHeader) { List<String[]> records = new ArrayList<>(); // add header record // records.add(new String[]{"ID","Name","Role","Salary"}); if (addNewHeader != null) records.add(addNewHeader); for (T bean : beans) { // beans.stream().map((bean) -> { List<String> record = new ArrayList<>(); // invoke getter method and convert to String Class<T> clazz = (Class<T>) bean.getClass(); // T t = ReflectionUtilities.invokeConstructor(clazz); List<Method> getter = (List<Method>) ReflectionUtilities.findGetters(clazz, true); for (Method method : getter) { record.add(String.valueOf(ReflectionUtilities.invokeGetter(bean, method))); } // getter.stream().forEach((method) -> // record.add(String.valueOf(ReflectionUtilities.invokeGetter(bean,method)))); // return record; // }).forEach((record) -> records.add(ListUtilities.toArray(record))); records.add(ListUtilities.toArray(record)); } return records; }
/** * This method builds the custom data collections used on the form * * @param customAttributeGroups */ @SuppressWarnings("unchecked") public void buildCustomDataCollectionsOnNewDocument( SortedMap<String, List> customAttributeGroups) { for (Map.Entry<String, CustomAttributeDocument> customAttributeDocumentEntry : getCustomAttributeDocuments().entrySet()) { String temp = customAttributeDocumentEntry.getValue().getCustomAttribute().getValue(); String groupName = customAttributeDocumentEntry.getValue().getCustomAttribute().getGroupName(); T newCustomData = getNewCustomData(); newCustomData.setCustomAttribute( customAttributeDocumentEntry.getValue().getCustomAttribute()); newCustomData.setCustomAttributeId( customAttributeDocumentEntry.getValue().getCustomAttributeId().longValue()); newCustomData.setValue( customAttributeDocumentEntry.getValue().getCustomAttribute().getDefaultValue()); getCustomDataList().add(newCustomData); if (StringUtils.isEmpty(groupName)) { groupName = "No Group"; } List<CustomAttributeDocument> customAttributeDocumentList = customAttributeGroups.get(groupName); if (customAttributeDocumentList == null) { customAttributeDocumentList = new ArrayList<CustomAttributeDocument>(); customAttributeGroups.put(groupName, customAttributeDocumentList); } customAttributeDocumentList.add( getCustomAttributeDocuments() .get(customAttributeDocumentEntry.getValue().getCustomAttributeId().toString())); Collections.sort(customAttributeDocumentList, new LabelComparator()); } }
public void fileDescriptorReceived(DownloadConnection source, FileDescriptor fd) throws IOException { if (this.fd != null) { if (T.t) { T.info("Already has FD. Ignore the new one and start download for this connection."); } if (T.t) { T.ass(source.readyToStartDownload(), "Not ready to start download?"); } if (needsMoreDownloadConnections()) { source.startDownloadingBlock(); } return; } if (T.t) { T.debug("Received file descriptor " + fd); } this.fd = fd; setState(State.DOWNLOADING); ArrayList<DownloadConnection> al = new ArrayList<DownloadConnection>(); for (DownloadConnection c : connections.values()) { al.add(c); } for (DownloadConnection c : al) { if (c.readyToStartDownload() && needsMoreDownloadConnections()) { c.startDownloadingBlock(); } } }
/** * This method builds the custom data collections used on the form and populates the values from * the collection of AwardCustomData on the Award. * * @param customAttributeGroups */ @SuppressWarnings("unchecked") public void buildCustomDataCollectionsOnExistingDocument( SortedMap<String, List> customAttributeGroups) { for (Map.Entry<String, CustomAttributeDocument> customAttributeDocumentEntry : getCustomAttributeDocuments().entrySet()) { T loopAwardCustomData = null; for (T awardCustomData : getCustomDataList()) { if (awardCustomData.getCustomAttributeId() == (long) customAttributeDocumentEntry.getValue().getCustomAttribute().getId()) { loopAwardCustomData = awardCustomData; break; } } if (loopAwardCustomData != null) { String groupName = getCustomAttributeDocuments() .get(loopAwardCustomData.getCustomAttributeId().toString()) .getCustomAttribute() .getGroupName(); List<CustomAttributeDocument> customAttributeDocumentList = customAttributeGroups.get(groupName); if (customAttributeDocumentList == null) { customAttributeDocumentList = new ArrayList<CustomAttributeDocument>(); customAttributeGroups.put(groupName, customAttributeDocumentList); } customAttributeDocumentList.add( getCustomAttributeDocuments() .get(loopAwardCustomData.getCustomAttributeId().toString())); Collections.sort(customAttributeDocumentList, new LabelComparator()); } } }
/** * There is a possible case that methods of particular object should be executed with classpath * different from the one implied by the current class' class loader. External system offers * {@link ParametersEnhancer#enhanceLocalProcessing(List)} method for defining that custom * classpath. * * <p>It's also possible that particular implementation of {@link ParametersEnhancer} is compiled * using dependency to classes which are provided by the {@link * ParametersEnhancer#enhanceLocalProcessing(List) expanded classpath}. E.g. a class <code>'A' * </code> might use method of class <code>'B'</code> and 'A' is located at the current * (system/plugin) classpath but <code>'B'</code> is not. We need to reload <code>'A'</code> using * its expanded classpath then, i.e. create new class loaded with that expanded classpath and load * <code>'A'</code> by it. * * <p>This method allows to do that. * * @param clazz custom classpath-aware class which instance should be created (is assumed to have * a no-args constructor) * @param <T> target type * @return newly created instance of the given class loaded by custom classpath-aware loader * @throws IllegalAccessException as defined by reflection processing * @throws InstantiationException as defined by reflection processing * @throws NoSuchMethodException as defined by reflection processing * @throws InvocationTargetException as defined by reflection processing * @throws ClassNotFoundException as defined by reflection processing */ @NotNull public static <T extends ParametersEnhancer> T reloadIfNecessary(@NotNull final Class<T> clazz) throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, ClassNotFoundException { T instance = clazz.newInstance(); List<URL> urls = ContainerUtilRt.newArrayList(); instance.enhanceLocalProcessing(urls); if (urls.isEmpty()) { return instance; } final ClassLoader baseLoader = clazz.getClassLoader(); Method method = baseLoader.getClass().getMethod("getUrls"); if (method != null) { //noinspection unchecked urls.addAll((Collection<? extends URL>) method.invoke(baseLoader)); } UrlClassLoader loader = new UrlClassLoader(UrlClassLoader.build().urls(urls).parent(baseLoader.getParent())) { @Override protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { if (name.equals(clazz.getName())) { return super.loadClass(name, resolve); } else { try { return baseLoader.loadClass(name); } catch (ClassNotFoundException e) { return super.loadClass(name, resolve); } } } }; //noinspection unchecked return (T) loader.loadClass(clazz.getName()).newInstance(); }
@SuppressWarnings("unchecked") @Override public INetSystem<F, N, P, T, M> clone(Map<N, N> map) { INetSystem<F, N, P, T, M> clone = null; try { clone = (INetSystem<F, N, P, T, M>) NetSystem.class.newInstance(); } catch (InstantiationException exception) { return null; } catch (IllegalAccessException exception) { return null; } for (P p : this.getPlaces()) { P np = (P) p.clone(); map.put((N) p, (N) np); clone.addPlace(np); } for (T t : this.getTransitions()) { T nt = (T) t.clone(); map.put((N) t, (N) nt); clone.addTransition(nt); } for (F f : this.getFlow()) { clone.addFlow(map.get(f.getSource()), map.get(f.getTarget())); } for (P p : this.getPlaces()) { clone.putTokens((P) map.get(p), this.getTokens(p)); } return clone; }
/** * 把list转为map 方便查找 * * @param list 数据库有效数据列表 * @return map */ private <T extends TrendValue> Map<String, T> tomap(List<T> list) { Map<String, T> map = new LinkedHashMap<>(); for (T value : list) { map.put(value.getDate(), value); } return map; }
@Override public ArrayList<String> getIdentifiers(Context context, T dso) { ArrayList<String> identifiers = new ArrayList<>(); IdentifierService identifierService = new DSpace().getSingletonService(IdentifierService.class); if (identifierService != null) { identifiers.addAll(identifierService.lookup(context, dso)); } else { log.warn("No IdentifierService found, will return an list containing " + "the Handle only."); if (dso.getHandle() != null) { identifiers.add(handleService.getCanonicalForm(dso.getHandle())); } } if (log.isDebugEnabled()) { StringBuilder dbgMsg = new StringBuilder(); for (String id : identifiers) { if (dbgMsg.capacity() == 0) { dbgMsg.append("This DSO's Identifiers are: "); } else { dbgMsg.append(", "); } dbgMsg.append(id); } dbgMsg.append("."); log.debug(dbgMsg.toString()); } return identifiers; }
private <T extends Mergeable> Object mergeProperties( Merge mergeAnnotation, String propertyName, T target, T source) throws MergerException { try { String tag = null; if (mergeAnnotation != null) { tag = mergeAnnotation.value(); } Object targetProperty = PropertyUtils.getProperty(target, propertyName); Object sourceProperty = PropertyUtils.getProperty(source, propertyName); Class propertyType = PropertyUtils.getPropertyType(target, propertyName); Object merged; if (tag != null && target.isGenerated() && target.containsTag(tag)) { merged = sourceProperty; } else { merged = merge(propertyType, targetProperty, sourceProperty); } updateTag(target, tag, merged == null); return merged; } catch (NoSuchMethodException e) { throw new MergerException("NoSuchMethodException while trying to merge", e); } catch (IllegalAccessException e) { throw new MergerException("IllegalAccessException while trying to merge", e); } catch (InvocationTargetException e) { throw new MergerException("InvocationTargetException while trying to merge", e); } }
/** * 根据聚合标识符和 指定 版本加载 聚合 * * @param aggregateIdentifier the identifier of the aggregate to load * @param expectedVersion The expected version of the loaded aggregate * @return the fully initialized aggregate */ @Override protected T doLoad(ID aggregateIdentifier, final Long expectedVersion) { AggregateEventStream events = null; AggregateEventStream originalStream = null; try { try { events = AggregateEventStore.readEvents(getTypeIdentifier(), aggregateIdentifier); } catch (EventStreamNotFoundException e) { throw new AggregateNotFoundException(aggregateIdentifier, "The aggregate was not found", e); } originalStream = events; for (EventStreamDecorator decorator : eventStreamDecorators) { events = decorator.decorateForRead(getTypeIdentifier(), aggregateIdentifier, events); } final T aggregate = aggregateFactory.createAggregate(aggregateIdentifier, events.peek()); List<AggregateEvent> unseenEvents = new ArrayList<AggregateEvent>(); aggregate.initializeState(new CapturingEventStream(events, unseenEvents, expectedVersion)); if (aggregate.isDeleted()) { throw new AggregateDeletedException(aggregateIdentifier); } CurrentUnitOfWork.get() .registerListener(new ConflictResolvingListener(aggregate, unseenEvents)); return aggregate; } finally { IOUtils.closeQuietlyIfCloseable(events); // if a decorator doesn't implement closeable, we still want to be sure we close the original // stream IOUtils.closeQuietlyIfCloseable(originalStream); } }
private void sortTree(T node) { List<MPSTreeNode> nodes = new ArrayList<MPSTreeNode>(); List<T> namespaces = new ArrayList<T>(); for (int i = 0; i < node.getChildCount(); i++) { MPSTreeNode child = (MPSTreeNode) node.getChildAt(i); if (myBuilder.isNamespaceNode(child)) { sortTree((T) child); namespaces.add((T) child); } else { nodes.add(child); } } Collections.sort(namespaces, new ToStringComparator()); Collections.sort( nodes, new jetbrains.mps.ide.projectPane.logicalview.nodes.ModuleTreeNodeComparator()); node.removeAllChildren(); for (T ns : namespaces) { node.add(ns); } for (MPSTreeNode n : nodes) { node.add(n); } }
/** * Copy from the copy method in StructUtil. Did not want to drag that code in. maybe this actually * should go to struct. * * @param from * @param to * @param excludes * @return * @throws Exception */ public static <T extends struct> T xcopy(struct from, T to, String... excludes) throws Exception { Arrays.sort(excludes); for (Field f : from.fields()) { if (Arrays.binarySearch(excludes, f.getName()) >= 0) continue; Object o = f.get(from); if (o == null) continue; Field tof = to.getField(f.getName()); if (tof != null) try { tof.set(to, Converter.cnv(tof.getGenericType(), o)); } catch (Exception e) { System.out.println( "Failed to convert " + f.getName() + " from " + from.getClass() + " to " + to.getClass() + " value " + o + " exception " + e); } } return to; }
public static <T> List<String> toStringList(T[] array) { List<String> list = new ArrayList(); for (T element : array) { list.add(element.toString()); } return list; }
/** * Sets up the mocks defined in the given mock class. * * <p>If the type {@linkplain MockClass#realClass referred to} by the mock class is actually an * interface, then a {@linkplain #newEmptyProxy(ClassLoader, Class) new empty proxy} is created. * * @param mockClassOrInstance the mock class itself (given by its {@code Class} literal), or an * instance of the mock class * @return the new proxy instance created for the mocked interface, or {@code null} otherwise * @throws IllegalArgumentException if a given mock class fails to specify the corresponding real * class using the {@code @MockClass(realClass = ...)} annotation; or if a mock class defines * a mock method for which no corresponding real method or constructor exists in the real * class; or if the real method matching a mock method is {@code abstract} * @see #setUpMock(Class, Object) * @see #setUpMocks(Object...) * @see <a * href="http://code.google.com/p/jmockit/source/browse/trunk/main/test/mockit/MockAnnotationsTest.java#696"> * Example</a> */ public static <T> T setUpMock(Object mockClassOrInstance) { Class<?> mockClass; Object mock; if (mockClassOrInstance instanceof Class<?>) { mockClass = (Class<?>) mockClassOrInstance; mock = null; } else { mockClass = mockClassOrInstance.getClass(); mock = mockClassOrInstance; } MockClassSetup setup = new MockClassSetup(mock, mockClass); Class<?> realClass = setup.getRealClass(); T proxy = null; if (realClass.isInterface()) { //noinspection unchecked proxy = (T) newEmptyProxy(mockClass.getClassLoader(), realClass); setup.setRealClass(proxy.getClass()); } setup.redefineMethods(); return proxy; }
public int compareTo(T child, T otherChild) { if (max) { return child.compareTo(otherChild); } else { return -1 * (child.compareTo(otherChild)); } }
@Override public String describe() { List<String> returns = Lists.newArrayList(); for (T r : values) returns.add(r.toString()); return "{" + Joiner.on(',').join(returns) + "}"; }
@Override public <T> T getService(Class<T> serviceClass) { //noinspection unchecked T service = (T) myServices.get(serviceClass); if (service == null) { final Iterator<T> iterator = ServiceLoader.load(serviceClass, serviceClass.getClassLoader()).iterator(); if (!iterator.hasNext()) { throw new ServiceConfigurationError("Implementation for " + serviceClass + " not found"); } service = iterator.next(); if (iterator.hasNext()) { throw new ServiceConfigurationError( "More than one implementation for " + serviceClass + " found: " + service.getClass() + " and " + iterator.next().getClass()); } myServices.putIfAbsent(serviceClass, service); //noinspection unchecked service = (T) myServices.get(serviceClass); } return service; }
/** * Both Model and Set are oplog-only; they never pass the state on the wire, only the oplog; new * replicas are booted with distilled oplog as well. So, this is the only point in the code that * mutates the state of a Set. */ @SwarmOperation(kind = SwarmOperationKind.Logged) public void change(FullSpec spec, JsonValue value) throws SwarmException { value = this.distillOp(spec, value); if (!value.isObject()) return; JsonObject jo = (JsonObject) value; for (JsonObject.Member entry : jo) { String keySpecStr = entry.getName(); TypeIdSpec key_spec = new TypeIdSpec(keySpecStr); JsonValue val = entry.getValue(); if (TRUE.equals(val)) { T obj = this.host.get(key_spec); this.objects.put(key_spec, obj); obj.on(JsonValue.NULL, this.proxy); } else if (FALSE.equals(val)) { T obj = this.objects.get(key_spec); if (obj != null) { obj.off(this.proxy); this.objects.remove(key_spec); } } else { logger.warn("unexpected value: {}->{}", spec, value); } } }
/** * 填充数据 * * @param list 数据库有效数据列表 * @return 填充的数据 */ private <T extends TrendValue> List<T> fulldata( List<T> list, DateFormat format, int field, Date start, Date end, Class<T> clazz) { Map<String, T> map = tomap(list); Calendar calendar = Calendar.getInstance(); calendar.setTime(start); List<T> nlist = new ArrayList<>(); while (calendar.getTime().before(end)) { String keytime = format.format(calendar.getTime()); T value = map.get(keytime); if (value == null) { value = AfReflecter.newInstance(clazz); value.setEmpty(); value.setDate(keytime); value.setTime(calendar.getTime()); nlist.add(value); } else { nlist.add(value); map.remove(keytime); } calendar.add(field, 1); } for (Map.Entry<String, T> entry : map.entrySet()) { nlist.add(entry.getValue()); } return nlist; }
private static <T extends Enum> int[] toIntArray(Collection<T> collection) { List<Integer> c = new ArrayList<Integer>(collection.size()); for (T t : collection) { c.add(t.ordinal()); } return ArrayUtils.toPrimitive(c.toArray(new Integer[c.size()])); }
public static <T> boolean isInSet(T value, T... set) { for (T i : set) { if (i.equals(value)) { return true; } } return false; }
private <T extends Widget> T add0(T child) { if (this.ui != null) ((Widget) child).attach(this.ui); child.parent = this; child.link(); child.added(); if (((Widget) child).canfocus && child.visible) newfocusable(child); return (child); }
/** * Validates that a type is extendable, i.e. is not an array, a primitive type or a {@code final} * type. * * @param typeDescription The type to validate. * @param <T> The actual type of the validated instance. * @return The input value. */ public static <T extends GenericTypeDescription> T isExtendable(T typeDescription) { if (!EXTENDABLE_TYPES.contains(typeDescription.getSort())) { throw new IllegalArgumentException("Cannot extend generic type: " + typeDescription); } else if (isDefineable(typeDescription.asErasure()).isFinal()) { throw new IllegalArgumentException("Cannot extend a final type: " + typeDescription); } return typeDescription; }
/** @throws FacebookException if the GraphObject doesn't have an ID. */ String getIdOfGraphObject(T graphObject) { if (graphObject.asMap().containsKey(ID)) { Object obj = graphObject.getProperty(ID); if (obj instanceof String) { return (String) obj; } } throw new FacebookException("Received an object without an ID."); }
public static <T> String fmtList(final List<T> list) { String result = ""; for (T item : list) { result += item.toString() + "\n"; } return result; }
public int selectBestBlockForDownload(Friend remoteFriend) throws IOException { if (T.t) { T.debug("Selecting best block for download. Remote: " + remoteFriend); } BlockMask bm = blockMasks.get(remoteFriend.getGuid()); if (bm == null) { if (T.t) { T.info("Ehh. Don't know anything about this friends block mask. Can't download."); } return -1; } BitSet interestingBlocks = getInterestingBlocks(bm); // remove bocks in progress from interesting blocks: BlockFile bf = storage.getBlockFile(root); BitSet blocksInProgress = bf == null ? new BitSet() : bf.getBlocksInProgress(); blocksInProgress.flip(0, fd.getNumberOfBlocks()); blocksInProgress.and(interestingBlocks); if (blocksInProgress.cardinality() > 0) { // there are blocks of interest that are NOT in progress. Take one of these interestingBlocks = blocksInProgress; } // else there are only blocks in progress. Use any of them int highestBlockNumber = 0; if (bf != null) { highestBlockNumber = bf.getHighestCompleteBlock(); } highestBlockNumber += manager.getCore().getSettings().getInternal().getMaxfileexpandinblocks(); // we prefer to load blocks below highestBlockNumber if (interestingBlocks.nextSetBit(0) < highestBlockNumber) { // we're good - there are interesting blocks below the highest block number. // remove all blocks above highest block number: if (highestBlockNumber + 1 < fd.getNumberOfBlocks()) { interestingBlocks.clear(highestBlockNumber + 1, fd.getNumberOfBlocks()); } } // select a random block of the ones we're interested in - change this to rarest first in the // future int c = interestingBlocks.cardinality(); int n = (int) (Math.random() * c); for (int i = interestingBlocks.nextSetBit(0), j = 0; i >= 0; i = interestingBlocks.nextSetBit(i + 1), j++) { if (j == n) { return i; } } if (T.t) { T.trace("Can't find any block to download from " + remoteFriend); } return -1; }
private <T extends Mergeable> void updateTag(T target, String tag, boolean remove) { if (tag != null) { if (remove) { target.removeMergeTag(tag); } else { target.addMergeTag(tag); } } }
/** * Restore the heap property, assuming that it may be violated only at K (a position in the array * 'data') and K's parent. */ private void reheapifyUp(int k) { T v = data.get(k); for (int p = k; k > 0; k = p) { p = (k - 1) / 2; if (v.compareTo(data.get(p)) > 0) data.set(k, data.get(p)); else break; } data.set(k, v); }
private <T extends MetadataItem> PartialList<Metadata> getMetadatas( int offset, int size, String sortBy, Class<T> clazz) { PartialList<T> items = persistenceService.getAllItems(clazz, offset, size, sortBy); List<Metadata> details = new LinkedList<>(); for (T definition : items.getList()) { details.add(definition.getMetadata()); } return new PartialList<>(details, items.getOffset(), items.getPageSize(), items.getTotalSize()); }
@SuppressWarnings("unchecked") protected <T extends Node> List<T> cloneList(List<T> list) { List<T> clone = new LinkedList<T>(); for (T n : list) { clone.add((T) n.clone()); } return clone; }