instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
protected List<String> getUserDns(String username) { if (this.userDnFormat == null) { return Collections.emptyList(); } List<String> userDns = new ArrayList<>(this.userDnFormat.length); String[] args = new String[] { LdapEncoder.nameEncode(username) }; synchronized (this.mutex) { for (MessageFormat formatter : this.userDnFormat) { userDns.add(formatter.format(args)); } } return userDns; } protected LdapUserSearch getUserSearch() { return this.userSearch; } @Override public void setMessageSource(@NonNull MessageSource messageSource) { Assert.notNull(messageSource, "Message source must not be null"); this.messages = new MessageSourceAccessor(messageSource); } /** * Sets the user attributes which will be retrieved from the directory. * @param userAttributes the set of user attributes to retrieve */ public void setUserAttributes(String[] userAttributes) { Assert.notNull(userAttributes, "The userAttributes property cannot be set to null"); this.userAttributes = userAttributes; } /**
* Sets the pattern which will be used to supply a DN for the user. The pattern should * be the name relative to the root DN. The pattern argument {0} will contain the * username. An example would be "cn={0},ou=people". * @param dnPattern the array of patterns which will be tried when converting a * username to a DN. */ public void setUserDnPatterns(String[] dnPattern) { Assert.notNull(dnPattern, "The array of DN patterns cannot be set to null"); // this.userDnPattern = dnPattern; this.userDnFormat = new MessageFormat[dnPattern.length]; for (int i = 0; i < dnPattern.length; i++) { this.userDnFormat[i] = new MessageFormat(dnPattern[i]); } } public void setUserSearch(LdapUserSearch userSearch) { Assert.notNull(userSearch, "The userSearch cannot be set to null"); this.userSearch = userSearch; } }
repos\spring-security-main\ldap\src\main\java\org\springframework\security\ldap\authentication\AbstractLdapAuthenticator.java
1
请完成以下Java代码
public static String replaceTitleCaseWithLowerCase(String original) { int lastIndex = 0; StringBuilder output = new StringBuilder(); Matcher matcher = TITLE_CASE_PATTERN.matcher(original); while (matcher.find()) { output.append(original, lastIndex, matcher.start()) .append(convert(matcher.group(1))); lastIndex = matcher.end(); } if (lastIndex < original.length()) { output.append(original, lastIndex, original.length()); } return output.toString(); } /** * Convert a token found into its desired lowercase * @param token the token to convert * @return the converted token */ private static String convert(String token) { return token.toLowerCase(); }
/** * Replace all the tokens in an input using the algorithm provided for each * @param original original string * @param tokenPattern the pattern to match with * @param converter the conversion to apply * @return the substituted string */ public static String replaceTokens(String original, Pattern tokenPattern, Function<Matcher, String> converter) { int lastIndex = 0; StringBuilder output = new StringBuilder(); Matcher matcher = tokenPattern.matcher(original); while (matcher.find()) { output.append(original, lastIndex, matcher.start()) .append(converter.apply(matcher)); lastIndex = matcher.end(); } if (lastIndex < original.length()) { output.append(original, lastIndex, original.length()); } return output.toString(); } }
repos\tutorials-master\core-java-modules\core-java-regex-2\src\main\java\com\baeldung\replacetokens\ReplacingTokens.java
1
请完成以下Java代码
public void addFocusListener (FocusListener l) { if (m_textArea == null) // during init super.addFocusListener(l); else m_textArea.addFocusListener(l); } /** * Add Text Mouse Listener * @param l */ @Override public void addMouseListener (MouseListener l) { m_textArea.addMouseListener(l); } /** * Add Text Key Listener * @param l */ @Override public void addKeyListener (KeyListener l) { m_textArea.addKeyListener(l); } /** * Add Text Input Method Listener * @param l */ @Override public void addInputMethodListener (InputMethodListener l) { m_textArea.addInputMethodListener(l); } /** * Get text Input Method Requests * @return requests */
@Override public InputMethodRequests getInputMethodRequests() { return m_textArea.getInputMethodRequests(); } /** * Set Text Input Verifier * @param l */ @Override public void setInputVerifier (InputVerifier l) { m_textArea.setInputVerifier(l); } @Override public final ICopyPasteSupportEditor getCopyPasteSupport() { return copyPasteSupport; } } // CTextArea
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\CTextArea.java
1
请完成以下Java代码
public class HalRelation { /** the name of the relation */ protected String relName; /** the url template used by the relation to construct links */ protected UriBuilder uriTemplate; /** the type of the resource we build a relation to. */ protected Class<?> resourceType; /** * Build a relation to a resource. * * @param relName the name of the relation. * @param resourceType the type of the resource * @return the relation */ public static HalRelation build(String relName, Class<?> resourceType, UriBuilder urlTemplate) { HalRelation relation = new HalRelation(); relation.relName = relName; relation.uriTemplate = urlTemplate; relation.resourceType = resourceType;
return relation; } public String getRelName() { return relName; } public UriBuilder getUriTemplate() { return uriTemplate; } public Class<?> getResourceType() { return resourceType; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\hal\HalRelation.java
1
请在Spring Boot框架中完成以下Java代码
public class OrderDocumentLocationAdapterFactory implements DocumentLocationAdapterFactory { @Override public Optional<IDocumentLocationAdapter> getDocumentLocationAdapterIfHandled(final Object record) { return toOrder(record).map(OrderDocumentLocationAdapterFactory::locationAdapter); } @Override public Optional<IDocumentBillLocationAdapter> getDocumentBillLocationAdapterIfHandled(final Object record) { return toOrder(record).map(OrderDocumentLocationAdapterFactory::billLocationAdapter); } @Override public Optional<IDocumentDeliveryLocationAdapter> getDocumentDeliveryLocationAdapter(final Object record) { return toOrder(record).map(OrderDocumentLocationAdapterFactory::deliveryLocationAdapter); } @Override public Optional<IDocumentHandOverLocationAdapter> getDocumentHandOverLocationAdapter(final Object record) { return toOrder(record).map(OrderDocumentLocationAdapterFactory::handOverLocationAdapter); } private static Optional<I_C_Order> toOrder(final Object record) { return InterfaceWrapperHelper.isInstanceOf(record, I_C_Order.class) ? Optional.of(InterfaceWrapperHelper.create(record, I_C_Order.class)) : Optional.empty(); } public static OrderMainLocationAdapter locationAdapter(@NonNull final I_C_Order delegate) {
return new OrderMainLocationAdapter(delegate); } public static OrderBillLocationAdapter billLocationAdapter(@NonNull final I_C_Order delegate) { return new OrderBillLocationAdapter(delegate); } public static OrderDropShipLocationAdapter deliveryLocationAdapter(@NonNull final I_C_Order delegate) { return new OrderDropShipLocationAdapter(delegate); } public static OrderHandOverLocationAdapter handOverLocationAdapter(@NonNull final I_C_Order delegate) { return new OrderHandOverLocationAdapter(delegate); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\location\adapter\OrderDocumentLocationAdapterFactory.java
2
请在Spring Boot框架中完成以下Java代码
public void revertLogicDeleted(List<String> ids) { this.baseMapper.revertLogicDeleted(ids); resreshRouter(null); } /** * 彻底删除 * @param ids */ @Override public void deleteLogicDeleted(List<String> ids) { this.baseMapper.deleteLogicDeleted(ids); resreshRouter(ids.get(0)); } /** * 路由复制 * @param id * @return */ @Override @Transactional(rollbackFor = Exception.class) public SysGatewayRoute copyRoute(String id) { log.info("--gateway 路由复制--"); SysGatewayRoute targetRoute = new SysGatewayRoute(); try { SysGatewayRoute sourceRoute = this.baseMapper.selectById(id); //1.复制路由 BeanUtils.copyProperties(sourceRoute,targetRoute); //1.1 获取当前日期 String formattedDate = dateFormat.format(new Date()); String copyRouteName = sourceRoute.getName() + "_copy_"; //1.2 判断数据库是否存在 Long count = this.baseMapper.selectCount(new LambdaQueryWrapper<SysGatewayRoute>().eq(SysGatewayRoute::getName, copyRouteName + formattedDate)); //1.3 新的路由名称 copyRouteName += count > 0?RandomUtil.randomNumbers(4):formattedDate; targetRoute.setId(null); targetRoute.setName(copyRouteName); targetRoute.setCreateTime(new Date()); targetRoute.setStatus(0); targetRoute.setDelFlag(CommonConstant.DEL_FLAG_0);
this.baseMapper.insert(targetRoute); //2.刷新路由 resreshRouter(null); } catch (Exception e) { log.error("路由配置解析失败", e); resreshRouter(null); e.printStackTrace(); } return targetRoute; } /** * 查询删除列表 * @return */ @Override public List<SysGatewayRoute> getDeletelist() { return baseMapper.queryDeleteList(); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\service\impl\SysGatewayRouteServiceImpl.java
2
请完成以下Java代码
public class Flowable5CommentWrapper implements Comment { private org.activiti.engine.task.Comment activit5Comment; public Flowable5CommentWrapper(org.activiti.engine.task.Comment activit5Comment) { this.activit5Comment = activit5Comment; } @Override public String getId() { return activit5Comment.getId(); } @Override public String getUserId() { return activit5Comment.getUserId(); } @Override public Date getTime() { return activit5Comment.getTime(); } @Override public String getTaskId() { return activit5Comment.getTaskId(); } @Override public String getProcessInstanceId() { return activit5Comment.getProcessInstanceId(); } @Override public String getType() { return activit5Comment.getType(); } @Override public String getFullMessage() { return activit5Comment.getFullMessage(); } public org.activiti.engine.task.Comment getRawObject() { return activit5Comment; } @Override public void setUserId(String userId) { ((CommentEntity) activit5Comment).setUserId(userId); }
@Override public void setTime(Date time) { ((CommentEntity) activit5Comment).setTime(time); } @Override public void setTaskId(String taskId) { ((CommentEntity) activit5Comment).setTaskId(taskId); } @Override public void setProcessInstanceId(String processInstanceId) { ((CommentEntity) activit5Comment).setProcessInstanceId(processInstanceId); } @Override public void setType(String type) { ((CommentEntity) activit5Comment).setType(type); } @Override public void setFullMessage(String fullMessage) { ((CommentEntity) activit5Comment).setFullMessage(fullMessage); } }
repos\flowable-engine-main\modules\flowable5-compatibility\src\main\java\org\flowable\compatibility\wrapper\Flowable5CommentWrapper.java
1
请完成以下Java代码
public void setFormatPattern (java.lang.String FormatPattern) { set_Value (COLUMNNAME_FormatPattern, FormatPattern); } /** Get Format Pattern. @return The pattern used to format a number or date. */ @Override public java.lang.String getFormatPattern () { return (java.lang.String)get_Value(COLUMNNAME_FormatPattern); } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override
public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set Reihenfolge. @param SeqNo Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Reihenfolge. @return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.datev\src\main\java-gen\de\metas\datev\model\X_DATEV_ExportFormatColumn.java
1
请完成以下Java代码
public void placeOrder(String productId, int amount) throws Exception { UserTransactionImp utx = new UserTransactionImp(); String orderId = UUID.randomUUID() .toString(); boolean rollback = false; try { utx.begin(); Connection inventoryConnection = inventoryDataSource.getConnection(); Connection orderConnection = orderDataSource.getConnection(); Statement s1 = inventoryConnection.createStatement(); String q1 = "update Inventory set balance = balance - " + amount + " where productId ='" + productId + "'"; s1.executeUpdate(q1); s1.close(); Statement s2 = orderConnection.createStatement(); String q2 = "insert into Orders values ( '" + orderId + "', '" + productId + "', " + amount + " )";
s2.executeUpdate(q2); s2.close(); inventoryConnection.close(); orderConnection.close(); } catch (Exception e) { System.out.println(e.getMessage()); rollback = true; } finally { if (!rollback) utx.commit(); else utx.rollback(); } } }
repos\tutorials-master\persistence-modules\atomikos\src\main\java\com\baeldung\atomikos\direct\Application.java
1
请完成以下Java代码
public void setResources(Map<String, EngineResource> resources) { this.resources = resources; } @Override public Date getDeploymentTime() { return deploymentTime; } @Override public void setDeploymentTime(Date deploymentTime) { this.deploymentTime = deploymentTime; } @Override public boolean isNew() { return isNew; } @Override public void setNew(boolean isNew) { this.isNew = isNew; } @Override public String getEngineVersion() { return engineVersion; } @Override public void setEngineVersion(String engineVersion) { this.engineVersion = engineVersion; } @Override public String getDerivedFrom() { return derivedFrom; } @Override
public void setDerivedFrom(String derivedFrom) { this.derivedFrom = derivedFrom; } @Override public String getDerivedFromRoot() { return derivedFromRoot; } @Override public void setDerivedFromRoot(String derivedFromRoot) { this.derivedFromRoot = derivedFromRoot; } @Override public String getParentDeploymentId() { return parentDeploymentId; } @Override public void setParentDeploymentId(String parentDeploymentId) { this.parentDeploymentId = parentDeploymentId; } // common methods ////////////////////////////////////////////////////////// @Override public String toString() { return "DeploymentEntity[id=" + id + ", name=" + name + "]"; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\DeploymentEntityImpl.java
1
请完成以下Java代码
public class ClientApp { static class ClientActor extends AbstractActor { private final String serverActorPath; public ClientActor(String serverActorPath) { this.serverActorPath = serverActorPath; } @Override public void preStart() { ActorSelection serverActor = getContext().actorSelection(serverActorPath); serverActor.tell("Hello from Client", getSelf()); } @Override
public Receive createReceive() { return receiveBuilder() .match(String.class, msg -> { System.out.println("Client received message: " + msg); }) .build(); } } public static void main(String[] args) { ActorSystem system = ActorSystem.create("RemoteSystem", ConfigFactory.load("client")); String serverPath = "akka://RemoteSystem@127.0.0.1:2552/user/serverActor"; ActorRef clientActor = system.actorOf(Props.create(ClientActor.class, serverPath), "clientActor"); System.out.println("Client is running..."); } }
repos\springboot-demo-master\akka\src\main\java\com\et\akka\remoting\ClientApp.java
1
请完成以下Java代码
public class DataStateImpl extends BaseElementImpl implements DataState { protected static Attribute<String> nameAttribute; public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(DataState.class, BPMN_ELEMENT_DATA_STATE) .namespaceUri(BpmnModelConstants.BPMN20_NS) .extendsType(BaseElement.class) .instanceProvider(new ModelTypeInstanceProvider<DataState>() { public DataState newInstance(ModelTypeInstanceContext instanceContext) { return new DataStateImpl(instanceContext); } }); nameAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_NAME) .build();
typeBuilder.build(); } public DataStateImpl(ModelTypeInstanceContext instanceContext) { super(instanceContext); } public String getName() { return nameAttribute.getValue(this); } public void setName(String name) { nameAttribute.setValue(this, name); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\DataStateImpl.java
1
请完成以下Java代码
public static final <T> List<T> copyAsList(final Iterable<? extends T> iterable) { if (iterable == null) { return null; } if (iterable instanceof Collection) { final Collection<? extends T> col = (Collection<? extends T>)iterable; return new ArrayList<>(col); } else { final List<T> list = new ArrayList<>(); for (final T item : iterable) { list.add(item); } return list; } } /** * Creates a new list having all elements from given <code>list</code> in reversed order. * * NOTE: returning list is not guaranteed to me modifiable. * * @param list * @return */ public static <T> List<T> copyAndReverse(final List<T> list) { if (list == null) { return null; } if (list.isEmpty()) { return Collections.emptyList(); }
final List<T> listCopy = new ArrayList<>(list); Collections.reverse(listCopy); return listCopy; } /** * @param list * @param predicate * @return a filtered copy of given list */ public static final <E> List<E> copyAndFilter(final List<? extends E> list, final Predicate<? super E> predicate) { final List<E> copy = new ArrayList<>(); for (final E element : list) { if (predicate.apply(element)) { copy.add(element); } } return copy; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\collections\ListUtils.java
1
请完成以下Java代码
private PoolingHttpClientConnectionManager createConnectionManager(HttpClientSettings settings) { PoolingHttpClientConnectionManagerBuilder builder = PoolingHttpClientConnectionManagerBuilder.create() .useSystemProperties(); PropertyMapper map = PropertyMapper.get(); builder.setDefaultSocketConfig(createSocketConfig()); builder.setDefaultConnectionConfig(createConnectionConfig(settings)); map.from(settings::sslBundle) .always() .as(this.tlsSocketStrategyFactory::getTlsSocketStrategy) .to(builder::setTlsSocketStrategy); this.connectionManagerCustomizer.accept(builder); return builder.build(); } private SocketConfig createSocketConfig() { SocketConfig.Builder builder = SocketConfig.custom(); this.socketConfigCustomizer.accept(builder); return builder.build(); } private ConnectionConfig createConnectionConfig(HttpClientSettings settings) { ConnectionConfig.Builder builder = ConnectionConfig.custom(); PropertyMapper map = PropertyMapper.get(); map.from(settings::connectTimeout) .as(Duration::toMillis) .to((timeout) -> builder.setConnectTimeout(timeout, TimeUnit.MILLISECONDS)); map.from(settings::readTimeout) .asInt(Duration::toMillis) .to((timeout) -> builder.setSocketTimeout(timeout, TimeUnit.MILLISECONDS)); this.connectionConfigCustomizer.accept(builder); return builder.build(); }
private RequestConfig createDefaultRequestConfig() { RequestConfig.Builder builder = RequestConfig.custom(); this.defaultRequestConfigCustomizer.accept(builder); return builder.build(); } /** * Factory that can be used to optionally create a {@link TlsSocketStrategy} given an * {@link SslBundle}. * * @since 4.0.0 */ public interface TlsSocketStrategyFactory { /** * Return the {@link TlsSocketStrategy} to use for the given bundle. * @param sslBundle the SSL bundle or {@code null} * @return the {@link TlsSocketStrategy} to use or {@code null} */ @Nullable TlsSocketStrategy getTlsSocketStrategy(@Nullable SslBundle sslBundle); } }
repos\spring-boot-4.0.1\module\spring-boot-http-client\src\main\java\org\springframework\boot\http\client\HttpComponentsHttpClientBuilder.java
1
请完成以下Java代码
public boolean isPostBudget() { return get_ValueAsBoolean(COLUMNNAME_PostBudget); } @Override public void setPostEncumbrance (final boolean PostEncumbrance) { set_Value (COLUMNNAME_PostEncumbrance, PostEncumbrance); } @Override public boolean isPostEncumbrance() { return get_ValueAsBoolean(COLUMNNAME_PostEncumbrance); } @Override public void setPostStatistical (final boolean PostStatistical) { set_Value (COLUMNNAME_PostStatistical, PostStatistical); } @Override public boolean isPostStatistical() { return get_ValueAsBoolean(COLUMNNAME_PostStatistical); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setProcessing (final boolean Processing) {
set_Value (COLUMNNAME_Processing, Processing); } @Override public boolean isProcessing() { return get_ValueAsBoolean(COLUMNNAME_Processing); } @Override public void setValue (final @Nullable java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_ElementValue.java
1
请完成以下Java代码
public class CompensateEventSubscriptionEntity extends EventSubscriptionEntity { private static final long serialVersionUID = 1L; private CompensateEventSubscriptionEntity() { } private CompensateEventSubscriptionEntity(ExecutionEntity executionEntity) { super(executionEntity); eventType = CompensationEventHandler.EVENT_HANDLER_TYPE; } public static CompensateEventSubscriptionEntity createAndInsert(ExecutionEntity executionEntity) { CompensateEventSubscriptionEntity eventSubscription = new CompensateEventSubscriptionEntity(executionEntity); if (executionEntity.getTenantId() != null) { eventSubscription.setTenantId(executionEntity.getTenantId()); } eventSubscription.insert(); return eventSubscription; } // custom processing behavior ////////////////////////////////////////////////////////////////////////////// @Override protected void processEventSync(Object payload) { delete(); super.processEventSync(payload); }
public CompensateEventSubscriptionEntity moveUnder(ExecutionEntity newExecution) { delete(); CompensateEventSubscriptionEntity newSubscription = createAndInsert(newExecution); newSubscription.setActivity(getActivity()); newSubscription.setConfiguration(configuration); // use the original date newSubscription.setCreated(created); return newSubscription; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\CompensateEventSubscriptionEntity.java
1
请完成以下Java代码
public String getConsumerTag() { return this.consumerTag; } /** * Retrieve the message envelope. * @return the message envelope. */ public Envelope getEnvelope() { return this.envelope; } /** * Retrieve the message properties. * @return the message properties. */ public BasicProperties getProperties() { return this.properties; } /**
* Retrieve the message body. * @return the message body. */ public byte[] getBody() { return this.body; // NOSONAR } /** * Retrieve the queue. * @return the queue. */ public String getQueue() { return this.queue; } }
repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\support\Delivery.java
1
请完成以下Java代码
public byte[] decrypt(byte[] encryptedMessage) { int paramsLength = Byte.toUnsignedInt(encryptedMessage[0]); int messageLength = encryptedMessage.length - paramsLength - 1; byte[] params = new byte[paramsLength]; byte[] message = new byte[messageLength]; System.arraycopy(encryptedMessage, 1, params, 0, paramsLength); System.arraycopy(encryptedMessage, paramsLength + 1, message, 0, messageLength); // create Key final SecretKeyFactory factory = SecretKeyFactory.getInstance(algorithm); final PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray()); SecretKey key = factory.generateSecret(keySpec); // Build parameters AlgorithmParameters algorithmParameters = AlgorithmParameters.getInstance(algorithm); algorithmParameters.init(params); // Build Cipher final Cipher cipherDecrypt = Cipher.getInstance(algorithm); cipherDecrypt.init( Cipher.DECRYPT_MODE, key, algorithmParameters ); return cipherDecrypt.doFinal(message); } /** {@inheritDoc} */ @Override
public void setPassword(String password) { this.password = password; } /** * <p>Setter for the field <code>saltGenerator</code>.</p> * * @param saltGenerator a {@link org.jasypt.salt.SaltGenerator} object */ public void setSaltGenerator(SaltGenerator saltGenerator) { this.saltGenerator = saltGenerator; } /** * <p>Setter for the field <code>iterations</code>.</p> * * @param iterations a int */ public void setIterations(int iterations) { this.iterations = iterations; } /** * <p>Setter for the field <code>algorithm</code>.</p> * * @param algorithm a {@link java.lang.String} object */ public void setAlgorithm(String algorithm) { this.algorithm = algorithm; } }
repos\jasypt-spring-boot-master\jasypt-spring-boot\src\main\java\com\ulisesbocchio\jasyptspringboot\encryptor\SimplePBEByteEncryptor.java
1
请在Spring Boot框架中完成以下Java代码
public void deleteJobSchedulesById(@NonNull final Set<PickingJobScheduleId> jobScheduleIds) { final PickingJobScheduleCollection deletedSchedules = pickingJobScheduleRepository.deleteByIdsAndReturn(jobScheduleIds); pickingJobShipmentScheduleService.flagForRecompute(deletedSchedules.getShipmentScheduleIds()); } public PickingJobScheduleCollection list(@NonNull final PickingJobScheduleQuery query) { return pickingJobScheduleRepository.list(query); } public Stream<PickingJobSchedule> stream(@NonNull final PickingJobScheduleQuery query) { return pickingJobScheduleRepository.stream(query); } public void markAsProcessed(final Set<PickingJobScheduleId> ids) { pickingJobScheduleRepository.updateByIds(ids, jobSchedule -> jobSchedule.toBuilder().processed(true).build()); } public Set<ShipmentScheduleId> getShipmentScheduleIdsWithAllJobSchedulesProcessedOrMissing(@NonNull final Set<ShipmentScheduleId> shipmentScheduleIds) { if (shipmentScheduleIds.isEmpty()) {return ImmutableSet.of();} final Map<ShipmentScheduleId, PickingJobScheduleCollection> jobSchedulesByShipmentScheduleId = stream(PickingJobScheduleQuery.builder().onlyShipmentScheduleIds(shipmentScheduleIds).build()) .collect(Collectors.groupingBy(PickingJobSchedule::getShipmentScheduleId, PickingJobScheduleCollection.collect())); final HashSet<ShipmentScheduleId> result = new HashSet<>(); for (final ShipmentScheduleId shipmentScheduleId : shipmentScheduleIds) { final PickingJobScheduleCollection jobSchedules = jobSchedulesByShipmentScheduleId.get(shipmentScheduleId); if (jobSchedules == null || jobSchedules.isAllProcessed())
{ result.add(shipmentScheduleId); } } return result; } public Quantity getQtyRemainingToScheduleForPicking(@NonNull final ShipmentScheduleId shipmentScheduleId) { final I_M_ShipmentSchedule shipmentSchedule = pickingJobShipmentScheduleService.getByIdAsRecord(shipmentScheduleId); final Quantity qtyToDeliver = pickingJobShipmentScheduleService.getQtyToDeliver(shipmentSchedule); final Quantity qtyScheduledForPicking = pickingJobShipmentScheduleService.getQtyScheduledForPicking(shipmentSchedule); return qtyToDeliver.subtract(qtyScheduledForPicking); } public void autoAssign(@NonNull final PickingJobScheduleAutoAssignRequest request) { PickingJobScheduleAutoAssignCommand.builder() .workplaceRepository(workplaceRepository) .pickingJobScheduleRepository(pickingJobScheduleRepository) .pickingJobShipmentScheduleService(pickingJobShipmentScheduleService) .sysConfigBL(sysConfigBL) .pickingJobProductService(pickingJobProductService) .request(request) .build() .execute(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job_schedule\service\PickingJobScheduleService.java
2
请在Spring Boot框架中完成以下Java代码
public ProcessPreconditionsResolution checkPreconditionsApplicable(@NonNull final IProcessPreconditionsContext context) { if (context.getSelectionSize().isNoSelection()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection(); } else if (context.getSelectionSize().isMoreThanOneSelected()) { return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection(); } return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() throws Exception { final IssueEntity issueEntity = issueRepository.getById(IssueId.ofRepoId(getRecord_ID()));
if (issueEntity.getExternalProjectReferenceId() == null || issueEntity.getExternalIssueNo() == null || issueEntity.getExternalIssueNo().signum() == 0) { throw new AdempiereException("The selected issue was not imported from Github!") .appendParametersToMessage() .setParameter("IssueEntity", issueEntity); } setExternalProjectReferenceId(issueEntity.getExternalProjectReferenceId()); setIssueNumbers(issueEntity.getExternalIssueNo().toString()); return super.doIt(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java\de\metas\serviceprovider\github\GithubImportSingleSelection.java
2
请在Spring Boot框架中完成以下Java代码
public class MultipartFileUploadStubController { @PostMapping("/stub/multipart") public ResponseEntity<UploadResultResource> uploadFile(MultipartFile file, String text, String text1, String text2, MultipartFile upstream) { UploadResultResource result = new UploadResultResource(file, text, text1, text2, upstream); return new ResponseEntity<>(result, HttpStatus.OK); } public static class UploadResultResource { private final String file; private final String text; private final String text1; private final String text2; private final String upstream; public UploadResultResource(MultipartFile file, String text, String text1, String text2, MultipartFile upstream) { this.file = format(file); this.text = text; this.text1 = text1; this.text2 = text2; this.upstream = format(upstream); } private static String format(MultipartFile file) { return file == null ? null : file.getOriginalFilename() + " (size: " + file.getSize() + " bytes)";
} public String getFile() { return file; } public String getText() { return text; } public String getText1() { return text1; } public String getText2() { return text2; } public String getUpstream() { return upstream; } } }
repos\tutorials-master\spring-web-modules\spring-mvc-java\src\main\java\com\baeldung\web\controller\MultipartFileUploadStubController.java
2
请在Spring Boot框架中完成以下Java代码
public String delete(Model model, DwzAjax dwz, @RequestParam("userNo") String userNo) { rpUserPayConfigService.deleteUserPayConfig(userNo); dwz.setStatusCode(DWZ.SUCCESS); dwz.setMessage(DWZ.SUCCESS_MSG); model.addAttribute("dwz", dwz); return DWZ.AJAX_DONE; } /** * 函数功能说明 : 审核 * * @参数: @return * @return String * @throws */ @RequiresPermissions("pay:config:add") @RequestMapping(value = "/audit", method ={RequestMethod.POST, RequestMethod.GET}) public String audit(Model model, DwzAjax dwz, @RequestParam("userNo") String userNo , @RequestParam("auditStatus") String auditStatus) { rpUserPayConfigService.audit(userNo, auditStatus); dwz.setStatusCode(DWZ.SUCCESS); dwz.setMessage(DWZ.SUCCESS_MSG); model.addAttribute("dwz", dwz); return DWZ.AJAX_DONE; } /** * 函数功能说明 :跳转编辑银行卡信息 * * @参数: @return * @return String * @throws */ @RequiresPermissions("pay:config:edit")
@RequestMapping(value = "/editBankUI", method = RequestMethod.GET) public String editBankUI(Model model, @RequestParam("userNo") String userNo) { RpUserBankAccount rpUserBankAccount = rpUserBankAccountService.getByUserNo(userNo); RpUserInfo rpUserInfo = rpUserInfoService.getDataByMerchentNo(userNo); model.addAttribute("BankCodeEnums", BankCodeEnum.toList()); model.addAttribute("BankAccountTypeEnums", BankAccountTypeEnum.toList()); model.addAttribute("CardTypeEnums", CardTypeEnum.toList()); model.addAttribute("rpUserBankAccount", rpUserBankAccount); model.addAttribute("rpUserInfo", rpUserInfo); return "pay/config/editBank"; } /** * 函数功能说明 : 更新银行卡信息 * * @参数: @return * @return String * @throws */ @RequiresPermissions("pay:config:edit") @RequestMapping(value = "/editBank", method = RequestMethod.POST) public String editBank(Model model, RpUserBankAccount rpUserBankAccount, DwzAjax dwz) { rpUserBankAccountService.createOrUpdate(rpUserBankAccount); dwz.setStatusCode(DWZ.SUCCESS); dwz.setMessage(DWZ.SUCCESS_MSG); model.addAttribute("dwz", dwz); return DWZ.AJAX_DONE; } }
repos\roncoo-pay-master\roncoo-pay-web-boss\src\main\java\com\roncoo\pay\controller\pay\UserPayConfigController.java
2
请完成以下Java代码
public final class ExchangeMatcherRedirectWebFilter implements WebFilter { private final ServerRedirectStrategy redirectStrategy = new DefaultServerRedirectStrategy(); private final ServerWebExchangeMatcher exchangeMatcher; private final URI redirectUri; /** * Create and initialize an instance of the web filter. * @param exchangeMatcher the exchange matcher * @param redirectUrl the redirect URL */ public ExchangeMatcherRedirectWebFilter(ServerWebExchangeMatcher exchangeMatcher, String redirectUrl) { Assert.notNull(exchangeMatcher, "exchangeMatcher cannot be null"); Assert.hasText(redirectUrl, "redirectUrl cannot be empty"); this.exchangeMatcher = exchangeMatcher; this.redirectUri = URI.create(redirectUrl); }
/** * {@inheritDoc} */ @Override public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) { // @formatter:off return this.exchangeMatcher.matches(exchange) .filter(MatchResult::isMatch) .switchIfEmpty(chain.filter(exchange).then(Mono.empty())) .flatMap((result) -> this.redirectStrategy.sendRedirect(exchange, this.redirectUri)); // @formatter:on } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\ExchangeMatcherRedirectWebFilter.java
1
请完成以下Java代码
public static RemoteCall<Example> deploy(Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { return deployRemoteCall(Example.class, web3j, credentials, gasPrice, gasLimit, BINARY, ""); } public static RemoteCall<Example> deploy(Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { return deployRemoteCall(Example.class, web3j, transactionManager, gasPrice, gasLimit, BINARY, ""); } public RemoteCall<TransactionReceipt> ExampleFunction() { final Function function = new Function( "ExampleFunction", Arrays.<Type>asList(), Collections.<TypeReference<?>>emptyList()); return executeRemoteCallTransaction(function); } public static Example load(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) {
return new Example(contractAddress, web3j, credentials, gasPrice, gasLimit); } public static Example load(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { return new Example(contractAddress, web3j, transactionManager, gasPrice, gasLimit); } protected String getStaticDeployedAddress(String networkId) { return _addresses.get(networkId); } public static String getPreviouslyDeployedAddress(String networkId) { return _addresses.get(networkId); } }
repos\tutorials-master\ethereum\src\main\java\com\baeldung\web3j\contracts\Example.java
1
请完成以下Java代码
public int getLine() { return line; } public void setLine(int line) { this.line = line; } public int getColumn() { return column; } public void setColumn(int column) { this.column = column; } public String getMainElementId() {
return mainElementId; } public void setMainElementId(String mainElementId) { this.mainElementId = mainElementId; } public List<String> getЕlementIds() { return еlementIds; } public void setЕlementIds(List<String> elementIds) { this.еlementIds = elementIds; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\ProblemDto.java
1
请完成以下Spring Boot application配置
spring: application: name: demo-provider # Dubbo 配置项,对应 DubboConfigurationProperties 类 dubbo: scan: base-packages: cn.iocoder.springcloud.labx14.providerdemo.service # 指定 Dubbo 服务实现类的扫描基准包 # Dubbo 服务暴露的协议配置,对应 ProtocolConfig Map protocols: dubbo: name: dubbo # 协议名称 port: -1 # 协议端口,-1 表示自增端口,从 20880 开始 # Dubbo 服务注册中心配置,对应 RegistryConfig 类 registry: address: spr
ing-cloud://127.0.0.1:8848 # 指定 Dubbo 服务注册中心的地址 # Spring Cloud Alibaba Dubbo 专属配置项,对应 DubboCloudProperties 类 cloud: subscribed-services: '' # 设置订阅的应用列表,默认为 * 订阅所有应用。
repos\SpringBoot-Labs-master\labx-14\labx-14-sc-skywalking-dubbo\labx-14-sc-skywalking-dubbo-provider\src\main\resources\application.yaml
2
请完成以下Java代码
int getParentNodeIndex(int index) { return (index - 1) / 2; } int getLeftNodeIndex(int index) { return (2 * index + 1); } int getRightNodeIndex(int index) { return (2 * index + 2); } HeapNode getRootNode() { return heapNodes[0]; } void heapifyFromRoot() { heapify(0); } void swap(int i, int j) { HeapNode temp = heapNodes[i]; heapNodes[i] = heapNodes[j]; heapNodes[j] = temp; } static int[] merge(int[][] array) { HeapNode[] heapNodes = new HeapNode[array.length]; int resultingArraySize = 0; for (int i = 0; i < array.length; i++) {
HeapNode node = new HeapNode(array[i][0], i); heapNodes[i] = node; resultingArraySize += array[i].length; } MinHeap minHeap = new MinHeap(heapNodes); int[] resultingArray = new int[resultingArraySize]; for (int i = 0; i < resultingArraySize; i++) { HeapNode root = minHeap.getRootNode(); resultingArray[i] = root.element; if (root.nextElementIndex < array[root.arrayIndex].length) { root.element = array[root.arrayIndex][root.nextElementIndex++]; } else { root.element = Integer.MAX_VALUE; } minHeap.heapifyFromRoot(); } return resultingArray; } }
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-6\src\main\java\com\baeldung\algorithms\minheapmerge\MinHeap.java
1
请在Spring Boot框架中完成以下Java代码
public SpanCustomizer spanCustomizer(Tracing tracing) { return CurrentSpanCustomizer.create(tracing); } // ==================== HTTP 相关 ==================== /** * Decides how to name and tag spans. By default they are named the same as the http method */ @Bean public HttpTracing httpTracing(Tracing tracing) { return HttpTracing.create(tracing); } /** * Creates server spans for http requests */ @Bean public Filter tracingFilter(HttpTracing httpTracing) { return TracingFilter.create(httpTracing); }
// ==================== SpringMVC 相关 ==================== // @see SpringMvcConfiguration 类上的,@Import(SpanCustomizingAsyncHandlerInterceptor.class) // ==================== HttpClient 相关 ==================== @Bean public RestTemplateCustomizer useTracedHttpClient(HttpTracing httpTracing) { // 创建 CloseableHttpClient 对象,内置 HttpTracing 进行 HTTP 链路追踪。 final CloseableHttpClient httpClient = TracingHttpClientBuilder.create(httpTracing).build(); // 创建 RestTemplateCustomizer 对象 return new RestTemplateCustomizer() { @Override public void customize(RestTemplate restTemplate) { restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory(httpClient)); } }; } }
repos\SpringBoot-Labs-master\lab-40\lab-40-demo\src\main\java\cn\iocoder\springboot\lab40\zipkindemo\config\ZipkinConfiguration.java
2
请完成以下Java代码
private static class TableRecordIdPair { private final int tableId; private final int recordId; public TableRecordIdPair(final int tableId, final int recordId) { super(); this.tableId = tableId; this.recordId = recordId; } public int getTableId() { return tableId; } public int getRecordId() { return recordId; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + recordId; result = prime * result + tableId; return result; } @Override
public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; TableRecordIdPair other = (TableRecordIdPair)obj; if (recordId != other.recordId) return false; if (tableId != other.tableId) return false; return true; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\async\spi\impl\EDIWorkpackageProcessor.java
1
请完成以下Java代码
public org.compiere.model.I_AD_WF_Responsible getAD_WF_Responsible() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_AD_WF_Responsible_ID, org.compiere.model.I_AD_WF_Responsible.class); } @Override public void setAD_WF_Responsible(org.compiere.model.I_AD_WF_Responsible AD_WF_Responsible) { set_ValueFromPO(COLUMNNAME_AD_WF_Responsible_ID, org.compiere.model.I_AD_WF_Responsible.class, AD_WF_Responsible); } /** Set Workflow - Verantwortlicher. @param AD_WF_Responsible_ID Verantwortlicher für die Ausführung des Workflow */ @Override public void setAD_WF_Responsible_ID (int AD_WF_Responsible_ID) { if (AD_WF_Responsible_ID < 1) set_Value (COLUMNNAME_AD_WF_Responsible_ID, null); else set_Value (COLUMNNAME_AD_WF_Responsible_ID, Integer.valueOf(AD_WF_Responsible_ID)); } /** Get Workflow - Verantwortlicher. @return Verantwortlicher für die Ausführung des Workflow */ @Override public int getAD_WF_Responsible_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_WF_Responsible_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Workflow - Verantwortlicher (text). @param AD_WF_Responsible_Name Workflow - Verantwortlicher (text) */ @Override public void setAD_WF_Responsible_Name (java.lang.String AD_WF_Responsible_Name) { set_Value (COLUMNNAME_AD_WF_Responsible_Name, AD_WF_Responsible_Name); } /** Get Workflow - Verantwortlicher (text). @return Workflow - Verantwortlicher (text) */ @Override public java.lang.String getAD_WF_Responsible_Name () { return (java.lang.String)get_Value(COLUMNNAME_AD_WF_Responsible_Name); } /** Set Document Responsible. @param C_Doc_Responsible_ID Document Responsible */ @Override public void setC_Doc_Responsible_ID (int C_Doc_Responsible_ID)
{ if (C_Doc_Responsible_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Doc_Responsible_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Doc_Responsible_ID, Integer.valueOf(C_Doc_Responsible_ID)); } /** Get Document Responsible. @return Document Responsible */ @Override public int getC_Doc_Responsible_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Doc_Responsible_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Datensatz-ID. @param Record_ID Direct internal record ID */ @Override public void setRecord_ID (int Record_ID) { if (Record_ID < 0) set_ValueNoCheck (COLUMNNAME_Record_ID, null); else set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID)); } /** Get Datensatz-ID. @return Direct internal record ID */ @Override public int getRecord_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\workflow\model\X_C_Doc_Responsible.java
1
请完成以下Java代码
public class ArrayIndexOutOfBoundsExceptionDemo { private static Logger LOG = LoggerFactory.getLogger(ArrayIndexOutOfBoundsExceptionDemo.class); public static void main(String[] args) { int[] numbers = new int[] { 1, 2, 3, 4, 5 }; getArrayElementAtIndex(numbers, 5); getListElementAtIndex(5); addArrayElementsUsingLoop(numbers); } public static void addArrayElementsUsingLoop(int[] numbers) { int sum = 0; for (int i = 0; i <= numbers.length; i++) { sum += numbers[i]; } } public static int addArrayElementsUsingLoopInsideTryCatchBlock(int[] numbers) { int sum = 0; try { for (int i = 0; i <= numbers.length; i++) { sum += numbers[i]; } } catch (ArrayIndexOutOfBoundsException e) { LOG.info("Attempted to access an index outside array bounds: {}", e.getMessage());
return -1; } return sum; } public static int getListElementAtIndex(int index) { List<Integer> numbersList = Arrays.asList(1, 2, 3, 4, 5); return numbersList.get(index); } public static int getArrayElementAtIndex(int[] numbers, int index) { return numbers[index]; } }
repos\tutorials-master\core-java-modules\core-java-exceptions-4\src\main\java\com\baeldung\exception\arrayindexoutofbounds\ArrayIndexOutOfBoundsExceptionDemo.java
1
请完成以下Java代码
private I_C_OrderLine createChargeOrderLine(final I_C_Order newOrder, final I_C_Contract_Change changeConditions, final BigDecimal additionalCharge) { final MOrderLine chargeOlPO = new MOrderLine((MOrder)InterfaceWrapperHelper.getPO(newOrder)); final de.metas.interfaces.I_C_OrderLine chargeOl = InterfaceWrapperHelper.create(chargeOlPO, de.metas.interfaces.I_C_OrderLine.class); chargeOlPO.setM_Product_ID(changeConditions.getM_Product_ID()); chargeOlPO.setQtyOrdered(BigDecimal.ONE); chargeOlPO.setQtyEntered(BigDecimal.ONE); chargeOlPO.setPrice(); chargeOl.setIsManualPrice(true); chargeOlPO.setPriceActual(additionalCharge.add(chargeOlPO.getPriceActual())); chargeOlPO.setPriceEntered(additionalCharge.add(chargeOlPO.getPriceEntered())); save(chargeOl); logger.debug("created new order line " + chargeOlPO); return chargeOl; } private BigDecimal computePriceDifference(@NonNull final ContextForCompesationOrder compensationOrderContext, @NonNull final I_C_Contract_Change contractChange) { final List<I_C_SubscriptionProgress> sps = compensationOrderContext.getSubscriptionProgress(); final Timestamp changeDate = compensationOrderContext.getChangeDate(); final List<I_C_SubscriptionProgress> deliveries = sps.stream() .filter(currentSP -> changeDate.after(currentSP.getEventDate()) && X_C_SubscriptionProgress.EVENTTYPE_Delivery.equals(currentSP.getEventType())) .collect(Collectors.toList()); if (deliveries.isEmpty()) { return BigDecimal.ZERO; } final ISubscriptionBL subscriptionBL = Services.get(ISubscriptionBL.class); final I_C_Flatrate_Term currentTerm = compensationOrderContext.getCurrentTerm(); final Properties ctx = InterfaceWrapperHelper.getCtx(currentTerm); final String trxName = InterfaceWrapperHelper.getTrxName(currentTerm); final PricingSystemId pricingSystemId = getPricingSystemId(currentTerm, contractChange);
// compute the difference (see javaDoc of computePriceDifference for details) final BigDecimal difference = subscriptionBL.computePriceDifference(ctx, pricingSystemId, deliveries, trxName); logger.debug("The price difference to be applied on deliveries before the change is " + difference); return difference; } private PricingSystemId getPricingSystemId(final I_C_Flatrate_Term currentTerm, final I_C_Contract_Change changeConditions) { final PricingSystemId pricingSystemId; if (changeConditions.getM_PricingSystem_ID() > 0) { pricingSystemId = PricingSystemId.ofRepoIdOrNull(changeConditions.getM_PricingSystem_ID()); } else { pricingSystemId = PricingSystemId.ofRepoIdOrNull(currentTerm.getC_Flatrate_Conditions().getM_PricingSystem_ID()); } return pricingSystemId; } @Override public void endContract(@NonNull final I_C_Flatrate_Term currentTerm) { currentTerm.setIsAutoRenew(false); currentTerm.setContractStatus(X_C_Flatrate_Term.CONTRACTSTATUS_EndingContract); save(currentTerm); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\impl\ContractChangeBL.java
1
请完成以下Java代码
public class ServletEndpointDiscoverer extends EndpointDiscoverer<ExposableServletEndpoint, Operation> implements ServletEndpointsSupplier { private final @Nullable List<PathMapper> endpointPathMappers; /** * Create a new {@link ServletEndpointDiscoverer} instance. * @param applicationContext the source application context * @param endpointPathMappers the endpoint path mappers * @param filters filters to apply */ public ServletEndpointDiscoverer(ApplicationContext applicationContext, @Nullable List<PathMapper> endpointPathMappers, Collection<EndpointFilter<ExposableServletEndpoint>> filters) { super(applicationContext, ParameterValueMapper.NONE, Collections.emptyList(), filters, Collections.emptyList()); this.endpointPathMappers = endpointPathMappers; } @Override protected boolean isEndpointTypeExposed(Class<?> beanType) { return MergedAnnotations.from(beanType, SearchStrategy.SUPERCLASS).isPresent(ServletEndpoint.class); } @Override protected ExposableServletEndpoint createEndpoint(Object endpointBean, EndpointId id, Access defaultAccess, Collection<Operation> operations) { String rootPath = PathMapper.getRootPath(this.endpointPathMappers, id); return new DiscoveredServletEndpoint(this, endpointBean, id, rootPath, defaultAccess); } @Override protected Operation createOperation(EndpointId endpointId, DiscoveredOperationMethod operationMethod, OperationInvoker invoker) { throw new IllegalStateException("ServletEndpoints must not declare operations"); } @Override protected OperationKey createOperationKey(Operation operation) {
throw new IllegalStateException("ServletEndpoints must not declare operations"); } @Override protected boolean isInvocable(ExposableServletEndpoint endpoint) { return true; } static class ServletEndpointDiscovererRuntimeHints implements RuntimeHintsRegistrar { @Override public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) { hints.reflection().registerType(ServletEndpointFilter.class, MemberCategory.INVOKE_DECLARED_CONSTRUCTORS); } } }
repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\endpoint\web\annotation\ServletEndpointDiscoverer.java
1
请完成以下Java代码
private XmlXtraDrug createXmlXtraDrug(@Nullable final XtraDrugType xtraDrug) { if (xtraDrug == null) { return null; } final XmlXtraDrugBuilder xXtraDrug = XmlXtraDrug.builder(); xXtraDrug.indicated(xtraDrug.isIndicated()); xXtraDrug.iocmCategory(xtraDrug.getIocmCategory()); xXtraDrug.delivery(xtraDrug.getDelivery()); xXtraDrug.regulationAttributes(xtraDrug.getRegulationAttributes()); xXtraDrug.limitation(xtraDrug.isLimitation()); return xXtraDrug.build(); } private ImmutableList<XmlDocument> createXmlDocuments(@Nullable final DocumentsType documents) { if (documents == null) { return ImmutableList.of(); } final ImmutableList.Builder<XmlDocument> xDocuments = ImmutableList.builder(); for (final DocumentType document : documents.getDocument()) { xDocuments.add(createXmlDocument(document)); } return xDocuments.build(); }
private XmlDocument createXmlDocument(@NonNull final DocumentType documentType) { final XmlDocumentBuilder xDocument = XmlDocument.builder(); xDocument.filename(documentType.getFilename()); xDocument.mimeType(documentType.getMimeType()); xDocument.title(documentType.getTitle()); xDocument.base64(documentType.getBase64()); xDocument.url(documentType.getUrl()); return xDocument.build(); } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_450_request\src\main\java\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_450\Invoice450ToCrossVersionModelTool.java
1
请在Spring Boot框架中完成以下Java代码
public static final class Builder extends RelyingPartyRegistration.AssertingPartyDetails.Builder { private EntityDescriptor descriptor; private Builder(EntityDescriptor descriptor) { this.descriptor = descriptor; } /** * {@inheritDoc} */ @Override public Builder entityId(String entityId) { return (Builder) super.entityId(entityId); } /** * {@inheritDoc} */ @Override public Builder wantAuthnRequestsSigned(boolean wantAuthnRequestsSigned) { return (Builder) super.wantAuthnRequestsSigned(wantAuthnRequestsSigned); } /** * {@inheritDoc} */ @Override public Builder signingAlgorithms(Consumer<List<String>> signingMethodAlgorithmsConsumer) { return (Builder) super.signingAlgorithms(signingMethodAlgorithmsConsumer); } /** * {@inheritDoc} */ @Override public Builder verificationX509Credentials(Consumer<Collection<Saml2X509Credential>> credentialsConsumer) { return (Builder) super.verificationX509Credentials(credentialsConsumer); } /** * {@inheritDoc} */ @Override public Builder encryptionX509Credentials(Consumer<Collection<Saml2X509Credential>> credentialsConsumer) { return (Builder) super.encryptionX509Credentials(credentialsConsumer); } /** * {@inheritDoc} */ @Override public Builder singleSignOnServiceLocation(String singleSignOnServiceLocation) { return (Builder) super.singleSignOnServiceLocation(singleSignOnServiceLocation); }
/** * {@inheritDoc} */ @Override public Builder singleSignOnServiceBinding(Saml2MessageBinding singleSignOnServiceBinding) { return (Builder) super.singleSignOnServiceBinding(singleSignOnServiceBinding); } /** * {@inheritDoc} */ @Override public Builder singleLogoutServiceLocation(String singleLogoutServiceLocation) { return (Builder) super.singleLogoutServiceLocation(singleLogoutServiceLocation); } /** * {@inheritDoc} */ @Override public Builder singleLogoutServiceResponseLocation(String singleLogoutServiceResponseLocation) { return (Builder) super.singleLogoutServiceResponseLocation(singleLogoutServiceResponseLocation); } /** * {@inheritDoc} */ @Override public Builder singleLogoutServiceBinding(Saml2MessageBinding singleLogoutServiceBinding) { return (Builder) super.singleLogoutServiceBinding(singleLogoutServiceBinding); } /** * Build an * {@link org.springframework.security.saml2.provider.service.registration.OpenSamlAssertingPartyDetails} * @return */ @Override public OpenSamlAssertingPartyDetails build() { return new OpenSamlAssertingPartyDetails(super.build(), this.descriptor); } } }
repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\provider\service\registration\OpenSamlAssertingPartyDetails.java
2
请在Spring Boot框架中完成以下Java代码
public class ScrubResponseGatewayFilterFactory extends AbstractGatewayFilterFactory<ScrubResponseGatewayFilterFactory.Config> { final Logger logger = LoggerFactory.getLogger(ScrubResponseGatewayFilterFactory.class); private ModifyResponseBodyGatewayFilterFactory modifyResponseBodyFilterFactory; public ScrubResponseGatewayFilterFactory(ModifyResponseBodyGatewayFilterFactory modifyResponseBodyFilterFactory) { super(Config.class); this.modifyResponseBodyFilterFactory = modifyResponseBodyFilterFactory; } @Override public List<String> shortcutFieldOrder() { return Arrays.asList("fields", "replacement"); } @Override public GatewayFilter apply(Config config) { return modifyResponseBodyFilterFactory .apply(c -> c.setRewriteFunction(JsonNode.class, JsonNode.class, new Scrubber(config))); } public static class Config { private String fields; private String replacement; public String getFields() { return fields; } public void setFields(String fields) { this.fields = fields; } public String getReplacement() { return replacement; } public void setReplacement(String replacement) { this.replacement = replacement; } } public static class Scrubber implements RewriteFunction<JsonNode,JsonNode> { private final Pattern fields; private final String replacement; public Scrubber(Config config) { this.fields = Pattern.compile(config.getFields()); this.replacement = config.getReplacement(); } @Override public Publisher<JsonNode> apply(ServerWebExchange t, JsonNode u) { return Mono.just(scrubRecursively(u));
} private JsonNode scrubRecursively(JsonNode u) { if ( !u.isContainerNode()) { return u; } if ( u.isObject()) { ObjectNode node = (ObjectNode)u; node.fields().forEachRemaining((f) -> { if ( fields.matcher(f.getKey()).matches() && f.getValue().isTextual()) { f.setValue(TextNode.valueOf(replacement)); } else { f.setValue(scrubRecursively(f.getValue())); } }); } else if ( u.isArray()) { ArrayNode array = (ArrayNode)u; for ( int i = 0 ; i < array.size() ; i++ ) { array.set(i, scrubRecursively(array.get(i))); } } return u; } } }
repos\tutorials-master\spring-cloud-modules\spring-cloud-gateway-2\src\main\java\com\baeldung\springcloudgateway\customfilters\gatewayapp\filters\factories\ScrubResponseGatewayFilterFactory.java
2
请完成以下Java代码
public class SupplyRequiredHandlerUtils { private final MainDataRequestHandler mainDataRequestHandler = new MainDataRequestHandler(); @NonNull public static MaterialRequest mkRequest( @NonNull final SupplyRequiredDescriptor supplyRequiredDescriptor, @NonNull final MaterialPlanningContext context) { return MaterialRequest.builder() .qtyToSupply(getQuantity(supplyRequiredDescriptor)) .context(context) .mrpDemandBPartnerId(BPartnerId.toRepoIdOr(supplyRequiredDescriptor.getCustomerId(), -1)) .mrpDemandOrderLineSOId(supplyRequiredDescriptor.getOrderLineId()) .mrpDemandShipmentScheduleId(supplyRequiredDescriptor.getShipmentScheduleId()) .demandDate(supplyRequiredDescriptor.getDemandDate()) .isSimulated(supplyRequiredDescriptor.isSimulated()) .build(); } private static @NonNull Quantity getQuantity(final @NonNull SupplyRequiredDescriptor supplyRequiredDescriptor) { final IProductBL productBL = Services.get(IProductBL.class); final ProductId productId = ProductId.ofRepoId(supplyRequiredDescriptor.getProductId()); final BigDecimal qtyToSupplyBD = supplyRequiredDescriptor.getQtyToSupplyBD(); final I_C_UOM uom = productBL.getStockUOM(productId); return Quantity.of(qtyToSupplyBD, uom); } public void updateQtySupplyRequired( @NonNull final MaterialDescriptor materialDescriptor, @NonNull final EventDescriptor eventDescriptor, @NonNull final BigDecimal qtySupplyRequiredDelta) {
if (qtySupplyRequiredDelta.signum() == 0) { return; } final IOrgDAO orgDAO = Services.get(IOrgDAO.class); final ZoneId orgTimezone = orgDAO.getTimeZone(eventDescriptor.getOrgId()); final MainDataRecordIdentifier mainDataRecordIdentifier = MainDataRecordIdentifier.createForMaterial(materialDescriptor, orgTimezone); mainDataRequestHandler.handleDataUpdateRequest( UpdateMainDataRequest.builder() .identifier(mainDataRecordIdentifier) .qtySupplyRequired(qtySupplyRequiredDelta) .build() ); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\planning\src\main\java\de\metas\material\planning\event\SupplyRequiredHandlerUtils.java
1
请在Spring Boot框架中完成以下Java代码
AuthoritiesConverter realmRolesAuthoritiesConverter() { return claims -> { final var realmAccess = Optional.ofNullable((Map<String, Object>) claims.get("realm_access")); final var roles = realmAccess.flatMap(map -> Optional.ofNullable((List<String>) map.get("roles"))); return roles.map(List::stream).orElse(Stream.empty()).map(SimpleGrantedAuthority::new) .map(GrantedAuthority.class::cast).toList(); }; } @Bean JwtAuthenticationConverter authenticationConverter(AuthoritiesConverter authoritiesConverter) { JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter(); jwtAuthenticationConverter .setJwtGrantedAuthoritiesConverter(jwt -> authoritiesConverter.convert(jwt.getClaims())); return jwtAuthenticationConverter; } @Bean SecurityFilterChain resourceServerSecurityFilterChain(HttpSecurity http,
Converter<Jwt, AbstractAuthenticationToken> jwtAuthenticationConverter) throws Exception { http.oauth2ResourceServer(resourceServer -> { resourceServer.jwt(jwtDecoder -> { jwtDecoder.jwtAuthenticationConverter(jwtAuthenticationConverter); }); }); http.sessionManagement(sessions -> { sessions.sessionCreationPolicy(SessionCreationPolicy.STATELESS); }).csrf(csrf -> { csrf.disable(); }); http.authorizeHttpRequests(requests -> { requests.requestMatchers("/me").authenticated(); requests.anyRequest().denyAll(); }); return http.build(); } }
repos\tutorials-master\spring-boot-modules\spring-boot-keycloak\spring-boot-resource-server\src\main\java\com\baeldung\boot\keycloak\resourceserver\SecurityConfig.java
2
请完成以下Java代码
protected Properties getDelegate() { return getActualContext(); } private static final long serialVersionUID = 0; }; private final Properties serverCtx; public WebRestApiContextProvider() { // // Create the server context serverCtx = new Properties(); Env.setContext(serverCtx, CTXNAME_IsServerContext, true); Env.setContext(serverCtx, CTXNAME_IsWebUI, true); } @Override public void init() { // nothing to do here } @Override public Properties getContext() { return ctxProxy; } private Properties getActualContext() { // // IMPORTANT: this method will be called very often, so please make sure it's FAST! // // // If there is currently a temporary context active, return it first final Properties temporaryCtx = temporaryCtxHolder.get(); if (temporaryCtx != null) { logger.trace("Returning temporary context: {}", temporaryCtx); return temporaryCtx; } // // Get the context from current session final UserSession userSession = UserSession.getCurrentOrNull(); if (userSession != null) { final Properties userSessionCtx = userSession.getCtx(); logger.trace("Returning user session context: {}", userSessionCtx); return userSessionCtx; } // // If there was no current session it means we are running on server side, so return the server context logger.trace("Returning server context: {}", serverCtx); return serverCtx; } @Override public IAutoCloseable switchContext(@NonNull final Properties ctx) { // If we were asked to set the context proxy (the one which we are returning everytime), // then it's better to do nothing because this could end in a StackOverflowException. if (ctx == ctxProxy) { logger.trace("Not switching context because the given temporary context it's actually our context proxy: {}", ctx); return NullAutoCloseable.instance; }
final Properties previousTempCtx = temporaryCtxHolder.get(); temporaryCtxHolder.set(ctx); logger.trace("Switched to temporary context. \n New temporary context: {} \n Previous temporary context: {}", ctx, previousTempCtx); return new IAutoCloseable() { private boolean closed = false; @Override public void close() { if (closed) { return; } if (previousTempCtx != null) { temporaryCtxHolder.set(previousTempCtx); } else { temporaryCtxHolder.remove(); } closed = true; logger.trace("Switched back from temporary context"); } }; } @Override public void reset() { temporaryCtxHolder.remove(); serverCtx.clear(); logger.debug("Reset done"); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\session\WebRestApiContextProvider.java
1
请在Spring Boot框架中完成以下Java代码
public Queue orderQueue() { return new Queue(QueueEnum.QUEUE_ORDER_CANCEL.getName()); } /** * 订单延迟队列(死信队列) */ @Bean public Queue orderTtlQueue() { return QueueBuilder .durable(QueueEnum.QUEUE_TTL_ORDER_CANCEL.getName()) .withArgument("x-dead-letter-exchange", QueueEnum.QUEUE_ORDER_CANCEL.getExchange())//到期后转发的交换机 .withArgument("x-dead-letter-routing-key", QueueEnum.QUEUE_ORDER_CANCEL.getRouteKey())//到期后转发的路由键 .build(); } /** * 将订单队列绑定到交换机 */ @Bean
Binding orderBinding(DirectExchange orderDirect,Queue orderQueue){ return BindingBuilder .bind(orderQueue) .to(orderDirect) .with(QueueEnum.QUEUE_ORDER_CANCEL.getRouteKey()); } /** * 将订单延迟队列绑定到交换机 */ @Bean Binding orderTtlBinding(DirectExchange orderTtlDirect,Queue orderTtlQueue){ return BindingBuilder .bind(orderTtlQueue) .to(orderTtlDirect) .with(QueueEnum.QUEUE_TTL_ORDER_CANCEL.getRouteKey()); } }
repos\mall-master\mall-portal\src\main\java\com\macro\mall\portal\config\RabbitMqConfig.java
2
请完成以下Java代码
public void afterUpdate(EntryEvent<K, V> event) { processEntryEvent(event, EntryEventType.UPDATE); } protected void processEntryEvent(EntryEvent<K, V> event, EntryEventType eventType) { } @Override public void afterRegionClear(RegionEvent<K, V> event) { processRegionEvent(event, RegionEventType.CLEAR); } @Override public void afterRegionCreate(RegionEvent<K, V> event) { processRegionEvent(event, RegionEventType.CREATE); } @Override public void afterRegionDestroy(RegionEvent<K, V> event) { processRegionEvent(event, RegionEventType.DESTROY); } @Override public void afterRegionInvalidate(RegionEvent<K, V> event) { processRegionEvent(event, RegionEventType.INVALIDATE); } @Override
public void afterRegionLive(RegionEvent<K, V> event) { processRegionEvent(event, RegionEventType.LIVE); } protected void processRegionEvent(RegionEvent<K, V> event, RegionEventType eventType) { } public enum EntryEventType { CREATE, DESTROY, INVALIDATE, UPDATE; } public enum RegionEventType { CLEAR, CREATE, DESTROY, INVALIDATE, LIVE; } }
repos\spring-boot-data-geode-main\spring-geode-project\apache-geode-extensions\src\main\java\org\springframework\geode\cache\AbstractCommonEventProcessingCacheListener.java
1
请完成以下Java代码
public class DatasourceConfig implements Serializable { /** * 主键 */ @Id @Column(name = "`id`") @GeneratedValue(generator = "JDBC") private Long id; /** * 数据库地址 */ @Column(name = "`host`") private String host; /** * 数据库端口 */ @Column(name = "`port`") private Integer port; /** * 数据库用户名 */ @Column(name = "`username`") private String username; /**
* 数据库密码 */ @Column(name = "`password`") private String password; /** * 数据库名称 */ @Column(name = "`database`") private String database; /** * 构造JDBC URL * * @return JDBC URL */ public String buildJdbcUrl() { return String.format("jdbc:mysql://%s:%s/%s?useUnicode=true&characterEncoding=utf-8&useSSL=false", this.host, this.port, this.database); } }
repos\spring-boot-demo-master\demo-dynamic-datasource\src\main\java\com\xkcoding\dynamic\datasource\model\DatasourceConfig.java
1
请完成以下Java代码
public Integer[] getBestPath() { assert (vertexCount > 2); Stack<Integer> stack = new Stack<Integer>(); int curNode = vertexCount - 1, curIndex = 0; QueueElement element; element = fromArray[curNode - 1][curIndex].GetFirst(); stack.push(curNode); stack.push(element.from); curNode = element.from; while (curNode != 0) { element = fromArray[element.from - 1][element.index].GetFirst(); stack.push(element.from); curNode = element.from; } return (Integer[]) stack.toArray(); } /** * 从短到长获取至多 n 条路径 * @param n * @return */ public List<int[]> getNPaths(int n) { List<int[]> result = new ArrayList<int[]>(); n = Math.min(Predefine.MAX_SEGMENT_NUM, n); for (int i = 0; i < N && result.size() < n; ++i)
{ List<int[]> pathList = getPaths(i); for (int[] path : pathList) { if (result.size() == n) break; result.add(path); } } return result; } /** * 获取前10条最短路径 * @return */ public List<int[]> getNPaths() { return getNPaths(Predefine.MAX_SEGMENT_NUM); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\seg\NShort\Path\NShortPath.java
1
请完成以下Java代码
public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public Integer getAge() { return age;
} public void setAge(Integer age) { this.age = age; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } }
repos\tutorials-master\spring-cloud-modules\spring-cloud-security\auth-resource\src\main\java\com\baeldung\model\Person.java
1
请完成以下Java代码
public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Date getDueDate() { return dueDate; } public void setDueDate(Date dueDate) { this.dueDate = dueDate; } public Date getFollowUpDate() { return followUpDate; } public void setFollowUpDate(Date followUpDate) { this.followUpDate = followUpDate; } public int getPriority() { return priority; } public void setPriority(int priority) { this.priority = priority; } public String getParentTaskId() { return parentTaskId; } public void setParentTaskId(String parentTaskId) { this.parentTaskId = parentTaskId; } public void setDeleteReason(final String deleteReason) { this.deleteReason = deleteReason; } public void setTaskId(String taskId) { this.taskId = taskId; } public String getTaskId() { return taskId; } public String getTaskDefinitionKey() { return taskDefinitionKey; } public void setTaskDefinitionKey(String taskDefinitionKey) { this.taskDefinitionKey = taskDefinitionKey; } public String getActivityInstanceId() { return activityInstanceId; } public void setActivityInstanceId(String activityInstanceId) { this.activityInstanceId = activityInstanceId; } public String getTenantId() { return tenantId; }
public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getTaskState() { return taskState; } public void setTaskState(String taskState) { this.taskState = taskState; } public String getRootProcessInstanceId() { return rootProcessInstanceId; } public void setRootProcessInstanceId(String rootProcessInstanceId) { this.rootProcessInstanceId = rootProcessInstanceId; } @Override public String toString() { return this.getClass().getSimpleName() + "[taskId" + taskId + ", assignee=" + assignee + ", owner=" + owner + ", name=" + name + ", description=" + description + ", dueDate=" + dueDate + ", followUpDate=" + followUpDate + ", priority=" + priority + ", parentTaskId=" + parentTaskId + ", deleteReason=" + deleteReason + ", taskDefinitionKey=" + taskDefinitionKey + ", durationInMillis=" + durationInMillis + ", startTime=" + startTime + ", endTime=" + endTime + ", id=" + id + ", eventType=" + eventType + ", executionId=" + executionId + ", processDefinitionId=" + processDefinitionId + ", rootProcessInstanceId=" + rootProcessInstanceId + ", processInstanceId=" + processInstanceId + ", activityInstanceId=" + activityInstanceId + ", tenantId=" + tenantId + ", taskState=" + taskState + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricTaskInstanceEventEntity.java
1
请在Spring Boot框架中完成以下Java代码
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth .inMemoryAuthentication() .withUser("user1") .password(passwordEncoder().encode("user1Pass")) .authorities("ROLE_USER"); } @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/securityNone") .permitAll() .anyRequest()
.authenticated() .and() .httpBasic() .authenticationEntryPoint(authenticationEntryPoint); http.addFilterAfter(new CustomFilter(), BasicAuthenticationFilter.class); return http.build(); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } }
repos\tutorials-master\apache-httpclient4\src\main\java\com\baeldung\filter\CustomWebSecurityConfigurerAdapter.java
2
请完成以下Java代码
public static Object getTarget(Object proxy) throws Exception { if (!AopUtils.isAopProxy(proxy)) { return proxy;//不是代理对象 } if (AopUtils.isJdkDynamicProxy(proxy)) { return getJdkDynamicProxyTargetObject(proxy); } else { //cglib return getCglibProxyTargetObject(proxy); } } private static Object getCglibProxyTargetObject(Object proxy) throws Exception { Field h = proxy.getClass().getDeclaredField("CGLIB$CALLBACK_0"); h.setAccessible(true); Object dynamicAdvisedInterceptor = h.get(proxy);
Field advised = dynamicAdvisedInterceptor.getClass().getDeclaredField("advised"); advised.setAccessible(true); Object target = ((AdvisedSupport) advised.get(dynamicAdvisedInterceptor)).getTargetSource().getTarget(); return target; } private static Object getJdkDynamicProxyTargetObject(Object proxy) throws Exception { Field h = proxy.getClass().getSuperclass().getDeclaredField("h"); h.setAccessible(true); AopProxy aopProxy = (AopProxy) h.get(proxy); Field advised = aopProxy.getClass().getDeclaredField("advised"); advised.setAccessible(true); Object target = ((AdvisedSupport) advised.get(aopProxy)).getTargetSource().getTarget(); return target; } }
repos\spring-boot-student-master\spring-boot-student-cache-redis\src\main\java\com\xiaolyuh\redis\utils\ReflectionUtils.java
1
请完成以下Java代码
private static final class CompositeOLCandValidator implements IOLCandValidator { private final ImmutableList<IOLCandValidator> validators; private final IErrorManager errorManager; private CompositeOLCandValidator(@NonNull final List<IOLCandValidator> validators, @NonNull final IErrorManager errorManager) { this.validators = ImmutableList.copyOf(validators); this.errorManager = errorManager; } /** @return {@code 0}. Actually, it doesn't matte for this validator. */ @Override public int getSeqNo() { return 0; } /** * Change {@link I_C_OLCand#COLUMN_IsError IsError}, {@link I_C_OLCand#COLUMN_ErrorMsg ErrorMsg}, * {@link I_C_OLCand#COLUMNNAME_AD_Issue_ID ADIssueID} accordingly, but <b>do not</b> save. */ @Override public void validate(@NonNull final I_C_OLCand olCand) { for (final IOLCandValidator olCandValdiator : validators) { try { olCandValdiator.validate(olCand); } catch (final Exception e) { final AdempiereException me = AdempiereException .wrapIfNeeded(e) .appendParametersToMessage() .setParameter("OLCandValidator", olCandValdiator.getClass().getSimpleName()); olCand.setIsError(true); olCand.setErrorMsg(me.getLocalizedMessage());
final AdIssueId issueId = errorManager.createIssue(e); olCand.setAD_Issue_ID(issueId.getRepoId()); olCand.setErrorMsgJSON(JsonObjectMapperHolder.toJsonNonNull(JsonErrorItem.builder() .message(me.getLocalizedMessage()) .errorCode(AdempiereException.extractErrorCodeOrNull(me)) .stackTrace(Trace.toOneLineStackTraceString(me.getStackTrace())) .adIssueId(JsonMetasfreshId.of(issueId.getRepoId())) .errorCode(AdempiereException.extractErrorCodeOrNull(me)) .throwable(me) .build())); break; } } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\ordercandidate\api\OLCandSPIRegistry.java
1
请完成以下Java代码
public void setMessageSource(MessageSource messageSource) { this.messages = new MessageSourceAccessor(messageSource); } /** * Only {@code AuthorizationFailureEvent} will be published. If you set this property * to {@code true}, {@code AuthorizedEvent}s will also be published. * @param publishAuthorizationSuccess default value is {@code false} */ public void setPublishAuthorizationSuccess(boolean publishAuthorizationSuccess) { this.publishAuthorizationSuccess = publishAuthorizationSuccess; } /** * By rejecting public invocations (and setting this property to <tt>true</tt>), * essentially you are ensuring that every secure object invocation advised by * <code>AbstractSecurityInterceptor</code> has a configuration attribute defined. * This is useful to ensure a "fail safe" mode where undeclared secure objects will be * rejected and configuration omissions detected early. An * <tt>IllegalArgumentException</tt> will be thrown by the * <tt>AbstractSecurityInterceptor</tt> if you set this property to <tt>true</tt> and * an attempt is made to invoke a secure object that has no configuration attributes. * @param rejectPublicInvocations set to <code>true</code> to reject invocations of * secure objects that have no configuration attributes (by default it is * <code>false</code> which treats undeclared secure objects as "public" or * unauthorized). */ public void setRejectPublicInvocations(boolean rejectPublicInvocations) { this.rejectPublicInvocations = rejectPublicInvocations; } public void setRunAsManager(RunAsManager runAsManager) { this.runAsManager = runAsManager; }
public void setValidateConfigAttributes(boolean validateConfigAttributes) { this.validateConfigAttributes = validateConfigAttributes; } private void publishEvent(ApplicationEvent event) { if (this.eventPublisher != null) { this.eventPublisher.publishEvent(event); } } private static class NoOpAuthenticationManager implements AuthenticationManager { @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { throw new AuthenticationServiceException("Cannot authenticate " + authentication); } } }
repos\spring-security-main\access\src\main\java\org\springframework\security\access\intercept\AbstractSecurityInterceptor.java
1
请完成以下Java代码
public void setHeight(final @Nullable BigDecimal Height) { set_Value(COLUMNNAME_Height, Height); } @Override public BigDecimal getHeight() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Height); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setLength(final @Nullable BigDecimal Length) { set_Value(COLUMNNAME_Length, Length); } @Override public BigDecimal getLength() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Length); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setMaxVolume(final BigDecimal MaxVolume) { set_Value(COLUMNNAME_MaxVolume, MaxVolume); } @Override public BigDecimal getMaxVolume() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_MaxVolume); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setMaxWeight(final BigDecimal MaxWeight) { set_Value(COLUMNNAME_MaxWeight, MaxWeight); } @Override public BigDecimal getMaxWeight() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_MaxWeight); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setM_PackagingContainer_ID(final int M_PackagingContainer_ID) { if (M_PackagingContainer_ID < 1) set_ValueNoCheck(COLUMNNAME_M_PackagingContainer_ID, null); else set_ValueNoCheck(COLUMNNAME_M_PackagingContainer_ID, M_PackagingContainer_ID); } @Override public int getM_PackagingContainer_ID() { return get_ValueAsInt(COLUMNNAME_M_PackagingContainer_ID); } @Override public void setM_Product_ID(final int M_Product_ID) { if (M_Product_ID < 1) set_Value(COLUMNNAME_M_Product_ID, null); else set_Value(COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); }
@Override public void setName(final java.lang.String Name) { set_Value(COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setValue(final @Nullable java.lang.String Value) { set_Value(COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } @Override public void setWidth(final @Nullable BigDecimal Width) { set_Value(COLUMNNAME_Width, Width); } @Override public BigDecimal getWidth() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Width); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_PackagingContainer.java
1
请完成以下Java代码
public class RecoveringDeserializationExceptionHandler implements DeserializationExceptionHandler { /** * Property name for configuring the recoverer using properties. */ public static final String KSTREAM_DESERIALIZATION_RECOVERER = "spring.deserialization.recoverer"; private static final Log LOGGER = LogFactory.getLog(RecoveringDeserializationExceptionHandler.class); private @Nullable ConsumerRecordRecoverer recoverer; public RecoveringDeserializationExceptionHandler() { } public RecoveringDeserializationExceptionHandler(ConsumerRecordRecoverer recoverer) { this.recoverer = recoverer; } @Override public DeserializationHandlerResponse handle(ErrorHandlerContext context, ConsumerRecord<byte[], byte[]> record, Exception exception) { if (this.recoverer == null) { return DeserializationHandlerResponse.FAIL; } try { this.recoverer.accept(record, exception); return DeserializationHandlerResponse.CONTINUE; } catch (RuntimeException e) { LOGGER.error("Recoverer threw an exception; recovery failed", e); return DeserializationHandlerResponse.FAIL; } } @Override public void configure(Map<String, ?> configs) { if (configs.containsKey(KSTREAM_DESERIALIZATION_RECOVERER)) { Object configValue = configs.get(KSTREAM_DESERIALIZATION_RECOVERER); if (configValue instanceof ConsumerRecordRecoverer) { this.recoverer = (ConsumerRecordRecoverer) configValue; } else if (configValue instanceof String) { fromString(configValue); } else if (configValue instanceof Class) { fromClass(configValue); } else {
LOGGER.error("Unknown property type for " + KSTREAM_DESERIALIZATION_RECOVERER + "; failed deserializations cannot be recovered"); } } } private void fromString(Object configValue) throws LinkageError { try { @SuppressWarnings("unchecked") Class<? extends ConsumerRecordRecoverer> clazz = (Class<? extends ConsumerRecordRecoverer>) ClassUtils .forName((String) configValue, RecoveringDeserializationExceptionHandler.class.getClassLoader()); Constructor<? extends ConsumerRecordRecoverer> constructor = clazz.getConstructor(); this.recoverer = constructor.newInstance(); } catch (Exception e) { LOGGER.error("Failed to instantiate recoverer, failed deserializations cannot be recovered", e); } } private void fromClass(Object configValue) { try { @SuppressWarnings("unchecked") Class<? extends ConsumerRecordRecoverer> clazz = (Class<? extends ConsumerRecordRecoverer>) configValue; Constructor<? extends ConsumerRecordRecoverer> constructor = clazz.getConstructor(); this.recoverer = constructor.newInstance(); } catch (Exception e) { LOGGER.error("Failed to instantiate recoverer, failed deserializations cannot be recovered", e); } } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\streams\RecoveringDeserializationExceptionHandler.java
1
请完成以下Java代码
public static void replyingToEmail(Email receivedEmail) { EmailBuilder.replyingTo(receivedEmail) .from("sender@example.com") .prependText("This is a Reply Email. Original email included below:") .buildEmail(); } public static void forwardingEmail(Email receivedEmail) { Email email = EmailBuilder.forwarding(receivedEmail) .from("sender@example.com") .prependText("This is an Forward Email. See below email:") .buildEmail(); } public static void handleExceptionWhenSendingEmail() { try { sendPlainTextEmail(); System.out.println("Email sent successfully!"); } catch (MailException e) { System.err.println("Error: " + e.getMessage()); } } public static void setCustomHeaderWhenSendingEmail() { Email email = EmailBuilder.startingBlank() .from("sender@example.com") .to("recipient@example.com") .withSubject("Email with Custom Header") .withPlainText("This is an important message.") .withHeader("X-Priority", "1")
.buildEmail(); sendEmail(email); } private static void sendEmailWithDeliveryReadRecipient() { Email email = EmailBuilder.startingBlank() .from("sender@example.com") .to("recipient@example.com") .withSubject("Email with Delivery/Read Receipt Configured!") .withPlainText("This is an email sending with delivery/read receipt.") .withDispositionNotificationTo(new Recipient("name", "address@domain.com", Message.RecipientType.TO)) .withReturnReceiptTo(new Recipient("name", "address@domain.com", Message.RecipientType.TO)) .buildEmail(); sendEmail(email); } private static void sendEmail(Email email) { Mailer mailer = MailerBuilder.withSMTPServer("smtp.example.com", 25, "username", "password") .withMaximumEmailSize(1024 * 1024 * 5) // 5 Megabytes .buildMailer(); boolean validate = mailer.validate(email); if (validate) { mailer.sendMail(email); } else { System.out.println("Invalid email address."); } } }
repos\tutorials-master\libraries-io\src\main\java\com\baeldung\java\io\simplemail\SimpleMailExample.java
1
请完成以下Java代码
public org.compiere.model.I_C_ValidCombination getP_WIP_A() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_P_WIP_Acct, org.compiere.model.I_C_ValidCombination.class); } @Override public void setP_WIP_A(org.compiere.model.I_C_ValidCombination P_WIP_A) { set_ValueFromPO(COLUMNNAME_P_WIP_Acct, org.compiere.model.I_C_ValidCombination.class, P_WIP_A); } /** Set Work In Process. @param P_WIP_Acct The Work in Process account is the account used Manufacturing Order */ @Override public void setP_WIP_Acct (int P_WIP_Acct)
{ set_Value (COLUMNNAME_P_WIP_Acct, Integer.valueOf(P_WIP_Acct)); } /** Get Work In Process. @return The Work in Process account is the account used Manufacturing Order */ @Override public int getP_WIP_Acct () { Integer ii = (Integer)get_Value(COLUMNNAME_P_WIP_Acct); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Product_Acct.java
1
请完成以下Java代码
public class AssignTasksPayload implements Payload { private String id; private List<String> taskIds; private String assignee; public AssignTasksPayload() { this.id = UUID.randomUUID().toString(); } public AssignTasksPayload(List<String> taskIds, String assignee) { this(); this.taskIds = taskIds; this.assignee = assignee; } @Override public String getId() { return id; }
public List<String> getTaskIds() { return taskIds; } public void setTaskIds(List<String> taskIds) { this.taskIds = taskIds; } public String getAssignee() { return assignee; } public void setAssignee(String assignee) { this.assignee = assignee; } }
repos\Activiti-develop\activiti-api\activiti-api-task-model\src\main\java\org\activiti\api\task\model\payloads\AssignTasksPayload.java
1
请在Spring Boot框架中完成以下Java代码
public List<DeployHistoryDto> queryAll(DeployHistoryQueryCriteria criteria){ return deployhistoryMapper.toDto(deployhistoryRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder))); } @Override public DeployHistoryDto findById(String id) { DeployHistory deployhistory = deployhistoryRepository.findById(id).orElseGet(DeployHistory::new); ValidationUtil.isNull(deployhistory.getId(),"DeployHistory","id",id); return deployhistoryMapper.toDto(deployhistory); } @Override @Transactional(rollbackFor = Exception.class) public void create(DeployHistory resources) { resources.setId(IdUtil.simpleUUID()); deployhistoryRepository.save(resources); } @Override @Transactional(rollbackFor = Exception.class) public void delete(Set<String> ids) { for (String id : ids) { deployhistoryRepository.deleteById(id);
} } @Override public void download(List<DeployHistoryDto> queryAll, HttpServletResponse response) throws IOException { List<Map<String, Object>> list = new ArrayList<>(); for (DeployHistoryDto deployHistoryDto : queryAll) { Map<String,Object> map = new LinkedHashMap<>(); map.put("部署编号", deployHistoryDto.getDeployId()); map.put("应用名称", deployHistoryDto.getAppName()); map.put("部署IP", deployHistoryDto.getIp()); map.put("部署时间", deployHistoryDto.getDeployDate()); map.put("部署人员", deployHistoryDto.getDeployUser()); list.add(map); } FileUtil.downloadExcel(list, response); } }
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\maint\service\impl\DeployHistoryServiceImpl.java
2
请完成以下Java代码
public void setDescription (final @Nullable java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setESR_PostBank (final boolean ESR_PostBank) { set_Value (COLUMNNAME_ESR_PostBank, ESR_PostBank); } @Override public boolean isESR_PostBank() { return get_ValueAsBoolean(COLUMNNAME_ESR_PostBank); } @Override public void setIsCashBank (final boolean IsCashBank) { set_Value (COLUMNNAME_IsCashBank, IsCashBank); } @Override public boolean isCashBank() { return get_ValueAsBoolean(COLUMNNAME_IsCashBank); } @Override public void setIsImportAsSingleSummaryLine (final boolean IsImportAsSingleSummaryLine) { set_Value (COLUMNNAME_IsImportAsSingleSummaryLine, IsImportAsSingleSummaryLine); } @Override public boolean isImportAsSingleSummaryLine() { return get_ValueAsBoolean(COLUMNNAME_IsImportAsSingleSummaryLine); } @Override public void setIsOwnBank (final boolean IsOwnBank) { set_Value (COLUMNNAME_IsOwnBank, IsOwnBank); } @Override public boolean isOwnBank() { return get_ValueAsBoolean(COLUMNNAME_IsOwnBank);
} @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setRoutingNo (final java.lang.String RoutingNo) { set_Value (COLUMNNAME_RoutingNo, RoutingNo); } @Override public java.lang.String getRoutingNo() { return get_ValueAsString(COLUMNNAME_RoutingNo); } @Override public void setSwiftCode (final @Nullable java.lang.String SwiftCode) { set_Value (COLUMNNAME_SwiftCode, SwiftCode); } @Override public java.lang.String getSwiftCode() { return get_ValueAsString(COLUMNNAME_SwiftCode); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Bank.java
1
请完成以下Java代码
private static class ShippingInfoCache { private final IShipmentScheduleBL shipmentScheduleBL; private final IShipmentScheduleEffectiveBL scheduleEffectiveBL; private final IShipperDAO shipperDAO; private final HashMap<ShipmentScheduleId, I_M_ShipmentSchedule> shipmentSchedulesById = new HashMap<>(); private final HashMap<String, I_M_Shipper> shipperByInternalName = new HashMap<>(); @Builder private ShippingInfoCache( @NonNull final IShipmentScheduleBL shipmentScheduleBL, @NonNull final IShipmentScheduleEffectiveBL scheduleEffectiveBL, @NonNull final IShipperDAO shipperDAO) { this.shipmentScheduleBL = shipmentScheduleBL; this.scheduleEffectiveBL = scheduleEffectiveBL; this.shipperDAO = shipperDAO; } public void warmUpForShipmentScheduleIds(@NonNull final Collection<ShipmentScheduleId> shipmentScheduleIds) { CollectionUtils.getAllOrLoad( shipmentSchedulesById, shipmentScheduleIds, shipmentScheduleBL::getByIds); } public void warmUpForShipperInternalNames(@NonNull final Collection<String> shipperInternalNameCollection) { CollectionUtils.getAllOrLoad( shipperByInternalName, shipperInternalNameCollection, shipperDAO::getByInternalName); } private I_M_ShipmentSchedule getShipmentScheduleById(@NonNull final ShipmentScheduleId shipmentScheduleId) { return shipmentSchedulesById.computeIfAbsent(shipmentScheduleId, shipmentScheduleBL::getById); } public OrgId getOrgId(@NonNull final ShipmentScheduleId shipmentScheduleId) { final I_M_ShipmentSchedule shipmentSchedule = getShipmentScheduleById(shipmentScheduleId); return OrgId.ofRepoId(shipmentSchedule.getAD_Org_ID());
} public BPartnerId getBPartnerId(@NonNull final ShipmentScheduleId shipmentScheduleId) { final I_M_ShipmentSchedule shipmentSchedule = getShipmentScheduleById(shipmentScheduleId); return scheduleEffectiveBL.getBPartnerId(shipmentSchedule); } @Nullable public ShipperId getShipperId(@Nullable final String shipperInternalName) { if (Check.isBlank(shipperInternalName)) { return null; } final I_M_Shipper shipper = shipperByInternalName.computeIfAbsent(shipperInternalName, this::loadShipper); return shipper != null ? ShipperId.ofRepoId(shipper.getM_Shipper_ID()) : null; } @Nullable public String getTrackingURL(@NonNull final String shipperInternalName) { final I_M_Shipper shipper = shipperByInternalName.computeIfAbsent(shipperInternalName, this::loadShipper); return shipper != null ? shipper.getTrackingURL() : null; } @Nullable private I_M_Shipper loadShipper(@NonNull final String shipperInternalName) { return shipperDAO.getByInternalName(ImmutableSet.of(shipperInternalName)).get(shipperInternalName); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v1\shipping\ShipmentService.java
1
请完成以下Java代码
protected void onStartUp(Set<Class<?>> c, String contextPath, Class<?> servletProcessApplicationClass, Consumer<String> processApplicationClassNameConsumer) throws Exception { if (c == null || c.isEmpty()) { // skip deployments that do not carry a PA return; } if (c.contains(ProcessApplication.class)) { // copy into a fresh Set as we don't know if the original Set is mutable or immutable c = new HashSet<>(c); // and now remove the annotation itself c.remove(ProcessApplication.class); } if (c.size() > 1) { // a deployment must only contain a single PA throw getServletException(LOG.multiplePasException(c, contextPath)); } else if (c.size() == 1) { Class<?> paClass = c.iterator().next(); // validate whether it is a legal Process Application
if (!AbstractProcessApplication.class.isAssignableFrom(paClass)) { throw getServletException(LOG.paWrongTypeException(paClass)); } // add it as listener if it's a servlet process application if (servletProcessApplicationClass.isAssignableFrom(paClass)) { LOG.detectedPa(paClass); processApplicationClassNameConsumer.accept(paClass.getName()); } } else { LOG.servletDeployerNoPaFound(contextPath); } } protected abstract Exception getServletException(String message); }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\application\impl\AbstractServletProcessApplicationDeployer.java
1
请完成以下Java代码
/* package */final class SqlDocumentFilterConvertersListWithFallback implements SqlDocumentFilterConverter { public static SqlDocumentFilterConvertersListWithFallback newInstance(final SqlDocumentFilterConvertersList converters, final SqlDocumentFilterConverter defaultConverter) { return new SqlDocumentFilterConvertersListWithFallback(converters, defaultConverter); } private final SqlDocumentFilterConvertersList converters; private final SqlDocumentFilterConverter defaultConverter; private SqlDocumentFilterConvertersListWithFallback(@NonNull final SqlDocumentFilterConvertersList converters, @NonNull final SqlDocumentFilterConverter defaultConverter) { this.converters = converters; this.defaultConverter = defaultConverter; } @Override public boolean canConvert(final String filterId)
{ return true; } @Override public FilterSql getSql( @NonNull final DocumentFilter filter, @NonNull final SqlOptions sqlOpts, @NonNull final SqlDocumentFilterConverterContext context) { // Find the effective converter to be used for given filter final String filterId = filter.getFilterId(); final SqlDocumentFilterConverter effectiveConverter = converters.getConverterOrDefault(filterId, defaultConverter); // Convert the filter to SQL using the effective converter return effectiveConverter.getSql(filter, sqlOpts, context); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\filter\sql\SqlDocumentFilterConvertersListWithFallback.java
1
请完成以下Java代码
public void setC_BPartner_ID (int C_BPartner_ID) { if (C_BPartner_ID < 1) set_ValueNoCheck (COLUMNNAME_C_BPartner_ID, null); else set_ValueNoCheck (COLUMNNAME_C_BPartner_ID, Integer.valueOf(C_BPartner_ID)); } /** Get Business Partner . @return Identifies a Business Partner */ public int getC_BPartner_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_BPartner_ID); if (ii == null) return 0; return ii.intValue(); } public I_C_ValidCombination getC_Prepayment_A() throws RuntimeException { return (I_C_ValidCombination)MTable.get(getCtx(), I_C_ValidCombination.Table_Name) .getPO(getC_Prepayment_Acct(), get_TrxName()); } /** Set Customer Prepayment. @param C_Prepayment_Acct Account for customer prepayments */ public void setC_Prepayment_Acct (int C_Prepayment_Acct) { set_Value (COLUMNNAME_C_Prepayment_Acct, Integer.valueOf(C_Prepayment_Acct)); } /** Get Customer Prepayment. @return Account for customer prepayments */ public int getC_Prepayment_Acct () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Prepayment_Acct); if (ii == null) return 0; return ii.intValue(); } public I_C_ValidCombination getC_Receivable_A() throws RuntimeException { return (I_C_ValidCombination)MTable.get(getCtx(), I_C_ValidCombination.Table_Name) .getPO(getC_Receivable_Acct(), get_TrxName()); } /** Set Customer Receivables. @param C_Receivable_Acct Account for Customer Receivables */ public void setC_Receivable_Acct (int C_Receivable_Acct)
{ set_Value (COLUMNNAME_C_Receivable_Acct, Integer.valueOf(C_Receivable_Acct)); } /** Get Customer Receivables. @return Account for Customer Receivables */ public int getC_Receivable_Acct () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Receivable_Acct); if (ii == null) return 0; return ii.intValue(); } public I_C_ValidCombination getC_Receivable_Services_A() throws RuntimeException { return (I_C_ValidCombination)MTable.get(getCtx(), I_C_ValidCombination.Table_Name) .getPO(getC_Receivable_Services_Acct(), get_TrxName()); } /** Set Receivable Services. @param C_Receivable_Services_Acct Customer Accounts Receivables Services Account */ public void setC_Receivable_Services_Acct (int C_Receivable_Services_Acct) { set_Value (COLUMNNAME_C_Receivable_Services_Acct, Integer.valueOf(C_Receivable_Services_Acct)); } /** Get Receivable Services. @return Customer Accounts Receivables Services Account */ public int getC_Receivable_Services_Acct () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Receivable_Services_Acct); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BP_Customer_Acct.java
1
请完成以下Java代码
public final Connection getConnection() throws SQLException { return delegate.getConnection(); } @Override public final boolean getMoreResults(final int current) throws SQLException { return delegate.getMoreResults(current); } @Override public final ResultSet getGeneratedKeys() throws SQLException { return delegate.getGeneratedKeys(); } @Override public final int executeUpdate(final String sql, final int autoGeneratedKeys) throws SQLException { return trace(sql, () -> delegate.executeUpdate(sql, autoGeneratedKeys)); } @Override public final int executeUpdate(final String sql, final int[] columnIndexes) throws SQLException { return trace(sql, () -> delegate.executeUpdate(sql, columnIndexes)); } @Override public final int executeUpdate(final String sql, final String[] columnNames) throws SQLException { return trace(sql, () -> delegate.executeUpdate(sql, columnNames)); } @Override public final boolean execute(final String sql, final int autoGeneratedKeys) throws SQLException { return trace(sql, () -> delegate.execute(sql, autoGeneratedKeys)); } @Override public final boolean execute(final String sql, final int[] columnIndexes) throws SQLException { return trace(sql, () -> delegate.execute(sql, columnIndexes));
} @Override public final boolean execute(final String sql, final String[] columnNames) throws SQLException { return trace(sql, () -> delegate.execute(sql, columnNames)); } @Override public final int getResultSetHoldability() throws SQLException { return delegate.getResultSetHoldability(); } @Override public final boolean isClosed() throws SQLException { return delegate.isClosed(); } @Override public final void setPoolable(final boolean poolable) throws SQLException { delegate.setPoolable(poolable); } @Override public final boolean isPoolable() throws SQLException { return delegate.isPoolable(); } @Override public final void closeOnCompletion() throws SQLException { delegate.closeOnCompletion(); } @Override public final boolean isCloseOnCompletion() throws SQLException { return delegate.isCloseOnCompletion(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\sql\impl\TracingStatement.java
1
请完成以下Java代码
public I_M_InOutLine getM_InOutLine() { return inoutLine; } @Override public ProductId getProductId() { return ProductId.ofRepoId(inoutLine.getM_Product_ID()); } /** * @returns MovementQty of the wrapped inout line */ @Override public BigDecimal getQty() { return inoutLine.getMovementQty(); } /**
* Sets both MovementQty and QtyEntered of the wrapped order line. * * @param qty MovementQty which will also be converted to QtyEntered. */ @Override protected void setQty(final BigDecimal qty) { inoutLine.setMovementQty(qty); final IUOMConversionBL uomConversionBL = Services.get(IUOMConversionBL.class); final BigDecimal qtyEntered = uomConversionBL.convertFromProductUOM(getProductId(), UomId.ofRepoId(inoutLine.getC_UOM_ID()), qty); inoutLine.setQtyEntered(qtyEntered); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\empties\EmptiesInOutLinePackingMaterialDocumentLine.java
1
请完成以下Java代码
public class InvoicesViewFactory implements IViewFactory, IViewsIndexStorage { static final String WINDOW_ID_String = "invoicesToAllocate"; // FIXME: HARDCODED public static final WindowId WINDOW_ID = WindowId.fromJson(WINDOW_ID_String); public static final String SYSCONFIG_EnablePreparedForAllocationFlag = "de.metas.ui.web.payment_allocation.EnablePreparedForAllocationFlag"; private final IMsgBL msgBL = Services.get(IMsgBL.class); private final PaymentsViewFactory paymentsViewFactory; public InvoicesViewFactory(@NonNull final PaymentsViewFactory paymentsViewFactory) { this.paymentsViewFactory = paymentsViewFactory; } public static boolean isEnablePreparedForAllocationFlag() { final ISysConfigBL sysConfigBL = Services.get(ISysConfigBL.class); return sysConfigBL.getBooleanValue(SYSCONFIG_EnablePreparedForAllocationFlag, false); } @Override public void setViewsRepository(@NonNull final IViewsRepository viewsRepository) { // nothing } @Override public ViewLayout getViewLayout(final WindowId windowId, final JSONViewDataType viewDataType, final ViewProfileId profileId) { final ViewLayout.Builder layoutBuilder = ViewLayout.builder() .setWindowId(WINDOW_ID) .setCaption(msgBL.translatable("InvoicesToAllocate")) .setAllowOpeningRowDetails(false) .addElementsFromViewRowClass(InvoiceRow.class, viewDataType); if (!isEnablePreparedForAllocationFlag()) { layoutBuilder.removeElementByFieldName(InvoiceRow.FIELD_IsPreparedForAllocation); } return layoutBuilder.build(); } @Override public InvoicesView createView(final @NonNull CreateViewRequest request) { throw new UnsupportedOperationException(); } @Override public WindowId getWindowId() { return WINDOW_ID; } @Override public void put(final IView view) { throw new UnsupportedOperationException(); }
@Nullable @Override public InvoicesView getByIdOrNull(final ViewId invoicesViewId) { final ViewId paymentsViewId = toPaymentsViewId(invoicesViewId); final PaymentsView paymentsView = paymentsViewFactory.getByIdOrNull(paymentsViewId); return paymentsView != null ? paymentsView.getInvoicesView() : null; } private static ViewId toPaymentsViewId(final ViewId invoicesViewId) { return invoicesViewId.withWindowId(PaymentsViewFactory.WINDOW_ID); } @Override public void closeById(final ViewId viewId, final ViewCloseAction closeAction) { } @Override public Stream<IView> streamAllViews() { return paymentsViewFactory.streamAllViews() .map(PaymentsView::cast) .map(PaymentsView::getInvoicesView); } @Override public void invalidateView(final ViewId invoicesViewId) { final InvoicesView invoicesView = getByIdOrNull(invoicesViewId); if (invoicesView != null) { invoicesView.invalidateAll(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\payment_allocation\InvoicesViewFactory.java
1
请完成以下Java代码
class FindJoinCellEditor extends FindCellEditor implements TableCellRenderer { private static final long serialVersionUID = 4115046751452112894L; private static final int JoinAndOr_AD_Reference_ID = X_AD_WF_NextCondition.ANDOR_AD_Reference_ID; private final DefaultTableCellRenderer defaultRenderer = new DefaultTableCellRenderer(); private CComboBox<Join> _editor; private final Map<Join, String> join2displayName; public FindJoinCellEditor() { super(); // Load translation final ADReferenceService adReferenceService = ADReferenceService.get(); final Properties ctx = Env.getCtx(); join2displayName = ImmutableMap.<Join, String> builder() .put(Join.AND, adReferenceService.retrieveListNameTrl(ctx, JoinAndOr_AD_Reference_ID, X_AD_WF_NextCondition.ANDOR_And)) .put(Join.OR, adReferenceService.retrieveListNameTrl(ctx, JoinAndOr_AD_Reference_ID, X_AD_WF_NextCondition.ANDOR_OR)) .build(); } @Override protected CEditor getEditor() { if (_editor == null) { _editor = new CComboBox<>(); _editor.setRenderer(new ToStringListCellRenderer<Join>() { private static final long serialVersionUID = 1L; @Override protected String renderToString(Join value) { return getDisplayValue(value); } }); // make sure we are setting the model AFTER we set the renderer because else, // the value from combobox editor will not be the one that is returned by rendered _editor.setModel(new DefaultComboBoxModel<>(Join.values())); _editor.enableAutoCompletion(); }
return _editor; } @Override public Component getTableCellRendererComponent(final JTable table, final Object value, final boolean isSelected, final boolean hasFocus, final int row, final int column) { final String displayValue = getDisplayValue(value); return defaultRenderer.getTableCellRendererComponent(table, displayValue, isSelected, hasFocus, row, column); } private String getDisplayValue(final Object value) { if (value == null) { return null; } if (value instanceof Join) { return join2displayName.get(value); } else { return value.toString(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\search\FindJoinCellEditor.java
1
请完成以下Java代码
protected org.compiere.model.POInfo initPO (Properties ctx) { org.compiere.model.POInfo poi = org.compiere.model.POInfo.getPOInfo (ctx, Table_Name, get_TrxName()); return poi; } @Override public String toString() { StringBuffer sb = new StringBuffer ("X_AD_BoilerPlate_Ref[") .append(get_ID()).append("]"); return sb.toString(); } @Override public de.metas.letters.model.I_AD_BoilerPlate getAD_BoilerPlate() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_AD_BoilerPlate_ID, de.metas.letters.model.I_AD_BoilerPlate.class); } @Override public void setAD_BoilerPlate(de.metas.letters.model.I_AD_BoilerPlate AD_BoilerPlate) { set_ValueFromPO(COLUMNNAME_AD_BoilerPlate_ID, de.metas.letters.model.I_AD_BoilerPlate.class, AD_BoilerPlate); } /** Set Textbaustein. @param AD_BoilerPlate_ID Textbaustein */ @Override public void setAD_BoilerPlate_ID (int AD_BoilerPlate_ID) { if (AD_BoilerPlate_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_BoilerPlate_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_BoilerPlate_ID, Integer.valueOf(AD_BoilerPlate_ID)); } /** Get Textbaustein. @return Textbaustein */ @Override public int getAD_BoilerPlate_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_BoilerPlate_ID); if (ii == null) return 0; return ii.intValue(); } @Override public de.metas.letters.model.I_AD_BoilerPlate getRef_BoilerPlate() throws RuntimeException {
return get_ValueAsPO(COLUMNNAME_Ref_BoilerPlate_ID, de.metas.letters.model.I_AD_BoilerPlate.class); } @Override public void setRef_BoilerPlate(de.metas.letters.model.I_AD_BoilerPlate Ref_BoilerPlate) { set_ValueFromPO(COLUMNNAME_Ref_BoilerPlate_ID, de.metas.letters.model.I_AD_BoilerPlate.class, Ref_BoilerPlate); } /** Set Referenced template. @param Ref_BoilerPlate_ID Referenced template */ @Override public void setRef_BoilerPlate_ID (int Ref_BoilerPlate_ID) { if (Ref_BoilerPlate_ID < 1) set_ValueNoCheck (COLUMNNAME_Ref_BoilerPlate_ID, null); else set_ValueNoCheck (COLUMNNAME_Ref_BoilerPlate_ID, Integer.valueOf(Ref_BoilerPlate_ID)); } /** Get Referenced template. @return Referenced template */ @Override public int getRef_BoilerPlate_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Ref_BoilerPlate_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\letters\model\X_AD_BoilerPlate_Ref.java
1
请完成以下Java代码
public class EventLogEntryEntityImpl extends AbstractEntityNoRevision implements EventLogEntryEntity { protected long logNumber; // cant use id here, it would clash with entity protected String type; protected String processDefinitionId; protected String processInstanceId; protected String executionId; protected String taskId; protected Date timeStamp; protected String userId; protected byte[] data; protected String lockOwner; protected String lockTime; protected int isProcessed; public EventLogEntryEntityImpl() {} @Override public Object getPersistentState() { return null; // Not updateable } public long getLogNumber() { return logNumber; } public void setLogNumber(long logNumber) { this.logNumber = logNumber; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getProcessDefinitionId() { return processDefinitionId; } public void setProcessDefinitionId(String processDefinitionId) { this.processDefinitionId = processDefinitionId; } public String getProcessInstanceId() { return processInstanceId; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } public String getExecutionId() { return executionId; } public void setExecutionId(String executionId) { this.executionId = executionId; } public String getTaskId() { return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; } public Date getTimeStamp() { return timeStamp; } public void setTimeStamp(Date timeStamp) { this.timeStamp = timeStamp; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId;
} public byte[] getData() { return data; } public void setData(byte[] data) { this.data = data; } public String getLockOwner() { return lockOwner; } public void setLockOwner(String lockOwner) { this.lockOwner = lockOwner; } public String getLockTime() { return lockTime; } public void setLockTime(String lockTime) { this.lockTime = lockTime; } public int getProcessed() { return isProcessed; } public void setProcessed(int isProcessed) { this.isProcessed = isProcessed; } @Override public String toString() { return timeStamp.toString() + " : " + type; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\EventLogEntryEntityImpl.java
1
请完成以下Java代码
public class User implements Observer { private final String name; private final String email; private final String phone; private final String street; private final String city; private final String state; private final String zipCode; public User(String name, String email, String phone, String street, String city, String state, String zipCode) { this.name = name; this.email = email; this.phone = phone; this.street = street; this.city = city; this.state = state; this.zipCode = zipCode; } public String getName() { return name; } public String getEmail() { return email; } public String getPhone() { return phone; } public String getStreet() { return street; } public String getCity() { return city; } public String getState() { return state; } public String getZipCode() {
return zipCode; } @Override public void update(final String quote) { // user got updated with a new quote } @Override public void subscribe(final Subject subject) { subject.attach(this); } @Override public void unsubscribe(final Subject subject) { subject.detach(this); } @Override public String toString() { return "User [name=" + name + "]"; } }
repos\tutorials-master\core-java-modules\core-java-perf-2\src\main\java\com\baeldung\lapsedlistener\User.java
1
请在Spring Boot框架中完成以下Java代码
public abstract class AbstractTranslationEntity<T extends AbstractEntity> extends AbstractEntity { public static final String COLUMNNAME_Record = "record"; @ManyToOne @NonNull private T record; public static final String COLUMNNAME_Language = "language"; @NonNull private String language; @Override protected void toString(final ToStringHelper toStringHelper) { toStringHelper .add("language", language) .add("record", record); } public T getRecord() { return record; }
public void setRecord(final T record) { this.record = record; } public String getLanguage() { return language; } public void setLanguage(final String language) { this.language = language; } }
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\model\AbstractTranslationEntity.java
2
请在Spring Boot框架中完成以下Java代码
public int getSignatureCheck() { return signatureCheck; } /** * Sets the value of the signatureCheck property. * */ public void setSignatureCheck(int value) { this.signatureCheck = value; } /** * Gets the value of the certificateCheck property. * */ public int getCertificateCheck() { return certificateCheck; } /** * Sets the value of the certificateCheck property. * */ public void setCertificateCheck(int value) { this.certificateCheck = value; }
/** * Gets the value of the signatureManifestCheck property. * */ public int getSignatureManifestCheck() { return signatureManifestCheck; } /** * Sets the value of the signatureManifestCheck property. * */ public void setSignatureManifestCheck(int value) { this.signatureManifestCheck = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\messaging\header\SignatureVerificationResultType.java
2
请完成以下Java代码
public class RoutingKafkaTemplate extends KafkaTemplate<Object, Object> { private static final String THIS_METHOD_IS_NOT_SUPPORTED = "This method is not supported"; private final Map<Pattern, ProducerFactory<Object, Object>> factoryMatchers; private final ConcurrentMap<String, ProducerFactory<Object, Object>> factoryMap = new ConcurrentHashMap<>(); /** * Construct an instance with the provided properties. The topic patterns will be * traversed in order so an ordered map, such as {@link LinkedHashMap} should be used * with more specific patterns declared first. * @param factories the factories. */ public RoutingKafkaTemplate(Map<Pattern, ProducerFactory<Object, Object>> factories) { super(() -> { throw new UnsupportedOperationException(); }); Assert.isTrue(factories.values().stream().noneMatch(ProducerFactory::transactionCapable), "Transactional factories are not supported"); this.factoryMatchers = new LinkedHashMap<>(factories); } @Override public ProducerFactory<Object, Object> getProducerFactory() { throw new UnsupportedOperationException(THIS_METHOD_IS_NOT_SUPPORTED); } @Override public ProducerFactory<Object, Object> getProducerFactory(String topic) { ProducerFactory<Object, Object> producerFactory = this.factoryMap.computeIfAbsent(topic, key -> { for (Entry<Pattern, ProducerFactory<Object, Object>> entry : this.factoryMatchers.entrySet()) { if (entry.getKey().matcher(topic).matches()) { return entry.getValue(); } } return null; }); Assert.state(producerFactory != null, "No producer factory found for topic: " + topic); return producerFactory; } @Override public <T> T execute(ProducerCallback<Object, Object, T> callback) { throw new UnsupportedOperationException(THIS_METHOD_IS_NOT_SUPPORTED); }
@Override public <T> T executeInTransaction(OperationsCallback<Object, Object, T> callback) { throw new UnsupportedOperationException(THIS_METHOD_IS_NOT_SUPPORTED); } @Override public void sendOffsetsToTransaction(Map<TopicPartition, OffsetAndMetadata> offsets, ConsumerGroupMetadata groupMetadata) { throw new UnsupportedOperationException(THIS_METHOD_IS_NOT_SUPPORTED); } @Override public Map<MetricName, ? extends Metric> metrics() { throw new UnsupportedOperationException(THIS_METHOD_IS_NOT_SUPPORTED); } @Override public void flush() { throw new UnsupportedOperationException(THIS_METHOD_IS_NOT_SUPPORTED); } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\core\RoutingKafkaTemplate.java
1
请完成以下Java代码
public class X_C_Calendar extends org.compiere.model.PO implements I_C_Calendar, org.compiere.model.I_Persistent { private static final long serialVersionUID = -1401646905L; /** Standard Constructor */ public X_C_Calendar (Properties ctx, int C_Calendar_ID, String trxName) { super (ctx, C_Calendar_ID, trxName); } /** Load Constructor */ public X_C_Calendar (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO(Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setC_Calendar_ID (int C_Calendar_ID) { if (C_Calendar_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Calendar_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Calendar_ID, Integer.valueOf(C_Calendar_ID)); } @Override public int getC_Calendar_ID() { return get_ValueAsInt(COLUMNNAME_C_Calendar_ID); }
@Override public void setDescription (java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return (java.lang.String)get_Value(COLUMNNAME_Description); } @Override public void setIsDefault (boolean IsDefault) { set_Value (COLUMNNAME_IsDefault, Boolean.valueOf(IsDefault)); } @Override public boolean isDefault() { return get_ValueAsBoolean(COLUMNNAME_IsDefault); } @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return (java.lang.String)get_Value(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Calendar.java
1
请在Spring Boot框架中完成以下Java代码
private MongoClientSettings clientSettings() throws FileNotFoundException, IOException { Builder settings = MongoClientSettings.builder() .applyConnectionString(new ConnectionString(uri)); if (encryptionConfig.isAutoDecryption()) { AutoEncryptionSettings.Builder builder = AutoEncryptionSettings.builder() .keyVaultNamespace(encryptionConfig.getKeyVaultNamespace()) .kmsProviders(LocalKmsUtils.providersMap(encryptionConfig.getMasterKeyPath())); if (encryptionConfig.isAutoEncryption() && encryptionConfig.getDataKeyId() != null) { File autoEncryptionLib = encryptionConfig.getAutoEncryptionLib(); if (!autoEncryptionLib.isFile()) { throw new IllegalArgumentException("encryption lib must be an existing file"); } Map<String, Object> map = new HashMap<>(); map.put("cryptSharedLibRequired", true); map.put("cryptSharedLibPath", autoEncryptionLib.toString()); builder.extraOptions(map); String keyUuid = encryptionConfig.dataKeyIdUuid(); HashMap<String, BsonDocument> schemaMap = new HashMap<>(); schemaMap.put(getDatabaseName() + ".citizens", BsonDocument.parse("{" + " bsonType: \"object\"," + " encryptMetadata: {" + " keyId: [UUID(\"" + keyUuid + "\")]"
+ " }," + " properties: {" + " email: {" + " encrypt: {" + " bsonType: \"string\"," + " algorithm: \"AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic\"" + " }" + " }," + " birthYear: {" + " encrypt: {" + " bsonType: \"int\"," + " algorithm: \"AEAD_AES_256_CBC_HMAC_SHA_512-Random\"" + " }" + " }" + " }" + "}")); builder.schemaMap(schemaMap); } else { builder.bypassAutoEncryption(true); } settings.autoEncryptionSettings(builder.build()); } return settings.build(); } }
repos\tutorials-master\persistence-modules\spring-boot-persistence-mongodb-3\src\main\java\com\baeldung\boot\csfle\config\MongoClientConfig.java
2
请在Spring Boot框架中完成以下Java代码
public ReturnT<String> logout(HttpServletRequest request, HttpServletResponse response){ CookieUtil.remove(request, response, LOGIN_IDENTITY_KEY); return ReturnT.SUCCESS; } /** * logout * * @param request * @return */ public XxlJobUser ifLogin(HttpServletRequest request, HttpServletResponse response){ String cookieToken = CookieUtil.getValue(request, LOGIN_IDENTITY_KEY); if (cookieToken != null) { XxlJobUser cookieUser = null; try { cookieUser = parseToken(cookieToken); } catch (Exception e) { logout(request, response);
} if (cookieUser != null) { XxlJobUser dbUser = xxlJobUserDao.loadByUserName(cookieUser.getUsername()); if (dbUser != null) { if (cookieUser.getPassword().equals(dbUser.getPassword())) { return dbUser; } } } } return null; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\service\LoginService.java
2
请在Spring Boot框架中完成以下Java代码
private TbResource fetchResource(ResourceCompositeKey compositeKey) { UUID tenantId = compositeKey.getTenantId().getId(); TransportProtos.GetResourceRequestMsg.Builder builder = TransportProtos.GetResourceRequestMsg.newBuilder(); builder .setTenantIdLSB(tenantId.getLeastSignificantBits()) .setTenantIdMSB(tenantId.getMostSignificantBits()) .setResourceType(compositeKey.resourceType.name()) .setResourceKey(compositeKey.resourceKey); TransportProtos.GetResourceResponseMsg responseMsg = transportService.getResource(builder.build()); if (responseMsg.hasResource()) { TbResource resource = ProtoUtils.fromProto(responseMsg.getResource()); resources.put(new ResourceCompositeKey(resource.getTenantId(), resource.getResourceType(), resource.getResourceKey()), resource); return resource; } return null; } @Override public void update(TenantId tenantId, ResourceType resourceType, String resourceKey) { ResourceCompositeKey compositeKey = new ResourceCompositeKey(tenantId, resourceType, resourceKey); if (keys.contains(compositeKey) || resources.containsKey(compositeKey)) { fetchResource(compositeKey); } }
@Override public void evict(TenantId tenantId, ResourceType resourceType, String resourceKey) { ResourceCompositeKey compositeKey = new ResourceCompositeKey(tenantId, resourceType, resourceKey); keys.remove(compositeKey); resources.remove(compositeKey); } @Data private static class ResourceCompositeKey { private final TenantId tenantId; private final ResourceType resourceType; private final String resourceKey; public ResourceCompositeKey getSystemKey() { return new ResourceCompositeKey(TenantId.SYS_TENANT_ID, resourceType, resourceKey); } } }
repos\thingsboard-master\common\transport\transport-api\src\main\java\org\thingsboard\server\common\transport\service\DefaultTransportResourceCache.java
2
请完成以下Java代码
public void setDescription (final @Nullable java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setIsExcludeAlreadyExported (final boolean IsExcludeAlreadyExported) { set_Value (COLUMNNAME_IsExcludeAlreadyExported, IsExcludeAlreadyExported); } @Override public boolean isExcludeAlreadyExported() { return get_ValueAsBoolean(COLUMNNAME_IsExcludeAlreadyExported); } @Override public void setIsNegateInboundAmounts (final boolean IsNegateInboundAmounts) { set_Value (COLUMNNAME_IsNegateInboundAmounts, IsNegateInboundAmounts); } @Override public boolean isNegateInboundAmounts() { return get_ValueAsBoolean(COLUMNNAME_IsNegateInboundAmounts); } @Override public void setIsPlaceBPAccountsOnCredit (final boolean IsPlaceBPAccountsOnCredit) { set_Value (COLUMNNAME_IsPlaceBPAccountsOnCredit, IsPlaceBPAccountsOnCredit); } @Override public boolean isPlaceBPAccountsOnCredit() { return get_ValueAsBoolean(COLUMNNAME_IsPlaceBPAccountsOnCredit); } /** * IsSOTrx AD_Reference_ID=319 * Reference name: _YesNo
*/ public static final int ISSOTRX_AD_Reference_ID=319; /** Yes = Y */ public static final String ISSOTRX_Yes = "Y"; /** No = N */ public static final String ISSOTRX_No = "N"; @Override public void setIsSOTrx (final @Nullable java.lang.String IsSOTrx) { set_Value (COLUMNNAME_IsSOTrx, IsSOTrx); } @Override public java.lang.String getIsSOTrx() { return get_ValueAsString(COLUMNNAME_IsSOTrx); } @Override public void setIsSwitchCreditMemo (final boolean IsSwitchCreditMemo) { set_Value (COLUMNNAME_IsSwitchCreditMemo, IsSwitchCreditMemo); } @Override public boolean isSwitchCreditMemo() { return get_ValueAsBoolean(COLUMNNAME_IsSwitchCreditMemo); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.datev\src\main\java-gen\de\metas\datev\model\X_DATEV_Export.java
1
请完成以下Java代码
public int getM_Package_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Package_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Package Content. @param PackageContent Package Content */ @Override public void setPackageContent (java.lang.String PackageContent) { set_Value (COLUMNNAME_PackageContent, PackageContent); } /** Get Package Content. @return Package Content */ @Override public java.lang.String getPackageContent () { return (java.lang.String)get_Value(COLUMNNAME_PackageContent); } /** Set Weight In Kg. @param WeightInKg Weight In Kg */ @Override public void setWeightInKg (int WeightInKg) { set_Value (COLUMNNAME_WeightInKg, Integer.valueOf(WeightInKg)); }
/** Get Weight In Kg. @return Weight In Kg */ @Override public int getWeightInKg () { Integer ii = (Integer)get_Value(COLUMNNAME_WeightInKg); if (ii == null) return 0; return ii.intValue(); } /** Set Width In Cm. @param WidthInCm Width In Cm */ @Override public void setWidthInCm (int WidthInCm) { set_Value (COLUMNNAME_WidthInCm, Integer.valueOf(WidthInCm)); } /** Get Width In Cm. @return Width In Cm */ @Override public int getWidthInCm () { Integer ii = (Integer)get_Value(COLUMNNAME_WidthInCm); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-gen\de\metas\shipper\gateway\dpd\model\X_DPD_StoreOrderLine.java
1
请完成以下Java代码
public Map<InOutLineId, List<I_M_HU>> retrieveShippedHUsByShipmentLineId(@NonNull final Set<InOutLineId> shipmentLineIds) { final List<I_M_InOutLine> inOutLines = inOutDAO.getLinesByIds(shipmentLineIds, I_M_InOutLine.class); return inOutLines .stream() .map(inOutLine -> { final InOutLineId inOutLineId = InOutLineId.ofRepoId(inOutLine.getM_InOutLine_ID()); return new HashMap.SimpleEntry<>(inOutLineId, getShippedHUsByShipmentLine(inOutLine)); }) .filter(entry -> !entry.getValue().isEmpty()) .collect(ImmutableMap.toImmutableMap(Map.Entry::getKey, Map.Entry::getValue)); } /** * NOTE: keep in sync with {@link #retrieveHandlingUnits(I_M_InOut)} logic */ @Override @Nullable public I_M_InOutLine retrieveCompletedReceiptLineOrNull(final I_M_HU hu) { final Properties ctx = InterfaceWrapperHelper.getCtx(hu); final AttributeId receiptInOutLineAttributeId = attributeDAO.getAttributeIdByCode(HUAttributeConstants.ATTR_ReceiptInOutLine_ID); final I_M_HU_Attribute huAttrReceiptInOutLine = huAttributesDAO.retrieveAttribute(hu, receiptInOutLineAttributeId); if (huAttrReceiptInOutLine == null || huAttrReceiptInOutLine.getValueNumber() == null || huAttrReceiptInOutLine.getValueNumber().signum() <= 0) { return null; } final int inOutLineId = huAttrReceiptInOutLine.getValueNumber().intValue(); final I_M_InOutLine inoutLine = InterfaceWrapperHelper.create(ctx, inOutLineId, I_M_InOutLine.class, ITrx.TRXNAME_ThreadInherited); if (!inoutLine.isActive()) { return null; } final I_M_InOut inOut = inoutLine.getM_InOut();
final DocStatus docStatus = DocStatus.ofNullableCodeOrUnknown(inOut.getDocStatus()); if (!docStatus.isCompletedOrClosed()) { return null; } return inoutLine; } @Override public List<I_M_InOutLine> retrieveInOutLinesForHU(final I_M_HU topLevelHU) { return huAssignmentDAO.retrieveModelsForHU(topLevelHU, I_M_InOutLine.class); } @Override public List<I_M_HU> retrieveHUsForReceiptLineId(final int receiptLineId) { return huAssignmentDAO.retrieveTopLevelHUsForModel(TableRecordReference.of(I_M_InOutLine.Table_Name, receiptLineId), ITrx.TRXNAME_ThreadInherited); } @NonNull private List<I_M_HU> getShippedHUsByShipmentLine(@NonNull final I_M_InOutLine inOutLine) { return huAssignmentDAO.retrieveTopLevelHUsForModel(inOutLine) .stream() .filter(hu -> X_M_HU.HUSTATUS_Shipped.equals(hu.getHUStatus())) .collect(ImmutableList.toImmutableList()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inout\impl\HUInOutDAO.java
1
请完成以下Java代码
public static byte[] getBytesUtf8(String string) { return StringUtils.getBytesUnchecked(string, UTF_8); } /** * Encodes the given string into a sequence of bytes using the named charset, storing the result into a new byte * array. * <p> * This method catches {@link UnsupportedEncodingException} and rethrows it as {@link IllegalStateException}, which * should never happen for a required charset name. Use this method when the encoding is required to be in the JRE. * </p> * * @param string * the String to encode * @param charsetName * The name of a required {@link java.nio.charset.Charset} * @return encoded bytes * @throws IllegalStateException * Thrown when a {@link UnsupportedEncodingException} is caught, which should never happen for a * required charset name. * @see <a href="http://commons.apache.org/proper/commons-codec/apidocs/org/apache/commons/codec/CharEncoding.html">CharEncoding</a>
* @see String#getBytes(String) */ public static byte[] getBytesUnchecked(String string, String charsetName) { if (string == null) { return null; } try { return string.getBytes(charsetName); } catch (UnsupportedEncodingException e) { throw StringUtils.newIllegalStateException(charsetName, e); } } private static IllegalStateException newIllegalStateException(String charsetName, UnsupportedEncodingException e) { return new IllegalStateException(charsetName + ": " + e); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\digest\_apacheCommonsCodec\StringUtils.java
1
请完成以下Java代码
private void updateBankStatementHeader(final BankStatementId bankStatementId) { updateStatementDifferenceAndEndingBalance(bankStatementId); updateBankStatementIsReconciledFlag(bankStatementId); CacheMgt.get().resetLocalNowAndBroadcastOnTrxCommit( ITrx.TRXNAME_ThreadInherited, CacheInvalidateMultiRequest.rootRecord(I_C_BankStatement.Table_Name, bankStatementId)); } @VisibleForTesting protected void updateStatementDifferenceAndEndingBalance(final BankStatementId bankStatementId) { // StatementDifference { final String sql = "UPDATE C_BankStatement bs" + " SET StatementDifference=(SELECT COALESCE(SUM(StmtAmt),0) FROM C_BankStatementLine bsl " + "WHERE bsl.C_BankStatement_ID=bs.C_BankStatement_ID AND bsl.IsActive='Y') " + "WHERE C_BankStatement_ID=?"; DB.executeUpdateAndThrowExceptionOnFail(sql, new Object[] { bankStatementId }, ITrx.TRXNAME_ThreadInherited); } // EndingBalance { final String sql = "UPDATE C_BankStatement bs" + " SET EndingBalance=BeginningBalance+StatementDifference " + "WHERE C_BankStatement_ID=?"; DB.executeUpdateAndThrowExceptionOnFail(sql, new Object[] { bankStatementId }, ITrx.TRXNAME_ThreadInherited); }
} @VisibleForTesting protected void updateBankStatementIsReconciledFlag(final BankStatementId bankStatementId) { final String sql = "UPDATE C_BankStatement bs" + " SET IsReconciled=(CASE WHEN (SELECT COUNT(1) FROM C_BankStatementLine bsl WHERE bsl.C_BankStatement_ID = bs.C_BankStatement_ID AND bsl.IsReconciled = 'N') = 0 THEN 'Y' ELSE 'N' END)" + " WHERE C_BankStatement_ID=?"; DB.executeUpdateAndThrowExceptionOnFail(sql, new Object[] { bankStatementId }, ITrx.TRXNAME_ThreadInherited); } private void assertReconcilationConsistent(final I_C_BankStatementLine line) { if (line.getLink_BankStatementLine_ID() > 0 && line.getC_Payment_ID() > 0) { throw new AdempiereException("Invalid reconcilation: cannot have bank transfer and payment at the same time"); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\model\validator\C_BankStatementLine.java
1
请完成以下Java代码
public class ThreadPerRequestServer { private static final Logger logger = LoggerFactory.getLogger(ThreadPerRequestServer.class); private static final int PORT = 8080; public static void main(String[] args) { List<ClientConnection> clientConnections = new ArrayList<>(); try (ServerSocket serverSocket = new ServerSocket(PORT)) { logger.info("Server started on port {}", PORT); while (!serverSocket.isClosed()) { acceptNewConnections(serverSocket, clientConnections); handleRequests(clientConnections); } } catch (IOException e) { logger.error("Server error", e); } finally { closeClientConnection(clientConnections); } } private static void acceptNewConnections(ServerSocket serverSocket, List<ClientConnection> clientConnections) throws SocketException { serverSocket.setSoTimeout(100); try { Socket newClient = serverSocket.accept(); ClientConnection clientConnection = new ClientConnection(newClient); clientConnections.add(clientConnection); logger.info("New client connected: {}", newClient.getInetAddress()); } catch (IOException ignored) { // ignore expected socket timeout } } private static void handleRequests(List<ClientConnection> clientConnections) { Iterator<ClientConnection> iterator = clientConnections.iterator(); while (iterator.hasNext()) { ClientConnection client = iterator.next(); if (client.getSocket() .isClosed()) { logger.info("Client disconnected: {}", client.getSocket() .getInetAddress()); iterator.remove(); continue;
} try { BufferedReader reader = client.getReader(); if (reader.ready()) { String request = reader.readLine(); if (request != null) { new ThreadPerRequest(client.getWriter(), request).start(); } } } catch (IOException e) { logger.error("Error reading from client {}", client.getSocket() .getInetAddress(), e); } } } private static void closeClientConnection(List<ClientConnection> clientConnections) { for (ClientConnection client : clientConnections) { try { client.close(); } catch (IOException e) { logger.error("Error closing client connection", e); } } } }
repos\tutorials-master\core-java-modules\core-java-sockets\src\main\java\com\baeldung\threading\request\ThreadPerRequestServer.java
1
请完成以下Java代码
public class ByteArrayEntityImpl extends AbstractEntity implements ByteArrayEntity, Serializable { private static final long serialVersionUID = 1L; protected String name; protected byte[] bytes; protected String deploymentId; public ByteArrayEntityImpl() {} public byte[] getBytes() { return bytes; } public Object getPersistentState() { return new PersistentState(name, bytes); } // getters and setters //////////////////////////////////////////////////////// public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDeploymentId() { return deploymentId; } public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } public void setBytes(byte[] bytes) { this.bytes = bytes; } @Override public String toString() { return "ByteArrayEntity[id=" + id + ", name=" + name + ", size=" + (bytes != null ? bytes.length : 0) + "]";
} // Wrapper for a byte array, needed to do byte array comparisons // See https://activiti.atlassian.net/browse/ACT-1524 private static class PersistentState { private final String name; private final byte[] bytes; public PersistentState(String name, byte[] bytes) { this.name = name; this.bytes = bytes; } public boolean equals(Object obj) { if (obj instanceof PersistentState) { PersistentState other = (PersistentState) obj; return StringUtils.equals(this.name, other.name) && Arrays.equals(this.bytes, other.bytes); } return false; } @Override public int hashCode() { throw new UnsupportedOperationException(); } } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\ByteArrayEntityImpl.java
1
请完成以下Java代码
public void setBestellLiefervorgabe(Liefervorgabe value) { this.bestellLiefervorgabe = value; } /** * Gets the value of the substitution property. * * @return * possible object is * {@link BestellungSubstitution } * */ public BestellungSubstitution getSubstitution() { return substitution; } /** * Sets the value of the substitution property. * * @param value * allowed object is * {@link BestellungSubstitution } * */ public void setSubstitution(BestellungSubstitution value) { this.substitution = value; } /** * Gets the value of the anteile property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the anteile property. * * <p> * For example, to add a new item, do as follows: * <pre> * getAnteile().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link BestellungAnteil } * * */ public List<BestellungAnteil> getAnteile() { if (anteile == null) { anteile = new ArrayList<BestellungAnteil>(); } return this.anteile; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v1\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v1\BestellungAntwortPosition.java
1
请完成以下Java代码
public Long getProductAttributeId() { return productAttributeId; } public void setProductAttributeId(Long productAttributeId) { this.productAttributeId = productAttributeId; } public String getValue() { return value; } public void setValue(String value) { this.value = value; }
@Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", productId=").append(productId); sb.append(", productAttributeId=").append(productAttributeId); sb.append(", value=").append(value); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsProductAttributeValue.java
1
请完成以下Java代码
protected void addError( List<ValidationError> validationErrors, String problem, Process process, BaseElement baseElement, boolean isWarning ) { addError(validationErrors, problem, process, baseElement, isWarning, new HashMap<>()); } protected void addError( List<ValidationError> validationErrors, String problem, Process process, BaseElement baseElement, boolean isWarning, Map<String, String> params ) { ValidationError error = new ValidationError(); error.setWarning(isWarning); if (process != null) { error.setProcessDefinitionId(process.getId()); error.setProcessDefinitionName(process.getName()); } if (baseElement != null) { error.setXmlLineNumber(baseElement.getXmlRowNumber()); error.setXmlColumnNumber(baseElement.getXmlColumnNumber()); } error.setKey(problem); error.setProblem(problem); error.setDefaultDescription(problem);
error.setParams(params); if (baseElement instanceof FlowElement) { FlowElement flowElement = (FlowElement) baseElement; error.setActivityId(flowElement.getId()); error.setActivityName(flowElement.getName()); } addError(validationErrors, error); } protected void addError(List<ValidationError> validationErrors, String problem, Process process, String id) { ValidationError error = new ValidationError(); if (process != null) { error.setProcessDefinitionId(process.getId()); error.setProcessDefinitionName(process.getName()); } error.setKey(problem); error.setProblem(problem); error.setDefaultDescription(problem); error.setActivityId(id); addError(validationErrors, error); } }
repos\Activiti-develop\activiti-core\activiti-process-validation\src\main\java\org\activiti\validation\validator\ValidatorImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class JpaTenantProfileDao extends JpaAbstractDao<TenantProfileEntity, TenantProfile> implements TenantProfileDao { @Autowired private TenantProfileRepository tenantProfileRepository; @Override protected Class<TenantProfileEntity> getEntityClass() { return TenantProfileEntity.class; } @Override protected JpaRepository<TenantProfileEntity, UUID> getRepository() { return tenantProfileRepository; } @Override public EntityInfo findTenantProfileInfoById(TenantId tenantId, UUID tenantProfileId) { return tenantProfileRepository.findTenantProfileInfoById(tenantProfileId); } @Override public PageData<TenantProfile> findTenantProfiles(TenantId tenantId, PageLink pageLink) { return DaoUtil.toPageData( tenantProfileRepository.findTenantProfiles( pageLink.getTextSearch(), DaoUtil.toPageable(pageLink))); } @Override public PageData<EntityInfo> findTenantProfileInfos(TenantId tenantId, PageLink pageLink) { return DaoUtil.pageToPageData( tenantProfileRepository.findTenantProfileInfos( pageLink.getTextSearch(), DaoUtil.toPageable(pageLink))); } @Override
public TenantProfile findDefaultTenantProfile(TenantId tenantId) { return DaoUtil.getData(tenantProfileRepository.findByDefaultTrue()); } @Override public EntityInfo findDefaultTenantProfileInfo(TenantId tenantId) { return tenantProfileRepository.findDefaultTenantProfileInfo(); } @Override public List<TenantProfile> findTenantProfilesByIds(TenantId tenantId, UUID[] ids) { return DaoUtil.convertDataList(tenantProfileRepository.findByIdIn(Arrays.asList(ids))); } @Override public List<TenantProfileFields> findNextBatch(UUID id, int batchSize) { return tenantProfileRepository.findNextBatch(id, Limit.of(batchSize)); } @Override public EntityType getEntityType() { return EntityType.TENANT_PROFILE; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\tenant\JpaTenantProfileDao.java
2
请完成以下Java代码
protected void createMultiInstanceLoopCharacteristics(BpmnParse bpmnParse, Activity modelActivity) { MultiInstanceLoopCharacteristics loopCharacteristics = modelActivity.getLoopCharacteristics(); // Activity Behavior MultiInstanceActivityBehavior miActivityBehavior = null; ActivityImpl activity = bpmnParse.getCurrentScope().findActivity(modelActivity.getId()); if (activity == null) { throw new ActivitiException("Activity " + modelActivity.getId() + " needed for multi instance cannot bv found"); } if (loopCharacteristics.isSequential()) { miActivityBehavior = bpmnParse.getActivityBehaviorFactory().createSequentialMultiInstanceBehavior( activity, activity.getActivityBehavior()); } else { miActivityBehavior = bpmnParse.getActivityBehaviorFactory().createParallelMultiInstanceBehavior( activity, activity.getActivityBehavior()); } // ActivityImpl settings activity.setScope(true); activity.setProperty("multiInstance", loopCharacteristics.isSequential() ? "sequential" : "parallel"); activity.setActivityBehavior(miActivityBehavior); ExpressionManager expressionManager = bpmnParse.getExpressionManager(); // loop cardinality if (StringUtils.isNotEmpty(loopCharacteristics.getLoopCardinality())) { miActivityBehavior.setLoopCardinalityExpression(expressionManager.createExpression(loopCharacteristics.getLoopCardinality())); } // completion condition if (StringUtils.isNotEmpty(loopCharacteristics.getCompletionCondition())) { miActivityBehavior.setCompletionConditionExpression(expressionManager.createExpression(loopCharacteristics.getCompletionCondition())); } // activiti:collection if (StringUtils.isNotEmpty(loopCharacteristics.getInputDataItem())) { if (loopCharacteristics.getInputDataItem().contains("{")) {
miActivityBehavior.setCollectionExpression(expressionManager.createExpression(loopCharacteristics.getInputDataItem())); } else { miActivityBehavior.setCollectionVariable(loopCharacteristics.getInputDataItem()); } } // activiti:elementVariable if (StringUtils.isNotEmpty(loopCharacteristics.getElementVariable())) { miActivityBehavior.setCollectionElementVariable(loopCharacteristics.getElementVariable()); } // activiti:elementIndexVariable if (StringUtils.isNotEmpty(loopCharacteristics.getElementIndexVariable())) { miActivityBehavior.setCollectionElementIndexVariable(loopCharacteristics.getElementIndexVariable()); } } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\handler\AbstractActivityBpmnParseHandler.java
1
请在Spring Boot框架中完成以下Java代码
RSocketServerFactory rSocketServerFactory(RSocketProperties properties, ReactorResourceFactory resourceFactory, ObjectProvider<RSocketServerCustomizer> customizers, ObjectProvider<SslBundles> sslBundles) { NettyRSocketServerFactory factory = new NettyRSocketServerFactory(); factory.setResourceFactory(resourceFactory); factory.setTransport(properties.getServer().getTransport()); PropertyMapper map = PropertyMapper.get(); map.from(properties.getServer().getAddress()).to(factory::setAddress); map.from(properties.getServer().getPort()).to(factory::setPort); map.from(properties.getServer().getFragmentSize()).to(factory::setFragmentSize); map.from(properties.getServer().getSsl()).to(factory::setSsl); factory.setSslBundles(sslBundles.getIfAvailable()); factory.setRSocketServerCustomizers(customizers.orderedStream().toList()); return factory; } @Bean @ConditionalOnMissingBean RSocketServerBootstrap rSocketServerBootstrap(RSocketServerFactory rSocketServerFactory, RSocketMessageHandler rSocketMessageHandler) { return new RSocketServerBootstrap(rSocketServerFactory, rSocketMessageHandler.responder()); } @Bean RSocketServerCustomizer frameDecoderRSocketServerCustomizer(RSocketMessageHandler rSocketMessageHandler) { return (server) -> { if (rSocketMessageHandler.getRSocketStrategies() .dataBufferFactory() instanceof NettyDataBufferFactory) { server.payloadDecoder(PayloadDecoder.ZERO_COPY); } }; } } static class OnRSocketWebServerCondition extends AllNestedConditions { OnRSocketWebServerCondition() { super(ConfigurationPhase.PARSE_CONFIGURATION); } @ConditionalOnWebApplication(type = Type.REACTIVE)
static class IsReactiveWebApplication { } @ConditionalOnProperty(name = "spring.rsocket.server.port", matchIfMissing = true) static class HasNoPortConfigured { } @ConditionalOnProperty("spring.rsocket.server.mapping-path") static class HasMappingPathConfigured { } @ConditionalOnProperty(name = "spring.rsocket.server.transport", havingValue = "websocket") static class HasWebsocketTransportConfigured { } } }
repos\spring-boot-4.0.1\module\spring-boot-rsocket\src\main\java\org\springframework\boot\rsocket\autoconfigure\RSocketServerAutoConfiguration.java
2
请完成以下Java代码
public boolean hasNext() { return delegate.hasNext(); } @Override public Entry<String, Object> next() { Entry<String, Object> entry = delegate.next(); return new AbstractMap.SimpleEntry<>(entry.getKey(), cachingResolver.resolveProperty(entry.getKey())); } } @Override public void forEach(BiConsumer<? super String, ? super Object> action) { delegate.forEach((k, v) -> action.accept(k, cachingResolver.resolveProperty(k))); } private class DecoratingEntryValueIterator implements Iterator<Object> { private final Iterator<Entry<String, Object>> entryIterator; DecoratingEntryValueIterator(Iterator<Entry<String, Object>> entryIterator) {
this.entryIterator = entryIterator; } @Override public boolean hasNext() { return entryIterator.hasNext(); } @Override public Object next() { Entry<String, Object> entry = entryIterator.next(); return cachingResolver.resolveProperty(entry.getKey()); } } }
repos\jasypt-spring-boot-master\jasypt-spring-boot\src\main\java\com\ulisesbocchio\jasyptspringboot\caching\EncryptableMapWrapper.java
1
请完成以下Java代码
private Object getGlobalContext(final String variableName, final Class<?> targetType) { if (Integer.class.equals(targetType) || int.class.equals(targetType)) { return Env.getContextAsInt(getCtx(), variableName); } else if (java.util.Date.class.equals(targetType) || Timestamp.class.equals(targetType)) { return Env.getContextAsDate(getCtx(), variableName); } else if (Boolean.class.equals(targetType)) { final String valueStr = Env.getContext(getCtx(), variableName); return DisplayType.toBoolean(valueStr, null); } final String valueStr = Env.getContext(getCtx(), variableName); // // Use some default value if (Check.isEmpty(valueStr)) { // FIXME hardcoded. when we will do a proper login, this won't be necessary if (variableName.startsWith("$Element_")) { return Boolean.FALSE; } } return valueStr; } /** Converts field value to {@link Evaluatee2} friendly string */ private static String convertToString(final Object value) { if (value == null) { return null; } else if (value instanceof Boolean) { return DisplayType.toBooleanString((Boolean)value); } else if (value instanceof String) { return value.toString(); } else if (value instanceof LookupValue) { return ((LookupValue)value).getIdAsString(); } else if (value instanceof java.util.Date) { final java.util.Date valueDate = (java.util.Date)value; return Env.toString(valueDate); } else { return value.toString(); } } private static Integer convertToInteger(final Object valueObj) { if (valueObj == null) { return null; } else if (valueObj instanceof Integer) { return (Integer)valueObj; } else if (valueObj instanceof Number) {
return ((Number)valueObj).intValue(); } else if (valueObj instanceof IntegerLookupValue) { return ((IntegerLookupValue)valueObj).getIdAsInt(); } else { final String valueStr = valueObj.toString().trim(); if (valueStr.isEmpty()) { return null; } return Integer.parseInt(valueStr); } } private static BigDecimal convertToBigDecimal(final Object valueObj) { if (valueObj == null) { return null; } else if (valueObj instanceof BigDecimal) { return (BigDecimal)valueObj; } else { final String valueStr = valueObj.toString().trim(); if (valueStr.isEmpty()) { return null; } return new BigDecimal(valueStr); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentEvaluatee.java
1
请完成以下Java代码
protected void applyFilters(JobDefinitionQuery query) { if (jobDefinitionId != null) { query.jobDefinitionId(jobDefinitionId); } if (activityIdIn != null && activityIdIn.length > 0) { query.activityIdIn(activityIdIn); } if (processDefinitionId != null) { query.processDefinitionId(processDefinitionId); } if (processDefinitionKey != null) { query.processDefinitionKey(processDefinitionKey); } if (jobType != null) { query.jobType(jobType); } if (jobConfiguration != null) { query.jobConfiguration(jobConfiguration); } if (TRUE.equals(active)) { query.active(); } if (TRUE.equals(suspended)) { query.suspended(); } if (TRUE.equals(withOverridingJobPriority)) { query.withOverridingJobPriority(); } if (tenantIds != null && !tenantIds.isEmpty()) { query.tenantIdIn(tenantIds.toArray(new String[tenantIds.size()])); } if (TRUE.equals(withoutTenantId)) { query.withoutTenantId(); } if (TRUE.equals(includeJobDefinitionsWithoutTenantId)) { query.includeJobDefinitionsWithoutTenantId(); }
} @Override protected void applySortBy(JobDefinitionQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) { if (sortBy.equals(SORT_BY_JOB_DEFINITION_ID)) { query.orderByJobDefinitionId(); } else if (sortBy.equals(SORT_BY_ACTIVITY_ID)) { query.orderByActivityId(); } else if (sortBy.equals(SORT_BY_PROCESS_DEFINITION_ID)) { query.orderByProcessDefinitionId(); } else if (sortBy.equals(SORT_BY_PROCESS_DEFINITION_KEY)) { query.orderByProcessDefinitionKey(); } else if (sortBy.equals(SORT_BY_JOB_TYPE)) { query.orderByJobType(); } else if (sortBy.equals(SORT_BY_JOB_CONFIGURATION)) { query.orderByJobConfiguration(); } else if (sortBy.equals(SORT_BY_TENANT_ID)) { query.orderByTenantId(); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\management\JobDefinitionQueryDto.java
1
请在Spring Boot框架中完成以下Java代码
public class City implements Serializable { @Id @GeneratedValue private Long id; @Column(nullable = false) private String name; @Column(nullable = false) private String state; // ... additional members, often include @OneToMany mappings protected City() { // no-args constructor required by JPA spec // this one is protected since it should not be used directly }
public City(String name, String state) { this.name = name; this.state = state; } public String getName() { return this.name; } public String getState() { return this.state; } // ... etc }
repos\spring-boot-4.0.1\documentation\spring-boot-docs\src\main\java\org\springframework\boot\docs\data\sql\jpaandspringdata\entityclasses\City.java
2
请在Spring Boot框架中完成以下Java代码
public class UserMapper { public List<UserDTO> usersToUserDTOs(List<User> users) { return users.stream() .filter(Objects::nonNull) .map(this::userToUserDTO) .collect(Collectors.toList()); } public UserDTO userToUserDTO(User user) { return new UserDTO(user); } public List<User> userDTOsToUsers(List<UserDTO> userDTOs) { return userDTOs.stream() .filter(Objects::nonNull) .map(this::userDTOToUser) .collect(Collectors.toList()); } public User userDTOToUser(UserDTO userDTO) { if (userDTO == null) { return null; } else { User user = new User(); user.setId(userDTO.getId()); user.setLogin(userDTO.getLogin()); user.setFirstName(userDTO.getFirstName()); user.setLastName(userDTO.getLastName()); user.setEmail(userDTO.getEmail()); user.setImageUrl(userDTO.getImageUrl()); user.setActivated(userDTO.isActivated()); user.setLangKey(userDTO.getLangKey()); Set<Authority> authorities = this.authoritiesFromStrings(userDTO.getAuthorities()); user.setAuthorities(authorities); return user; } } private Set<Authority> authoritiesFromStrings(Set<String> authoritiesAsString) {
Set<Authority> authorities = new HashSet<>(); if(authoritiesAsString != null){ authorities = authoritiesAsString.stream().map(string -> { Authority auth = new Authority(); auth.setName(string); return auth; }).collect(Collectors.toSet()); } return authorities; } public User userFromId(Long id) { if (id == null) { return null; } User user = new User(); user.setId(id); return user; } }
repos\tutorials-master\jhipster-6\bookstore-monolith\src\main\java\com\baeldung\jhipster6\service\mapper\UserMapper.java
2
请完成以下Java代码
protected void initializeWebClient(Integer port) { this.webClient = WebClient.create("http://localhost:" + port); } public CustomerInfo getCustomerInfo(Long customerId) { // enable to trigger the test failure (scenario where each method call is blocked) // return getCustomerInfoBlockEach(customerId); return getCustomerInfoBlockCombined(customerId); } private CustomerInfo getCustomerInfoBlockEach(Long customerId) { Customer customer = webClient.get() .uri(uriBuilder -> uriBuilder.path(CustomerController.PATH_CUSTOMER) .pathSegment(String.valueOf(customerId)) .build()) .retrieve() .onStatus(status -> status.is5xxServerError() || status.is4xxClientError(), response -> response.bodyToMono(String.class) .map(ApiGatewayException::new)) .bodyToMono(Customer.class) .block(); Billing billing = webClient.get() .uri(uriBuilder -> uriBuilder.path(BillingController.PATH_BILLING) .pathSegment(String.valueOf(customerId)) .build()) .retrieve() .onStatus(status -> status.is5xxServerError() || status.is4xxClientError(), response -> response.bodyToMono(String.class) .map(ApiGatewayException::new)) .bodyToMono(Billing.class) .block(); return new CustomerInfo(customer.getId(), customer.getName(), billing.getBalance()); } private CustomerInfo getCustomerInfoBlockCombined(Long customerId) { Mono<Customer> customerMono = webClient.get() .uri(uriBuilder -> uriBuilder.path(CustomerController.PATH_CUSTOMER)
.pathSegment(String.valueOf(customerId)) .build()) .retrieve() .onStatus(status -> status.is5xxServerError() || status.is4xxClientError(), response -> response.bodyToMono(String.class) .map(ApiGatewayException::new)) .bodyToMono(Customer.class); Mono<Billing> billingMono = webClient.get() .uri(uriBuilder -> uriBuilder.path(BillingController.PATH_BILLING) .pathSegment(String.valueOf(customerId)) .build()) .retrieve() .onStatus(status -> status.is5xxServerError() || status.is4xxClientError(), response -> response.bodyToMono(String.class) .map(ApiGatewayException::new)) .bodyToMono(Billing.class); return Mono.zip(customerMono, billingMono, (customer, billing) -> new CustomerInfo(customer.getId(), customer.getName(), billing.getBalance())) .block(); } }
repos\tutorials-master\spring-reactive-modules\spring-reactive-client-2\src\main\java\com\baeldung\synchronous\gateway\CustomerInfoService.java
1
请完成以下Java代码
public boolean openWindow(final AdWindowId adWindowId) { final WindowManager windowManager = null; final int adWorkbenchId = 0; return openWindow(windowManager, adWorkbenchId, adWindowId); } @Override public boolean openWindow(final WindowManager windowManager, final int AD_Workbench_ID, final AdWindowId adWindowId) { // // Show hidden window if any AWindow frame = (AWindow)Env.showWindow(adWindowId); if (frame != null) { addFrame(windowManager, frame); return true; } // // Find existing cached window and show it (if any) frame = findFrame(windowManager, adWindowId); if (frame != null) { final boolean isOneInstanceOnly = frame.getGridWindow().getVO().isOneInstanceOnly(); if (Ini.isPropertyBool(Ini.P_SINGLE_INSTANCE_PER_WINDOW) || isOneInstanceOnly) { AEnv.showWindow(frame); return true; } } // // New window frame = new AWindow(); final boolean OK; if (AD_Workbench_ID > 0) { OK = frame.initWorkbench(AD_Workbench_ID); } else { OK = frame.initWindow(adWindowId, null); // No Query Value } if (!OK) { return false; } if (Ini.isPropertyBool(Ini.P_OPEN_WINDOW_MAXIMIZED)) { AEnv.showMaximized(frame); } // Center the window
if (!Ini.isPropertyBool(Ini.P_OPEN_WINDOW_MAXIMIZED)) { // frame.validate(); // metas: tsa: is this still necessary? AEnv.showCenterScreen(frame); } addFrame(windowManager, frame); frame.getAPanel().requestFocusInWindow(); // metas-2009_0021_AP1_CR064: set Cursor to the first search field in the search panel return true; } private void addFrame(final WindowManager windowManager, final AWindow frame) { if (windowManager != null) { windowManager.add(frame); return; } AEnv.addToWindowManager(frame); } private AWindow findFrame(final WindowManager windowManager, final AdWindowId adWindowId) { if (windowManager != null) { return windowManager.find(adWindowId); } return AEnv.findInWindowManager(adWindowId); } @Override public I_AD_Window getWindowFromMenu(final Properties ctx, final int menuID) { final I_AD_Menu menu = InterfaceWrapperHelper.create(ctx, menuID, I_AD_Menu.class, ITrx.TRXNAME_None); if (menu == null) { return null; } final I_AD_Window window = menu.getAD_Window(); // only return the window if active if (window.isActive()) { return window; } return null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\adempiere\ui\api\impl\WindowBL.java
1
请完成以下Java代码
public String getProcessDefinitionId() { return processDefinitionId; } public void setInstructions(List<AbstractProcessInstanceModificationCommand> instructions) { this.instructions = instructions; } public void setProcessDefinitionId(String processDefinitionId) { this.processDefinitionId = processDefinitionId; } @Override public RestartProcessInstanceBuilder processInstanceIds(List<String> processInstanceIds) { this.processInstanceIds.addAll(processInstanceIds); return this; } @Override public RestartProcessInstanceBuilder initialSetOfVariables() { this.initialVariables = true; return this; } public boolean isInitialVariables() { return initialVariables; } @Override public RestartProcessInstanceBuilder skipCustomListeners() { this.skipCustomListeners = true;
return this; } @Override public RestartProcessInstanceBuilder skipIoMappings() { this.skipIoMappings = true; return this; } public boolean isSkipCustomListeners() { return skipCustomListeners; } public boolean isSkipIoMappings() { return skipIoMappings; } @Override public RestartProcessInstanceBuilder withoutBusinessKey() { withoutBusinessKey = true; return this; } public boolean isWithoutBusinessKey() { return withoutBusinessKey; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\RestartProcessInstanceBuilderImpl.java
1
请完成以下Java代码
public void setHtmlView(boolean isHtmlView) { this.isHtmlView = isHtmlView; } public void setName(String name) { this.name = name; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public Boolean getSkipDownLoad() { return skipDownLoad; } public void setSkipDownLoad(Boolean skipDownLoad) { this.skipDownLoad = skipDownLoad; } public String getTifPreviewType() { return tifPreviewType; } public void setTifPreviewType(String previewType) { this.tifPreviewType = previewType; }
public Boolean forceUpdatedCache() { return forceUpdatedCache; } public void setForceUpdatedCache(Boolean forceUpdatedCache) { this.forceUpdatedCache = forceUpdatedCache; } public String getKkProxyAuthorization() { return kkProxyAuthorization; } public void setKkProxyAuthorization(String kkProxyAuthorization) { this.kkProxyAuthorization = kkProxyAuthorization; } }
repos\kkFileView-master\server\src\main\java\cn\keking\model\FileAttribute.java
1
请完成以下Java代码
public String getTypeRef() { return typeRef; } public void setTypeRef(String typeRef) { this.typeRef = typeRef; } public UnaryTests getAllowedValues() { return allowedValues; } public void setAllowedValues(UnaryTests allowedValues) { this.allowedValues = allowedValues; } public List<ItemDefinition> getItemComponents() { return itemComponents; } public void setItemComponents(List<ItemDefinition> itemComponents) { this.itemComponents = itemComponents;
} public void addItemComponent(ItemDefinition itemComponent) { this.itemComponents.add(itemComponent); } public String getTypeLanguage() { return typeLanguage; } public void setTypeLanguage(String typeLanguage) { this.typeLanguage = typeLanguage; } public boolean isCollection() { return isCollection; } public void setCollection(boolean collection) { isCollection = collection; } }
repos\flowable-engine-main\modules\flowable-dmn-model\src\main\java\org\flowable\dmn\model\ItemDefinition.java
1
请完成以下Java代码
public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context) { if (context.isNoSelection()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection(); } if (context.isMoreThanOneSelected()) { return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection(); } final ProductId productId = ProductId.ofRepoIdOrNull(context.getSingleSelectedRecordId()); final I_M_Product productRecord = productDAO.getById(productId); if (productRecord.getM_AttributeSetInstance_ID() <= 0) {
return ProcessPreconditionsResolution.rejectWithInternalReason("The individual master data is already empty"); } return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() throws Exception { final ProductId productId = ProductId.ofRepoId(getRecord_ID()); productDAO.clearIndividualMasterDataFromProduct(productId); return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\product\process\M_Product_Clear_AttributeSetInstance.java
1
请完成以下Java代码
public void onEvent(ActivitiEvent event) { if (isValidEvent(event)) { Object delegate = DelegateExpressionUtil.resolveDelegateExpression( expression, new NoExecutionVariableScope() ); if (delegate instanceof ActivitiEventListener) { // Cache result of isFailOnException() from delegate-instance // until next event is received. This prevents us from having to resolve // the expression twice when an error occurs. failOnException = ((ActivitiEventListener) delegate).isFailOnException(); // Call the delegate ((ActivitiEventListener) delegate).onEvent(event); } else { // Force failing, since the exception we're about to throw // cannot be ignored, because it did not originate from the listener itself failOnException = true;
throw new ActivitiIllegalArgumentException( "Delegate expression " + expression + " did not resolve to an implementation of " + ActivitiEventListener.class.getName() ); } } } @Override public boolean isFailOnException() { return failOnException; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\helper\DelegateExpressionActivitiEventListener.java
1
请完成以下Java代码
private static void processField(Object target, Field field, Properties arguments) { Argument argument = field.getAnnotation(Argument.class); if (argument != null) { String name = Args.getName(argument, field); String alias = Args.getAlias(argument); Class type = field.getType(); Object value = arguments.get(name); if (value == null && alias != null) { value = arguments.get(alias); } if (value != null) { if (type == Boolean.TYPE || type == Boolean.class) { value = true; } Args.setField(type, field, target, value, argument.delimiter()); } else { if (argument.required()) { throw new IllegalArgumentException("You must set argument " + name); } } } } private static void processProperty(Object target, PropertyDescriptor property, Properties arguments) { Method writeMethod = property.getWriteMethod(); if (writeMethod != null) { Argument argument = writeMethod.getAnnotation(Argument.class);
if (argument != null) { String name = Args.getName(argument, property); String alias = Args.getAlias(argument); Object value = arguments.get(name); if (value == null && alias != null) { value = arguments.get(alias); } if (value != null) { Class type = property.getPropertyType(); if (type == Boolean.TYPE || type == Boolean.class) { value = true; } Args.setProperty(type, property, target, value, argument.delimiter()); } else { if (argument.required()) { throw new IllegalArgumentException("You must set argument " + name); } } } } } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\perceptron\cli\PropertiesArgs.java
1