org.apache.commons.lang3.ArrayUtils Java Examples
The following examples show how to use
org.apache.commons.lang3.ArrayUtils.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: QuerydslUtilsBeanImpl.java From gvnix with GNU General Public License v3.0 | 6 votes |
/** * {@inheritDoc} */ @Override public <T> Class<?> getFieldType1(String fieldName, PathBuilder<T> entity) { Class<?> entityType = entity.getType(); String fieldNameToFindType = fieldName; // Makes the array of classes to find fieldName agains them Class<?>[] classArray = ArrayUtils.<Class<?>> toArray(entityType); if (fieldName.contains(SEPARATOR_FIELDS)) { String[] fieldNameSplitted = StringUtils.split(fieldName, SEPARATOR_FIELDS); for (int i = 0; i < fieldNameSplitted.length - 1; i++) { Class<?> fieldType = BeanUtils.findPropertyType( fieldNameSplitted[i], ArrayUtils.<Class<?>> toArray(entityType)); classArray = ArrayUtils.add(classArray, fieldType); entityType = fieldType; } fieldNameToFindType = fieldNameSplitted[fieldNameSplitted.length - 1]; } return BeanUtils.findPropertyType(fieldNameToFindType, classArray); }
Example #2
Source File: TestLayerSpace.java From deeplearning4j with Apache License 2.0 | 6 votes |
@Test public void testSimpleConv() { ConvolutionLayer conv2d = new Convolution2D.Builder().dilation(1,2).kernelSize(2,2).nIn(2).nOut(3).build(); ConvolutionLayerSpace conv2dSpace = new ConvolutionLayerSpace.Builder().dilation(1,2).kernelSize(2,2).nIn(2).nOut(3).build(); assertEquals(0,conv2dSpace.getNumParameters()); assertEquals(conv2d, conv2dSpace.getValue(new double[0])); Deconvolution2DLayerSpace deconvd2dls = new Deconvolution2DLayerSpace.Builder().dilation(2,1).nIn(2).nOut(2).hasBias(new BooleanSpace()).build(); assertEquals(1, deconvd2dls.getNumParameters()); //Set the parameter numbers... List<ParameterSpace> list = deconvd2dls.collectLeaves(); int k = 0; for( int j = 0; j<list.size();j++) { if (list.get(j).numParameters() > 0) { list.get(j).setIndices(k++); } } Deconvolution2D actual = deconvd2dls.getValue(new double[]{0.9}); assertTrue(!actual.hasBias()); assertEquals(ArrayUtils.toString(new int[] {2,1} ),ArrayUtils.toString(actual.getDilation())); }
Example #3
Source File: CasMultiFactorWebflowConfigurer.java From cas-mfa with Apache License 2.0 | 6 votes |
@Override @PostConstruct public void afterPropertiesSet() throws Exception { try { String[] flowIds = flowDefinitionRegistry.getFlowDefinitionIds(); flowIds = ArrayUtils.removeElement(flowIds, FLOW_ID_LOGIN); flowIds = ArrayUtils.removeElement(flowIds, FLOW_ID_LOGOUT); LOGGER.debug("Detected {} flow configurations: [{}]", flowIds.length, Arrays.toString(flowIds)); LOGGER.debug("Configuring webflow for multifactor authentication..."); setupWebflow(flowIds); LOGGER.debug("Configured webflow for multifactor authentication."); LOGGER.debug("Registering default credentials-to-principal resolver..."); registerDefaultCredentialsToPrincipalResolver(); LOGGER.debug("Registered default credentials-to-principal resolver."); } catch (final Exception e) { LOGGER.error(e.getMessage(), e); } }
Example #4
Source File: PropertiesService.java From lutece-core with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * Add properties from all files found in a given directory * * @param strRelativePath * Relative path from the root path */ public void addPropertiesDirectory( String strRelativePath ) { File directory = new File( _strRootPath + strRelativePath ); if ( directory.exists( ) ) { File [ ] listFile = directory.listFiles( ); if ( ArrayUtils.isNotEmpty( listFile ) ) { for ( File file : listFile ) { if ( file.getName( ).endsWith( ".properties" ) ) { String strFullPath = file.getAbsolutePath( ); _mapPropertiesFiles.put( file.getName( ), strFullPath ); loadFile( strFullPath ); } } } } }
Example #5
Source File: ContainerKeyPrefixCodec.java From hadoop-ozone with Apache License 2.0 | 6 votes |
@Override public ContainerKeyPrefix fromPersistedFormat(byte[] rawData) throws IOException { // First 8 bytes is the containerId. long containerIdFromDB = ByteBuffer.wrap(ArrayUtils.subarray( rawData, 0, Long.BYTES)).getLong(); // When reading from byte[], we can always expect to have the containerId, // key and version parts in the byte array. byte[] keyBytes = ArrayUtils.subarray(rawData, Long.BYTES + 1, rawData.length - Long.BYTES - 1); String keyPrefix = new String(keyBytes, UTF_8); // Last 8 bytes is the key version. byte[] versionBytes = ArrayUtils.subarray(rawData, rawData.length - Long.BYTES, rawData.length); long version = ByteBuffer.wrap(versionBytes).getLong(); return new ContainerKeyPrefix(containerIdFromDB, keyPrefix, version); }
Example #6
Source File: DBLTIService.java From sakai with Educational Community License v2.0 | 6 votes |
/** * * {@inheritDoc} * * @see org.sakaiproject.lti.api.LTIService#countContentsDao(java.lang.String, * java.lang.String, boolean) */ public int countContentsDao(String search, String siteId, boolean isAdminRole) { // It is important that any tables/columns added for the purposes of display or searching be // LEFT JOIN - *any* INNER JOIN will function as a WHERE clause and will hide content // items from the admin UI - so they will not be seen and cannot be repaired String joinClause = "LEFT JOIN SAKAI_SITE ON lti_content.SITE_ID = SAKAI_SITE.SITE_ID" + " LEFT JOIN SAKAI_SITE_PROPERTY ssp1 ON (lti_content.SITE_ID = ssp1.SITE_ID AND ssp1.name = 'contact-name')" + " LEFT JOIN SAKAI_SITE_PROPERTY ssp2 ON (lti_content.SITE_ID = ssp2.SITE_ID AND ssp2.name = 'contact-email')" + " LEFT JOIN lti_tools ON (lti_content.tool_id = lti_tools.id)"; final String propertyKey = serverConfigurationService.getString(LTI_SITE_ATTRIBUTION_PROPERTY_KEY, LTI_SITE_ATTRIBUTION_PROPERTY_KEY_DEFAULT); if (StringUtils.isNotEmpty(propertyKey)) { joinClause = joinClause + " LEFT JOIN SAKAI_SITE_PROPERTY ssp3 ON (lti_content.SITE_ID = ssp3.SITE_ID AND ssp3.name = '" + propertyKey + "')"; } String[] fields = (String[])ArrayUtils.addAll(LTIService.CONTENT_MODEL, LTIService.CONTENT_EXTRA_FIELDS); search = foorm.searchCheck(search, "lti_content", fields); return countThingsDao("lti_content", LTIService.CONTENT_MODEL, joinClause, search, null, siteId, isAdminRole); }
Example #7
Source File: HttpHeader.java From PacketProxy with Apache License 2.0 | 6 votes |
static public boolean isHTTPHeader(byte[] data) { // Headerサイズは正 if (calcHeaderSize(data) == -1) { return false; } // first line取得 int index = ArrayUtils.indexOf(data, (byte)'\n'); if (index < 0) { return false; } if (index > 0 && data[index - 1] == '\r') { index--; } byte[] line = Arrays.copyOfRange(data, 0, index); // first lineに制御文字は無い for (int i = 0; i < line.length; i++) { if (line[i] < 0x20 || 0x7f <= line[i]) { return false; } } // first lineはスペース区切りでmethod pas, HTTP/?.?になってる String[] strs = new String(line).split(" "); if (strs.length != 3) { return false; } if (!strs[2].matches("HTTP/[0-9.]+")) { return false; } return true; }
Example #8
Source File: NumpyArray.java From deeplearning4j with Apache License 2.0 | 6 votes |
public NumpyArray(INDArray nd4jArray) { Nd4j.getAffinityManager().ensureLocation(nd4jArray, AffinityManager.Location.HOST); DataBuffer buff = nd4jArray.data(); address = buff.pointer().address(); shape = nd4jArray.shape(); long[] nd4jStrides = nd4jArray.stride(); strides = new long[nd4jStrides.length]; int elemSize = buff.getElementSize(); for (int i = 0; i < strides.length; i++) { strides[i] = nd4jStrides[i] * elemSize; } dtype = nd4jArray.dataType(); this.nd4jArray = nd4jArray; String cacheKey = address + "_" + nd4jArray.length() + "_" + dtype + "_" + ArrayUtils.toString(strides); arrayCache.put(cacheKey, nd4jArray); }
Example #9
Source File: StrTokenizerTest.java From astor with GNU General Public License v2.0 | 6 votes |
@Test public void test1() { final String input = "a;b;c;\"d;\"\"e\";f; ; ; "; final StrTokenizer tok = new StrTokenizer(input); tok.setDelimiterChar(';'); tok.setQuoteChar('"'); tok.setIgnoredMatcher(StrMatcher.trimMatcher()); tok.setIgnoreEmptyTokens(false); final String tokens[] = tok.getTokenArray(); final String expected[] = new String[]{"a", "b", "c", "d;\"e", "f", "", "", "",}; assertEquals(ArrayUtils.toString(tokens), expected.length, tokens.length); for (int i = 0; i < expected.length; i++) { assertTrue("token[" + i + "] was '" + tokens[i] + "' but was expected to be '" + expected[i] + "'", ObjectUtils.equals(expected[i], tokens[i])); } }
Example #10
Source File: Wallet.java From gsc-core with GNU Lesser General Public License v3.0 | 6 votes |
public Transaction triggerConstantContract(TriggerSmartContract triggerSmartContract, TransactionWrapper trxCap, Builder builder, Return.Builder retBuilder) throws ContractValidateException, ContractExeException, HeaderNotFound, VMIllegalException { ContractStore contractStore = dbManager.getContractStore(); byte[] contractAddress = triggerSmartContract.getContractAddress().toByteArray(); byte[] isContractExiste = contractStore.findContractByHash(contractAddress); if (ArrayUtils.isEmpty(isContractExiste)) { throw new ContractValidateException("No contract or not a smart contract"); } if (!Args.getInstance().isSupportConstant()) { throw new ContractValidateException("this node don't support constant"); } return callConstantContract(trxCap, builder, retBuilder); }
Example #11
Source File: BaseGraph.java From gatk-protected with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * Walk along the reference path in the graph and pull out the corresponding bases * @param fromVertex starting vertex * @param toVertex ending vertex * @param includeStart should the starting vertex be included in the path * @param includeStop should the ending vertex be included in the path * @return byte[] array holding the reference bases, this can be null if there are no nodes between the starting and ending vertex (insertions for example) */ public final byte[] getReferenceBytes( final V fromVertex, final V toVertex, final boolean includeStart, final boolean includeStop ) { Utils.nonNull(fromVertex, "Starting vertex in requested path cannot be null."); Utils.nonNull(toVertex, "From vertex in requested path cannot be null."); byte[] bytes = null; V v = fromVertex; if( includeStart ) { bytes = ArrayUtils.addAll(bytes, getAdditionalSequence(v)); } v = getNextReferenceVertex(v); // advance along the reference path while( v != null && !v.equals(toVertex) ) { bytes = ArrayUtils.addAll(bytes, getAdditionalSequence(v)); v = getNextReferenceVertex(v); // advance along the reference path } if( includeStop && v != null && v.equals(toVertex)) { bytes = ArrayUtils.addAll(bytes, getAdditionalSequence(v)); } return bytes; }
Example #12
Source File: TopDomainsDataSet.java From openemm with GNU Affero General Public License v3.0 | 6 votes |
private void updateRates(int tempTableID, int targetGroupIndex, int base, int... categories) throws Exception { if (categories.length == 0) { return; } else { StringBuilder sqlUpdateRatesBuilder = new StringBuilder(); sqlUpdateRatesBuilder.append("UPDATE ").append(getTemporaryTableName(tempTableID)).append(" SET rate = "); if (base <= 0) { // Negative value tells that rate isn't available sqlUpdateRatesBuilder.append(base < 0 ? -1 : 0); } else { sqlUpdateRatesBuilder.append("(value * 1.0) / ").append(base); } sqlUpdateRatesBuilder.append(" WHERE category_index IN (" + StringUtils.join(ArrayUtils.toObject(categories), ", ") + ") AND targetgroup_index = ?"); updateEmbedded(logger, sqlUpdateRatesBuilder.toString(), targetGroupIndex); } }
Example #13
Source File: ExtensionMessageFactoryImpl.java From joyqueue with Apache License 2.0 | 6 votes |
@Override public Message createMessage(String queueName, byte[] body) { try { Preconditions.checkArgument(StringUtils.isNotBlank(queueName), "queueName can not be null"); Preconditions.checkArgument(ArrayUtils.isNotEmpty(body), "body can not be null"); } catch (Throwable cause) { throw ExceptionConverter.convertProduceException(cause); } OMSProduceMessage omsProduceMessage = new OMSProduceMessage(); omsProduceMessage.setTopic(queueName); omsProduceMessage.setBodyBytes(body); MessageAdapter messageAdapter = new MessageAdapter(omsProduceMessage); omsProduceMessage.setOmsMessage(messageAdapter); return messageAdapter; }
Example #14
Source File: PagedQueryParam.java From bird-java with MIT License | 6 votes |
public PagedQueryParam withDataRule(String... tables) { if (ArrayUtils.isEmpty(tables)) return this; try { IDataRuleStore store = SpringContextHolder.getBean(IDataRuleStore.class); Long userId = SessionContext.getUserId(); if (NumberHelper.isPositive(userId)) { this.filterGroup = store.get(userId, tables); } else { logger.error("当前用户未登录"); } } catch (NoSuchBeanDefinitionException exception) { logger.error("IDataRuleStore未注入,数据权限规则无效", exception); } catch (NumberFormatException ex) { logger.error("当前用户未登录", ex); } return this; }
Example #15
Source File: GuessUtil.java From youran with Apache License 2.0 | 5 votes |
/** * 猜测特殊字段类型 * * @param fieldName * @param jFieldType * @return */ public static String guessSpecialField(String fieldName, JFieldType jFieldType) { String lowerCase = fieldName.toLowerCase(); boolean createPre = isMatchLabel(lowerCase, CREATE_PREFIX, true); boolean operatePre = isMatchLabel(lowerCase, OPERATE_PREFIX, true); if (jFieldType == JFieldType.DATE) { boolean timeSuff = isMatchLabel(lowerCase, TIME_SUFFIX, false); if (createPre && timeSuff) { return MetaSpecialField.CREATED_TIME; } if (operatePre && timeSuff) { return MetaSpecialField.OPERATED_TIME; } } if (jFieldType == JFieldType.STRING) { boolean userSuff = isMatchLabel(lowerCase, USER_SUFFIX, false); if (createPre && userSuff) { return MetaSpecialField.CREATED_BY; } if (operatePre && userSuff) { return MetaSpecialField.OPERATED_BY; } } if (VERSION_LABEL.equals(lowerCase) && jFieldType == JFieldType.INTEGER) { return MetaSpecialField.VERSION; } if (ArrayUtils.contains(DELETED_LABEL, lowerCase) && jFieldType == JFieldType.BOOLEAN) { return MetaSpecialField.DELETED; } return null; }
Example #16
Source File: Value.java From gsc-core with GNU Lesser General Public License v3.0 | 5 votes |
/** * @return */ public TransactionWrapper getTransaction() { if (ArrayUtils.isEmpty(any)) { return null; } try { return new TransactionWrapper(any); } catch (BadItemException e) { return null; } }
Example #17
Source File: BasicConfigurationService.java From sakai with Educational Community License v2.0 | 5 votes |
/** * {@inheritDoc} */ public List<String> getStringList(String name, List<String> dflt) { String[] values = getStrings(name); if (ArrayUtils.isNotEmpty(values)) { return Arrays.asList(values); } else { return dflt != null ? dflt : new ArrayList<>(); } }
Example #18
Source File: EntitySerialization.java From cuba with Apache License 2.0 | 5 votes |
protected Gson createGsonForSerialization(@Nullable View view, EntitySerializationOption... options) { GsonBuilder gsonBuilder = new GsonBuilder(); if (ArrayUtils.contains(options, EntitySerializationOption.PRETTY_PRINT)) { gsonBuilder.setPrettyPrinting(); } gsonBuilder .registerTypeHierarchyAdapter(Entity.class, new EntitySerializer(view, options)) .registerTypeHierarchyAdapter(Date.class, new DateSerializer()) .create(); if (ArrayUtils.contains(options, EntitySerializationOption.SERIALIZE_NULLS)) { gsonBuilder.serializeNulls(); } return gsonBuilder.create(); }
Example #19
Source File: StartpointManager.java From samza with Apache License 2.0 | 5 votes |
/** * Read the fanned out {@link Startpoint}s for the given {@link TaskName} * @param taskName to read the fan out Startpoints for * @return fanned out Startpoints */ public Map<SystemStreamPartition, Startpoint> getFanOutForTask(TaskName taskName) throws IOException { Preconditions.checkState(!stopped, "Underlying metadata store not available"); Preconditions.checkNotNull(taskName, "TaskName cannot be null"); byte[] fanOutBytes = fanOutStore.get(toFanOutStoreKey(taskName)); if (ArrayUtils.isEmpty(fanOutBytes)) { return ImmutableMap.of(); } StartpointFanOutPerTask startpointFanOutPerTask = objectMapper.readValue(fanOutBytes, StartpointFanOutPerTask.class); return ImmutableMap.copyOf(startpointFanOutPerTask.getFanOuts()); }
Example #20
Source File: ArrayUtilsUnitTest.java From tutorials with MIT License | 5 votes |
@Test public void givenArray_whenAddingAllElementsAtTheEnd_thenCorrect() { int[] oldArray = { 0, 1, 2 }; int[] newArray = ArrayUtils.addAll(oldArray, 3, 4, 5); int[] expectedArray = { 0, 1, 2, 3, 4, 5 }; assertArrayEquals(expectedArray, newArray); }
Example #21
Source File: CoveredColumnIndexCodec.java From phoenix with Apache License 2.0 | 5 votes |
private static void addColumnsToPut(Put indexInsert, List<ColumnEntry> columns) { // add each of the corresponding families to the put int count = 0; for (ColumnEntry column : columns) { indexInsert.addColumn(INDEX_ROW_COLUMN_FAMILY, ArrayUtils.addAll(Bytes.toBytes(count++), toIndexQualifier(column.ref)), null); } }
Example #22
Source File: NodeTest.java From htmlunit with Apache License 2.0 | 5 votes |
/** * @throws Exception if the test fails */ @Test @Alerts({"1", "2", "§§URL§§second"}) public void eventListener() throws Exception { final String html = "<html><head>\n" + "<script>\n" + " function clicking1() {\n" + " alert(1);\n" + " }\n" + " function clicking2() {\n" + " alert(2);\n" + " }\n" + " function test() {\n" + " var e = document.getElementById('myAnchor');\n" + " e.addEventListener('click', clicking1, false);\n" + " e.addEventListener('click', clicking2, false);\n" + " }\n" + "</script></head><body onload='test()'>\n" + " <a href='second' id='myAnchor'>Click me</a>\n" + "</body></html>"; getMockWebConnection().setDefaultResponse("<html><body>Test</body></html>"); expandExpectedAlertsVariables(URL_FIRST); final WebDriver driver = loadPage2(html); driver.findElement(By.id("myAnchor")).click(); verifyAlerts(driver, ArrayUtils.subarray(getExpectedAlerts(), 0, 2)); Thread.sleep(200); // FF60 WebDriver assertEquals(getExpectedAlerts()[2], driver.getCurrentUrl()); }
Example #23
Source File: ValueBinder.java From cuba with Apache License 2.0 | 5 votes |
/** * Set field's "required" flag to false if the value has been filtered by Row Level Security. * This is necessary to allow user to submit form with filtered attribute even if attribute is required. */ protected void resetRequiredIfAttributeFiltered(Field<?> field, EntityValueSource valueSource, MetaPropertyPath metaPropertyPath) { if (field.isRequired() && valueSource.getState() == BindingState.ACTIVE && valueSource.getItem() != null && metaPropertyPath.getMetaProperty().getRange().isClass()) { Entity rootItem = valueSource.getItem(); Entity targetItem = rootItem; MetaProperty[] propertiesChain = metaPropertyPath.getMetaProperties(); if (propertiesChain.length > 1) { String basePropertyItem = Arrays.stream(propertiesChain) .limit(propertiesChain.length - 1) .map(MetadataObject::getName) .collect(Collectors.joining(".")); targetItem = rootItem.getValueEx(basePropertyItem); } if (targetItem instanceof BaseGenericIdEntity) { String metaPropertyName = metaPropertyPath.getMetaProperty().getName(); Object value = targetItem.getValue(metaPropertyName); BaseGenericIdEntity baseGenericIdEntity = (BaseGenericIdEntity) targetItem; String[] filteredAttributes = getFilteredAttributes(baseGenericIdEntity); if (value == null && filteredAttributes != null && ArrayUtils.contains(filteredAttributes, metaPropertyName)) { field.setRequired(false); } } } }
Example #24
Source File: ChecksumAlgorithm.java From ghidra with Apache License 2.0 | 5 votes |
/** * Converts a long to a little-endian array. * * @param l The long to convert. * @param numBytes The desired size of the resulting array. Result is truncated or padded if * numBytes is smaller or larger than size of long. * @return The little-endian array. */ public static byte[] toArray(long l, int numBytes) { ByteBuffer buffy = ByteBuffer.allocate(Long.BYTES); buffy.putLong(l); byte[] checksumArray = new byte[numBytes]; int n = Math.min(Long.BYTES, numBytes); System.arraycopy(buffy.array(), Long.BYTES - n, checksumArray, numBytes - n, n); ArrayUtils.reverse(checksumArray); return checksumArray; }
Example #25
Source File: HeadlessDriverUtils.java From headless-chrome with MIT License | 5 votes |
public static void takeFullScreenshot(WebDriver webDriver, File pngFile, By... highlights) throws IOException { final PageSnapshot pageSnapshot = Shutterbug.shootPage(webDriver, BOTH_DIRECTIONS); if (ArrayUtils.isNotEmpty(highlights)) { Arrays.stream(highlights) .map(webDriver::findElements) .flatMap(Collection::stream) .forEach(pageSnapshot::highlight); } FileUtils.forceMkdirParent(pngFile); pageSnapshot.withName(pngFile.getName()); pageSnapshot.save(pngFile.getParent()); FileUtils.deleteQuietly(pngFile); FileUtils.moveFile(new File(pngFile.getPath() + ".png"), pngFile); }
Example #26
Source File: LoggingHttpServletRequestWrapper.java From servlet-logging-filter with Apache License 2.0 | 5 votes |
@Override public String[] getParameterValues(String name) { if (ArrayUtils.isEmpty(content) || this.parameterMap.isEmpty()) { return super.getParameterValues(name); } return this.parameterMap.get(name); }
Example #27
Source File: MethodUtilsTest.java From astor with GNU General Public License v2.0 | 5 votes |
public void testGetAccessibleInterfaceMethod() throws Exception { Class<?>[][] p = { ArrayUtils.EMPTY_CLASS_ARRAY, null }; for (int i = 0; i < p.length; i++) { Method method = TestMutable.class.getMethod("getValue", p[i]); Method accessibleMethod = MethodUtils.getAccessibleMethod(method); assertNotSame(accessibleMethod, method); assertSame(Mutable.class, accessibleMethod.getDeclaringClass()); } }
Example #28
Source File: StrBuilder.java From astor with GNU General Public License v2.0 | 5 votes |
/** * Copies the builder's character array into a new character array. * * @return a new array that represents the contents of the builder */ public char[] toCharArray() { if (size == 0) { return ArrayUtils.EMPTY_CHAR_ARRAY; } char chars[] = new char[size]; System.arraycopy(buffer, 0, chars, 0, size); return chars; }
Example #29
Source File: LocalFeignBeanDefinitionRegistryPostProcessor.java From onetwo with Apache License 2.0 | 5 votes |
protected void modifyFeignBeanFacotries(ConfigurableListableBeanFactory beanFactory){ ListableBeanFactory bf = (ListableBeanFactory)beanFactory.getParentBeanFactory(); if(bf==null){ return ; } String[] feignBeanNames = bf.getBeanNamesForAnnotation(EnhanceFeignClient.class); BeanDefinitionRegistry bdr = (BeanDefinitionRegistry)bf; Stream.of(feignBeanNames).forEach(beanName->{ BeanDefinition feignBeanDefinition = bdr.getBeanDefinition(feignBeanNames[0]); String typeName = (String)feignBeanDefinition.getPropertyValues().getPropertyValue("type").getValue(); Class<?> fallbackType = (Class<?>)feignBeanDefinition.getPropertyValues().getPropertyValue("fallback").getValue(); Class<?> clientInterface = ReflectUtils.loadClass(typeName); Class<?> apiInterface = clientInterface.getInterfaces()[0]; String[] typeBeanNames = bf.getBeanNamesForType(apiInterface);//maybe: feignclient, fallback, controller if(typeBeanNames.length<=1){ return ; } String[] localBeanNames = ArrayUtils.removeElement(typeBeanNames, beanName);//remove Optional<String> localBeanNameOpt = Stream.of(localBeanNames).filter(lbn->{ BeanDefinition bd = bdr.getBeanDefinition(lbn); return !bd.getBeanClassName().equals(fallbackType.getName()); }) .findFirst(); if(!localBeanNameOpt.isPresent()){ return ; } MutablePropertyValues mpvs = feignBeanDefinition.getPropertyValues(); this.clearMutablePropertyValues(mpvs); feignBeanDefinition.setBeanClassName(LocalFeignInvokerFactoryBean.class.getName()); mpvs.addPropertyValue("remoteInterface", clientInterface); mpvs.addPropertyValue("localBeanName", localBeanNameOpt.get()); }); }
Example #30
Source File: PermissionServiceImpl.java From EasyReport with Apache License 2.0 | 5 votes |
private String distinct(final String[] ids) { if (ArrayUtils.isEmpty(ids)) { return StringUtils.EMPTY; } final Set<String> idSet = new HashSet<>(ids.length); Collections.addAll(idSet, ids); return StringUtils.join(idSet, ','); }