instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public boolean hasNext()
{
while (!closed)
{
if (currentChildScanner == null)
{
currentChildScanner = retrieveNextChildScriptScanner();
}
if (currentChildScanner == null)
{
closed = true;
return false;
}
if (currentChildScanner.hasNext())
{
return true;
}
else
{
currentChildScanner = null; | }
}
return false;
}
@Override
public IScript next()
{
if (!hasNext())
{
throw new NoSuchElementException();
}
return currentChildScanner.next();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.base\src\main\java\de\metas\migration\scanner\impl\AbstractRecursiveScriptScanner.java | 1 |
请完成以下Java代码 | public String toString()
{
return MoreObjects.toStringHelper(this)
.add("AD_Column_ID", getAD_Column_ID())
.add("ColumnName", getColumnName())
.toString();
}
@Deprecated
public static int getColumn_ID(String TableName, String columnName)
{
int m_table_id = MTable.getTable_ID(TableName);
if (m_table_id == 0)
return 0;
int retValue = 0;
String SQL = "SELECT AD_Column_ID FROM AD_Column WHERE AD_Table_ID = ? AND columnname = ?";
try
{
PreparedStatement pstmt = DB.prepareStatement(SQL, null);
pstmt.setInt(1, m_table_id);
pstmt.setString(2, columnName);
ResultSet rs = pstmt.executeQuery();
if (rs.next())
retValue = rs.getInt(1);
rs.close();
pstmt.close();
}
catch (SQLException e)
{
s_log.error(SQL, e);
retValue = -1;
}
return retValue;
}
// end vpj-cd e-evolution
/** | * Get Table Id for a column
*
* @param ctx context
* @param AD_Column_ID id
* @param trxName transaction
* @return MColumn
*/
public static int getTable_ID(Properties ctx, int AD_Column_ID, String trxName)
{
final String sqlStmt = "SELECT AD_Table_ID FROM AD_Column WHERE AD_Column_ID=?";
return DB.getSQLValue(trxName, sqlStmt, AD_Column_ID);
}
public static boolean isSuggestSelectionColumn(String columnName, boolean caseSensitive)
{
if (columnName == null || Check.isBlank(columnName))
return false;
//
if (columnName.equals("Value") || (!caseSensitive && columnName.equalsIgnoreCase("Value")))
return true;
else if (columnName.equals("Name") || (!caseSensitive && columnName.equalsIgnoreCase("Name")))
return true;
else if (columnName.equals("DocumentNo") || (!caseSensitive && columnName.equalsIgnoreCase("DocumentNo")))
return true;
else if (columnName.equals("Description") || (!caseSensitive && columnName.equalsIgnoreCase("Description")))
return true;
else if (columnName.contains("Name") || (!caseSensitive && columnName.toUpperCase().contains("Name".toUpperCase())))
return true;
else if(columnName.equals("DocStatus") || (!caseSensitive && columnName.equalsIgnoreCase("DocStatus")))
return true;
else
return false;
}
} // MColumn | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MColumn.java | 1 |
请完成以下Java代码 | private InOutId extractSingleSelectedInOutId(final @NonNull IProcessPreconditionsContext context)
{
return InOutId.ofRepoIdOrNull(context.getSingleSelectedRecordId());
}
@Override
protected final String doIt() throws Exception
{
countExported = 0;
countErrors = 0;
retrieveValidSelectedDocuments().forEach(this::performNestedProcessInvocation);
if (countExported > 0 && countErrors == 0)
{
return MSG_OK;
}
return MSG_Error + Services.get(IMsgBL.class).getMsg(getCtx(), errorMsg, new Object[] { countExported, countErrors });
}
private void performNestedProcessInvocation(@NonNull final InOutId inOutId)
{
final StringBuilder logMessage = new StringBuilder("Export M_InOut_ID={} ==>").append(inOutId.getRepoId());
try
{
final ProcessExecutor processExecutor = ProcessInfo
.builder()
.setProcessCalledFrom(getProcessInfo().getProcessCalledFrom())
.setAD_ProcessByClassname(M_InOut_EDI_Export_JSON.class.getName())
.addParameter(PARAM_M_InOut_ID, inOutId.getRepoId())
.setRecord(I_M_InOut.Table_Name, inOutId.getRepoId()) // will be stored in the AD_Pinstance
.buildAndPrepareExecution()
.executeSync();
final ProcessExecutionResult result = processExecutor.getResult();
final String summary = result.getSummary();
if (MSG_OK.equals(summary))
countExported++;
else
countErrors++; | logMessage.append("AD_PInstance_ID=").append(PInstanceId.toRepoId(processExecutor.getProcessInfo().getPinstanceId()))
.append("; Summary=").append(summary);
}
catch (final Exception e)
{
final AdIssueId issueId = errorManager.createIssue(e);
logMessage
.append("Failed with AD_Issue_ID=").append(issueId.getRepoId())
.append("; Exception: ").append(e.getMessage());
countErrors++;
}
finally
{
addLog(logMessage.toString());
}
}
@NonNull
private Stream<InOutId> retrieveValidSelectedDocuments()
{
return createSelectedInvoicesQueryBuilder()
.addOnlyActiveRecordsFilter()
.addEqualsFilter(org.compiere.model.I_M_InOut.COLUMNNAME_IsSOTrx, true)
.addEqualsFilter(org.compiere.model.I_M_InOut.COLUMNNAME_DocStatus, I_M_InOut.DOCSTATUS_Completed)
.addEqualsFilter(I_M_InOut.COLUMNNAME_IsEdiEnabled, true)
.addEqualsFilter(I_M_InOut.COLUMNNAME_EDI_ExportStatus, I_EDI_Document.EDI_EXPORTSTATUS_Pending)
.create()
.iterateAndStreamIds(InOutId::ofRepoId);
}
private IQueryBuilder<I_M_InOut> createSelectedInvoicesQueryBuilder()
{
return queryBL
.createQueryBuilder(I_M_InOut.class)
.filter(getProcessInfo().getQueryFilterOrElseFalse());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\process\export\json\M_InOut_Selection_Export_JSON.java | 1 |
请完成以下Java代码 | public class C_Dunning_Candidate
{
public static final String POATTR_CallerPO = C_Dunning_Candidate.class + "#CallerPO";
@ModelChange(timings = ModelValidator.TYPE_AFTER_CHANGE
, ifColumnsChanged = I_C_Dunning_Candidate.COLUMNNAME_DunningGrace)
public void setDunningGraceOnInvoice(final I_C_Dunning_Candidate candidate)
{
if (candidate.getAD_Table_ID() != InterfaceWrapperHelper.getTableId(I_C_Invoice.class))
{
return;
}
final Properties ctx = InterfaceWrapperHelper.getCtx(candidate);
final String trxName = InterfaceWrapperHelper.getTrxName(candidate);
final I_C_Invoice invoice = InterfaceWrapperHelper.create(ctx, candidate.getRecord_ID(), I_C_Invoice.class, trxName);
invoice.setDunningGrace(candidate.getDunningGrace());
InterfaceWrapperHelper.setDynAttribute(invoice, POATTR_CallerPO, candidate);
InterfaceWrapperHelper.save(invoice);
}
@ModelChange(timings = ModelValidator.TYPE_AFTER_CHANGE | , ifColumnsChanged = I_C_Dunning_Candidate.COLUMNNAME_IsDunningDocProcessed)
public void setDunningLevelOnInvoice(final I_C_Dunning_Candidate candidate)
{
if (candidate.getAD_Table_ID() != InterfaceWrapperHelper.getTableId(I_C_Invoice.class)
|| !candidate.isDunningDocProcessed())
{
return;
}
final Properties ctx = InterfaceWrapperHelper.getCtx(candidate);
final String trxName = InterfaceWrapperHelper.getTrxName(candidate);
final I_C_Invoice invoice = InterfaceWrapperHelper.create(ctx, candidate.getRecord_ID(), I_C_Invoice.class, trxName);
invoice.setC_DunningLevel(candidate.getC_DunningLevel());
InterfaceWrapperHelper.save(invoice);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\invoice\model\validator\C_Dunning_Candidate.java | 1 |
请完成以下Java代码 | public BigDecimal getQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Service date.
@param ServiceDate
Date service was provided
*/
public void setServiceDate (Timestamp ServiceDate)
{
set_Value (COLUMNNAME_ServiceDate, ServiceDate);
}
/** Get Service date.
@return Date service was provided
*/
public Timestamp getServiceDate ()
{
return (Timestamp)get_Value(COLUMNNAME_ServiceDate);
}
/** Set Text Message.
@param TextMsg
Text Message
*/
public void setTextMsg (String TextMsg)
{
set_Value (COLUMNNAME_TextMsg, TextMsg);
}
/** Get Text Message.
@return Text Message
*/
public String getTextMsg ()
{
return (String)get_Value(COLUMNNAME_TextMsg);
}
public I_C_ElementValue getUser1() throws RuntimeException
{
return (I_C_ElementValue)MTable.get(getCtx(), I_C_ElementValue.Table_Name)
.getPO(getUser1_ID(), get_TrxName()); }
/** Set User List 1.
@param User1_ID
User defined list element #1
*/
public void setUser1_ID (int User1_ID)
{
if (User1_ID < 1)
set_Value (COLUMNNAME_User1_ID, null);
else
set_Value (COLUMNNAME_User1_ID, Integer.valueOf(User1_ID));
}
/** Get User List 1.
@return User defined list element #1
*/
public int getUser1_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_User1_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_C_ElementValue getUser2() throws RuntimeException
{
return (I_C_ElementValue)MTable.get(getCtx(), I_C_ElementValue.Table_Name)
.getPO(getUser2_ID(), get_TrxName()); }
/** Set User List 2.
@param User2_ID
User defined list element #2
*/
public void setUser2_ID (int User2_ID) | {
if (User2_ID < 1)
set_Value (COLUMNNAME_User2_ID, null);
else
set_Value (COLUMNNAME_User2_ID, Integer.valueOf(User2_ID));
}
/** Get User List 2.
@return User defined list element #2
*/
public int getUser2_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_User2_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Valid from.
@param ValidFrom
Valid from including this date (first day)
*/
public void setValidFrom (Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
/** Get Valid from.
@return Valid from including this date (first day)
*/
public Timestamp getValidFrom ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidFrom);
}
/** Set Valid to.
@param ValidTo
Valid to including this date (last day)
*/
public void setValidTo (Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
/** Get Valid to.
@return Valid to including this date (last day)
*/
public Timestamp getValidTo ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidTo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_Movement.java | 1 |
请完成以下Java代码 | private Resource getWorkstationById(final ResourceId workstationId)
{
final Resource workstation = resourceService.getById(workstationId);
assertWorkstation(workstation);
return workstation;
}
private static void assertWorkstation(final Resource workstation)
{
if (!workstation.isWorkstation())
{
throw new AdempiereException("Not a workstation QR Code");
}
}
private JsonWorkstation toJson(final Resource workstation)
{
final ResourceId workstationId = workstation.getResourceId();
final WorkplaceId workplaceId = workstation.getWorkplaceId();
final String workplaceName = workplaceId != null ? workplaceService.getById(workplaceId).getName() : null;
return JsonWorkstation.builder()
.id(workstationId)
.name(workstation.getName())
.qrCode(workstation.toQrCode().toGlobalQRCodeJsonString())
.workplaceName(workplaceName)
.isUserAssigned(userWorkstationService.isUserAssigned(Env.getLoggedUserId(), workstationId))
.build();
}
@GetMapping
public JsonWorkstationSettings getStatus()
{
return JsonWorkstationSettings.builder()
.assignedWorkstation(userWorkstationService.getUserWorkstationId(Env.getLoggedUserId())
.map(resourceService::getById)
.map(this::toJson)
.orElse(null))
.build();
}
@PostMapping("/assign")
public JsonWorkstation assign(@RequestBody @NonNull final JsonAssignWorkstationRequest request) | {
final Resource workstation = getWorkstationById(request.getWorkstationIdEffective());
final UserId loggedUserId = Env.getLoggedUserId();
userWorkstationService.assign(loggedUserId, workstation.getResourceId());
Optional.ofNullable(workstation.getWorkplaceId())
.ifPresent(workplaceId -> workplaceService.assignWorkplace(loggedUserId, workplaceId));
return toJson(workstation);
}
@PostMapping("/byQRCode")
public JsonWorkstation getWorkstationByQRCode(@RequestBody @NonNull final JsonGetWorkstationByQRCodeRequest request)
{
final ResourceQRCode qrCode = ResourceQRCode.ofGlobalQRCodeJsonString(request.getQrCode());
final Resource workstation = getWorkstationById(qrCode.getResourceId());
return toJson(workstation);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\workstation\WorkstationRestController.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public long getMinEvictableIdleTimeMillis() {
return minEvictableIdleTimeMillis;
}
public void setMinEvictableIdleTimeMillis(long minEvictableIdleTimeMillis) {
this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
}
public long getMaxEvictableIdleTimeMillis() {
return maxEvictableIdleTimeMillis;
}
public void setMaxEvictableIdleTimeMillis(long maxEvictableIdleTimeMillis) {
this.maxEvictableIdleTimeMillis = maxEvictableIdleTimeMillis;
}
public String getValidationQuery() {
return validationQuery;
}
public void setValidationQuery(String validationQuery) {
this.validationQuery = validationQuery;
}
public boolean isTestWhileIdle() {
return testWhileIdle;
}
public void setTestWhileIdle(boolean testWhileIdle) {
this.testWhileIdle = testWhileIdle;
}
public boolean isTestOnBorrow() {
return testOnBorrow;
}
public void setTestOnBorrow(boolean testOnBorrow) {
this.testOnBorrow = testOnBorrow;
}
public boolean isTestOnReturn() {
return testOnReturn;
}
public void setTestOnReturn(boolean testOnReturn) {
this.testOnReturn = testOnReturn;
}
public boolean isPoolPreparedStatements() { | return poolPreparedStatements;
}
public void setPoolPreparedStatements(boolean poolPreparedStatements) {
this.poolPreparedStatements = poolPreparedStatements;
}
public String getFilters() {
return filters;
}
public void setFilters(String filters) {
this.filters = filters;
}
public String getConnectionProperties() {
return connectionProperties;
}
public void setConnectionProperties(String connectionProperties) {
this.connectionProperties = connectionProperties;
}
} | repos\spring-boot-leaning-master\2.x_42_courses\第 3-7 课: Spring Boot 集成 Druid 监控数据源\spring-boot-multi-Jpa-druid\src\main\java\com\neo\config\druid\DruidConfig.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public String buildAccountNo() {
String accountNo = ACCOUNT_NO_PREFIX + IdWorker.getId();
return accountNo;
}
/**
* 获取支付流水号
**/
@Override
public String buildTrxNo() {
String trxNo = TRX_NO_PREFIX + IdWorker.getId();
return trxNo;
}
/** | * 获取银行订单号
**/
@Override
public String buildBankOrderNo() {
String bankOrderNo = BANK_ORDER_NO_PREFIX + IdWorker.getId();
return bankOrderNo;
}
/** 获取对账批次号 **/
public String buildReconciliationNo() {
String batchNo = RECONCILIATION_BATCH_NO + IdWorker.getId();
return batchNo;
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\user\service\impl\BuildNoServiceImpl.java | 2 |
请完成以下Java代码 | public List<ChartOfAccounts> getByIds(final Set<ChartOfAccountsId> chartOfAccountsIds)
{
return getMap().getByIds(chartOfAccountsIds);
}
public Optional<ChartOfAccounts> getByName(@NonNull final String chartOfAccountsName, @NonNull final ClientId clientId, @NonNull final OrgId orgId)
{
return getMap().getByName(chartOfAccountsName, clientId, orgId);
}
public Optional<ChartOfAccounts> getByTreeId(@NonNull final AdTreeId treeId)
{
return getMap().getByTreeId(treeId);
}
ChartOfAccounts createChartOfAccounts(
@NonNull final String name, | @NonNull final ClientId clientId,
@NonNull final OrgId orgId,
@NonNull final AdTreeId chartOfAccountsTreeId)
{
final I_C_Element record = InterfaceWrapperHelper.newInstance(I_C_Element.class);
InterfaceWrapperHelper.setValue(record, I_C_Element.COLUMNNAME_AD_Client_ID, clientId.getRepoId());
record.setAD_Org_ID(orgId.getRepoId());
record.setName(name);
record.setAD_Tree_ID(chartOfAccountsTreeId.getRepoId());
record.setElementType(X_C_Element.ELEMENTTYPE_Account);
record.setIsNaturalAccount(true);
InterfaceWrapperHelper.save(record);
return fromRecord(record);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\elementvalue\ChartOfAccountsRepository.java | 1 |
请完成以下Java代码 | public String getProtocol() {
return (!StringUtils.hasText(protocol)) ? DEFAULT_PROTOCOL : protocol;
}
@Override
public SslManagerBundle getManagers() {
return managersToUse;
}
@Override
public String toString() {
ToStringCreator creator = new ToStringCreator(this);
creator.append("key", getKey());
creator.append("options", getOptions());
creator.append("protocol", getProtocol());
creator.append("stores", getStores());
return creator.toString();
}
};
}
/**
* Factory method to create a new {@link SslBundle} which uses the system defaults.
* @return a new {@link SslBundle} instance
* @since 3.5.0
*/
static SslBundle systemDefault() {
try {
KeyManagerFactory keyManagerFactory = KeyManagerFactory
.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(null, null);
TrustManagerFactory trustManagerFactory = TrustManagerFactory
.getInstance(TrustManagerFactory.getDefaultAlgorithm()); | trustManagerFactory.init((KeyStore) null);
SSLContext sslContext = SSLContext.getDefault();
return of(null, null, null, null, new SslManagerBundle() {
@Override
public KeyManagerFactory getKeyManagerFactory() {
return keyManagerFactory;
}
@Override
public TrustManagerFactory getTrustManagerFactory() {
return trustManagerFactory;
}
@Override
public SSLContext createSslContext(String protocol) {
return sslContext;
}
});
}
catch (NoSuchAlgorithmException | KeyStoreException | UnrecoverableKeyException ex) {
throw new IllegalStateException("Could not initialize system default SslBundle: " + ex.getMessage(), ex);
}
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\ssl\SslBundle.java | 1 |
请完成以下Java代码 | public static ProductASIDescription ofString(final String value)
{
if (value == null)
{
return NONE;
}
final String valueNorm = value.trim();
if (valueNorm.isEmpty())
{
return NONE;
}
return new ProductASIDescription(valueNorm);
}
public static final ProductASIDescription NONE = new ProductASIDescription(""); | private final String value;
private ProductASIDescription(@NonNull final String value)
{
this.value = value;
}
@Override
@JsonValue
public String toString()
{
return value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\products_proposal\model\ProductASIDescription.java | 1 |
请完成以下Java代码 | protected void writeAdditionalAttributes(BaseElement element, BpmnModel model, XMLStreamWriter xtw)
throws Exception {
ValuedDataObject dataObject = (ValuedDataObject) element;
if (
dataObject.getItemSubjectRef() != null &&
StringUtils.isNotEmpty(dataObject.getItemSubjectRef().getStructureRef())
) {
writeDefaultAttribute(ATTRIBUTE_DATA_ITEM_REF, dataObject.getItemSubjectRef().getStructureRef(), xtw);
}
}
@Override
protected boolean writeExtensionChildElements(
BaseElement element,
boolean didWriteExtensionStartElement,
XMLStreamWriter xtw
) throws Exception {
ValuedDataObject dataObject = (ValuedDataObject) element;
if (StringUtils.isNotEmpty(dataObject.getId()) && dataObject.getValue() != null) {
if (!didWriteExtensionStartElement) {
xtw.writeStartElement(ELEMENT_EXTENSIONS);
didWriteExtensionStartElement = true;
}
xtw.writeStartElement(ACTIVITI_EXTENSIONS_PREFIX, ELEMENT_DATA_VALUE, ACTIVITI_EXTENSIONS_NAMESPACE);
if (dataObject.getValue() != null) {
String value = null;
if (dataObject instanceof DateDataObject) {
value = sdf.format(dataObject.getValue());
} else {
value = dataObject.getValue().toString(); | }
if (dataObject instanceof StringDataObject && xmlChars.matcher(value).find()) {
xtw.writeCData(value);
} else {
xtw.writeCharacters(value);
}
}
xtw.writeEndElement();
}
return didWriteExtensionStartElement;
}
@Override
protected void writeAdditionalChildElements(BaseElement element, BpmnModel model, XMLStreamWriter xtw)
throws Exception {}
} | repos\Activiti-develop\activiti-core\activiti-bpmn-converter\src\main\java\org\activiti\bpmn\converter\ValuedDataObjectXMLConverter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public TaskBuilder tenantId(String tenantId) {
this.tenantId = tenantId;
return this;
}
@Override
public TaskBuilder formKey(String formKey) {
this.formKey = formKey;
return this;
}
@Override
public TaskBuilder taskDefinitionId(String taskDefinitionId) {
this.taskDefinitionId = taskDefinitionId;
return this;
}
@Override
public TaskBuilder taskDefinitionKey(String taskDefinitionKey) {
this.taskDefinitionKey = taskDefinitionKey;
return this;
}
@Override
public TaskBuilder identityLinks(Set<? extends IdentityLinkInfo> identityLinks) {
this.identityLinks = identityLinks;
return this;
}
@Override
public TaskBuilder scopeId(String scopeId) {
this.scopeId = scopeId;
return this;
}
@Override
public TaskBuilder scopeType(String scopeType) {
this.scopeType = scopeType;
return this;
}
@Override
public String getId() {
return id;
}
@Override
public String getName() {
return name;
}
@Override
public String getDescription() {
return description;
}
@Override
public int getPriority() {
return priority;
}
@Override
public String getOwner() {
return ownerId;
}
@Override
public String getAssignee() {
return assigneeId;
}
@Override
public String getTaskDefinitionId() {
return taskDefinitionId;
}
@Override
public String getTaskDefinitionKey() { | return taskDefinitionKey;
}
@Override
public Date getDueDate() {
return dueDate;
}
@Override
public String getCategory() {
return category;
}
@Override
public String getParentTaskId() {
return parentTaskId;
}
@Override
public String getTenantId() {
return tenantId;
}
@Override
public String getFormKey() {
return formKey;
}
@Override
public Set<? extends IdentityLinkInfo> getIdentityLinks() {
return identityLinks;
}
@Override
public String getScopeId() {
return this.scopeId;
}
@Override
public String getScopeType() {
return this.scopeType;
}
} | repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\BaseTaskBuilderImpl.java | 2 |
请完成以下Java代码 | public static ImmutableList<DeviceConfig> getAllDevices()
{
return staticState.getAllDevices();
}
public static void addDevice(@NonNull final DummyDeviceAddRequest request)
{
final DeviceConfig device = DeviceConfig.builder(request.getDeviceName())
.setAssignedAttributeCodes(request.getAssignedAttributeCodes())
.setDeviceClassname(DummyDevice.class.getName())
.setParameterValueSupplier(DummyDeviceConfigPool::getDeviceParamValue)
.setRequestClassnamesSupplier(DummyDeviceConfigPool::getDeviceRequestClassnames)
.setAssignedWarehouseIds(request.getOnlyWarehouseIds())
.build();
staticState.addDevice(device);
logger.info("Added device: {}", device);
}
public static void removeDeviceByName(@NonNull final String deviceName)
{
staticState.removeDeviceByName(deviceName);
}
private static String getDeviceParamValue(final String deviceName, final String parameterName, final String defaultValue)
{
return defaultValue;
}
private static Set<String> getDeviceRequestClassnames(final String deviceName, final AttributeCode attributeCode)
{
return DummyDevice.getDeviceRequestClassnames();
}
public static DummyDeviceResponse generateRandomResponse()
{
final BigDecimal value = NumberUtils.randomBigDecimal(responseMinValue, responseMaxValue, 3);
return new DummyDeviceResponse(value);
}
//
//
//
//
//
private static class StaticStateHolder
{
private final HashMap<String, DeviceConfig> devicesByName = new HashMap<>(); | private final ArrayListMultimap<AttributeCode, DeviceConfig> devicesByAttributeCode = ArrayListMultimap.create();
public synchronized void addDevice(final DeviceConfig device)
{
final String deviceName = device.getDeviceName();
final DeviceConfig existingDevice = removeDeviceByName(deviceName);
devicesByName.put(deviceName, device);
device.getAssignedAttributeCodes()
.forEach(attributeCode -> devicesByAttributeCode.put(attributeCode, device));
logger.info("addDevice: {} -> {}", existingDevice, device);
}
public synchronized @Nullable DeviceConfig removeDeviceByName(@NonNull final String deviceName)
{
final DeviceConfig existingDevice = devicesByName.remove(deviceName);
if (existingDevice != null)
{
existingDevice.getAssignedAttributeCodes()
.forEach(attributeCode -> devicesByAttributeCode.remove(attributeCode, existingDevice));
}
return existingDevice;
}
public synchronized ImmutableList<DeviceConfig> getAllDevices()
{
return ImmutableList.copyOf(devicesByName.values());
}
public synchronized ImmutableList<DeviceConfig> getDeviceConfigsForAttributeCode(@NonNull final AttributeCode attributeCode)
{
return ImmutableList.copyOf(devicesByAttributeCode.get(attributeCode));
}
public ImmutableSet<AttributeCode> getAllAttributeCodes()
{
return ImmutableSet.copyOf(devicesByAttributeCode.keySet());
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.device.adempiere\src\main\java\de\metas\device\dummy\DummyDeviceConfigPool.java | 1 |
请完成以下Java代码 | public final class WorkflowLauncherId
{
private static final Joiner JOINER = Joiner.on("$");
private static final Splitter SPLITTER = Splitter.on("$");
public static WorkflowLauncherId ofParts(
@NonNull final MobileApplicationId applicationId,
final Object... parts)
{
if (parts == null || parts.length <= 0)
{
throw new AdempiereException("more than one part is required");
}
return new WorkflowLauncherId(
applicationId,
Stream.of(parts)
.map(part -> part != null ? part.toString() : "")
.collect(ImmutableList.toImmutableList()));
}
@JsonCreator
public static WorkflowLauncherId ofString(@NonNull final String stringRepresentation)
{
MobileApplicationId applicationId = null;
final ImmutableList.Builder<String> parts = ImmutableList.builder();
for (final String part : SPLITTER.split(stringRepresentation))
{
if (applicationId == null)
{
applicationId = MobileApplicationId.ofString(part);
}
else
{
parts.add(part);
}
}
if (applicationId == null)
{
throw new AdempiereException("Invalid string: " + stringRepresentation);
}
final WorkflowLauncherId result = new WorkflowLauncherId(applicationId, parts.build());
result._stringRepresentation = stringRepresentation; | return result;
}
@Getter
private final MobileApplicationId applicationId;
private final ImmutableList<String> parts;
private String _stringRepresentation;
private WorkflowLauncherId(
@NonNull final MobileApplicationId applicationId,
@NonNull final ImmutableList<String> parts)
{
this.applicationId = applicationId;
this.parts = parts;
}
@Override
@Deprecated
public String toString()
{
return getAsString();
}
@JsonValue
public String getAsString()
{
String stringRepresentation = _stringRepresentation;
if (stringRepresentation == null)
{
_stringRepresentation = stringRepresentation = JOINER
.join(Iterables.concat(
ImmutableList.of(applicationId.getAsString()),
parts));
}
return stringRepresentation;
}
public String getPartAsString(final int index)
{
return parts.get(index);
}
public Integer getPartAsInt(final int index)
{
return NumberUtils.asIntegerOrNull(getPartAsString(index));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.workflow.rest-api\src\main\java\de\metas\workflow\rest_api\model\WorkflowLauncherId.java | 1 |
请完成以下Java代码 | public int run(boolean waitForProcess, Collection<String> args, Map<String, String> environmentVariables)
throws IOException {
ProcessBuilder builder = new ProcessBuilder(this.command);
builder.directory(this.workingDirectory);
builder.command().addAll(args);
builder.environment().putAll(environmentVariables);
builder.redirectErrorStream(true);
builder.inheritIO();
try {
Process process = builder.start();
this.process = process;
SignalUtils.attachSignalHandler(this::handleSigInt);
if (waitForProcess) {
try {
return process.waitFor();
}
catch (InterruptedException ex) {
Thread.currentThread().interrupt();
return 1;
}
}
return 5;
}
finally {
if (waitForProcess) {
this.endTime = System.currentTimeMillis();
this.process = null;
}
}
}
/**
* Return the running process.
* @return the process or {@code null}
*/
public @Nullable Process getRunningProcess() {
return this.process;
}
/**
* Return if the process was stopped.
* @return {@code true} if stopped
*/
public boolean handleSigInt() {
if (allowChildToHandleSigInt()) {
return true;
}
return doKill();
}
private boolean allowChildToHandleSigInt() {
Process process = this.process;
if (process == null) {
return true;
}
long end = System.currentTimeMillis() + 5000;
while (System.currentTimeMillis() < end) {
if (!process.isAlive()) {
return true;
}
try {
Thread.sleep(500);
} | catch (InterruptedException ex) {
Thread.currentThread().interrupt();
return false;
}
}
return false;
}
/**
* Kill this process.
*/
public void kill() {
doKill();
}
private boolean doKill() {
// destroy the running process
Process process = this.process;
if (process != null) {
try {
process.destroy();
process.waitFor();
this.process = null;
return true;
}
catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
return false;
}
public boolean hasJustEnded() {
return System.currentTimeMillis() < (this.endTime + JUST_ENDED_LIMIT);
}
} | repos\spring-boot-4.0.1\loader\spring-boot-loader-tools\src\main\java\org\springframework\boot\loader\tools\RunProcess.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void insertBookBatch(Book book) {
StringBuilder sb = new StringBuilder("BEGIN BATCH ").append("INSERT INTO ").append(TABLE_NAME).append("(id, title, author, subject) ").append("VALUES (").append(book.getId()).append(", '").append(book.getTitle()).append("', '").append(book.getAuthor())
.append("', '").append(book.getSubject()).append("');").append("INSERT INTO ").append(TABLE_NAME_BY_TITLE).append("(id, title) ").append("VALUES (").append(book.getId()).append(", '").append(book.getTitle()).append("');")
.append("APPLY BATCH;");
final String query = sb.toString();
session.execute(query);
}
/**
* Select book by id.
*
* @return
*/
public Book selectByTitle(String title) {
StringBuilder sb = new StringBuilder("SELECT * FROM ").append(TABLE_NAME_BY_TITLE).append(" WHERE title = '").append(title).append("';");
final String query = sb.toString();
ResultSet rs = session.execute(query);
List<Book> books = new ArrayList<Book>();
for (Row r : rs) {
Book s = new Book(r.getUUID("id"), r.getString("title"), null, null);
books.add(s);
}
return books.get(0);
}
/**
* Select all books from books
*
* @return
*/
public List<Book> selectAll() {
StringBuilder sb = new StringBuilder("SELECT * FROM ").append(TABLE_NAME);
final String query = sb.toString();
ResultSet rs = session.execute(query);
List<Book> books = new ArrayList<Book>();
for (Row r : rs) {
Book book = new Book(r.getUUID("id"), r.getString("title"), r.getString("author"), r.getString("subject"));
books.add(book);
}
return books;
}
/**
* Select all books from booksByTitle
* @return | */
public List<Book> selectAllBookByTitle() {
StringBuilder sb = new StringBuilder("SELECT * FROM ").append(TABLE_NAME_BY_TITLE);
final String query = sb.toString();
ResultSet rs = session.execute(query);
List<Book> books = new ArrayList<Book>();
for (Row r : rs) {
Book book = new Book(r.getUUID("id"), r.getString("title"), null, null);
books.add(book);
}
return books;
}
/**
* Delete a book by title.
*/
public void deletebookByTitle(String title) {
StringBuilder sb = new StringBuilder("DELETE FROM ").append(TABLE_NAME_BY_TITLE).append(" WHERE title = '").append(title).append("';");
final String query = sb.toString();
session.execute(query);
}
/**
* Delete table.
*
* @param tableName the name of the table to delete.
*/
public void deleteTable(String tableName) {
StringBuilder sb = new StringBuilder("DROP TABLE IF EXISTS ").append(tableName);
final String query = sb.toString();
session.execute(query);
}
} | repos\tutorials-master\persistence-modules\java-cassandra\src\main\java\com\baeldung\cassandra\java\client\repository\BookRepository.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class PackageablesView_OpenProductsToPick extends PackageablesViewBasedProcess
{
@Autowired
private ProductsToPickViewFactory productsToPickViewFactory;
@Autowired
private ShipmentScheduleLockRepository locksRepo;
@Override
protected ProcessPreconditionsResolution checkPreconditionsApplicable()
{
return checkPreconditionsApplicable_SingleSelectedRow()
.and(this::acceptIfRowNotLockedByOtherUser);
}
private ProcessPreconditionsResolution acceptIfRowNotLockedByOtherUser()
{
final PackageableRow row = getSingleSelectedRow();
if (row.isNotLocked() || row.isLockedBy(getLoggedUserId()))
{
return ProcessPreconditionsResolution.accept();
}
else
{
return ProcessPreconditionsResolution.rejectWithInternalReason("row is locked by other users");
}
}
@Override
protected String doIt()
{
final PackageableRow row = getSingleSelectedRow(); | final ShipmentScheduleLockRequest lockRequest = createLockRequest(row);
locksRepo.lock(lockRequest);
try
{
final ProductsToPickView productsToPickView = productsToPickViewFactory.createView(row);
getResult().setWebuiViewToOpen(WebuiViewToOpen.builder()
.target(ViewOpenTarget.ModalOverlay)
.viewId(productsToPickView.getViewId().toJson())
.build());
return MSG_OK;
}
catch (final Exception ex)
{
locksRepo.unlockNoFail(ShipmentScheduleUnLockRequest.of(lockRequest));
throw AdempiereException.wrapIfNeeded(ex);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingV2\packageable\process\PackageablesView_OpenProductsToPick.java | 2 |
请完成以下Java代码 | public boolean isEmpty() {return set.isEmpty();}
public Set<WarehouseId> getWarehouseFromIds() {return getValues(DistributionFacetGroupType.WAREHOUSE_FROM, DistributionFacetId::getWarehouseId);}
public Set<WarehouseId> getWarehouseToIds() {return getValues(DistributionFacetGroupType.WAREHOUSE_TO, DistributionFacetId::getWarehouseId);}
public Set<OrderId> getSalesOrderIds() {return getValues(DistributionFacetGroupType.SALES_ORDER, DistributionFacetId::getSalesOrderId);}
public Set<PPOrderId> getManufacturingOrderIds() {return getValues(DistributionFacetGroupType.MANUFACTURING_ORDER_NO, DistributionFacetId::getManufacturingOrderId);}
public Set<LocalDate> getDatesPromised() {return getValues(DistributionFacetGroupType.DATE_PROMISED, DistributionFacetId::getDatePromised);}
public Set<ProductId> getProductIds() {return getValues(DistributionFacetGroupType.PRODUCT, DistributionFacetId::getProductId);}
public Set<Quantity> getQuantities() {return getValues(DistributionFacetGroupType.QUANTITY, DistributionFacetId::getQty);} | public Set<ResourceId> getPlantIds() {return getValues(DistributionFacetGroupType.PLANT_RESOURCE_ID, DistributionFacetId::getPlantId);}
public <T> Set<T> getValues(DistributionFacetGroupType groupType, Function<DistributionFacetId, T> valueExtractor)
{
if (set.isEmpty())
{
return ImmutableSet.of();
}
return set.stream()
.filter(facetId -> facetId.getGroup().equals(groupType))
.map(valueExtractor)
.collect(ImmutableSet.toImmutableSet());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\launchers\facets\DistributionFacetIdsCollection.java | 1 |
请完成以下Java代码 | public String getAttributeValueType()
{
return X_M_Attribute.ATTRIBUTEVALUETYPE_List;
}
/**
* @return <code>false</code>, because ADR is a List attribute.
*/
@Override
public boolean canGenerateValue(final Properties ctx, final IAttributeSet attributeSet, final I_M_Attribute attribute)
{
return false;
}
/**
* Creates an ADR attribute value for the C_BPartner which is specified by <code>tableId</code> and <code>recordId</code>.
*/
@Override
public AttributeListValue generateAttributeValue(final Properties ctx, final int tableId, final int recordId, final boolean isSOTrx, final String trxName)
{
final IContextAware context = new PlainContextAware(ctx, trxName);
final ITableRecordReference record = TableRecordReference.of(tableId, recordId);
final I_C_BPartner partner = record.getModel(context, I_C_BPartner.class);
Check.assumeNotNull(partner, "partner not null");
final I_M_Attribute adrAttribute = Services.get(IADRAttributeDAO.class).retrieveADRAttribute(partner);
if (adrAttribute == null)
{
// ADR Attribute was not configured, nothing to do
return null;
}
final String adrRegionValue = Services.get(IADRAttributeBL.class).getADRForBPartner(partner, isSOTrx);
if (Check.isEmpty(adrRegionValue, true))
{
return null; | }
//
// Fetched AD_Ref_List record
final ADRefListItem adRefList = ADReferenceService.get().retrieveListItemOrNull(I_C_BPartner.ADRZertifizierung_L_AD_Reference_ID, adrRegionValue);
Check.assumeNotNull(adRefList, "adRefList not null");
final String adrRegionName = adRefList.getName().getDefaultValue();
return Services.get(IAttributeDAO.class).createAttributeValue(AttributeListValueCreateRequest.builder()
.attributeId(AttributeId.ofRepoId(adrAttribute.getM_Attribute_ID()))
.value(adrRegionValue)
.name(adrRegionName)
.build());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java\org\adempiere\mm\attributes\spi\impl\ADRAttributeGenerator.java | 1 |
请完成以下Java代码 | public void setC_Currency_ID (int C_Currency_ID)
{
if (C_Currency_ID < 1)
set_Value (COLUMNNAME_C_Currency_ID, null);
else
set_Value (COLUMNNAME_C_Currency_ID, Integer.valueOf(C_Currency_ID));
}
/** Get Currency.
@return The Currency for this record
*/
public int getC_Currency_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Currency_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Default.
@param IsDefault
Default value
*/
public void setIsDefault (boolean IsDefault)
{ | set_Value (COLUMNNAME_IsDefault, Boolean.valueOf(IsDefault));
}
/** Get Default.
@return Default value
*/
public boolean isDefault ()
{
Object oo = get_Value(COLUMNNAME_IsDefault);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_CashBook.java | 1 |
请完成以下Java代码 | public void addSupplier(final IDocumentRepostingSupplier supplier)
{
if (supplier == null)
{
return;
}
suppliers.addIfAbsent(supplier);
}
@Override
public List<IDocument> retrievePostedWithoutFactAcct(final Properties ctx, final Timestamp startTime)
{
final IDocumentBL docActionBL = Services.get(IDocumentBL.class);
final List<IDocument> documentsPostedWithoutFactAcct = new ArrayList<>(); | // Retrieve the documents marked as posted but with no fact accounts from all the handlers
for (final IDocumentRepostingSupplier handler : suppliers)
{
final List<?> documents = handler.retrievePostedWithoutFactAcct(ctx, startTime);
for (final Object document : documents)
{
documentsPostedWithoutFactAcct.add(docActionBL.getDocument(document));
}
}
return documentsPostedWithoutFactAcct;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\spi\impl\CompositeDocumentRepostingSupplier.java | 1 |
请完成以下Java代码 | public class X_M_Allergen_Trace extends org.compiere.model.PO implements I_M_Allergen_Trace, org.compiere.model.I_Persistent
{
private static final long serialVersionUID = -674050343L;
/** Standard Constructor */
public X_M_Allergen_Trace (final Properties ctx, final int M_Allergen_Trace_ID, @Nullable final String trxName)
{
super (ctx, M_Allergen_Trace_ID, trxName);
}
/** Load Constructor */
public X_M_Allergen_Trace (final Properties ctx, final ResultSet rs, @Nullable final String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setDescription (final @Nullable java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{ | return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setM_Allergen_Trace_ID (final int M_Allergen_Trace_ID)
{
if (M_Allergen_Trace_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Allergen_Trace_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Allergen_Trace_ID, M_Allergen_Trace_ID);
}
@Override
public int getM_Allergen_Trace_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Allergen_Trace_ID);
}
@Override
public void setName (final @Nullable java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Allergen_Trace.java | 1 |
请完成以下Java代码 | public ResponseEntity<byte[]> getImage(
@PathVariable("imageId") final int imageIdInt,
@RequestParam(name = "maxWidth", required = false, defaultValue = "-1") final int maxWidth,
@RequestParam(name = "maxHeight", required = false, defaultValue = "-1") final int maxHeight,
final WebRequest request)
{
userSession.assertLoggedIn();
final WebuiImageId imageId = WebuiImageId.ofRepoIdOrNull(imageIdInt);
return ETagResponseEntityBuilder.ofETagAware(request, getWebuiImage(imageId, maxWidth, maxHeight))
.includeLanguageInETag()
.cacheMaxAge(userSession.getHttpCacheMaxAge())
.jsonOptions(this::newJSONOptions)
.toResponseEntity((responseBuilder, webuiImage) -> webuiImage.toResponseEntity(responseBuilder));
}
private WebuiImage getWebuiImage(final WebuiImageId imageId, final int maxWidth, final int maxHeight) | {
final WebuiImage image = imageService.getWebuiImage(imageId, maxWidth, maxHeight);
assertUserHasAccess(image);
return image;
}
private void assertUserHasAccess(final WebuiImage image)
{
final BooleanWithReason hasAccess = userSession.getUserRolePermissions().checkCanView(image.getAdClientId(), image.getAdOrgId(), I_AD_Image.Table_ID, image.getAdImageId().getRepoId());
if (hasAccess.isFalse())
{
throw new EntityNotFoundException(hasAccess.getReason());
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\upload\ImageRestController.java | 1 |
请在Spring Boot框架中完成以下Java代码 | static class HazelcastPropertiesCustomizer implements JCachePropertiesCustomizer {
private final @Nullable HazelcastInstance hazelcastInstance;
private final CacheProperties cacheProperties;
HazelcastPropertiesCustomizer(@Nullable HazelcastInstance hazelcastInstance, CacheProperties cacheProperties) {
this.hazelcastInstance = hazelcastInstance;
this.cacheProperties = cacheProperties;
}
@Override
public void customize(Properties properties) {
Resource configLocation = this.cacheProperties
.resolveConfigLocation(this.cacheProperties.getJcache().getConfig());
if (configLocation != null) {
// Hazelcast does not use the URI as a mean to specify a custom config.
properties.setProperty("hazelcast.config.location", toUri(configLocation).toString());
}
else if (this.hazelcastInstance != null) {
properties.put("hazelcast.instance.itself", this.hazelcastInstance); | }
}
private static URI toUri(Resource config) {
try {
return config.getURI();
}
catch (IOException ex) {
throw new IllegalArgumentException("Could not get URI from " + config, ex);
}
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-cache\src\main\java\org\springframework\boot\cache\autoconfigure\HazelcastJCacheCustomizationConfiguration.java | 2 |
请完成以下Java代码 | public void createAndPostMaterialEvents()
{
if (disposed.getAndSet(true))
{
throw new AdempiereException("Collector was already disposed: " + this);
}
final List<AttributesChangedEvent> events = new ArrayList<>();
for (final HUAttributeChanges huAttributeChanges : huAttributeChangesMap.values())
{
events.addAll(createMaterialEvent(huAttributeChanges));
}
events.forEach(materialEventService::enqueueEventAfterNextCommit);
}
private List<AttributesChangedEvent> createMaterialEvent(final HUAttributeChanges changes)
{
if (changes.isEmpty())
{
return ImmutableList.of();
}
final HuId huId = changes.getHuId();
final I_M_HU hu = handlingUnitsBL.getById(huId);
//
// Consider only those HUs which have QtyOnHand
if (!huStatusBL.isQtyOnHand(hu.getHUStatus()))
{
return ImmutableList.of();
}
//
// Consider only VHUs
if (!handlingUnitsBL.isVirtual(hu))
{
return ImmutableList.of();
}
final EventDescriptor eventDescriptor = EventDescriptor.ofClientAndOrg(hu.getAD_Client_ID(), hu.getAD_Org_ID());
final Instant date = changes.getLastChangeDate();
final WarehouseId warehouseId = warehousesRepo.getWarehouseIdByLocatorRepoId(hu.getM_Locator_ID());
final AttributesKeyWithASI oldStorageAttributes = toAttributesKeyWithASI(changes.getOldAttributesKey());
final AttributesKeyWithASI newStorageAttributes = toAttributesKeyWithASI(changes.getNewAttributesKey());
final List<IHUProductStorage> productStorages = handlingUnitsBL.getStorageFactory()
.getStorage(hu)
.getProductStorages();
final List<AttributesChangedEvent> events = new ArrayList<>();
for (final IHUProductStorage productStorage : productStorages) | {
events.add(AttributesChangedEvent.builder()
.eventDescriptor(eventDescriptor)
.warehouseId(warehouseId)
.date(date)
.productId(productStorage.getProductId().getRepoId())
.qty(productStorage.getQtyInStockingUOM().toBigDecimal())
.oldStorageAttributes(oldStorageAttributes)
.newStorageAttributes(newStorageAttributes)
.huId(productStorage.getHuId().getRepoId())
.build());
}
return events;
}
private AttributesKeyWithASI toAttributesKeyWithASI(final AttributesKey attributesKey)
{
return attributesKeyWithASIsCache.computeIfAbsent(attributesKey, this::createAttributesKeyWithASI);
}
private AttributesKeyWithASI createAttributesKeyWithASI(final AttributesKey attributesKey)
{
final AttributeSetInstanceId asiId = AttributesKeys.createAttributeSetInstanceFromAttributesKey(attributesKey);
return AttributesKeyWithASI.of(attributesKey, asiId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\material\interceptor\HUAttributeChangesCollector.java | 1 |
请完成以下Java代码 | private IInvoicingParams getInvoicingParams()
{
Check.assumeNotNull(_invoicingParams, "invoicingParams not null");
return _invoicingParams;
}
@Override
public final InvoiceCandidateEnqueuer setFailOnChanges(final boolean failOnChanges)
{
this._failOnChanges = failOnChanges;
return this;
}
private boolean isFailOnChanges()
{
// Use the explicit setting if available
if (_failOnChanges != null)
{
return _failOnChanges;
}
// Use the sysconfig setting
return sysConfigBL.getBooleanValue(SYSCONFIG_FailOnChanges, DEFAULT_FailOnChanges);
}
private IInvoiceCandidatesChangesChecker newInvoiceCandidatesChangesChecker()
{
if (isFailOnChanges())
{
return new InvoiceCandidatesChangesChecker()
.setTotalNetAmtToInvoiceChecksum(_totalNetAmtToInvoiceChecksum);
}
else
{
return IInvoiceCandidatesChangesChecker.NULL;
}
}
@Override
public IInvoiceCandidateEnqueuer setTotalNetAmtToInvoiceChecksum(final BigDecimal totalNetAmtToInvoiceChecksum)
{ | this._totalNetAmtToInvoiceChecksum = totalNetAmtToInvoiceChecksum;
return this;
}
@Override
public IInvoiceCandidateEnqueuer setAsyncBatchId(final AsyncBatchId asyncBatchId)
{
_asyncBatchId = asyncBatchId;
return this;
}
@Override
public IInvoiceCandidateEnqueuer setPriority(final IWorkpackagePrioStrategy priority)
{
_priority = priority;
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceCandidateEnqueuer.java | 1 |
请完成以下Java代码 | private Map<String, Integer> buildProdIdCountMap(OrdersEntity ordersEntity) {
// 初始化结果集
Map<String, Integer> prodIdCountMap = Maps.newHashMap();
// 获取产品列表
List<ProductOrderEntity> productOrderList = ordersEntity.getProductOrderList();
// 构造结果集
for (ProductOrderEntity productOrderEntity : productOrderList) {
// 产品ID
String prodId = productOrderEntity.getProductEntity().getId();
// 购买数量
Integer count = productOrderEntity.getCount();
prodIdCountMap.put(prodId, count);
}
return prodIdCountMap;
}
/**
* 将prodIdCountMap装入Context
* @param prodIdCountMap
* @param payModeEnum
* @param orderProcessContext | */
private void setIntoContext(Map<String, Integer> prodIdCountMap, PayModeEnum payModeEnum, OrderProcessContext orderProcessContext) {
// 构造 订单插入请求
OrderInsertReq orderInsertReq = new OrderInsertReq();
// 插入prodIdCountMap
orderInsertReq.setProdIdCountMap(prodIdCountMap);
// 插入支付方式
orderInsertReq.setPayModeCode(payModeEnum.getCode());
orderProcessContext.getOrderProcessReq().setReqData(orderInsertReq);
}
} | repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Order\src\main\java\com\gaoxi\order\component\datatransfer\ProdIdCountMapTransferComponent.java | 1 |
请完成以下Java代码 | public String getCaseId() {
return caseId;
}
/**
* Sets the value of the caseId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCaseId(String value) {
this.caseId = value;
}
/**
* Gets the value of the caseDate property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getCaseDate() {
return caseDate;
}
/**
* Sets the value of the caseDate property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setCaseDate(XMLGregorianCalendar value) {
this.caseDate = value;
}
/**
* Gets the value of the ssn property.
*
* @return
* possible object is
* {@link String }
* | */
public String getSsn() {
return ssn;
}
/**
* Sets the value of the ssn property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSsn(String value) {
this.ssn = value;
}
/**
* Gets the value of the nif property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getNif() {
return nif;
}
/**
* Sets the value of the nif property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setNif(String value) {
this.nif = value;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_450_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_450\request\IvgLawType.java | 1 |
请完成以下Java代码 | public class TaskActivityBehavior extends AbstractBpmnActivityBehavior {
/**
* Activity instance id before execution.
*/
protected String activityInstanceId;
/**
* The method which will be called before the execution is performed.
*
* @param execution the execution which is used during execution
* @throws Exception
*/
protected void preExecution(ActivityExecution execution) throws Exception {
activityInstanceId = execution.getActivityInstanceId();
}
/**
* The method which should be overridden by the sub classes to perform an execution.
*
* @param execution the execution which is used during performing the execution
* @throws Exception
*/
protected void performExecution(ActivityExecution execution) throws Exception {
leave(execution);
}
/**
* The method which will be called after performing the execution. | *
* @param execution the execution
* @throws Exception
*/
protected void postExecution(ActivityExecution execution) throws Exception {
}
@Override
public void execute(ActivityExecution execution) throws Exception {
performExecution(execution);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\behavior\TaskActivityBehavior.java | 1 |
请完成以下Java代码 | public class DecisionLogger extends ProcessEngineLogger {
public ProcessEngineException decisionResultMappingException(DmnDecisionResult decisionResult, DecisionResultMapper resultMapper, DmnEngineException cause) {
return new ProcessEngineException(exceptionMessage(
"001",
"The decision result mapper '{}' failed to process '{}'",
resultMapper,
decisionResult
), cause);
}
public ProcessEngineException decisionResultCollectMappingException(Collection<String> outputNames, DmnDecisionResult decisionResult, DecisionResultMapper resultMapper) {
return new ProcessEngineException(exceptionMessage(
"002",
"The decision result mapper '{}' failed to process '{}'. The decision outputs should only contains values for one output name but found '{}'.",
resultMapper,
decisionResult,
outputNames
));
}
public BadUserRequestException exceptionEvaluateDecisionDefinitionByIdAndTenantId() {
return new BadUserRequestException(exceptionMessage(
"003", "Cannot specify a tenant-id when evaluate a decision definition by decision definition id.")); | }
public ProcessEngineException exceptionParseDmnResource(String resouceName, Exception cause) {
return new ProcessEngineException(exceptionMessage(
"004",
"Unable to transform DMN resource '{}'.",
resouceName
), cause);
}
public ProcessEngineException exceptionNoDrdForResource(String resourceName) {
return new ProcessEngineException(exceptionMessage(
"005",
"Found no decision requirements definition for DMN resource '{}'.",
resourceName
));
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\dmn\DecisionLogger.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private boolean hasValidSignature(Token token, String key) {
try {
PublicKey publicKey = getPublicKey(key);
Signature signature = Signature.getInstance("SHA256withRSA");
signature.initVerify(publicKey);
signature.update(token.getContent());
return signature.verify(token.getSignature());
}
catch (GeneralSecurityException ex) {
return false;
}
}
private PublicKey getPublicKey(String key) throws NoSuchAlgorithmException, InvalidKeySpecException {
key = key.replace("-----BEGIN PUBLIC KEY-----\n", "");
key = key.replace("-----END PUBLIC KEY-----", "");
key = key.trim().replace("\n", "");
byte[] bytes = Base64.getDecoder().decode(key);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes);
return KeyFactory.getInstance("RSA").generatePublic(keySpec);
}
private Mono<Void> validateExpiry(Token token) {
long currentTime = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis());
if (currentTime > token.getExpiry()) {
return Mono.error(new CloudFoundryAuthorizationException(Reason.TOKEN_EXPIRED, "Token expired"));
}
return Mono.empty();
} | private Mono<Void> validateIssuer(Token token) {
return this.securityService.getUaaUrl()
.map((uaaUrl) -> String.format("%s/oauth/token", uaaUrl))
.filter((issuerUri) -> issuerUri.equals(token.getIssuer()))
.switchIfEmpty(Mono
.error(new CloudFoundryAuthorizationException(Reason.INVALID_ISSUER, "Token issuer does not match")))
.then();
}
private Mono<Void> validateAudience(Token token) {
if (!token.getScope().contains("actuator.read")) {
return Mono.error(new CloudFoundryAuthorizationException(Reason.INVALID_AUDIENCE,
"Token does not have audience actuator"));
}
return Mono.empty();
}
} | repos\spring-boot-4.0.1\module\spring-boot-cloudfoundry\src\main\java\org\springframework\boot\cloudfoundry\autoconfigure\actuate\endpoint\reactive\TokenValidator.java | 2 |
请完成以下Java代码 | public @PostConstruct void init() {
employeeRepository.save(new Employee("Bilbo", "Baggins", "thief"));
employeeRepository.save(new Employee("Frodo", "Baggins", "ring bearer"));
employeeRepository.save(new Employee("Gandalf", "the Wizard", "servant of the Secret Fire"));
/*
* Due to method-level protections on {@link example.company.ItemRepository}, the security context must be loaded
* with an authentication token containing the necessary privileges.
*/
SecurityUtils.runAs("system", "system", "ROLE_ADMIN");
itemRepository.save(new Item("Sting"));
itemRepository.save(new Item("the one ring"));
SecurityContextHolder.clearContext();
}
/**
* This application is secured at both the URL level for some parts, and the method level for other parts. The URL
* security is shown inside this code, while method-level annotations are enabled at by {@link EnableMethodSecurity}.
*
* @author Greg Turnquist
* @author Oliver Gierke
*/
@Configuration
@EnableMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
static class SecurityConfiguration {
/**
* This section defines the user accounts which can be used for authentication as well as the roles each user has.
*/
@Bean
InMemoryUserDetailsManager userDetailsManager() {
var builder = User.builder().passwordEncoder(PasswordEncoderFactories.createDelegatingPasswordEncoder()::encode);
var greg = builder.username("greg").password("turnquist").roles("USER").build();
var ollie = builder.username("ollie").password("gierke").roles("USER", "ADMIN").build(); | return new InMemoryUserDetailsManager(greg, ollie);
}
/**
* This section defines the security policy for the app.
* <p>
* <ul>
* <li>BASIC authentication is supported (enough for this REST-based demo).</li>
* <li>/employees is secured using URL security shown below.</li>
* <li>CSRF headers are disabled since we are only testing the REST interface, not a web one.</li>
* </ul>
* NOTE: GET is not shown which defaults to permitted.
*
* @param http
* @throws Exception
*/
@Bean
protected SecurityFilterChain configure(HttpSecurity http) throws Exception {
return http.authorizeHttpRequests((authorize) -> {
authorize //
.requestMatchers(HttpMethod.POST, "/employees").hasRole("ADMIN") //
.requestMatchers(HttpMethod.PUT, "/employees/**").hasRole("ADMIN") //
.requestMatchers(HttpMethod.PATCH, "/employees/**").hasRole("ADMIN") //
.anyRequest().permitAll();
}).httpBasic(Customizer.withDefaults()).csrf(AbstractHttpConfigurer::disable).build();
}
}
} | repos\spring-data-examples-main\rest\security\src\main\java\example\springdata\rest\security\Application.java | 1 |
请完成以下Java代码 | public I_S_Resource getS_Resource() throws RuntimeException
{
return (I_S_Resource)MTable.get(getCtx(), I_S_Resource.Table_Name)
.getPO(getS_Resource_ID(), get_TrxName()); }
/** Set Resource.
@param S_Resource_ID
Resource
*/
public void setS_Resource_ID (int S_Resource_ID)
{
if (S_Resource_ID < 1)
set_ValueNoCheck (COLUMNNAME_S_Resource_ID, null);
else
set_ValueNoCheck (COLUMNNAME_S_Resource_ID, Integer.valueOf(S_Resource_ID));
}
/** Get Resource.
@return Resource
*/
public int getS_Resource_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_S_Resource_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair() | {
return new KeyNamePair(get_ID(), String.valueOf(getS_Resource_ID()));
}
/** Set Resource Unavailability.
@param S_ResourceUnAvailable_ID Resource Unavailability */
public void setS_ResourceUnAvailable_ID (int S_ResourceUnAvailable_ID)
{
if (S_ResourceUnAvailable_ID < 1)
set_ValueNoCheck (COLUMNNAME_S_ResourceUnAvailable_ID, null);
else
set_ValueNoCheck (COLUMNNAME_S_ResourceUnAvailable_ID, Integer.valueOf(S_ResourceUnAvailable_ID));
}
/** Get Resource Unavailability.
@return Resource Unavailability */
public int getS_ResourceUnAvailable_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_S_ResourceUnAvailable_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_S_ResourceUnAvailable.java | 1 |
请完成以下Java代码 | public boolean isEmailNotificationEnabled() {
return isEmailNotificationEnabled;
}
public void setAssignee(TemplateDefinition assignee) {
this.assignee = assignee;
}
public TemplateDefinition getCandidate() {
return candidate;
}
public void setCandidate(TemplateDefinition candidate) {
this.candidate = candidate;
}
public void setEmailNotificationEnabled(boolean emailNotificationEnabled) {
this.isEmailNotificationEnabled = emailNotificationEnabled;
}
@Override | public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TaskTemplateDefinition that = (TaskTemplateDefinition) o;
return (
Objects.equals(assignee, that.assignee) &&
Objects.equals(candidate, that.candidate) &&
isEmailNotificationEnabled == that.isEmailNotificationEnabled
);
}
@Override
public int hashCode() {
return Objects.hash(assignee, candidate, isEmailNotificationEnabled);
}
} | repos\Activiti-develop\activiti-core\activiti-spring-process-extensions\src\main\java\org\activiti\spring\process\model\TaskTemplateDefinition.java | 1 |
请完成以下Java代码 | public class S3Application {
private static String AWS_BUCKET = "baeldung-tutorial-s3";
public static Region AWS_REGION = Region.EU_CENTRAL_1;
public static void main(String[] args) {
S3Service s3Service = new S3Service(AWS_REGION);
//creating a bucket
s3Service.createBucket(AWS_BUCKET);
//check if a bucket exists
if(s3Service.doesBucketExist(AWS_BUCKET)) {
System.out.println("Bucket name is not available."
+ " Try again with a different Bucket name.");
return;
}
s3Service.putObjects(AWS_BUCKET, FileGenerator.generateFiles(1000, 1));
//list all the buckets
s3Service.listBuckets();
s3Service.listObjectsInBucket(AWS_BUCKET);
s3Service.listAllObjectsInBucket(AWS_BUCKET);
s3Service.listAllObjectsInBucketPaginated(AWS_BUCKET, 500);
s3Service.listAllObjectsInBucketPaginatedWithPrefix(AWS_BUCKET, 500, "backup/");
//deleting bucket
s3Service.deleteBucket("baeldung-bucket-test2");
//uploading object
s3Service.putObject(
AWS_BUCKET,
"Document/hello.txt",
new File("/Users/user/Document/hello.txt")
);
s3Service.updateObject(
AWS_BUCKET,
"Document/hello2.txt",
new File("/Users/user/Document/hello2.txt")
); | //listing objects
s3Service.listObjects(AWS_BUCKET);
//downloading an object
s3Service.getObject(AWS_BUCKET, "Document/hello.txt");
//copying an object
s3Service.copyObject(
"baeldung-bucket",
"picture/pic.png",
"baeldung-bucket2",
"Document/picture.png"
);
//deleting an object
s3Service.deleteObject(AWS_BUCKET, "Document/hello.txt");
//deleting multiple objects
List<String> objKeyList = List.of("Document/hello2.txt", "Document/picture.png");
s3Service.deleteObjects(AWS_BUCKET, objKeyList);
}
} | repos\tutorials-master\aws-modules\aws-s3\src\main\java\com\baeldung\s3\S3Application.java | 1 |
请完成以下Java代码 | protected void logError(String id, String messageTemplate, Throwable t) {
super.logError(id, messageTemplate, t);
}
protected void logInfo(String id, String messageTemplate, Throwable t) {
super.logInfo(id, messageTemplate, t);
}
public void logSpinValueMapperDetected() {
logInfo("001", "Spin value mapper detected");
}
public FeelException spinValueMapperInstantiationException(Throwable cause) {
return new FeelException(exceptionMessage(
"002", SpinValueMapperFactory.SPIN_VALUE_MAPPER_CLASS_NAME + " class found " +
"on class path but cannot be instantiated."), cause);
}
public FeelException spinValueMapperAccessException(Throwable cause) {
return new FeelException(exceptionMessage(
"003", SpinValueMapperFactory.SPIN_VALUE_MAPPER_CLASS_NAME + " class found " +
"on class path but cannot be accessed."), cause);
}
public FeelException spinValueMapperCastException(Throwable cause, String className) {
return new FeelException(exceptionMessage(
"004", SpinValueMapperFactory.SPIN_VALUE_MAPPER_CLASS_NAME + " class found " +
"on class path but cannot be cast to " + className), cause);
} | public FeelException spinValueMapperException(Throwable cause) {
return new FeelException(exceptionMessage(
"005", "Error while looking up or registering Spin value mapper", cause));
}
public FeelException functionCountExceededException() {
return new FeelException(exceptionMessage(
"006", "Only set one return value or a function."));
}
public FeelException customFunctionNotFoundException() {
return new FeelException(exceptionMessage(
"007", "Custom function not available."));
}
public FeelException evaluationException(String message) {
return new FeelException(exceptionMessage(
"008", "Error while evaluating expression: {}", message));
}
} | repos\camunda-bpm-platform-master\engine-dmn\feel-scala\src\main\java\org\camunda\bpm\dmn\feel\impl\scala\ScalaFeelLogger.java | 1 |
请完成以下Java代码 | public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("Foo [id=").append(id).append(", name=").append(name).append("]");
return builder.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = (prime * result) + ((id == null) ? 0 : id.hashCode());
result = (prime * result) + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
} | if (getClass() != obj.getClass()) {
return false;
}
final Foo other = (Foo) obj;
if (id == null) {
if (other.id != null) {
return false;
}
} else if (!id.equals(other.id)) {
return false;
}
if (name == null) {
if (other.name != null) {
return false;
}
} else if (!name.equals(other.name)) {
return false;
}
return true;
}
} | repos\tutorials-master\spring-security-modules\spring-security-web-boot-1\src\main\java\com\baeldung\roles\custom\persistence\model\Foo.java | 1 |
请完成以下Java代码 | protected Object extractAndConvertValue(ConsumerRecord<?, ?> record, @Nullable Type type) {
Object value = record.value();
if (record.value() == null) {
return KafkaNull.INSTANCE;
}
JavaType javaType = determineJavaType(record, type);
if (value instanceof Bytes) {
value = ((Bytes) value).get();
}
if (value instanceof String) {
try {
return this.objectMapper.readValue((String) value, javaType);
}
catch (IOException e) {
throw new ConversionException("Failed to convert from JSON", record, e);
}
}
else if (value instanceof byte[]) {
try {
return this.objectMapper.readValue((byte[]) value, javaType);
}
catch (IOException e) {
throw new ConversionException("Failed to convert from JSON", record, e);
}
}
else {
throw new IllegalStateException("Only String, Bytes, or byte[] supported");
} | }
private JavaType determineJavaType(ConsumerRecord<?, ?> record, @Nullable Type type) {
JavaType javaType = this.typeMapper.getTypePrecedence()
.equals(org.springframework.kafka.support.mapping.Jackson2JavaTypeMapper.TypePrecedence.INFERRED) && type != null
? TypeFactory.defaultInstance().constructType(type)
: this.typeMapper.toJavaType(record.headers());
if (javaType == null) { // no headers
if (type != null) {
javaType = TypeFactory.defaultInstance().constructType(type);
}
else {
javaType = OBJECT;
}
}
return javaType;
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\converter\JsonMessageConverter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void customize(ConfigurableServletWebServerFactory factory) {
SslCredentials sslCredentials = this.httpServerSslCredentialsConfig.getCredentials();
Ssl ssl = serverProperties.getSsl();
ssl.setBundle("default");
ssl.setKeyAlias(sslCredentials.getKeyAlias());
ssl.setKeyPassword(sslCredentials.getKeyPassword());
factory.setSsl(ssl);
factory.setSslBundles(sslBundles);
}
@Bean
public SslBundles sslBundles() {
SslStoreBundle storeBundle = SslStoreBundle.of(
httpServerSslCredentialsConfig.getCredentials().getKeyStore(),
httpServerSslCredentialsConfig.getCredentials().getKeyPassword(),
null
);
return new SslBundles() {
@Override | public SslBundle getBundle(String name) {
return SslBundle.of(storeBundle);
}
@Override
public List<String> getBundleNames() {
return List.of("default");
}
@Override
public void addBundleUpdateHandler(String name, Consumer<SslBundle> handler) {
// no-op
}
};
}
} | repos\thingsboard-master\common\transport\transport-api\src\main\java\org\thingsboard\server\common\transport\config\ssl\SslCredentialsWebServerCustomizer.java | 2 |
请完成以下Java代码 | public Object instantiate(String entityName, EntityMode entityMode, Serializable id) throws CallbackException {
// TODO Auto-generated method stub
return null;
}
@Override
public String getEntityName(Object object) throws CallbackException {
// TODO Auto-generated method stub
return null;
}
@Override
public Object getEntity(String entityName, Serializable id) throws CallbackException {
// TODO Auto-generated method stub
return null;
}
@Override
public void afterTransactionBegin(Transaction tx) {
// TODO Auto-generated method stub
} | @Override
public void beforeTransactionCompletion(Transaction tx) {
// TODO Auto-generated method stub
}
@Override
public void afterTransactionCompletion(Transaction tx) {
// TODO Auto-generated method stub
}
@Override
public String onPrepareStatement(String sql) {
// TODO Auto-generated method stub
return null;
}
} | repos\tutorials-master\persistence-modules\hibernate5\src\main\java\com\baeldung\hibernate\interceptors\CustomInterceptorImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | ReplyingKafkaTemplate<String, String, String> template(
ProducerFactory<String, String> pf,
ConcurrentKafkaListenerContainerFactory<String, String> factory) {
ConcurrentMessageListenerContainer<String, String> replyContainer =
factory.createContainer("replies");
replyContainer.getContainerProperties().setGroupId("request.replies");
ReplyingKafkaTemplate<String, String, String> template =
new ReplyingKafkaTemplate<>(pf, replyContainer);
template.setMessageConverter(new ByteArrayJacksonJsonMessageConverter());
template.setDefaultTopic("requests");
return template;
}
// end::beans[]
@Bean
ApplicationRunner runner(ReplyingKafkaTemplate<String, String, String> template) {
return args -> {
// tag::sendReceive[]
RequestReplyTypedMessageFuture<String, String, Thing> future1 =
template.sendAndReceive(MessageBuilder.withPayload("getAThing").build(),
new ParameterizedTypeReference<Thing>() { });
log.info(future1.getSendFuture().get(10, TimeUnit.SECONDS).getRecordMetadata().toString());
Thing thing = future1.get(10, TimeUnit.SECONDS).getPayload();
log.info(thing.toString());
RequestReplyTypedMessageFuture<String, String, List<Thing>> future2 =
template.sendAndReceive(MessageBuilder.withPayload("getThings").build(),
new ParameterizedTypeReference<List<Thing>>() { });
log.info(future2.getSendFuture().get(10, TimeUnit.SECONDS).getRecordMetadata().toString());
List<Thing> things = future2.get(10, TimeUnit.SECONDS).getPayload();
things.forEach(thing1 -> log.info(thing1.toString()));
// end::sendReceive[]
};
}
@KafkaListener(id = "myId", topics = "requests", properties = "auto.offset.reset:earliest")
@SendTo
public byte[] listen(String in) {
log.info(in);
if (in.equals("\"getAThing\"")) {
return ("{\"thingProp\":\"someValue\"}").getBytes();
}
if (in.equals("\"getThings\"")) {
return ("[{\"thingProp\":\"someValue1\"},{\"thingProp\":\"someValue2\"}]").getBytes();
}
return in.toUpperCase().getBytes();
} | public static class Thing {
private String thingProp;
public String getThingProp() {
return this.thingProp;
}
public void setThingProp(String thingProp) {
this.thingProp = thingProp;
}
@Override
public String toString() {
return "Thing [thingProp=" + this.thingProp + "]";
}
}
} | repos\spring-kafka-main\spring-kafka-docs\src\main\java\org\springframework\kafka\jdocs\requestreply\Application.java | 2 |
请完成以下Java代码 | protected final String doIt()
{
final I_M_HU hu = getSelectedHU();
generateQRCode(hu);
final ReportResultData labelReport = createLabelReport(hu);
getResult().setReportData(labelReport);
return MSG_OK;
}
private I_M_HU getSelectedHU()
{
final List<I_M_HU> hus = handlingUnitsBL.getBySelectionId(getPinstanceId());
return CollectionUtils.singleElement(hus);
} | private void generateQRCode(final I_M_HU hu)
{
final HuId huId = HuId.ofRepoId(hu.getM_HU_ID());
huQRCodesService.generateForExistingHU(huId);
}
private ReportResultData createLabelReport(@NonNull final I_M_HU hu)
{
final HUToReport huToReport = HUToReportWrapper.of(hu);
return HUReportExecutor.newInstance()
.printPreview(true)
.executeNow(getPrintFormatProcessId(), ImmutableList.of(huToReport))
.getReportData();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\process\M_HU_Report_Print_Template.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public List<String> getPostNames(String postIds) {
return postService.getPostNames(postIds);
}
@Override
@GetMapping(API_PREFIX + "/getRole")
public Role getRole(Long id) {
return roleService.getById(id);
}
@Override
public String getRoleIds(String tenantId, String roleNames) {
return roleService.getRoleIds(tenantId, roleNames);
}
@Override
@GetMapping(API_PREFIX + "/getRoleName")
public String getRoleName(Long id) {
return roleService.getById(id).getRoleName();
}
@Override
public List<String> getRoleNames(String roleIds) {
return roleService.getRoleNames(roleIds);
} | @Override
@GetMapping(API_PREFIX + "/getRoleAlias")
public String getRoleAlias(Long id) {
return roleService.getById(id).getRoleAlias();
}
@Override
@GetMapping(API_PREFIX + "/tenant")
public R<Tenant> getTenant(Long id) {
return R.data(tenantService.getById(id));
}
@Override
@GetMapping(API_PREFIX + "/tenant-id")
public R<Tenant> getTenant(String tenantId) {
return R.data(tenantService.getByTenantId(tenantId));
}
} | repos\SpringBlade-master\blade-service\blade-system\src\main\java\org\springblade\system\feign\SysClient.java | 2 |
请完成以下Java代码 | public ExtensionsV1beta1Ingress createExtensionIngress(String namespace, String ingressName, Map<String, String> annotations, String path,
String serviceName, Integer servicePort) {
//build ingress yaml
ExtensionsV1beta1Ingress ingress = new ExtensionsV1beta1IngressBuilder()
.withNewMetadata()
.withName(ingressName)
.withAnnotations(annotations)
.endMetadata()
.withNewSpec()
.addNewRule()
.withHttp(new ExtensionsV1beta1HTTPIngressRuleValueBuilder().addToPaths(new ExtensionsV1beta1HTTPIngressPathBuilder()
.withPath(path)
.withBackend(new ExtensionsV1beta1IngressBackendBuilder()
.withServiceName(serviceName)
.withServicePort(new IntOrString(servicePort)).build()).build()).build()) | .endRule()
.endSpec()
.build();
ExtensionsV1beta1Api api = new ExtensionsV1beta1Api(apiClient);
ExtensionsV1beta1Ingress extensionsV1beta1Ingress = null;
try {
extensionsV1beta1Ingress = api.createNamespacedIngress(namespace, ingress, null, null, null);
} catch (ApiException e) {
log.error("create ingress error:" + e.getResponseBody(), e);
} catch (Exception e) {
log.error("create ingress system error:", e);
}
return extensionsV1beta1Ingress;
}
} | repos\springboot-demo-master\Kubernetes\src\main\java\com\et\k8s\client\K8sClient.java | 1 |
请完成以下Java代码 | public void setDLM_Partition_Config_ID(final int DLM_Partition_Config_ID)
{
if (DLM_Partition_Config_ID < 1)
{
set_ValueNoCheck(COLUMNNAME_DLM_Partition_Config_ID, null);
}
else
{
set_ValueNoCheck(COLUMNNAME_DLM_Partition_Config_ID, Integer.valueOf(DLM_Partition_Config_ID));
}
}
/**
* Get DLM Partitionierungskonfiguration.
*
* @return DLM Partitionierungskonfiguration
*/
@Override
public int getDLM_Partition_Config_ID()
{
final Integer ii = (Integer)get_Value(COLUMNNAME_DLM_Partition_Config_ID);
if (ii == null)
{
return 0;
}
return ii.intValue();
}
/**
* Set Standard.
*
* @param IsDefault
* Default value
*/
@Override
public void setIsDefault(final boolean IsDefault)
{
set_Value(COLUMNNAME_IsDefault, Boolean.valueOf(IsDefault));
}
/**
* Get Standard.
*
* @return Default value
*/
@Override | public boolean isDefault()
{
final Object oo = get_Value(COLUMNNAME_IsDefault);
if (oo != null)
{
if (oo instanceof Boolean)
{
return ((Boolean)oo).booleanValue();
}
return "Y".equals(oo);
}
return false;
}
/**
* Set Name.
*
* @param Name
* Alphanumeric identifier of the entity
*/
@Override
public void setName(final 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.dlm\base\src\main\java-gen\de\metas\dlm\model\X_DLM_Partition_Config.java | 1 |
请完成以下Java代码 | public static char[] encode(byte[] bytes) {
final int nBytes = bytes.length;
char[] result = new char[2 * nBytes];
int j = 0;
for (byte aByte : bytes) {
// Char for top 4 bits
result[j++] = HEX[(0xF0 & aByte) >>> 4];
// Bottom 4
result[j++] = HEX[(0x0F & aByte)];
}
return result;
}
public static byte[] decode(CharSequence s) {
int nChars = s.length();
if (nChars % 2 != 0) { | throw new IllegalArgumentException("Hex-encoded string must have an even number of characters");
}
byte[] result = new byte[nChars / 2];
for (int i = 0; i < nChars; i += 2) {
int msb = Character.digit(s.charAt(i), 16);
int lsb = Character.digit(s.charAt(i + 1), 16);
if (msb < 0 || lsb < 0) {
throw new IllegalArgumentException(
"Detected a Non-hex character at " + (i + 1) + " or " + (i + 2) + " position");
}
result[i / 2] = (byte) ((msb << 4) | lsb);
}
return result;
}
} | repos\spring-security-main\crypto\src\main\java\org\springframework\security\crypto\codec\Hex.java | 1 |
请完成以下Java代码 | public void setIcon(String icon) {
this.icon = icon;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getLoginTime() {
return loginTime;
}
public void setLoginTime(Date loginTime) {
this.loginTime = loginTime;
}
public Integer getStatus() {
return status;
} | public void setStatus(Integer status) {
this.status = status;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", username=").append(username);
sb.append(", password=").append(password);
sb.append(", icon=").append(icon);
sb.append(", email=").append(email);
sb.append(", nickName=").append(nickName);
sb.append(", note=").append(note);
sb.append(", createTime=").append(createTime);
sb.append(", loginTime=").append(loginTime);
sb.append(", status=").append(status);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsAdmin.java | 1 |
请完成以下Java代码 | public class NotifierService {
private static final String ORDERS_CHANNEL = "orders";
private final JdbcTemplate tpl;
@Transactional
public void notifyOrderCreated(Order order) {
tpl.execute("NOTIFY " + ORDERS_CHANNEL + ", '" + order.getId() + "'");
}
public Runnable createNotificationHandler(Consumer<PGNotification> consumer) {
return () -> {
tpl.execute((Connection c) -> {
log.info("notificationHandler: sending LISTEN command...");
c.createStatement().execute("LISTEN " + ORDERS_CHANNEL);
PGConnection pgconn = c.unwrap(PGConnection.class); | while(!Thread.currentThread().isInterrupted()) {
PGNotification[] nts = pgconn.getNotifications(10000);
if ( nts == null || nts.length == 0 ) {
continue;
}
for( PGNotification nt : nts) {
consumer.accept(nt);
}
}
return 0;
});
};
}
} | repos\tutorials-master\messaging-modules\postgres-notify\src\main\java\com\baeldung\messaging\postgresql\service\NotifierService.java | 1 |
请完成以下Java代码 | public static HUConsolidationJobReference ofParams(final Params params)
{
try
{
final BPartnerId bpartnerId = params.getParameterAsId("bpartnerId", BPartnerId.class);
if (bpartnerId == null)
{
throw new AdempiereException("bpartnerId not set");
}
@Nullable final BPartnerLocationId bpartnerLocationId = BPartnerLocationId.ofRepoId(bpartnerId, params.getParameterAsInt("bpartnerLocationId", -1));
@Nullable final ImmutableSet<PickingSlotId> pickingSlotIds = RepoIdAwares.ofCommaSeparatedSet(params.getParameterAsString("pickingSlotIds"), PickingSlotId.class);
@Nullable final HUConsolidationJobId startedJobId = params.getParameterAsId("startedJobId", HUConsolidationJobId.class);
return builder()
.bpartnerLocationId(bpartnerLocationId)
.pickingSlotIds(pickingSlotIds != null ? pickingSlotIds : ImmutableSet.of())
.countHUs(params.getParameterAsInt("countHUs", 0))
.startedJobId(startedJobId)
.build();
}
catch (Exception ex)
{
throw new AdempiereException("Invalid params: " + params, ex);
}
}
public static HUConsolidationJobReference ofJob(@NonNull final HUConsolidationJob job)
{
return builder()
.bpartnerLocationId(job.getShipToBPLocationId())
.pickingSlotIds(job.getPickingSlotIds())
.countHUs(null)
.startedJobId(job.getId())
.build();
}
public Params toParams()
{
return Params.builder()
.value("bpartnerId", bpartnerLocationId.getBpartnerId().getRepoId())
.value("bpartnerLocationId", bpartnerLocationId.getRepoId())
.value("pickingSlotIds", RepoIdAwares.toCommaSeparatedString(pickingSlotIds))
.value("countHUs", countHUs)
.value("startedJobId", startedJobId != null ? startedJobId.getRepoId() : null)
.build();
}
public boolean isStatsMissing()
{
return countHUs == null;
} | public OptionalInt getCountHUs()
{
return countHUs != null ? OptionalInt.of(countHUs) : OptionalInt.empty();
}
public HUConsolidationJobReference withUpdatedStats(@NonNull final PickingSlotQueuesSummary summary)
{
final OptionalInt optionalCountHUs = summary.getCountHUs(pickingSlotIds);
if (optionalCountHUs.isPresent())
{
final int countHUsNew = optionalCountHUs.getAsInt();
if (this.countHUs == null || this.countHUs != countHUsNew)
{
return toBuilder().countHUs(countHUsNew).build();
}
else
{
return this;
}
}
else
{
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.hu_consolidation.mobile\src\main\java\de\metas\hu_consolidation\mobile\job\HUConsolidationJobReference.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class MessageCorrelationBatchConfiguration extends BatchConfiguration {
protected String messageName;
public MessageCorrelationBatchConfiguration(List<String> ids,
String messageName,
String batchId) {
this(ids, null, messageName, batchId);
}
public MessageCorrelationBatchConfiguration(List<String> ids,
DeploymentMappings mappings,
String messageName,
String batchId) {
super(ids, mappings);
this.messageName = messageName;
this.batchId = batchId;
} | public MessageCorrelationBatchConfiguration(List<String> ids,
DeploymentMappings mappings,
String messageName) {
this(ids, mappings, messageName, null);
}
public String getMessageName() {
return messageName;
}
public void setMessageName(String messageName) {
this.messageName = messageName;;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\batch\message\MessageCorrelationBatchConfiguration.java | 2 |
请完成以下Spring Boot application配置 | spring.application.name=travel-agency-service
server.port=8080
spring.cloud.kubernetes.reload.enabled=true
spring.cloud.kubernetes.secrets.name=db-secret
spring.data.mongodb.host=mongodb-service
spring.data.mongodb.port=27017
spring.data.mongodb.database=admin
spring.data.mongodb.username=${MONGO_USERNAME}
spring.data.mongodb.password=${MONGO_PASSWORD}
management.e | ndpoint.health.enabled=true
management.endpoint.info.enabled=true
management.endpoint.restart.enabled=true
com.baeldung.spring.cloud.kubernetes.services=debug | repos\tutorials-master\spring-cloud-modules\spring-cloud-kubernetes\kubernetes-guide\travel-agency-service\src\main\resources\application.properties | 2 |
请完成以下Java代码 | public void setMediaTypes (final @Nullable java.lang.String MediaTypes)
{
set_Value (COLUMNNAME_MediaTypes, MediaTypes);
}
@Override
public java.lang.String getMediaTypes()
{
return get_ValueAsString(COLUMNNAME_MediaTypes);
}
@Override
public void setMultiLine_LinesCount (final int MultiLine_LinesCount)
{
set_Value (COLUMNNAME_MultiLine_LinesCount, MultiLine_LinesCount);
}
@Override
public int getMultiLine_LinesCount()
{
return get_ValueAsInt(COLUMNNAME_MultiLine_LinesCount);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
@Override
public void setSeqNoGrid (final int SeqNoGrid)
{
set_Value (COLUMNNAME_SeqNoGrid, SeqNoGrid);
}
@Override
public int getSeqNoGrid()
{
return get_ValueAsInt(COLUMNNAME_SeqNoGrid);
}
@Override
public void setSeqNo_SideList (final int SeqNo_SideList)
{
set_Value (COLUMNNAME_SeqNo_SideList, SeqNo_SideList);
}
@Override
public int getSeqNo_SideList()
{
return get_ValueAsInt(COLUMNNAME_SeqNo_SideList);
}
@Override
public void setUIStyle (final @Nullable java.lang.String UIStyle)
{
set_Value (COLUMNNAME_UIStyle, UIStyle);
}
@Override
public java.lang.String getUIStyle()
{
return get_ValueAsString(COLUMNNAME_UIStyle);
}
/**
* ViewEditMode AD_Reference_ID=541263
* Reference name: ViewEditMode
*/
public static final int VIEWEDITMODE_AD_Reference_ID=541263;
/** Never = N */
public static final String VIEWEDITMODE_Never = "N";
/** OnDemand = D */
public static final String VIEWEDITMODE_OnDemand = "D";
/** Always = Y */ | public static final String VIEWEDITMODE_Always = "Y";
@Override
public void setViewEditMode (final @Nullable java.lang.String ViewEditMode)
{
set_Value (COLUMNNAME_ViewEditMode, ViewEditMode);
}
@Override
public java.lang.String getViewEditMode()
{
return get_ValueAsString(COLUMNNAME_ViewEditMode);
}
/**
* WidgetSize AD_Reference_ID=540724
* Reference name: WidgetSize_WEBUI
*/
public static final int WIDGETSIZE_AD_Reference_ID=540724;
/** Small = S */
public static final String WIDGETSIZE_Small = "S";
/** Medium = M */
public static final String WIDGETSIZE_Medium = "M";
/** Large = L */
public static final String WIDGETSIZE_Large = "L";
/** ExtraLarge = XL */
public static final String WIDGETSIZE_ExtraLarge = "XL";
/** XXL = XXL */
public static final String WIDGETSIZE_XXL = "XXL";
@Override
public void setWidgetSize (final @Nullable java.lang.String WidgetSize)
{
set_Value (COLUMNNAME_WidgetSize, WidgetSize);
}
@Override
public java.lang.String getWidgetSize()
{
return get_ValueAsString(COLUMNNAME_WidgetSize);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_UI_Element.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public final class RestClientAutoConfiguration {
@Bean
@ConditionalOnMissingBean(RestClientSsl.class)
@ConditionalOnBean(SslBundles.class)
AutoConfiguredRestClientSsl restClientSsl(ResourceLoader resourceLoader,
ObjectProvider<ClientHttpRequestFactoryBuilder<?>> clientHttpRequestFactoryBuilder,
ObjectProvider<HttpClientSettings> httpClientSettings, SslBundles sslBundles) {
ClassLoader classLoader = resourceLoader.getClassLoader();
return new AutoConfiguredRestClientSsl(
clientHttpRequestFactoryBuilder
.getIfAvailable(() -> ClientHttpRequestFactoryBuilder.detect(classLoader)),
httpClientSettings.getIfAvailable(HttpClientSettings::defaults), sslBundles);
}
@Bean
@ConditionalOnMissingBean
RestClientBuilderConfigurer restClientBuilderConfigurer(ResourceLoader resourceLoader,
ObjectProvider<ClientHttpRequestFactoryBuilder<?>> clientHttpRequestFactoryBuilder,
ObjectProvider<HttpClientSettings> httpClientSettings,
ObjectProvider<RestClientCustomizer> customizerProvider) {
return new RestClientBuilderConfigurer(
clientHttpRequestFactoryBuilder
.getIfAvailable(() -> ClientHttpRequestFactoryBuilder.detect(resourceLoader.getClassLoader())),
httpClientSettings.getIfAvailable(HttpClientSettings::defaults),
customizerProvider.orderedStream().toList());
}
@Bean | @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@ConditionalOnMissingBean
RestClient.Builder restClientBuilder(RestClientBuilderConfigurer restClientBuilderConfigurer) {
return restClientBuilderConfigurer.configure(RestClient.builder());
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(HttpMessageConverters.class)
static class HttpMessageConvertersConfiguration {
@Bean
@ConditionalOnBean(ClientHttpMessageConvertersCustomizer.class)
@Order(Ordered.LOWEST_PRECEDENCE)
HttpMessageConvertersRestClientCustomizer httpMessageConvertersRestClientCustomizer(
ObjectProvider<ClientHttpMessageConvertersCustomizer> customizerProvider) {
return new HttpMessageConvertersRestClientCustomizer(customizerProvider.orderedStream().toList());
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-restclient\src\main\java\org\springframework\boot\restclient\autoconfigure\RestClientAutoConfiguration.java | 2 |
请完成以下Java代码 | private static int measurementIterations(Map<String, String> parameters) {
String measurements = parameters.remove("measurementIterations");
return parseOrDefault(measurements, DEFAULT_MEASUREMENT_ITERATIONS);
}
private static int parseOrDefault(String parameter, int defaultValue) {
return parameter != null ? Integer.parseInt(parameter) : defaultValue;
}
@Benchmark
public Object homemadeMatrixMultiplication(BigMatrixProvider matrixProvider) {
return HomemadeMatrix.multiplyMatrices(matrixProvider.getFirstMatrix(), matrixProvider.getSecondMatrix());
}
@Benchmark
public Object ejmlMatrixMultiplication(BigMatrixProvider matrixProvider) {
SimpleMatrix firstMatrix = new SimpleMatrix(matrixProvider.getFirstMatrix());
SimpleMatrix secondMatrix = new SimpleMatrix(matrixProvider.getSecondMatrix());
return firstMatrix.mult(secondMatrix);
}
@Benchmark
public Object apacheCommonsMatrixMultiplication(BigMatrixProvider matrixProvider) {
RealMatrix firstMatrix = new Array2DRowRealMatrix(matrixProvider.getFirstMatrix());
RealMatrix secondMatrix = new Array2DRowRealMatrix(matrixProvider.getSecondMatrix());
return firstMatrix.multiply(secondMatrix);
}
@Benchmark
public Object la4jMatrixMultiplication(BigMatrixProvider matrixProvider) {
Matrix firstMatrix = new Basic2DMatrix(matrixProvider.getFirstMatrix());
Matrix secondMatrix = new Basic2DMatrix(matrixProvider.getSecondMatrix());
return firstMatrix.multiply(secondMatrix); | }
@Benchmark
public Object nd4jMatrixMultiplication(BigMatrixProvider matrixProvider) {
INDArray firstMatrix = Nd4j.create(matrixProvider.getFirstMatrix());
INDArray secondMatrix = Nd4j.create(matrixProvider.getSecondMatrix());
return firstMatrix.mmul(secondMatrix);
}
@Benchmark
public Object coltMatrixMultiplication(BigMatrixProvider matrixProvider) {
DoubleFactory2D doubleFactory2D = DoubleFactory2D.dense;
DoubleMatrix2D firstMatrix = doubleFactory2D.make(matrixProvider.getFirstMatrix());
DoubleMatrix2D secondMatrix = doubleFactory2D.make(matrixProvider.getSecondMatrix());
Algebra algebra = new Algebra();
return algebra.mult(firstMatrix, secondMatrix);
}
} | repos\tutorials-master\core-java-modules\core-java-lang-math-2\src\main\java\com\baeldung\matrices\benchmark\BigMatrixMultiplicationBenchmarking.java | 1 |
请完成以下Java代码 | public int getC_Channel_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Channel_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Costs.
@param Costs
Costs in accounting currency
*/
public void setCosts (BigDecimal Costs)
{
set_Value (COLUMNNAME_Costs, Costs);
}
/** Get Costs.
@return Costs in accounting currency
*/
public BigDecimal getCosts ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Costs);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set End Date.
@param EndDate
Last effective date (inclusive)
*/
public void setEndDate (Timestamp EndDate)
{
set_Value (COLUMNNAME_EndDate, EndDate);
}
/** Get End Date.
@return Last effective date (inclusive)
*/
public Timestamp getEndDate ()
{
return (Timestamp)get_Value(COLUMNNAME_EndDate);
}
/** Set Summary Level.
@param IsSummary
This is a summary entity
*/
public void setIsSummary (boolean IsSummary)
{
set_Value (COLUMNNAME_IsSummary, Boolean.valueOf(IsSummary));
}
/** Get Summary Level.
@return This is a summary entity
*/
public boolean isSummary ()
{
Object oo = get_Value(COLUMNNAME_IsSummary);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo); | }
return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** 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 Search Key.
@param Value
Search key for the record in the format required - must be unique
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Campaign.java | 1 |
请完成以下Java代码 | public class LockExclusiveJobCmd implements Command<Object>, Serializable {
private static final long serialVersionUID = 1L;
private static Logger log = LoggerFactory.getLogger(LockExclusiveJobCmd.class);
protected Job job;
public LockExclusiveJobCmd(Job job) {
this.job = job;
}
public Object execute(CommandContext commandContext) {
if (job == null) {
throw new ActivitiIllegalArgumentException("job is null");
}
if (log.isDebugEnabled()) {
log.debug("Executing lock exclusive job {} {}", job.getId(), job.getExecutionId()); | }
if (job.isExclusive()) {
if (job.getExecutionId() != null) {
ExecutionEntity execution = commandContext.getExecutionEntityManager().findById(job.getExecutionId());
if (execution != null) {
commandContext
.getExecutionEntityManager()
.updateProcessInstanceLockTime(execution.getProcessInstanceId());
}
}
}
return null;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\LockExclusiveJobCmd.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected final void handlePurchaseCandidateEvent(@NonNull final PurchaseCandidateEvent event)
{
final MaterialDescriptor materialDescriptor = event.getPurchaseMaterialDescriptor();
final CandidatesQuery query = createCandidatesQuery(event);
final Candidate existingCandidteOrNull = candidateRepositoryRetrieval.retrieveLatestMatchOrNull(query);
final CandidateBuilder candidateBuilder;
final PurchaseDetailBuilder purchaseDetailBuilder;
if (existingCandidteOrNull != null)
{
candidateBuilder = existingCandidteOrNull.toBuilder();
purchaseDetailBuilder = PurchaseDetail
.cast(existingCandidteOrNull.getBusinessCaseDetail())
.toBuilder();
}
else
{
candidateBuilder = createInitialBuilder()
.clientAndOrgId(event.getClientAndOrgId());
purchaseDetailBuilder = PurchaseDetail.builder();
}
final PurchaseDetail purchaseDetail = purchaseDetailBuilder
.qty(materialDescriptor.getQuantity()) | .vendorRepoId(event.getVendorId())
.purchaseCandidateRepoId(event.getPurchaseCandidateRepoId())
.advised(Flag.FALSE_DONT_UPDATE)
.build();
candidateBuilder
.materialDescriptor(materialDescriptor)
.minMaxDescriptor(event.getMinMaxDescriptor())
.businessCaseDetail(purchaseDetail);
final Candidate supplyCandidate = updateBuilderFromEvent(candidateBuilder, event).build();
candidateChangeHandler.onCandidateNewOrChange(supplyCandidate);
}
protected abstract CandidateBuilder updateBuilderFromEvent(CandidateBuilder candidateBuilder, PurchaseCandidateEvent event);
protected abstract CandidatesQuery createCandidatesQuery(@NonNull final PurchaseCandidateEvent event);
protected final CandidateBuilder createInitialBuilder()
{
return Candidate.builder()
.type(CandidateType.SUPPLY)
.businessCase(CandidateBusinessCase.PURCHASE)
;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-service\src\main\java\de\metas\material\dispo\service\event\handler\purchasecandidate\PurchaseCandidateCreatedOrUpdatedHandler.java | 2 |
请完成以下Java代码 | public String getName() {
return "spin://" + serializationFormat;
}
@Override
protected String getTypeNameForDeserialized(Object deserializedObject) {
throw LOG.fallbackSerializerCannotDeserializeObjects();
}
@Override
protected byte[] serializeToByteArray(Object deserializedObject) throws Exception {
throw LOG.fallbackSerializerCannotDeserializeObjects();
}
@Override | protected Object deserializeFromByteArray(byte[] object, String objectTypeName) throws Exception {
throw LOG.fallbackSerializerCannotDeserializeObjects();
}
@Override
protected boolean isSerializationTextBased() {
return true;
}
@Override
protected boolean canSerializeValue(Object value) {
throw LOG.fallbackSerializerCannotDeserializeObjects();
}
} | repos\camunda-bpm-platform-master\engine-plugins\spin-plugin\src\main\java\org\camunda\spin\plugin\impl\FallbackSpinObjectValueSerializer.java | 1 |
请完成以下Java代码 | public I_C_OLCand retrieveByIds(@NonNull final OLCandId olCandId)
{
return InterfaceWrapperHelper.load(olCandId, I_C_OLCand.class);
}
@NonNull
public Map<OLCandId, OrderLineId> retrieveOLCandIdToOrderLineId(@NonNull final Set<OLCandId> olCandIds)
{
if (olCandIds.isEmpty())
{
return ImmutableMap.of();
}
return queryBL.createQueryBuilder(I_C_Order_Line_Alloc.class)
.addInArrayFilter(I_C_Order_Line_Alloc.COLUMNNAME_C_OLCand_ID, olCandIds)
.create()
.stream()
.collect(ImmutableMap.toImmutableMap(
olAlloc -> OLCandId.ofRepoId(olAlloc.getC_OLCand_ID()),
olAlloc -> OrderLineId.ofRepoId(olAlloc.getC_OrderLine_ID())
));
}
public boolean isAnyRecordProcessed(@NonNull final Set<OLCandId> olCandIds)
{
return queryBL.createQueryBuilder(I_C_OLCand.class)
.addInArrayFilter(I_C_OLCand.COLUMNNAME_C_OLCand_ID, olCandIds)
.addEqualsFilter(I_C_OLCand.COLUMNNAME_Processed, true)
.create()
.anyMatch();
}
public int deleteRecords(@NonNull final Set<OLCandId> olCandIds)
{
return queryBL.createQueryBuilder(I_C_OLCand.class)
.addInArrayFilter(I_C_OLCand.COLUMNNAME_C_OLCand_ID, olCandIds)
.create()
.delete();
}
public int deleteUnprocessedRecords(@NonNull final IQueryFilter<I_C_OLCand> queryFilter)
{ | return queryBL.createQueryBuilder(I_C_OLCand.class)
.addEqualsFilter(I_C_OLCand.COLUMNNAME_Processed, false)
.filter(queryFilter)
.create()
.delete();
}
public void assignAsyncBatchId(@NonNull final Set<OLCandId> olCandIds, @NonNull final AsyncBatchId asyncBatchId)
{
final ICompositeQueryUpdater<I_C_OLCand> updater = queryBL.createCompositeQueryUpdater(I_C_OLCand.class)
.addSetColumnValue(I_C_OLCand.COLUMNNAME_C_Async_Batch_ID, asyncBatchId.getRepoId());
queryBL.createQueryBuilder(I_C_OLCand.class)
.addInArrayFilter(I_C_OLCand.COLUMNNAME_C_OLCand_ID, olCandIds)
.create()
.update(updater);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\ordercandidate\api\impl\OLCandDAO.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private I_M_HU extractOneCU(@NonNull final I_M_HU hu)
{
final IHUProductStorage huProductStorage = getProductStorage(hu);
final List<I_M_HU> result = HUTransformService
.newInstance()
.husToNewCUs(HUsToNewCUsRequest.builder()
.productId(huProductStorage.getProductId())
.qtyCU(huProductStorage.getQty().toOne())
.sourceHU(hu)
.build())
.getNewCUs();
final I_M_HU cu;
if (result.isEmpty())
{
throw new AdempiereException("Failed extracting 1 CU from " + hu.getValue());
}
else if (result.size() == 1)
{
cu = result.get(0);
}
else
{
cu = result.get(0);
}
return cu;
}
private IAttributeStorage getHUAttributes(final I_M_HU hu)
{
final IContextAware ctxAware = getContextAware(hu);
final IHUContext huContext = handlingUnitsBL.createMutableHUContext(ctxAware);
final IAttributeStorageFactory attributeStorageFactory = huContext.getHUAttributeStorageFactory();
return attributeStorageFactory.getAttributeStorage(hu);
}
private IHUProductStorage getProductStorage(final I_M_HU hu)
{
final IHUStorage huStorage = handlingUnitsBL
.getStorageFactory()
.getStorage(hu);
final ProductId productId = huStorage.getSingleProductIdOrNull();
if (productId == null)
{
throw new AdempiereException("HU is empty");
}
return huStorage.getProductStorage(productId);
}
private void updateHUAttributes(
@NonNull final I_M_HU hu,
@NonNull final HUAttributesUpdateRequest from)
{
final IAttributeStorage huAttributes = getHUAttributes(hu);
updateHUAttributes(huAttributes, from);
huAttributes.saveChangesIfNeeded();
}
private static void updateHUAttributes( | @NonNull final IAttributeStorage huAttributes,
@NonNull final HUAttributesUpdateRequest from)
{
huAttributes.setValue(AttributeConstants.ATTR_SecurPharmScannedStatus, from.getStatus().getCode());
if (!from.isSkipUpdatingBestBeforeDate())
{
final JsonExpirationDate bestBeforeDate = from.getBestBeforeDate();
huAttributes.setValue(AttributeConstants.ATTR_BestBeforeDate, bestBeforeDate != null ? bestBeforeDate.toLocalDate() : null);
}
if (!from.isSkipUpdatingLotNo())
{
huAttributes.setValue(AttributeConstants.ATTR_LotNumber, from.getLotNo());
}
if (!from.isSkipUpdatingSerialNo())
{
huAttributes.setValue(AttributeConstants.ATTR_SerialNo, from.getSerialNo());
}
}
@Value
@Builder
private static class HUAttributesUpdateRequest
{
public static final HUAttributesUpdateRequest ERROR = builder()
.status(SecurPharmAttributesStatus.ERROR)
// UPDATE just the status field, skip the others
.skipUpdatingBestBeforeDate(true)
.skipUpdatingLotNo(true)
.skipUpdatingSerialNo(true)
.build();
@NonNull
SecurPharmAttributesStatus status;
boolean skipUpdatingBestBeforeDate;
@Nullable
JsonExpirationDate bestBeforeDate;
boolean skipUpdatingLotNo;
@Nullable
String lotNo;
boolean skipUpdatingSerialNo;
String serialNo;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.securpharm\src\main\java\de\metas\vertical\pharma\securpharm\service\SecurPharmHUAttributesScanner.java | 2 |
请完成以下Java代码 | public class TransferFundsAsyncEvent implements AccountAsyncEvent {
private final String id;
private final String sourceAccountId;
private final String destinationAccountId;
private final Integer credit;
@JsonCreator
public TransferFundsAsyncEvent(@JsonProperty("id") String id,
@JsonProperty("sourceAccountId") String sourceAccountId,
@JsonProperty("destinationAccountId") String destinationAccountId,
@JsonProperty("credit") Integer credit) {
this.id = id;
this.sourceAccountId = sourceAccountId;
this.destinationAccountId = destinationAccountId;
this.credit = credit;
}
@Override
public String getId() {
return id;
}
@Override
public String keyMessageKey() { | return sourceAccountId;
}
public String getSourceAccountId() {
return sourceAccountId;
}
public String getDestinationAccountId() {
return destinationAccountId;
}
public Integer getCredit() {
return credit;
}
} | repos\spring-examples-java-17\spring-kafka\kafka-common\src\main\java\itx\examples\spring\kafka\events\TransferFundsAsyncEvent.java | 1 |
请完成以下Java代码 | public int getM_ShipmentSchedule_ID()
{
return get_ValueAsInt(COLUMNNAME_M_ShipmentSchedule_ID);
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setQty (final @Nullable BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
@Override
public BigDecimal getQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
/**
* Status AD_Reference_ID=540002
* Reference name: C_SubscriptionProgress Status
*/ | public static final int STATUS_AD_Reference_ID=540002;
/** Planned = P */
public static final String STATUS_Planned = "P";
/** Open = O */
public static final String STATUS_Open = "O";
/** Delivered = D */
public static final String STATUS_Delivered = "D";
/** InPicking = C */
public static final String STATUS_InPicking = "C";
/** Done = E */
public static final String STATUS_Done = "E";
/** Delayed = H */
public static final String STATUS_Delayed = "H";
@Override
public void setStatus (final java.lang.String Status)
{
set_Value (COLUMNNAME_Status, Status);
}
@Override
public java.lang.String getStatus()
{
return get_ValueAsString(COLUMNNAME_Status);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_C_SubscriptionProgress.java | 1 |
请完成以下Java代码 | public TaskFormHandler getTaskFormHandler() {
return taskFormHandler;
}
public void setTaskFormHandler(TaskFormHandler taskFormHandler) {
this.taskFormHandler = taskFormHandler;
}
public Expression getFormKeyExpression() {
return formKeyExpression;
}
public void setFormKeyExpression(Expression formKeyExpression) {
this.formKeyExpression = formKeyExpression;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public Expression getDueDateExpression() {
return dueDateExpression;
}
public void setDueDateExpression(Expression dueDateExpression) {
this.dueDateExpression = dueDateExpression;
}
public Expression getBusinessCalendarNameExpression() {
return businessCalendarNameExpression;
}
public void setBusinessCalendarNameExpression(Expression businessCalendarNameExpression) {
this.businessCalendarNameExpression = businessCalendarNameExpression;
}
public Expression getCategoryExpression() {
return categoryExpression;
}
public void setCategoryExpression(Expression categoryExpression) {
this.categoryExpression = categoryExpression;
}
public Map<String, List<TaskListener>> getTaskListeners() {
return taskListeners;
}
public void setTaskListeners(Map<String, List<TaskListener>> taskListeners) {
this.taskListeners = taskListeners;
} | public List<TaskListener> getTaskListener(String eventName) {
return taskListeners.get(eventName);
}
public void addTaskListener(String eventName, TaskListener taskListener) {
if (TaskListener.EVENTNAME_ALL_EVENTS.equals(eventName)) {
// In order to prevent having to merge the "all" tasklisteners with the ones for a specific eventName,
// every time "getTaskListener()" is called, we add the listener explicitly to the individual lists
this.addTaskListener(TaskListener.EVENTNAME_CREATE, taskListener);
this.addTaskListener(TaskListener.EVENTNAME_ASSIGNMENT, taskListener);
this.addTaskListener(TaskListener.EVENTNAME_COMPLETE, taskListener);
this.addTaskListener(TaskListener.EVENTNAME_DELETE, taskListener);
} else {
List<TaskListener> taskEventListeners = taskListeners.get(eventName);
if (taskEventListeners == null) {
taskEventListeners = new ArrayList<>();
taskListeners.put(eventName, taskEventListeners);
}
taskEventListeners.add(taskListener);
}
}
public Expression getSkipExpression() {
return skipExpression;
}
public void setSkipExpression(Expression skipExpression) {
this.skipExpression = skipExpression;
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\task\TaskDefinition.java | 1 |
请完成以下Java代码 | public class SysUserCacheInfo {
private String sysUserId;
private String sysUserCode;
private String sysUserName;
private String sysOrgCode;
/**
* 当前用户部门ID
*/
private String sysOrgId;
private List<String> sysMultiOrgCode;
private boolean oneDepart;
/**
* 当前用户角色code(多个逗号分割)
*/
private String sysRoleCode;
public boolean isOneDepart() {
return oneDepart;
}
public void setOneDepart(boolean oneDepart) {
this.oneDepart = oneDepart;
}
public String getSysDate() {
return DateUtils.formatDate();
}
public String getSysTime() {
return DateUtils.now();
}
public String getSysUserCode() {
return sysUserCode;
}
public void setSysUserCode(String sysUserCode) {
this.sysUserCode = sysUserCode;
}
public String getSysUserName() {
return sysUserName; | }
public void setSysUserName(String sysUserName) {
this.sysUserName = sysUserName;
}
public String getSysOrgCode() {
return sysOrgCode;
}
public void setSysOrgCode(String sysOrgCode) {
this.sysOrgCode = sysOrgCode;
}
public List<String> getSysMultiOrgCode() {
return sysMultiOrgCode;
}
public void setSysMultiOrgCode(List<String> sysMultiOrgCode) {
this.sysMultiOrgCode = sysMultiOrgCode;
}
public String getSysUserId() {
return sysUserId;
}
public void setSysUserId(String sysUserId) {
this.sysUserId = sysUserId;
}
public String getSysOrgId() {
return sysOrgId;
}
public void setSysOrgId(String sysOrgId) {
this.sysOrgId = sysOrgId;
}
public String getSysRoleCode() {
return sysRoleCode;
}
public void setSysRoleCode(String sysRoleCode) {
this.sysRoleCode = sysRoleCode;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\system\vo\SysUserCacheInfo.java | 1 |
请完成以下Java代码 | public ResourceOptionsDto availableOperations(UriInfo context) {
final IdentityService identityService = getIdentityService();
UriBuilder baseUriBuilder = context.getBaseUriBuilder()
.path(relativeRootResourcePath)
.path(GroupRestService.PATH);
ResourceOptionsDto resourceOptionsDto = new ResourceOptionsDto();
// GET /
URI baseUri = baseUriBuilder.build();
resourceOptionsDto.addReflexiveLink(baseUri, HttpMethod.GET, "list");
// GET /count
URI countUri = baseUriBuilder.clone().path("/count").build();
resourceOptionsDto.addReflexiveLink(countUri, HttpMethod.GET, "count"); | // POST /create
if(!identityService.isReadOnly() && isAuthorized(CREATE)) {
URI createUri = baseUriBuilder.clone().path("/create").build();
resourceOptionsDto.addReflexiveLink(createUri, HttpMethod.POST, "create");
}
return resourceOptionsDto;
}
// utility methods //////////////////////////////////////
protected IdentityService getIdentityService() {
return getProcessEngine().getIdentityService();
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\GroupRestServiceImpl.java | 1 |
请完成以下Java代码 | public class X_EDI_M_InOut_Overdelivery_C_OrderLine_v extends org.compiere.model.PO implements I_EDI_M_InOut_Overdelivery_C_OrderLine_v, org.compiere.model.I_Persistent
{
private static final long serialVersionUID = 332969759L;
/** Standard Constructor */
public X_EDI_M_InOut_Overdelivery_C_OrderLine_v (final Properties ctx, final int EDI_M_InOut_Overdelivery_C_OrderLine_v_ID, @Nullable final String trxName)
{
super (ctx, EDI_M_InOut_Overdelivery_C_OrderLine_v_ID, trxName);
}
/** Load Constructor */
public X_EDI_M_InOut_Overdelivery_C_OrderLine_v (final Properties ctx, final ResultSet rs, @Nullable final String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setC_OrderLine_ID (final int C_OrderLine_ID)
{
if (C_OrderLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_OrderLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_OrderLine_ID, C_OrderLine_ID);
} | @Override
public int getC_OrderLine_ID()
{
return get_ValueAsInt(COLUMNNAME_C_OrderLine_ID);
}
@Override
public org.compiere.model.I_M_InOut getM_InOut()
{
return get_ValueAsPO(COLUMNNAME_M_InOut_ID, org.compiere.model.I_M_InOut.class);
}
@Override
public void setM_InOut(final org.compiere.model.I_M_InOut M_InOut)
{
set_ValueFromPO(COLUMNNAME_M_InOut_ID, org.compiere.model.I_M_InOut.class, M_InOut);
}
@Override
public void setM_InOut_ID (final int M_InOut_ID)
{
if (M_InOut_ID < 1)
set_Value (COLUMNNAME_M_InOut_ID, null);
else
set_Value (COLUMNNAME_M_InOut_ID, M_InOut_ID);
}
@Override
public int getM_InOut_ID()
{
return get_ValueAsInt(COLUMNNAME_M_InOut_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_M_InOut_Overdelivery_C_OrderLine_v.java | 1 |
请完成以下Java代码 | public Class<?> getCommonPropertyType(ELContext context, Object base) {
if (base == null) {
return null;
}
return Object.class;
}
abstract static class BeanProperties {
protected final Map<String, BeanProperty> properties;
protected final Class<?> type;
BeanProperties(Class<?> type) throws ELException {
this.type = type;
this.properties = new HashMap<>();
}
private BeanProperty get(String name) {
return this.properties.get(name);
}
private Class<?> getType() {
return type;
}
}
abstract static class BeanProperty {
private final Class<?> type;
private final Class<?> owner;
private Method read;
private Method write;
BeanProperty(Class<?> owner, Class<?> type) {
this.owner = owner;
this.type = type;
}
public Class<?> getPropertyType() {
return this.type;
}
public boolean isReadOnly(Object base) {
return write(base) == null;
}
private Method write(Object base) {
if (this.write == null) {
this.write = Util.getMethod(this.owner, base, getWriteMethod());
}
return this.write;
}
private Method read(Object base) {
if (this.read == null) {
this.read = Util.getMethod(this.owner, base, getReadMethod());
}
return this.read; | }
abstract Method getWriteMethod();
abstract Method getReadMethod();
abstract String getName();
}
private BeanProperty property(Object base, Object property) {
Class<?> type = base.getClass();
String prop = property.toString();
BeanProperties props = this.cache.get(type.getName());
if (props == null || type != props.getType()) {
props = BeanSupport.getInstance().getBeanProperties(type);
this.cache.put(type.getName(), props);
}
return props.get(prop);
}
private static final class ConcurrentCache<K, V> {
private final int size;
private final Map<K, V> eden;
private final Map<K, V> longterm;
ConcurrentCache(int size) {
this.size = size;
this.eden = new ConcurrentHashMap<>(size);
this.longterm = new WeakHashMap<>(size);
}
public V get(K key) {
V value = this.eden.get(key);
if (value == null) {
synchronized (longterm) {
value = this.longterm.get(key);
}
if (value != null) {
this.eden.put(key, value);
}
}
return value;
}
public void put(K key, V value) {
if (this.eden.size() >= this.size) {
synchronized (longterm) {
this.longterm.putAll(this.eden);
}
this.eden.clear();
}
this.eden.put(key, value);
}
}
} | repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\javax\el\BeanELResolver.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private PaymentTermId getOrCreateDerivedPaymentTerm0(@NonNull BasePaymentTermIdAndDiscount basePaymentTermIdAndDiscount)
{
final PaymentTermId basePaymentTermId = basePaymentTermIdAndDiscount.getBasePaymentTermId();
final Percent discount = basePaymentTermIdAndDiscount.getDiscount();
final I_C_PaymentTerm basePaymentTermRecord = newLoaderAndSaver().getRecordById(basePaymentTermId);
// see if the designed payment term already exists
final I_C_PaymentTerm existingDerivedPaymentTermRecord = queryBL.createQueryBuilderOutOfTrx(I_C_PaymentTerm.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_PaymentTerm.COLUMNNAME_IsValid, true)
.addEqualsFilter(I_C_PaymentTerm.COLUMNNAME_Discount, discount.toBigDecimal())
.addEqualsFilter(I_C_PaymentTerm.COLUMNNAME_AD_Client_ID, basePaymentTermRecord.getAD_Client_ID())
.addEqualsFilter(I_C_PaymentTerm.COLUMNNAME_AD_Org_ID, basePaymentTermRecord.getAD_Org_ID())
.addEqualsFilter(I_C_PaymentTerm.COLUMNNAME_Discount2, basePaymentTermRecord.getDiscount2())
.addEqualsFilter(I_C_PaymentTerm.COLUMNNAME_DiscountDays2, basePaymentTermRecord.getDiscountDays2())
.addEqualsFilter(I_C_PaymentTerm.COLUMNNAME_AfterDelivery, basePaymentTermRecord.isAfterDelivery())
.addEqualsFilter(I_C_PaymentTerm.COLUMNNAME_FixMonthCutoff, basePaymentTermRecord.getFixMonthCutoff())
.addEqualsFilter(I_C_PaymentTerm.COLUMNNAME_FixMonthDay, basePaymentTermRecord.getFixMonthDay())
.addEqualsFilter(I_C_PaymentTerm.COLUMNNAME_FixMonthOffset, basePaymentTermRecord.getFixMonthOffset())
.addEqualsFilter(I_C_PaymentTerm.COLUMNNAME_GraceDays, basePaymentTermRecord.getGraceDays())
.addEqualsFilter(I_C_PaymentTerm.COLUMNNAME_IsDueFixed, basePaymentTermRecord.isDueFixed())
.addEqualsFilter(I_C_PaymentTerm.COLUMNNAME_IsNextBusinessDay, basePaymentTermRecord.isNextBusinessDay())
.addEqualsFilter(I_C_PaymentTerm.COLUMNNAME_NetDay, basePaymentTermRecord.getNetDay())
.addEqualsFilter(I_C_PaymentTerm.COLUMNNAME_NetDays, basePaymentTermRecord.getNetDays())
.orderBy(I_C_PaymentTerm.COLUMNNAME_C_PaymentTerm_ID)
.create()
.first(); | if (existingDerivedPaymentTermRecord != null)
{
return PaymentTermId.ofRepoId(existingDerivedPaymentTermRecord.getC_PaymentTerm_ID());
}
final I_C_PaymentTerm newPaymentTerm = newInstance(I_C_PaymentTerm.class);
InterfaceWrapperHelper.copyValues(basePaymentTermRecord, newPaymentTerm);
newPaymentTerm.setDiscount(discount.toBigDecimal());
final String newName = basePaymentTermRecord.getName() + " (=>" + discount.toBigDecimal() + " %)";
newPaymentTerm.setName(newName);
saveRecord(newPaymentTerm);
return PaymentTermId.ofRepoId(newPaymentTerm.getC_PaymentTerm_ID());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\payment\paymentterm\repository\impl\PaymentTermRepository.java | 2 |
请完成以下Java代码 | private static void validateOrderDocumentTypeWithOrgCode(@NonNull final JsonInvoiceCandidateReference invoiceCandidate)
{
if (invoiceCandidate.getOrderDocumentType() != null && Check.isBlank(invoiceCandidate.getOrgCode()))
{
throw new InvalidEntityException(TranslatableStrings.constant(
"When specifying Order Document Type, the org code also has to be specified"));
}
}
@Nullable
private OrgId getOrgId(@NonNull final JsonInvoiceCandidateReference invoiceCandidate)
{
final String orgCode = invoiceCandidate.getOrgCode();
if (Check.isNotBlank(orgCode))
{
return orgDAO.retrieveOrgIdBy(OrgQuery.ofValue(orgCode))
.orElseThrow(() -> MissingResourceException.builder()
.resourceName("organisation")
.resourceIdentifier("(val-)" + orgCode)
.build());
}
else
{
return null;
}
}
@Nullable
private DocTypeId getOrderDocTypeId(
@Nullable final JsonDocTypeInfo orderDocumentType, | @Nullable final OrgId orgId)
{
if (orderDocumentType == null)
{
return null;
}
if (orgId == null)
{
throw new InvalidEntityException(TranslatableStrings.constant(
"When specifying Order Document Type, the org code also has to be specified"));
}
final DocBaseType docBaseType = Optional.of(orderDocumentType)
.map(JsonDocTypeInfo::getDocBaseType)
.map(DocBaseType::ofCode)
.orElse(null);
final DocSubType subType = Optional.of(orderDocumentType)
.map(JsonDocTypeInfo::getDocSubType)
.map(DocSubType::ofNullableCode)
.orElse(DocSubType.ANY);
return Optional.ofNullable(docBaseType)
.map(baseType -> docTypeService.getDocTypeId(docBaseType, subType, orgId))
.orElseThrow(() -> MissingResourceException.builder()
.resourceName("DocType")
.parentResource(orderDocumentType)
.build());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\invoicecandidates\impl\InvoiceJsonConverters.java | 1 |
请完成以下Java代码 | public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
// persistent object methods ////////////////////////////////////////////////
public String getId() {
return name;
}
public Object getPersistentState() {
return value;
}
public void setId(String id) {
throw LOG.notAllowedIdException(id); | }
public int getRevisionNext() {
return revision+1;
}
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[name=" + name
+ ", revision=" + revision
+ ", value=" + value
+ "]";
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\PropertyEntity.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Blog {
private final ArticleRepo articleRepo;
private final AuditRepo auditRepo;
private final AuditService auditService;
private final TransactionTemplate transactionTemplate;
Blog(ArticleRepo articleRepo, AuditRepo auditRepo, AuditService auditService, TransactionTemplate transactionTemplate) {
this.articleRepo = articleRepo;
this.auditRepo = auditRepo;
this.auditService = auditService;
this.transactionTemplate = transactionTemplate;
}
@Transactional
public Optional<Long> publishArticle(Article article) {
try {
article = articleRepo.save(article);
auditRepo.save(new Audit("SAVE_ARTICLE", "SUCCESS", "saved: " + article.getTitle()));
return Optional.of(article.getId());
} catch (Exception e) {
String errMsg = "failed to save: %s, err: %s".formatted(article.getTitle(), e.getMessage());
auditRepo.save(new Audit("SAVE_ARTICLE", "FAILURE", errMsg));
return Optional.empty();
}
}
@Transactional
public Optional<Long> publishArticle_v2(Article article) {
try {
article = articleRepo.save(article);
auditService.saveAudit("SAVE_ARTICLE", "SUCCESS", "saved: " + article.getTitle());
return Optional.of(article.getId());
} catch (Exception e) {
auditService.saveAudit("SAVE_ARTICLE", "FAILURE", "failed to save: " + article.getTitle());
return Optional.empty();
} | }
public Optional<Long> publishArticle_v3(final Article article) {
try {
Article savedArticle = transactionTemplate.execute(txStatus -> {
Article saved = articleRepo.save(article);
auditRepo.save(new Audit("SAVE_ARTICLE", "SUCCESS", "saved: " + article.getTitle()));
return saved;
});
return Optional.of(savedArticle.getId());
} catch (Exception e) {
auditRepo.save(
new Audit("SAVE_ARTICLE", "FAILURE", "failed to save: " + article.getTitle()));
return Optional.empty();
}
}
} | repos\tutorials-master\persistence-modules\spring-boot-persistence-5\src\main\java\com\baeldung\rollbackonly\Blog.java | 2 |
请完成以下Java代码 | public static <T> List<List<T>> partitionStream(Stream<T> source, int batchSize) {
return source.collect(partitionBySize(batchSize, Collectors.toList()));
}
public static <T, A, R> Collector<T, ?, R> partitionBySize(int batchSize, Collector<List<T>, A, R> downstream) {
Supplier<Accumulator<T, A>> supplier = () -> new Accumulator<>(
batchSize,
downstream.supplier().get(),
downstream.accumulator()::accept
);
BiConsumer<Accumulator<T, A>, T> accumulator = (acc, value) -> acc.add(value);
BinaryOperator<Accumulator<T, A>> combiner = (acc1, acc2) -> acc1.combine(acc2, downstream.combiner());
Function<Accumulator<T, A>, R> finisher = acc -> {
if (!acc.values.isEmpty()) {
downstream.accumulator().accept(acc.downstreamAccumulator, acc.values);
}
return downstream.finisher().apply(acc.downstreamAccumulator);
};
return Collector.of(supplier, accumulator, combiner, finisher, Collector.Characteristics.UNORDERED);
}
static class Accumulator<T, A> {
private final List<T> values = new ArrayList<>();
private final int batchSize;
private A downstreamAccumulator; | private final BiConsumer<A, List<T>> batchFullListener;
Accumulator(int batchSize, A accumulator, BiConsumer<A, List<T>> onBatchFull) {
this.batchSize = batchSize;
this.downstreamAccumulator = accumulator;
this.batchFullListener = onBatchFull;
}
void add(T value) {
values.add(value);
if (values.size() == batchSize) {
batchFullListener.accept(downstreamAccumulator, new ArrayList<>(values));
values.clear();
}
}
Accumulator<T, A> combine(Accumulator<T, A> other, BinaryOperator<A> accumulatorCombiner) {
this.downstreamAccumulator = accumulatorCombiner.apply(downstreamAccumulator, other.downstreamAccumulator);
other.values.forEach(this::add);
return this;
}
}
} | repos\tutorials-master\core-java-modules\core-java-streams-5\src\main\java\com\baeldung\streams\partitioning\PartitionStream.java | 1 |
请完成以下Java代码 | public void setDocStatus (java.lang.String DocStatus)
{
set_Value (COLUMNNAME_DocStatus, DocStatus);
}
/** Get Belegstatus.
@return The current status of the document
*/
@Override
public java.lang.String getDocStatus ()
{
return (java.lang.String)get_Value(COLUMNNAME_DocStatus);
}
/**
* PaymentRule AD_Reference_ID=195
* Reference name: _Payment Rule
*/
public static final int PAYMENTRULE_AD_Reference_ID=195;
/** Cash = B */
public static final String PAYMENTRULE_Cash = "B";
/** CreditCard = K */
public static final String PAYMENTRULE_CreditCard = "K";
/** DirectDeposit = T */
public static final String PAYMENTRULE_DirectDeposit = "T";
/** Check = S */
public static final String PAYMENTRULE_Check = "S";
/** OnCredit = P */
public static final String PAYMENTRULE_OnCredit = "P";
/** DirectDebit = D */
public static final String PAYMENTRULE_DirectDebit = "D";
/** Mixed = M */
public static final String PAYMENTRULE_Mixed = "M";
/** Rückerstattung = E */
public static final String PAYMENTRULE_Reimbursement = "E";
/** Verrechnung = F */
public static final String PAYMENTRULE_Settlement = "F";
/** Set Zahlungsweise.
@param PaymentRule
Wie die Rechnung bezahlt wird
*/
@Override
public void setPaymentRule (java.lang.String PaymentRule)
{
set_Value (COLUMNNAME_PaymentRule, PaymentRule);
}
/** Get Zahlungsweise.
@return Wie die Rechnung bezahlt wird
*/
@Override
public java.lang.String getPaymentRule ()
{
return (java.lang.String)get_Value(COLUMNNAME_PaymentRule);
}
/** 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;
}
/**
* Status AD_Reference_ID=541011
* Reference name: C_Payment_Reservation_Status
*/
public static final int STATUS_AD_Reference_ID=541011;
/** WAITING_PAYER_APPROVAL = W */
public static final String STATUS_WAITING_PAYER_APPROVAL = "W";
/** APPROVED = A */
public static final String STATUS_APPROVED = "A";
/** VOIDED = V */
public static final String STATUS_VOIDED = "V";
/** COMPLETED = C */
public static final String STATUS_COMPLETED = "C";
/** Set Status.
@param Status Status */
@Override
public void setStatus (java.lang.String Status)
{
set_Value (COLUMNNAME_Status, Status);
}
/** Get Status.
@return Status */
@Override
public java.lang.String getStatus ()
{
return (java.lang.String)get_Value(COLUMNNAME_Status);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Payment_Reservation.java | 1 |
请完成以下Java代码 | public String getTargetCmmnElementRef() {
return targetCmmnElementRef;
}
public void setTargetCmmnElementRef(String targetCmmnElementRef) {
this.targetCmmnElementRef = targetCmmnElementRef;
}
public GraphicInfo getSourceDockerInfo() {
return sourceDockerInfo;
}
public void setSourceDockerInfo(GraphicInfo sourceDockerInfo) {
this.sourceDockerInfo = sourceDockerInfo;
}
public GraphicInfo getTargetDockerInfo() {
return targetDockerInfo;
}
public void setTargetDockerInfo(GraphicInfo targetDockerInfo) {
this.targetDockerInfo = targetDockerInfo;
}
public void addWaypoint(GraphicInfo graphicInfo) {
this.waypoints.add(graphicInfo);
} | public List<GraphicInfo> getWaypoints() {
return waypoints;
}
public void setWaypoints(List<GraphicInfo> waypoints) {
this.waypoints = waypoints;
}
public GraphicInfo getLabelGraphicInfo() {
return labelGraphicInfo;
}
public void setLabelGraphicInfo(GraphicInfo labelGraphicInfo) {
this.labelGraphicInfo = labelGraphicInfo;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\CmmnDiEdge.java | 1 |
请完成以下Java代码 | public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public Boolean isPaused() { | return paused;
}
public void setPaused(Boolean paused) {
this.paused = paused;
}
public Boolean isOver() {
return over;
}
public void setOver(Boolean over) {
this.over = over;
}
} | repos\tutorials-master\jackson-modules\jackson-conversions-3\src\main\java\com\baeldung\jackson\booleanAsInt\Game.java | 1 |
请完成以下Java代码 | public int getCurrentImpression() {
return getActualImpression() + getStartImpression();
}
/**
* Adds an Impression to the current Ad
* We will deactivate the Ad as soon as one of the Max Criterias are fullfiled
*/
public void addImpression() {
setActualImpression(getActualImpression()+1);
if (getCurrentImpression()>=getMaxImpression())
setIsActive(false);
save();
}
/**
* Get Next of this Category, this Procedure will return the next Ad in a category and expire it if needed
* @param ctx Context
* @param CM_Ad_Cat_ID Category
* @param trxName Transaction
* @return MAd
*/
public static MAd getNext(Properties ctx, int CM_Ad_Cat_ID, String trxName) {
MAd thisAd = null;
int [] thisAds = MAd.getAllIDs("CM_Ad","ActualImpression+StartImpression<MaxImpression AND CM_Ad_Cat_ID=" + CM_Ad_Cat_ID, trxName);
if (thisAds!=null) {
for (int i=0;i<thisAds.length;i++) { | MAd tempAd = new MAd(ctx, thisAds[i], trxName);
if (thisAd==null)
thisAd = tempAd;
if (tempAd.getCurrentImpression()<=thisAd.getCurrentImpression())
thisAd = tempAd;
}
}
if (thisAd!=null)
thisAd.addImpression();
return thisAd;
}
/**
* Add Click Record to Log
*/
public void addClick()
{
setActualClick(getActualClick()+1);
if (getActualClick()>getMaxClick())
setIsActive(true);
save();
}
} // MAd | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MAd.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public abstract class BaseEdgeEventService implements EdgeEventService {
@Autowired
private EdgeEventDao edgeEventDao;
@Autowired
private RateLimitService rateLimitService;
@Autowired
private DataValidator<EdgeEvent> edgeEventValidator;
@Override
public PageData<EdgeEvent> findEdgeEvents(TenantId tenantId, EdgeId edgeId, Long seqIdStart, Long seqIdEnd, TimePageLink pageLink) {
return edgeEventDao.findEdgeEvents(tenantId.getId(), edgeId, seqIdStart, seqIdEnd, pageLink);
}
@Override | public void cleanupEvents(long ttl) {
edgeEventDao.cleanupEvents(ttl);
}
protected void validateEdgeEvent(EdgeEvent edgeEvent) {
if (!rateLimitService.checkRateLimit(LimitedApi.EDGE_EVENTS, edgeEvent.getTenantId())) {
throw new TbRateLimitsException(EntityType.TENANT);
}
if (!rateLimitService.checkRateLimit(LimitedApi.EDGE_EVENTS_PER_EDGE, edgeEvent.getTenantId(), edgeEvent.getEdgeId())) {
throw new TbRateLimitsException(EntityType.EDGE);
}
edgeEventValidator.validate(edgeEvent, EdgeEvent::getTenantId);
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\edge\BaseEdgeEventService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public List<RestIdentityLink> getIdentityLinks(@ApiParam(name = "caseInstanceId") @PathVariable String caseInstanceId) {
CaseInstance caseInstance = getCaseInstanceFromRequestWithoutAccessCheck(caseInstanceId);
if (restApiInterceptor != null) {
restApiInterceptor.accessCaseInstanceIdentityLinks(caseInstance);
}
return restResponseFactory.createRestIdentityLinks(runtimeService.getIdentityLinksForCaseInstance(caseInstance.getId()));
}
@ApiOperation(value = "Add an involved user to a case instance", tags = {"Case Instance Identity Links" }, nickname = "createCaseInstanceIdentityLinks",
notes = "Note that the groupId in Response Body will always be null, as it’s only possible to involve users with a case instance.",
code = 201)
@ApiResponses(value = {
@ApiResponse(code = 201, message = "Indicates the case instance was found and the link is created."),
@ApiResponse(code = 400, message = "Indicates the requested body did not contain a userId or a type."),
@ApiResponse(code = 404, message = "Indicates the requested case instance was not found.")
})
@PostMapping(value = "/cmmn-runtime/case-instances/{caseInstanceId}/identitylinks", produces = "application/json")
@ResponseStatus(HttpStatus.CREATED)
public RestIdentityLink createIdentityLink(@ApiParam(name = "caseInstanceId") @PathVariable String caseInstanceId, @RequestBody RestIdentityLink identityLink) { | CaseInstance caseInstance = getCaseInstanceFromRequestWithoutAccessCheck(caseInstanceId);
if (identityLink.getGroup() != null) {
throw new FlowableIllegalArgumentException("Only user identity links are supported on a case instance.");
}
if (identityLink.getUser() == null) {
throw new FlowableIllegalArgumentException("The user is required.");
}
if (identityLink.getType() == null) {
throw new FlowableIllegalArgumentException("The identity link type is required.");
}
if (restApiInterceptor != null) {
restApiInterceptor.createCaseInstanceIdentityLink(caseInstance, identityLink);
}
runtimeService.addUserIdentityLink(caseInstance.getId(), identityLink.getUser(), identityLink.getType());
return restResponseFactory.createRestIdentityLink(identityLink.getType(), identityLink.getUser(), identityLink.getGroup(), null, null, caseInstance.getId());
}
} | repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\runtime\caze\CaseInstanceIdentityLinkCollectionResource.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public String filePreviewHandle(String url, Model model, FileAttribute fileAttribute) {
// 预览Type,参数传了就取参数的,没传取系统默认
String officePreviewType = fileAttribute.getOfficePreviewType() == null ? ConfigConstants.getOfficePreviewType() : fileAttribute.getOfficePreviewType();
String baseUrl = BaseUrlFilter.getBaseUrl();
boolean forceUpdatedCache = fileAttribute.forceUpdatedCache();
String fileName = fileAttribute.getName();
String cadPreviewType = ConfigConstants.getCadPreviewType();
String cacheName = fileAttribute.getCacheName();
String outFilePath = fileAttribute.getOutFilePath();
// 判断之前是否已转换过,如果转换过,直接返回,否则执行转换
if (forceUpdatedCache || !fileHandlerService.listConvertedFiles().containsKey(cacheName) || !ConfigConstants.isCacheEnabled()) {
ReturnResponse<String> response = DownloadUtils.downLoad(fileAttribute, fileName);
if (response.isFailure()) {
return otherFilePreview.notSupportedFile(model, fileAttribute, response.getMsg());
}
String filePath = response.getContent();
String imageUrls = null;
if (StringUtils.hasText(outFilePath)) {
try {
imageUrls = fileHandlerService.cadToPdf(filePath, outFilePath, cadPreviewType, fileAttribute);
} catch (Exception e) {
logger.error("Failed to convert CAD file: {}", filePath, e);
}
if (imageUrls == null) {
return otherFilePreview.notSupportedFile(model, fileAttribute, "CAD转换异常,请联系管理员");
}
//是否保留CAD源文件
if (!fileAttribute.isCompressFile() && ConfigConstants.getDeleteSourceFile()) {
KkFileUtils.deleteFileByPath(filePath);
}
if (ConfigConstants.isCacheEnabled()) {
// 加入缓存
fileHandlerService.addConvertedFile(cacheName, fileHandlerService.getRelativePath(outFilePath));
}
} | }
cacheName= WebUtils.encodeFileName(cacheName);
if ("tif".equalsIgnoreCase(cadPreviewType)) {
model.addAttribute("currentUrl", cacheName);
return TIFF_FILE_PREVIEW_PAGE;
} else if ("svg".equalsIgnoreCase(cadPreviewType)) {
model.addAttribute("currentUrl", cacheName);
return SVG_FILE_PREVIEW_PAGE;
}
if (baseUrl != null && (OFFICE_PREVIEW_TYPE_IMAGE.equals(officePreviewType) || OFFICE_PREVIEW_TYPE_ALL_IMAGES.equals(officePreviewType))) {
return getPreviewType(model, fileAttribute, officePreviewType, cacheName, outFilePath, fileHandlerService, OFFICE_PREVIEW_TYPE_IMAGE, otherFilePreview);
}
model.addAttribute("pdfUrl", cacheName);
return PDF_FILE_PREVIEW_PAGE;
}
} | repos\kkFileView-master\server\src\main\java\cn\keking\service\impl\CadFilePreviewImpl.java | 2 |
请完成以下Java代码 | public TenantProfileId getId() {
return super.getId();
}
@Schema(description = "Timestamp of the tenant profile creation, in milliseconds", example = "1609459200000", accessMode = Schema.AccessMode.READ_ONLY)
@Override
public long getCreatedTime() {
return super.getCreatedTime();
}
@Override
public String getName() {
return name;
}
public TenantProfileData getProfileData() {
if (profileData != null) {
return profileData;
} else {
if (profileDataBytes != null) {
try {
profileData = mapper.readValue(new ByteArrayInputStream(profileDataBytes), TenantProfileData.class);
} catch (IOException e) {
log.warn("Can't deserialize tenant profile data: ", e);
return createDefaultTenantProfileData();
}
return profileData;
} else {
return createDefaultTenantProfileData();
}
}
}
@JsonIgnore | public Optional<DefaultTenantProfileConfiguration> getProfileConfiguration() {
return Optional.ofNullable(getProfileData().getConfiguration())
.filter(profileConfiguration -> profileConfiguration instanceof DefaultTenantProfileConfiguration)
.map(profileConfiguration -> (DefaultTenantProfileConfiguration) profileConfiguration);
}
@JsonIgnore
public DefaultTenantProfileConfiguration getDefaultProfileConfiguration() {
return getProfileConfiguration().orElse(null);
}
public TenantProfileData createDefaultTenantProfileData() {
TenantProfileData tpd = new TenantProfileData();
tpd.setConfiguration(new DefaultTenantProfileConfiguration());
this.profileData = tpd;
return tpd;
}
public void setProfileData(TenantProfileData data) {
this.profileData = data;
try {
this.profileDataBytes = data != null ? mapper.writeValueAsBytes(data) : null;
} catch (JsonProcessingException e) {
log.warn("Can't serialize tenant profile data: ", e);
}
}
} | repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\TenantProfile.java | 1 |
请完成以下Java代码 | public class ScoringRules {
private ScoringRules() {
}
static int pairs(List<Integer> dices, int nrOfPairs) {
Map<Integer, Long> frequency = dices.stream()
.collect(groupingBy(identity(), counting()));
List<Integer> pairs = frequency
.entrySet().stream()
.filter(it -> it.getValue() >= 2)
.map(Map.Entry::getKey)
.toList();
if (pairs.size() < nrOfPairs) {
return 0;
}
return pairs.stream()
.sorted(reverseOrder())
.limit(nrOfPairs)
.mapToInt(it -> it * 2)
.sum();
}
static Integer moreOfSameKind(List<Integer> roll, int nrOfDicesOfSameKind) { | Map<Integer, Long> frequency = roll.stream()
.collect(groupingBy(identity(), counting()));
Optional<Integer> diceValue = frequency.entrySet().stream()
.filter(entry -> entry.getValue() >= nrOfDicesOfSameKind)
.map(Map.Entry::getKey)
.max(Integer::compare);
return diceValue.map(it -> it * nrOfDicesOfSameKind)
.orElse(0);
}
static Integer specificValue(List<Integer> dices, Integer value) {
return dices.stream()
.filter(value::equals)
.mapToInt(it -> it)
.sum();
}
} | repos\tutorials-master\patterns-modules\data-oriented-programming\src\main\java\com\baeldung\patterns\ScoringRules.java | 1 |
请完成以下Java代码 | public class SpecSearchCriteria {
private String key;
private SearchOperation operation;
private Object value;
private boolean orPredicate;
public SpecSearchCriteria() {
}
public SpecSearchCriteria(final String key, final SearchOperation operation, final Object value) {
super();
this.key = key;
this.operation = operation;
this.value = value;
}
public SpecSearchCriteria(final String orPredicate, final String key, final SearchOperation operation, final Object value) {
super();
this.orPredicate = orPredicate != null && orPredicate.equals(SearchOperation.OR_PREDICATE_FLAG);
this.key = key;
this.operation = operation;
this.value = value;
}
public SpecSearchCriteria(String key, String operation, String prefix, String value, String suffix) {
SearchOperation op = SearchOperation.getSimpleOperation(operation.charAt(0));
if (op != null) {
if (op == SearchOperation.EQUALITY) { // the operation may be complex operation
final boolean startWithAsterisk = prefix != null && prefix.contains(SearchOperation.ZERO_OR_MORE_REGEX);
final boolean endWithAsterisk = suffix != null && suffix.contains(SearchOperation.ZERO_OR_MORE_REGEX);
if (startWithAsterisk && endWithAsterisk) {
op = SearchOperation.CONTAINS;
} else if (startWithAsterisk) {
op = SearchOperation.ENDS_WITH;
} else if (endWithAsterisk) {
op = SearchOperation.STARTS_WITH;
}
}
}
this.key = key;
this.operation = op;
this.value = value;
}
public String getKey() { | return key;
}
public void setKey(final String key) {
this.key = key;
}
public SearchOperation getOperation() {
return operation;
}
public void setOperation(final SearchOperation operation) {
this.operation = operation;
}
public Object getValue() {
return value;
}
public void setValue(final Object value) {
this.value = value;
}
public boolean isOrPredicate() {
return orPredicate;
}
public void setOrPredicate(boolean orPredicate) {
this.orPredicate = orPredicate;
}
} | repos\tutorials-master\spring-web-modules\spring-rest-query-language\src\main\java\com\baeldung\web\util\SpecSearchCriteria.java | 1 |
请完成以下Java代码 | public void setUseAuthenticationRequestCredentials(boolean useAuthenticationRequestCredentials) {
this.useAuthenticationRequestCredentials = useAuthenticationRequestCredentials;
}
@Override
public void setMessageSource(@NonNull MessageSource messageSource) {
this.messages = new MessageSourceAccessor(messageSource);
}
/**
* Sets the {@link GrantedAuthoritiesMapper} used for converting the authorities
* loaded from storage to a new set of authorities which will be associated to the
* {@link UsernamePasswordAuthenticationToken}. If not set, defaults to a
* {@link NullAuthoritiesMapper}.
* @param authoritiesMapper the {@link GrantedAuthoritiesMapper} used for mapping the
* user's authorities
*/
public void setAuthoritiesMapper(GrantedAuthoritiesMapper authoritiesMapper) {
this.authoritiesMapper = authoritiesMapper;
}
/**
* Allows a custom strategy to be used for creating the <tt>UserDetails</tt> which | * will be stored as the principal in the <tt>Authentication</tt> returned by the
* {@link #createSuccessfulAuthentication(org.springframework.security.authentication.UsernamePasswordAuthenticationToken, org.springframework.security.core.userdetails.UserDetails)}
* method.
* @param userDetailsContextMapper the strategy instance. If not set, defaults to a
* simple <tt>LdapUserDetailsMapper</tt>.
*/
public void setUserDetailsContextMapper(UserDetailsContextMapper userDetailsContextMapper) {
Assert.notNull(userDetailsContextMapper, "UserDetailsContextMapper must not be null");
this.userDetailsContextMapper = userDetailsContextMapper;
}
/**
* Provides access to the injected {@code UserDetailsContextMapper} strategy for use
* by subclasses.
*/
protected UserDetailsContextMapper getUserDetailsContextMapper() {
return this.userDetailsContextMapper;
}
} | repos\spring-security-main\ldap\src\main\java\org\springframework\security\ldap\authentication\AbstractLdapAuthenticationProvider.java | 1 |
请完成以下Java代码 | protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setAD_User_ID (final int AD_User_ID)
{
if (AD_User_ID < 0)
set_ValueNoCheck (COLUMNNAME_AD_User_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_User_ID, AD_User_ID);
}
@Override
public int getAD_User_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_User_ID);
}
@Override
public void setAD_User_Occupation_AdditionalSpecialization_ID (final int AD_User_Occupation_AdditionalSpecialization_ID)
{
if (AD_User_Occupation_AdditionalSpecialization_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_User_Occupation_AdditionalSpecialization_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_User_Occupation_AdditionalSpecialization_ID, AD_User_Occupation_AdditionalSpecialization_ID);
}
@Override
public int getAD_User_Occupation_AdditionalSpecialization_ID()
{ | return get_ValueAsInt(COLUMNNAME_AD_User_Occupation_AdditionalSpecialization_ID);
}
@Override
public org.compiere.model.I_CRM_Occupation getCRM_Occupation()
{
return get_ValueAsPO(COLUMNNAME_CRM_Occupation_ID, org.compiere.model.I_CRM_Occupation.class);
}
@Override
public void setCRM_Occupation(final org.compiere.model.I_CRM_Occupation CRM_Occupation)
{
set_ValueFromPO(COLUMNNAME_CRM_Occupation_ID, org.compiere.model.I_CRM_Occupation.class, CRM_Occupation);
}
@Override
public void setCRM_Occupation_ID (final int CRM_Occupation_ID)
{
if (CRM_Occupation_ID < 1)
set_Value (COLUMNNAME_CRM_Occupation_ID, null);
else
set_Value (COLUMNNAME_CRM_Occupation_ID, CRM_Occupation_ID);
}
@Override
public int getCRM_Occupation_ID()
{
return get_ValueAsInt(COLUMNNAME_CRM_Occupation_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_User_Occupation_AdditionalSpecialization.java | 1 |
请完成以下Java代码 | public class ExecutorRouteRound extends ExecutorRouter {
private static ConcurrentMap<Integer, AtomicInteger> routeCountEachJob = new ConcurrentHashMap<>();
private static long CACHE_VALID_TIME = 0;
private static int count(int jobId) {
// cache clear
if (System.currentTimeMillis() > CACHE_VALID_TIME) {
routeCountEachJob.clear();
CACHE_VALID_TIME = System.currentTimeMillis() + 1000*60*60*24;
}
AtomicInteger count = routeCountEachJob.get(jobId);
if (count == null || count.get() > 1000000) {
// 初始化时主动Random一次,缓解首次压力
count = new AtomicInteger(new Random().nextInt(100)); | } else {
// count++
count.addAndGet(1);
}
routeCountEachJob.put(jobId, count);
return count.get();
}
@Override
public ReturnT<String> route(TriggerParam triggerParam, List<String> addressList) {
String address = addressList.get(count(triggerParam.getJobId())%addressList.size());
return new ReturnT<String>(address);
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\core\route\strategy\ExecutorRouteRound.java | 1 |
请完成以下Java代码 | public TrxItemExecutorBuilder<IT, RT> setExceptionHandler(@NonNull final ITrxItemExceptionHandler exceptionHandler)
{
this._exceptionHandler = exceptionHandler;
return this;
}
private final ITrxItemExceptionHandler getExceptionHandler()
{
return _exceptionHandler;
}
@Override
public ITrxItemExecutorBuilder<IT, RT> setOnItemErrorPolicy(@NonNull final OnItemErrorPolicy onItemErrorPolicy)
{
this._onItemErrorPolicy = onItemErrorPolicy;
return this;
}
@Override
public ITrxItemExecutorBuilder<IT, RT> setItemsPerBatch(final int itemsPerBatch)
{
if (itemsPerBatch == Integer.MAX_VALUE)
{ | this.itemsPerBatch = null;
}
else
{
this.itemsPerBatch = itemsPerBatch;
}
return this;
}
@Override
public ITrxItemExecutorBuilder<IT, RT> setUseTrxSavepoints(final boolean useTrxSavepoints)
{
this._useTrxSavepoints = useTrxSavepoints;
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\processor\api\impl\TrxItemExecutorBuilder.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class SecureResourceController {
private final UserService userService;
private final SecurityIdentity securityIdentity;
public SecureResourceController(UserService userService, SecurityIdentity securityIdentity) {
this.userService = userService;
this.securityIdentity = securityIdentity;
}
@GET
@Path("/resource")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed({"VIEW_ADMIN_DETAILS"})
public String get() {
return "Hello world, here are some details about the admin!";
}
@GET
@Path("/resource/user")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed({"VIEW_USER_DETAILS"})
public Message getUser() {
return new Message("Hello "+securityIdentity.getPrincipal().getName()+"!");
}
@POST
@Path("/resource")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed("${customer.send.message.permission:SEND_MESSAGE}")
public Response getUser(Message message) {
return Response.ok(message).build();
} | @POST
@Path("/user")
@RolesAllowed({"CREATE_USER"})
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response postUser(@Valid final UserDto userDto) {
final var user = userService.createUser(userDto);
final var roles = user.getRoles().stream().map(Role::getName).collect(Collectors.toSet());
return Response.ok(new UserResponse(user.getUsername(), roles)).build();
}
@POST
@Path("/login")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@PermitAll
public Response login(@Valid final LoginDto loginDto) {
if (userService.checkUserCredentials(loginDto.username(), loginDto.password())) {
final var user = userService.findByUsername(loginDto.username());
final var token = userService.generateJwtToken(user);
return Response.ok().entity(new TokenResponse("Bearer " + token,"3600")).build();
} else {
return Response.status(Response.Status.UNAUTHORIZED).entity(new Message("Invalid credentials")).build();
}
}
} | repos\tutorials-master\quarkus-modules\quarkus-rbac\src\main\java\com\baeldung\quarkus\rbac\api\SecureResourceController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class EDIDesadvId implements RepoIdAware
{
int repoId;
@JsonCreator
@NonNull
public static EDIDesadvId ofRepoId(final int repoId)
{
return new EDIDesadvId(repoId);
}
@Nullable
public static EDIDesadvId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? new EDIDesadvId(repoId) : null;
}
public static int toRepoId(@Nullable final EDIDesadvId ediDesadvId) | {
return ediDesadvId != null ? ediDesadvId.getRepoId() : -1;
}
private EDIDesadvId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "EDI_Desadv_ID");
}
@JsonValue
@Override
public int getRepoId()
{
return repoId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\api\EDIDesadvId.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class User {
@Id
@GenericGenerator(name = "system-uuid", strategy = "uuid")
@GeneratedValue(generator = "system-uuid")
private String id;
private String name;
private Integer age;
private Boolean sex;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) { | this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Boolean getSex() {
return sex;
}
public void setSex(Boolean sex) {
this.sex = sex;
}
} | repos\springboot-demo-master\hikari\src\main\java\com\et\hikari\entity\User.java | 2 |
请完成以下Java代码 | public abstract class BasePropertiesParser implements PropertiesParser, DynamicBpmnConstants, PropertiesParserConstants {
@Override
public ObjectNode parseElement(FlowElement flowElement, ObjectNode flowElementNode, ObjectMapper mapper) {
ObjectNode resultNode = mapper.createObjectNode();
resultNode.put(ELEMENT_ID, flowElement.getId());
resultNode.put(ELEMENT_TYPE, flowElement.getClass().getSimpleName());
if (supports(flowElement)) {
resultNode.set(ELEMENT_PROPERTIES, createPropertiesNode(flowElement, flowElementNode, mapper));
}
return resultNode;
}
protected void putPropertyValue(String key, String value, ObjectNode propertiesNode) {
if (StringUtils.isNotBlank(value)) {
propertiesNode.put(key, value);
}
}
protected void putPropertyValue(String key, List<String> values, ObjectNode propertiesNode) {
// we don't set a node value if the collection is null.
// An empty collection is a indicator. if a task has candidate users you can only overrule it by putting an empty array as dynamic candidate users
if (values != null) {
ArrayNode arrayNode = propertiesNode.putArray(key);
for (String value : values) {
arrayNode.add(value);
}
} | }
protected void putPropertyValue(String key, JsonNode node, ObjectNode propertiesNode) {
if (node != null) {
if (!node.isMissingNode() && !node.isNull()) {
propertiesNode.set(key, node);
}
}
}
protected abstract ObjectNode createPropertiesNode(FlowElement flowElement, ObjectNode flowElementNode, ObjectMapper objectMapper);
@Override
public abstract boolean supports(FlowElement flowElement);
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\dynamic\BasePropertiesParser.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public static <T> Result<T> newFailureResult(CommonBizException commonBizException){
Result<T> result = new Result<>();
result.isSuccess = false;
result.errorCode = commonBizException.getCodeEnum().getCode();
result.message = commonBizException.getCodeEnum().getMessage();
return result;
}
/**
* 返回失败的结果
* @param commonBizException 异常
* @param data 需返回的数据
* @param <T>
* @return
*/
public static <T> Result<T> newFailureResult(CommonBizException commonBizException, T data){
Result<T> result = new Result<>();
result.isSuccess = false;
result.errorCode = commonBizException.getCodeEnum().getCode();
result.message = commonBizException.getCodeEnum().getMessage();
result.data = data;
return result;
}
public boolean isSuccess() {
return isSuccess;
}
public void setSuccess(boolean success) {
isSuccess = success;
}
public String getErrorCode() {
return errorCode;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
public String getMessage() {
return message;
} | public void setMessage(String message) {
this.message = message;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
@Override
public String toString() {
return "Result{" +
"isSuccess=" + isSuccess +
", errorCode=" + errorCode +
", message='" + message + '\'' +
", data=" + data +
'}';
}
} | repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\rsp\Result.java | 2 |
请完成以下Java代码 | public MilestoneInstanceQuery milestoneInstanceCaseInstanceId(String caseInstanceId) {
this.caseInstanceId = caseInstanceId;
return this;
}
@Override
public MilestoneInstanceQuery milestoneInstanceCaseDefinitionId(String caseDefinitionId) {
this.caseDefinitionId = caseDefinitionId;
return this;
}
@Override
public MilestoneInstanceQuery milestoneInstanceReachedBefore(Date reachedBefore) {
this.reachedBefore = reachedBefore;
return this;
}
@Override
public MilestoneInstanceQuery milestoneInstanceReachedAfter(Date reachedAfter) {
this.reachedAfter = reachedAfter;
return this;
}
@Override
public MilestoneInstanceQuery milestoneInstanceTenantId(String tenantId) {
if (tenantId == null) {
throw new FlowableIllegalArgumentException("tenant id is null");
}
this.tenantId = tenantId;
return this;
}
@Override
public MilestoneInstanceQuery milestoneInstanceTenantIdLike(String tenantIdLike) {
if (tenantIdLike == null) {
throw new FlowableIllegalArgumentException("tenant id is null");
}
this.tenantIdLike = tenantIdLike;
return this;
}
@Override
public MilestoneInstanceQuery milestoneInstanceWithoutTenantId() {
this.withoutTenantId = true;
return this;
}
@Override
public MilestoneInstanceQuery orderByMilestoneName() {
return orderBy(MilestoneInstanceQueryProperty.MILESTONE_NAME);
}
@Override
public MilestoneInstanceQuery orderByTimeStamp() {
return orderBy(MilestoneInstanceQueryProperty.MILESTONE_TIMESTAMP);
}
@Override
public long executeCount(CommandContext commandContext) {
return CommandContextUtil.getMilestoneInstanceEntityManager(commandContext).findMilestoneInstanceCountByQueryCriteria(this);
} | @Override
public List<MilestoneInstance> executeList(CommandContext commandContext) {
return CommandContextUtil.getMilestoneInstanceEntityManager(commandContext).findMilestoneInstancesByQueryCriteria(this);
}
public String getMilestoneInstanceId() {
return milestoneInstanceId;
}
@Override
public String getId() {
return milestoneInstanceId;
}
public String getName() {
return name;
}
public String getCaseInstanceId() {
return caseInstanceId;
}
public String getCaseDefinitionId() {
return caseDefinitionId;
}
public Date getReachedBefore() {
return reachedBefore;
}
public Date getReachedAfter() {
return reachedAfter;
}
public String getTenantId() {
return tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\MilestoneInstanceQueryImpl.java | 1 |
请完成以下Java代码 | public void onLocationChanged(@NonNull final I_C_BPartner_QuickInput record)
{
final OrgId orgInChangeId = getOrgInChangeViaLocationPostalCode(record);
if (orgInChangeId == null)
{
return;
}
final boolean userHasOrgPermissions = Env.getUserRolePermissions().isOrgAccess(orgInChangeId, null, Access.WRITE);
if (userHasOrgPermissions)
{
record.setAD_Org_ID(orgInChangeId.getRepoId());
}
}
@Nullable
private OrgId getOrgInChangeViaLocationPostalCode(final @NonNull I_C_BPartner_QuickInput record)
{ | final LocationId locationId = LocationId.ofRepoIdOrNull(record.getC_Location_ID());
if (locationId == null)
{
return null;
}
final I_C_Location locationRecord = locationDAO.getById(locationId);
final PostalId postalId = PostalId.ofRepoIdOrNull(locationRecord.getC_Postal_ID());
if (postalId == null)
{
return null;
}
final I_C_Postal postalRecord = locationDAO.getPostalById(postalId);
final OrgId orgInChargeId = OrgId.ofRepoId(postalRecord.getAD_Org_InCharge_ID());
return orgInChargeId.isRegular() ? orgInChargeId : null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\quick_input\callout\C_BPartner_QuickInput.java | 1 |
请完成以下Java代码 | public class PlanItemStartTriggerImpl extends StartTriggerImpl implements PlanItemStartTrigger {
protected static AttributeReference<PlanItem> sourceRefAttribute;
protected static ChildElement<PlanItemTransitionStandardEvent> standardEventChild;
public PlanItemStartTriggerImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
}
public PlanItem getSource() {
return sourceRefAttribute.getReferenceTargetElement(this);
}
public void setSource(PlanItem source) {
sourceRefAttribute.setReferenceTargetElement(this, source);
}
public PlanItemTransition getStandardEvent() {
PlanItemTransitionStandardEvent child = standardEventChild.getChild(this);
return child.getValue();
}
public void setStandardEvent(PlanItemTransition standardEvent) {
PlanItemTransitionStandardEvent child = standardEventChild.getChild(this);
child.setValue(standardEvent);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(PlanItemStartTrigger.class, CMMN_ELEMENT_PLAN_ITEM_START_TRIGGER)
.extendsType(StartTrigger.class) | .namespaceUri(CMMN11_NS)
.instanceProvider(new ModelTypeInstanceProvider<PlanItemStartTrigger>() {
public PlanItemStartTrigger newInstance(ModelTypeInstanceContext instanceContext) {
return new PlanItemStartTriggerImpl(instanceContext);
}
});
sourceRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_SOURCE_REF)
.idAttributeReference(PlanItem.class)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
standardEventChild = sequenceBuilder.element(PlanItemTransitionStandardEvent.class)
.build();
typeBuilder.build();
}
} | repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\PlanItemStartTriggerImpl.java | 1 |
请完成以下Java代码 | public void addDirectoryEntry(JarOutputStream target, String parentPath, File dir) throws IOException {
String remaining = "";
if (parentPath.endsWith(File.separator))
remaining = dir.getAbsolutePath()
.substring(parentPath.length());
else
remaining = dir.getAbsolutePath()
.substring(parentPath.length() + 1);
String name = remaining.replace("\\", "/");
if (!name.endsWith("/"))
name += "/";
JarEntry entry = new JarEntry(name);
entry.setTime(dir.lastModified());
target.putNextEntry(entry);
target.closeEntry();
}
public void addFile(JarOutputStream target, String rootPath, String source) throws IOException {
BufferedInputStream in = null;
String remaining = "";
if (rootPath.endsWith(File.separator))
remaining = source.substring(rootPath.length());
else
remaining = source.substring(rootPath.length() + 1);
String name = remaining.replace("\\", "/");
JarEntry entry = new JarEntry(name);
entry.setTime(new File(source).lastModified());
target.putNextEntry(entry); | in = new BufferedInputStream(new FileInputStream(source));
byte[] buffer = new byte[1024];
while (true) {
int count = in.read(buffer);
if (count == -1)
break;
target.write(buffer, 0, count);
}
target.closeEntry();
in.close();
}
public JarOutputStream openJar(String jarFile) throws IOException {
JarOutputStream target = new JarOutputStream(new FileOutputStream(jarFile), manifest);
return target;
}
public void setMainClass(String mainFQCN) {
if (mainFQCN != null && !mainFQCN.equals(""))
manifest.getMainAttributes()
.put(Attributes.Name.MAIN_CLASS, mainFQCN);
}
public void startManifest() {
manifest.getMainAttributes()
.put(Attributes.Name.MANIFEST_VERSION, "1.0");
}
} | repos\tutorials-master\core-java-modules\core-java-jar\src\main\java\com\baeldung\createjar\JarTool.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Book selectByTitle(String title) {
StringBuilder sb = new StringBuilder("SELECT * FROM ").append(TABLE_NAME_BY_TITLE).append(" WHERE title = '").append(title).append("';");
final String query = sb.toString();
ResultSet rs = session.execute(query);
List<Book> books = new ArrayList<Book>();
for (Row r : rs) {
Book s = new Book(r.getUUID("id"), r.getString("title"), null, null);
books.add(s);
}
return books.get(0);
}
/**
* Select all books from books
*
* @return
*/
public List<Book> selectAll() {
StringBuilder sb = new StringBuilder("SELECT * FROM ").append(TABLE_NAME);
final String query = sb.toString();
ResultSet rs = session.execute(query);
List<Book> books = new ArrayList<Book>();
for (Row r : rs) {
Book book = new Book(r.getUUID("id"), r.getString("title"), r.getString("author"), r.getString("subject"));
books.add(book);
}
return books;
}
/**
* Select all books from booksByTitle
* @return
*/
public List<Book> selectAllBookByTitle() {
StringBuilder sb = new StringBuilder("SELECT * FROM ").append(TABLE_NAME_BY_TITLE);
final String query = sb.toString();
ResultSet rs = session.execute(query);
List<Book> books = new ArrayList<Book>();
for (Row r : rs) {
Book book = new Book(r.getUUID("id"), r.getString("title"), null, null);
books.add(book); | }
return books;
}
/**
* Delete a book by title.
*/
public void deletebookByTitle(String title) {
StringBuilder sb = new StringBuilder("DELETE FROM ").append(TABLE_NAME_BY_TITLE).append(" WHERE title = '").append(title).append("';");
final String query = sb.toString();
session.execute(query);
}
/**
* Delete table.
*
* @param tableName the name of the table to delete.
*/
public void deleteTable(String tableName) {
StringBuilder sb = new StringBuilder("DROP TABLE IF EXISTS ").append(tableName);
final String query = sb.toString();
session.execute(query);
}
} | repos\tutorials-master\persistence-modules\java-cassandra\src\main\java\com\baeldung\cassandra\java\client\repository\BookRepository.java | 2 |
请完成以下Java代码 | public class ModularArithmetic {
private static final int MOD = 1000000007;
private static int minSymmetricMod(int x) {
if (Math.abs(x % MOD) <= Math.abs((MOD - x) % MOD)) {
return x % MOD;
} else {
return -1 * ((MOD - x) % MOD);
}
}
private static int minSymmetricMod(long x) {
if (Math.abs(x % MOD) <= Math.abs((MOD - x) % MOD)) {
return (int) (x % MOD);
} else {
return (int) (-1 * ((MOD - x) % MOD));
}
}
public static int mod(int x) {
if (x >= 0) {
return (x % MOD);
} else {
return mod(MOD + x);
}
}
public static int mod(long x) {
if (x >= 0) {
return (int) (x % (long) MOD);
} else {
return mod(MOD + x);
}
}
public static int modSum(int a, int b) {
return mod(minSymmetricMod(a) + minSymmetricMod(b));
}
public static int modSubtract(int a, int b) {
return mod(minSymmetricMod(a) - minSymmetricMod(b));
}
public static int modMultiply(int a, int b) {
int result = minSymmetricMod((long) minSymmetricMod(a) * (long) minSymmetricMod(b));
return mod(result);
}
public static int modPower(int base, int exp) {
int result = 1;
int b = base;
while (exp > 0) {
if ((exp & 1) == 1) {
result = minSymmetricMod((long) minSymmetricMod(result) * (long) minSymmetricMod(b));
}
b = minSymmetricMod((long) minSymmetricMod(b) * (long) minSymmetricMod(b)); | exp >>= 1;
}
return mod(result);
}
private static int[] extendedGcd(int a, int b) {
if (b == 0) {
return new int[] { a, 1, 0 };
}
int[] result = extendedGcd(b, a % b);
int gcd = result[0];
int x = result[2];
int y = result[1] - (a / b) * result[2];
return new int[] { gcd, x, y };
}
public static int modInverse(int a) {
int[] result = extendedGcd(a, MOD);
int x = result[1];
return mod(x);
}
public static int modDivide(int a, int b) {
return modMultiply(minSymmetricMod(a), minSymmetricMod(modInverse(b)));
}
} | repos\tutorials-master\core-java-modules\core-java-lang-math-4\src\main\java\com\baeldung\math\moduloarithmetic\ModularArithmetic.java | 1 |
请完成以下Java代码 | public class WebAuthenticationDetails implements Serializable {
private static final long serialVersionUID = 620L;
private final String remoteAddress;
private final @Nullable String sessionId;
/**
* Records the remote address and will also set the session Id if a session already
* exists (it won't create one).
* @param request that the authentication request was received from
*/
public WebAuthenticationDetails(HttpServletRequest request) {
this(request.getRemoteAddr(), extractSessionId(request));
}
/**
* Constructor to add Jackson2 serialize/deserialize support
* @param remoteAddress remote address of current request
* @param sessionId session id
* @since 5.7
*/
public WebAuthenticationDetails(String remoteAddress, @Nullable String sessionId) {
this.remoteAddress = remoteAddress;
this.sessionId = sessionId;
}
private static @Nullable String extractSessionId(HttpServletRequest request) {
HttpSession session = request.getSession(false);
return (session != null) ? session.getId() : null;
}
/**
* Indicates the TCP/IP address the authentication request was received from.
* @return the address
*/
public String getRemoteAddress() {
return this.remoteAddress;
} | /**
* Indicates the <code>HttpSession</code> id the authentication request was received
* from.
* @return the session ID
*/
public @Nullable String getSessionId() {
return this.sessionId;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
WebAuthenticationDetails that = (WebAuthenticationDetails) o;
return Objects.equals(this.remoteAddress, that.remoteAddress) && Objects.equals(this.sessionId, that.sessionId);
}
@Override
public int hashCode() {
return Objects.hash(this.remoteAddress, this.sessionId);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName()).append(" [");
sb.append("RemoteIpAddress=").append(this.getRemoteAddress()).append(", ");
sb.append("SessionId=").append(this.getSessionId()).append("]");
return sb.toString();
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\WebAuthenticationDetails.java | 1 |
请完成以下Java代码 | protected ProcessPreconditionsResolution checkPreconditionsApplicable()
{
return checkPreconditionsApplicable_SingleSelectedRow()
.and(this::acceptIfRowNotLockedByOtherUser);
}
private ProcessPreconditionsResolution acceptIfRowNotLockedByOtherUser()
{
final PackageableRow row = getSingleSelectedRow();
if (row.isNotLocked() || row.isLockedBy(getLoggedUserId()))
{
return ProcessPreconditionsResolution.accept();
}
else
{
return ProcessPreconditionsResolution.rejectWithInternalReason("row is locked by other users");
}
}
@Override
protected String doIt()
{
final PackageableRow row = getSingleSelectedRow();
final ShipmentScheduleLockRequest lockRequest = createLockRequest(row);
locksRepo.lock(lockRequest); | try
{
final ProductsToPickView productsToPickView = productsToPickViewFactory.createView(row);
getResult().setWebuiViewToOpen(WebuiViewToOpen.builder()
.target(ViewOpenTarget.ModalOverlay)
.viewId(productsToPickView.getViewId().toJson())
.build());
return MSG_OK;
}
catch (final Exception ex)
{
locksRepo.unlockNoFail(ShipmentScheduleUnLockRequest.of(lockRequest));
throw AdempiereException.wrapIfNeeded(ex);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingV2\packageable\process\PackageablesView_OpenProductsToPick.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.