instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public void setIsParameterNextLine(boolean IsParameterNextLine)
{
set_Value (COLUMNNAME_IsParameterNextLine, Boolean.valueOf(IsParameterNextLine));
}
public void setParameterSeqNo (int ParameterSeqNo)
{
set_Value (COLUMNNAME_ParameterSeqNo, Integer.valueOf(ParameterSeqNo));
}
public int getParameterSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_ParameterSeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
public void setParameterDisplayLogic (String ParameterDisplayLogic)
{
set_Value (COLUMNNAME_ParameterDisplayLogic, ParameterDisplayLogic);
}
public String getParameterDisplayLogic ()
{
return (String)get_Value(COLUMNNAME_ParameterDisplayLogic);
}
public void setColumnName (String ColumnName)
{
set_Value (COLUMNNAME_ColumnName, ColumnName);
}
public String getColumnName ()
{
return (String)get_Value(COLUMNNAME_ColumnName);
}
/** Set Query Criteria Function.
@param QueryCriteriaFunction
column used for adding a sql function to query criteria | */
public void setQueryCriteriaFunction (String QueryCriteriaFunction)
{
set_Value (COLUMNNAME_QueryCriteriaFunction, QueryCriteriaFunction);
}
/** Get Query Criteria Function.
@return column used for adding a sql function to query criteria
*/
public String getQueryCriteriaFunction ()
{
return (String)get_Value(COLUMNNAME_QueryCriteriaFunction);
}
@Override
public void setDefaultValue (String DefaultValue)
{
set_Value (COLUMNNAME_DefaultValue, DefaultValue);
}
@Override
public String getDefaultValue ()
{
return (String)get_Value(COLUMNNAME_DefaultValue);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_InfoColumn.java | 1 |
请完成以下Java代码 | void reserveId(int id)
{
if (id >= _units.size())
{
expandUnits();
}
if (id == _extrasHead)
{
_extrasHead = extras(id).next;
if (_extrasHead == id)
{
_extrasHead = _units.size();
}
}
extras(extras(id).prev).next = extras(id).next;
extras(extras(id).next).prev = extras(id).prev;
extras(id).isFixed = true;
}
void expandUnits()
{
int srcNumUnits = _units.size();
int srcNumBlocks = numBlocks();
int destNumUnits = srcNumUnits + BLOCK_SIZE;
int destNumBlocks = srcNumBlocks + 1;
if (destNumBlocks > NUM_EXTRA_BLOCKS)
{
fixBlock(srcNumBlocks - NUM_EXTRA_BLOCKS);
}
_units.resize(destNumUnits);
if (destNumBlocks > NUM_EXTRA_BLOCKS)
{
for (int id = srcNumUnits; id < destNumUnits; ++id)
{
extras(id).isUsed = false;
extras(id).isFixed = false;
}
}
for (int i = srcNumUnits + 1; i < destNumUnits; ++i)
{
extras(i - 1).next = i;
extras(i).prev = i - 1;
}
extras(srcNumUnits).prev = destNumUnits - 1;
extras(destNumUnits - 1).next = srcNumUnits;
extras(srcNumUnits).prev = extras(_extrasHead).prev;
extras(destNumUnits - 1).next = _extrasHead;
extras(extras(_extrasHead).prev).next = srcNumUnits;
extras(_extrasHead).prev = destNumUnits - 1; | }
void fixAllBlocks()
{
int begin = 0;
if (numBlocks() > NUM_EXTRA_BLOCKS)
{
begin = numBlocks() - NUM_EXTRA_BLOCKS;
}
int end = numBlocks();
for (int blockId = begin; blockId != end; ++blockId)
{
fixBlock(blockId);
}
}
void fixBlock(int blockId)
{
int begin = blockId * BLOCK_SIZE;
int end = begin + BLOCK_SIZE;
int unusedOffset = 0;
for (int offset = begin; offset != end; ++offset)
{
if (!extras(offset).isUsed)
{
unusedOffset = offset;
break;
}
}
for (int id = begin; id != end; ++id)
{
if (!extras(id).isFixed)
{
reserveId(id);
int[] units = _units.getBuffer();
// units[id].setLabel(id ^ unused_offset);
units[id] = (units[id] & ~0xFF)
| ((id ^ unusedOffset) & 0xFF);
}
}
}
private AutoIntPool _units = new AutoIntPool();
private DoubleArrayBuilderExtraUnit[] _extras;
private AutoBytePool _labels = new AutoBytePool();
private int[] _table;
private int _extrasHead;
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\dartsclone\details\DoubleArrayBuilder.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void updateEngineProperty(@ApiParam(name = "engineProperty") @PathVariable String engineProperty, @RequestBody PropertyRequestBody propertyRequestBody) {
validateAccessToProperties();
validatePropertyExists(engineProperty);
managementService.executeCommand(commandContext -> {
PropertyEntityManager propertyEntityManager = CommandContextUtil.getPropertyEntityManager(commandContext);
PropertyEntity propertyEntity = propertyEntityManager.findById(engineProperty);
propertyEntity.setValue(propertyRequestBody.getValue());
propertyEntityManager.update(propertyEntity);
return null;
});
}
public static class PropertyRequestBody {
protected String name;
protected String value;
public PropertyRequestBody() {
}
public PropertyRequestBody(String name, String value) {
this.name = name;
this.value = value; | }
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
} | repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\management\EnginePropertiesResource.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class RequestStatusCategoryId implements RepoIdAware
{
@JsonCreator
public static RequestStatusCategoryId ofRepoId(final int repoId)
{
return new RequestStatusCategoryId(repoId);
}
@Nullable
public static RequestStatusCategoryId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? ofRepoId(repoId) : null;
}
public static int toRepoId(@Nullable final RequestStatusCategoryId categoryId)
{ | return categoryId != null ? categoryId.getRepoId() : -1;
}
int repoId;
private RequestStatusCategoryId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "R_StatusCategory_ID");
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\request\RequestStatusCategoryId.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void execute()
{
ServiceRepairProjectTask task = projectTaskRepository
.getTaskByRepairOrderId(repairOrder.getProjectId(), repairOrder.getId())
.orElseThrow(() -> new AdempiereException("No task found for " + repairOrder));
final Set<PPOrderAndCostCollectorId> alreadyImportedRepairCostCollectorIds = projectCostCollectorRepository.retainExistingPPCostCollectorIds(
repairOrder.getProjectId(),
repairOrder.getCostCollectorIds());
for (final RepairManufacturingCostCollector mfgCostCollector : repairOrder.getCostCollectors())
{
// skip already imported cost collectors
if (alreadyImportedRepairCostCollectorIds.contains(mfgCostCollector.getId()))
{
continue;
}
createCostCollector_RepairingConsumption(task, mfgCostCollector);
}
if (!projectCostCollectorRepository.matchesByTaskAndProduct(task.getId(), repairOrder.getRepairedProductId()))
{
createCostCollector_RepairedProductToReturn(task);
}
task = task.withRepairOrderDone(repairOrder.getSummary(), repairOrder.getServicePerformedId());
projectTaskRepository.save(task);
}
private void createCostCollector_RepairingConsumption(
@NonNull final ServiceRepairProjectTask task,
@NonNull final RepairManufacturingCostCollector mfgCostCollector)
{ | serviceRepairProjectService.createCostCollector(CreateProjectCostCollectorRequest.builder()
.taskId(task.getId())
.type(ServiceRepairProjectCostCollectorType.RepairingConsumption)
.productId(mfgCostCollector.getProductId())
.qtyConsumed(mfgCostCollector.getQtyConsumed())
.repairOrderCostCollectorId(mfgCostCollector.getId())
.warrantyCase(task.getWarrantyCase())
.build());
}
private void createCostCollector_RepairedProductToReturn(
@NonNull final ServiceRepairProjectTask task)
{
final ProductId repairedProductId = repairOrder.getRepairedProductId();
final HuId repairedVhuId = Objects.requireNonNull(task.getRepairVhuId());
final AttributeSetInstanceId asiId = handlingUnitsBL.createASIFromHUAttributes(repairedProductId, repairedVhuId);
serviceRepairProjectService.createCostCollector(CreateProjectCostCollectorRequest.builder()
.taskId(task.getId())
.type(ServiceRepairProjectCostCollectorType.RepairedProductToReturn)
.productId(repairedProductId)
.asiId(asiId)
.warrantyCase(task.getWarrantyCase())
.qtyReserved(repairOrder.getRepairedQty())
.reservedVhuId(repairedVhuId)
.build());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.base\src\main\java\de\metas\servicerepair\project\service\commands\ImportProjectCostsFromRepairOrderCommand.java | 2 |
请完成以下Java代码 | public VariableMap submitTaskFormWithVariablesInReturn(String taskId, Map<String, Object> properties, boolean deserializeValues) {
return commandExecutor.execute(new SubmitTaskFormCmd(taskId, properties, true, deserializeValues));
}
public String getStartFormKey(String processDefinitionId) {
return commandExecutor.execute(new GetFormKeyCmd(processDefinitionId));
}
public String getTaskFormKey(String processDefinitionId, String taskDefinitionKey) {
return commandExecutor.execute(new GetFormKeyCmd(processDefinitionId, taskDefinitionKey));
}
public VariableMap getStartFormVariables(String processDefinitionId) {
return getStartFormVariables(processDefinitionId, null, true);
}
public VariableMap getStartFormVariables(String processDefinitionId, Collection<String> formVariables, boolean deserializeObjectValues) {
return commandExecutor.execute(new GetStartFormVariablesCmd(processDefinitionId, formVariables, deserializeObjectValues));
} | public VariableMap getTaskFormVariables(String taskId) {
return getTaskFormVariables(taskId, null, true);
}
public VariableMap getTaskFormVariables(String taskId, Collection<String> formVariables, boolean deserializeObjectValues) {
return commandExecutor.execute(new GetTaskFormVariablesCmd(taskId, formVariables, deserializeObjectValues));
}
public InputStream getDeployedStartForm(String processDefinitionId) {
return commandExecutor.execute(new GetDeployedStartFormCmd(processDefinitionId));
}
public InputStream getDeployedTaskForm(String taskId) {
return commandExecutor.execute(new GetDeployedTaskFormCmd(taskId));
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\FormServiceImpl.java | 1 |
请完成以下Java代码 | public void addQtyReserved(final Properties ctx,
final I_M_Locator locator,
final int productId,
final int attributeSetInstanceId,
final BigDecimal diffQtyReserved,
final String trxName)
{
if (isMStorageDisabled())
{
return;
}
MStorage.add(ctx,
locator.getM_Warehouse_ID(),
locator.getM_Locator_ID(),
productId, // M_Product_ID,
attributeSetInstanceId, // M_AttributeSetInstance_ID,
attributeSetInstanceId, // reservationAttributeSetInstance_ID,
BigDecimal.ZERO, // diffQtyOnHand,
diffQtyReserved, // diffQtyReserved,
BigDecimal.ZERO, // diffQtyOrdered
trxName);
}
@Override
public void addAsync(final Properties ctx,
final int M_Warehouse_ID,
final int M_Locator_ID,
final int M_Product_ID,
final int M_AttributeSetInstance_ID,
final int reservationAttributeSetInstance_ID,
final BigDecimal diffQtyOnHand,
final BigDecimal diffQtyReserved,
final BigDecimal diffQtyOrdered,
final String trxName)
{
if (isMStorageDisabled())
{
return;
}
// @formatter:off
Services.get(IWorkPackageQueueFactory.class).getQueueForEnqueuing(ctx, M_Storage_Add.class)
.newWorkPackage()
.bindToTrxName(trxName)
.parameters()
.setParameter(M_Storage_Add.WP_PARAM_M_Warehouse_ID, M_Warehouse_ID)
.setParameter(M_Storage_Add.WP_PARAM_M_Locator_ID, M_Locator_ID)
.setParameter(M_Storage_Add.WP_PARAM_M_Product_ID, M_Product_ID)
.setParameter(M_Storage_Add.WP_PARAM_M_AttributeSetInstance_ID, M_AttributeSetInstance_ID)
.setParameter(M_Storage_Add.WP_PARAM_reservationAttributeSetInstance_ID, reservationAttributeSetInstance_ID)
.setParameter(M_Storage_Add.WP_PARAM_diffQtyOnHand, diffQtyOnHand)
.setParameter(M_Storage_Add.WP_PARAM_diffQtyReserved, diffQtyReserved)
.setParameter(M_Storage_Add.WP_PARAM_diffQtyOrdered, diffQtyOrdered)
.end()
.buildAndEnqueue(); // @formatter:on
}
@Override
public void add(
final Properties ctx,
final int M_Warehouse_ID,
final int M_Locator_ID, | final int M_Product_ID,
final int M_AttributeSetInstance_ID,
final int reservationAttributeSetInstance_ID,
final BigDecimal diffQtyOnHand,
final BigDecimal diffQtyReserved,
final BigDecimal diffQtyOrdered,
final String trxName)
{
if (isMStorageDisabled())
{
return;
}
MStorage.add(ctx,
M_Warehouse_ID,
M_Locator_ID,
M_Product_ID,
M_AttributeSetInstance_ID,
reservationAttributeSetInstance_ID,
diffQtyOnHand,
diffQtyReserved,
diffQtyOrdered,
trxName);
}
private boolean isMStorageDisabled()
{
return Services.get(ISysConfigBL.class).getBooleanValue(CFG_M_STORAGE_DISABLED, false);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\product\impl\StorageBL.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class UserArgumentResolver implements HandlerMethodArgumentResolver {
private final UserRepository userRepository;
@Override
public boolean supportsParameter(MethodParameter parameter) {
return parameter.getParameterType() == User.class;
}
@Override
public Object resolveArgument(
MethodParameter parameter,
ModelAndViewContainer mavContainer,
NativeWebRequest webRequest,
WebDataBinderFactory binderFactory) {
SecurityContext securityContext = SecurityContextHolder.getContext();
Authentication authentication = securityContext.getAuthentication(); | if (authentication instanceof AnonymousAuthenticationToken) {
return User.anonymous();
}
JwtAuthenticationToken jwtAuthenticationToken = (JwtAuthenticationToken) authentication;
String userId = jwtAuthenticationToken.getName().strip();
String token = jwtAuthenticationToken.getToken().getTokenValue().strip();
return userRepository
.findById(UUID.fromString(userId))
.map(it -> it.possessToken(token))
.orElseThrow(() -> new InvalidBearerTokenException("`%s` is invalid token".formatted(token)));
}
} | repos\realworld-spring-boot-native-master\src\main\java\com\softwaremill\realworld\application\config\UserArgumentResolver.java | 2 |
请完成以下Java代码 | public int getC_PaymentTerm_ID()
{
return get_ValueAsInt(COLUMNNAME_C_PaymentTerm_ID);
}
@Override
public void setDueAmt (final BigDecimal DueAmt)
{
set_Value (COLUMNNAME_DueAmt, DueAmt);
}
@Override
public BigDecimal getDueAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_DueAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setDueDate (final java.sql.Timestamp DueDate)
{
set_Value (COLUMNNAME_DueDate, DueDate);
}
@Override
public java.sql.Timestamp getDueDate()
{
return get_ValueAsTimestamp(COLUMNNAME_DueDate);
}
@Override
public void setOffsetDays (final int OffsetDays)
{
set_Value (COLUMNNAME_OffsetDays, OffsetDays);
}
@Override
public int getOffsetDays()
{
return get_ValueAsInt(COLUMNNAME_OffsetDays);
}
@Override
public void setPercent (final int Percent)
{
set_Value (COLUMNNAME_Percent, Percent);
}
@Override
public int getPercent()
{
return get_ValueAsInt(COLUMNNAME_Percent);
}
/**
* ReferenceDateType AD_Reference_ID=541989
* Reference name: ReferenceDateType
*/
public static final int REFERENCEDATETYPE_AD_Reference_ID=541989;
/** InvoiceDate = IV */
public static final String REFERENCEDATETYPE_InvoiceDate = "IV";
/** BLDate = BL */
public static final String REFERENCEDATETYPE_BLDate = "BL";
/** OrderDate = OD */ | public static final String REFERENCEDATETYPE_OrderDate = "OD";
/** LCDate = LC */
public static final String REFERENCEDATETYPE_LCDate = "LC";
/** ETADate = ET */
public static final String REFERENCEDATETYPE_ETADate = "ET";
@Override
public void setReferenceDateType (final java.lang.String ReferenceDateType)
{
set_Value (COLUMNNAME_ReferenceDateType, ReferenceDateType);
}
@Override
public java.lang.String getReferenceDateType()
{
return get_ValueAsString(COLUMNNAME_ReferenceDateType);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
/**
* Status AD_Reference_ID=541993
* Reference name: C_OrderPaySchedule_Status
*/
public static final int STATUS_AD_Reference_ID=541993;
/** Pending_Ref = PR */
public static final String STATUS_Pending_Ref = "PR";
/** Awaiting_Pay = WP */
public static final String STATUS_Awaiting_Pay = "WP";
/** Paid = P */
public static final String STATUS_Paid = "P";
@Override
public void setStatus (final java.lang.String Status)
{
set_Value (COLUMNNAME_Status, Status);
}
@Override
public java.lang.String getStatus()
{
return get_ValueAsString(COLUMNNAME_Status);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_OrderPaySchedule.java | 1 |
请完成以下Java代码 | public static TransportProtos.GetAttributeRequestMsg toGetAttributeRequestMsg(Request inbound) throws AdaptorException {
List<String> queryElements = inbound.getOptions().getUriQuery();
TransportProtos.GetAttributeRequestMsg.Builder result = TransportProtos.GetAttributeRequestMsg.newBuilder();
if (queryElements != null && queryElements.size() > 0) {
Set<String> clientKeys = toKeys(queryElements, "clientKeys");
Set<String> sharedKeys = toKeys(queryElements, "sharedKeys");
if (clientKeys != null) {
result.addAllClientAttributeNames(clientKeys);
}
if (sharedKeys != null) {
result.addAllSharedAttributeNames(sharedKeys);
}
}
result.setOnlyShared(false);
return result.build();
} | private static Set<String> toKeys(List<String> queryElements, String attributeName) throws AdaptorException {
String keys = null;
for (String queryElement : queryElements) {
String[] queryItem = queryElement.split("=");
if (queryItem.length == 2 && queryItem[0].equals(attributeName)) {
keys = queryItem[1];
}
}
if (keys != null && !StringUtils.isEmpty(keys)) {
return new HashSet<>(Arrays.asList(keys.split(",")));
} else {
return null;
}
}
} | repos\thingsboard-master\common\transport\coap\src\main\java\org\thingsboard\server\transport\coap\adaptors\CoapAdaptorUtils.java | 1 |
请完成以下Java代码 | public void setIsSOTrx (boolean IsSOTrx)
{
set_Value (COLUMNNAME_IsSOTrx, Boolean.valueOf(IsSOTrx));
}
/** Get Sales Transaction.
@return This is a Sales Transaction
*/
@Override
public boolean isSOTrx ()
{
Object oo = get_Value(COLUMNNAME_IsSOTrx);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Referenz.
@param Reference
Bezug für diesen Eintrag | */
@Override
public void setReference (java.lang.String Reference)
{
set_Value (COLUMNNAME_Reference, Reference);
}
/** Get Referenz.
@return Bezug für diesen Eintrag
*/
@Override
public java.lang.String getReference ()
{
return (java.lang.String)get_Value(COLUMNNAME_Reference);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-gen\de\metas\banking\model\X_C_Payment_Request.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void configure(HttpSecurity http) throws Exception {
http
.csrf()
.disable()
.headers()
.frameOptions()
.disable()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/api/**").authenticated()
.antMatchers("/management/health").permitAll()
.antMatchers("/management/info").permitAll()
.antMatchers("/management/**").hasAuthority(AuthoritiesConstants.ADMIN);
}
@Bean
public TokenStore tokenStore(JwtAccessTokenConverter jwtAccessTokenConverter) {
return new JwtTokenStore(jwtAccessTokenConverter);
}
@Bean | public JwtAccessTokenConverter jwtAccessTokenConverter(OAuth2SignatureVerifierClient signatureVerifierClient) {
return new OAuth2JwtAccessTokenConverter(oAuth2Properties, signatureVerifierClient);
}
@Bean
@Qualifier("loadBalancedRestTemplate")
public RestTemplate loadBalancedRestTemplate(RestTemplateCustomizer customizer) {
RestTemplate restTemplate = new RestTemplate();
customizer.customize(restTemplate);
return restTemplate;
}
@Bean
@Qualifier("vanillaRestTemplate")
public RestTemplate vanillaRestTemplate() {
return new RestTemplate();
}
} | repos\tutorials-master\jhipster-modules\jhipster-uaa\quotes\src\main\java\com\baeldung\jhipster\quotes\config\SecurityConfiguration.java | 2 |
请完成以下Java代码 | private void initSession() {
if (this.keyspaceName != null) {
this.sessionBuilder.withKeyspace(this.keyspaceName);
}
this.sessionBuilder.withLocalDatacenter(localDatacenter);
if (StringUtils.isNotBlank(cloudSecureConnectBundlePath)) {
this.sessionBuilder.withCloudSecureConnectBundle(Paths.get(cloudSecureConnectBundlePath));
this.sessionBuilder.withAuthCredentials(cloudClientId, cloudClientSecret);
}
session = sessionBuilder.build();
if (this.metrics && this.jmx) {
MetricRegistry registry =
session.getMetrics().orElseThrow(
() -> new IllegalStateException("Metrics are disabled"))
.getRegistry();
this.reporter =
JmxReporter.forRegistry(registry)
.inDomain("com.datastax.oss.driver")
.build();
this.reporter.start();
}
}
@PreDestroy
public void close() { | if (reporter != null) {
reporter.stop();
}
if (session != null) {
session.close();
}
}
public ConsistencyLevel getDefaultReadConsistencyLevel() {
return driverOptions.getDefaultReadConsistencyLevel();
}
public ConsistencyLevel getDefaultWriteConsistencyLevel() {
return driverOptions.getDefaultWriteConsistencyLevel();
}
} | repos\thingsboard-master\common\dao-api\src\main\java\org\thingsboard\server\dao\cassandra\AbstractCassandraCluster.java | 1 |
请完成以下Java代码 | private void shiftLeft() {
int i = 1;
while (i < items.length) {
if (items[i] == null) {
break;
}
items[i - 1] = items[i];
i++;
}
}
@Override
public E peek() {
if (count <= 0) {
return null;
} | return (E) items[0];
}
@Override
public int size() {
return count;
}
@Override
public Iterator<E> iterator() {
List<E> list = new ArrayList<>(count);
for (int i = 0; i < count; i++) {
list.add((E) items[i]);
}
return list.iterator();
}
} | repos\tutorials-master\core-java-modules\core-java-collections-4\src\main\java\com\baeldung\collections\fixedsizequeues\FifoFixedSizeQueue.java | 1 |
请完成以下Java代码 | public static int[] mergeAndRemoveDuplicatesOnSortedArray(int[] arr1, int[] arr2) {
return removeDuplicateOnSortedArray(mergeArrays(arr1, arr2));
}
private static int[] mergeArrays(int[] arr1, int[] arr2) {
int[] mergedArrays = new int[arr1.length + arr2.length];
System.arraycopy(arr1, 0, mergedArrays, 0, arr1.length);
System.arraycopy(arr2, 0, mergedArrays, arr1.length, arr2.length);
return mergedArrays;
}
private static int[] removeDuplicate(int[] arr) {
int[] withoutDuplicates = new int[arr.length];
int i = 0;
for(int element : arr) {
if(!isElementPresent(withoutDuplicates, element)) {
withoutDuplicates[i] = element;
i++;
} | }
int[] truncatedArray = new int[i];
System.arraycopy(withoutDuplicates, 0, truncatedArray, 0, i);
return truncatedArray;
}
private static boolean isElementPresent(int[] arr, int element) {
for(int el : arr) {
if(el == element) {
return true;
}
}
return false;
}
} | repos\tutorials-master\core-java-modules\core-java-arrays-guides\src\main\java\com\baeldung\mergeandremoveduplicate\MergeArraysAndRemoveDuplicate.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class AotApplication {
public static void main(String[] args) {
SpringApplication.run(AotApplication.class, args);
}
@Bean
CommandLineRunner commandLineRunner(UserRepository repository, CassandraOperations operations)
throws InterruptedException {
operations.getCqlOperations().execute("CREATE INDEX IF NOT EXISTS user_username ON users (uname);");
operations.getCqlOperations().execute(
"CREATE CUSTOM INDEX IF NOT EXISTS users_lname_idx_1 ON users (lname) USING 'org.apache.cassandra.index.sasi.SASIIndex';");
/*
Cassandra secondary indexes are created in the background without the possibility to check
whether they are available or not. So we are forced to just wait. *sigh*
*/
Thread.sleep(1000);
return args -> {
User user = new User();
user.setId(42L); | user.setUsername("heisenberg");
user.setFirstname("Walter");
user.setLastname("White");
user.setCurrent(new Address("308 Negra Arroyo Lane", "87104", "Albuquerque"));
user.setPrevious(Collections.singletonList(new Address("12000 – 12100 Coors Rd SW", "87045", "Albuquerque")));
repository.save(user);
System.out.println("------- Annotated Single -------");
System.out.println(repository.findUserByIdIn(1000));
System.out.println(repository.findUserByIdIn(42));
System.out.println("------- Derived Single -------");
System.out.println(repository.findUserByUsername(user.getUsername()));
System.out.println("------- Derived SASI -------");
System.out.println(repository.findUsersByLastnameStartsWith("White", Limit.of(1)));
};
}
} | repos\spring-data-examples-main\cassandra\aot-optimization\src\main\java\example\springdata\cassandra\AotApplication.java | 2 |
请完成以下Java代码 | public void execute(DelegateExecution execution) {
readFields(execution);
List<String> argList = new ArrayList<>();
argList.add(commandStr);
if (arg1Str != null) {
argList.add(arg1Str);
}
if (arg2Str != null) {
argList.add(arg2Str);
}
if (arg3Str != null) {
argList.add(arg3Str);
}
if (arg4Str != null) {
argList.add(arg4Str);
}
if (arg5Str != null) {
argList.add(arg5Str);
}
ProcessBuilder processBuilder = new ProcessBuilder(argList);
try {
processBuilder.redirectErrorStream(redirectErrorFlag);
if (cleanEnvBoolean) {
Map<String, String> env = processBuilder.environment();
env.clear();
}
if (directoryStr != null && directoryStr.length() > 0) {
processBuilder.directory(new File(directoryStr));
}
Process process = processBuilder.start();
if (waitFlag) {
int errorCode = process.waitFor();
if (resultVariableStr != null) {
String result = convertStreamToStr(process.getInputStream());
execution.setVariable(resultVariableStr, result);
}
if (errorCodeVariableStr != null) {
execution.setVariable(errorCodeVariableStr, Integer.toString(errorCode));
}
}
} catch (Exception e) {
throw new FlowableException("Could not execute shell command for " + execution, e);
}
leave(execution); | }
public static String convertStreamToStr(InputStream is) throws IOException {
if (is != null) {
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} finally {
is.close();
}
return writer.toString();
} else {
return "";
}
}
protected String getStringFromField(Expression expression, DelegateExecution execution) {
if (expression != null) {
Object value = expression.getValue(execution);
if (value != null) {
return value.toString();
}
}
return null;
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\bpmn\behavior\ShellActivityBehavior.java | 1 |
请完成以下Java代码 | public void setIsPrinted (boolean IsPrinted)
{
set_Value (COLUMNNAME_IsPrinted, Boolean.valueOf(IsPrinted));
}
/** Get Printed.
@return Indicates if this document / line is printed
*/
public boolean isPrinted ()
{
Object oo = get_Value(COLUMNNAME_IsPrinted);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Max Value.
@param MaxValue Max Value */
public void setMaxValue (int MaxValue)
{
set_Value (COLUMNNAME_MaxValue, Integer.valueOf(MaxValue));
}
/** Get Max Value.
@return Max Value */
public int getMaxValue ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_MaxValue);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Min Value.
@param MinValue Min Value */
public void setMinValue (int MinValue)
{
set_Value (COLUMNNAME_MinValue, Integer.valueOf(MinValue));
}
/** Get Min Value.
@return Min Value */
public int getMinValue ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_MinValue);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Quantity.
@param Qty
Quantity
*/
public void setQty (BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
/** Get Quantity.
@return Quantity
*/
public BigDecimal getQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Service date.
@param ServiceDate
Date service was provided
*/
public void setServiceDate (Timestamp ServiceDate)
{
set_Value (COLUMNNAME_ServiceDate, ServiceDate);
}
/** Get Service date.
@return Date service was provided
*/
public Timestamp getServiceDate ()
{
return (Timestamp)get_Value(COLUMNNAME_ServiceDate);
}
/** Set Text Message.
@param TextMsg | Text Message
*/
public void setTextMsg (String TextMsg)
{
set_Value (COLUMNNAME_TextMsg, TextMsg);
}
/** Get Text Message.
@return Text Message
*/
public String getTextMsg ()
{
return (String)get_Value(COLUMNNAME_TextMsg);
}
/** Set Valid from.
@param ValidFrom
Valid from including this date (first day)
*/
public void setValidFrom (Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
/** Get Valid from.
@return Valid from including this date (first day)
*/
public Timestamp getValidFrom ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidFrom);
}
/** Set Valid to.
@param ValidTo
Valid to including this date (last day)
*/
public void setValidTo (Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
/** Get Valid to.
@return Valid to including this date (last day)
*/
public Timestamp getValidTo ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidTo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_Attribute.java | 1 |
请完成以下Java代码 | public class HistoryCleanupJobDeclaration extends JobDeclaration<HistoryCleanupContext, EverLivingJobEntity> {
private final static CommandLogger LOG = ProcessEngineLogger.CMD_LOGGER;
public HistoryCleanupJobDeclaration() {
super(HistoryCleanupJobHandler.TYPE);
}
@Override
protected ExecutionEntity resolveExecution(HistoryCleanupContext context) {
return null;
}
@Override
protected EverLivingJobEntity newJobInstance(HistoryCleanupContext context) {
return new EverLivingJobEntity();
}
@Override
protected void postInitialize(HistoryCleanupContext context, EverLivingJobEntity job) {
}
@Override
public EverLivingJobEntity reconfigure(HistoryCleanupContext context, EverLivingJobEntity job) {
HistoryCleanupJobHandlerConfiguration configuration = resolveJobHandlerConfiguration(context);
job.setJobHandlerConfiguration(configuration);
return job;
}
@Override
protected HistoryCleanupJobHandlerConfiguration resolveJobHandlerConfiguration(HistoryCleanupContext context) {
HistoryCleanupJobHandlerConfiguration config = new HistoryCleanupJobHandlerConfiguration();
config.setImmediatelyDue(context.isImmediatelyDue());
config.setMinuteFrom(context.getMinuteFrom());
config.setMinuteTo(context.getMinuteTo());
return config;
}
@Override
protected int resolveRetries(HistoryCleanupContext context) {
return context.getMaxRetries();
} | @Override
public Date resolveDueDate(HistoryCleanupContext context) {
return resolveDueDate(context.isImmediatelyDue());
}
private Date resolveDueDate(boolean isImmediatelyDue) {
CommandContext commandContext = Context.getCommandContext();
if (isImmediatelyDue) {
return ClockUtil.getCurrentTime();
} else {
final BatchWindow currentOrNextBatchWindow = commandContext.getProcessEngineConfiguration().getBatchWindowManager()
.getCurrentOrNextBatchWindow(ClockUtil.getCurrentTime(), commandContext.getProcessEngineConfiguration());
if (currentOrNextBatchWindow != null) {
return currentOrNextBatchWindow.getStart();
} else {
return null;
}
}
}
public ParameterValueProvider getJobPriorityProvider() {
ProcessEngineConfigurationImpl configuration = Context.getProcessEngineConfiguration();
long historyCleanupJobPriority = configuration.getHistoryCleanupJobPriority();
return new ConstantValueProvider(historyCleanupJobPriority);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\historycleanup\HistoryCleanupJobDeclaration.java | 1 |
请完成以下Java代码 | public String getElementId() {
return innerPlanItemInstance.getElementId();
}
@Override
public String getPlanItemDefinitionId() {
return innerPlanItemInstance.getPlanItemDefinitionId();
}
@Override
public String getStageInstanceId() {
return innerPlanItemInstance.getStageInstanceId();
}
@Override
public String getState() { | return innerPlanItemInstance.getState();
}
@Override
public String toString() {
return "GenericEventListenerInstanceImpl{" +
"id='" + getId() + '\'' +
", name='" + getName() + '\'' +
", caseInstanceId='" + getCaseInstanceId() + '\'' +
", caseDefinitionId='" + getCaseDefinitionId() + '\'' +
", elementId='" + getElementId() + '\'' +
", planItemDefinitionId='" + getPlanItemDefinitionId() + '\'' +
", stageInstanceId='" + getStageInstanceId() + '\'' +
'}';
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\GenericEventListenerInstanceImpl.java | 1 |
请完成以下Java代码 | public String getHelp ()
{
return (String)get_Value(COLUMNNAME_Help);
}
/** Set Exclude.
@param IsExclude
Exclude access to the data - if not selected Include access to the data
*/
public void setIsExclude (boolean IsExclude)
{
set_Value (COLUMNNAME_IsExclude, Boolean.valueOf(IsExclude));
}
/** Get Exclude.
@return Exclude access to the data - if not selected Include access to the data
*/
public boolean isExclude ()
{
Object oo = get_Value(COLUMNNAME_IsExclude);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
} | /** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_AccessProfile.java | 1 |
请完成以下Java代码 | public void onMessage(Session session, Message message) {
message.setFrom(users.get(session.getId()));
broadcast(message);
}
@OnClose
public void onClose(Session session) {
chatEndpoints.remove(this);
Message message = new Message();
message.setFrom(users.get(session.getId()));
message.setContent("Disconnected!");
broadcast(message);
}
@OnError
public void onError(Session session, Throwable throwable) {
// Do error handling here
} | private static void broadcast(Message message) {
chatEndpoints.forEach(endpoint -> {
synchronized (endpoint) {
try {
endpoint.session.getBasicRemote()
.sendObject(message);
} catch (IOException | EncodeException e) {
e.printStackTrace();
}
}
});
}
} | repos\tutorials-master\core-java-modules\java-websocket\src\main\java\com\baeldung\websocket\ChatEndpoint.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public DeviceProfile save(DeviceProfile deviceProfile, SecurityUser user) throws Exception {
ActionType actionType = deviceProfile.getId() == null ? ActionType.ADDED : ActionType.UPDATED;
TenantId tenantId = deviceProfile.getTenantId();
try {
DeviceProfile savedDeviceProfile = checkNotNull(deviceProfileService.saveDeviceProfile(deviceProfile));
autoCommit(user, savedDeviceProfile.getId());
logEntityActionService.logEntityAction(tenantId, savedDeviceProfile.getId(), savedDeviceProfile,
null, actionType, user);
return savedDeviceProfile;
} catch (Exception e) {
logEntityActionService.logEntityAction(tenantId, emptyId(EntityType.DEVICE_PROFILE), deviceProfile, actionType, user, e);
throw e;
}
}
@Override
public void delete(DeviceProfile deviceProfile, User user) {
ActionType actionType = ActionType.DELETED;
DeviceProfileId deviceProfileId = deviceProfile.getId();
TenantId tenantId = deviceProfile.getTenantId();
try {
deviceProfileService.deleteDeviceProfile(tenantId, deviceProfileId);
logEntityActionService.logEntityAction(tenantId, deviceProfileId, deviceProfile, null,
actionType, user, deviceProfileId.toString());
} catch (Exception e) {
logEntityActionService.logEntityAction(tenantId, emptyId(EntityType.DEVICE_PROFILE), actionType,
user, e, deviceProfileId.toString());
throw e;
}
}
@Override
public DeviceProfile setDefaultDeviceProfile(DeviceProfile deviceProfile, DeviceProfile previousDefaultDeviceProfile, User user) throws ThingsboardException {
TenantId tenantId = deviceProfile.getTenantId();
DeviceProfileId deviceProfileId = deviceProfile.getId();
try {
if (deviceProfileService.setDefaultDeviceProfile(tenantId, deviceProfileId)) { | if (previousDefaultDeviceProfile != null) {
previousDefaultDeviceProfile = deviceProfileService.findDeviceProfileById(tenantId, previousDefaultDeviceProfile.getId());
logEntityActionService.logEntityAction(tenantId, previousDefaultDeviceProfile.getId(), previousDefaultDeviceProfile,
ActionType.UPDATED, user);
}
deviceProfile = deviceProfileService.findDeviceProfileById(tenantId, deviceProfileId);
logEntityActionService.logEntityAction(tenantId, deviceProfileId, deviceProfile, ActionType.UPDATED, user);
}
return deviceProfile;
} catch (Exception e) {
logEntityActionService.logEntityAction(tenantId, emptyId(EntityType.DEVICE_PROFILE), ActionType.UPDATED,
user, e, deviceProfileId.toString());
throw e;
}
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\entitiy\device\profile\DefaultTbDeviceProfileService.java | 2 |
请完成以下Java代码 | public String getJobType() {
return jobType;
}
public void setJobType(String jobType) {
this.jobType = jobType;
}
@Override
public String getElementId() {
return elementId;
}
public void setElementId(String elementId) {
this.elementId = elementId;
}
@Override
public String getElementName() {
return elementName;
}
public void setElementName(String elementName) {
this.elementName = elementName;
}
@Override
public String getScopeId() {
return scopeId;
}
public void setScopeId(String scopeId) {
this.scopeId = scopeId;
}
@Override
public String getSubScopeId() {
return subScopeId;
}
public void setSubScopeId(String subScopeId) {
this.subScopeId = subScopeId;
}
@Override
public String getScopeType() {
return scopeType;
}
public void setScopeType(String scopeType) {
this.scopeType = scopeType;
}
@Override
public String getScopeDefinitionId() {
return scopeDefinitionId;
}
public void setScopeDefinitionId(String scopeDefinitionId) {
this.scopeDefinitionId = scopeDefinitionId;
}
@Override
public String getJobHandlerType() {
return jobHandlerType;
}
public void setJobHandlerType(String jobHandlerType) {
this.jobHandlerType = jobHandlerType;
}
@Override
public String getJobHandlerConfiguration() {
return jobHandlerConfiguration;
}
public void setJobHandlerConfiguration(String jobHandlerConfiguration) {
this.jobHandlerConfiguration = jobHandlerConfiguration;
}
public String getRepeat() {
return repeat;
} | public void setRepeat(String repeat) {
this.repeat = repeat;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
@Override
public String getExceptionMessage() {
return exceptionMessage;
}
public void setExceptionMessage(String exceptionMessage) {
this.exceptionMessage = StringUtils.abbreviate(exceptionMessage, MAX_EXCEPTION_MESSAGE_LENGTH);
}
@Override
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
public String getCorrelationId() {
// v5 Jobs have no correlationId
return null;
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\AbstractJobEntity.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public BigDecimal getCareType() {
return careType;
}
public void setCareType(BigDecimal careType) {
this.careType = careType;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
InsuranceContractRequiredTemplates insuranceContractRequiredTemplates = (InsuranceContractRequiredTemplates) o;
return Objects.equals(this.templateId, insuranceContractRequiredTemplates.templateId) &&
Objects.equals(this.careType, insuranceContractRequiredTemplates.careType);
}
@Override
public int hashCode() {
return Objects.hash(templateId, careType);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class InsuranceContractRequiredTemplates {\n");
sb.append(" templateId: ").append(toIndentedString(templateId)).append("\n"); | sb.append(" careType: ").append(toIndentedString(careType)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-article-api\src\main\java\io\swagger\client\model\InsuranceContractRequiredTemplates.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public Collection<Class<? extends AttributesChangedEvent>> getHandledEventType()
{
return ImmutableList.of(AttributesChangedEvent.class);
}
@Override
public void handleEvent(final AttributesChangedEvent event)
{
final Candidate fromCandidate = createCandidate(event, CandidateType.ATTRIBUTES_CHANGED_FROM);
final MaterialDispoGroupId groupId = candidateChangeHandler.onCandidateNewOrChange(fromCandidate)
.getEffectiveGroupId()
.orElseThrow(() -> new AdempiereException("No groupId"));
final Candidate toCandidate = createCandidate(event, CandidateType.ATTRIBUTES_CHANGED_TO)
.withGroupId(groupId);
candidateChangeHandler.onCandidateNewOrChange(toCandidate);
}
private Candidate createCandidate(final AttributesChangedEvent event, final CandidateType type)
{
final BigDecimal qty;
final AttributesKeyWithASI attributes;
if (CandidateType.ATTRIBUTES_CHANGED_FROM.equals(type))
{
qty = event.getQty().negate();
attributes = event.getOldStorageAttributes();
}
else if (CandidateType.ATTRIBUTES_CHANGED_TO.equals(type))
{
qty = event.getQty(); | attributes = event.getNewStorageAttributes();
}
else
{
throw new AdempiereException("Invalid type: " + type); // really shall not happen
}
return Candidate.builderForEventDescriptor(event.getEventDescriptor())
.type(type)
.materialDescriptor(MaterialDescriptor.builder()
.warehouseId(event.getWarehouseId())
.quantity(qty)
.date(event.getDate())
.productDescriptor(toProductDescriptor(event.getProductId(), attributes))
.build())
.build();
}
private static ProductDescriptor toProductDescriptor(final int productId, final AttributesKeyWithASI attributes)
{
return ProductDescriptor.forProductAndAttributes(productId,
CoalesceUtil.coalesceNotNull(attributes.getAttributesKey(), AttributesKey.NONE),
attributes.getAttributeSetInstanceId().getRepoId());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-service\src\main\java\de\metas\material\dispo\service\event\handler\attributes\AttributesChangedEventHandler.java | 2 |
请完成以下Java代码 | public String getMdl() {
return mdl;
}
/**
* Sets the value of the mdl property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMdl(String value) {
this.mdl = value;
}
/**
* Gets the value of the vrsnNb property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getVrsnNb() {
return vrsnNb;
}
/**
* Sets the value of the vrsnNb property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setVrsnNb(String value) {
this.vrsnNb = value;
}
/**
* Gets the value of the srlNb property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSrlNb() {
return srlNb;
}
/**
* Sets the value of the srlNb property. | *
* @param value
* allowed object is
* {@link String }
*
*/
public void setSrlNb(String value) {
this.srlNb = value;
}
/**
* Gets the value of the apprvlNb 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 apprvlNb property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getApprvlNb().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getApprvlNb() {
if (apprvlNb == null) {
apprvlNb = new ArrayList<String>();
}
return this.apprvlNb;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\PointOfInteractionComponent1.java | 1 |
请完成以下Java代码 | public final class Person {
private String firstName;
private String lastName;
private List<String> phoneNumbers = new ArrayList<>();
private List<Address> address = new ArrayList<>();
public List<Address> getAddress() {
return address;
}
public void setAddress(List<Address> address) {
this.address = address;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
} | public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public List<String> getPhoneNumbers() {
return phoneNumbers;
}
public void setPhoneNumbers(List<String> phoneNumbers) {
this.phoneNumbers = phoneNumbers;
}
} | repos\tutorials-master\jackson-modules\jackson-conversions\src\main\java\com\baeldung\jackson\xml\Person.java | 1 |
请完成以下Java代码 | public List<Tweet> getTweetsBlocking() {
log.info("Starting BLOCKING Controller!");
final String uri = getSlowServiceUri();
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<List<Tweet>> response = restTemplate.exchange(
uri, HttpMethod.GET, null,
new ParameterizedTypeReference<List<Tweet>>(){});
List<Tweet> result = response.getBody();
result.forEach(tweet -> log.info(tweet.toString()));
log.info("Exiting BLOCKING Controller!");
return result;
}
@GetMapping(value = "/tweets-non-blocking", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<Tweet> getTweetsNonBlocking() {
log.info("Starting NON-BLOCKING Controller!"); | Flux<Tweet> tweetFlux = WebClient.create()
.get()
.uri(getSlowServiceUri())
.retrieve()
.bodyToFlux(Tweet.class);
tweetFlux.subscribe(tweet -> log.info(tweet.toString()));
log.info("Exiting NON-BLOCKING Controller!");
return tweetFlux;
}
private String getSlowServiceUri() {
return "http://localhost:" + serverPort + "/slow-service-tweets";
}
} | repos\tutorials-master\spring-reactive-modules\spring-reactive\src\main\java\com\baeldung\reactive\webclient\WebController.java | 1 |
请完成以下Java代码 | public String getExtraValue() {
return extraValue;
}
@Override
public void setExtraValue(String extraValue) {
this.extraValue = extraValue;
}
@Override
public boolean isShowInOverview() {
return showInOverview;
}
@Override
public void setShowInOverview(boolean showInOverview) {
this.showInOverview = showInOverview;
}
@Override
public String getTenantId() {
return tenantId;
}
@Override
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getLocalizedName() {
return localizedName;
}
@Override
public void setLocalizedName(String localizedName) {
this.localizedName = localizedName;
}
@Override
public Map<String, Object> getPlanItemInstanceLocalVariables() {
Map<String, Object> variables = new HashMap<>();
if (queryVariables != null) {
for (HistoricVariableInstance variableInstance : queryVariables) {
if (variableInstance.getId() != null && variableInstance.getSubScopeId() != null) {
variables.put(variableInstance.getVariableName(), variableInstance.getValue());
}
}
}
return variables;
}
@Override
public List<HistoricVariableInstanceEntity> getQueryVariables() {
if (queryVariables == null && Context.getCommandContext() != null) {
queryVariables = new HistoricVariableInitializingList();
}
return queryVariables;
}
public void setQueryVariables(List<HistoricVariableInstanceEntity> queryVariables) {
this.queryVariables = queryVariables; | }
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("HistoricPlanItemInstance with id: ")
.append(id);
if (getName() != null) {
sb.append(", name: ").append(getName());
}
sb.append(", definitionId: ")
.append(planItemDefinitionId)
.append(", state: ")
.append(state);
sb
.append(", caseInstanceId: ")
.append(caseInstanceId)
.append(", caseDefinitionId: ")
.append(caseDefinitionId);
if (StringUtils.isNotEmpty(tenantId)) {
sb.append(", tenantId=").append(tenantId);
}
return sb.toString();
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\persistence\entity\HistoricPlanItemInstanceEntityImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class JsonPurchaseCandidateReference
{
@ApiModelProperty(position = 10, required = true,
value = "Identifier of the `ExternalSystem` record that tells where this Purchase Candidate came from.\n"
+ "This translates to 'ExternalSystem.value.'")
String externalSystemCode;
@ApiModelProperty(position = 20, dataType = "java.lang.String", example = "ExternalHeaderId_1",//
value = "Used to select which invoice candidates should be enqueued.")
JsonExternalId externalHeaderId;
@ApiModelProperty(position = 30, allowEmptyValue = true, dataType = "java.lang.String", example = "[\"ExternalLineId_2\", \"ExternalLineId_3\"]", //
value = "Optional, used to select which invoice candidates which have these `C_PurchaseCandidate.ExternalLineId`s should be enqueued.\n"
+ "Inherited from order line candidates.\n"
+ "If not specified, then all purchase candidate with the specified `externalHeaderId` are matched")
@JsonInclude(JsonInclude.Include.NON_EMPTY) | List<JsonExternalId> externalLineIds;
@JsonCreator
@Builder(toBuilder = true)
private JsonPurchaseCandidateReference(
final @JsonProperty("externalSystemCode") @NonNull String externalSystemCode,
final @JsonProperty("externalHeaderId") @NonNull JsonExternalId externalHeaderId,
final @JsonProperty("externalLineIds") @Nullable @Singular List<JsonExternalId> externalLineIds)
{
this.externalSystemCode = externalSystemCode;
this.externalHeaderId = externalHeaderId;
this.externalLineIds = externalLineIds == null ? ImmutableList.of() : ImmutableList.copyOf(externalLineIds);
}
} | repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-rest_api\src\main\java\de\metas\common\rest_api\v2\JsonPurchaseCandidateReference.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class StartInfo {
private String workflowType;
private String workflowId;
private String taskQueue;
private String inputJson;
public String getWorkflowType() {
return workflowType;
}
public void setWorkflowType(String workflowType) {
this.workflowType = workflowType;
}
public String getWorkflowId() {
return workflowId;
}
public void setWorkflowId(String workflowId) {
this.workflowId = workflowId;
} | public String getTaskQueue() {
return taskQueue;
}
public void setTaskQueue(String taskQueue) {
this.taskQueue = taskQueue;
}
public String getInputJson() {
return inputJson;
}
public void setInputJson(String inputJson) {
this.inputJson = inputJson;
}
} | repos\spring-boot-demo-main\src\main\java\com\temporal\demos\temporalspringbootdemo\webui\model\StartInfo.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public String getExitCriterionId() {
return exitCriterionId;
}
public void setExitCriterionId(String exitCriterionId) {
this.exitCriterionId = exitCriterionId;
}
public String getFormKey() {
return formKey;
}
public void setFormKey(String formKey) {
this.formKey = formKey;
}
public String getExtraValue() {
return extraValue;
}
public void setExtraValue(String extraValue) {
this.extraValue = extraValue;
}
public boolean isShowInOverview() {
return showInOverview;
}
public void setShowInOverview(boolean showInOverview) {
this.showInOverview = showInOverview;
}
@ApiModelProperty(example = "null")
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@ApiModelProperty(example = "http://localhost:8182/cmmn-history/historic-planitem-instances/5")
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
@ApiModelProperty(example = "http://localhost:8182/cmmn-history/historic-case-instances/12345")
public String getCaseInstanceUrl() {
return caseInstanceUrl;
}
public void setCaseInstanceUrl(String caseInstanceUrl) {
this.caseInstanceUrl = caseInstanceUrl; | }
@ApiModelProperty(example = "http://localhost:8182/cmmn-repository/case-definitions/myCaseId%3A1%3A4")
public String getCaseDefinitionUrl() {
return caseDefinitionUrl;
}
public void setCaseDefinitionUrl(String caseDefinitionUrl) {
this.caseDefinitionUrl = caseDefinitionUrl;
}
public String getDerivedCaseDefinitionUrl() {
return derivedCaseDefinitionUrl;
}
public void setDerivedCaseDefinitionUrl(String derivedCaseDefinitionUrl) {
this.derivedCaseDefinitionUrl = derivedCaseDefinitionUrl;
}
public String getStageInstanceUrl() {
return stageInstanceUrl;
}
public void setStageInstanceUrl(String stageInstanceUrl) {
this.stageInstanceUrl = stageInstanceUrl;
}
public void setLocalVariables(List<RestVariable> localVariables){
this.localVariables = localVariables;
}
public List<RestVariable> getLocalVariables() {
return localVariables;
}
public void addLocalVariable(RestVariable restVariable) {
localVariables.add(restVariable);
}
} | repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\history\planitem\HistoricPlanItemInstanceResponse.java | 2 |
请完成以下Java代码 | public class DmnDecisionTaskActivityBehavior extends DecisionTaskActivityBehavior {
protected DecisionResultMapper decisionResultMapper;
@Override
protected void performStart(CmmnActivityExecution execution) {
try {
CaseExecutionEntity executionEntity = (CaseExecutionEntity) execution;
evaluateDecision(executionEntity,
executionEntity.getCaseDefinitionTenantId(),
callableElement,
resultVariable,
decisionResultMapper);
if (execution.isActive()) {
execution.complete();
}
} catch (RuntimeException e) { | throw e;
} catch (Exception e) {
throw LOG.decisionDefinitionEvaluationFailed(execution, e);
}
}
public DecisionResultMapper getDecisionTableResultMapper() {
return decisionResultMapper;
}
public void setDecisionTableResultMapper(DecisionResultMapper decisionResultMapper) {
this.decisionResultMapper = decisionResultMapper;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\behavior\DmnDecisionTaskActivityBehavior.java | 1 |
请完成以下Java代码 | public void setUltmtCdtr(PartyIdentification32 value) {
this.ultmtCdtr = value;
}
/**
* Gets the value of the tradgPty property.
*
* @return
* possible object is
* {@link PartyIdentification32 }
*
*/
public PartyIdentification32 getTradgPty() {
return tradgPty;
}
/**
* Sets the value of the tradgPty property.
*
* @param value
* allowed object is
* {@link PartyIdentification32 }
*
*/
public void setTradgPty(PartyIdentification32 value) {
this.tradgPty = value;
}
/**
* Gets the value of the prtry 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 prtry property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre> | * getPrtry().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link ProprietaryParty2 }
*
*
*/
public List<ProprietaryParty2> getPrtry() {
if (prtry == null) {
prtry = new ArrayList<ProprietaryParty2>();
}
return this.prtry;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\TransactionParty2.java | 1 |
请完成以下Java代码 | public static DeserializationException getExceptionFromHeader(final ConsumerRecord<?, ?> record,
String headerName, LogAccessor logger) {
Header header = record.headers().lastHeader(headerName);
if (header != null && !(header instanceof DeserializationExceptionHeader)) {
logger.warn(
() -> String.format("Foreign deserialization exception header in (%s) ignored; possible attack?",
KafkaUtils.format(record)));
return null;
}
if (header != null) {
DeserializationException exception = byteArrayToDeserializationException(logger, header);
if (exception != null) {
Headers headers = new RecordHeaders(record.headers().toArray());
headers.remove(headerName);
exception.setHeaders(headers);
}
return exception;
}
return null;
}
/**
* Convert a byte array containing a serialized {@link DeserializationException} to the
* {@link DeserializationException}.
* @param logger a log accessor to log errors.
* @param header the header.
* @return the exception or null if deserialization fails.
* @since 2.9.11
*/
@Nullable
public static DeserializationException byteArrayToDeserializationException(LogAccessor logger, Header header) {
if (header != null && !(header instanceof DeserializationExceptionHeader)) { | throw new IllegalStateException("Foreign deserialization exception header ignored; possible attack?");
}
try {
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(header.value())) {
boolean first = true;
@Override
protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException {
if (this.first) {
this.first = false;
Assert.state(desc.getName().equals(DeserializationException.class.getName()),
"Header does not contain a DeserializationException");
}
return super.resolveClass(desc);
}
};
return (DeserializationException) ois.readObject();
}
catch (IOException | ClassNotFoundException | ClassCastException e) {
logger.error(e, "Failed to deserialize a deserialization exception");
return null;
}
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\serializer\SerializationUtils.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public OAuth2AuthorizationServerMetadataEndpointConfigurer authorizationServerMetadataCustomizer(
Consumer<OAuth2AuthorizationServerMetadata.Builder> authorizationServerMetadataCustomizer) {
this.authorizationServerMetadataCustomizer = authorizationServerMetadataCustomizer;
return this;
}
void addDefaultAuthorizationServerMetadataCustomizer(
Consumer<OAuth2AuthorizationServerMetadata.Builder> defaultAuthorizationServerMetadataCustomizer) {
this.defaultAuthorizationServerMetadataCustomizer = (this.defaultAuthorizationServerMetadataCustomizer == null)
? defaultAuthorizationServerMetadataCustomizer : this.defaultAuthorizationServerMetadataCustomizer
.andThen(defaultAuthorizationServerMetadataCustomizer);
}
@Override
void init(HttpSecurity httpSecurity) {
AuthorizationServerSettings authorizationServerSettings = OAuth2ConfigurerUtils
.getAuthorizationServerSettings(httpSecurity);
String authorizationServerMetadataEndpointUri = authorizationServerSettings.isMultipleIssuersAllowed()
? "/.well-known/oauth-authorization-server/**" : "/.well-known/oauth-authorization-server";
this.requestMatcher = PathPatternRequestMatcher.withDefaults()
.matcher(HttpMethod.GET, authorizationServerMetadataEndpointUri);
}
@Override
void configure(HttpSecurity httpSecurity) {
OAuth2AuthorizationServerMetadataEndpointFilter authorizationServerMetadataEndpointFilter = new OAuth2AuthorizationServerMetadataEndpointFilter();
Consumer<OAuth2AuthorizationServerMetadata.Builder> authorizationServerMetadataCustomizer = getAuthorizationServerMetadataCustomizer();
if (authorizationServerMetadataCustomizer != null) { | authorizationServerMetadataEndpointFilter
.setAuthorizationServerMetadataCustomizer(authorizationServerMetadataCustomizer);
}
httpSecurity.addFilterBefore(postProcess(authorizationServerMetadataEndpointFilter),
AbstractPreAuthenticatedProcessingFilter.class);
}
private Consumer<OAuth2AuthorizationServerMetadata.Builder> getAuthorizationServerMetadataCustomizer() {
Consumer<OAuth2AuthorizationServerMetadata.Builder> authorizationServerMetadataCustomizer = null;
if (this.defaultAuthorizationServerMetadataCustomizer != null
|| this.authorizationServerMetadataCustomizer != null) {
if (this.defaultAuthorizationServerMetadataCustomizer != null) {
authorizationServerMetadataCustomizer = this.defaultAuthorizationServerMetadataCustomizer;
}
if (this.authorizationServerMetadataCustomizer != null) {
authorizationServerMetadataCustomizer = (authorizationServerMetadataCustomizer != null)
? authorizationServerMetadataCustomizer.andThen(this.authorizationServerMetadataCustomizer)
: this.authorizationServerMetadataCustomizer;
}
}
return authorizationServerMetadataCustomizer;
}
@Override
RequestMatcher getRequestMatcher() {
return this.requestMatcher;
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\oauth2\server\authorization\OAuth2AuthorizationServerMetadataEndpointConfigurer.java | 2 |
请完成以下Java代码 | public int getC_PaySchedule_ID()
{
return get_ValueAsInt(COLUMNNAME_C_PaySchedule_ID);
}
@Override
public void setDiscountAmt (final @Nullable BigDecimal DiscountAmt)
{
set_Value (COLUMNNAME_DiscountAmt, DiscountAmt);
}
@Override
public BigDecimal getDiscountAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_DiscountAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setDiscountDate (final @Nullable java.sql.Timestamp DiscountDate)
{
set_Value (COLUMNNAME_DiscountDate, DiscountDate);
}
@Override
public java.sql.Timestamp getDiscountDate()
{
return get_ValueAsTimestamp(COLUMNNAME_DiscountDate);
}
@Override
public void setDueAmt (final BigDecimal DueAmt)
{
set_Value (COLUMNNAME_DueAmt, DueAmt);
}
@Override
public BigDecimal getDueAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_DueAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setDueDate (final java.sql.Timestamp DueDate)
{
set_Value (COLUMNNAME_DueDate, DueDate);
}
@Override
public java.sql.Timestamp getDueDate()
{
return get_ValueAsTimestamp(COLUMNNAME_DueDate);
}
@Override
public void setIsValid (final boolean IsValid)
{
set_Value (COLUMNNAME_IsValid, IsValid);
}
@Override
public boolean isValid() | {
return get_ValueAsBoolean(COLUMNNAME_IsValid);
}
@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);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_InvoicePaySchedule.java | 1 |
请完成以下Java代码 | private <T> T[] clone(T[] array) {
return (array != null) ? array.clone() : null;
}
/**
* Get the {@link SecurityInfo} for the given {@link ZipContent}.
* @param content the zip content
* @return the security info
*/
static SecurityInfo get(ZipContent content) {
if (!content.hasJarSignatureFile()) {
return NONE;
}
try {
return load(content);
}
catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}
/**
* Load security info from the jar file. We need to use {@link JarInputStream} to
* obtain the security info since we don't have an actual real file to read. This
* isn't that fast, but hopefully doesn't happen too often and the result is cached.
* @param content the zip content
* @return the security info
* @throws IOException on I/O error
*/
@SuppressWarnings("resource")
private static SecurityInfo load(ZipContent content) throws IOException {
int size = content.size();
boolean hasSecurityInfo = false;
Certificate[][] entryCertificates = new Certificate[size][];
CodeSigner[][] entryCodeSigners = new CodeSigner[size][];
try (JarEntriesStream entries = new JarEntriesStream(content.openRawZipData().asInputStream())) { | JarEntry entry = entries.getNextEntry();
while (entry != null) {
ZipContent.Entry relatedEntry = content.getEntry(entry.getName());
if (relatedEntry != null && entries.matches(relatedEntry.isDirectory(),
relatedEntry.getUncompressedSize(), relatedEntry.getCompressionMethod(),
() -> relatedEntry.openContent().asInputStream())) {
Certificate[] certificates = entry.getCertificates();
CodeSigner[] codeSigners = entry.getCodeSigners();
if (certificates != null || codeSigners != null) {
hasSecurityInfo = true;
entryCertificates[relatedEntry.getLookupIndex()] = certificates;
entryCodeSigners[relatedEntry.getLookupIndex()] = codeSigners;
}
}
entry = entries.getNextEntry();
}
}
return (!hasSecurityInfo) ? NONE : new SecurityInfo(entryCertificates, entryCodeSigners);
}
} | repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\jar\SecurityInfo.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Show getShowDetails() {
return this.showDetails;
}
public void setShowDetails(Show showDetails) {
this.showDetails = showDetails;
}
public Map<String, Group> getGroup() {
return this.group;
}
public Logging getLogging() {
return this.logging;
}
/**
* A health endpoint group.
*/
public static class Group extends HealthProperties {
public static final String SERVER_PREFIX = "server:";
public static final String MANAGEMENT_PREFIX = "management:";
/**
* Health indicator IDs that should be included or '*' for all.
*/
private @Nullable Set<String> include;
/**
* Health indicator IDs that should be excluded or '*' for all.
*/
private @Nullable Set<String> exclude;
/**
* When to show full health details. Defaults to the value of
* 'management.endpoint.health.show-details'.
*/
private @Nullable Show showDetails;
/**
* Additional path that this group can be made available on. The additional path
* must start with a valid prefix, either `server` or `management` to indicate if
* it will be available on the main port or the management port. For instance,
* `server:/healthz` will configure the group on the main port at `/healthz`.
*/
private @Nullable String additionalPath;
public @Nullable Set<String> getInclude() {
return this.include;
}
public void setInclude(@Nullable Set<String> include) {
this.include = include;
}
public @Nullable Set<String> getExclude() {
return this.exclude;
}
public void setExclude(@Nullable Set<String> exclude) {
this.exclude = exclude;
}
@Override
public @Nullable Show getShowDetails() {
return this.showDetails;
} | public void setShowDetails(@Nullable Show showDetails) {
this.showDetails = showDetails;
}
public @Nullable String getAdditionalPath() {
return this.additionalPath;
}
public void setAdditionalPath(@Nullable String additionalPath) {
this.additionalPath = additionalPath;
}
}
/**
* Health logging properties.
*/
public static class Logging {
/**
* Threshold after which a warning will be logged for slow health indicators.
*/
private Duration slowIndicatorThreshold = Duration.ofSeconds(10);
public Duration getSlowIndicatorThreshold() {
return this.slowIndicatorThreshold;
}
public void setSlowIndicatorThreshold(Duration slowIndicatorThreshold) {
this.slowIndicatorThreshold = slowIndicatorThreshold;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-health\src\main\java\org\springframework\boot\health\autoconfigure\actuate\endpoint\HealthEndpointProperties.java | 2 |
请完成以下Java代码 | public class PrependScriptDecorator extends AbstractScriptDecoratorAdapter
{
private final Iterator<IScript> scriptsToPrepend;
private boolean removeFromHere = false;
public PrependScriptDecorator(IScriptScanner scanner, List<IScript> scriptsToPrepend)
{
super(scanner);
this.scriptsToPrepend = scriptsToPrepend.iterator();
}
@Override
public void remove()
{
if (removeFromHere)
{
scriptsToPrepend.remove();
}
else
{
super.remove();
}
}
@Override
public boolean hasNext() | {
return scriptsToPrepend.hasNext() || super.hasNext();
}
@Override
public IScript next()
{
final boolean hasNext = scriptsToPrepend.hasNext();
if (hasNext)
{
removeFromHere = true;
return scriptsToPrepend.next();
}
removeFromHere = false;
return super.next();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.base\src\main\java\de\metas\migration\scanner\impl\PrependScriptDecorator.java | 1 |
请完成以下Java代码 | public StringAttributeBuilder stringAttribute(String attributeName) {
StringAttributeBuilderImpl builder = new StringAttributeBuilderImpl(attributeName, modelType);
modelBuildOperations.add(builder);
return builder;
}
public AttributeBuilder<Integer> integerAttribute(String attributeName) {
IntegerAttributeBuilder builder = new IntegerAttributeBuilder(attributeName, modelType);
modelBuildOperations.add(builder);
return builder;
}
public AttributeBuilder<Double> doubleAttribute(String attributeName) {
DoubleAttributeBuilder builder = new DoubleAttributeBuilder(attributeName, modelType);
modelBuildOperations.add(builder);
return builder;
}
public <V extends Enum<V>> AttributeBuilder<V> enumAttribute(String attributeName, Class<V> enumType) {
EnumAttributeBuilder<V> builder = new EnumAttributeBuilder<V>(attributeName, modelType, enumType);
modelBuildOperations.add(builder);
return builder;
}
public <V extends Enum<V>> AttributeBuilder<V> namedEnumAttribute(String attributeName, Class<V> enumType) {
NamedEnumAttributeBuilder<V> builder = new NamedEnumAttributeBuilder<V>(attributeName, modelType, enumType);
modelBuildOperations.add(builder);
return builder;
}
public ModelElementType build() {
model.registerType(modelType, instanceType);
return modelType;
}
public ModelElementTypeBuilder abstractType() {
modelType.setAbstract(true);
return this;
} | public SequenceBuilder sequence() {
SequenceBuilderImpl builder = new SequenceBuilderImpl(modelType);
modelBuildOperations.add(builder);
return builder;
}
public void buildTypeHierarchy(Model model) {
// build type hierarchy
if(extendedType != null) {
ModelElementTypeImpl extendedModelElementType = (ModelElementTypeImpl) model.getType(extendedType);
if(extendedModelElementType == null) {
throw new ModelException("Type "+modelType+" is defined to extend "+extendedType+" but no such type is defined.");
} else {
modelType.setBaseType(extendedModelElementType);
extendedModelElementType.registerExtendingType(modelType);
}
}
}
public void performModelBuild(Model model) {
for (ModelBuildOperation operation : modelBuildOperations) {
operation.performModelBuild(model);
}
}
} | repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\type\ModelElementTypeBuilderImpl.java | 1 |
请完成以下Spring Boot application配置 | spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-cl | ass-name=com.mysql.jdbc.Driver
flyway.locations=classpath:/db | repos\SpringBoot-Learning-master\1.x\Chapter3-2-9\src\main\resources\application.properties | 2 |
请完成以下Java代码 | public void setAD_Ref_List_ID (int AD_Ref_List_ID)
{
if (AD_Ref_List_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Ref_List_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Ref_List_ID, Integer.valueOf(AD_Ref_List_ID));
}
/** Get Referenzliste.
@return Reference List based on Table
*/
@Override
public int getAD_Ref_List_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Ref_List_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_AD_Role getAD_Role() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_AD_Role_ID, org.compiere.model.I_AD_Role.class);
}
@Override
public void setAD_Role(org.compiere.model.I_AD_Role AD_Role)
{
set_ValueFromPO(COLUMNNAME_AD_Role_ID, org.compiere.model.I_AD_Role.class, AD_Role);
}
/** Set Rolle.
@param AD_Role_ID
Responsibility Role
*/
@Override
public void setAD_Role_ID (int AD_Role_ID)
{
if (AD_Role_ID < 0)
set_ValueNoCheck (COLUMNNAME_AD_Role_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Role_ID, Integer.valueOf(AD_Role_ID));
}
/** Get Rolle.
@return Responsibility Role
*/
@Override
public int getAD_Role_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Role_ID);
if (ii == null)
return 0;
return ii.intValue(); | }
@Override
public org.compiere.model.I_C_DocType getC_DocType() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_C_DocType_ID, org.compiere.model.I_C_DocType.class);
}
@Override
public void setC_DocType(org.compiere.model.I_C_DocType C_DocType)
{
set_ValueFromPO(COLUMNNAME_C_DocType_ID, org.compiere.model.I_C_DocType.class, C_DocType);
}
/** Set Belegart.
@param C_DocType_ID
Document type or rules
*/
@Override
public void setC_DocType_ID (int C_DocType_ID)
{
if (C_DocType_ID < 0)
set_ValueNoCheck (COLUMNNAME_C_DocType_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_DocType_ID, Integer.valueOf(C_DocType_ID));
}
/** Get Belegart.
@return Document type or rules
*/
@Override
public int getC_DocType_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_DocType_ID);
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_AD_Document_Action_Access.java | 1 |
请完成以下Java代码 | public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue(); | }
/** Set Version.
@param Version
Version of the table definition
*/
public void setVersion (String Version)
{
set_Value (COLUMNNAME_Version, Version);
}
/** Get Version.
@return Version of the table definition
*/
public String getVersion ()
{
return (String)get_Value(COLUMNNAME_Version);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Modification.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class InsertDetailRequest
{
DetailDataRecordIdentifier detailDataRecordIdentifier;
int orderLineId;
int orderId;
int subscriptionLineId;
int subscriptionId;
int docTypeId;
/**
* May be zero because shipment schedules initially have a zero bpartnerId.
*/
int bPartnerId;
BigDecimal qtyOrdered;
BigDecimal qtyReserved;
@Builder
public InsertDetailRequest(
@NonNull final DetailDataRecordIdentifier detailDataRecordIdentifier,
final int orderLineId,
final int orderId,
final int subscriptionLineId,
final int subscriptionId,
final int bPartnerId,
final int docTypeId,
@NonNull final BigDecimal qtyOrdered,
@NonNull final BigDecimal qtyReserved)
{
this.detailDataRecordIdentifier = detailDataRecordIdentifier;
this.bPartnerId = bPartnerId; | this.qtyOrdered = qtyOrdered;
this.qtyReserved = qtyReserved;
this.orderLineId = orderLineId;
this.orderId = orderId;
this.subscriptionLineId = subscriptionLineId;
this.subscriptionId = subscriptionId;
this.docTypeId = docTypeId;
validate();
}
public final void validate()
{
final boolean orderLineIdSet = orderLineId > 0;
final boolean subscriptionLineIdSet = subscriptionLineId > 0;
Check.errorUnless(orderLineIdSet ^ subscriptionLineIdSet,
"Either orderLineId or subscriptionLineId need to be > 0 (but not both!); orderLineId={}; subscriptionLineId={}",
orderLineId, subscriptionLineId);
Check.errorIf(orderLineIdSet && orderId <= 0,
"If orderLineId is > 0, then orderId also needs to be > 0; orderLineId={}, orderId={}",
orderLineId, orderId);
Check.errorIf(subscriptionLineIdSet && subscriptionId <= 0,
"If subscriptionLineId is > 0, then orderId also needs to be > 0; subscriptionLineId={}, subscriptionId={}",
subscriptionLineId, subscriptionId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java\de\metas\material\cockpit\view\detailrecord\InsertDetailRequest.java | 2 |
请完成以下Java代码 | public void setDocuments(DocumentsType value) {
this.documents = value;
}
/**
* Gets the value of the roleTitle property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRoleTitle() {
return roleTitle;
}
/**
* Sets the value of the roleTitle property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRoleTitle(String value) {
this.roleTitle = value;
}
/**
* Gets the value of the role property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRole() {
return role;
}
/**
* Sets the value of the role property.
*
* @param value
* allowed object is
* {@link String }
*
*/ | public void setRole(String value) {
this.role = value;
}
/**
* Gets the value of the place property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPlace() {
return place;
}
/**
* Sets the value of the place property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPlace(String value) {
this.place = value;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\BodyType.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public ResponseEntity<User> getUserById(
@PathVariable(value = "id") Long userId) throws ResourceNotFoundException {
User user = userRepository.findById(userId)
.orElseThrow(() -> new ResourceNotFoundException("User not found :: " + userId));
return ResponseEntity.ok().body(user);
}
@PostMapping("/users")
public User createUser(@Valid @RequestBody User user) {
return userRepository.save(user);
}
@PutMapping("/users/{id}")
public ResponseEntity<User> updateUser(
@PathVariable(value = "id") Long userId,
@Valid @RequestBody User userDetails) throws ResourceNotFoundException {
User user = userRepository.findById(userId)
.orElseThrow(() -> new ResourceNotFoundException("User not found :: " + userId)); | user.setEmailId(userDetails.getEmailId());
user.setLastName(userDetails.getLastName());
user.setFirstName(userDetails.getFirstName());
user.setUpdatedAt(new Date());
final User updatedUser = userRepository.save(user);
return ResponseEntity.ok(updatedUser);
}
@DeleteMapping("/users/{id}")
public Map<String, Boolean> deleteUser(
@PathVariable(value = "id") Long userId) throws ResourceNotFoundException {
User user = userRepository.findById(userId)
.orElseThrow(() -> new ResourceNotFoundException("User not found :: " + userId));
userRepository.delete(user);
Map<String, Boolean> response = new HashMap<>();
response.put("deleted", Boolean.TRUE);
return response;
}
} | repos\Spring-Boot-Advanced-Projects-main\spring-boot-crud-rest\src\main\java\com\alanbinu\springbootcrudrest\controller\UserController.java | 2 |
请完成以下Java代码 | public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
/**
* UseScalePrice AD_Reference_ID=541376
* Reference name: UseScalePrice
*/
public static final int USESCALEPRICE_AD_Reference_ID=541376;
/** Use scale price, fallback to product price = Y */
public static final String USESCALEPRICE_UseScalePriceFallbackToProductPrice = "Y";
/** Don't use scale price = N */
public static final String USESCALEPRICE_DonTUseScalePrice = "N";
/** Use scale price (strict) = S */
public static final String USESCALEPRICE_UseScalePriceStrict = "S";
@Override
public void setUseScalePrice (final java.lang.String UseScalePrice)
{ | set_Value (COLUMNNAME_UseScalePrice, UseScalePrice);
}
@Override
public java.lang.String getUseScalePrice()
{
return get_ValueAsString(COLUMNNAME_UseScalePrice);
}
@Override
public void setValidFrom (final @Nullable java.sql.Timestamp ValidFrom)
{
throw new IllegalArgumentException ("ValidFrom is virtual column"); }
@Override
public java.sql.Timestamp getValidFrom()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidFrom);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_ProductPrice.java | 1 |
请完成以下Java代码 | private ModelElementInstance findElementToInsertAfter(ModelElementInstance elementToInsert) {
List<ModelElementType> childElementTypes = elementType.getAllChildElementTypes();
List<DomElement> childDomElements = domElement.getChildElements();
Collection<ModelElementInstance> childElements = ModelUtil.getModelElementCollection(childDomElements, modelInstance);
ModelElementInstance insertAfterElement = null;
int newElementTypeIndex = ModelUtil.getIndexOfElementType(elementToInsert, childElementTypes);
for (ModelElementInstance childElement : childElements) {
int childElementTypeIndex = ModelUtil.getIndexOfElementType(childElement, childElementTypes);
if (newElementTypeIndex >= childElementTypeIndex) {
insertAfterElement = childElement;
}
else {
break;
}
}
return insertAfterElement;
}
public void insertElementAfter(ModelElementInstance elementToInsert, ModelElementInstance insertAfterElement) {
if (insertAfterElement == null || insertAfterElement.getDomElement() == null) {
domElement.insertChildElementAfter(elementToInsert.getDomElement(), null);
}
else {
domElement.insertChildElementAfter(elementToInsert.getDomElement(), insertAfterElement.getDomElement());
}
}
public void updateAfterReplacement() {
// do nothing
}
/**
* Removes all reference to this.
*/
private void unlinkAllReferences() {
Collection<Attribute<?>> attributes = elementType.getAllAttributes();
for (Attribute<?> attribute : attributes) {
Object identifier = attribute.getValue(this);
if (identifier != null) {
((AttributeImpl<?>) attribute).unlinkReference(this, identifier);
}
}
}
/**
* Removes every reference to children of this.
*/
private void unlinkAllChildReferences() {
List<ModelElementType> childElementTypes = elementType.getAllChildElementTypes();
for (ModelElementType type : childElementTypes) {
Collection<ModelElementInstance> childElementsForType = getChildElementsByType(type);
for (ModelElementInstance childElement : childElementsForType) {
((ModelElementInstanceImpl) childElement).unlinkAllReferences();
}
}
} | protected <T> Set<T> asSet(T element, Set<T> elements){
Set<T> result = new HashSet<T>();
result.add(element);
if (elements != null) {
result.addAll(elements);
}
return result;
}
@Override
public int hashCode() {
return domElement.hashCode();
}
@Override
public boolean equals(Object obj) {
if(obj == null) {
return false;
} else if(obj == this) {
return true;
} else if(!(obj instanceof ModelElementInstanceImpl)) {
return false;
} else {
ModelElementInstanceImpl other = (ModelElementInstanceImpl) obj;
return other.domElement.equals(domElement);
}
}
} | repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\instance\ModelElementInstanceImpl.java | 1 |
请完成以下Java代码 | public String getPropagatedStageInstanceId() {
return propagatedStageInstanceId;
}
@Override
public String getParentId() {
return parentId;
}
@Override
public String getSuperExecutionId() {
return superExecutionId;
}
@Override
public String getCurrentActivityId() {
return currentActivityId;
}
@Override
public String getTenantId() {
return tenantId;
}
@Override
public FlowElement getCurrentFlowElement() {
return currentFlowElement;
}
@Override
public boolean isActive() {
return active;
}
@Override
public boolean isEnded() {
return ended;
}
@Override
public boolean isConcurrent() {
return concurrent;
}
@Override | public boolean isProcessInstanceType() {
return processInstanceType;
}
@Override
public boolean isScope() {
return scope;
}
@Override
public boolean isMultiInstanceRoot() {
return multiInstanceRoot;
}
@Override
public Object getVariable(String variableName) {
return variables.get(variableName);
}
@Override
public boolean hasVariable(String variableName) {
return variables.containsKey(variableName);
}
@Override
public Set<String> getVariableNames() {
return variables.keySet();
}
@Override
public String toString() {
return new StringJoiner(", ", getClass().getSimpleName() + "[", "]")
.add("id='" + id + "'")
.add("currentActivityId='" + currentActivityId + "'")
.add("processInstanceId='" + processInstanceId + "'")
.add("processDefinitionId='" + processDefinitionId + "'")
.add("tenantId='" + tenantId + "'")
.toString();
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\delegate\ReadOnlyDelegateExecutionImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class WebuiDocumentReference
{
WebuiDocumentReferenceId id;
String internalName;
ITranslatableString caption;
WebuiDocumentReferenceTargetWindow targetWindow;
Priority priority;
int documentsCount;
DocumentFilter filter;
Duration loadDuration;
@Builder
private WebuiDocumentReference(
@NonNull final WebuiDocumentReferenceId id,
@Nullable final String internalName,
@NonNull final ITranslatableString caption,
@NonNull final WebuiDocumentReferenceTargetWindow targetWindow,
@NonNull final Priority priority,
final int documentsCount,
@NonNull final DocumentFilter filter,
@Nullable final Duration loadDuration)
{ | this.id = id;
this.internalName = internalName;
this.caption = caption;
this.targetWindow = targetWindow;
this.priority = priority;
this.documentsCount = documentsCount;
this.filter = filter;
this.loadDuration = loadDuration;
}
public String getCaption(final String adLanguage)
{
return caption.translate(adLanguage);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\references\WebuiDocumentReference.java | 2 |
请完成以下Java代码 | private Stream<JsonMappingConfig> streamEligibleConfigs(final @NotNull String attributeType, @NonNull final Function<String, String> valueProvider )
{
return orderedConfigsByAttributeType.get(attributeType)
.stream()
.filter(config -> config.isConfigFor(valueProvider));
}
public List<JsonReference> getReferences(
@NonNull final String attributeType,
@NonNull final Function<String, String> valueProvider)
{
return getValuesByKeyAttributeKey(attributeType, valueProvider)
.asMap().entrySet().stream()
.map(entry -> JsonReference.builder()
.kind(Integer.parseInt(entry.getKey()))
.value(concatValues(entry.getValue()))
.build())
.collect(Collectors.toList());
}
private static String concatValues(@NonNull final Collection<String> values)
{
return String.join(" ", values);
}
@NonNull
public String getSingleValue(@NonNull final String attributeType, @NonNull final Function<String, String> valueProvider)
{
return concatValues(getValueList(attributeType, valueProvider));
}
@NonNull
private ImmutableList<String> getValueList(@NonNull final String attributeType, @NonNull final Function<String, String> valueProvider)
{
return streamEligibleConfigs(attributeType, valueProvider)
.map(config -> valueProvider.apply(config.getAttributeValue()))
.filter(Check::isNotBlank)
.collect(ImmutableList.toImmutableList());
}
public ImmutableList<String> getDetailGroupKeysForType(@NonNull final String attributeType, @NonNull final Function<String, String> valueProvider)
{
return streamEligibleConfigs(attributeType, valueProvider) | .map(JsonMappingConfig::getGroupKey)
.filter(Check::isNotBlank)
.distinct()
.collect(ImmutableList.toImmutableList());
}
public List<JsonDetail> getDetailsForGroupAndType(
@NonNull final String attributeGroupKey,
@NonNull final String attributeType,
@NonNull final Function<String, String> valueProvider)
{
final Map<Integer, String> detailsByKindId = streamEligibleConfigs(attributeType, valueProvider)
.filter(config -> attributeGroupKey.equals(config.getGroupKey()))
.filter(config -> Check.isNotBlank(config.getAttributeKey()))
.map(config -> new AbstractMap.SimpleImmutableEntry<>(
Integer.parseInt(config.getAttributeKey()),
valueProvider.apply(config.getAttributeValue())))
.filter(entry -> Check.isNotBlank(entry.getValue()))
.collect(Collectors.groupingBy(Map.Entry::getKey,
Collectors.mapping(Map.Entry::getValue, Collectors.joining(" "))));
return detailsByKindId.entrySet().stream()
.map(entry -> JsonDetail.builder()
.kindId(entry.getKey())
.value(entry.getValue())
.build())
.collect(Collectors.toList());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.client.nshift\src\main\java\de\metas\shipper\client\nshift\NShiftMappingConfigs.java | 1 |
请完成以下Java代码 | public abstract class BaseApi {
protected static final String BASE_API_URL = "https://api.weixin.qq.com/";
protected BaseResponse executeGet(String url) {
BaseResponse response;
BeanUtil.requireNonNull(url, "url is null");
response = NetWorkCenter.get(url);
return response;
}
protected BaseResponse executePost(String url, String json, File file) {
BaseResponse response;
BeanUtil.requireNonNull(url, "url is null");
List<File> files = null;
if (null != file) {
files = new ArrayList<File>() {{
add(file); | }};
}
response = NetWorkCenter.post(url, json, files);
return response;
}
protected BaseResponse executePost(String url, String json) {
return executePost(url, json, null);
}
protected boolean isSuccess(String errCode) {
return ResultType.SUCCESS.getCode().toString().equals(errCode);
}
} | repos\spring-boot-quick-master\quick-wx-public\src\main\java\com\wx\pn\api\BaseApi.java | 1 |
请完成以下Java代码 | public static void lessThanOperator() {
Bson filter = lt("age", 25);
FindIterable<Document> documents = collection.find(filter);
printResult(documents);
}
public static void inOperator() {
Bson filter = in("userName", "Jack", "Lisa");
FindIterable<Document> documents = collection.find(filter);
printResult(documents);
}
public static void notInOperator() {
Bson filter = nin("userName", "Jack", "Lisa");
FindIterable<Document> documents = collection.find(filter);
printResult(documents);
}
public static void andOperator() {
Bson filter = and(gt("age", 25), eq("role", "Admin"));
FindIterable<Document> documents = collection.find(filter);
printResult(documents);
}
public static void orOperator() {
Bson filter = or(gt("age", 30), eq("role", "Admin"));
FindIterable<Document> documents = collection.find(filter);
printResult(documents);
}
public static void existsOperator() {
Bson filter = exists("type");
FindIterable<Document> documents = collection.find(filter);
printResult(documents);
}
public static void regexOperator() {
Bson filter = regex("userName", "a");
FindIterable<Document> documents = collection.find(filter);
printResult(documents);
}
private static void printResult(FindIterable<Document> documents) {
MongoCursor<Document> cursor = documents.iterator(); | while (cursor.hasNext()) {
System.out.println(cursor.next());
}
}
public static void main(String args[]) {
setUp();
equalsOperator();
notEqualOperator();
greaterThanOperator();
lessThanOperator();
inOperator();
notInOperator();
andOperator();
orOperator();
existsOperator();
regexOperator();
}
} | repos\tutorials-master\persistence-modules\java-mongodb\src\main\java\com\baeldung\mongo\filter\FilterOperation.java | 1 |
请完成以下Java代码 | protected void completeDunningDocLine()
{
for (final I_C_DunningDoc_Line_Source source : dunningDocLineSources)
{
completeDunningDocLineSource(source);
}
dunningDocLineSources.clear();
if (dunningDocLine == null)
{
return;
}
final IDunningDAO dunningDAO = Services.get(IDunningDAO.class);
dunningDAO.save(dunningDocLine);
dunningDocLine = null;
}
protected void completeDunningDocLineSource(final I_C_DunningDoc_Line_Source source)
{
final I_C_Dunning_Candidate candidate = source.getC_Dunning_Candidate();
candidate.setProcessed(true);
InterfaceWrapperHelper.save(candidate); | }
@Override
public void finish()
{
completeDunningDoc();
}
@Override
public void addAggregator(final IDunningAggregator aggregator)
{
dunningAggregators.addAggregator(aggregator);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\api\impl\DefaultDunningProducer.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void deleteIdentityLink(@ApiParam(name = "caseDefinitionId") @PathVariable("caseDefinitionId") String caseDefinitionId,
@ApiParam(name = "family") @PathVariable("family") String family, @ApiParam(name = "identityId") @PathVariable("identityId") String identityId) {
CaseDefinition caseDefinition = getCaseDefinitionFromRequestWithoutAccessCheck(caseDefinitionId);
validateIdentityLinkArguments(family, identityId);
// Check if identitylink to delete exists
IdentityLink link = getIdentityLink(family, identityId, caseDefinition.getId());
if (restApiInterceptor != null) {
restApiInterceptor.deleteCaseDefinitionIdentityLink(caseDefinition, link);
}
if (link.getUserId() != null) {
repositoryService.deleteCandidateStarterUser(caseDefinition.getId(), link.getUserId());
} else {
repositoryService.deleteCandidateStarterGroup(caseDefinition.getId(), link.getGroupId());
}
}
protected void validateIdentityLinkArguments(String family, String identityId) {
if (family == null || (!CmmnRestUrls.SEGMENT_IDENTITYLINKS_FAMILY_GROUPS.equals(family) && !CmmnRestUrls.SEGMENT_IDENTITYLINKS_FAMILY_USERS.equals(family))) {
throw new FlowableIllegalArgumentException("Identity link family should be 'users' or 'groups'.");
} | if (identityId == null) {
throw new FlowableIllegalArgumentException("IdentityId is required.");
}
}
protected IdentityLink getIdentityLink(String family, String identityId, String caseDefinitionId) {
boolean isUser = family.equals(CmmnRestUrls.SEGMENT_IDENTITYLINKS_FAMILY_USERS);
List<IdentityLink> allLinks = repositoryService.getIdentityLinksForCaseDefinition(caseDefinitionId);
for (IdentityLink link : allLinks) {
boolean rightIdentity = false;
if (isUser) {
rightIdentity = identityId.equals(link.getUserId());
} else {
rightIdentity = identityId.equals(link.getGroupId());
}
if (rightIdentity && link.getType().equals(IdentityLinkType.CANDIDATE)) {
return link;
}
}
throw new FlowableObjectNotFoundException("Could not find the requested identity link.", IdentityLink.class);
}
} | repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\repository\CaseDefinitionIdentityLinkResource.java | 2 |
请完成以下Java代码 | public Map<String, String> createEmptyMap() {
Map<String, String> emptyMap = Collections.emptyMap();
return emptyMap;
}
public Map<String, String> createUsingDoubleBrace() {
Map<String, String> doubleBraceMap = new HashMap<String, String>() {
/**
*
*/
private static final long serialVersionUID = 1L;
{
put("key1", "value1");
put("key2", "value2");
}
};
return doubleBraceMap;
}
public Map<String, String> createMapUsingStreamStringArray() {
Map<String, String> map = Stream.of(new String[][] { { "Hello", "World" }, { "John", "Doe" }, })
.collect(Collectors.toMap(data -> data[0], data -> data[1]));
return map;
}
public Map<String, Integer> createMapUsingStreamObjectArray() {
Map<String, Integer> map = Stream.of(new Object[][] { { "data1", 1 }, { "data2", 2 }, })
.collect(Collectors.toMap(data -> (String) data[0], data -> (Integer) data[1])); | return map;
}
public Map<String, Integer> createMapUsingStreamSimpleEntry() {
Map<String, Integer> map = Stream.of(new AbstractMap.SimpleEntry<>("idea", 1), new AbstractMap.SimpleEntry<>("mobile", 2))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
return map;
}
public Map<String, Integer> createMapUsingStreamSimpleImmutableEntry() {
Map<String, Integer> map = Stream.of(new AbstractMap.SimpleImmutableEntry<>("idea", 1), new AbstractMap.SimpleImmutableEntry<>("mobile", 2))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
return map;
}
public Map<String, String> createImmutableMapWithStreams() {
Map<String, String> map = Stream.of(new String[][] { { "Hello", "World" }, { "John", "Doe" }, })
.collect(Collectors.collectingAndThen(Collectors.toMap(data -> data[0], data -> data[1]), Collections::<String, String> unmodifiableMap));
return map;
}
} | repos\tutorials-master\core-java-modules\core-java-collections-maps\src\main\java\com\baeldung\map\initialize\MapInitializer.java | 1 |
请完成以下Java代码 | private void fetchPackingMaterialsFromGebindeLager(final IHUContext huContext)
{
huTrxBL.createHUContextProcessorExecutor(huContext)
.run((IHUContextProcessor)huContext1 -> IHUContextProcessor.NULL_RESULT);
}
/**
* Assign <code>hu</code> to receipt line. Also transfer the attributes from HU to receipt line's ASI.
*
* @param hu top level HU (LU, TU, VHU)
*/
private void transferHandlingUnit(final IHUContext huContext,
final I_M_ReceiptSchedule rs,
final I_M_HU hu,
final I_M_InOutLine receiptLine)
{
//
// Assign it to Receipt Line
assignHU(receiptLine, hu);
//
// Transfer attributes from HU to receipt line's ASI
final IHUContextProcessorExecutor executor = huTrxBL.createHUContextProcessorExecutor(huContext);
executor.run((IHUContextProcessor)huContext1 -> {
final IHUTransactionAttributeBuilder trxAttributesBuilder = executor.getTrxAttributesBuilder();
final IAttributeStorageFactory attributeStorageFactory = trxAttributesBuilder.getAttributeStorageFactory();
final IAttributeStorage huAttributeStorageFrom = attributeStorageFactory.getAttributeStorage(hu);
final IAttributeStorage receiptLineAttributeStorageTo = attributeStorageFactory.getAttributeStorage(receiptLine);
final IHUStorageFactory storageFactory = huContext1.getHUStorageFactory();
final IHUStorage huStorageFrom = storageFactory.getStorage(hu);
final IHUAttributeTransferRequestBuilder requestBuilder = new HUAttributeTransferRequestBuilder(huContext1)
.setProductId(ProductId.ofRepoId(rs.getM_Product_ID()))
.setQty(receiptScheduleBL.getQtyMoved(rs)) | .setUOM(loadOutOfTrx(rs.getC_UOM_ID(), I_C_UOM.class))
.setAttributeStorageFrom(huAttributeStorageFrom)
.setAttributeStorageTo(receiptLineAttributeStorageTo)
.setHUStorageFrom(huStorageFrom);
final IHUAttributeTransferRequest request = requestBuilder.create();
trxAttributesBuilder.transferAttributes(request);
return IHUContextProcessor.NULL_RESULT;
});
//
// Create HU snapshots
huSnapshotProducer.addModel(hu);
}
private void unassignHU(final I_M_ReceiptSchedule_Alloc rsa)
{
//
// De-activate this allocation because we moved the HU to receipt line
// TODO: provide proper implementation. See http://dewiki908/mediawiki/index.php/06103_Create_proper_HU_transactions_when_creating_Receipt_from_Schedules_%28102206835942%29
rsa.setIsActive(false);
InterfaceWrapperHelper.save(rsa);
}
private void assignHU(final I_M_InOutLine receiptLine, final I_M_HU hu)
{
final String trxName = InterfaceWrapperHelper.getTrxName(receiptLine);
huAssignmentBL.assignHU(receiptLine, hu, trxName);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\inoutcandidate\spi\impl\InOutProducerFromReceiptScheduleHU.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class GatewayConfiguration {
@Configuration
public static class SwaggerBasePathRewritingConfiguration {
@Bean
public SwaggerBasePathRewritingFilter swaggerBasePathRewritingFilter(){
return new SwaggerBasePathRewritingFilter();
}
}
@Configuration
public static class AccessControlFilterConfiguration {
@Bean
public AccessControlFilter accessControlFilter(RouteLocator routeLocator, JHipsterProperties jHipsterProperties){
return new AccessControlFilter(routeLocator, jHipsterProperties);
}
}
/**
* Configures the Zuul filter that limits the number of API calls per user.
* <p> | * This uses Bucket4J to limit the API calls, see {@link com.baeldung.jhipster.gateway.gateway.ratelimiting.RateLimitingFilter}.
*/
@Configuration
@ConditionalOnProperty("jhipster.gateway.rate-limiting.enabled")
public static class RateLimitingConfiguration {
private final JHipsterProperties jHipsterProperties;
public RateLimitingConfiguration(JHipsterProperties jHipsterProperties) {
this.jHipsterProperties = jHipsterProperties;
}
@Bean
public RateLimitingFilter rateLimitingFilter() {
return new RateLimitingFilter(jHipsterProperties);
}
}
} | repos\tutorials-master\jhipster-modules\jhipster-uaa\gateway\src\main\java\com\baeldung\jhipster\gateway\config\GatewayConfiguration.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public final IPackingItem getUnpackedItemByGroupingKey(@NonNull final PackingItemGroupingKey groupingKey)
{
final ImmutableList<IPackingItem> items = getUnpackedItems()
.stream()
.filter(item -> PackingItemGroupingKey.equals(item.getGroupingKey(), groupingKey))
.collect(ImmutableList.toImmutableList());
if (items.isEmpty())
{
return null;
}
else if (items.size() == 1)
{
return items.get(0);
}
else
{
throw new AdempiereException("More than one item found for " + groupingKey + " in " + this);
}
}
public void addUnpackedItem(@NonNull final IPackingItem item)
{
addItem(PackingSlot.UNPACKED, item);
}
public void addUnpackedItems(final Collection<? extends IPackingItem> items)
{
addItems(PackingSlot.UNPACKED, items);
}
public void addItem(@NonNull final PackingSlot slot, @NonNull final IPackingItem item)
{
items.put(slot, item);
}
public void addItems(@NonNull final PackingSlot slot, @NonNull final Collection<? extends IPackingItem> items)
{
this.items.putAll(slot, items);
}
public PackingItemsMap copy()
{
return new PackingItemsMap(this);
}
public List<IPackingItem> removeBySlot(@NonNull final PackingSlot slot)
{
return items.removeAll(slot);
}
public void removeUnpackedItem(@NonNull final IPackingItem itemToRemove)
{
final boolean removed = items.remove(PackingSlot.UNPACKED, itemToRemove);
if (!removed)
{
throw new AdempiereException("Unpacked item " + itemToRemove + " was not found in: " + items.get(PackingSlot.UNPACKED));
}
}
/**
* Append given <code>itemPacked</code> to existing packed items
*
* @param slot
* @param packedItem | */
public void appendPackedItem(@NonNull final PackingSlot slot, @NonNull final IPackingItem packedItem)
{
for (final IPackingItem item : items.get(slot))
{
// add new item into the list only if is a real new item
// NOTE: should be only one item with same grouping key
if (PackingItemGroupingKey.equals(item.getGroupingKey(), packedItem.getGroupingKey()))
{
item.addParts(packedItem);
return;
}
}
//
// No matching existing packed item where our item could be added was found
// => add it here as a new item
addItem(slot, packedItem);
}
/**
*
* @return true if there exists at least one packed item
*/
public boolean hasPackedItems()
{
return streamPackedItems().findAny().isPresent();
}
public boolean hasPackedItemsMatching(@NonNull final Predicate<IPackingItem> predicate)
{
return streamPackedItems().anyMatch(predicate);
}
public Stream<IPackingItem> streamPackedItems()
{
return items
.entries()
.stream()
.filter(e -> !e.getKey().isUnpacked())
.map(e -> e.getValue());
}
/**
*
* @return true if there exists at least one unpacked item
*/
public boolean hasUnpackedItems()
{
return !items.get(PackingSlot.UNPACKED).isEmpty();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\picking\service\PackingItemsMap.java | 2 |
请完成以下Java代码 | public void setResourceNamesOnEventDefinitions(ParsedDeployment parsedDeployment) {
for (EventDefinitionEntity eventDefinition : parsedDeployment.getAllEventDefinitions()) {
String resourceName = parsedDeployment.getResourceForEventDefinition(eventDefinition).getName();
eventDefinition.setResourceName(resourceName);
}
}
/**
* Gets the persisted event definition that matches this one for tenant and key.
* If none is found, returns null. This method assumes that the tenant and key are properly set on the
* event definition entity.
*/
public EventDefinitionEntity getMostRecentVersionOfEventDefinition(EventDefinitionEntity eventDefinition) {
String key = eventDefinition.getKey();
String tenantId = eventDefinition.getTenantId();
EventDefinitionEntityManager eventDefinitionEntityManager = CommandContextUtil.getEventRegistryConfiguration().getEventDefinitionEntityManager();
EventDefinitionEntity existingDefinition = null;
if (tenantId != null && !tenantId.equals(EventRegistryEngineConfiguration.NO_TENANT_ID)) {
existingDefinition = eventDefinitionEntityManager.findLatestEventDefinitionByKeyAndTenantId(key, tenantId);
} else {
existingDefinition = eventDefinitionEntityManager.findLatestEventDefinitionByKey(key);
}
return existingDefinition; | }
/**
* Gets the persisted version of the already-deployed event definition.
*/
public EventDefinitionEntity getPersistedInstanceOfEventDefinition(EventDefinitionEntity eventDefinition) {
String deploymentId = eventDefinition.getDeploymentId();
if (StringUtils.isEmpty(eventDefinition.getDeploymentId())) {
throw new FlowableIllegalArgumentException("Provided event definition must have a deployment id.");
}
EventDefinitionEntityManager eventDefinitionEntityManager = CommandContextUtil.getEventRegistryConfiguration().getEventDefinitionEntityManager();
EventDefinitionEntity persistedEventDefinition = null;
if (eventDefinition.getTenantId() == null || EventRegistryEngineConfiguration.NO_TENANT_ID.equals(eventDefinition.getTenantId())) {
persistedEventDefinition = eventDefinitionEntityManager.findEventDefinitionByDeploymentAndKey(deploymentId, eventDefinition.getKey());
} else {
persistedEventDefinition = eventDefinitionEntityManager.findEventDefinitionByDeploymentAndKeyAndTenantId(deploymentId,
eventDefinition.getKey(), eventDefinition.getTenantId());
}
return persistedEventDefinition;
}
} | repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\deployer\EventDefinitionDeploymentHelper.java | 1 |
请完成以下Java代码 | public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
public void setRootProcessInstanceId(String rootProcessInstanceId) {
this.rootProcessInstanceId = rootProcessInstanceId;
}
@Override
public Set<String> getReferencedEntityIds() {
Set<String> referencedEntityIds = new HashSet<String>();
return referencedEntityIds;
}
@Override
public Map<String, Class> getReferencedEntitiesIdAndClass() {
Map<String, Class> referenceIdAndClass = new HashMap<String, Class>();
return referenceIdAndClass; | }
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[id=" + id
+ ", revision=" + revision
+ ", authorizationType=" + authorizationType
+ ", permissions=" + permissions
+ ", userId=" + userId
+ ", groupId=" + groupId
+ ", resourceType=" + resourceType
+ ", resourceId=" + resourceId
+ "]";
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\AuthorizationEntity.java | 1 |
请完成以下Java代码 | public Tls sslContext(SSLContext sslContext) {
this.tls.sslContext(sslContext);
return this;
}
public Tls trustEverything() {
this.tls.trustEverything();
return this;
}
}
public static final class Affinity {
private final ConnectionSettings.Affinity<? extends ConnectionBuilder> affinity;
private Affinity(ConnectionSettings.Affinity<? extends ConnectionBuilder> affinity) {
this.affinity = affinity;
}
public Affinity queue(String queue) {
this.affinity.queue(queue);
return this;
}
public Affinity operation(ConnectionSettings.Affinity.Operation operation) {
this.affinity.operation(operation);
return this;
}
public Affinity reuse(boolean reuse) {
this.affinity.reuse(reuse);
return this;
}
public Affinity strategy(ConnectionSettings.AffinityStrategy strategy) {
this.affinity.strategy(strategy);
return this;
}
}
public static final class OAuth2 {
private final OAuth2Settings<? extends ConnectionBuilder> oAuth2Settings;
private OAuth2(OAuth2Settings<? extends ConnectionBuilder> oAuth2Settings) {
this.oAuth2Settings = oAuth2Settings;
}
public OAuth2 tokenEndpointUri(String uri) {
this.oAuth2Settings.tokenEndpointUri(uri);
return this;
}
public OAuth2 clientId(String clientId) {
this.oAuth2Settings.clientId(clientId);
return this;
}
public OAuth2 clientSecret(String clientSecret) { | this.oAuth2Settings.clientSecret(clientSecret);
return this;
}
public OAuth2 grantType(String grantType) {
this.oAuth2Settings.grantType(grantType);
return this;
}
public OAuth2 parameter(String name, String value) {
this.oAuth2Settings.parameter(name, value);
return this;
}
public OAuth2 shared(boolean shared) {
this.oAuth2Settings.shared(shared);
return this;
}
public OAuth2 sslContext(SSLContext sslContext) {
this.oAuth2Settings.tls().sslContext(sslContext);
return this;
}
}
public static final class Recovery {
private final ConnectionBuilder.RecoveryConfiguration recoveryConfiguration;
private Recovery(ConnectionBuilder.RecoveryConfiguration recoveryConfiguration) {
this.recoveryConfiguration = recoveryConfiguration;
}
public Recovery activated(boolean activated) {
this.recoveryConfiguration.activated(activated);
return this;
}
public Recovery backOffDelayPolicy(BackOffDelayPolicy backOffDelayPolicy) {
this.recoveryConfiguration.backOffDelayPolicy(backOffDelayPolicy);
return this;
}
public Recovery topology(boolean activated) {
this.recoveryConfiguration.topology(activated);
return this;
}
}
} | repos\spring-amqp-main\spring-rabbitmq-client\src\main\java\org\springframework\amqp\rabbitmq\client\SingleAmqpConnectionFactory.java | 1 |
请完成以下Java代码 | final class HttpCodecDelegate {
private static final ResolvableType REQUEST_TYPE = ResolvableType.forClass(SerializableGraphQlRequest.class);
private static final ResolvableType RESPONSE_TYPE = ResolvableType.forClassWithGenerics(Map.class, String.class, Object.class);
private final Decoder<?> decoder;
private final Encoder<?> encoder;
HttpCodecDelegate(CodecConfigurer codecConfigurer) {
Assert.notNull(codecConfigurer, "CodecConfigurer is required");
this.decoder = findJsonDecoder(codecConfigurer);
this.encoder = findJsonEncoder(codecConfigurer);
}
private static Decoder<?> findJsonDecoder(CodecConfigurer configurer) {
return configurer.getReaders().stream()
.filter((reader) -> reader.canRead(REQUEST_TYPE, MediaType.APPLICATION_JSON))
.map((reader) -> ((DecoderHttpMessageReader<?>) reader).getDecoder())
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("No JSON Decoder"));
}
private static Encoder<?> findJsonEncoder(CodecConfigurer configurer) {
return configurer.getWriters().stream()
.filter((writer) -> writer.canWrite(RESPONSE_TYPE, MediaType.APPLICATION_JSON)) | .map((writer) -> ((EncoderHttpMessageWriter<?>) writer).getEncoder())
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("No JSON Encoder"));
}
@SuppressWarnings("unchecked")
DataBuffer encode(Map<String, Object> resultMap) {
return ((Encoder<Map<String, Object>>) this.encoder).encodeValue(
resultMap, DefaultDataBufferFactory.sharedInstance, RESPONSE_TYPE, MimeTypeUtils.APPLICATION_JSON, null);
}
@SuppressWarnings("unchecked")
Mono<SerializableGraphQlRequest> decode(Publisher<DataBuffer> inputStream, MediaType contentType) {
return (Mono<SerializableGraphQlRequest>) this.decoder.decodeToMono(inputStream, REQUEST_TYPE, contentType, null);
}
} | repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\server\webflux\HttpCodecDelegate.java | 1 |
请完成以下Java代码 | public class DatabaseGOClientLogger implements GOClientLogger
{
public static final transient DatabaseGOClientLogger instance = new DatabaseGOClientLogger();
private static final Logger logger = LogManager.getLogger(DatabaseGOClientLogger.class);
private DatabaseGOClientLogger()
{
}
@Override
public void log(@NonNull final GOClientLogEvent event)
{
try
{
createLogRecord(event);
}
catch (final Exception ex)
{
logger.warn("Failed creating GO log record: {}", event, ex);
}
// Also send it to SLF4J logger
SLF4JGOClientLogger.instance.log(event);
}
private void createLogRecord(@NonNull final GOClientLogEvent event)
{ | final I_GO_DeliveryOrder_Log logRecord = InterfaceWrapperHelper.newInstance(I_GO_DeliveryOrder_Log.class);
logRecord.setAction(event.getAction());
logRecord.setGO_ConfigSummary(event.getConfigSummary());
logRecord.setDurationMillis((int)event.getDurationMillis());
if (event.getDeliveryOrderRepoId() > 0)
{
logRecord.setGO_DeliveryOrder_ID(event.getDeliveryOrderRepoId());
}
logRecord.setRequestMessage(event.getRequestAsString());
if (event.getResponseException() != null)
{
logRecord.setIsError(true);
final AdIssueId issueId = Services.get(IErrorManager.class).createIssue(event.getResponseException());
logRecord.setAD_Issue_ID(issueId.getRepoId());
}
else
{
logRecord.setIsError(false);
logRecord.setResponseMessage(event.getResponseAsString());
}
InterfaceWrapperHelper.save(logRecord);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.go\src\main\java\de\metas\shipper\gateway\go\DatabaseGOClientLogger.java | 1 |
请完成以下Java代码 | public class C_SubscriptionProgress
{
static final transient C_SubscriptionProgress instance = new C_SubscriptionProgress();
private C_SubscriptionProgress()
{
}
@ModelChange(timings = { ModelValidator.TYPE_AFTER_NEW, ModelValidator.TYPE_AFTER_CHANGE })
public void createMissingShipmentSchedules(@NonNull final I_C_SubscriptionProgress subscriptionProgress)
{
if (!isGoingToHaveAShipmentScheduleSomeDay(subscriptionProgress))
{
return;
}
CreateMissingShipmentSchedulesWorkpackageProcessor.scheduleIfNotPostponed(subscriptionProgress);
}
@ModelChange(timings = ModelValidator.TYPE_BEFORE_DELETE)
public void deleteShipmentSchedules(@NonNull final I_C_SubscriptionProgress subscriptionProgress)
{
Services.get(IShipmentSchedulePA.class)
.deleteAllForReference(TableRecordReference.of(subscriptionProgress));
}
@ModelChange(//
timings = { ModelValidator.TYPE_AFTER_NEW, ModelValidator.TYPE_AFTER_CHANGE }, //
ifColumnsChanged = { I_C_SubscriptionProgress.COLUMNNAME_DropShip_BPartner_ID, I_C_SubscriptionProgress.COLUMNNAME_DropShip_Location_ID })
public void assertDropshipFieldsAreValid(@NonNull final I_C_SubscriptionProgress subscriptionProgress)
{
if (!isGoingToHaveAShipmentScheduleSomeDay(subscriptionProgress))
{
return;
} | Check.errorIf(subscriptionProgress.getDropShip_BPartner_ID() <= 0,
"The given subscription progress needs to have DropShip_BPartner_ID > 0; subscriptionProgress={}",
subscriptionProgress);
Check.errorIf(subscriptionProgress.getDropShip_Location_ID() <= 0,
"The given subscription progress needs to have DropShip_Location_ID > 0; subscriptionProgress={}",
subscriptionProgress);
}
private boolean isGoingToHaveAShipmentScheduleSomeDay(@NonNull final I_C_SubscriptionProgress subscriptionProgress)
{
if (!X_C_SubscriptionProgress.EVENTTYPE_Delivery.equals(subscriptionProgress.getEventType()))
{
return false;
}
if (!X_C_SubscriptionProgress.STATUS_Planned.equals(subscriptionProgress.getStatus()))
{
return false;
}
if (!X_C_SubscriptionProgress.CONTRACTSTATUS_Running.equals(subscriptionProgress.getContractStatus()))
{
return false;
}
if (subscriptionProgress.getM_ShipmentSchedule_ID() > 0)
{
return false;
}
return true;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\interceptor\C_SubscriptionProgress.java | 1 |
请完成以下Java代码 | public String toString()
{
return getAsString();
}
public static Cell ofNullable(@Nullable final Object valueObj)
{
if (valueObj instanceof Cell)
{
return (Cell)valueObj;
}
final String valueStr = valueObj != null ? valueObj.toString() : null;
return valueStr != null
? new Cell(valueStr, false)
: NULL; | }
public String getAsString()
{
return isNull ? NULL_DISPLAY_STRING : valueStr;
}
public int getWidth()
{
return getAsString().length();
}
public boolean isBlank()
{
return isNull || Check.isBlank(valueStr);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\text\tabular\Cell.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public LazyInitRegistration lazyInitRegistration() {
return new LazyInitRegistration();
}
@Bean
public FaviconResourceResolver faviconResourceResolver() {
return new FaviconResourceResolver();
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
final String classpath = "classpath:" + properties.getWebapp().getWebjarClasspath();
WebappProperty webapp = properties.getWebapp();
String applicationPath = webapp.getApplicationPath();
registry.addResourceHandler(applicationPath + "/lib/**")
.addResourceLocations(classpath + "/lib/");
registry.addResourceHandler(applicationPath + "/api/**")
.addResourceLocations("classpath:/api/");
registry.addResourceHandler(applicationPath + "/app/**")
.addResourceLocations(classpath + "/app/"); | registry.addResourceHandler(applicationPath + "/assets/**")
.addResourceLocations(classpath + "/assets/");
registry.addResourceHandler(applicationPath + "/favicon.ico")
.addResourceLocations(classpath + "/") // add slash to get rid of the WARN log
.resourceChain(true)
.addResolver(faviconResourceResolver());
}
@Override
public void addViewControllers(ViewControllerRegistry registry) {
WebappProperty webapp = properties.getWebapp();
if (webapp.isIndexRedirectEnabled()) {
String applicationPath = webapp.getApplicationPath();
registry.addRedirectViewController("/", applicationPath + "/app/");
}
}
} | repos\camunda-bpm-platform-master\spring-boot-starter\starter-webapp-core\src\main\java\org\camunda\bpm\spring\boot\starter\webapp\CamundaBpmWebappAutoConfiguration.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public SecurityContextPrincipalProvider securityContextPrincipalProvider() {
return new LocalSpringSecurityContextPrincipalProvider();
}
@Bean
@ConditionalOnMissingBean
public PrincipalIdentityProvider principalIdentityProvider() {
return new AuthenticationPrincipalIdentityProvider();
}
@Bean
@ConditionalOnMissingBean
public PrincipalGroupsProvider principalGroupsProvider(
GrantedAuthoritiesResolver grantedAuthoritiesResolver,
GrantedAuthoritiesGroupsMapper grantedAuthoritiesGroupsMapper
) {
return new AuthenticationPrincipalGroupsProvider(grantedAuthoritiesResolver, grantedAuthoritiesGroupsMapper);
}
@Bean
@ConditionalOnMissingBean
public PrincipalRolesProvider principalRolessProvider(
GrantedAuthoritiesResolver grantedAuthoritiesResolver, | GrantedAuthoritiesRolesMapper grantedAuthoritiesRolesMapper
) {
return new AuthenticationPrincipalRolesProvider(grantedAuthoritiesResolver, grantedAuthoritiesRolesMapper);
}
@Bean
@ConditionalOnMissingBean
public SecurityManager securityManager(
SecurityContextPrincipalProvider securityContextPrincipalProvider,
PrincipalIdentityProvider principalIdentityProvider,
PrincipalGroupsProvider principalGroupsProvider,
PrincipalRolesProvider principalRolessProvider
) {
return new LocalSpringSecurityManager(
securityContextPrincipalProvider,
principalIdentityProvider,
principalGroupsProvider,
principalRolessProvider
);
}
} | repos\Activiti-develop\activiti-core-common\activiti-spring-security\src\main\java\org\activiti\core\common\spring\security\config\ActivitiSpringSecurityAutoConfiguration.java | 2 |
请完成以下Java代码 | protected String doIt() throws Exception
{
if (shipmentSchedule == null || shipmentSchedule.getM_ShipmentSchedule_ID() <= 0)
{
throw new FillMandatoryException(I_M_ShipmentSchedule.COLUMNNAME_M_ShipmentSchedule_ID);
}
final ShipmentScheduleQtyOnHandStorage storagesContainer = shipmentScheduleQtyOnHandStorageFactory.ofShipmentSchedule(shipmentSchedule);
final ShipmentScheduleAvailableStock storageDetails = storagesContainer.getStockDetailsMatching(shipmentSchedule);
addLog("@QtyOnHand@ (@Total@): " + storageDetails.getTotalQtyAvailable());
for (int storageIndex = 0; storageIndex < storageDetails.size(); storageIndex++)
{
final ShipmentScheduleAvailableStockDetail storageDetail = storageDetails.getStorageDetail(storageIndex); | addLog("------------------------------------------------------------");
addLog(storageDetail.toString());
}
//
// Also show the Storage Query
{
final StockDataQuery materialQuery = storagesContainer.toQuery(shipmentSchedule);
addLog("------------------------------------------------------------");
addLog("Storage Query:");
addLog(String.valueOf(materialQuery));
}
return MSG_OK;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\process\M_ShipmentSchedule_ShowMatchingStorages.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setDurationUnits(TimeUnit durationUnits) {
this.durationUnits = durationUnits;
}
public String getHost() {
return this.host;
}
public void setHost(String host) {
this.host = host;
}
public Integer getPort() {
return this.port;
}
public void setPort(Integer port) {
this.port = port;
}
public GraphiteProtocol getProtocol() {
return this.protocol;
}
public void setProtocol(GraphiteProtocol protocol) {
this.protocol = protocol;
}
public Boolean getGraphiteTagsEnabled() { | return (this.graphiteTagsEnabled != null) ? this.graphiteTagsEnabled : ObjectUtils.isEmpty(this.tagsAsPrefix);
}
public void setGraphiteTagsEnabled(Boolean graphiteTagsEnabled) {
this.graphiteTagsEnabled = graphiteTagsEnabled;
}
public String[] getTagsAsPrefix() {
return this.tagsAsPrefix;
}
public void setTagsAsPrefix(String[] tagsAsPrefix) {
this.tagsAsPrefix = tagsAsPrefix;
}
} | repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\graphite\GraphiteProperties.java | 2 |
请完成以下Java代码 | protected Instance[] loadTrainInstances(String trainingFile, final MutableFeatureMap mutableFeatureMap) throws IOException
{
final List<Instance> instanceList = new LinkedList<Instance>();
IOUtility.loadInstance(trainingFile, new InstanceHandler()
{
@Override
public boolean process(Sentence sentence)
{
Utility.normalize(sentence);
instanceList.add(PerceptronTrainer.this.createInstance(sentence, mutableFeatureMap));
return false;
}
});
Instance[] instances = new Instance[instanceList.size()];
instanceList.toArray(instances);
return instances;
}
private static DoubleArrayTrie<Integer> loadDictionary(String trainingFile, String dictionaryFile) throws IOException
{
FrequencyMap dictionaryMap = new FrequencyMap();
if (dictionaryFile == null)
{
out.printf("从训练文件%s中统计词库...\n", trainingFile);
loadWordFromFile(trainingFile, dictionaryMap, true);
}
else
{
out.printf("从外部词典%s中加载词库...\n", trainingFile);
loadWordFromFile(dictionaryFile, dictionaryMap, false);
}
DoubleArrayTrie<Integer> dat = new DoubleArrayTrie<Integer>();
dat.build(dictionaryMap);
out.printf("加载完毕,词库总词数:%d,总词频:%d\n", dictionaryMap.size(), dictionaryMap.totalFrequency);
return dat;
}
public Result train(String trainingFile, String modelFile) throws IOException | {
return train(trainingFile, trainingFile, modelFile);
}
public Result train(String trainingFile, String developFile, String modelFile) throws IOException
{
return train(trainingFile, developFile, modelFile, 0.1, 50, Runtime.getRuntime().availableProcessors());
}
private static void loadWordFromFile(String path, FrequencyMap storage, boolean segmented) throws IOException
{
BufferedReader br = IOUtility.newBufferedReader(path);
String line;
while ((line = br.readLine()) != null)
{
if (segmented)
{
for (String word : IOUtility.readLineToArray(line))
{
storage.add(word);
}
}
else
{
line = line.trim();
if (line.length() != 0)
{
storage.add(line);
}
}
}
br.close();
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\perceptron\PerceptronTrainer.java | 1 |
请完成以下Java代码 | public String getDestination() {
return destination;
}
public void setDestination(String destination) {
this.destination = destination;
}
@Column(name = "delivered", columnDefinition = "boolean")
public boolean isDelivered() {
return isDelivered;
}
public void setDelivered(boolean delivered) {
isDelivered = delivered;
}
@ElementCollection(fetch = EAGER)
@CollectionTable(name = "consignment_item", joinColumns = @JoinColumn(name = "consignment_id"))
@OrderColumn(name = "item_index") | public List<Item> getItems() {
return items;
}
public void setItems(List<Item> items) {
this.items = items;
}
@ElementCollection(fetch = EAGER)
@CollectionTable(name = "consignment_checkin", joinColumns = @JoinColumn(name = "consignment_id"))
@OrderColumn(name = "checkin_index")
public List<Checkin> getCheckins() {
return checkins;
}
public void setCheckins(List<Checkin> checkins) {
this.checkins = checkins;
}
} | repos\tutorials-master\aws-modules\aws-lambda-modules\shipping-tracker-lambda\ShippingFunction\src\main\java\com\baeldung\lambda\shipping\Consignment.java | 1 |
请完成以下Java代码 | public final HttpStatusCode statusCode() {
return this.statusCode;
}
@Override
public void setStatusCode(HttpStatusCode statusCode) {
this.statusCode = statusCode;
}
@Override
public final HttpHeaders headers() {
return this.headers;
}
@Override
public MultiValueMap<String, Cookie> cookies() {
return this.cookies;
}
@Override
public @Nullable ModelAndView writeTo(HttpServletRequest request, HttpServletResponse response, Context context)
throws ServletException, IOException {
try {
writeStatusAndHeaders(response);
long lastModified = headers().getLastModified();
ServletWebRequest servletWebRequest = new ServletWebRequest(request, response);
HttpMethod httpMethod = HttpMethod.valueOf(request.getMethod());
if (SAFE_METHODS.contains(httpMethod)
&& servletWebRequest.checkNotModified(headers().getETag(), lastModified)) {
return null;
}
else {
return writeToInternal(request, response, context);
}
}
catch (Throwable throwable) {
return handleError(throwable, request, response, context); | }
}
private void writeStatusAndHeaders(HttpServletResponse response) {
response.setStatus(this.statusCode.value());
writeHeaders(response);
writeCookies(response);
}
private void writeHeaders(HttpServletResponse servletResponse) {
this.headers.forEach((headerName, headerValues) -> {
for (String headerValue : headerValues) {
servletResponse.addHeader(headerName, headerValue);
}
});
// HttpServletResponse exposes some headers as properties: we should include those
// if not already present
if (servletResponse.getContentType() == null && this.headers.getContentType() != null) {
servletResponse.setContentType(this.headers.getContentType().toString());
}
if (servletResponse.getCharacterEncoding() == null && this.headers.getContentType() != null
&& this.headers.getContentType().getCharset() != null) {
servletResponse.setCharacterEncoding(this.headers.getContentType().getCharset().name());
}
}
private void writeCookies(HttpServletResponse servletResponse) {
this.cookies.values().stream().flatMap(Collection::stream).forEach(servletResponse::addCookie);
}
protected abstract @Nullable ModelAndView writeToInternal(HttpServletRequest request, HttpServletResponse response,
Context context) throws Exception;
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\handler\AbstractGatewayServerResponse.java | 1 |
请完成以下Java代码 | private static String stripQuotes(final String rolloutDir)
{
if (rolloutDir == null)
{
return null;
}
return rolloutDir
.replaceAll("^\"|\"$", "")
.replaceAll("^'|'$", "");
}
public final void printHelp(final PrintStream out)
{
final PrintWriter writer = new PrintWriter(out);
final String commandName = "RolloutMigrate";
final String header = "Util to apply metasfresh migration scripts to a POstgresSQL database. The database settings are read from a settings (properties) file.\n"
+ "The tool will by default only run if its own version (as set in in the " + RolloutVersionLoader.PROP_VERSION + " property of its " + RolloutVersionLoader.BUILD_INFO_FILENAME + ")"
+ " is higher than the version selected from the DB (AD_System.DBVersion).";
final String footer = "\nHints: "
+ "* For each individual migration file the tool checks against the Table AD_MigrationScript if the migration file was already been applied"
+ "* The migration files are ordered by their filenames \"globally\", no matter in thich directory they are";
final HelpFormatter formatter = new HelpFormatter();
formatter.printHelp(
writer, // output
200, // width,
stripQuotes(commandName), // cmdLineSyntax
stripQuotes(header), // header,
options, // options
4, // leftPad, | 4, // descPad,
stripQuotes(footer), // footer,
true // autoUsage
);
writer.flush();
}
public final String printHelpToString()
{
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final PrintStream out = new PrintStream(baos);
printHelp(out);
final String content = baos.toString();
return stripQuotes(content);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.cli\src\main\java\de\metas\migration\cli\rollout_migrate\CommandlineParams.java | 1 |
请完成以下Java代码 | public ChangeLogRecord build()
{
return new ChangeLogRecord(this);
}
public Builder setAD_Session_ID(final int AD_Session_ID)
{
this.AD_Session_ID = AD_Session_ID;
return this;
}
public Builder setTrxName(final String trxName)
{
this.trxName = trxName;
return this;
}
public Builder setAD_Table_ID(final int AD_Table_ID)
{
this.AD_Table_ID = AD_Table_ID;
return this;
}
public Builder setAD_Column_ID(final int AD_Column_ID)
{
this.AD_Column_ID = AD_Column_ID;
return this;
}
public Builder setRecord_ID(final int record_ID)
{
this.record_ID = record_ID;
return this;
}
public Builder setAD_Client_ID(final int AD_Client_ID)
{
this.AD_Client_ID = AD_Client_ID;
return this;
}
public Builder setAD_Org_ID(final int AD_Org_ID)
{
this.AD_Org_ID = AD_Org_ID;
return this;
}
public Builder setOldValue(final Object oldValue)
{
this.oldValue = oldValue; | return this;
}
public Builder setNewValue(final Object newValue)
{
this.newValue = newValue;
return this;
}
public Builder setEventType(final String eventType)
{
this.eventType = eventType;
return this;
}
public Builder setAD_User_ID(final int AD_User_ID)
{
this.AD_User_ID = AD_User_ID;
return this;
}
/**
*
* @param AD_PInstance_ID
* @return
* @task https://metasfresh.atlassian.net/browse/FRESH-314
*/
public Builder setAD_PInstance_ID(final PInstanceId AD_PInstance_ID)
{
this.AD_PInstance_ID = AD_PInstance_ID;
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\session\ChangeLogRecord.java | 1 |
请完成以下Java代码 | protected String doIt()
{
if (from_AD_ImpFormat_ID.equals(to_AD_ImpFormat_ID))
{
throw new AdempiereException("Copying into same import format is not allowed");
}
final I_AD_ImpFormat from = retrieveImpFormatRecord(from_AD_ImpFormat_ID);
final I_AD_ImpFormat target = retrieveImpFormatRecord(to_AD_ImpFormat_ID);
if (from.getAD_Table_ID() != target.getAD_Table_ID())
{
throw new AdempiereException("From-To do Not have same Format Table");
}
final ClientId targetClientId = ClientId.ofRepoId(target.getAD_Client_ID());
if (!targetClientId.equals(getClientId()))
{
throw new AdempiereException("No permissions");
}
final List<I_AD_ImpFormat_Row> fromRows = retrieveRows(from_AD_ImpFormat_ID);
for (final I_AD_ImpFormat_Row row : fromRows)
{
copyRow(row, target);
}
final String msg = "#" + fromRows.size();
if (!from.getFormatType().equals(target.getFormatType()))
{
return msg + " - Note: Format Type different!";
}
return msg;
} // doIt
private I_AD_ImpFormat retrieveImpFormatRecord(@NonNull final ImpFormatId id)
{
final I_AD_ImpFormat from = load(id, I_AD_ImpFormat.class);
Check.assumeNotNull(from, "Parameter from is not null");
return from;
} | private List<I_AD_ImpFormat_Row> retrieveRows(@NonNull final ImpFormatId impFormatId)
{
return Services.get(IQueryBL.class)
.createQueryBuilder(I_AD_ImpFormat_Row.class)
.addEqualsFilter(I_AD_ImpFormat_Row.COLUMN_AD_ImpFormat_ID, impFormatId)
// .addOnlyActiveRecordsFilter() // ALL!
.orderBy(I_AD_ImpFormat_Row.COLUMN_SeqNo)
.create()
.list();
}
private void copyRow(final I_AD_ImpFormat_Row fromRow, final I_AD_ImpFormat target)
{
final I_AD_ImpFormat_Row toRow = newInstance(I_AD_ImpFormat_Row.class);
InterfaceWrapperHelper.copyValues(fromRow, toRow);
toRow.setAD_Org_ID(fromRow.getAD_Org_ID()); // usually "*"
toRow.setAD_ImpFormat_ID(target.getAD_ImpFormat_ID());
saveRecord(toRow);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\process\AD_ImpFormat_CopyLinesFrom.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public void setTenantIdLike(String tenantIdLike) {
this.tenantIdLike = tenantIdLike;
}
public Boolean getWithoutTenantId() {
return withoutTenantId;
}
public void setWithoutTenantId(Boolean withoutTenantId) {
this.withoutTenantId = withoutTenantId;
}
public Boolean getWithoutProcessInstanceId() {
return withoutProcessInstanceId;
}
public void setWithoutProcessInstanceId(Boolean withoutProcessInstanceId) {
this.withoutProcessInstanceId = withoutProcessInstanceId;
}
public String getTaskCandidateGroup() {
return taskCandidateGroup;
}
public void setTaskCandidateGroup(String taskCandidateGroup) {
this.taskCandidateGroup = taskCandidateGroup;
}
public boolean isIgnoreTaskAssignee() {
return ignoreTaskAssignee;
} | public void setIgnoreTaskAssignee(boolean ignoreTaskAssignee) {
this.ignoreTaskAssignee = ignoreTaskAssignee;
}
public String getPlanItemInstanceId() {
return planItemInstanceId;
}
public void setPlanItemInstanceId(String planItemInstanceId) {
this.planItemInstanceId = planItemInstanceId;
}
public String getRootScopeId() {
return rootScopeId;
}
public void setRootScopeId(String rootScopeId) {
this.rootScopeId = rootScopeId;
}
public String getParentScopeId() {
return parentScopeId;
}
public void setParentScopeId(String parentScopeId) {
this.parentScopeId = parentScopeId;
}
public Set<String> getScopeIds() {
return scopeIds;
}
public void setScopeIds(Set<String> scopeIds) {
this.scopeIds = scopeIds;
}
public String getScopeId() {
return scopeId;
}
public void setScopeId(String scopeId) {
this.scopeId = scopeId;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\history\task\HistoricTaskInstanceQueryRequest.java | 2 |
请完成以下Java代码 | private JsonOutOfStockResponse buildOutOfStockNoticeResponse(
@NonNull final Map<WarehouseId, String> warehouseId2InventoryDocNo,
@NonNull final Map<WarehouseId, List<ShipmentScheduleId>> warehouseId2ClosedShipmentSchedules)
{
final JsonOutOfStockResponse.JsonOutOfStockResponseBuilder responseBuilder = JsonOutOfStockResponse.builder();
final Set<WarehouseId> seenWarehouseIds = new HashSet<>();
warehouseId2ClosedShipmentSchedules.keySet()
.stream()
.map(warehouseId -> {
final List<JsonMetasfreshId> closedShipmentScheduleIds = warehouseId2ClosedShipmentSchedules.get(warehouseId)
.stream()
.map(ShipmentScheduleId::getRepoId)
.map(JsonMetasfreshId::of)
.collect(ImmutableList.toImmutableList());
if (closedShipmentScheduleIds.isEmpty())
{
return null;
}
seenWarehouseIds.add(warehouseId);
return JsonOutOfStockResponseItem.builder()
.warehouseId(JsonMetasfreshId.of(warehouseId.getRepoId()))
.closedShipmentSchedules(closedShipmentScheduleIds) | .inventoryDocNo(warehouseId2InventoryDocNo.get(warehouseId))
.build();
})
.filter(Objects::nonNull)
.forEach(responseBuilder::affectedWarehouse);
warehouseId2InventoryDocNo.entrySet()
.stream()
.filter(warehouseId2InvEntry -> !seenWarehouseIds.contains(warehouseId2InvEntry.getKey()))
.map(warehouseId2InvDocNoEntry -> JsonOutOfStockResponseItem.builder()
.inventoryDocNo(warehouseId2InvDocNoEntry.getValue())
.warehouseId(JsonMetasfreshId.of(warehouseId2InvDocNoEntry.getKey().getRepoId()))
.build())
.forEach(responseBuilder::affectedWarehouse);
return responseBuilder.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\warehouse\WarehouseService.java | 1 |
请完成以下Java代码 | private String getTokenFromRequest(Request request) {
return (request.getSourceContext() != null ? request.getSourceContext().getPeerAddress().getAddress().getHostAddress() : "null")
+ ":" + (request.getSourceContext() != null ? request.getSourceContext().getPeerAddress().getPort() : -1) + ":" + request.getTokenString();
}
public class CoapResourceObserver implements ResourceObserver {
@Override
public void changedName(String old) {
}
@Override
public void changedPath(String old) {
}
@Override
public void addedChild(Resource child) {
}
@Override
public void removedChild(Resource child) {
}
@Override
public void addedObserveRelation(ObserveRelation relation) {
}
@Override
public void removedObserveRelation(ObserveRelation relation) {
}
} | private void sendOtaData(CoapExchange exchange) {
String idStr = exchange.getRequestOptions().getUriPath().get(exchange.getRequestOptions().getUriPath().size() - 1
);
UUID currentId = UUID.fromString(idStr);
Response response = new Response(CoAP.ResponseCode.CONTENT);
byte[] otaData = this.getOtaData(currentId);
if (otaData != null && otaData.length > 0) {
log.debug("Read ota data (length): [{}]", otaData.length);
response.setPayload(otaData);
if (exchange.getRequestOptions().getBlock2() != null) {
int szx = exchange.getRequestOptions().getBlock2().getSzx();
int chunkSize = exchange.getRequestOptions().getBlock2().getSize();
boolean lastFlag = otaData.length <= chunkSize;
response.getOptions().setBlock2(szx, lastFlag, 0);
log.trace("With block2 Send currentId: [{}], length: [{}], chunkSize [{}], szx [{}], moreFlag [{}]", currentId, otaData.length, chunkSize, szx, lastFlag);
} else {
log.trace("With block1 Send currentId: [{}], length: [{}], ", currentId, otaData.length);
}
exchange.respond(response);
} else {
log.trace("Ota packaged currentId: [{}] is not found.", currentId);
}
}
private byte[] getOtaData(UUID currentId) {
return otaPackageDataCache.get(currentId.toString());
}
} | repos\thingsboard-master\common\transport\lwm2m\src\main\java\org\thingsboard\server\transport\lwm2m\server\LwM2mTransportCoapResource.java | 1 |
请完成以下Java代码 | public boolean updatePriceFromContract(final IPMMPricingAware pricingAware)
{
final I_C_Flatrate_Term flatrateTerm = pricingAware.getC_Flatrate_Term();
if (flatrateTerm == null)
{
throw new AdempiereException("@Missing@ @" + I_C_Flatrate_Term.COLUMNNAME_C_Flatrate_Term_ID + "@");
}
final ProductId productId = ProductId.ofRepoIdOrNull(pricingAware.getProductId());
if (productId == null)
{
logger.info("Event : {} is missing M_Product_ID!", pricingAware);
return false;
}
final I_C_Flatrate_DataEntry dataEntryForProduct = pricingAware.getC_Flatrate_DataEntry();
if (dataEntryForProduct == null)
{
logger.info("Event is missing C_Flatrate_DataEntry: {}", pricingAware);
return false;
}
final BigDecimal flatrateAmtPerUOM = dataEntryForProduct.getFlatrateAmtPerUOM();
// in case of null or negative flatrateAmtPerUOM, do not use it for pricing
if (InterfaceWrapperHelper.isNull(dataEntryForProduct, I_C_Flatrate_DataEntry.COLUMNNAME_FlatrateAmtPerUOM)
|| flatrateAmtPerUOM.signum() < 0)
{
logger.info("Invalid FlatrateAmtPerUOM: {} (event={})", flatrateAmtPerUOM, pricingAware);
return false;
}
final CurrencyId currencyId = CurrencyId.ofRepoIdOrNull(flatrateTerm.getC_Currency_ID());
if (currencyId == null)
{
logger.info("Missing CurrencyId on flatrateTerm: {}", flatrateTerm);
return false;
}
final UomId flatrateTermUomId = UomId.ofRepoIdOrNull(flatrateTerm.getC_UOM_ID());
if (flatrateTermUomId == null)
{
logger.info("Missing flatrateTermUomId on flatrateTerm: {}", flatrateTerm);
return false; | }
final ProductPrice productPriceInTermUOM = ProductPrice.builder()
.productId(productId)
.uomId(flatrateTermUomId)
.money(Money.of(flatrateAmtPerUOM, currencyId))
.build();
final UomId uomIdTo = UomId.ofRepoId(pricingAware.getC_UOM().getC_UOM_ID());
final CurrencyPrecision currencyPrecision = currencyDAO.getStdPrecision(currencyId);
final ProductPrice productPriceInTargetUOM = uomConversionBL.convertProductPriceToUom(productPriceInTermUOM, uomIdTo, currencyPrecision);
pricingAware.setCurrencyId(currencyId);
pricingAware.setPrice(productPriceInTargetUOM.toBigDecimal());
return true;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\impl\PMMPricingBL.java | 1 |
请完成以下Java代码 | private static void applySubtraction(List<String> validExpressions, Equation equation, int endIndex, StringBuilder currentExpression, long currentResult,
long currentOperandValue) {
appendToExpression(currentExpression, Operator.SUBTRACTION, currentOperandValue);
evaluateExpressions(validExpressions, equation, endIndex + 1, currentExpression, currentResult - currentOperandValue, -currentOperandValue);
removeFromExpression(currentExpression, Operator.SUBTRACTION, currentOperandValue);
}
private static void applyMultiplication(List<String> validExpressions, Equation equation, int endIndex, StringBuilder currentExpression, long currentResult,
long currentOperandValue, long lastOperand) {
appendToExpression(currentExpression, Operator.MULTIPLICATION, currentOperandValue);
evaluateExpressions(validExpressions, equation, endIndex + 1, currentExpression, currentResult - lastOperand + (lastOperand * currentOperandValue),
lastOperand * currentOperandValue);
removeFromExpression(currentExpression, Operator.MULTIPLICATION, currentOperandValue);
}
private static void appendToExpression(StringBuilder currentExpression, Operator operator, long currentOperand) {
currentExpression.append(operator.getSymbol())
.append(currentOperand);
}
private static void removeFromExpression(StringBuilder currentExpression, Operator operator, long currentOperand) {
currentExpression.setLength(currentExpression.length() - operator.getSymbolLength() - String.valueOf(currentOperand)
.length());
}
private enum Operator {
ADDITION("+"),
SUBTRACTION("-"),
MULTIPLICATION("*"),
NONE("");
private final String symbol;
private final int symbolLength;
Operator(String symbol) {
this.symbol = symbol;
this.symbolLength = symbol.length();
}
public String getSymbol() {
return symbol;
}
public int getSymbolLength() {
return symbolLength; | }
}
private static class Equation {
private final String digits;
private final int target;
public Equation(String digits, int target) {
this.digits = digits;
this.target = target;
}
public String getDigits() {
return digits;
}
public int getTarget() {
return target;
}
}
} | repos\tutorials-master\core-java-modules\core-java-string-algorithms-5\src\main\java\com\baeldung\backtracking\Backtracking.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public MADBoilerPlate getDefaultTextPreset() {
return null;
}
@Override
public String getExportFilePrefix() {
return null;
}
@Override
public I_AD_User getFrom() {
return null;
}
@Override
public String getMessage() {
return null; | }
@Override
public String getSubject() {
return null;
}
@Override
public String getTitle() {
return null;
}
@Override
public String getTo() {
return null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\compiere\report\email\service\impl\EmptyEmailParams.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void setIncludeDeploymentsWithoutTenantId(Boolean includeDeploymentsWithoutTenantId) {
this.includeDeploymentsWithoutTenantId = includeDeploymentsWithoutTenantId;
}
@Override
protected boolean isValidSortByValue(String value) {
return VALID_SORT_BY_VALUES.contains(value);
}
@Override
protected DeploymentQuery createNewQuery(ProcessEngine engine) {
return engine.getRepositoryService().createDeploymentQuery();
}
@Override
protected void applyFilters(DeploymentQuery query) {
if (withoutSource != null && withoutSource && source != null) {
throw new InvalidRequestException(Status.BAD_REQUEST, "The query parameters \"withoutSource\" and \"source\" cannot be used in combination.");
}
if (id != null) {
query.deploymentId(id);
}
if (name != null) {
query.deploymentName(name);
}
if (nameLike != null) {
query.deploymentNameLike(nameLike);
}
if (TRUE.equals(withoutSource)) {
query.deploymentSource(null);
}
if (source != null) {
query.deploymentSource(source);
}
if (before != null) { | query.deploymentBefore(before);
}
if (after != null) {
query.deploymentAfter(after);
}
if (tenantIds != null && !tenantIds.isEmpty()) {
query.tenantIdIn(tenantIds.toArray(new String[tenantIds.size()]));
}
if (TRUE.equals(withoutTenantId)) {
query.withoutTenantId();
}
if (TRUE.equals(includeDeploymentsWithoutTenantId)) {
query.includeDeploymentsWithoutTenantId();
}
}
@Override
protected void applySortBy(DeploymentQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) {
if (sortBy.equals(SORT_BY_ID_VALUE)) {
query.orderByDeploymentId();
} else if (sortBy.equals(SORT_BY_NAME_VALUE)) {
query.orderByDeploymentName();
} else if (sortBy.equals(SORT_BY_DEPLOYMENT_TIME_VALUE)) {
query.orderByDeploymentTime();
} 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\repository\DeploymentQueryDto.java | 2 |
请完成以下Java代码 | public int getPlanningHorizon()
{
return get_ValueAsInt(COLUMNNAME_PlanningHorizon);
}
@Override
public void setQueuingTime (final @Nullable BigDecimal QueuingTime)
{
set_Value (COLUMNNAME_QueuingTime, QueuingTime);
}
@Override
public BigDecimal getQueuingTime()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QueuingTime);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setS_Resource_ID (final int S_Resource_ID)
{
if (S_Resource_ID < 1)
set_ValueNoCheck (COLUMNNAME_S_Resource_ID, null);
else
set_ValueNoCheck (COLUMNNAME_S_Resource_ID, S_Resource_ID);
}
@Override
public int getS_Resource_ID()
{
return get_ValueAsInt(COLUMNNAME_S_Resource_ID);
}
@Override
public org.compiere.model.I_S_ResourceType getS_ResourceType()
{
return get_ValueAsPO(COLUMNNAME_S_ResourceType_ID, org.compiere.model.I_S_ResourceType.class);
}
@Override
public void setS_ResourceType(final org.compiere.model.I_S_ResourceType S_ResourceType)
{
set_ValueFromPO(COLUMNNAME_S_ResourceType_ID, org.compiere.model.I_S_ResourceType.class, S_ResourceType);
}
@Override
public void setS_ResourceType_ID (final int S_ResourceType_ID)
{
if (S_ResourceType_ID < 1)
set_Value (COLUMNNAME_S_ResourceType_ID, null);
else
set_Value (COLUMNNAME_S_ResourceType_ID, S_ResourceType_ID);
}
@Override
public int getS_ResourceType_ID() | {
return get_ValueAsInt(COLUMNNAME_S_ResourceType_ID);
}
@Override
public void setValue (final java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
@Override
public void setWaitingTime (final @Nullable BigDecimal WaitingTime)
{
set_Value (COLUMNNAME_WaitingTime, WaitingTime);
}
@Override
public BigDecimal getWaitingTime()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_WaitingTime);
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_S_Resource.java | 1 |
请完成以下Java代码 | public int size() {
return getView(modelElement).size();
}
public boolean add(T e) {
if(!isMutable) {
throw new UnsupportedModelOperationException("add()", "collection is immutable");
}
performAddOperation(modelElement, e);
return true;
}
public boolean addAll(Collection<? extends T> c) {
if(!isMutable) {
throw new UnsupportedModelOperationException("addAll()", "collection is immutable");
}
boolean result = false;
for (T t : c) {
result |= add(t);
}
return result;
}
public void clear() {
if(!isMutable) {
throw new UnsupportedModelOperationException("clear()", "collection is immutable");
}
Collection<DomElement> view = getView(modelElement);
performClearOperation(modelElement, view); | }
public boolean remove(Object e) {
if(!isMutable) {
throw new UnsupportedModelOperationException("remove()", "collection is immutable");
}
ModelUtil.ensureInstanceOf(e, ModelElementInstanceImpl.class);
return performRemoveOperation(modelElement, e);
}
public boolean removeAll(Collection<?> c) {
if(!isMutable) {
throw new UnsupportedModelOperationException("removeAll()", "collection is immutable");
}
boolean result = false;
for (Object t : c) {
result |= remove(t);
}
return result;
}
public boolean retainAll(Collection<?> c) {
throw new UnsupportedModelOperationException("retainAll()", "not implemented");
}
};
}
} | repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\type\child\ChildElementCollectionImpl.java | 1 |
请完成以下Java代码 | public DataFetcherResult<User> getMe(
@RequestHeader(value = "Authorization") String authorization,
DataFetchingEnvironment dataFetchingEnvironment) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication instanceof AnonymousAuthenticationToken
|| authentication.getPrincipal() == null) {
return null;
}
io.spring.core.user.User user = (io.spring.core.user.User) authentication.getPrincipal();
UserData userData =
userQueryService.findById(user.getId()).orElseThrow(ResourceNotFoundException::new);
UserWithToken userWithToken = new UserWithToken(userData, authorization.split(" ")[1]);
User result =
User.newBuilder()
.email(userWithToken.getEmail())
.username(userWithToken.getUsername())
.token(userWithToken.getToken())
.build(); | return DataFetcherResult.<User>newResult().data(result).localContext(user).build();
}
@DgsData(parentType = USERPAYLOAD.TYPE_NAME, field = USERPAYLOAD.User)
public DataFetcherResult<User> getUserPayloadUser(
DataFetchingEnvironment dataFetchingEnvironment) {
io.spring.core.user.User user = dataFetchingEnvironment.getLocalContext();
User result =
User.newBuilder()
.email(user.getEmail())
.username(user.getUsername())
.token(jwtService.toToken(user))
.build();
return DataFetcherResult.<User>newResult().data(result).localContext(user).build();
}
} | repos\spring-boot-realworld-example-app-master\src\main\java\io\spring\graphql\MeDatafetcher.java | 1 |
请完成以下Java代码 | public SourceRecordsKey toSourceRecordsKey()
{
return SourceRecordsKey.of(tableName);
}
/** Needed to identify the proper implementor(s) of this interface for a given {@link RelatedRecordsProvider}'s result. */
public static RecordsToHandleKey ofSourceRecordsKey(@NonNull final SourceRecordsKey key)
{
return RecordsToHandleKey.of(key.getTableName());
}
}
static ITranslatableString createInvalidDocStatusErrorMessage(
@NonNull final OrderId orderId,
@NonNull final String documentTrlValue,
@NonNull final String documentNo,
@NonNull final DocStatus docStatus) | {
final I_C_Order orderRecord = Services.get(IOrderDAO.class).getById(orderId, I_C_Order.class);
final ADReferenceService adReferenceService = ADReferenceService.get();
final String docStatusTrl = adReferenceService.retrieveListNameTrl(DocStatus.AD_REFERENCE_ID, docStatus.getCode());
final IMsgBL msgBL = Services.get(IMsgBL.class);
return msgBL.getTranslatableMsgText(
Msg_OrderDocumentCancelNotAllowed_4P,
orderRecord.getDocumentNo(),
msgBL.translate(Env.getCtx(), documentTrlValue),
documentNo,
docStatusTrl);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\voidorderandrelateddocs\VoidOrderAndRelatedDocsHandler.java | 1 |
请完成以下Java代码 | public void markReqCreatedIfNeeded()
{
if (purchaseMatchesOrExceedsRequiredQty())
{
purchaseCandidate.setReqCreated(true);
}
}
@Nullable
public BigDecimal getPrice()
{
return purchaseCandidate.getPriceEnteredEff();
}
@Nullable
public UomId getPriceUomId()
{
return purchaseCandidate.getPriceUomId();
}
@Nullable
public Percent getDiscount()
{
return purchaseCandidate.getDiscountEff();
}
@Nullable
public String getExternalPurchaseOrderUrl()
{
return purchaseCandidate.getExternalPurchaseOrderUrl();
} | @Nullable
public ExternalId getExternalHeaderId()
{
return purchaseCandidate.getExternalHeaderId();
}
@Nullable
public ExternalSystemId getExternalSystemId()
{
return purchaseCandidate.getExternalSystemId();
}
@Nullable
public ExternalId getExternalLineId()
{
return purchaseCandidate.getExternalLineId();
}
@Nullable
public String getPOReference()
{
return purchaseCandidate.getPOReference();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\purchaseordercreation\remotepurchaseitem\PurchaseOrderItem.java | 1 |
请完成以下Java代码 | public String getSql()
{
buildSql();
return sqlWhereClause;
}
@Override
public List<Object> getSqlParams(final Properties ctx)
{
return getSqlParams();
}
public List<Object> getSqlParams()
{
buildSql();
return sqlParams;
}
private boolean sqlBuilt = false;
private String sqlWhereClause = null;
private List<Object> sqlParams = null;
private void buildSql()
{
if (sqlBuilt)
{
return;
} | final StringBuilder sqlWhereClause = new StringBuilder();
final List<Object> sqlParams;
final String sqlColumnNames = modifier.getColumnSql("COALESCE(" + String.join(",", columnNames) + ")");
sqlWhereClause.append(sqlColumnNames);
if (value == null)
{
sqlWhereClause.append(" IS NULL");
sqlParams = null;
}
else
{
sqlParams = new ArrayList<>();
sqlWhereClause.append("=").append(modifier.getValueSql(value, sqlParams));
}
this.sqlWhereClause = sqlWhereClause.toString();
this.sqlParams = sqlParams != null && !sqlParams.isEmpty() ? Collections.unmodifiableList(sqlParams) : ImmutableList.of();
this.sqlBuilt = true;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\CoalesceEqualsQueryFilter.java | 1 |
请完成以下Java代码 | public void invalidateAll()
{
// nothing
}
@Override
public void patchRow(
final RowEditingContext ctx,
final List<JSONDocumentChangedEvent> fieldChangeRequests)
{
final ShipmentCandidateRowUserChangeRequest userChanges = toUserChangeRequest(fieldChangeRequests);
changeRow(ctx.getRowId(), row -> row.withChanges(userChanges));
}
private static ShipmentCandidateRowUserChangeRequest toUserChangeRequest(@NonNull final List<JSONDocumentChangedEvent> fieldChangeRequests)
{
Check.assumeNotEmpty(fieldChangeRequests, "fieldChangeRequests is not empty");
final ShipmentCandidateRowUserChangeRequestBuilder builder = ShipmentCandidateRowUserChangeRequest.builder();
for (final JSONDocumentChangedEvent fieldChangeRequest : fieldChangeRequests)
{
final String fieldName = fieldChangeRequest.getPath();
if (ShipmentCandidateRow.FIELD_qtyToDeliverUserEntered.equals(fieldName))
{
builder.qtyToDeliverUserEntered(fieldChangeRequest.getValueAsBigDecimal());
}
else if (ShipmentCandidateRow.FIELD_qtyToDeliverCatchOverride.equals(fieldName))
{
builder.qtyToDeliverCatchOverride(fieldChangeRequest.getValueAsBigDecimal());
}
else if (ShipmentCandidateRow.FIELD_asi.equals(fieldName))
{
builder.asi(fieldChangeRequest.getValueAsIntegerLookupValue());
}
}
return builder.build();
}
private void changeRow(
@NonNull final DocumentId rowId,
@NonNull final UnaryOperator<ShipmentCandidateRow> mapper)
{
if (!rowIds.contains(rowId))
{
throw new EntityNotFoundException(rowId.toJson());
} | rowsById.compute(rowId, (key, oldRow) -> {
if (oldRow == null)
{
throw new EntityNotFoundException(rowId.toJson());
}
return mapper.apply(oldRow);
});
}
Optional<ShipmentScheduleUserChangeRequestsList> createShipmentScheduleUserChangeRequestsList()
{
final ImmutableList<ShipmentScheduleUserChangeRequest> userChanges = rowsById.values()
.stream()
.map(row -> row.createShipmentScheduleUserChangeRequest().orElse(null))
.filter(Objects::nonNull)
.collect(ImmutableList.toImmutableList());
return !userChanges.isEmpty()
? Optional.of(ShipmentScheduleUserChangeRequestsList.of(userChanges))
: Optional.empty();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\shipment_candidates_editor\ShipmentCandidateRows.java | 1 |
请完成以下Java代码 | protected void validateParams(String userId, String groupId, String type, String taskId) {
if (taskId == null) {
throw new ActivitiIllegalArgumentException("taskId is null");
}
if (type == null) {
throw new ActivitiIllegalArgumentException("type is required when adding a new task identity link");
}
// Special treatment for assignee and owner: group cannot be used and
// userId may be null
if (IdentityLinkType.ASSIGNEE.equals(type) || IdentityLinkType.OWNER.equals(type)) {
if (groupId != null) {
throw new ActivitiIllegalArgumentException(
"Incompatible usage: cannot use type '" + type + "' together with a groupId"
);
}
} else {
if (userId == null && groupId == null) {
throw new ActivitiIllegalArgumentException("userId and groupId cannot both be null");
} | }
}
protected Void execute(CommandContext commandContext, TaskEntity task) {
if (IdentityLinkType.ASSIGNEE.equals(type)) {
commandContext.getTaskEntityManager().changeTaskAssignee(task, null);
} else if (IdentityLinkType.OWNER.equals(type)) {
commandContext.getTaskEntityManager().changeTaskOwner(task, null);
} else {
commandContext.getIdentityLinkEntityManager().deleteIdentityLink(task, userId, groupId, type);
}
commandContext.getHistoryManager().createIdentityLinkComment(taskId, userId, groupId, type, false);
return null;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\DeleteIdentityLinkCmd.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setPhone(String phone) {
this.phone = phone;
}
public String getPostCode() {
return postCode;
}
public void setPostCode(String postCode) {
this.postCode = postCode;
}
public String getUserId() {
return userId;
} | public void setUserId(String userId) {
this.userId = userId;
}
@Override
public String toString() {
return "LocationEntity{" +
"id='" + id + '\'' +
", location='" + location + '\'' +
", name='" + name + '\'' +
", phone='" + phone + '\'' +
", postCode='" + postCode + '\'' +
", userId='" + userId + '\'' +
'}';
}
} | repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\entity\user\LocationEntity.java | 2 |
请完成以下Java代码 | protected BatchElementConfiguration collectProcessInstanceIds(CommandContext commandContext) {
BatchElementConfiguration elementConfiguration = new BatchElementConfiguration();
if (!CollectionUtil.isEmpty(processInstanceIds)) {
ProcessInstanceQueryImpl query = new ProcessInstanceQueryImpl();
query.processInstanceIds(new HashSet<>(processInstanceIds));
List<ImmutablePair<String, String>> mappings =
commandContext.runWithoutAuthorization(query::listDeploymentIdMappings);
elementConfiguration.addDeploymentMappings(mappings);
}
ProcessInstanceQueryImpl processInstanceQuery =
(ProcessInstanceQueryImpl) this.processInstanceQuery;
if (processInstanceQuery != null) {
List<ImmutablePair<String, String>> mappings =
processInstanceQuery.listDeploymentIdMappings(); | elementConfiguration.addDeploymentMappings(mappings);
}
HistoricProcessInstanceQueryImpl historicProcessInstanceQuery =
(HistoricProcessInstanceQueryImpl) this.historicProcessInstanceQuery;
if (historicProcessInstanceQuery != null) {
historicProcessInstanceQuery.unfinished();
List<ImmutablePair<String, String>> mappings =
historicProcessInstanceQuery.listDeploymentIdMappings();
elementConfiguration.addDeploymentMappings(mappings);
}
return elementConfiguration;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\batch\variables\SetVariablesToProcessInstancesBatchCmd.java | 1 |
请完成以下Java代码 | public String getCompletedBy() {
return completedBy;
}
@Override
public void setCompletedBy(String completedBy) {
this.completedBy = completedBy;
}
@Override
public String getTaskId() {
return taskId;
}
@Override
public void setTaskId(String taskId) {
this.taskId = taskId;
}
@Override
public String getCalledProcessInstanceId() {
return calledProcessInstanceId;
}
@Override
public void setCalledProcessInstanceId(String calledProcessInstanceId) {
this.calledProcessInstanceId = calledProcessInstanceId;
}
@Override
public String getTenantId() {
return tenantId;
} | @Override
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
public Date getTime() {
return getStartTime();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("ActivityInstanceEntity[id=").append(id)
.append(", activityId=").append(activityId);
if (activityName != null) {
sb.append(", activityName=").append(activityName);
}
sb.append(", executionId=").append(executionId)
.append(", definitionId=").append(processDefinitionId);
if (StringUtils.isNotEmpty(tenantId)) {
sb.append(", tenantId=").append(tenantId);
}
sb.append("]");
return sb.toString();
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\ActivityInstanceEntityImpl.java | 1 |
请完成以下Java代码 | public void setLastname (final @Nullable java.lang.String Lastname)
{
set_Value (COLUMNNAME_Lastname, Lastname);
}
@Override
public java.lang.String getLastname()
{
return get_ValueAsString(COLUMNNAME_Lastname);
}
@Override
public void setName (final @Nullable java.lang.String Name)
{
set_ValueNoCheck (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);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_Adv_Search.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public long findHistoricTaskInstanceCountByNativeQuery(Map<String, Object> parameterMap) {
return dataManager.findHistoricTaskInstanceCountByNativeQuery(parameterMap);
}
@Override
public void deleteHistoricTaskInstances(HistoricTaskInstanceQueryImpl historicTaskInstanceQuery) {
dataManager.deleteHistoricTaskInstances(historicTaskInstanceQuery);
}
@Override
public void bulkDeleteHistoricTaskInstancesForIds(Collection<String> taskIds) {
dataManager.bulkDeleteHistoricTaskInstancesForIds(taskIds);
}
@Override
public void deleteHistoricTaskInstancesForNonExistingProcessInstances() {
dataManager.deleteHistoricTaskInstancesForNonExistingProcessInstances(); | }
@Override
public void deleteHistoricTaskInstancesForNonExistingCaseInstances() {
dataManager.deleteHistoricTaskInstancesForNonExistingCaseInstances();
}
public HistoricTaskInstanceDataManager getHistoricTaskInstanceDataManager() {
return dataManager;
}
public void setHistoricTaskInstanceDataManager(HistoricTaskInstanceDataManager historicTaskInstanceDataManager) {
this.dataManager = historicTaskInstanceDataManager;
}
} | repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\persistence\entity\HistoricTaskInstanceEntityManagerImpl.java | 2 |
请完成以下Java代码 | private Quantity toZeroOrNull(@Nullable final Quantity weightNet)
{
return weightNet != null ? weightNet.toZero() : null;
}
/**
* Iterates all child-HUs' storage quantities for the given productId and returns the median (or something close).
* Goal: return a reasonably common quantity, and ignore possible outliers.
* <p>
* If this HU has no children, then return this HU's quantity!
*/
public Quantity extractMedianCUQtyPerChildHU(@NonNull final ProductId productId)
{
if (getChildHUs().isEmpty())
{
return getProductQtysInStockUOM().get(productId);
}
final ImmutableList<BigDecimal> allQuantities = this.getChildHUs()
.stream()
.filter(hu -> hu.getProductQtysInStockUOM().containsKey(productId))
.map(hu -> hu.getProductQtysInStockUOM().get(productId).toBigDecimal())
.sorted()
.collect(ImmutableList.toImmutableList()); | final BigDecimal qtyCU = allQuantities.get(allQuantities.size() / 2);
return Quantitys.of(qtyCU, productId);
}
@Nullable
public String getPackagingGTIN(@NonNull final BPartnerId bpartnerId)
{
final String gtin = packagingGTINs.get(bpartnerId);
if (Check.isNotBlank(gtin))
{
return gtin;
}
return packagingGTINs.get(BPartnerId.NONE);
}
@VisibleForTesting
public ImmutableMap<BPartnerId, String> getAllPackaginGTINs()
{
return ImmutableMap.copyOf(packagingGTINs);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\generichumodel\HU.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private DDOrderMoveSchedule createNewSchedule(final DistributionJobLine line, final HuId huId)
{
final IHUProductStorage huStorage = huService.getSingleHUProductStorage(huId);
if (!ProductId.equals(huStorage.getProductId(), line.getProductId()))
{
throw new AdempiereException("Product not matching")
.setParameter("line", line)
.setParameter("huStorage", huStorage);
}
return ddOrderMoveScheduleService.createScheduleToMove(
DDOrderMoveScheduleCreateRequest.builder()
.ddOrderId(changedJob.getDdOrderId())
.ddOrderLineId(line.getDDOrderLineId())
.productId(line.getProductId())
.pickFromLocatorId(line.getPickFromLocatorId())
.pickFromHUId(huStorage.getHuId())
.qtyToPick(huStorage.getQty())
.isPickWholeHU(true)
.dropToLocatorId(line.getDropToLocatorId())
.build()
);
}
@NonNull
private HuId getHuIdToPick(@NonNull final DistributionJobLine line)
{
if (_huIdToPick == null)
{
_huIdToPick = resolveHuIdToPick(line);
}
return _huIdToPick;
}
@NonNull
private HuId resolveHuIdToPick(@NonNull final DistributionJobLine line)
{
final JsonDistributionEvent.PickFrom pickFrom = Check.assumeNotNull(this.pickFrom, "pickFrom must be set");
final ScannedCode pickFromScannedCode = ScannedCode.ofString(Check.assumeNotNull(pickFrom.getQrCode(), "pickFrom.qrCode must be set"));
final HuId sourceHuId = huService.resolveHUId(pickFromScannedCode);
final Quantity sourceHUQty = huService.getProductQuantity(sourceHuId, line.getProductId());
final Quantity qtyToPick = pickFrom.getQtyPicked(line.getUOM()).orElse(null);
if (qtyToPick == null)
{
// no qty to pick specified by user => pick the whole HU
return sourceHuId;
}
else if (qtyToPick.compareTo(sourceHUQty) > 0)
{
throw new AdempiereException(NOT_ENOUGH_QTY, sourceHUQty);
}
else if (qtyToPick.compareTo(sourceHUQty) == 0)
{
// scanned HU has exactly the required qty | return sourceHuId;
}
else
{
return splitQty(line, sourceHuId, qtyToPick);
}
}
@NonNull
private HuId splitQty(
@NonNull final DistributionJobLine line,
@NonNull final HuId pickFromVHUId,
@NonNull final Quantity qty)
{
final PackToHUsProducer.PackToInfo packToInfo = packToHUsProducer.extractPackToInfo(PackToSpec.VIRTUAL, line.getPickFromLocatorId())
.withPackForShipping(false);
final I_M_HU splitHU = packToHUsProducer.packToHU(
PackToHUsProducer.PackToHURequest.builder()
.huContext(HUContextHolder.getCurrent())
.pickFromHUId(pickFromVHUId)
.packToInfo(packToInfo)
.productId(line.getProductId())
.qtyPicked(qty)
.documentRef(line.getDDOrderLineId().toTableRecordReference())
.checkIfAlreadyPacked(true)
.build()).getSingleTopLevelTURecord();
return HuId.ofRepoId(splitHU.getM_HU_ID());
}
private Optional<LocatorId> getInTransitLocatorId()
{
return warehouseService.getTrolleyByUserId(userId).map(LocatorQRCode::getLocatorId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\job\service\commands\pick_from\DistributionJobPickFromCommand.java | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.