instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public IHandlingUnitsInfo getHandlingUnitsInfo()
{
return handlingUnitsInfo;
}
public void setHandlingUnitsInfo(final IHandlingUnitsInfo handlingUnitsInfo)
{
this.handlingUnitsInfo = handlingUnitsInfo;
}
/**
* This method does nothing!
*/
@Override
public void add(final Object IGNORED)
{
}
/**
* This method returns the empty list.
*/ | @Override
public List<Object> getModels()
{
return Collections.emptyList();
}
@Override public I_M_PriceList_Version getPLV()
{
return plv;
}
public void setPlv(I_M_PriceList_Version plv)
{
this.plv = plv;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\PlainVendorReceipt.java | 1 |
请完成以下Java代码 | public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Max. Wert.
@param ValueMax
Maximum Value for a field
*/
@Override
public void setValueMax (java.lang.String ValueMax)
{
set_Value (COLUMNNAME_ValueMax, ValueMax);
}
/** Get Max. Wert.
@return Maximum Value for a field
*/
@Override
public java.lang.String getValueMax ()
{
return (java.lang.String)get_Value(COLUMNNAME_ValueMax);
}
/** Set Min. Wert.
@param ValueMin
Minimum Value for a field
*/
@Override
public void setValueMin (java.lang.String ValueMin)
{
set_Value (COLUMNNAME_ValueMin, ValueMin);
}
/** Get Min. Wert.
@return Minimum Value for a field
*/ | @Override
public java.lang.String getValueMin ()
{
return (java.lang.String)get_Value(COLUMNNAME_ValueMin);
}
/** Set Value Format.
@param VFormat
Format of the value; Can contain fixed format elements, Variables: "_lLoOaAcCa09"
*/
@Override
public void setVFormat (java.lang.String VFormat)
{
set_Value (COLUMNNAME_VFormat, VFormat);
}
/** Get Value Format.
@return Format of the value; Can contain fixed format elements, Variables: "_lLoOaAcCa09"
*/
@Override
public java.lang.String getVFormat ()
{
return (java.lang.String)get_Value(COLUMNNAME_VFormat);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Process_Para.java | 1 |
请完成以下Java代码 | public final void initialize(final IModelValidationEngine engine, final I_AD_Client client)
{
adClientId = client == null ? -1 : client.getAD_Client_ID();
onInit(engine, client);
}
/**
* Called when interceptor is registered and needs to be initialized
*/
protected abstract void onInit(final IModelValidationEngine engine, final I_AD_Client client);
@Override
public final int getAD_Client_ID()
{
return adClientId;
}
// NOTE: method signature shall be the same as org.adempiere.ad.security.IUserLoginListener.onUserLogin(int, int, int)
@Override
public void onUserLogin(final int AD_Org_ID, final int AD_Role_ID, final int AD_User_ID)
{
// nothing
}
@Override
public void beforeLogout(final MFSession session)
{ | // nothing
}
@Override
public void afterLogout(final MFSession session)
{
// nothing
}
@Override
public void onModelChange(final Object model, final ModelChangeType changeType) throws Exception
{
// nothing
}
@Override
public void onDocValidate(final Object model, final DocTimingType timing) throws Exception
{
// nothing
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\modelvalidator\AbstractModelInterceptor.java | 1 |
请完成以下Java代码 | public void updateIncomingReferences(ModelElementInstance modelElement, String newIdentifier, String oldIdentifier) {
if (!incomingReferences.isEmpty()) {
for (Reference<?> incomingReference : incomingReferences) {
((ReferenceImpl<?>) incomingReference).referencedElementUpdated(modelElement, oldIdentifier, newIdentifier);
}
}
}
public T getDefaultValue() {
return defaultValue;
}
public void setDefaultValue(T defaultValue) {
this.defaultValue = defaultValue;
}
public boolean isRequired() {
return isRequired;
}
/**
*/
public void setRequired(boolean required) {
this.isRequired = required;
}
/**
* @param namespaceUri the namespaceUri to set
*/
public void setNamespaceUri(String namespaceUri) {
this.namespaceUri = namespaceUri;
}
/**
* @return the namespaceUri
*/
public String getNamespaceUri() {
return namespaceUri;
}
public boolean isIdAttribute() {
return isIdAttribute;
}
/**
* Indicate whether this attribute is an Id attribute
*
*/
public void setId() {
this.isIdAttribute = true;
}
/**
* @return the attributeName
*/
public String getAttributeName() {
return attributeName;
} | /**
* @param attributeName the attributeName to set
*/
public void setAttributeName(String attributeName) {
this.attributeName = attributeName;
}
public void removeAttribute(ModelElementInstance modelElement) {
if (namespaceUri == null) {
modelElement.removeAttribute(attributeName);
}
else {
modelElement.removeAttributeNs(namespaceUri, attributeName);
}
}
public void unlinkReference(ModelElementInstance modelElement, Object referenceIdentifier) {
if (!incomingReferences.isEmpty()) {
for (Reference<?> incomingReference : incomingReferences) {
((ReferenceImpl<?>) incomingReference).referencedElementRemoved(modelElement, referenceIdentifier);
}
}
}
/**
* @return the incomingReferences
*/
public List<Reference<?>> getIncomingReferences() {
return incomingReferences;
}
/**
* @return the outgoingReferences
*/
public List<Reference<?>> getOutgoingReferences() {
return outgoingReferences;
}
public void registerOutgoingReference(Reference<?> ref) {
outgoingReferences.add(ref);
}
public void registerIncoming(Reference<?> ref) {
incomingReferences.add(ref);
}
} | repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\type\attribute\AttributeImpl.java | 1 |
请完成以下Java代码 | public void setAuthorities(List<GrantedAuthority> authorities) {
this.authorities = authorities;
}
/**
* Set all authorities for this user from String values. It will create the necessary
* {@link GrantedAuthority} objects.
* @param authoritiesAsStrings {@link List} <{@link String}>
* @since 1.1
*/
public void setAuthoritiesAsString(List<String> authoritiesAsStrings) {
setAuthorities(new ArrayList<>(authoritiesAsStrings.size()));
for (String authority : authoritiesAsStrings) {
addAuthority(new SimpleGrantedAuthority(authority));
}
}
public @Nullable String getPassword() {
return this.password;
}
public boolean isEnabled() {
return this.enabled; | }
public boolean isValid() {
return (this.password != null) && (this.authorities.size() > 0);
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public void setPassword(String password) {
this.password = password;
}
} | repos\spring-security-main\core\src\main\java\org\springframework\security\core\userdetails\memory\UserAttribute.java | 1 |
请完成以下Java代码 | public String toString() {
StringBuilder result = new StringBuilder(this.name);
if (this.description != null) {
result.append(" (").append(this.description).append(")");
}
result.append(":").append(this.type);
return result.toString();
}
}
/**
* Utility to convert to JMX supported types.
*/
private static final class JmxType {
static Class<?> get(Class<?> source) {
if (source.isEnum()) {
return String.class; | }
if (Date.class.isAssignableFrom(source) || Instant.class.isAssignableFrom(source)) {
return String.class;
}
if (source.getName().startsWith("java.")) {
return source;
}
if (source.equals(Void.TYPE)) {
return source;
}
return Object.class;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\endpoint\jmx\annotation\DiscoveredJmxOperation.java | 1 |
请完成以下Java代码 | private OrgId getPaymentOrgId(@Nullable final I_C_Payment payment)
{
return payment != null
? OrgId.ofRepoId(payment.getAD_Org_ID())
: super.getOrgId();
}
/**
* @return <ul>
* <li>true if this line is an inbound transaction (i.e. we received money in our bank account)
* <li>false if this line is an outbound transaction (i.e. we paid money from our bank account)
* </ul>
*/
public boolean isInboundTrx()
{
return getStmtAmt().signum() >= 0;
}
private I_C_BankStatementLine getC_BankStatementLine()
{
return getModel(I_C_BankStatementLine.class);
}
CurrencyConversionContext getCurrencyConversionCtxForBankAsset()
{
CurrencyConversionContext currencyConversionContext = this._currencyConversionContextForBankAsset;
if (currencyConversionContext == null)
{
currencyConversionContext = this._currencyConversionContextForBankAsset = createCurrencyConversionCtxForBankAsset();
}
return currencyConversionContext;
}
private CurrencyConversionContext createCurrencyConversionCtxForBankAsset()
{
final I_C_BankStatementLine line = getC_BankStatementLine();
final OrgId orgId = OrgId.ofRepoId(line.getAD_Org_ID());
// IMPORTANT for Bank Asset Account booking,
// * we shall NOT consider the fixed Currency Rate because we want to compute currency gain/loss
// * use default conversion types
return services.createCurrencyConversionContext(
LocalDateAndOrgId.ofTimestamp(line.getDateAcct(), orgId, services::getTimeZone),
null,
ClientId.ofRepoId(line.getAD_Client_ID()));
}
CurrencyConversionContext getCurrencyConversionCtxForBankInTransit()
{
CurrencyConversionContext currencyConversionContext = this._currencyConversionContextForBankInTransit; | if (currencyConversionContext == null)
{
currencyConversionContext = this._currencyConversionContextForBankInTransit = createCurrencyConversionCtxForBankInTransit();
}
return currencyConversionContext;
}
private CurrencyConversionContext createCurrencyConversionCtxForBankInTransit()
{
final I_C_Payment payment = getC_Payment();
if (payment != null)
{
return paymentBL.extractCurrencyConversionContext(payment);
}
else
{
final I_C_BankStatementLine line = getC_BankStatementLine();
final PaymentCurrencyContext paymentCurrencyContext = bankStatementBL.getPaymentCurrencyContext(line);
final OrgId orgId = OrgId.ofRepoId(line.getAD_Org_ID());
CurrencyConversionContext conversionCtx = services.createCurrencyConversionContext(
LocalDateAndOrgId.ofTimestamp(line.getDateAcct(), orgId, services::getTimeZone),
paymentCurrencyContext.getCurrencyConversionTypeId(),
ClientId.ofRepoId(line.getAD_Client_ID()));
final FixedConversionRate fixedCurrencyRate = paymentCurrencyContext.toFixedConversionRateOrNull();
if (fixedCurrencyRate != null)
{
conversionCtx = conversionCtx.withFixedConversionRate(fixedCurrencyRate);
}
return conversionCtx;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-legacy\org\compiere\acct\DocLine_BankStatement.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected void initProcessInstanceStateChangedCallbacks(ProcessEngineConfigurationImpl processEngineConfiguration) {
if (processEngineConfiguration.getProcessInstanceStateChangedCallbacks() == null) {
processEngineConfiguration.setProcessInstanceStateChangedCallbacks(new HashMap<>());
}
Map<String, List<RuntimeInstanceStateChangeCallback>> callbacks = processEngineConfiguration.getProcessInstanceStateChangedCallbacks();
if (!callbacks.containsKey(CallbackTypes.PLAN_ITEM_CHILD_PROCESS)) {
callbacks.put(CallbackTypes.PLAN_ITEM_CHILD_PROCESS, new ArrayList<>());
}
callbacks.get(CallbackTypes.PLAN_ITEM_CHILD_PROCESS).add(new ChildProcessInstanceStateChangeCallback(cmmnEngineConfiguration));
}
@Override
protected List<Class<? extends Entity>> getEntityInsertionOrder() {
return EntityDependencyOrder.INSERT_ORDER;
}
@Override
protected List<Class<? extends Entity>> getEntityDeletionOrder() {
return EntityDependencyOrder.DELETE_ORDER;
}
@Override | protected CmmnEngine buildEngine() {
if (cmmnEngineConfiguration == null) {
throw new FlowableException("CmmnEngineConfiguration is required");
}
return cmmnEngineConfiguration.buildCmmnEngine();
}
public CmmnEngineConfiguration getCmmnEngineConfiguration() {
return cmmnEngineConfiguration;
}
public CmmnEngineConfigurator setCmmnEngineConfiguration(CmmnEngineConfiguration cmmnEngineConfiguration) {
this.cmmnEngineConfiguration = cmmnEngineConfiguration;
return this;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine-configurator\src\main\java\org\flowable\cmmn\engine\configurator\CmmnEngineConfigurator.java | 2 |
请完成以下Java代码 | public void setInternalName (java.lang.String InternalName)
{
set_ValueNoCheck (COLUMNNAME_InternalName, InternalName);
}
/** Get Interner Name.
@return Generally used to give records a name that can be safely referenced from code.
*/
@Override
public java.lang.String getInternalName ()
{
return (java.lang.String)get_Value(COLUMNNAME_InternalName);
}
/** Set Name. | @param Name Name */
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Name */
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.dimension\src\main\java-gen\de\metas\dimension\model\X_DIM_Dimension_Type.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public EventDeploymentBuilder addChannelDefinition(String resourceName, String channelDefinition) {
addString(resourceName, channelDefinition);
return this;
}
@Override
public EventDeploymentBuilder name(String name) {
deployment.setName(name);
return this;
}
@Override
public EventDeploymentBuilder category(String category) {
deployment.setCategory(category);
return this;
}
@Override
public EventDeploymentBuilder tenantId(String tenantId) {
deployment.setTenantId(tenantId);
return this;
}
@Override
public EventDeploymentBuilder parentDeploymentId(String parentDeploymentId) {
deployment.setParentDeploymentId(parentDeploymentId);
return this;
}
@Override
public EventDeploymentBuilder enableDuplicateFiltering() {
this.isDuplicateFilterEnabled = true; | return this;
}
@Override
public EventDeployment deploy() {
return repositoryService.deploy(this);
}
// getters and setters
// //////////////////////////////////////////////////////
public EventDeploymentEntity getDeployment() {
return deployment;
}
public boolean isDuplicateFilterEnabled() {
return isDuplicateFilterEnabled;
}
} | repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\repository\EventDeploymentBuilderImpl.java | 2 |
请完成以下Java代码 | public class ProcessDefinitionMetaImpl implements ProcessDefinitionMeta {
private String processDefinitionKey;
private List<String> usersIds;
private List<String> groupIds;
private List<String> connectorsIds;
public ProcessDefinitionMetaImpl() {}
public ProcessDefinitionMetaImpl(String processDefinitionKey) {
this.processDefinitionKey = processDefinitionKey;
}
@Override
public String getProcessDefinitionKey() {
return processDefinitionKey;
}
public void setProcessDefinitionKey(String processDefinitionKey) {
this.processDefinitionKey = processDefinitionKey;
}
public List<String> getUsersIds() {
return usersIds;
}
public void setUsersIds(List<String> usersIds) {
this.usersIds = usersIds; | }
public List<String> getGroupIds() {
return groupIds;
}
public void setGroupIds(List<String> groupIds) {
this.groupIds = groupIds;
}
public List<String> getConnectorsIds() {
return connectorsIds;
}
public void setConnectorsIds(List<String> connectorsIds) {
this.connectorsIds = connectorsIds;
}
} | repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-model-impl\src\main\java\org\activiti\api\runtime\model\impl\ProcessDefinitionMetaImpl.java | 1 |
请完成以下Java代码 | public static File getPDFAsFile(String filename, Pageable pageable)
{
final File result = new File(filename);
try
{
writePDF(pageable, new FileOutputStream(result));
}
catch (Exception e)
{
e.printStackTrace();
}
return result;
}
public static byte[] getPDFAsArray(Pageable pageable)
{
try
{
ByteArrayOutputStream output = new ByteArrayOutputStream(10240);
writePDF(pageable, output);
return output.toByteArray();
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
public static PDFViewerBean getViewer()
{
return new PDFViewerBean();
}
public static boolean isValid(Pageable layout)
{
return true;
}
public static boolean isLicensed()
{
return true;
}
/**
* Converts given image to PDF.
*
* @param image
* @return PDF file as bytes array.
*/
public static byte[] toPDFBytes(final BufferedImage image)
{
try
{
// | // PDF Image
final ByteArrayOutputStream imageBytes = new ByteArrayOutputStream();
ImageIO.write(image, "PNG", imageBytes);
final Image pdfImage = Image.getInstance(imageBytes.toByteArray());
//
// PDF page size: image size + margins
final com.itextpdf.text.Rectangle pageSize = new com.itextpdf.text.Rectangle(0, 0,
(int)(pdfImage.getWidth() + 100),
(int)(pdfImage.getHeight() + 100));
// PDF document
final com.itextpdf.text.Document document = new com.itextpdf.text.Document(pageSize, 50, 50, 50, 50);
//
// Add image to document
final ByteArrayOutputStream pdfBytes = new ByteArrayOutputStream();
final PdfWriter writer = PdfWriter.getInstance(document, pdfBytes);
writer.open();
document.open();
document.add(pdfImage);
document.close();
writer.close();
return pdfBytes.toByteArray();
}
catch (final Exception e)
{
throw new AdempiereException("Failed converting the image to PDF", e);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\pdf\Document.java | 1 |
请完成以下Java代码 | public TableMetaData getTableMetaData(String tableName) {
return commandExecutor.execute(new GetTableMetaDataCmd(tableName));
}
@Override
public void executeJob(String jobId) {
commandExecutor.execute(new ExecuteJobsCmd(jobId));
}
@Override
public void deleteJob(String jobId) {
commandExecutor.execute(new CancelJobCmd(jobId));
}
@Override
public void setJobRetries(String jobId, int retries) {
commandExecutor.execute(new SetJobRetriesCmd(jobId, retries));
}
@Override
public TablePageQuery createTablePageQuery() {
return new TablePageQueryImpl(commandExecutor);
}
@Override
public JobQuery createJobQuery() {
return new JobQueryImpl(commandExecutor);
}
@Override
public TimerJobQuery createTimerJobQuery() {
return new TimerJobQueryImpl(commandExecutor);
}
@Override
public String getJobExceptionStacktrace(String jobId) {
return commandExecutor.execute(new GetJobExceptionStacktraceCmd(jobId));
}
@Override
public Map<String, String> getProperties() {
return commandExecutor.execute(new GetPropertiesCmd());
}
@Override
public <T> T executeCommand(Command<T> command) {
if (command == null) {
throw new ActivitiIllegalArgumentException("The command is null");
}
return commandExecutor.execute(command);
}
@Override
public <T> T executeCommand(CommandConfig config, Command<T> command) {
if (config == null) { | throw new ActivitiIllegalArgumentException("The config is null");
}
if (command == null) {
throw new ActivitiIllegalArgumentException("The command is null");
}
return commandExecutor.execute(config, command);
}
@Override
public <MapperType, ResultType> ResultType executeCustomSql(CustomSqlExecution<MapperType, ResultType> customSqlExecution) {
Class<MapperType> mapperClass = customSqlExecution.getMapperClass();
return commandExecutor.execute(new ExecuteCustomSqlCmd<>(mapperClass, customSqlExecution));
}
@Override
public List<EventLogEntry> getEventLogEntries(Long startLogNr, Long pageSize) {
return commandExecutor.execute(new GetEventLogEntriesCmd(startLogNr, pageSize));
}
@Override
public List<EventLogEntry> getEventLogEntriesByProcessInstanceId(String processInstanceId) {
return commandExecutor.execute(new GetEventLogEntriesCmd(processInstanceId));
}
@Override
public void deleteEventLogEntry(long logNr) {
commandExecutor.execute(new DeleteEventLogEntry(logNr));
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\ManagementServiceImpl.java | 1 |
请完成以下Java代码 | public static <T> ImmutableSet<T> toImmutableSetOrEmpty(@Nullable final Collection<T> collection)
{
return collection != null && !collection.isEmpty() ? ImmutableSet.copyOf(collection) : ImmutableSet.of();
}
@Builder(builderMethodName = "syncLists", builderClassName = "SyncListsBuilder", buildMethodName = "execute")
private static <T, S, K> ImmutableList<T> syncLists0(
@NonNull final Iterable<T> target,
@NonNull final Iterable<S> source,
@NonNull final Function<T, K> targetKeyExtractor,
@NonNull final Function<S, K> sourceKeyExtractor,
@NonNull final BiFunction<T, S, T> mergeFunction
)
{
final ImmutableMap<K, T> targetByKey = Maps.uniqueIndex(target, targetKeyExtractor::apply);
final ImmutableList.Builder<T> result = ImmutableList.builder();
for (final S sourceItem : source)
{
final K key = sourceKeyExtractor.apply(sourceItem);
T targetItem = targetByKey.get(key);
final T resultItem = mergeFunction.apply(targetItem, sourceItem);
result.add(resultItem);
}
return result.build();
}
public static <K, V> Map<K, V> fillMissingKeys(@NonNull final Map<K, V> map, @NonNull final Collection<K> keys, @NonNull final V defaultValue)
{
if (keys.isEmpty())
{
return map;
}
LinkedHashMap<K, V> result = null;
for (K key : keys)
{
if (!map.containsKey(key))
{
if (result == null)
{
result = new LinkedHashMap<>(map.size() + keys.size());
result.putAll(map);
}
result.put(key, defaultValue);
}
}
return result == null ? map : result;
}
public <K, V> ImmutableMap<K, V> merge(@NonNull final ImmutableMap<K, V> map, K key, V value, BinaryOperator<V> remappingFunction)
{
if (map.isEmpty()) | {
return ImmutableMap.of(key, value);
}
final ImmutableMap.Builder<K, V> mapBuilder = ImmutableMap.builder();
boolean added = false;
boolean changed = false;
for (Map.Entry<K, V> entry : map.entrySet())
{
if (!added && Objects.equals(key, entry.getKey()))
{
final V valueOld = entry.getValue();
final V valueNew = remappingFunction.apply(valueOld, value);
mapBuilder.put(key, valueNew);
added = true;
if (!Objects.equals(valueOld, valueNew))
{
changed = true;
}
}
else
{
mapBuilder.put(entry.getKey(), entry.getValue());
}
}
if (!added)
{
mapBuilder.put(key, value);
changed = true;
}
if (!changed)
{
return map;
}
return mapBuilder.build();
}
public static <T> ImmutableList<T> removeIf(@NonNull ImmutableList<T> list, @NonNull Predicate<T> predicate)
{
if (list.isEmpty()) {return list;}
final ImmutableList<T> result = list.stream()
.filter(item -> !predicate.test(item))
.collect(ImmutableList.toImmutableList());
return list.size() == result.size() ? list : result;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\collections\CollectionUtils.java | 1 |
请完成以下Java代码 | public class MProjectPhase extends X_C_ProjectPhase
{
/**
*
*/
private static final long serialVersionUID = 3445836323245259566L;
public MProjectPhase (final Properties ctx, final int C_ProjectPhase_ID, final String trxName)
{
super (ctx, C_ProjectPhase_ID, trxName);
if (C_ProjectPhase_ID == 0)
{
// setC_ProjectPhase_ID (0); // PK
// setC_Project_ID (0); // Parent
// setC_Phase_ID (0); // FK
setCommittedAmt (BigDecimal.ZERO);
setIsCommitCeiling (false);
setIsComplete (false);
setSeqNo (0);
// setName (null);
setQty (BigDecimal.ZERO);
}
} // MProjectPhase
public MProjectPhase (final Properties ctx, final ResultSet rs, final String trxName)
{
super(ctx, rs, trxName);
} // MProjectPhase
public List<I_C_ProjectTask> getTasks()
{
return Services.get(IQueryBL.class).createQueryBuilder(I_C_ProjectTask.class)
.addEqualsFilter(I_C_ProjectTask.COLUMNNAME_C_ProjectPhase_ID, getC_ProjectPhase_ID())
.orderBy(I_C_ProjectTask.COLUMNNAME_SeqNo)
.create()
.list();
}
/**
* @return number of tasks copied
*/
public int copyTasksFrom (final MProjectPhase fromPhase)
{
if (fromPhase == null)
return 0;
int count = 0;
//
final List<I_C_ProjectTask> myTasks = getTasks();
final List<I_C_ProjectTask> fromTasks = fromPhase.getTasks();
// Copy Project Tasks
for (final I_C_ProjectTask fromTask : fromTasks)
{
// Check if Task already exists
final int C_Task_ID = fromTask.getC_Task_ID(); | boolean exists = false;
if (C_Task_ID != 0)
{
for (final I_C_ProjectTask myTask : myTasks)
{
if (myTask.getC_Task_ID() == C_Task_ID)
{
exists = true;
break;
}
}
}
// Phase exist
if (exists)
log.info("Task already exists here, ignored - " + fromTask);
else
{
final I_C_ProjectTask toTask = InterfaceWrapperHelper.create(getCtx(), I_C_ProjectTask.class, get_TrxName());
PO.copyValues(
InterfaceWrapperHelper.getPO(fromTask),
InterfaceWrapperHelper.getPO(toTask),
getAD_Client_ID(),
getAD_Org_ID());
toTask.setC_ProjectPhase_ID(getC_ProjectPhase_ID());
InterfaceWrapperHelper.save(toTask);
count++;
}
}
if (fromTasks.size() != count)
log.warn("Count difference - ProjectPhase=" + fromTasks.size() + " <> Saved=" + count);
return count;
}
@Override
public String toString ()
{
return "MProjectPhase[" + get_ID()
+ "-" + getSeqNo()
+ "-" + getName()
+ "]";
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MProjectPhase.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private static final class LiquibaseUrlCondition {
}
}
static class LiquibaseAutoConfigurationRuntimeHints implements RuntimeHintsRegistrar {
@Override
public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) {
hints.resources().registerPattern("db/changelog/**");
}
}
/**
* Adapts {@link LiquibaseProperties} to {@link LiquibaseConnectionDetails}.
*/
static final class PropertiesLiquibaseConnectionDetails implements LiquibaseConnectionDetails {
private final LiquibaseProperties properties;
PropertiesLiquibaseConnectionDetails(LiquibaseProperties properties) {
this.properties = properties;
}
@Override
public @Nullable String getUsername() {
return this.properties.getUser();
}
@Override
public @Nullable String getPassword() { | return this.properties.getPassword();
}
@Override
public @Nullable String getJdbcUrl() {
return this.properties.getUrl();
}
@Override
public @Nullable String getDriverClassName() {
String driverClassName = this.properties.getDriverClassName();
return (driverClassName != null) ? driverClassName : LiquibaseConnectionDetails.super.getDriverClassName();
}
}
@FunctionalInterface
interface SpringLiquibaseCustomizer {
/**
* Customize the given {@link SpringLiquibase} instance.
* @param springLiquibase the instance to configure
*/
void customize(SpringLiquibase springLiquibase);
}
} | repos\spring-boot-4.0.1\module\spring-boot-liquibase\src\main\java\org\springframework\boot\liquibase\autoconfigure\LiquibaseAutoConfiguration.java | 2 |
请完成以下Java代码 | public static Optional<MarginConfig> castOrEmpty(@NonNull final CommissionConfig commissionConfig)
{
if (commissionConfig instanceof MarginConfig)
{
return Optional.of((MarginConfig)commissionConfig);
}
return Optional.empty();
}
@Builder
MarginConfig(
@JsonProperty("commissionProductId") @NonNull final ProductId commissionProductId,
@JsonProperty("tradedPercent") @NonNull final Percent tradedPercent,
@JsonProperty("pointsPrecision") @NonNull final Integer pointsPrecision,
@JsonProperty("marginContract") @NonNull final MarginContract marginContract,
@JsonProperty("customerTradeMarginLineId") @NonNull final CustomerTradeMarginLineId customerTradeMarginLineId)
{
this.commissionProductId = commissionProductId;
this.tradedPercent = tradedPercent;
this.pointsPrecision = pointsPrecision;
this.marginContract = marginContract;
this.customerTradeMarginLineId = customerTradeMarginLineId;
}
@Override | public CommissionType getCommissionType()
{
return CommissionType.MARGIN_COMMISSION;
}
@Override
public CommissionContract getContractFor(@NonNull final BPartnerId contractualBPartnerId)
{
if (marginContract.getContractOwnerBPartnerId().equals(contractualBPartnerId))
{
return marginContract;
}
return null;
}
@NonNull
public CustomerTradeMarginId getId()
{
return customerTradeMarginLineId.getCustomerTradeMarginId();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\commissioninstance\businesslogic\margin\MarginConfig.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class JtaProcessEngineConfiguration extends ProcessEngineConfigurationImpl {
protected TransactionManager transactionManager;
public JtaProcessEngineConfiguration() {
this.transactionsExternallyManaged = true;
}
@Override
public CommandInterceptor createTransactionInterceptor() {
if (transactionManager == null) {
throw new ActivitiException(
"transactionManager is required property for JtaProcessEngineConfiguration, use " +
StandaloneProcessEngineConfiguration.class.getName() +
" otherwise"
);
}
return new JtaTransactionInterceptor(transactionManager);
} | @Override
public void initTransactionContextFactory() {
if (transactionContextFactory == null) {
transactionContextFactory = new JtaTransactionContextFactory(transactionManager);
}
}
public TransactionManager getTransactionManager() {
return transactionManager;
}
public void setTransactionManager(TransactionManager transactionManager) {
this.transactionManager = transactionManager;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cfg\JtaProcessEngineConfiguration.java | 2 |
请完成以下Java代码 | public void setMatchKey (final @Nullable java.lang.String MatchKey)
{
set_Value (COLUMNNAME_MatchKey, MatchKey);
}
@Override
public java.lang.String getMatchKey()
{
return get_ValueAsString(COLUMNNAME_MatchKey);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
/**
* PostingSign AD_Reference_ID=541699
* Reference name: PostingSign
*/
public static final int POSTINGSIGN_AD_Reference_ID=541699;
/** DR = D */ | public static final String POSTINGSIGN_DR = "D";
/** CR = C */
public static final String POSTINGSIGN_CR = "C";
@Override
public void setPostingSign (final java.lang.String PostingSign)
{
set_Value (COLUMNNAME_PostingSign, PostingSign);
}
@Override
public java.lang.String getPostingSign()
{
return get_ValueAsString(COLUMNNAME_PostingSign);
}
@Override
public void setUserElementString1 (final @Nullable java.lang.String UserElementString1)
{
set_Value (COLUMNNAME_UserElementString1, UserElementString1);
}
@Override
public java.lang.String getUserElementString1()
{
return get_ValueAsString(COLUMNNAME_UserElementString1);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-gen\de\metas\acct\model\X_Fact_Acct_UserChange.java | 1 |
请完成以下Java代码 | public void setMatchAfter(boolean matchAfter) {
this.matchAfter = matchAfter;
}
/**
* Return if filter mappings should be matched after any declared Filter mappings of
* the ServletContext.
* @return if filter mappings are matched after
*/
public boolean isMatchAfter() {
return this.matchAfter;
}
@Override
protected String getDescription() {
Filter filter = getFilter();
Assert.notNull(filter, "'filter' must not be null");
return "filter " + getOrDeduceName(filter);
}
@Override
protected Dynamic addRegistration(String description, ServletContext servletContext) {
Filter filter = getFilter();
return servletContext.addFilter(getOrDeduceName(filter), filter);
}
/**
* Configure registration settings. Subclasses can override this method to perform
* additional configuration if required.
* @param registration the registration
*/
@Override
protected void configure(FilterRegistration.Dynamic registration) {
super.configure(registration);
EnumSet<DispatcherType> dispatcherTypes = determineDispatcherTypes();
Set<String> servletNames = new LinkedHashSet<>();
for (ServletRegistrationBean<?> servletRegistrationBean : this.servletRegistrationBeans) {
servletNames.add(servletRegistrationBean.getServletName());
}
servletNames.addAll(this.servletNames);
if (servletNames.isEmpty() && this.urlPatterns.isEmpty()) {
registration.addMappingForUrlPatterns(dispatcherTypes, this.matchAfter, DEFAULT_URL_MAPPINGS);
}
else {
if (!servletNames.isEmpty()) {
registration.addMappingForServletNames(dispatcherTypes, this.matchAfter,
StringUtils.toStringArray(servletNames));
}
if (!this.urlPatterns.isEmpty()) {
registration.addMappingForUrlPatterns(dispatcherTypes, this.matchAfter,
StringUtils.toStringArray(this.urlPatterns));
}
}
}
/**
* Return the {@link Filter} to be registered.
* @return the filter
*/
public abstract @Nullable T getFilter();
/** | * Returns the filter name that will be registered.
* @return the filter name
* @since 3.2.0
*/
public String getFilterName() {
return getOrDeduceName(getFilter());
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder(getOrDeduceName(this));
if (this.servletNames.isEmpty() && this.urlPatterns.isEmpty()) {
builder.append(" urls=").append(Arrays.toString(DEFAULT_URL_MAPPINGS));
}
else {
if (!this.servletNames.isEmpty()) {
builder.append(" servlets=").append(this.servletNames);
}
if (!this.urlPatterns.isEmpty()) {
builder.append(" urls=").append(this.urlPatterns);
}
}
builder.append(" order=").append(getOrder());
return builder.toString();
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\web\servlet\AbstractFilterRegistrationBean.java | 1 |
请完成以下Java代码 | public class KeyValueType {
@XmlElementRefs({
@XmlElementRef(name = "DSAKeyValue", namespace = "http://www.w3.org/2000/09/xmldsig#", type = JAXBElement.class, required = false),
@XmlElementRef(name = "RSAKeyValue", namespace = "http://www.w3.org/2000/09/xmldsig#", type = JAXBElement.class, required = false)
})
@XmlMixed
@XmlAnyElement(lax = true)
protected List<Object> content;
/**
* Gets the value of the content 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 content property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getContent().add(newItem);
* </pre>
*
*
* <p> | * Objects of the following type(s) are allowed in the list
* {@link JAXBElement }{@code <}{@link DSAKeyValueType }{@code >}
* {@link JAXBElement }{@code <}{@link RSAKeyValueType }{@code >}
* {@link Element }
* {@link Object }
* {@link String }
*
*
*/
public List<Object> getContent() {
if (content == null) {
content = new ArrayList<Object>();
}
return this.content;
}
} | 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\KeyValueType.java | 1 |
请完成以下Java代码 | public table getTable()
{
return m_table;
} // getTable
/**
* Get Table Row (no class set)
* @return table row
*/
public tr getTopRow()
{
return m_topRow;
} // getTopRow
/**
* Get Table Data Left (no class set)
* @return table data
*/
public td getTopLeft()
{
return m_topLeft;
} // getTopLeft
/**
* Get Table Data Right (no class set)
* @return table data
*/
public td getTopRight()
{
return m_topRight;
} // getTopRight
/**
* String representation
* @return String
*/
@Override
public String toString()
{
return m_html.toString();
} // toString
/**
* Output Document
* @param out out
*/
public void output (OutputStream out) | {
m_html.output(out);
} // output
/**
* Output Document
* @param out out
*/
public void output (PrintWriter out)
{
m_html.output(out);
} // output
/**
* Add Popup Center
* @param nowrap set nowrap in td
* @return null or center single td
*/
public td addPopupCenter(boolean nowrap)
{
if (m_table == null)
return null;
//
td center = new td ("popupCenter", AlignType.CENTER, AlignType.MIDDLE, nowrap);
center.setColSpan(2);
m_table.addElement(new tr()
.addElement(center));
return center;
} // addPopupCenter
} // WDoc | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\WebDoc.java | 1 |
请完成以下Java代码 | public void setMSV3_VerfuegbarkeitsanfrageEinzelne_Artikel_ID (int MSV3_VerfuegbarkeitsanfrageEinzelne_Artikel_ID)
{
if (MSV3_VerfuegbarkeitsanfrageEinzelne_Artikel_ID < 1)
set_ValueNoCheck (COLUMNNAME_MSV3_VerfuegbarkeitsanfrageEinzelne_Artikel_ID, null);
else
set_ValueNoCheck (COLUMNNAME_MSV3_VerfuegbarkeitsanfrageEinzelne_Artikel_ID, Integer.valueOf(MSV3_VerfuegbarkeitsanfrageEinzelne_Artikel_ID));
}
/** Get MSV3_VerfuegbarkeitsanfrageEinzelne_Artikel.
@return MSV3_VerfuegbarkeitsanfrageEinzelne_Artikel */
@Override
public int getMSV3_VerfuegbarkeitsanfrageEinzelne_Artikel_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_VerfuegbarkeitsanfrageEinzelne_Artikel_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public de.metas.vertical.pharma.vendor.gateway.msv3.model.I_MSV3_VerfuegbarkeitsanfrageEinzelne getMSV3_VerfuegbarkeitsanfrageEinzelne() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_MSV3_VerfuegbarkeitsanfrageEinzelne_ID, de.metas.vertical.pharma.vendor.gateway.msv3.model.I_MSV3_VerfuegbarkeitsanfrageEinzelne.class);
}
@Override
public void setMSV3_VerfuegbarkeitsanfrageEinzelne(de.metas.vertical.pharma.vendor.gateway.msv3.model.I_MSV3_VerfuegbarkeitsanfrageEinzelne MSV3_VerfuegbarkeitsanfrageEinzelne)
{
set_ValueFromPO(COLUMNNAME_MSV3_VerfuegbarkeitsanfrageEinzelne_ID, de.metas.vertical.pharma.vendor.gateway.msv3.model.I_MSV3_VerfuegbarkeitsanfrageEinzelne.class, MSV3_VerfuegbarkeitsanfrageEinzelne);
}
/** Set MSV3_VerfuegbarkeitsanfrageEinzelne.
@param MSV3_VerfuegbarkeitsanfrageEinzelne_ID MSV3_VerfuegbarkeitsanfrageEinzelne */
@Override | public void setMSV3_VerfuegbarkeitsanfrageEinzelne_ID (int MSV3_VerfuegbarkeitsanfrageEinzelne_ID)
{
if (MSV3_VerfuegbarkeitsanfrageEinzelne_ID < 1)
set_ValueNoCheck (COLUMNNAME_MSV3_VerfuegbarkeitsanfrageEinzelne_ID, null);
else
set_ValueNoCheck (COLUMNNAME_MSV3_VerfuegbarkeitsanfrageEinzelne_ID, Integer.valueOf(MSV3_VerfuegbarkeitsanfrageEinzelne_ID));
}
/** Get MSV3_VerfuegbarkeitsanfrageEinzelne.
@return MSV3_VerfuegbarkeitsanfrageEinzelne */
@Override
public int getMSV3_VerfuegbarkeitsanfrageEinzelne_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_VerfuegbarkeitsanfrageEinzelne_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.vendor.gateway.msv3\src\main\java-gen\de\metas\vertical\pharma\vendor\gateway\msv3\model\X_MSV3_VerfuegbarkeitsanfrageEinzelne_Artikel.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class JsonAddress
{
@JsonProperty("Kind")
JsonAddressKind kind;
@JsonProperty("Name1")
String name1;
@JsonProperty("Name2")
String name2;
@JsonProperty("Street1")
String street1;
@JsonProperty("Street2")
String street2;
@JsonProperty("State")
String state;
@JsonProperty("PostCode")
String postCode;
@JsonProperty("City")
String city;
@JsonProperty("POBox")
String poBox;
@JsonProperty("POPostCode")
String poPostCode;
@JsonProperty("POCity")
String poCity;
@JsonProperty("Phone")
String phone;
@JsonProperty("Mobile")
String mobile;
@JsonProperty("Email")
String email;
@JsonProperty("Attention")
String attention;
@JsonProperty("CustNo") | String custNo;
@JsonProperty("Fax")
String fax;
@JsonProperty("CountryCode")
String countryCode;
@JsonProperty("Province")
String province;
@JsonProperty("ERPRef")
String erpRef;
@JsonProperty("OpeningHours")
String openingHours;
@JsonProperty("VATNo")
String vatNo;
@JsonProperty("VOECNumber")
String voecNumber;
@JsonProperty("Residential")
String residential;
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.client.nshift\src\main\java\de\metas\shipper\client\nshift\json\JsonAddress.java | 2 |
请完成以下Java代码 | public class Result<R> {
private boolean success;
private int code;
private String msg;
private R data;
public static <R> Result<R> ofSuccess(R data) {
return new Result<R>()
.setSuccess(true)
.setMsg("success")
.setData(data);
}
public static <R> Result<R> ofSuccessMsg(String msg) {
return new Result<R>()
.setSuccess(true)
.setMsg(msg);
}
public static <R> Result<R> ofFail(int code, String msg) {
Result<R> result = new Result<>();
result.setSuccess(false);
result.setCode(code);
result.setMsg(msg);
return result;
}
public static <R> Result<R> ofThrowable(int code, Throwable throwable) {
Result<R> result = new Result<>();
result.setSuccess(false);
result.setCode(code);
result.setMsg(throwable.getClass().getName() + ", " + throwable.getMessage());
return result;
}
public boolean isSuccess() {
return success;
}
public Result<R> setSuccess(boolean success) {
this.success = success;
return this;
}
public int getCode() {
return code;
}
public Result<R> setCode(int code) {
this.code = code;
return this;
} | public String getMsg() {
return msg;
}
public Result<R> setMsg(String msg) {
this.msg = msg;
return this;
}
public R getData() {
return data;
}
public Result<R> setData(R data) {
this.data = data;
return this;
}
@Override
public String toString() {
return "Result{" +
"success=" + success +
", code=" + code +
", msg='" + msg + '\'' +
", data=" + data +
'}';
}
} | repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\domain\Result.java | 1 |
请完成以下Java代码 | private static int binarySearch(int[] a, int fromIndex, int length, int key)
{
int low = fromIndex;
int high = fromIndex + length - 1;
while (low <= high)
{
int mid = (low + high) >>> 1;
int midVal = a[mid << 1];
if (midVal < key)
low = mid + 1;
else if (midVal > key)
high = mid - 1;
else
return mid; // key found
}
return -(low + 1); // key not found.
}
/**
* 获取共现频次
*
* @param a 第一个词
* @param b 第二个词
* @return 第一个词@第二个词出现的频次
*/
public static int getBiFrequency(String a, String b)
{
int idA = CoreDictionary.trie.exactMatchSearch(a);
if (idA == -1)
{
return 0;
}
int idB = CoreDictionary.trie.exactMatchSearch(b);
if (idB == -1)
{
return 0;
}
int index = binarySearch(pair, start[idA], start[idA + 1] - start[idA], idB);
if (index < 0) return 0;
index <<= 1;
return pair[index + 1];
}
/**
* 获取共现频次
* @param idA 第一个词的id
* @param idB 第二个词的id | * @return 共现频次
*/
public static int getBiFrequency(int idA, int idB)
{
// 负数id表示来自用户词典的词语的词频(用户自定义词语没有id),返回正值增加其亲和度
if (idA < 0)
{
return -idA;
}
if (idB < 0)
{
return -idB;
}
int index = binarySearch(pair, start[idA], start[idA + 1] - start[idA], idB);
if (index < 0) return 0;
index <<= 1;
return pair[index + 1];
}
/**
* 获取词语的ID
*
* @param a 词语
* @return id
*/
public static int getWordID(String a)
{
return CoreDictionary.trie.exactMatchSearch(a);
}
/**
* 热更新二元接续词典<br>
* 集群环境(或其他IOAdapter)需要自行删除缓存文件
* @return 是否成功
*/
public static boolean reload()
{
String biGramDictionaryPath = HanLP.Config.BiGramDictionaryPath;
IOUtil.deleteFile(biGramDictionaryPath + ".table" + Predefine.BIN_EXT);
return load(biGramDictionaryPath);
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dictionary\CoreBiGramTableDictionary.java | 1 |
请完成以下Java代码 | public void setEntityType (final java.lang.String EntityType)
{
set_Value (COLUMNNAME_EntityType, EntityType);
}
@Override
public java.lang.String getEntityType()
{
return get_ValueAsString(COLUMNNAME_EntityType);
}
@Override
public void setErrorCode (final @Nullable java.lang.String ErrorCode)
{
set_Value (COLUMNNAME_ErrorCode, ErrorCode);
}
@Override
public java.lang.String getErrorCode()
{
return get_ValueAsString(COLUMNNAME_ErrorCode);
}
@Override
public void setMsgText (final java.lang.String MsgText)
{
set_Value (COLUMNNAME_MsgText, MsgText);
}
@Override
public java.lang.String getMsgText()
{
return get_ValueAsString(COLUMNNAME_MsgText);
}
@Override
public void setMsgTip (final @Nullable java.lang.String MsgTip)
{
set_Value (COLUMNNAME_MsgTip, MsgTip);
}
@Override
public java.lang.String getMsgTip()
{
return get_ValueAsString(COLUMNNAME_MsgTip);
}
/** | * MsgType AD_Reference_ID=103
* Reference name: AD_Message Type
*/
public static final int MSGTYPE_AD_Reference_ID=103;
/** Fehler = E */
public static final String MSGTYPE_Fehler = "E";
/** Information = I */
public static final String MSGTYPE_Information = "I";
/** Menü = M */
public static final String MSGTYPE_Menue = "M";
@Override
public void setMsgType (final java.lang.String MsgType)
{
set_Value (COLUMNNAME_MsgType, MsgType);
}
@Override
public java.lang.String getMsgType()
{
return get_ValueAsString(COLUMNNAME_MsgType);
}
@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);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Message.java | 1 |
请完成以下Java代码 | public void setSupportUnits (int SupportUnits)
{
set_ValueNoCheck (COLUMNNAME_SupportUnits, Integer.valueOf(SupportUnits));
}
/** Get Internal Users.
@return Number of Internal Users for Adempiere Support
*/
@Override
public int getSupportUnits ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SupportUnits);
if (ii == null)
return 0;
return ii.intValue();
}
/**
* SystemStatus AD_Reference_ID=374
* Reference name: AD_System Status
*/
public static final int SYSTEMSTATUS_AD_Reference_ID=374;
/** Evaluation = E */
public static final String SYSTEMSTATUS_Evaluation = "E";
/** Implementation = I */
public static final String SYSTEMSTATUS_Implementation = "I";
/** Production = P */
public static final String SYSTEMSTATUS_Production = "P";
/** Set System Status.
@param SystemStatus
Status of the system - Support priority depends on system status
*/
@Override
public void setSystemStatus (java.lang.String SystemStatus)
{
set_Value (COLUMNNAME_SystemStatus, SystemStatus);
}
/** Get System Status.
@return Status of the system - Support priority depends on system status
*/
@Override
public java.lang.String getSystemStatus ()
{
return (java.lang.String)get_Value(COLUMNNAME_SystemStatus);
}
/** Set Registered EMail.
@param UserName
Email of the responsible for the System
*/
@Override
public void setUserName (java.lang.String UserName)
{
set_Value (COLUMNNAME_UserName, UserName);
}
/** Get Registered EMail.
@return Email of the responsible for the System
*/
@Override
public java.lang.String getUserName ()
{
return (java.lang.String)get_Value(COLUMNNAME_UserName);
}
/** Set Version.
@param Version | Version of the table definition
*/
@Override
public void setVersion (java.lang.String Version)
{
set_ValueNoCheck (COLUMNNAME_Version, Version);
}
/** Get Version.
@return Version of the table definition
*/
@Override
public java.lang.String getVersion ()
{
return (java.lang.String)get_Value(COLUMNNAME_Version);
}
/** Set ZK WebUI URL.
@param WebUI_URL
ZK WebUI root URL
*/
@Override
public void setWebUI_URL (java.lang.String WebUI_URL)
{
set_Value (COLUMNNAME_WebUI_URL, WebUI_URL);
}
/** Get ZK WebUI URL.
@return ZK WebUI root URL
*/
@Override
public java.lang.String getWebUI_URL ()
{
return (java.lang.String)get_Value(COLUMNNAME_WebUI_URL);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_System.java | 1 |
请完成以下Java代码 | public static String gensalt(String prefix, int log_rounds) throws IllegalArgumentException {
return gensalt(prefix, log_rounds, new SecureRandom());
}
/**
* Generate a salt for use with the BCrypt.hashpw() method
* @param log_rounds the log2 of the number of rounds of hashing to apply - the work
* factor therefore increases as 2**log_rounds.
* @param random an instance of SecureRandom to use
* @return an encoded salt value
* @exception IllegalArgumentException if log_rounds is invalid
*/
public static String gensalt(int log_rounds, SecureRandom random) throws IllegalArgumentException {
return gensalt("$2a", log_rounds, random);
}
/**
* Generate a salt for use with the BCrypt.hashpw() method
* @param log_rounds the log2 of the number of rounds of hashing to apply - the work
* factor therefore increases as 2**log_rounds.
* @return an encoded salt value
* @exception IllegalArgumentException if log_rounds is invalid
*/
public static String gensalt(int log_rounds) throws IllegalArgumentException {
return gensalt(log_rounds, new SecureRandom());
}
public static String gensalt(String prefix) {
return gensalt(prefix, GENSALT_DEFAULT_LOG2_ROUNDS);
}
/**
* Generate a salt for use with the BCrypt.hashpw() method, selecting a reasonable
* default for the number of hashing rounds to apply
* @return an encoded salt value
*/
public static String gensalt() {
return gensalt(GENSALT_DEFAULT_LOG2_ROUNDS);
} | /**
* Check that a plaintext password matches a previously hashed one
* @param plaintext the plaintext password to verify
* @param hashed the previously-hashed password
* @return true if the passwords match, false otherwise
*/
public static boolean checkpw(String plaintext, String hashed) {
byte[] passwordb = plaintext.getBytes(StandardCharsets.UTF_8);
return equalsNoEarlyReturn(hashed, hashpwforcheck(passwordb, hashed));
}
/**
* Check that a password (as a byte array) matches a previously hashed one
* @param passwordb the password to verify, as a byte array
* @param hashed the previously-hashed password
* @return true if the passwords match, false otherwise
* @since 5.3
*/
public static boolean checkpw(byte[] passwordb, String hashed) {
return equalsNoEarlyReturn(hashed, hashpwforcheck(passwordb, hashed));
}
static boolean equalsNoEarlyReturn(String a, String b) {
return MessageDigest.isEqual(a.getBytes(StandardCharsets.UTF_8), b.getBytes(StandardCharsets.UTF_8));
}
} | repos\spring-security-main\crypto\src\main\java\org\springframework\security\crypto\bcrypt\BCrypt.java | 1 |
请完成以下Java代码 | public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Bounds.class, DC_ELEMENT_BOUNDS)
.namespaceUri(DC_NS)
.instanceProvider(new ModelTypeInstanceProvider<Bounds>() {
public Bounds newInstance(ModelTypeInstanceContext instanceContext) {
return new BoundsImpl(instanceContext);
}
});
xAttribute = typeBuilder.doubleAttribute(DC_ATTRIBUTE_X)
.required()
.build();
yAttribute = typeBuilder.doubleAttribute(DC_ATTRIBUTE_Y)
.required()
.build();
widthAttribute = typeBuilder.doubleAttribute(DC_ATTRIBUTE_WIDTH)
.required()
.build();
heightAttribute = typeBuilder.doubleAttribute(DC_ATTRIBUTE_HEIGHT)
.required()
.build();
typeBuilder.build();
}
public BoundsImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
}
public Double getX() {
return xAttribute.getValue(this);
}
public void setX(double x) {
xAttribute.setValue(this, x);
} | public Double getY() {
return yAttribute.getValue(this);
}
public void setY(double y) {
yAttribute.setValue(this, y);
}
public Double getWidth() {
return widthAttribute.getValue(this);
}
public void setWidth(double width) {
widthAttribute.setValue(this, width);
}
public Double getHeight() {
return heightAttribute.getValue(this);
}
public void setHeight(double height) {
heightAttribute.setValue(this, height);
}
} | repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\dc\BoundsImpl.java | 1 |
请完成以下Java代码 | public boolean isImportAsSingleSummaryLine(@NonNull final BankAccountId bankAccountId)
{
final BankId bankId = bankAccountDAO.getBankId(bankAccountId);
return bankRepo.isImportAsSingleSummaryLine(bankId);
}
@NonNull
public Optional<BankId> getBankIdBySwiftCode(@NonNull final String swiftCode)
{
return bankRepo.getBankIdBySwiftCode(swiftCode);
}
@NonNull
public Optional<BankAccountId> getBankAccountId(
@NonNull final BankId bankId,
@NonNull final String accountNo)
{
return bankAccountDAO.getBankAccountId(bankId, accountNo); | }
@NonNull
public Optional<BankAccountId> getBankAccountIdByIBAN(@NonNull final String iban)
{
return bankAccountDAO.getBankAccountIdByIBAN(iban);
}
@NonNull
public Optional<String> getBankName(@NonNull final BankAccountId bankAccountId)
{
return Optional.of(bankAccountDAO.getById(bankAccountId))
.map(BankAccount::getBankId)
.map(bankRepo::getById)
.map(Bank::getBankName);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\banking\api\BankAccountService.java | 1 |
请完成以下Java代码 | public class X_MD_Candidate_ATP_QueryResult extends org.compiere.model.PO implements I_MD_Candidate_ATP_QueryResult, org.compiere.model.I_Persistent
{
private static final long serialVersionUID = 60721310L;
/** Standard Constructor */
public X_MD_Candidate_ATP_QueryResult (Properties ctx, int MD_Candidate_ATP_QueryResult_ID, String trxName)
{
super (ctx, MD_Candidate_ATP_QueryResult_ID, trxName);
}
/** Load Constructor */
public X_MD_Candidate_ATP_QueryResult (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO(Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setC_BPartner_Customer_ID (int C_BPartner_Customer_ID)
{
if (C_BPartner_Customer_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_BPartner_Customer_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_BPartner_Customer_ID, Integer.valueOf(C_BPartner_Customer_ID));
}
@Override
public int getC_BPartner_Customer_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BPartner_Customer_ID);
}
@Override
public void setDateProjected (java.sql.Timestamp DateProjected)
{
set_ValueNoCheck (COLUMNNAME_DateProjected, DateProjected);
}
@Override
public java.sql.Timestamp getDateProjected()
{
return get_ValueAsTimestamp(COLUMNNAME_DateProjected);
}
@Override
public void setM_Product_ID (int M_Product_ID)
{
if (M_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID));
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setM_Warehouse_ID (int M_Warehouse_ID)
{
if (M_Warehouse_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Warehouse_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Warehouse_ID, Integer.valueOf(M_Warehouse_ID));
}
@Override
public int getM_Warehouse_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Warehouse_ID);
} | @Override
public void setQty (java.math.BigDecimal Qty)
{
set_ValueNoCheck (COLUMNNAME_Qty, Qty);
}
@Override
public java.math.BigDecimal getQty()
{
BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setSeqNo (int SeqNo)
{
set_ValueNoCheck (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
@Override
public void setStorageAttributesKey (java.lang.String StorageAttributesKey)
{
set_ValueNoCheck (COLUMNNAME_StorageAttributesKey, StorageAttributesKey);
}
@Override
public java.lang.String getStorageAttributesKey()
{
return (java.lang.String)get_Value(COLUMNNAME_StorageAttributesKey);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java-gen\de\metas\material\dispo\model\X_MD_Candidate_ATP_QueryResult.java | 1 |
请完成以下Java代码 | public class EndsWithQueryFilter<T> implements IQueryFilter<T>, ISqlQueryFilter
{
private final String columnName;
private final String endsWithString;
public EndsWithQueryFilter(@NonNull final String columnName, @NonNull final String endsWithString)
{
this.columnName = columnName;
this.endsWithString = endsWithString;
}
@Override
public String getSql()
{
buildSql();
return sqlWhereClause;
}
@Override
public List<Object> getSqlParams(Properties ctx)
{
buildSql();
return sqlParams;
}
@Override
public boolean accept(T model)
{
final Object value = InterfaceWrapperHelper.getValueOrNull(model, columnName);
if (value == null)
{
return false;
}
else if (value instanceof String)
{
return ((String)value).endsWith(endsWithString);
}
else | {
throw new IllegalArgumentException("Invalid '" + columnName + "' value for " + model);
}
}
private boolean sqlBuilt = false;
private String sqlWhereClause = null;
private List<Object> sqlParams = null;
private void buildSql()
{
if (sqlBuilt)
{
return;
}
final String sqlWhereClause = columnName
+ " LIKE "
+ "'%'||? ";
this.sqlParams = Collections.singletonList(endsWithString);
this.sqlWhereClause = sqlWhereClause;
this.sqlBuilt = true;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\EndsWithQueryFilter.java | 1 |
请完成以下Java代码 | public boolean isNumericValue()
{
return false;
}
@Override
public boolean isStringValue()
{
return false;
}
@Override
public boolean isList()
{
return false;
}
@Override
public boolean isDateValue()
{
return false;
}
@Override
public boolean isEmpty()
{
return true;
}
@Override
public Object getEmptyValue()
{
return null;
}
@Override
public String getPropagationType()
{
return NullHUAttributePropagator.instance.getPropagationType();
}
@Override
public IAttributeAggregationStrategy retrieveAggregationStrategy()
{
return NullAggregationStrategy.instance;
}
@Override
public IAttributeSplitterStrategy retrieveSplitterStrategy()
{
return NullSplitterStrategy.instance;
}
@Override
public IHUAttributeTransferStrategy retrieveTransferStrategy()
{
return SkipHUAttributeTransferStrategy.instance;
}
@Override
public boolean isUseInASI()
{
return false;
}
@Override
public boolean isDefinedByTemplate()
{
return false;
}
@Override
public void addAttributeValueListener(final IAttributeValueListener listener)
{
// nothing
}
@Override
public List<ValueNamePair> getAvailableValues()
{
throw new InvalidAttributeValueException("method not supported for " + this);
}
@Override
public IAttributeValuesProvider getAttributeValuesProvider()
{
throw new InvalidAttributeValueException("method not supported for " + this);
}
@Override
public I_C_UOM getC_UOM()
{
return null;
}
@Override
public IAttributeValueCallout getAttributeValueCallout()
{
return NullAttributeValueCallout.instance;
}
@Override
public IAttributeValueGenerator getAttributeValueGeneratorOrNull()
{
return null;
}
@Override
public void removeAttributeValueListener(final IAttributeValueListener listener)
{
// nothing | }
@Override
public boolean isReadonlyUI()
{
return true;
}
@Override
public boolean isDisplayedUI()
{
return false;
}
@Override
public boolean isMandatory()
{
return false;
}
@Override
public int getDisplaySeqNo()
{
return 0;
}
@Override
public NamePair getNullAttributeValue()
{
return null;
}
/**
* @return true; we consider Null attributes as always generated
*/
@Override
public boolean isNew()
{
return true;
}
@Override
public boolean isOnlyIfInProductAttributeSet()
{
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\impl\NullAttributeValue.java | 1 |
请完成以下Java代码 | public Double getDoubleValue() {
return doubleValue;
}
public void setDoubleValue(Double doubleValue) {
this.doubleValue = doubleValue;
}
public String getTextValue() {
return textValue;
}
public void setTextValue(String textValue) {
this.textValue = textValue;
}
public String getTextValue2() {
return textValue2;
}
public void setTextValue2(String textValue2) {
this.textValue2 = textValue2;
}
public Object getCachedValue() {
return cachedValue;
}
public void setCachedValue(Object cachedValue) {
this.cachedValue = cachedValue;
}
public void setVariableType(VariableType variableType) {
this.variableType = variableType;
}
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public String getTaskId() {
return taskId;
}
public void setTaskId(String taskId) {
this.taskId = taskId;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getLastUpdatedTime() {
return lastUpdatedTime;
} | public void setLastUpdatedTime(Date lastUpdatedTime) {
this.lastUpdatedTime = lastUpdatedTime;
}
public String getExecutionId() {
return executionId;
}
public void setExecutionId(String executionId) {
this.executionId = executionId;
}
public Date getTime() {
return getCreateTime();
}
public ByteArrayRef getByteArrayRef() {
return byteArrayRef;
}
// common methods //////////////////////////////////////////////////////////
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("HistoricVariableInstanceEntity[");
sb.append("id=").append(id);
sb.append(", name=").append(name);
sb.append(", revision=").append(revision);
sb.append(", type=").append(variableType != null ? variableType.getTypeName() : "null");
if (longValue != null) {
sb.append(", longValue=").append(longValue);
}
if (doubleValue != null) {
sb.append(", doubleValue=").append(doubleValue);
}
if (textValue != null) {
sb.append(", textValue=").append(StringUtils.abbreviate(textValue, 40));
}
if (textValue2 != null) {
sb.append(", textValue2=").append(StringUtils.abbreviate(textValue2, 40));
}
if (byteArrayRef != null && byteArrayRef.getId() != null) {
sb.append(", byteArrayValueId=").append(byteArrayRef.getId());
}
sb.append("]");
return sb.toString();
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\HistoricVariableInstanceEntityImpl.java | 1 |
请完成以下Java代码 | public String getPositionId() {
return positionId;
}
public void setPositionId(String positionId) {
this.positionId = positionId;
}
public String getDepPostParentId() {
return depPostParentId;
}
public void setDepPostParentId(String depPostParentId) {
this.depPostParentId = depPostParentId;
}
/**
* 重写equals方法
*/
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SysDepartTreeModel model = (SysDepartTreeModel) o;
return Objects.equals(id, model.id) &&
Objects.equals(parentId, model.parentId) &&
Objects.equals(departName, model.departName) &&
Objects.equals(departNameEn, model.departNameEn) &&
Objects.equals(departNameAbbr, model.departNameAbbr) &&
Objects.equals(departOrder, model.departOrder) &&
Objects.equals(description, model.description) &&
Objects.equals(orgCategory, model.orgCategory) &&
Objects.equals(orgType, model.orgType) && | Objects.equals(orgCode, model.orgCode) &&
Objects.equals(mobile, model.mobile) &&
Objects.equals(fax, model.fax) &&
Objects.equals(address, model.address) &&
Objects.equals(memo, model.memo) &&
Objects.equals(status, model.status) &&
Objects.equals(delFlag, model.delFlag) &&
Objects.equals(qywxIdentifier, model.qywxIdentifier) &&
Objects.equals(createBy, model.createBy) &&
Objects.equals(createTime, model.createTime) &&
Objects.equals(updateBy, model.updateBy) &&
Objects.equals(updateTime, model.updateTime) &&
Objects.equals(directorUserIds, model.directorUserIds) &&
Objects.equals(positionId, model.positionId) &&
Objects.equals(depPostParentId, model.depPostParentId) &&
Objects.equals(children, model.children);
}
/**
* 重写hashCode方法
*/
@Override
public int hashCode() {
return Objects.hash(id, parentId, departName, departNameEn, departNameAbbr,
departOrder, description, orgCategory, orgType, orgCode, mobile, fax, address,
memo, status, delFlag, qywxIdentifier, createBy, createTime, updateBy, updateTime,
children,directorUserIds, positionId, depPostParentId);
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\model\SysDepartTreeModel.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void reopenPickingJobs(@NonNull final ReopenPickingJobRequest request)
{
final Map<ShipmentScheduleId, List<PickingJobId>> scheduleId2JobIds = pickingJobRepository
.getPickingJobIdsByScheduleId(request.getShipmentScheduleIds());
final PickingJobReopenCommand.PickingJobReopenCommandBuilder commandBuilder = PickingJobReopenCommand.builder()
.pickingSlotService(pickingSlotService)
.pickingJobRepository(pickingJobRepository)
.shipmentScheduleService(shipmentScheduleService)
.huService(huService);
scheduleId2JobIds.values().stream()
.flatMap(List::stream)
.collect(ImmutableSet.toImmutableSet())
.stream()
.map(this::getById)
.filter(pickingJob -> pickingJob.getAllPickedHuIds()
.stream()
.anyMatch(huId -> request.getHuIds().contains(huId)))
.map(job -> commandBuilder
.jobToReopen(job)
.huIdsToPick(request.getHuInfoList())
.build())
.forEach(PickingJobReopenCommand::execute);
}
public PickingSlotSuggestions getPickingSlotsSuggestions(final @NonNull PickingJob pickingJob)
{
final Set<DocumentLocation> deliveryLocations = bpartnerService.getDocumentLocations(pickingJob.getDeliveryBPLocationIds());
return pickingSlotService.getPickingSlotsSuggestions(deliveryLocations);
}
public PickingJob pickAll(@NonNull final PickingJobId pickingJobId, final @NonNull UserId callerId) | {
return PickingJobPickAllCommand.builder()
.pickingJobService(this)
//
.pickingJobId(pickingJobId)
.callerId(callerId)
//
.build().execute();
}
public PickingJobQtyAvailable getQtyAvailable(@NonNull final PickingJobId pickingJobId, final @NonNull UserId callerId)
{
return PickingJobGetQtyAvailableCommand.builder()
.pickingJobService(this)
.warehouseService(warehouseService)
.huService(huService)
//
.pickingJobId(pickingJobId)
.callerId(callerId)
//
.build().execute();
}
public GetNextEligibleLineToPackResponse getNextEligibleLineToPack(@NonNull GetNextEligibleLineToPackRequest request)
{
return GetNextEligibleLineToPackCommand.builder()
.pickingJobService(this)
.huService(huService)
.shipmentSchedules(shipmentScheduleService.newLoadingCache())
.request(request)
.build().execute();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\service\PickingJobService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public static class DateTypeAdapter extends TypeAdapter<Date> {
private DateFormat dateFormat;
public DateTypeAdapter() {
}
public DateTypeAdapter(DateFormat dateFormat) {
this.dateFormat = dateFormat;
}
public void setFormat(DateFormat dateFormat) {
this.dateFormat = dateFormat;
}
@Override
public void write(JsonWriter out, Date date) throws IOException {
if (date == null) {
out.nullValue();
} else {
String value;
if (dateFormat != null) {
value = dateFormat.format(date);
} else {
value = ISO8601Utils.format(date, true);
}
out.value(value);
}
}
@Override
public Date read(JsonReader in) throws IOException {
try {
switch (in.peek()) {
case NULL:
in.nextNull();
return null;
default:
String date = in.nextString();
try { | if (dateFormat != null) {
return dateFormat.parse(date);
}
return ISO8601Utils.parse(date, new ParsePosition(0));
} catch (ParseException e) {
throw new JsonParseException(e);
}
}
} catch (IllegalArgumentException e) {
throw new JsonParseException(e);
}
}
}
public JSON setDateFormat(DateFormat dateFormat) {
dateTypeAdapter.setFormat(dateFormat);
return this;
}
public JSON setSqlDateFormat(DateFormat dateFormat) {
sqlDateTypeAdapter.setFormat(dateFormat);
return this;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-article-api\src\main\java\io\swagger\client\JSON.java | 2 |
请在Spring Boot框架中完成以下Java代码 | void setHttpMessageConvertersCustomizers(
@Nullable List<ClientHttpMessageConvertersCustomizer> httpMessageConvertersCustomizers) {
this.httpMessageConvertersCustomizers = httpMessageConvertersCustomizers;
}
void setRestTemplateCustomizers(@Nullable List<RestTemplateCustomizer> restTemplateCustomizers) {
this.restTemplateCustomizers = restTemplateCustomizers;
}
void setRestTemplateRequestCustomizers(
@Nullable List<RestTemplateRequestCustomizer<?>> restTemplateRequestCustomizers) {
this.restTemplateRequestCustomizers = restTemplateRequestCustomizers;
}
/**
* Configure the specified {@link RestTemplateBuilder}. The builder can be further
* tuned and default settings can be overridden.
* @param builder the {@link RestTemplateBuilder} instance to configure
* @return the configured builder
*/
public RestTemplateBuilder configure(RestTemplateBuilder builder) {
if (this.requestFactoryBuilder != null) {
builder = builder.requestFactoryBuilder(this.requestFactoryBuilder);
} | if (this.clientSettings != null) {
builder = builder.clientSettings(this.clientSettings);
}
if (this.httpMessageConvertersCustomizers != null) {
ClientBuilder clientBuilder = HttpMessageConverters.forClient();
this.httpMessageConvertersCustomizers.forEach((customizer) -> customizer.customize(clientBuilder));
builder = builder.messageConverters(clientBuilder.build());
}
builder = addCustomizers(builder, this.restTemplateCustomizers, RestTemplateBuilder::customizers);
builder = addCustomizers(builder, this.restTemplateRequestCustomizers, RestTemplateBuilder::requestCustomizers);
return builder;
}
private <T> RestTemplateBuilder addCustomizers(RestTemplateBuilder builder, @Nullable List<T> customizers,
BiFunction<RestTemplateBuilder, Collection<T>, RestTemplateBuilder> method) {
if (!ObjectUtils.isEmpty(customizers)) {
return method.apply(builder, customizers);
}
return builder;
}
} | repos\spring-boot-4.0.1\module\spring-boot-restclient\src\main\java\org\springframework\boot\restclient\autoconfigure\RestTemplateBuilderConfigurer.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class AnnotationApplication implements CommandLineRunner {
private static final Logger logger = LoggerFactory.getLogger(AnnotationApplication.class);
@Autowired
private GitHubLookupService githubLookupService;
@Bean("threadPoolTaskExecutor")
public TaskExecutor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(20);
executor.setMaxPoolSize(1000);
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.setThreadNamePrefix("Async-");
return executor;
}
public static void main(String[] args) {
SpringApplication.run(AnnotationApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
// Start the clock
long start = System.currentTimeMillis();
//kick of multiple, asynchronous lookups | CompletableFuture <User> page1 = githubLookupService.findUser("PivotalSoftware");
CompletableFuture < User > page2 = githubLookupService.findUser("CloudFoundry");
CompletableFuture < User > page3 = githubLookupService.findUser("Spring-Projects");
CompletableFuture < User > page4 = githubLookupService.findUser("Hamdambek");
// Wait until they are all done
CompletableFuture.allOf(page1, page2, page3, page4).join();
// Print results, including elapsed time
logger.info("Elapsed time: " + (System.currentTimeMillis() - start));
logger.info("--> " + page1.get());
logger.info("--> " + page2.get());
logger.info("--> " + page3.get());
logger.info("--> " + page4.get());
}
} | repos\Spring-Boot-Advanced-Projects-main\Springboot-Annotation-LookService\src\main\java\spring\annotation\AnnotationApplication.java | 2 |
请完成以下Java代码 | public void setStudentGender(String studentGender) {
this.studentGender = studentGender;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Integer getGrade() {
return grade;
} | public void setGrade(Integer grade) {
this.grade = grade;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
private String state;
} | repos\tutorials-master\persistence-modules\spring-jdbc\src\main\java\com\baeldung\spring\jdbc\replacedeprecated\model\Student.java | 1 |
请完成以下Java代码 | public void onDelete(final I_M_Product product)
{
final MSV3ServerConfig serverConfig = getServerConfigService().getServerConfig();
if (!isMSV3ServerProduct(serverConfig, product))
{
return;
}
final ProductId productId = ProductId.ofRepoId(product.getM_Product_ID());
runAfterCommit(() -> getStockAvailabilityService().publishProductDeletedEvent(productId));
}
private boolean isMSV3ServerProduct(final MSV3ServerConfig serverConfig, final I_M_Product product)
{
if (!serverConfig.hasProducts())
{
return false;
}
if (!product.isActive())
{
return false;
}
final ProductCategoryId productCategoryId = ProductCategoryId.ofRepoId(product.getM_Product_Category_ID()); | if (!serverConfig.getProductCategoryIds().contains(productCategoryId))
{
return false;
}
return true;
}
private MSV3ServerConfigService getServerConfigService()
{
return Adempiere.getBean(MSV3ServerConfigService.class);
}
private MSV3StockAvailabilityService getStockAvailabilityService()
{
return Adempiere.getBean(MSV3StockAvailabilityService.class);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.server-peer-metasfresh\src\main\java\de\metas\vertical\pharma\msv3\server\peer\metasfresh\interceptor\M_Product.java | 1 |
请完成以下Java代码 | public static boolean isBitOn(int value, int bitNumber) {
ensureBitRange(bitNumber);
return ((value & MASKS[bitNumber - 1]) == MASKS[bitNumber - 1]);
}
/**
* Set bit to '0' or '1' in the given int.
* @param current integer value
* @param bitNumber number of the bit to set to '0' or '1' (right first bit starting at 1).
* @param bitValue if true, bit set to '1'. If false, '0'.
*/
public static int setBit(int value, int bitNumber, boolean bitValue)
{
if(bitValue) {
return setBitOn(value, bitNumber); | }
else {
return setBitOff(value, bitNumber);
}
}
public static int getMaskForBit(int bitNumber) {
return MASKS[bitNumber - 1];
}
private static void ensureBitRange(final int bitNumber) {
if(bitNumber <= 0 && bitNumber > 8) {
throw LOG.invalidBitNumber(bitNumber);
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\util\BitMaskUtil.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private static String toString(Observation.Context context) {
return null == context ? "(no context)" : context.getName()
+ " (" + context.getClass().getName() + "@" + System.identityHashCode(context) + ")";
}
private static String toString(Observation.Event event) {
return null == event ? "(no event)" : event.getName();
}
@Override
public boolean supportsContext(Observation.Context context) {
return true;
}
@Override
public void onStart(Observation.Context context) {
log.info("Starting context " + toString(context));
}
@Override
public void onError(Observation.Context context) {
log.info("Error for context " + toString(context));
}
@Override
public void onEvent(Observation.Event event, Observation.Context context) {
log.info("Event for context " + toString(context) + " [" + toString(event) + "]"); | }
@Override
public void onScopeOpened(Observation.Context context) {
log.info("Scope opened for context " + toString(context));
}
@Override
public void onScopeClosed(Observation.Context context) {
log.info("Scope closed for context " + toString(context));
}
@Override
public void onStop(Observation.Context context) {
log.info("Stopping context " + toString(context));
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-3-observation\src\main\java\com\baeldung\samples\config\SimpleLoggingHandler.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void setMinConnections(int minConnections) {
this.minConnections = minConnections;
}
public boolean isMultiUserAuthentication() {
return this.multiUserAuthentication;
}
public void setMultiUserAuthentication(boolean multiUserAuthentication) {
this.multiUserAuthentication = multiUserAuthentication;
}
public long getPingInterval() {
return this.pingInterval;
}
public void setPingInterval(long pingInterval) {
this.pingInterval = pingInterval;
}
public boolean isPrSingleHopEnabled() {
return this.prSingleHopEnabled;
}
public void setPrSingleHopEnabled(boolean prSingleHopEnabled) {
this.prSingleHopEnabled = prSingleHopEnabled;
}
public int getReadTimeout() {
return this.readTimeout;
}
public void setReadTimeout(int readTimeout) {
this.readTimeout = readTimeout;
}
public boolean isReadyForEvents() {
return this.readyForEvents;
}
public void setReadyForEvents(boolean readyForEvents) {
this.readyForEvents = readyForEvents;
}
public int getRetryAttempts() {
return this.retryAttempts;
}
public void setRetryAttempts(int retryAttempts) {
this.retryAttempts = retryAttempts;
}
public String getServerGroup() {
return this.serverGroup;
}
public void setServerGroup(String serverGroup) {
this.serverGroup = serverGroup;
}
public String[] getServers() {
return this.servers;
}
public void setServers(String[] servers) {
this.servers = servers;
} | public int getSocketBufferSize() {
return this.socketBufferSize;
}
public void setSocketBufferSize(int socketBufferSize) {
this.socketBufferSize = socketBufferSize;
}
public int getStatisticInterval() {
return this.statisticInterval;
}
public void setStatisticInterval(int statisticInterval) {
this.statisticInterval = statisticInterval;
}
public int getSubscriptionAckInterval() {
return this.subscriptionAckInterval;
}
public void setSubscriptionAckInterval(int subscriptionAckInterval) {
this.subscriptionAckInterval = subscriptionAckInterval;
}
public boolean isSubscriptionEnabled() {
return this.subscriptionEnabled;
}
public void setSubscriptionEnabled(boolean subscriptionEnabled) {
this.subscriptionEnabled = subscriptionEnabled;
}
public int getSubscriptionMessageTrackingTimeout() {
return this.subscriptionMessageTrackingTimeout;
}
public void setSubscriptionMessageTrackingTimeout(int subscriptionMessageTrackingTimeout) {
this.subscriptionMessageTrackingTimeout = subscriptionMessageTrackingTimeout;
}
public int getSubscriptionRedundancy() {
return this.subscriptionRedundancy;
}
public void setSubscriptionRedundancy(int subscriptionRedundancy) {
this.subscriptionRedundancy = subscriptionRedundancy;
}
public boolean isThreadLocalConnections() {
return this.threadLocalConnections;
}
public void setThreadLocalConnections(boolean threadLocalConnections) {
this.threadLocalConnections = threadLocalConnections;
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\configuration\support\PoolProperties.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public Optional<InvoiceProcessingServiceCompanyConfig> getByCustomerIdAndDate(@NonNull final BPartnerId customerId, @NonNull final ZonedDateTime validFrom)
{
final ImmutableList<InvoiceProcessingServiceCompanyConfig> configsForCompanyBPartners = companyBPartnersToConfigsSorted.values().asList();
for (int i = configsForCompanyBPartners.size() - 1; i >= 0; i--)
{
final InvoiceProcessingServiceCompanyConfig companyConfig = configsForCompanyBPartners.get(i);
if (companyConfig.isValid(validFrom))
{
if (companyConfig.isBPartnerDetailsActive(customerId))
{
return Optional.of(companyConfig);
}
else
{
return Optional.empty();
}
}
}
return Optional.empty();
}
/**
* If ValidFrom is before any of the CompanyConfigs.ValidFrom, we will return the CompanyConfig with ValidFrom closest to the received parameter.
* <p>
* example:
* - ValidFrom: 2020-01-01
* - CompanyConfig1.ValidFrom: 2020-02-01
* - CompanyConfig2.ValidFrom: 2020-03-01
* => return CompanyConfig1.
*/
public Optional<InvoiceProcessingServiceCompanyConfig> getByServiceCompanyBPartnerIdAndDateIncludingInvalidDates(final BPartnerId serviceCompanyBPartnerId, final ZonedDateTime validFrom)
{
final ImmutableList<InvoiceProcessingServiceCompanyConfig> configs = companyBPartnersToConfigsSorted.get(serviceCompanyBPartnerId); | if (configs.isEmpty())
{
return Optional.empty();
}
for (int i = configs.size() - 1; i >= 0; i--)
{
final InvoiceProcessingServiceCompanyConfig config = configs.get(i);
if (config.getValidFrom().isBefore(validFrom) || config.getValidFrom().isEqual(validFrom))
{
return Optional.of(config);
}
}
return Optional.of(configs.get(0));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\invoiceProcessingServiceCompany\InvoiceProcessingServiceCompanyConfigMap.java | 2 |
请完成以下Java代码 | public class ServerHttpBasicAuthenticationConverter implements Function<ServerWebExchange, Mono<Authentication>> {
public static final String BASIC = "Basic ";
private Charset credentialsCharset = StandardCharsets.UTF_8;
@Override
@Deprecated
public Mono<Authentication> apply(ServerWebExchange exchange) {
ServerHttpRequest request = exchange.getRequest();
String authorization = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
if (!StringUtils.startsWithIgnoreCase(authorization, "basic ")) {
return Mono.empty();
}
String credentials = (authorization.length() <= BASIC.length()) ? "" : authorization.substring(BASIC.length());
String decoded = new String(base64Decode(credentials), this.credentialsCharset);
String[] parts = decoded.split(":", 2);
if (parts.length != 2) {
return Mono.empty();
}
return Mono.just(UsernamePasswordAuthenticationToken.unauthenticated(parts[0], parts[1]));
}
private byte[] base64Decode(String value) {
try {
return Base64.getDecoder().decode(value);
}
catch (Exception ex) {
return new byte[0];
} | }
/**
* Sets the {@link Charset} used to decode the Base64-encoded bytes of the basic
* authentication credentials. The default is <code>UTF_8</code>.
* @param credentialsCharset the {@link Charset} used to decode the Base64-encoded
* bytes of the basic authentication credentials
* @since 5.7
*/
public final void setCredentialsCharset(Charset credentialsCharset) {
Assert.notNull(credentialsCharset, "credentialsCharset cannot be null");
this.credentialsCharset = credentialsCharset;
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\ServerHttpBasicAuthenticationConverter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getQUANTITYMEASUREUNIT() {
return quantitymeasureunit;
}
/**
* Sets the value of the quantitymeasureunit property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setQUANTITYMEASUREUNIT(String value) {
this.quantitymeasureunit = value;
}
/**
* Gets the value of the discrepancycode property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDISCREPANCYCODE() {
return discrepancycode;
}
/**
* Sets the value of the discrepancycode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDISCREPANCYCODE(String value) {
this.discrepancycode = value;
}
/**
* Gets the value of the discrepancyreason property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDISCREPANCYREASON() {
return discrepancyreason;
}
/**
* Sets the value of the discrepancyreason property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDISCREPANCYREASON(String value) {
this.discrepancyreason = value;
}
/**
* Gets the value of the discrepancydesc property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDISCREPANCYDESC() {
return discrepancydesc;
}
/**
* Sets the value of the discrepancydesc property.
* | * @param value
* allowed object is
* {@link String }
*
*/
public void setDISCREPANCYDESC(String value) {
this.discrepancydesc = value;
}
/**
* Gets the value of the discrepancydate1 property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDISCREPANCYDATE1() {
return discrepancydate1;
}
/**
* Sets the value of the discrepancydate1 property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDISCREPANCYDATE1(String value) {
this.discrepancydate1 = value;
}
/**
* Gets the value of the discrepancydate2 property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDISCREPANCYDATE2() {
return discrepancydate2;
}
/**
* Sets the value of the discrepancydate2 property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDISCREPANCYDATE2(String value) {
this.discrepancydate2 = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\DQVAR1.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private DQUAN1 createQuantityDetail(
@NonNull final String documentId,
@NonNull final String lineNumber,
@NonNull final QuantityQual qualifier)
{
final DQUAN1 cuQuantity = DESADV_objectFactory.createDQUAN1();
cuQuantity.setDOCUMENTID(documentId);
cuQuantity.setLINENUMBER(lineNumber);
cuQuantity.setQUANTITYQUAL(qualifier.toString());
return cuQuantity;
}
private DQVAR1 createDQVAR1(
@NonNull final String documentId,
@NonNull final EDIExpDesadvLineType line,
@NonNull final BigDecimal quantityDiff,
@NonNull final DecimalFormat decimalFormat)
{
final DQVAR1 dqvar1 = DESADV_objectFactory.createDQVAR1();
dqvar1.setDOCUMENTID(documentId);
dqvar1.setLINENUMBER(extractLineNumber(line, decimalFormat));
dqvar1.setQUANTITY(formatNumber(quantityDiff, decimalFormat));
dqvar1.setDISCREPANCYCODE(extractDiscrepancyCode(line.getIsSubsequentDeliveryPlanned(), quantityDiff).toString());
return dqvar1;
}
@NonNull
private BigDecimal extractQtyDelivered(@Nullable final SinglePack singlePack)
{
if (singlePack == null)
{
return ZERO;
}
final BigDecimal qtyDelivered = singlePack.getPackItem().getQtyCUsPerLU();
if (qtyDelivered == null)
{
return ZERO; | }
return qtyDelivered;
}
private DiscrepencyCode extractDiscrepancyCode(
@Nullable final String isSubsequentDeliveryPlanned,
@NonNull final BigDecimal diff)
{
final DiscrepencyCode discrepancyCode;
if (diff.signum() > 0)
{
discrepancyCode = DiscrepencyCode.OVSH; // = Over-shipped
return discrepancyCode;
}
if (Boolean.parseBoolean(isSubsequentDeliveryPlanned))
{
discrepancyCode = DiscrepencyCode.BFOL; // = Shipment partial - back order to follow
}
else
{
discrepancyCode = DiscrepencyCode.BCOM; // = shipment partial - considered complete, no backorder;
}
return discrepancyCode;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\desadvexport\stepcom\StepComXMLDesadvBean.java | 2 |
请完成以下Java代码 | public void addSentence(String sentence)
{
for (IScorer scorer : scorerList)
{
scorer.addSentence(sentence);
}
}
@Override
public void removeAllSentences()
{
for (IScorer scorer : scorerList)
{
scorer.removeAllSentences();
}
}
@Override
public List<String> suggest(String key, int size)
{
List<String> resultList = new ArrayList<String>(size);
TreeMap<String, Double> scoreMap = new TreeMap<String, Double>();
for (BaseScorer scorer : scorerList)
{
Map<String, Double> map = scorer.computeScore(key);
Double max = max(map); // 用于正规化一个map
for (Map.Entry<String, Double> entry : map.entrySet())
{
Double score = scoreMap.get(entry.getKey());
if (score == null) score = 0.0;
scoreMap.put(entry.getKey(), score + entry.getValue() * scorer.boost / max);
}
}
for (Map.Entry<Double, Set<String>> entry : sortScoreMap(scoreMap).entrySet())
{
for (String sentence : entry.getValue())
{
if (resultList.size() >= size) return resultList;
resultList.add(sentence);
}
}
return resultList;
}
/**
* 将分数map排序折叠
* @param scoreMap
* @return
*/
private static TreeMap<Double ,Set<String>> sortScoreMap(TreeMap<String, Double> scoreMap)
{
TreeMap<Double, Set<String>> result = new TreeMap<Double, Set<String>>(Collections.reverseOrder());
for (Map.Entry<String, Double> entry : scoreMap.entrySet())
{ | Set<String> sentenceSet = result.get(entry.getValue());
if (sentenceSet == null)
{
sentenceSet = new HashSet<String>();
result.put(entry.getValue(), sentenceSet);
}
sentenceSet.add(entry.getKey());
}
return result;
}
/**
* 从map的值中找出最大值,这个值是从0开始的
* @param map
* @return
*/
private static Double max(Map<String, Double> map)
{
Double theMax = 0.0;
for (Double v : map.values())
{
theMax = Math.max(theMax, v);
}
return theMax;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\suggest\Suggester.java | 1 |
请完成以下Java代码 | public class GetPatientsRouteContext
{
@NonNull
private final JsonExternalSystemRequest request;
@NonNull
private final PatientApi patientApi;
@NonNull
private final DoctorApi doctorApi;
@NonNull
private final NursingHomeApi nursingHomeApi;
@NonNull
private final NursingServiceApi nursingServiceApi;
@NonNull
private final HospitalApi hospitalApi;
@NonNull
private final PayerApi payerApi;
@NonNull
private final PharmacyApi pharmacyApi;
@NonNull
private final UserApi userApi;
@NonNull
private final AlbertaConnectionDetails albertaConnectionDetails;
@Nullable
private final JsonMetasfreshId rootBPartnerIdForUsers;
@NonNull
private Instant updatedAfterValue;
public void setUpdatedAfterValue(@Nullable final Instant candidate)
{
if (candidate == null)
{
return; | }
if (candidate.isAfter(this.updatedAfterValue))
{
this.updatedAfterValue = candidate;
}
}
private final List<JsonResponseBPartnerCompositeUpsertItem> importedBPartnerResponseList = new ArrayList<>();
public void addResponseItems(@NonNull final List<JsonResponseBPartnerCompositeUpsertItem> responseBPartnerCompositeUpsertItems)
{
importedBPartnerResponseList.addAll(responseBPartnerCompositeUpsertItems);
}
public void removeAllResponseItems()
{
importedBPartnerResponseList.clear();
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\de-metas-camel-alberta-camelroutes\src\main\java\de\metas\camel\externalsystems\alberta\patient\GetPatientsRouteContext.java | 1 |
请完成以下Java代码 | public void setRenderedAddressAndCapturedLocation(final @NonNull RenderedAddressAndCapturedLocation from)
{
IDocumentDeliveryLocationAdapter.super.setRenderedAddressAndCapturedLocation(from);
}
@Override
public void setRenderedAddress(final @NonNull RenderedAddressAndCapturedLocation from)
{
IDocumentDeliveryLocationAdapter.super.setRenderedAddress(from);
}
public void setFromDeliveryLocation(@NonNull final I_C_Order from)
{
setFrom(new OrderDropShipLocationAdapter(from).toDocumentLocation());
}
public void setFromShipLocation(@NonNull final I_C_Order from)
{
setFrom(OrderDocumentLocationAdapterFactory.locationAdapter(from).toDocumentLocation());
}
@Override | public I_C_Order getWrappedRecord()
{
return delegate;
}
@Override
public Optional<DocumentLocation> toPlainDocumentLocation(final IDocumentLocationBL documentLocationBL)
{
return documentLocationBL.toPlainDocumentLocation(this);
}
@Override
public OrderDropShipLocationAdapter toOldValues()
{
InterfaceWrapperHelper.assertNotOldValues(delegate);
return new OrderDropShipLocationAdapter(InterfaceWrapperHelper.createOld(delegate, I_C_Order.class));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\location\adapter\OrderDropShipLocationAdapter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
SysMessageTemplate sysMessageTemplate = sysMessageTemplateService.getById(id);
return Result.ok(sysMessageTemplate);
}
/**
* 导出excel
*
* @param request
*/
@GetMapping(value = "/exportXls")
public ModelAndView exportXls(HttpServletRequest request,SysMessageTemplate sysMessageTemplate) {
return super.exportXls(request, sysMessageTemplate, SysMessageTemplate.class,"推送消息模板");
}
/**
* excel导入
*
* @param request
* @param response
* @return
*/
@PostMapping(value = "/importExcel")
public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
return super.importExcel(request, response, SysMessageTemplate.class);
} | /**
* 发送消息
*/
@PostMapping(value = "/sendMsg")
public Result<SysMessageTemplate> sendMessage(@RequestBody MsgParams msgParams) {
Result<SysMessageTemplate> result = new Result<SysMessageTemplate>();
try {
MessageDTO md = new MessageDTO();
md.setToAll(false);
md.setTitle("消息发送测试");
md.setTemplateCode(msgParams.getTemplateCode());
md.setToUser(msgParams.getReceiver());
md.setType(msgParams.getMsgType());
String testData = msgParams.getTestData();
if(oConvertUtils.isNotEmpty(testData)){
Map<String, Object> data = JSON.parseObject(testData, Map.class);
md.setData(data);
}
sysBaseApi.sendTemplateMessage(md);
return result.success("消息发送成功!");
} catch (Exception e) {
log.error("发送消息出错:" + e.getMessage(), e);
return result.error500("发送消息出错!");
}
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\message\controller\SysMessageTemplateController.java | 2 |
请完成以下Spring Boot application配置 | server:
port: 8081
dubbo:
application:
# 服务名称,保持唯一
name: server-consumer
# zookeeper地址,用于从中获取注册的服务
registry:
address: zookeepe | r://127.0.0.1:2181
protocol:
# dubbo协议,固定写法
name: dubbo | repos\SpringAll-master\40.Spring-Boot-Dubbo-Zookeeper\server-consumer\src\main\resources\application.yml | 2 |
请完成以下Java代码 | public org.compiere.model.I_R_StatusCategory getR_StatusCategory() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_R_StatusCategory_ID, org.compiere.model.I_R_StatusCategory.class);
}
@Override
public void setR_StatusCategory(org.compiere.model.I_R_StatusCategory R_StatusCategory)
{
set_ValueFromPO(COLUMNNAME_R_StatusCategory_ID, org.compiere.model.I_R_StatusCategory.class, R_StatusCategory);
}
/** Set Status Category.
@param R_StatusCategory_ID
Request Status Category
*/
@Override
public void setR_StatusCategory_ID (int R_StatusCategory_ID)
{
if (R_StatusCategory_ID < 1)
set_Value (COLUMNNAME_R_StatusCategory_ID, null);
else | set_Value (COLUMNNAME_R_StatusCategory_ID, Integer.valueOf(R_StatusCategory_ID));
}
/** Get Status Category.
@return Request Status Category
*/
@Override
public int getR_StatusCategory_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_StatusCategory_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_R_RequestType.java | 1 |
请完成以下Java代码 | static public <U, T> IterableDecorator<U, T> transform(Iterable<U> source, Function<U, T> transform) {
return new IterableDecorator<>(source, transform, v -> true);
}
/**
* <p>filter.</p>
*
* @param source a {@link java.lang.Iterable} object
* @param filter a {@link java.util.function.Predicate} object
* @param <T> a T class
* @return a {@link com.ulisesbocchio.jasyptspringboot.util.Iterables.IterableDecorator} object
*/
static public <T> IterableDecorator<T, T> filter(Iterable<T> source, Predicate<T> filter) {
return new IterableDecorator<>(source, Function.identity(), filter);
}
public static class IterableDecorator<U, T> implements Iterable<T> {
private final Function<U, T> transform;
private final Predicate<U> filter;
private final Iterable<U> source;
IterableDecorator(Iterable<U> source, Function<U, T> transform, Predicate<U> filter) {
this.source = source;
this.transform = transform;
this.filter = filter;
}
@Override
public Iterator<T> iterator() {
return new IteratorDecorator<>(this.source.iterator(), this.transform, this.filter);
}
}
public static class IteratorDecorator<U, T> implements Iterator<T> {
private final Iterator<U> source;
private final Function<U, T> transform;
private final Predicate<U> filter;
private T next = null;
public IteratorDecorator(Iterator<U> source, Function<U, T> transform, Predicate<U> filter) {
this.source = source;
this.transform = transform;
this.filter = filter;
}
public boolean hasNext() { | this.maybeFetchNext();
return next != null;
}
public T next() {
if (next == null) {
throw new NoSuchElementException();
}
T val = next;
next = null;
return val;
}
private void maybeFetchNext() {
if (next == null) {
if (source.hasNext()) {
U val = source.next();
if (filter.test(val)) {
next = transform.apply(val);
}
}
}
}
public void remove() {
throw new UnsupportedOperationException();
}
}
} | repos\jasypt-spring-boot-master\jasypt-spring-boot\src\main\java\com\ulisesbocchio\jasyptspringboot\util\Iterables.java | 1 |
请完成以下Java代码 | public void setMaxImpression (int MaxImpression)
{
set_Value (COLUMNNAME_MaxImpression, Integer.valueOf(MaxImpression));
}
/** Get Max Impression Count.
@return Maximum Impression Count until banner is deactivated
*/
public int getMaxImpression ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_MaxImpression);
if (ii == null)
return 0;
return ii.intValue();
}
/** 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());
}
/** Set Start Date.
@param StartDate
First effective day (inclusive)
*/
public void setStartDate (Timestamp StartDate)
{
set_Value (COLUMNNAME_StartDate, StartDate);
}
/** Get Start Date.
@return First effective day (inclusive)
*/
public Timestamp getStartDate ()
{
return (Timestamp)get_Value(COLUMNNAME_StartDate);
}
/** Set Start Count Impression.
@param StartImpression | For rotation we need a start count
*/
public void setStartImpression (int StartImpression)
{
set_Value (COLUMNNAME_StartImpression, Integer.valueOf(StartImpression));
}
/** Get Start Count Impression.
@return For rotation we need a start count
*/
public int getStartImpression ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_StartImpression);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Target Frame.
@param Target_Frame
Which target should be used if user clicks?
*/
public void setTarget_Frame (String Target_Frame)
{
set_Value (COLUMNNAME_Target_Frame, Target_Frame);
}
/** Get Target Frame.
@return Which target should be used if user clicks?
*/
public String getTarget_Frame ()
{
return (String)get_Value(COLUMNNAME_Target_Frame);
}
/** Set Target URL.
@param TargetURL
URL for the Target
*/
public void setTargetURL (String TargetURL)
{
set_Value (COLUMNNAME_TargetURL, TargetURL);
}
/** Get Target URL.
@return URL for the Target
*/
public String getTargetURL ()
{
return (String)get_Value(COLUMNNAME_TargetURL);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_Ad.java | 1 |
请完成以下Java代码 | public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
public MessageType getMessageType() {
return messageType;
}
public void setMessageType(MessageType messageType) {
this.messageType = messageType;
}
public Card getCard() {
return card;
}
public void setCard(Card card) {
this.card = card;
}
public enum MessageType {
text, interactive
}
public static class Card {
/**
* This is header title.
*/
private String title = "Codecentric's Spring Boot Admin notice"; | private String themeColor = "red";
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getThemeColor() {
return themeColor;
}
public void setThemeColor(String themeColor) {
this.themeColor = themeColor;
}
}
} | repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\notify\FeiShuNotifier.java | 1 |
请完成以下Java代码 | private IOException releaseInputStreams(IOException exceptionChain) {
synchronized (this.inputStreams) {
for (InputStream inputStream : List.copyOf(this.inputStreams)) {
try {
inputStream.close();
}
catch (IOException ex) {
exceptionChain = addToExceptionChain(exceptionChain, ex);
}
}
this.inputStreams.clear();
}
return exceptionChain;
}
private IOException releaseZipContent(IOException exceptionChain) {
ZipContent zipContent = this.zipContent;
if (zipContent != null) {
try {
zipContent.close();
}
catch (IOException ex) {
exceptionChain = addToExceptionChain(exceptionChain, ex);
}
finally {
this.zipContent = null;
}
}
return exceptionChain;
} | private IOException releaseZipContentForManifest(IOException exceptionChain) {
ZipContent zipContentForManifest = this.zipContentForManifest;
if (zipContentForManifest != null) {
try {
zipContentForManifest.close();
}
catch (IOException ex) {
exceptionChain = addToExceptionChain(exceptionChain, ex);
}
finally {
this.zipContentForManifest = null;
}
}
return exceptionChain;
}
private IOException addToExceptionChain(IOException exceptionChain, IOException ex) {
if (exceptionChain != null) {
exceptionChain.addSuppressed(ex);
return exceptionChain;
}
return ex;
}
} | repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\jar\NestedJarFileResources.java | 1 |
请完成以下Java代码 | public Long getTotalQps() {
return totalQps;
}
public void setTotalQps(Long totalQps) {
this.totalQps = totalQps;
}
public Long getAverageRt() {
return averageRt;
}
public void setAverageRt(Long averageRt) {
this.averageRt = averageRt;
}
public Long getPassRequestQps() {
return passRequestQps;
}
public void setPassRequestQps(Long passRequestQps) {
this.passRequestQps = passRequestQps;
}
public Long getExceptionQps() {
return exceptionQps;
}
public void setExceptionQps(Long exceptionQps) {
this.exceptionQps = exceptionQps;
}
public Long getOneMinuteException() {
return oneMinuteException;
}
public void setOneMinuteException(Long oneMinuteException) { | this.oneMinuteException = oneMinuteException;
}
public Long getOneMinutePass() {
return oneMinutePass;
}
public void setOneMinutePass(Long oneMinutePass) {
this.oneMinutePass = oneMinutePass;
}
public Long getOneMinuteBlock() {
return oneMinuteBlock;
}
public void setOneMinuteBlock(Long oneMinuteBlock) {
this.oneMinuteBlock = oneMinuteBlock;
}
public Long getOneMinuteTotal() {
return oneMinuteTotal;
}
public void setOneMinuteTotal(Long oneMinuteTotal) {
this.oneMinuteTotal = oneMinuteTotal;
}
public boolean isVisible() {
return visible;
}
public void setVisible(boolean visible) {
this.visible = visible;
}
} | repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\domain\vo\ResourceVo.java | 1 |
请完成以下Java代码 | public void addActionListener(ActionListener l)
{
listenerList.add(ActionListener.class, l);
} // addActionListener
@Override
public void setBackground(final Color bg)
{
m_text.setBackground(bg);
}
// metas
@Override
public boolean isAutoCommit()
{
return true;
}
// metas
@Override
public void addMouseListener(final MouseListener l)
{
m_text.addMouseListener(l);
}
@Override
public void addKeyListener(final KeyListener l)
{
m_text.addKeyListener(l);
}
public int getCaretPosition()
{ | return m_text.getCaretPosition();
}
public void setCaretPosition(final int position)
{
m_text.setCaretPosition(position);
}
@Override
public final ICopyPasteSupportEditor getCopyPasteSupport()
{
return m_text == null ? NullCopyPasteSupportEditor.instance : m_text.getCopyPasteSupport();
}
@Override
protected final boolean processKeyBinding(final KeyStroke ks, final KeyEvent e, final int condition, final boolean pressed)
{
// Forward all key events on this component to the text field.
// We have to do this for the case when we are embedding this editor in a JTable and the JTable is forwarding the key strokes to editing component.
// Effect of NOT doing this: when in JTable, user presses a key (e.g. a digit) to start editing but the first key he pressed gets lost here.
if (m_text != null && condition == WHEN_FOCUSED)
{
if (m_text.processKeyBinding(ks, e, condition, pressed))
{
return true;
}
}
//
// Fallback to super
return super.processKeyBinding(ks, e, condition, pressed);
}
} // VDate | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VDate.java | 1 |
请完成以下Java代码 | public class ConditionHandlerResult {
private ProcessDefinitionEntity processDefinition;
private ActivityImpl activity;
public ConditionHandlerResult(ProcessDefinitionEntity processDefinition, ActivityImpl activity) {
this.setProcessDefinition(processDefinition);
this.setActivity(activity);
}
public ProcessDefinitionEntity getProcessDefinition() {
return processDefinition;
}
public void setProcessDefinition(ProcessDefinitionEntity processDefinition) {
this.processDefinition = processDefinition; | }
public ActivityImpl getActivity() {
return activity;
}
public void setActivity(ActivityImpl activity) {
this.activity = activity;
}
public static ConditionHandlerResult matchedProcessDefinition(ProcessDefinitionEntity processDefinition, ActivityImpl startActivityId) {
ConditionHandlerResult conditionHandlerResult = new ConditionHandlerResult(processDefinition, startActivityId);
return conditionHandlerResult;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\runtime\ConditionHandlerResult.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void create(Job resources) {
Job job = jobRepository.findByName(resources.getName());
if(job != null){
throw new EntityExistException(Job.class,"name",resources.getName());
}
jobRepository.save(resources);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void update(Job resources) {
Job job = jobRepository.findById(resources.getId()).orElseGet(Job::new);
Job old = jobRepository.findByName(resources.getName());
if(old != null && !old.getId().equals(resources.getId())){
throw new EntityExistException(Job.class,"name",resources.getName());
}
ValidationUtil.isNull( job.getId(),"Job","id",resources.getId());
resources.setId(job.getId());
jobRepository.save(resources);
// 删除缓存
delCaches(resources.getId());
}
@Override
@Transactional(rollbackFor = Exception.class)
public void delete(Set<Long> ids) {
jobRepository.deleteAllByIdIn(ids);
// 删除缓存
redisUtils.delByKeys(CacheKey.JOB_ID, ids);
}
@Override
public void download(List<JobDto> jobDtos, HttpServletResponse response) throws IOException {
List<Map<String, Object>> list = new ArrayList<>();
for (JobDto jobDTO : jobDtos) {
Map<String,Object> map = new LinkedHashMap<>();
map.put("岗位名称", jobDTO.getName()); | map.put("岗位状态", jobDTO.getEnabled() ? "启用" : "停用");
map.put("创建日期", jobDTO.getCreateTime());
list.add(map);
}
FileUtil.downloadExcel(list, response);
}
@Override
public void verification(Set<Long> ids) {
if(userRepository.countByJobs(ids) > 0){
throw new BadRequestException("所选的岗位中存在用户关联,请解除关联再试!");
}
}
/**
* 删除缓存
* @param id /
*/
public void delCaches(Long id){
redisUtils.del(CacheKey.JOB_ID + id);
}
} | repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\system\service\impl\JobServiceImpl.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class JsonCreateReceiptsRequest extends MeasurableRequest
{
@NonNull
@JsonProperty("receiptList")
List<JsonCreateReceiptInfo> jsonCreateReceiptInfoList;
@NonNull
@JsonProperty("returnList")
List<JsonCreateCustomerReturnInfo> jsonCreateCustomerReturnInfoList;
@Builder
@JsonIgnoreProperties(ignoreUnknown = true)
public JsonCreateReceiptsRequest(@JsonProperty("receiptList") final List<JsonCreateReceiptInfo> jsonCreateReceiptInfoList,
@JsonProperty("returnList") final List<JsonCreateCustomerReturnInfo> jsonCreateCustomerReturnInfoList)
{ | this.jsonCreateReceiptInfoList = jsonCreateReceiptInfoList != null
? jsonCreateReceiptInfoList.stream().filter(Objects::nonNull).collect(ImmutableList.toImmutableList())
: ImmutableList.of();
this.jsonCreateCustomerReturnInfoList = jsonCreateCustomerReturnInfoList != null
? jsonCreateCustomerReturnInfoList.stream().filter(Objects::nonNull).collect(ImmutableList.toImmutableList())
: ImmutableList.of();
}
@JsonIgnore
public int getSize()
{
return jsonCreateReceiptInfoList.size() + jsonCreateCustomerReturnInfoList.size();
}
} | repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-shipping\src\main\java\de\metas\common\shipping\v1\receipt\JsonCreateReceiptsRequest.java | 2 |
请完成以下Java代码 | class SubmitUsageCommand {
SubmitUsageCommand() {
}
private SubmitUsageService service = getDefault();
@Parameter(names = "--help", help = true)
private boolean help;
@Parameter(
names = { "--customer", "-C" },
description = "Id of the Customer who's using the services",
validateWith = UUIDValidator.class,
order = 1,
required = true
)
private String customerId;
@Parameter(
names = { "--subscription", "-S" },
description = "Id of the Subscription that was purchased",
order = 2,
required = true
)
private String subscriptionId;
@Parameter(
names = { "--pricing-type", "-P" },
description = "Pricing type of the usage reported",
order = 3,
required = true
)
private PricingType pricingType;
@Parameter(
names = { "--quantity" },
description = "Used quantity; reported quantity is added over the billing period",
order = 3,
required = true
)
private Integer quantity;
@Parameter(
names = { "--timestamp" },
description = "Timestamp of the usage event, must lie in the current billing period",
converter = ISO8601TimestampConverter.class,
order = 4, | required = true
)
private Instant timestamp;
@Parameter(
names = { "--price" },
description = "If PRE_RATED, unit price to be applied per unit of usage quantity reported",
order = 5
)
private BigDecimal price;
void submit() {
UsageRequest req = UsageRequest.builder()
.customerId(customerId)
.subscriptionId(subscriptionId)
.pricingType(pricingType)
.quantity(quantity)
.timestamp(timestamp)
.price(price)
.build();
String reqId = service.submit(req);
System.out.println("Generated Request Id for reference: " + reqId);
}
} | repos\tutorials-master\libraries-cli\src\main\java\com\baeldung\jcommander\usagebilling\cli\SubmitUsageCommand.java | 1 |
请完成以下Java代码 | public void setPMM_Week_ID (int PMM_Week_ID)
{
if (PMM_Week_ID < 1)
set_Value (COLUMNNAME_PMM_Week_ID, null);
else
set_Value (COLUMNNAME_PMM_Week_ID, Integer.valueOf(PMM_Week_ID));
}
/** Get Procurement Week.
@return Procurement Week */
@Override
public int getPMM_Week_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PMM_Week_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Week report event.
@param PMM_WeekReport_Event_ID Week report event */
@Override
public void setPMM_WeekReport_Event_ID (int PMM_WeekReport_Event_ID)
{
if (PMM_WeekReport_Event_ID < 1)
set_ValueNoCheck (COLUMNNAME_PMM_WeekReport_Event_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PMM_WeekReport_Event_ID, Integer.valueOf(PMM_WeekReport_Event_ID));
}
/** Get Week report event.
@return Week report event */
@Override
public int getPMM_WeekReport_Event_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PMM_WeekReport_Event_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Verarbeitet.
@param Processed
Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
} | /** Get Verarbeitet.
@return Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Wochenerster.
@param WeekDate Wochenerster */
@Override
public void setWeekDate (java.sql.Timestamp WeekDate)
{
set_Value (COLUMNNAME_WeekDate, WeekDate);
}
/** Get Wochenerster.
@return Wochenerster */
@Override
public java.sql.Timestamp getWeekDate ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_WeekDate);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java-gen\de\metas\procurement\base\model\X_PMM_WeekReport_Event.java | 1 |
请完成以下Java代码 | public void setUseCurrencyBalancing (boolean UseCurrencyBalancing)
{
set_Value (COLUMNNAME_UseCurrencyBalancing, Boolean.valueOf(UseCurrencyBalancing));
}
/** Get Wähungsunterschiede verbuchen.
@return Sollen Währungsdifferenzen verbucht werden?
*/
@Override
public boolean isUseCurrencyBalancing ()
{
Object oo = get_Value(COLUMNNAME_UseCurrencyBalancing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set doppelte Buchführung.
@param UseSuspenseBalancing
Verwendet doppelte Buchführung über Zwischenkonto bei manuellen Buchungen.
*/
@Override
public void setUseSuspenseBalancing (boolean UseSuspenseBalancing)
{
set_Value (COLUMNNAME_UseSuspenseBalancing, Boolean.valueOf(UseSuspenseBalancing));
}
/** Get doppelte Buchführung.
@return Verwendet doppelte Buchführung über Zwischenkonto bei manuellen Buchungen.
*/
@Override
public boolean isUseSuspenseBalancing ()
{
Object oo = get_Value(COLUMNNAME_UseSuspenseBalancing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false; | }
/** Set CpD-Fehlerkonto verwenden.
@param UseSuspenseError CpD-Fehlerkonto verwenden */
@Override
public void setUseSuspenseError (boolean UseSuspenseError)
{
set_Value (COLUMNNAME_UseSuspenseError, Boolean.valueOf(UseSuspenseError));
}
/** Get CpD-Fehlerkonto verwenden.
@return CpD-Fehlerkonto verwenden */
@Override
public boolean isUseSuspenseError ()
{
Object oo = get_Value(COLUMNNAME_UseSuspenseError);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_AcctSchema_GL.java | 1 |
请完成以下Java代码 | public int getS_Resource_ID()
{
return get_ValueAsInt(COLUMNNAME_S_Resource_ID);
}
@Override
public void setStatus_Print_Job_Instructions (boolean Status_Print_Job_Instructions)
{
set_ValueNoCheck (COLUMNNAME_Status_Print_Job_Instructions, Boolean.valueOf(Status_Print_Job_Instructions));
}
@Override
public boolean isStatus_Print_Job_Instructions()
{
return get_ValueAsBoolean(COLUMNNAME_Status_Print_Job_Instructions);
}
@Override
public void setTrayNumber (int TrayNumber)
{
set_ValueNoCheck (COLUMNNAME_TrayNumber, Integer.valueOf(TrayNumber));
}
@Override
public int getTrayNumber()
{
return get_ValueAsInt(COLUMNNAME_TrayNumber);
}
@Override
public void setWP_IsError (boolean WP_IsError) | {
set_ValueNoCheck (COLUMNNAME_WP_IsError, Boolean.valueOf(WP_IsError));
}
@Override
public boolean isWP_IsError()
{
return get_ValueAsBoolean(COLUMNNAME_WP_IsError);
}
@Override
public void setWP_IsProcessed (boolean WP_IsProcessed)
{
set_ValueNoCheck (COLUMNNAME_WP_IsProcessed, Boolean.valueOf(WP_IsProcessed));
}
@Override
public boolean isWP_IsProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_WP_IsProcessed);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_C_Order_MFGWarehouse_Report_PrintInfo_v.java | 1 |
请完成以下Java代码 | public boolean hasFailedOnEndListeners() {
return false;
}
// getters / setters /////////////////////////////////////////////////
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getBusinessKeyWithoutCascade() {
return businessKeyWithoutCascade;
}
public void setBusinessKey(String businessKey) {
this.businessKey = businessKey;
this.businessKeyWithoutCascade = businessKey;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public boolean isSkipCustomListeners() {
return skipCustomListeners;
}
public void setSkipCustomListeners(boolean skipCustomListeners) {
this.skipCustomListeners = skipCustomListeners; | }
public boolean isSkipIoMappings() {
return skipIoMapping;
}
public void setSkipIoMappings(boolean skipIoMappings) {
this.skipIoMapping = skipIoMappings;
}
public boolean isSkipSubprocesses() {
return skipSubprocesses;
}
public void setSkipSubprocesseses(boolean skipSubprocesses) {
this.skipSubprocesses = skipSubprocesses;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\core\instance\CoreExecution.java | 1 |
请完成以下Java代码 | abstract class UserGroupRecordAccess_Base extends JavaProcess implements IProcessPrecondition
{
private final RecordAccessService userGroupRecordAccessService = SpringContextHolder.instance.getBean(RecordAccessService.class);
@Param(parameterName = "PrincipalType", mandatory = true)
private String principalTypeCode;
@Param(parameterName = "AD_User_ID", mandatory = false)
private UserId userId;
@Param(parameterName = "AD_UserGroup_ID", mandatory = false)
private UserGroupId userGroupId;
private static final String PARAM_PermissionCode = "Access";
@Param(parameterName = PARAM_PermissionCode, mandatory = false)
private String permissionCode;
@Override
public final ProcessPreconditionsResolution checkPreconditionsApplicable(final IProcessPreconditionsContext context)
{
if (context.isNoSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection().toInternal();
}
return ProcessPreconditionsResolution.accept();
}
protected final void grantAccessToRecord()
{
userGroupRecordAccessService.grantAccess(RecordAccessGrantRequest.builder()
.recordRef(getRecordRef())
.principal(getPrincipal())
.permissions(getPermissionsToGrant())
.issuer(PermissionIssuer.MANUAL)
.requestedBy(getUserId())
.build());
}
protected final void revokeAccessFromRecord()
{
final boolean revokeAllPermissions;
final List<Access> permissionsToRevoke;
final Access permission = getPermissionOrNull();
if (permission == null)
{
revokeAllPermissions = true;
permissionsToRevoke = ImmutableList.of();
}
else
{
revokeAllPermissions = false;
permissionsToRevoke = ImmutableList.of(permission);
}
userGroupRecordAccessService.revokeAccess(RecordAccessRevokeRequest.builder()
.recordRef(getRecordRef())
.principal(getPrincipal())
.revokeAllPermissions(revokeAllPermissions)
.permissions(permissionsToRevoke)
.issuer(PermissionIssuer.MANUAL) | .requestedBy(getUserId())
.build());
}
private Principal getPrincipal()
{
final PrincipalType principalType = PrincipalType.ofCode(principalTypeCode);
if (PrincipalType.USER.equals(principalType))
{
return Principal.userId(userId);
}
else if (PrincipalType.USER_GROUP.equals(principalType))
{
return Principal.userGroupId(userGroupId);
}
else
{
throw new AdempiereException("@Unknown@ @PrincipalType@: " + principalType);
}
}
private Set<Access> getPermissionsToGrant()
{
final Access permission = getPermissionOrNull();
if (permission == null)
{
throw new FillMandatoryException(PARAM_PermissionCode);
}
if (Access.WRITE.equals(permission))
{
return ImmutableSet.of(Access.READ, Access.WRITE);
}
else
{
return ImmutableSet.of(permission);
}
}
private Access getPermissionOrNull()
{
if (Check.isEmpty(permissionCode))
{
return null;
}
else
{
return Access.ofCode(permissionCode);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\process\UserGroupRecordAccess_Base.java | 1 |
请完成以下Java代码 | private static Language findInitialLanguage()
{
final Locale locale = LocaleContextHolder.getLocale();
if (locale != null)
{
final Language language = Language.findLanguageByLocale(locale);
if (language != null)
{
return language;
}
}
return Language.getBaseLanguage();
}
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.omitNullValues()
.add("sessionId", sessionId)
.add("loggedIn", loggedIn)
.add("locale", locale)
.add("userPreferences", userPreference)
.add("defaultUseHttpAcceptLanguage", defaultUseHttpAcceptLanguage)
.toString();
}
private void writeObject(final java.io.ObjectOutputStream out) throws IOException
{
out.defaultWriteObject();
UserSession.logger.trace("User session serialized: {}", this);
}
private void readObject(final java.io.ObjectInputStream in) throws IOException, ClassNotFoundException
{
in.defaultReadObject();
UserSession.logger.trace("User session deserialized: {}", this);
}
Properties getCtx()
{
return ctx;
}
public ClientId getClientId()
{
return Env.getClientId(getCtx());
}
public OrgId getOrgId()
{
return Env.getOrgId(getCtx());
}
public String getOrgName()
{
return Env.getContext(getCtx(), Env.CTXNAME_AD_Org_Name);
} | public UserId getLoggedUserId()
{
return Env.getLoggedUserId(getCtx());
}
public Optional<UserId> getLoggedUserIdIfExists()
{
return Env.getLoggedUserIdIfExists(getCtx());
}
public RoleId getLoggedRoleId()
{
return Env.getLoggedRoleId(getCtx());
}
public String getUserName()
{
return Env.getContext(getCtx(), Env.CTXNAME_AD_User_Name);
}
public String getRoleName()
{
return Env.getContext(getCtx(), Env.CTXNAME_AD_Role_Name);
}
String getAdLanguage()
{
return Env.getContext(getCtx(), Env.CTXNAME_AD_Language);
}
Language getLanguage()
{
return Env.getLanguage(getCtx());
}
/**
* @return previous language
*/
String verifyLanguageAndSet(final Language lang)
{
final Properties ctx = getCtx();
final String adLanguageOld = Env.getContext(ctx, Env.CTXNAME_AD_Language);
//
// Check the language (and update it if needed)
final Language validLang = Env.verifyLanguageFallbackToBase(lang);
//
// Actual update
final String adLanguageNew = validLang.getAD_Language();
Env.setContext(ctx, Env.CTXNAME_AD_Language, adLanguageNew);
this.locale = validLang.getLocale();
UserSession.logger.debug("Changed AD_Language: {} -> {}, {}", adLanguageOld, adLanguageNew, validLang);
return adLanguageOld;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\session\InternalUserSessionData.java | 1 |
请完成以下Java代码 | public void setPP_Order_Cost_ID (final int PP_Order_Cost_ID)
{
if (PP_Order_Cost_ID < 1)
set_ValueNoCheck (COLUMNNAME_PP_Order_Cost_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PP_Order_Cost_ID, PP_Order_Cost_ID);
}
@Override
public int getPP_Order_Cost_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Order_Cost_ID);
}
/**
* PP_Order_Cost_TrxType AD_Reference_ID=540941
* Reference name: PP_Order_Cost_TrxType
*/
public static final int PP_ORDER_COST_TRXTYPE_AD_Reference_ID=540941;
/** MainProduct = MR */
public static final String PP_ORDER_COST_TRXTYPE_MainProduct = "MR";
/** MaterialIssue = MI */
public static final String PP_ORDER_COST_TRXTYPE_MaterialIssue = "MI";
/** ResourceUtilization = RU */
public static final String PP_ORDER_COST_TRXTYPE_ResourceUtilization = "RU";
/** ByProduct = BY */
public static final String PP_ORDER_COST_TRXTYPE_ByProduct = "BY";
/** CoProduct = CO */
public static final String PP_ORDER_COST_TRXTYPE_CoProduct = "CO";
@Override
public void setPP_Order_Cost_TrxType (final java.lang.String PP_Order_Cost_TrxType)
{
set_Value (COLUMNNAME_PP_Order_Cost_TrxType, PP_Order_Cost_TrxType);
}
@Override
public java.lang.String getPP_Order_Cost_TrxType() | {
return get_ValueAsString(COLUMNNAME_PP_Order_Cost_TrxType);
}
@Override
public org.eevolution.model.I_PP_Order getPP_Order()
{
return get_ValueAsPO(COLUMNNAME_PP_Order_ID, org.eevolution.model.I_PP_Order.class);
}
@Override
public void setPP_Order(final org.eevolution.model.I_PP_Order PP_Order)
{
set_ValueFromPO(COLUMNNAME_PP_Order_ID, org.eevolution.model.I_PP_Order.class, PP_Order);
}
@Override
public void setPP_Order_ID (final int PP_Order_ID)
{
if (PP_Order_ID < 1)
set_ValueNoCheck (COLUMNNAME_PP_Order_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PP_Order_ID, PP_Order_ID);
}
@Override
public int getPP_Order_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Order_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Order_Cost.java | 1 |
请完成以下Java代码 | public abstract class AbstractAuditingEntity implements Serializable {
private static final long serialVersionUID = 1L;
@CreatedBy
@Column(name = "created_by", nullable = false, length = 50, updatable = false)
@JsonIgnore
private String createdBy;
@CreatedDate
@Column(name = "created_date", updatable = false)
@JsonIgnore
private Instant createdDate = Instant.now();
@LastModifiedBy
@Column(name = "last_modified_by", length = 50)
@JsonIgnore
private String lastModifiedBy;
@LastModifiedDate
@Column(name = "last_modified_date")
@JsonIgnore
private Instant lastModifiedDate = Instant.now();
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public Instant getCreatedDate() {
return createdDate;
} | public void setCreatedDate(Instant createdDate) {
this.createdDate = createdDate;
}
public String getLastModifiedBy() {
return lastModifiedBy;
}
public void setLastModifiedBy(String lastModifiedBy) {
this.lastModifiedBy = lastModifiedBy;
}
public Instant getLastModifiedDate() {
return lastModifiedDate;
}
public void setLastModifiedDate(Instant lastModifiedDate) {
this.lastModifiedDate = lastModifiedDate;
}
} | repos\tutorials-master\jhipster-6\bookstore-monolith\src\main\java\com\baeldung\jhipster6\domain\AbstractAuditingEntity.java | 1 |
请完成以下Java代码 | public ImpFormat getById(@NonNull final ImpFormatId impFormatId)
{
final I_AD_ImpFormat impFormatRecord = InterfaceWrapperHelper.loadOutOfTrx(impFormatId, I_AD_ImpFormat.class);
return toImpFormat(impFormatRecord);
}
public ImpFormat toImpFormat(@NonNull final I_AD_ImpFormat impFormatRecord)
{
final ImpFormatId impFormatId = ImpFormatId.ofRepoId(impFormatRecord.getAD_ImpFormat_ID());
final ImmutableList<ImpFormatColumn> columns = retrieveColumns(impFormatId);
final AdTableId adTableId = AdTableId.ofRepoId(impFormatRecord.getAD_Table_ID());
final ImportTableDescriptor importTableDescriptor = importTableDescriptorRepo.getByTableId(adTableId);
return ImpFormat.builder()
.id(impFormatId)
.name(impFormatRecord.getName())
.formatType(ImpFormatType.ofCode(impFormatRecord.getFormatType()))
.multiLine(impFormatRecord.isMultiLine())
.manualImport(impFormatRecord.isManualImport())
.importTableDescriptor(importTableDescriptor)
.columns(columns)
.charset(Charset.forName(impFormatRecord.getFileCharset()))
.skipFirstNRows(impFormatRecord.getSkipFirstNRows())
.build();
}
private ImmutableList<ImpFormatColumn> retrieveColumns(@NonNull final ImpFormatId impFormatId)
{
return Services.get(IQueryBL.class)
.createQueryBuilderOutOfTrx(I_AD_ImpFormat_Row.class)
.addEqualsFilter(I_AD_ImpFormat_Row.COLUMNNAME_AD_ImpFormat_ID, impFormatId)
.addOnlyActiveRecordsFilter()
.orderBy(I_AD_ImpFormat_Row.COLUMNNAME_SeqNo)
.create()
.stream(I_AD_ImpFormat_Row.class)
.map(this::toImpFormatRowOrNull)
.filter(Objects::nonNull) | .collect(ImmutableList.toImmutableList());
}
private ImpFormatColumn toImpFormatRowOrNull(final I_AD_ImpFormat_Row rowRecord)
{
final I_AD_Column adColumn = rowRecord.getAD_Column();
if (!adColumn.isActive())
{
return null;
}
return ImpFormatColumn.builder()
.name(rowRecord.getName())
.columnName(adColumn.getColumnName())
.startNo(rowRecord.getStartNo())
.endNo(rowRecord.getEndNo())
.dataType(ImpFormatColumnDataType.ofCode(rowRecord.getDataType()))
.maxLength(adColumn.getFieldLength())
.dataFormat(rowRecord.getDataFormat())
.decimalSeparator(DecimalSeparator.ofNullableStringOrDot(rowRecord.getDecimalPoint()))
.divideBy100(rowRecord.isDivideBy100())
.constantValue(rowRecord.getConstantValue())
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\format\ImpFormatRepository.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private Report.ParameterType getParameterType(IParameterDefn param) {
if (IParameterDefn.TYPE_INTEGER == param.getDataType()) {
return Report.ParameterType.INT;
}
return Report.ParameterType.STRING;
}
public void generateMainReport(String reportName, OutputType output, HttpServletResponse response, HttpServletRequest request) {
switch (output) {
case HTML:
generateHTMLReport(reports.get(reportName), response, request);
break;
case PDF:
generatePDFReport(reports.get(reportName), response, request);
break;
default:
throw new IllegalArgumentException("Output type not recognized:" + output);
}
}
/**
* Generate a report as HTML
*/
@SuppressWarnings("unchecked")
private void generateHTMLReport(IReportRunnable report, HttpServletResponse response, HttpServletRequest request) {
IRunAndRenderTask runAndRenderTask = birtEngine.createRunAndRenderTask(report);
response.setContentType(birtEngine.getMIMEType("html"));
IRenderOption options = new RenderOption();
HTMLRenderOption htmlOptions = new HTMLRenderOption(options);
htmlOptions.setOutputFormat("html");
htmlOptions.setBaseImageURL("/" + reportsPath + imagesPath);
htmlOptions.setImageDirectory(imageFolder);
htmlOptions.setImageHandler(htmlImageHandler);
runAndRenderTask.setRenderOption(htmlOptions);
runAndRenderTask.getAppContext().put(EngineConstants.APPCONTEXT_BIRT_VIEWER_HTTPSERVET_REQUEST, request);
try {
htmlOptions.setOutputStream(response.getOutputStream());
runAndRenderTask.run();
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e); | } finally {
runAndRenderTask.close();
}
}
/**
* Generate a report as PDF
*/
@SuppressWarnings("unchecked")
private void generatePDFReport(IReportRunnable report, HttpServletResponse response, HttpServletRequest request) {
IRunAndRenderTask runAndRenderTask = birtEngine.createRunAndRenderTask(report);
response.setContentType(birtEngine.getMIMEType("pdf"));
IRenderOption options = new RenderOption();
PDFRenderOption pdfRenderOption = new PDFRenderOption(options);
pdfRenderOption.setOutputFormat("pdf");
runAndRenderTask.setRenderOption(pdfRenderOption);
runAndRenderTask.getAppContext().put(EngineConstants.APPCONTEXT_PDF_RENDER_CONTEXT, request);
try {
pdfRenderOption.setOutputStream(response.getOutputStream());
runAndRenderTask.run();
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
} finally {
runAndRenderTask.close();
}
}
@Override
public void destroy() {
birtEngine.destroy();
Platform.shutdown();
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-mvc-birt\src\main\java\com\baeldung\birt\engine\service\BirtReportService.java | 2 |
请完成以下Java代码 | class CapitalizeFirstCharacterEachWordUtils {
static String usingCharacterToUpperCaseMethod(String input) {
if (input == null || input.isEmpty()) {
return null;
}
return Arrays.stream(input.split("\\s+"))
.map(word -> Character.toUpperCase(word.charAt(0)) + word.substring(1))
.collect(Collectors.joining(" "));
}
static String usingStringToUpperCaseMethod(String input) {
if (input == null || input.isEmpty()) {
return null;
} | return Arrays.stream(input.split("\\s+"))
.map(word -> word.substring(0, 1).toUpperCase() + word.substring(1))
.collect(Collectors.joining(" "));
}
static String usingStringUtilsClass(String input) {
if (input == null || input.isEmpty()) {
return null;
}
return Arrays.stream(input.split("\\s+"))
.map(StringUtils::capitalize)
.collect(Collectors.joining(" "));
}
} | repos\tutorials-master\core-java-modules\core-java-string-operations-7\src\main\java\com\baeldung\capitalizefirstcharactereachword\CapitalizeFirstCharacterEachWordUtils.java | 1 |
请完成以下Java代码 | public void packageDelivered(Instant pickupTime) {
Workflow.await(() -> shipping != null);
shipping = shipping.toStatus(ShippingStatus.DELIVERED, pickupTime, "Package delivered");
}
@Override
public void packageReturned(Instant pickupTime) {
shipping = shipping.toStatus(ShippingStatus.RETURNED, pickupTime, "Package returned");
}
@Override
public Order getOrder() {
return order;
}
@Override | public Shipping getShipping() {
return shipping;
}
@Override
public PaymentAuthorization getPayment() {
return payment;
}
@Override
public RefundRequest getRefund() {
return refund;
}
} | repos\tutorials-master\saas-modules\temporal\src\main\java\com\baeldung\temporal\workflows\sboot\order\workflow\OrderWorkflowImpl.java | 1 |
请完成以下Java代码 | public org.eevolution.model.I_PP_Order_Workflow getPP_Order_Workflow()
{
return get_ValueAsPO(COLUMNNAME_PP_Order_Workflow_ID, org.eevolution.model.I_PP_Order_Workflow.class);
}
@Override
public void setPP_Order_Workflow(final org.eevolution.model.I_PP_Order_Workflow PP_Order_Workflow)
{
set_ValueFromPO(COLUMNNAME_PP_Order_Workflow_ID, org.eevolution.model.I_PP_Order_Workflow.class, PP_Order_Workflow);
}
@Override
public int getPP_Order_Workflow_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Order_Workflow_ID);
}
@Override
public void setPP_Order_Workflow_ID(final int PP_Order_Workflow_ID)
{
if (PP_Order_Workflow_ID < 1)
set_ValueNoCheck(COLUMNNAME_PP_Order_Workflow_ID, null);
else
set_ValueNoCheck(COLUMNNAME_PP_Order_Workflow_ID, PP_Order_Workflow_ID);
}
@Override
public BigDecimal getQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQty(final @Nullable BigDecimal Qty)
{
set_Value(COLUMNNAME_Qty, Qty);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
@Override
public void setSeqNo(final int SeqNo)
{
set_Value(COLUMNNAME_SeqNo, SeqNo);
}
@Override
public java.lang.String getSpecification() | {
return get_ValueAsString(COLUMNNAME_Specification);
}
@Override
public void setSpecification(final @Nullable java.lang.String Specification)
{
set_Value(COLUMNNAME_Specification, Specification);
}
@Override
public BigDecimal getYield()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Yield);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setYield(final @Nullable BigDecimal Yield)
{
set_Value(COLUMNNAME_Yield, Yield);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Order_Node_Product.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private RequestBody forceContentLength(final RequestBody requestBody) throws IOException {
final Buffer buffer = new Buffer();
requestBody.writeTo(buffer);
return new RequestBody() {
@Override
public MediaType contentType() {
return requestBody.contentType();
}
@Override
public long contentLength() {
return buffer.size();
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
sink.write(buffer.snapshot());
}
};
}
private RequestBody gzip(final RequestBody body) {
return new RequestBody() { | @Override public MediaType contentType() {
return body.contentType();
}
@Override public long contentLength() {
return -1; // We don't know the compressed length in advance!
}
@Override public void writeTo(BufferedSink sink) throws IOException {
BufferedSink gzipSink = Okio.buffer(new GzipSink(sink));
body.writeTo(gzipSink);
gzipSink.close();
}
};
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-article-api\src\main\java\io\swagger\client\GzipRequestInterceptor.java | 2 |
请完成以下Java代码 | private int createSelection()
{
final IQueryBuilder<I_C_Invoice_Candidate> queryBuilder = createICQueryBuilder();
//
// Create selection and return how many items were added
final PInstanceId adPInstanceId = getPinstanceId();
Check.assumeNotNull(adPInstanceId, "adPInstanceId is not null");
DB.deleteT_Selection(adPInstanceId, ITrx.TRXNAME_ThreadInherited);
final int selectionCount = queryBuilder
.create()
.setRequiredAccess(Access.READ)
.createSelection(adPInstanceId);
return selectionCount;
}
private IQueryBuilder<I_C_Invoice_Candidate> createICQueryBuilder()
{
final IQuery<I_M_Product_Category> subQuery_ProductcategFilter = queryBL
.createQueryBuilder(I_M_Product_Category.class)
.addEqualsFilter(I_M_Product_Category.COLUMNNAME_M_Product_Category_ID, p_ProductCategoryId)
.setJoinOr() | .addEqualsFilter(I_M_Product_Category.COLUMNNAME_M_Product_Category_Parent_ID, p_ProductCategoryId)
.create();
final IQuery<I_M_Product> subQuery_Product = queryBL
.createQueryBuilder(I_M_Product.class)
.addInSubQueryFilter()
.matchingColumnNames(I_M_Product.COLUMNNAME_M_Product_Category_ID, I_M_Product_Category.COLUMNNAME_M_Product_Category_ID)
.subQuery(subQuery_ProductcategFilter)
.end()
.create();
return queryBL
.createQueryBuilder(I_C_Invoice_Candidate.class, getCtx(), ITrx.TRXNAME_None)
.addEqualsFilter(I_C_Invoice_Candidate.COLUMNNAME_AD_Org_ID, p_OrgId)
.addEqualsFilter(I_C_Invoice_Candidate.COLUMNNAME_Processed, false)
.addInSubQueryFilter()
.matchingColumnNames(I_C_Invoice_Candidate.COLUMNNAME_M_Product_ID, I_M_Product.COLUMNNAME_M_Product_ID)
.subQuery(subQuery_Product)
.end()
.addOnlyContextClient();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\process\C_Invoice_Candidate_EnqueueSelectionForInvoicingAndPDFConcatenating.java | 1 |
请完成以下Java代码 | public int getRepoId()
{
return repoId;
}
public static int toRepoId(@Nullable final InvoiceId invoiceId)
{
return toRepoIdOr(invoiceId, -1);
}
public static int toRepoIdOr(@Nullable final InvoiceId invoiceId, final int defaultValue)
{
return invoiceId != null ? invoiceId.getRepoId() : defaultValue;
}
public static ImmutableSet<InvoiceId> fromIntSet(@NonNull final Collection<Integer> repoIds)
{
if (repoIds.isEmpty()) | {
return ImmutableSet.of();
}
return repoIds.stream().map(InvoiceId::ofRepoIdOrNull).filter(Objects::nonNull).collect(ImmutableSet.toImmutableSet());
}
public static ImmutableSet<Integer> toIntSet(@NonNull final Collection<InvoiceId> ids)
{
if (ids.isEmpty())
{
return ImmutableSet.of();
}
return ids.stream().map(InvoiceId::getRepoId).collect(ImmutableSet.toImmutableSet());
}
public static boolean equals(@Nullable final InvoiceId id1, @Nullable final InvoiceId id2) {return Objects.equals(id1, id2);}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\invoice\InvoiceId.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public UserVO login(LoginUserRequest request) {
Observation observation =
Observation.start(USER_CONTEXT + ".login", this::createUserContext, observationRegistry);
try (Observation.Scope ignored = observation.openScope()) {
UserVO loggedInUser = userService.login(request);
observation.event(Observation.Event.of("loggedIn", "User logged in"));
return loggedInUser;
} catch (Exception ex) {
observation.error(ex);
throw ex;
} finally {
observation.stop();
}
}
@Override
public UserVO update(User user, UpdateUserRequest request) {
Observation observation =
Observation.start(USER_CONTEXT + ".update", this::createUserContext, observationRegistry);
try (Observation.Scope ignored = observation.openScope()) {
UserVO updatedUser = userService.update(user, request);
observation.event(Observation.Event.of("updated", "User updated")); | return updatedUser;
} catch (Exception ex) {
observation.error(ex);
throw ex;
} finally {
observation.stop();
}
}
private Observation.Context createUserContext() {
Observation.Context context = new Observation.Context();
context.addLowCardinalityKeyValues(KeyValues.of("context", "user"));
return context;
}
} | repos\realworld-spring-boot-native-master\src\main\java\com\softwaremill\realworld\application\user\service\ObservedUserService.java | 2 |
请完成以下Java代码 | public Doc<?> get(@NonNull final List<AcctSchema> acctSchemas, @NonNull final TableRecordReference documentRef)
{
final Doc<?> doc = docProviders.getOrNull(acctDocRequiredServices, acctSchemas, documentRef);
if (doc == null)
{
throw new PostingExecutionException("No accountable document found: " + documentRef);
}
return doc;
}
public Set<String> getDocTableNames()
{
return docProviders.getDocTableNames();
}
public boolean isAccountingTable(final String docTableName)
{
return docProviders.isAccountingTable(docTableName);
}
//
//
//
// ------------------------------------------------------------------------
//
//
//
@ToString
private static class AggregatedAcctDocProvider implements IAcctDocProvider
{
private final ImmutableMap<String, IAcctDocProvider> providersByDocTableName;
private AggregatedAcctDocProvider(final List<IAcctDocProvider> providers)
{
final ImmutableMap.Builder<String, IAcctDocProvider> mapBuilder = ImmutableMap.builder();
for (final IAcctDocProvider provider : providers)
{
for (final String docTableName : provider.getDocTableNames())
{
mapBuilder.put(docTableName, provider);
}
}
this.providersByDocTableName = mapBuilder.build();
}
public boolean isAccountingTable(final String docTableName)
{
return getDocTableNames().contains(docTableName);
}
@Override | public Set<String> getDocTableNames()
{
return providersByDocTableName.keySet();
}
@Override
public Doc<?> getOrNull(
@NonNull final AcctDocRequiredServicesFacade services,
@NonNull final List<AcctSchema> acctSchemas,
@NonNull final TableRecordReference documentRef)
{
try
{
final String docTableName = documentRef.getTableName();
final IAcctDocProvider provider = providersByDocTableName.get(docTableName);
if (provider == null)
{
return null;
}
return provider.getOrNull(services, acctSchemas, documentRef);
}
catch (final AdempiereException ex)
{
throw ex;
}
catch (final Exception ex)
{
throw PostingExecutionException.wrapIfNeeded(ex);
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\doc\AcctDocRegistry.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getTaskId() {
return taskId;
}
@Override
public Date getTimeStamp() {
return timeStamp;
}
@Override
public String getUserId() {
return userId;
}
@Override
public String getData() {
return data;
}
@Override
public String getExecutionId() {
return executionId;
}
@Override
public String getProcessInstanceId() {
return processInstanceId;
}
@Override
public String getProcessDefinitionId() {
return processDefinitionId;
}
@Override
public String getScopeId() {
return scopeId;
} | @Override
public String getScopeDefinitionId() {
return scopeDefinitionId;
}
@Override
public String getSubScopeId() {
return subScopeId;
}
@Override
public String getScopeType() {
return scopeType;
}
@Override
public String getTenantId() {
return tenantId;
}
@Override
public String toString() {
return this.getClass().getName() + "(" + logNumber + ", " + getTaskId() + ", " + type +")";
}
} | repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\persistence\entity\HistoricTaskLogEntryEntityImpl.java | 2 |
请完成以下Java代码 | public class RestClientRegistrationClient implements RegistrationClient {
private static final ParameterizedTypeReference<Map<String, Object>> RESPONSE_TYPE = new ParameterizedTypeReference<>() {
};
private final RestClient restClient;
public RestClientRegistrationClient(RestClient restClient) {
this.restClient = restClient;
}
@Override
public String register(String adminUrl, Application application) {
Map<String, Object> response = this.restClient.post()
.uri(adminUrl)
.headers(this::setRequestHeaders) | .body(application)
.retrieve()
.body(RESPONSE_TYPE);
return response.get("id").toString();
}
@Override
public void deregister(String adminUrl, String id) {
this.restClient.delete().uri(adminUrl + '/' + id).retrieve().toBodilessEntity();
}
protected void setRequestHeaders(HttpHeaders headers) {
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
}
} | repos\spring-boot-admin-master\spring-boot-admin-client\src\main\java\de\codecentric\boot\admin\client\registration\RestClientRegistrationClient.java | 1 |
请完成以下Java代码 | public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
} | public List<Person> getAuthors() {
return authors;
}
public void setAuthors(List<Person> authors) {
this.authors = authors;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
} | repos\tutorials-master\video-tutorials\jackson-annotations-video\src\main\java\com\baeldung\jacksonannotation\deserialization\jsondeserialize\Item.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
QuoteDTO quoteDTO = (QuoteDTO) o;
if (quoteDTO.getId() == null || getId() == null) {
return false;
}
return Objects.equals(getId(), quoteDTO.getId());
} | @Override
public int hashCode() {
return Objects.hashCode(getId());
}
@Override
public String toString() {
return "QuoteDTO{" +
"id=" + getId() +
", symbol='" + getSymbol() + "'" +
", price=" + getPrice() +
", lastTrade='" + getLastTrade() + "'" +
"}";
}
} | repos\tutorials-master\jhipster-modules\jhipster-uaa\quotes\src\main\java\com\baeldung\jhipster\quotes\service\dto\QuoteDTO.java | 2 |
请完成以下Java代码 | public Void execute(CommandContext commandContext) {
ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(commandContext);
if (!processEngineConfiguration.isFlowable5CompatibilityEnabled() || processEngineConfiguration.getFlowable5CompatibilityHandler() == null) {
RepositoryService repositoryService = processEngineConfiguration.getRepositoryService();
long numberOfV5Deployments = repositoryService.createDeploymentQuery().deploymentEngineVersion(Flowable5Util.V5_ENGINE_TAG).count();
LOGGER.info("Total of v5 deployments found: {}", numberOfV5Deployments);
if (numberOfV5Deployments > 0) {
List<ProcessDefinition> processDefinitions = repositoryService.createProcessDefinitionQuery()
.latestVersion()
.processDefinitionEngineVersion(Flowable5Util.V5_ENGINE_TAG)
.list();
if (!processDefinitions.isEmpty()) {
String message = new StringBuilder("Found v5 process definitions that are the latest version.")
.append(" Enable the 'flowable5CompatibilityEnabled' property in the process engine configuration")
.append(" and make sure the flowable5-compatibility dependency is available on the classpath").toString();
LOGGER.error(message);
for (ProcessDefinition processDefinition : processDefinitions) {
LOGGER.error("Found v5 process definition with id: {}, and key: {}", processDefinition.getId(), processDefinition.getKey());
}
throw new FlowableException(message);
}
RuntimeService runtimeService = processEngineConfiguration.getRuntimeService();
long numberOfV5ProcessInstances = runtimeService.createProcessInstanceQuery().processDefinitionEngineVersion(Flowable5Util.V5_ENGINE_TAG).count(); | if (numberOfV5ProcessInstances > 0) {
String message = new StringBuilder("Found at least one running v5 process instance.")
.append(" Enable the 'flowable5CompatibilityEnabled' property in the process engine configuration")
.append(" and make sure the flowable5-compatibility dependency is available on the classpath").toString();
LOGGER.error(message);
throw new FlowableException(message);
}
}
}
return null;
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\cmd\ValidateV5EntitiesCmd.java | 1 |
请完成以下Java代码 | public boolean add(Cookie cookie) {
if (cookie == null) {
return false;
}
cookieMap.put(cookie.getName(), cookie);
return true;
}
@Override
public boolean remove(Object o) {
if (o instanceof String) {
return cookieMap.remove((String)o) != null;
}
if (o instanceof Cookie) {
Cookie c = (Cookie)o;
return cookieMap.remove(c.getName()) != null;
}
return false;
}
public Cookie get(String name) {
return cookieMap.get(name);
}
@Override
public boolean containsAll(Collection<?> collection) {
for(Object o : collection) {
if (!contains(o)) {
return false;
}
}
return true;
}
@Override
public boolean addAll(Collection<? extends Cookie> collection) {
boolean result = false;
for(Cookie cookie : collection) {
result|= add(cookie);
}
return result;
}
@Override
public boolean removeAll(Collection<?> collection) { | boolean result = false;
for(Object cookie : collection) {
result|= remove(cookie);
}
return result;
}
@Override
public boolean retainAll(Collection<?> collection) {
boolean result = false;
Iterator<Map.Entry<String, Cookie>> it = cookieMap.entrySet().iterator();
while(it.hasNext()) {
Map.Entry<String, Cookie> e = it.next();
if (!collection.contains(e.getKey()) && !collection.contains(e.getValue())) {
it.remove();
result = true;
}
}
return result;
}
@Override
public void clear() {
cookieMap.clear();
}
} | repos\tutorials-master\jhipster-modules\jhipster-uaa\gateway\src\main\java\com\baeldung\jhipster\gateway\security\oauth2\CookieCollection.java | 1 |
请完成以下Java代码 | public final class JavaLanguage extends AbstractLanguage {
/**
* Java {@link Language} identifier.
*/
public static final String ID = "java";
/**
* Creates a new instance with the JVM version {@value #DEFAULT_JVM_VERSION}.
*/
public JavaLanguage() {
this(DEFAULT_JVM_VERSION);
}
/**
* Creates a new instance.
* @param jvmVersion the JVM version | */
public JavaLanguage(String jvmVersion) {
super(ID, jvmVersion, "java");
}
@Override
public boolean supportsEscapingKeywordsInPackage() {
return false;
}
@Override
public boolean isKeyword(String input) {
return SourceVersion.isKeyword(input);
}
} | repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\language\java\JavaLanguage.java | 1 |
请完成以下Java代码 | public class MyRealm extends AuthorizingRealm {
// 授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
Object principal = principalCollection.getPrimaryPrincipal();
Set<String> roles = new HashSet<>();
roles.add("user");
if ("admin".equals(principal)) {
roles.add("admin");
}
return new SimpleAuthorizationInfo(roles);
}
// 认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
log.info("MyRealm doGetAuthenticationInfo");
UsernamePasswordToken userToken = (UsernamePasswordToken) token;
String username = userToken.getUsername();
if ("unknown".equals(username)) {
throw new UnknownAccountException("用户不存在");
} | if ("monster".equals(username)) {
throw new LockedAccountException("用户被锁定");
}
Object principal = username;
Object credentials = "e10adc3949ba59abbe56e057f20f883e";
String realmName = getName();
log.info("doGetAuthenticationInfo username: {}", username);
/**
* 见 {@link ShiroConfig#myRealm} 的密码指定算法
*/
return new SimpleAuthenticationInfo(principal, credentials, realmName);
}
public static void main(String[] args) {
String hashAlgorithmName = "MD5";
String credentials = "123456";
Object salt = null;
int hashIterations = 100;
SimpleHash simpleHash = new SimpleHash(hashAlgorithmName, credentials, salt, hashIterations);
System.out.println(simpleHash);
}
} | repos\spring-boot-quick-master\quick-shiro\src\main\java\com\shiro\quick\shiro\realm\MyRealm.java | 1 |
请完成以下Java代码 | public Object getParameterDefaultValue(final IProcessDefaultParameter parameter)
{
if (PARAM_EXTERNAL_SYSTEM_CONFIG_ALBERTA_ID.equals(parameter.getColumnName()))
{
final ImmutableList<ExternalSystemParentConfig> configs = externalSystemConfigDAO.getActiveByType(ExternalSystemType.Alberta);
return configs.size() == 1
? configs.get(0).getChildConfig().getId().getRepoId()
: IProcessDefaultParametersProvider.DEFAULT_VALUE_NOTAVAILABLE;
}
return IProcessDefaultParametersProvider.DEFAULT_VALUE_NOTAVAILABLE;
}
@Override
public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context)
{
final ImmutableList<ExternalSystemParentConfig> configs = externalSystemConfigDAO.getActiveByType(ExternalSystemType.Alberta);
if (configs.size() > 0)
{
return ProcessPreconditionsResolution.accept();
}
return ProcessPreconditionsResolution.reject(msgBL.getTranslatableMsgText(MSG_ERR_PROCESS_NOT_AVAILABLE, ExternalSystemType.Alberta.getValue()));
}
@Override
protected String doIt() throws Exception
{
addLog("Calling with params: externalSystemConfigAlbertaId {}, ignoreSelection {}, orgId {}", externalSystemConfigAlbertaId, ignoreSelection, orgId);
final Set<BPartnerId> bPartnerIdSet = (ignoreSelection ? getAllBPartnerRecords() : getSelectedBPartnerRecords())
.stream()
.map(I_C_BPartner::getC_BPartner_ID)
.map(BPartnerId::ofRepoId)
.collect(ImmutableSet.toImmutableSet());
final OrgId computedOrgId = orgId > 0 ? OrgId.ofRepoId(orgId) : getProcessInfo().getOrgId();
final ExternalSystemAlbertaConfigId albertaConfigId = ExternalSystemAlbertaConfigId.ofRepoId(externalSystemConfigAlbertaId);
final Stream<JsonExternalSystemRequest> requestList = invokeAlbertaService
.streamSyncExternalRequestsForBPartnerIds(bPartnerIdSet, albertaConfigId, getPinstanceId(), computedOrgId); | final ExternalSystemMessageSender externalSystemMessageSender = SpringContextHolder.instance.getBean(ExternalSystemMessageSender.class);
requestList.forEach(externalSystemMessageSender::send);
return JavaProcess.MSG_OK;
}
@NonNull
private List<I_C_BPartner> getAllBPartnerRecords()
{
final IQueryBuilder<I_C_BPartner> bPartnerQuery = queryBL.createQueryBuilder(I_C_BPartner.class)
.addOnlyActiveRecordsFilter();
if (orgId > 0)
{
bPartnerQuery.addEqualsFilter(I_C_BPartner.COLUMNNAME_AD_Org_ID, orgId);
}
return bPartnerQuery.create()
.stream()
.collect(ImmutableList.toImmutableList());
}
@NonNull
private List<I_C_BPartner> getSelectedBPartnerRecords()
{
final IQueryBuilder<I_C_BPartner> bPartnerQuery = retrieveSelectedRecordsQueryBuilder(I_C_BPartner.class);
if (orgId > 0)
{
bPartnerQuery.addEqualsFilter(I_C_BPartner.COLUMNNAME_AD_Org_ID, orgId);
}
return bPartnerQuery.create()
.stream()
.collect(ImmutableList.toImmutableList());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\process\InvokeAlbertaForBPartnerIds.java | 1 |
请完成以下Java代码 | public class XMLFilePropertyMutator implements PropertyMutator {
private final String propertyFileName;
public XMLFilePropertyMutator(String propertyFileName) {
this.propertyFileName = propertyFileName;
}
@Override
public String getProperty(String key) throws IOException {
Properties properties = loadProperties();
return properties.getProperty(key);
}
@Override
public void addOrUpdateProperty(String key, String value) throws IOException {
String filePath = getXMLAppPropertiesWithFileStreamFilePath();
Properties properties = loadProperties(filePath);
try (OutputStream os = Files.newOutputStream(Paths.get(filePath))) {
properties.setProperty(key, value);
properties.storeToXML(os, null);
}
}
private Properties loadProperties() throws IOException {
return loadProperties(getXMLAppPropertiesWithFileStreamFilePath());
}
private Properties loadProperties(String filepath) throws IOException { | Properties props = new Properties();
try (InputStream is = Files.newInputStream(Paths.get(filepath))) {
props.loadFromXML(is);
}
return props;
}
String getXMLAppPropertiesWithFileStreamFilePath() {
URL resourceUrl = getClass().getClassLoader()
.getResource(propertyFileName);
Objects.requireNonNull(resourceUrl, "Property file with name [" + propertyFileName + "] was not found.");
return resourceUrl.getFile();
}
} | repos\tutorials-master\core-java-modules\core-java-properties\src\main\java\com\baeldung\core\java\properties\XMLFilePropertyMutator.java | 1 |
请完成以下Java代码 | protected void rewriteHeaders(ServerWebExchange exchange, Config config) {
final String name = Objects.requireNonNull(config.getName(), "name must not be null");
final HttpHeaders responseHeaders = exchange.getResponse().getHeaders();
if (responseHeaders.get(name) != null) {
List<String> oldValue = Objects.requireNonNull(responseHeaders.get(name), "oldValue must not be null");
List<String> newValue = rewriteHeaders(config, oldValue);
if (newValue != null) {
responseHeaders.put(name, newValue);
}
else {
responseHeaders.remove(name);
}
}
}
protected List<String> rewriteHeaders(Config config, List<String> headers) {
String regexp = Objects.requireNonNull(config.getRegexp(), "regexp must not be null");
String replacement = Objects.requireNonNull(config.getReplacement(), "replacement must not be null");
ArrayList<String> rewrittenHeaders = new ArrayList<>();
for (int i = 0; i < headers.size(); i++) {
String rewriten = rewrite(headers.get(i), regexp, replacement);
rewrittenHeaders.add(rewriten);
}
return rewrittenHeaders;
}
String rewrite(String value, String regexp, String replacement) {
return value.replaceAll(regexp, replacement.replace("$\\", "$"));
}
public static class Config extends AbstractGatewayFilterFactory.NameConfig {
private @Nullable String regexp; | private @Nullable String replacement;
public @Nullable String getRegexp() {
return regexp;
}
public Config setRegexp(String regexp) {
this.regexp = regexp;
return this;
}
public @Nullable String getReplacement() {
return replacement;
}
public Config setReplacement(String replacement) {
this.replacement = replacement;
return this;
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\RewriteResponseHeaderGatewayFilterFactory.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class AlarmsDeletionTaskProcessor extends HousekeeperTaskProcessor<AlarmsDeletionHousekeeperTask> {
private final AlarmService alarmService;
@Override
public void process(AlarmsDeletionHousekeeperTask task) throws Exception {
EntityId entityId = task.getEntityId();
EntityType entityType = entityId.getEntityType();
TenantId tenantId = task.getTenantId();
if (task.getAlarms() == null) {
AlarmId lastId = null;
long lastCreatedTime = 0;
while (true) {
List<TbPair<UUID, Long>> alarms = alarmService.findAlarmIdsByOriginatorId(tenantId, entityId, lastCreatedTime, lastId, 128);
if (alarms.isEmpty()) {
break;
}
housekeeperClient.submitTask(new AlarmsDeletionHousekeeperTask(tenantId, entityId, alarms.stream().map(TbPair::getFirst).toList()));
TbPair<UUID, Long> last = alarms.get(alarms.size() - 1);
lastId = new AlarmId(last.getFirst());
lastCreatedTime = last.getSecond();
log.debug("[{}][{}][{}] Submitted task for deleting {} alarms", tenantId, entityType, entityId, alarms.size()); | }
int count = alarmService.deleteEntityAlarmRecords(tenantId, entityId);
log.debug("[{}][{}][{}] Deleted {} entity alarms", tenantId, entityType, entityId, count);
} else {
for (UUID alarmId : task.getAlarms()) {
alarmService.delAlarm(tenantId, new AlarmId(alarmId));
}
log.debug("[{}][{}][{}] Deleted {} alarms", tenantId, entityType, entityId, task.getAlarms().size());
}
}
@Override
public HousekeeperTaskType getTaskType() {
return HousekeeperTaskType.DELETE_ALARMS;
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\housekeeper\processor\AlarmsDeletionTaskProcessor.java | 2 |
请完成以下Java代码 | public String getOrderByCreateTime() {
return orderByCreateTime;
}
public void setOrderByCreateTime(String orderByCreateTime) {
this.orderByCreateTime = orderByCreateTime;
}
public Boolean getUseCreateTime() {
return useCreateTime;
}
public void setUseCreateTime(Boolean useCreateTime) {
this.useCreateTime = useCreateTime;
}
public Boolean getDisableAutoFetching() {
return disableAutoFetching;
}
public void setDisableAutoFetching(Boolean disableAutoFetching) {
this.disableAutoFetching = disableAutoFetching;
}
public Boolean getDisableBackoffStrategy() {
return disableBackoffStrategy;
}
public void setDisableBackoffStrategy(Boolean disableBackoffStrategy) {
this.disableBackoffStrategy = disableBackoffStrategy;
}
public void fromAnnotation(EnableExternalTaskClient annotation) {
String baseUrl = annotation.baseUrl();
setBaseUrl(isNull(baseUrl) ? null : baseUrl);
int maxTasks = annotation.maxTasks();
setMaxTasks(isNull(maxTasks) ? null : maxTasks);
String workerId = annotation.workerId();
setWorkerId(isNull(workerId) ? null : workerId);
setUsePriority(annotation.usePriority()); | setUseCreateTime(annotation.useCreateTime());
configureOrderByCreateTime(annotation);
long asyncResponseTimeout = annotation.asyncResponseTimeout();
setAsyncResponseTimeout(isNull(asyncResponseTimeout) ? null : asyncResponseTimeout);
setDisableAutoFetching(annotation.disableAutoFetching());
setDisableBackoffStrategy(annotation.disableBackoffStrategy());
long lockDuration = annotation.lockDuration();
setLockDuration(isNull(lockDuration) ? null : lockDuration);
String dateFormat = annotation.dateFormat();
setDateFormat(isNull(dateFormat) ? null : dateFormat);
String serializationFormat = annotation.defaultSerializationFormat();
setDefaultSerializationFormat(isNull(serializationFormat) ? null : serializationFormat);
}
protected void configureOrderByCreateTime(EnableExternalTaskClient annotation) {
if (EnableExternalTaskClient.STRING_NULL_VALUE.equals(annotation.orderByCreateTime())) {
setOrderByCreateTime(null);
} else {
setOrderByCreateTime(annotation.orderByCreateTime());
}
}
protected static boolean isNull(String value) {
return ExternalTaskSubscription.STRING_NULL_VALUE.equals(value);
}
protected static boolean isNull(long value) {
return LONG_NULL_VALUE == value;
}
protected static boolean isNull(int value) {
return INT_NULL_VALUE == value;
}
} | repos\camunda-bpm-platform-master\spring-boot-starter\starter-client\spring\src\main\java\org\camunda\bpm\client\spring\impl\client\ClientConfiguration.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private static class ReturnProductInfoProvider
{
Map<String, I_M_Product> searchKey2Product = new HashMap<>();
Map<String, OrgId> searchKey2Org = new HashMap<>();
IProductDAO productRepo = Services.get(IProductDAO.class);
IOrgDAO orgDAO = Services.get(IOrgDAO.class);
IUOMDAO uomDAO = Services.get(IUOMDAO.class);
private static ReturnProductInfoProvider newInstance()
{
return new ReturnProductInfoProvider();
}
private OrgId getOrgId(@NonNull final String orgCode)
{
return searchKey2Org.computeIfAbsent(orgCode, this::retrieveOrgId);
}
@NonNull
private ProductId getProductId(@NonNull final String productSearchKey)
{
final I_M_Product product = getProductNotNull(productSearchKey);
return ProductId.ofRepoId(product.getM_Product_ID());
}
@NonNull
private I_C_UOM getStockingUOM(@NonNull final String productSearchKey)
{
final I_M_Product product = getProductNotNull(productSearchKey);
return uomDAO.getById(UomId.ofRepoId(product.getC_UOM_ID()));
}
@NonNull
private I_M_Product getProductNotNull(@NonNull final String productSearchKey)
{
final I_M_Product product = searchKey2Product.computeIfAbsent(productSearchKey, this::loadProduct); | if (product == null)
{
throw new AdempiereException("No product could be found for the target search key!")
.appendParametersToMessage()
.setParameter("ProductSearchKey", productSearchKey);
}
return product;
}
private I_M_Product loadProduct(@NonNull final String productSearchKey)
{
return productRepo.retrieveProductByValue(productSearchKey);
}
private OrgId retrieveOrgId(@NonNull final String orgCode)
{
final OrgQuery query = OrgQuery.builder()
.orgValue(orgCode)
.failIfNotExists(true)
.build();
return orgDAO.retrieveOrgIdBy(query).orElseThrow(() -> new AdempiereException("No AD_Org was found for the given search key!")
.appendParametersToMessage()
.setParameter("OrgSearchKey", orgCode));
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\receipt\CustomerReturnRestService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public DmnDeploymentBuilder addDmnModel(String resourceName, DmnDefinition dmnDefinition) {
DmnXMLConverter dmnXMLConverter = new DmnXMLConverter();
String dmn20Xml = new String(dmnXMLConverter.convertToXML(dmnDefinition), StandardCharsets.UTF_8);
addString(resourceName, dmn20Xml);
return this;
}
@Override
public DmnDeploymentBuilder name(String name) {
deployment.setName(name);
return this;
}
@Override
public DmnDeploymentBuilder category(String category) {
deployment.setCategory(category);
return this;
}
@Override
public DmnDeploymentBuilder disableSchemaValidation() {
this.isDmn20XsdValidationEnabled = false;
return this;
}
@Override
public DmnDeploymentBuilder tenantId(String tenantId) {
deployment.setTenantId(tenantId);
return this;
}
@Override
public DmnDeploymentBuilder parentDeploymentId(String parentDeploymentId) {
deployment.setParentDeploymentId(parentDeploymentId); | return this;
}
@Override
public DmnDeploymentBuilder enableDuplicateFiltering() {
isDuplicateFilterEnabled = true;
return this;
}
@Override
public DmnDeployment deploy() {
return repositoryService.deploy(this);
}
// getters and setters
// //////////////////////////////////////////////////////
public DmnDeploymentEntity getDeployment() {
return deployment;
}
public boolean isDmnXsdValidationEnabled() {
return isDmn20XsdValidationEnabled;
}
public boolean isDuplicateFilterEnabled() {
return isDuplicateFilterEnabled;
}
} | repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\repository\DmnDeploymentBuilderImpl.java | 2 |
请完成以下Java代码 | public void setM_QualityInsp_LagerKonf_ID (int M_QualityInsp_LagerKonf_ID)
{
if (M_QualityInsp_LagerKonf_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_QualityInsp_LagerKonf_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_QualityInsp_LagerKonf_ID, Integer.valueOf(M_QualityInsp_LagerKonf_ID));
}
/** Get Lagerkonferenz.
@return Lagerkonferenz */
@Override
public int getM_QualityInsp_LagerKonf_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_QualityInsp_LagerKonf_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/ | @Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java-gen\de\metas\materialtracking\ch\lagerkonf\model\X_M_QualityInsp_LagerKonf.java | 1 |
请完成以下Java代码 | public Date getTriggerDay() {
return triggerDay;
}
public void setTriggerDay(Date triggerDay) {
this.triggerDay = triggerDay;
}
public int getRunningCount() {
return runningCount;
}
public void setRunningCount(int runningCount) {
this.runningCount = runningCount;
} | public int getSucCount() {
return sucCount;
}
public void setSucCount(int sucCount) {
this.sucCount = sucCount;
}
public int getFailCount() {
return failCount;
}
public void setFailCount(int failCount) {
this.failCount = failCount;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\core\model\XxlJobLogReport.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.