instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请完成以下Java代码
|
public int getM_HU_PI_Item_Product_ID()
{
return M_HU_PI_Item_Product_ID;
}
public int getC_Flatrate_DataEntry_ID()
{
return C_Flatrate_DataEntry_ID;
}
public static final class Builder
{
private Integer C_BPartner_ID;
private Integer M_Product_ID;
private int M_AttributeSetInstance_ID = 0;
private Integer M_HU_PI_Item_Product_ID;
private int C_Flatrate_DataEntry_ID = -1;
private Builder()
{
super();
}
public PMMPurchaseCandidateSegment build()
{
return new PMMPurchaseCandidateSegment(this);
}
public Builder setC_BPartner_ID(final int C_BPartner_ID)
{
this.C_BPartner_ID = C_BPartner_ID;
return this;
}
public Builder setM_Product_ID(final int M_Product_ID)
{
this.M_Product_ID = M_Product_ID;
return this;
}
|
public Builder setM_AttributeSetInstance_ID(final int M_AttributeSetInstance_ID)
{
this.M_AttributeSetInstance_ID = M_AttributeSetInstance_ID;
return this;
}
public Builder setM_HU_PI_Item_Product_ID(final int M_HU_PI_Item_Product_ID)
{
this.M_HU_PI_Item_Product_ID = M_HU_PI_Item_Product_ID;
return this;
}
public Builder setC_Flatrate_DataEntry_ID(final int C_Flatrate_DataEntry_ID)
{
this.C_Flatrate_DataEntry_ID = C_Flatrate_DataEntry_ID;
return this;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\order\PMMPurchaseCandidateSegment.java
| 1
|
请完成以下Java代码
|
private String traversePreOrder(BinaryTreeModel root) {
if (root == null) {
return "";
}
StringBuilder sb = new StringBuilder();
sb.append(root.getValue());
String pointerRight = "└──";
String pointerLeft = (root.getRight() != null) ? "├──" : "└──";
traverseNodes(sb, "", pointerLeft, root.getLeft(), root.getRight() != null);
traverseNodes(sb, "", pointerRight, root.getRight(), false);
return sb.toString();
}
private void traverseNodes(StringBuilder sb, String padding, String pointer, BinaryTreeModel node,
boolean hasRightSibling) {
if (node != null) {
sb.append("\n");
sb.append(padding);
sb.append(pointer);
sb.append(node.getValue());
StringBuilder paddingBuilder = new StringBuilder(padding);
if (hasRightSibling) {
paddingBuilder.append("│ ");
} else {
paddingBuilder.append(" ");
}
|
String paddingForBoth = paddingBuilder.toString();
String pointerRight = "└──";
String pointerLeft = (node.getRight() != null) ? "├──" : "└──";
traverseNodes(sb, paddingForBoth, pointerLeft, node.getLeft(), node.getRight() != null);
traverseNodes(sb, paddingForBoth, pointerRight, node.getRight(), false);
}
}
public void print(PrintStream os) {
os.print(traversePreOrder(tree));
}
}
|
repos\tutorials-master\data-structures-2\src\main\java\com\baeldung\printbinarytree\BinaryTreePrinter.java
| 1
|
请完成以下Java代码
|
protected boolean beforeSave(final boolean newRecord)
{
if (newRecord || is_ValueChanged("C_BP_Group_ID"))
{
final I_C_BP_Group grp = getBPGroup();
if (grp == null)
{
throw new AdempiereException("@NotFound@: @C_BP_Group_ID@");
}
final BPGroupId parentGroupId = BPGroupId.ofRepoIdOrNull(grp.getParent_BP_Group_ID());
if (parentGroupId != null)
{
final I_C_BP_Group parentGroup = bpGroupsRepo.getById(parentGroupId);
setBPGroup(parentGroup); // attempt to set from parent group first
}
setBPGroup(grp); // setDefaults
}
return true;
} // beforeSave
/**************************************************************************
* After Save
*
* @param newRecord
* new
* @param success
* success
* @return success
*/
@Override
protected boolean afterSave(final boolean newRecord, final boolean success)
{
if (newRecord && success)
{
// Trees
insert_Tree(MTree_Base.TREETYPE_BPartner);
// Accounting
insert_Accounting("C_BP_Customer_Acct", "C_BP_Group_Acct",
"p.C_BP_Group_ID=" + getC_BP_Group_ID());
insert_Accounting("C_BP_Vendor_Acct", "C_BP_Group_Acct",
"p.C_BP_Group_ID=" + getC_BP_Group_ID());
insert_Accounting("C_BP_Employee_Acct", "C_AcctSchema_Default",
null);
}
// Value/Name change
if (success && !newRecord
&& (is_ValueChanged("Value") || is_ValueChanged("Name")))
{
MAccount.updateValueDescription(getCtx(), "C_BPartner_ID="
|
+ getC_BPartner_ID(), get_TrxName());
}
return success;
} // afterSave
/**
* Before Delete
*
* @return true
*/
@Override
protected boolean beforeDelete()
{
return delete_Accounting("C_BP_Customer_Acct")
&& delete_Accounting("C_BP_Vendor_Acct")
&& delete_Accounting("C_BP_Employee_Acct");
} // beforeDelete
/**
* After Delete
*
* @param success
* @return deleted
*/
@Override
protected boolean afterDelete(final boolean success)
{
if (success)
{
delete_Tree(MTree_Base.TREETYPE_BPartner);
}
return success;
} // afterDelete
} // MBPartner
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MBPartner.java
| 1
|
请完成以下Java代码
|
public void run() {
/*
* Algorithm: for each execution that is involved in this command context,
*
* 1) Get its process definition
* 2) Verify if its process definitions has any InactiveActivityBehavior behaviours.
* 3) If so, verify if there are any executions inactive in those activities
* 4) Execute the inactivated behavior
*
*/
for (ExecutionEntity executionEntity : involvedExecutions) {
Process process = ProcessDefinitionUtil.getProcess(executionEntity.getProcessDefinitionId());
Collection<String> flowNodeIdsWithInactivatedBehavior = new ArrayList<String>();
for (FlowNode flowNode : process.findFlowElementsOfType(FlowNode.class)) {
if (flowNode.getBehavior() instanceof InactiveActivityBehavior) {
flowNodeIdsWithInactivatedBehavior.add(flowNode.getId());
}
}
if (flowNodeIdsWithInactivatedBehavior.size() > 0) {
Collection<ExecutionEntity> inactiveExecutions = commandContext
.getExecutionEntityManager()
.findInactiveExecutionsByProcessInstanceId(executionEntity.getProcessInstanceId());
for (ExecutionEntity inactiveExecution : inactiveExecutions) {
if (
!inactiveExecution.isActive() &&
flowNodeIdsWithInactivatedBehavior.contains(inactiveExecution.getActivityId()) &&
!inactiveExecution.isDeleted()
) {
|
FlowNode flowNode = (FlowNode) process.getFlowElement(inactiveExecution.getActivityId(), true);
InactiveActivityBehavior inactiveActivityBehavior =
((InactiveActivityBehavior) flowNode.getBehavior());
logger.debug(
"Found InactiveActivityBehavior instance of class {} that can be executed on activity '{}'",
inactiveActivityBehavior.getClass(),
flowNode.getId()
);
inactiveActivityBehavior.executeInactive(inactiveExecution);
}
}
}
}
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\agenda\ExecuteInactiveBehaviorsOperation.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private Optional<TUPickingTarget> getTUPickingTarget(
@NonNull final PickingJob pickingJob,
@Nullable final PickingJobLineId lineId)
{
return pickingJob.getTuPickingTarget(lineId);
}
public void reopenPickingJobs(@NonNull final ReopenPickingJobRequest request)
{
final Map<ShipmentScheduleId, List<PickingJobId>> scheduleId2JobIds = pickingJobRepository
.getPickingJobIdsByScheduleId(request.getShipmentScheduleIds());
final PickingJobReopenCommand.PickingJobReopenCommandBuilder commandBuilder = PickingJobReopenCommand.builder()
.pickingSlotService(pickingSlotService)
.pickingJobRepository(pickingJobRepository)
.shipmentScheduleService(shipmentScheduleService)
.huService(huService);
scheduleId2JobIds.values().stream()
.flatMap(List::stream)
.collect(ImmutableSet.toImmutableSet())
.stream()
.map(this::getById)
.filter(pickingJob -> pickingJob.getAllPickedHuIds()
.stream()
.anyMatch(huId -> request.getHuIds().contains(huId)))
.map(job -> commandBuilder
.jobToReopen(job)
.huIdsToPick(request.getHuInfoList())
.build())
.forEach(PickingJobReopenCommand::execute);
}
public PickingSlotSuggestions getPickingSlotsSuggestions(final @NonNull PickingJob pickingJob)
{
final Set<DocumentLocation> deliveryLocations = bpartnerService.getDocumentLocations(pickingJob.getDeliveryBPLocationIds());
return pickingSlotService.getPickingSlotsSuggestions(deliveryLocations);
}
public PickingJob pickAll(@NonNull final PickingJobId pickingJobId, final @NonNull UserId callerId)
{
return PickingJobPickAllCommand.builder()
.pickingJobService(this)
//
.pickingJobId(pickingJobId)
.callerId(callerId)
//
.build().execute();
|
}
public PickingJobQtyAvailable getQtyAvailable(@NonNull final PickingJobId pickingJobId, final @NonNull UserId callerId)
{
return PickingJobGetQtyAvailableCommand.builder()
.pickingJobService(this)
.warehouseService(warehouseService)
.huService(huService)
//
.pickingJobId(pickingJobId)
.callerId(callerId)
//
.build().execute();
}
public GetNextEligibleLineToPackResponse getNextEligibleLineToPack(@NonNull GetNextEligibleLineToPackRequest request)
{
return GetNextEligibleLineToPackCommand.builder()
.pickingJobService(this)
.huService(huService)
.shipmentSchedules(shipmentScheduleService.newLoadingCache())
.request(request)
.build().execute();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\service\PickingJobService.java
| 2
|
请完成以下Java代码
|
public class ExploreSpring5URLPatternUsingRouterFunctions {
private RouterFunction<ServerResponse> routingFunction() {
return route(GET("/t?st"), serverRequest -> ok().body(fromValue("Path /t?st is accessed"))).andRoute(GET("/test/{*id}"), serverRequest -> ok().body(fromValue(serverRequest.pathVariable("id"))))
.andRoute(GET("/baeldung/*Id"), serverRequest -> ok().body(fromValue("/baeldung/*Id path was accessed")))
.andRoute(GET("/{var1}_{var2}"), serverRequest -> ok().body(fromValue(serverRequest.pathVariable("var1") + " , " + serverRequest.pathVariable("var2"))))
.andRoute(GET("/{baeldung:[a-z]+}"), serverRequest -> ok().body(fromValue("/{baeldung:[a-z]+} was accessed and baeldung=" + serverRequest.pathVariable("baeldung"))))
.and(RouterFunctions.resources("/files/{*filepaths}", new ClassPathResource("files/")))
.and(RouterFunctions.resources("/resources/**", new ClassPathResource("resources/")));
}
WebServer start() {
WebHandler webHandler = (WebHandler) toHttpHandler(routingFunction());
HttpHandler httpHandler = WebHttpHandlerBuilder.webHandler(webHandler)
.filter(new IndexRewriteFilter())
.build();
Tomcat tomcat = new Tomcat();
tomcat.setHostname("localhost");
tomcat.setPort(9090);
Context rootContext = tomcat.addContext("", System.getProperty("java.io.tmpdir"));
ServletHttpHandlerAdapter servlet = new ServletHttpHandlerAdapter(httpHandler);
Wrapper servletWrapper = Tomcat.addServlet(rootContext, "httpHandlerServlet", servlet);
servletWrapper.setAsyncSupported(true);
rootContext.addServletMappingDecoded("/", "httpHandlerServlet");
|
TomcatWebServer server = new TomcatWebServer(tomcat);
server.start();
return server;
}
public static void main(String[] args) {
try {
new FunctionalWebApplication().start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
repos\tutorials-master\spring-reactive-modules\spring-reactive-2\src\main\java\com\baeldung\reactive\urlmatch\ExploreSpring5URLPatternUsingRouterFunctions.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class ExecutorServiceBean implements ExecutorService {
@Resource(mappedName="eis/JcaExecutorServiceConnectionFactory")
protected JcaExecutorServiceConnectionFactory executorConnectionFactory;
protected JcaExecutorServiceConnection executorConnection;
@PostConstruct
protected void openConnection() {
try {
executorConnection = executorConnectionFactory.getConnection();
} catch (ResourceException e) {
throw new ProcessEngineException("Could not open connection to executor service connection factory ", e);
}
}
@PreDestroy
|
protected void closeConnection() {
if(executorConnection != null) {
executorConnection.closeConnection();
}
}
public boolean schedule(Runnable runnable, boolean isLongRunning) {
return executorConnection.schedule(runnable, isLongRunning);
}
public Runnable getExecuteJobsRunnable(List<String> jobIds, ProcessEngineImpl processEngine) {
return executorConnection.getExecuteJobsRunnable(jobIds, processEngine);
}
}
|
repos\camunda-bpm-platform-master\javaee\ejb-service\src\main\java\org\camunda\bpm\container\impl\ejb\ExecutorServiceBean.java
| 2
|
请完成以下Java代码
|
private void dbUpdateErrorMessagesIFA(@NonNull final ImportRecordsSelection selection)
{
StringBuilder sql;
sql = new StringBuilder("UPDATE ")
.append(targetTableName + " i ")
.append(" SET " + COLUMNNAME_I_IsImported + "='E', " + COLUMNNAME_I_ErrorMsg + "=" + COLUMNNAME_I_ErrorMsg + "||'ERR=Invalid ProdCategory,' ")
.append("WHERE M_Product_Category_ID IS NULL AND A00SSATZ = '1'") // category shall be mandatory only when is new product
.append(" AND " + COLUMNNAME_I_IsImported + "<>'Y'")
.append(selection.toSqlWhereClause("i"));
DB.executeUpdateAndThrowExceptionOnFail(sql.toString(), ITrx.TRXNAME_ThreadInherited);
sql = new StringBuilder("UPDATE ")
.append(targetTableName + " i ")
.append(" SET " + COLUMNNAME_I_IsImported + "='E', " + COLUMNNAME_I_ErrorMsg + "=" + COLUMNNAME_I_ErrorMsg + "||'ERR=A00PZN is mandatory,' ")
.append("WHERE A00PZN IS NULL")
.append(" AND " + COLUMNNAME_I_IsImported + "<>'Y'")
.append(selection.toSqlWhereClause("i"));
DB.executeUpdateAndThrowExceptionOnFail(sql.toString(), ITrx.TRXNAME_ThreadInherited);
sql = new StringBuilder("UPDATE ")
.append(targetTableName + " i ")
.append(" SET " + COLUMNNAME_I_IsImported + "='E', " + COLUMNNAME_I_ErrorMsg + "=" + COLUMNNAME_I_ErrorMsg + "||'ERR=Invalid Package UOM,' ")
.append("WHERE Package_UOM_ID IS NULL and i.A00PGEINH IS NOT NULL ")
.append(" AND " + COLUMNNAME_I_IsImported + "<>'Y'")
.append(selection.toSqlWhereClause("i"));
DB.executeUpdateAndThrowExceptionOnFail(sql.toString(), ITrx.TRXNAME_ThreadInherited);
sql = new StringBuilder("UPDATE ")
.append(targetTableName + " i ")
.append(" SET " + COLUMNNAME_I_IsImported + "='E', " + COLUMNNAME_I_ErrorMsg + "=" + COLUMNNAME_I_ErrorMsg + "||'ERR=Invalid Dosage Form,' ")
.append("WHERE M_DosageForm_ID IS NULL and (i.A00DARFO IS NOT NULL and i.A00DARFO <> '---')")
.append(" AND " + COLUMNNAME_I_IsImported + "<>'Y'")
|
.append(selection.toSqlWhereClause("i"));
DB.executeUpdateAndThrowExceptionOnFail(sql.toString(), ITrx.TRXNAME_ThreadInherited);
}
public static void dbUpdateIsPriceCopiedToYes(@NonNull final String targetTableName, @NonNull final String columnName)
{
StringBuilder sql;
sql = new StringBuilder("UPDATE ")
.append(targetTableName + " i ")
.append(" SET " + columnName + " = 'Y' ")
.append(" WHERE coalesce(" + columnName + ", 'N') != 'Y'");
DB.executeUpdateAndThrowExceptionOnFail(sql.toString(), ITrx.TRXNAME_ThreadInherited);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\product\impexp\MProductImportTableSqlUpdater.java
| 1
|
请完成以下Java代码
|
public class ForEachLoop {
public static void main(String[] args) {
int[] numbers = { 1, 2, 3, 4, 5 };
List<String> wordsList = new ArrayList<>();
wordsList.add("Java");
wordsList.add("is");
wordsList.add("great!");
Set<String> wordsSet = new HashSet<>();
wordsSet.addAll(wordsList);
Map<Integer, String> map = new HashMap<>();
map.put(1, "Java");
map.put(2, "is");
map.put(3, "great!");
traverseArray(numbers);
traverseList(wordsList);
traverseSet(wordsSet);
traverseMap(map);
}
private static void traverseMap(Map<Integer, String> map) {
for (Map.Entry<Integer, String> entry : map.entrySet()) {
System.out.println("number: " + entry.getKey() + " - " + "word: " + entry.getValue());
|
}
}
private static void traverseSet(Set<String> wordsSet) {
for (String word : wordsSet) {
System.out.println(word + " ");
}
}
private static void traverseList(List<String> wordsList) {
for (String word : wordsList) {
System.out.println(word + " ");
}
}
private static void traverseArray(int[] numbers) {
for (int number : numbers) {
System.out.println(number + " ");
}
}
}
|
repos\tutorials-master\core-java-modules\core-java-lang-syntax\src\main\java\com\baeldung\core\controlstructures\loops\ForEachLoop.java
| 1
|
请完成以下Java代码
|
public BigDecimal retrieveMinimumSumPercentage()
{
final String minimumPercentageAccepted_Value = sysConfigBL.getValue(
SYS_CONFIG_DefaultMinimumPercentage, SYS_CONFIG_DefaultMinimumPercentage_DEFAULT);
try
{
return new BigDecimal(minimumPercentageAccepted_Value);
}
catch (final NumberFormatException e)
{
Check.errorIf(true, "AD_SysConfig {} = {} can't be parsed as a number", SYS_CONFIG_DefaultMinimumPercentage, minimumPercentageAccepted_Value);
return null; // shall not be reached
}
}
@Override
public void save(@NonNull final I_EDI_Desadv ediDesadv)
{
InterfaceWrapperHelper.save(ediDesadv);
}
@Override
public void save(@NonNull final I_EDI_DesadvLine ediDesadvLine)
{
InterfaceWrapperHelper.save(ediDesadvLine);
}
@Override
@NonNull
|
public List<I_M_InOut> retrieveShipmentsWithStatus(@NonNull final I_EDI_Desadv desadv, @NonNull final ImmutableSet<EDIExportStatus> statusSet)
{
return queryBL.createQueryBuilder(I_M_InOut.class, desadv)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_M_InOut.COLUMNNAME_EDI_Desadv_ID, desadv.getEDI_Desadv_ID())
.addInArrayFilter(I_M_InOut.COLUMNNAME_EDI_ExportStatus, statusSet)
.create()
.list(I_M_InOut.class);
}
@Override
@NonNull
public I_M_InOut_Desadv_V getInOutDesadvByInOutId(@NonNull final InOutId shipmentId)
{
return queryBL.createQueryBuilder(I_M_InOut_Desadv_V.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_M_InOut_Desadv_V.COLUMNNAME_M_InOut_ID, shipmentId)
.create()
.firstOnlyNotNull(I_M_InOut_Desadv_V.class);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\api\impl\DesadvDAO.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class Saml2AssertionAuthentication extends Saml2Authentication {
@Serial
private static final long serialVersionUID = -4194323643788693205L;
private final Saml2ResponseAssertionAccessor assertion;
private final String relyingPartyRegistrationId;
public Saml2AssertionAuthentication(Saml2ResponseAssertionAccessor assertion,
Collection<? extends GrantedAuthority> authorities, String relyingPartyRegistrationId) {
super(assertion, assertion.getResponseValue(), authorities);
this.assertion = assertion;
this.relyingPartyRegistrationId = relyingPartyRegistrationId;
}
public Saml2AssertionAuthentication(Object principal, Saml2ResponseAssertionAccessor assertion,
Collection<? extends GrantedAuthority> authorities, String relyingPartyRegistrationId) {
super(principal, assertion.getResponseValue(), authorities);
this.assertion = assertion;
this.relyingPartyRegistrationId = relyingPartyRegistrationId;
setAuthenticated(true);
}
protected Saml2AssertionAuthentication(Builder<?> builder) {
super(builder);
this.assertion = builder.assertion;
this.relyingPartyRegistrationId = builder.relyingPartyRegistrationId;
}
@Override
public Saml2ResponseAssertionAccessor getCredentials() {
return this.assertion;
}
public String getRelyingPartyRegistrationId() {
return this.relyingPartyRegistrationId;
}
@Override
public Builder<?> toBuilder() {
return new Builder<>(this);
}
/**
* A builder of {@link Saml2AssertionAuthentication} instances
*
* @since 7.0
*/
|
public static class Builder<B extends Builder<B>> extends Saml2Authentication.Builder<B> {
private Saml2ResponseAssertionAccessor assertion;
private String relyingPartyRegistrationId;
protected Builder(Saml2AssertionAuthentication token) {
super(token);
this.assertion = token.assertion;
this.relyingPartyRegistrationId = token.relyingPartyRegistrationId;
}
/**
* Use these credentials. They must be of type
* {@link Saml2ResponseAssertionAccessor}.
* @param credentials the credentials to use
* @return the {@link Builder} for further configurations
*/
@Override
public B credentials(@Nullable Object credentials) {
Assert.isInstanceOf(Saml2ResponseAssertionAccessor.class, credentials,
"credentials must be of type Saml2ResponseAssertionAccessor");
saml2Response(((Saml2ResponseAssertionAccessor) credentials).getResponseValue());
this.assertion = (Saml2ResponseAssertionAccessor) credentials;
return (B) this;
}
/**
* Use this registration id
* @param relyingPartyRegistrationId the
* {@link RelyingPartyRegistration#getRegistrationId} to use
* @return the {@link Builder} for further configurations
*/
public B relyingPartyRegistrationId(String relyingPartyRegistrationId) {
this.relyingPartyRegistrationId = relyingPartyRegistrationId;
return (B) this;
}
@Override
public Saml2AssertionAuthentication build() {
return new Saml2AssertionAuthentication(this);
}
}
}
|
repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\provider\service\authentication\Saml2AssertionAuthentication.java
| 2
|
请完成以下Java代码
|
public void setUseLifeMonths (int UseLifeMonths)
{
set_Value (COLUMNNAME_UseLifeMonths, Integer.valueOf(UseLifeMonths));
}
/** Get Usable Life - Months.
@return Months of the usable life of the asset
*/
public int getUseLifeMonths ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_UseLifeMonths);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Usable Life - Years.
@param UseLifeYears
Years of the usable life of the asset
|
*/
public void setUseLifeYears (int UseLifeYears)
{
set_Value (COLUMNNAME_UseLifeYears, Integer.valueOf(UseLifeYears));
}
/** Get Usable Life - Years.
@return Years of the usable life of the asset
*/
public int getUseLifeYears ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_UseLifeYears);
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_A_Asset_Group_Acct.java
| 1
|
请完成以下Java代码
|
public void setDisplay()
{
m_text.setText(getDisplay());
final boolean isDatabaseOK = m_value != null && m_value.isDatabaseOK();
// Mark the text field as error if both AppsServer and DB connections are not established
setBackground(!isDatabaseOK);
// Mark the connection indicator button as error if any of AppsServer or DB connection is not established.
btnConnection.setBackground(isDatabaseOK ? AdempierePLAF.getFieldBackground_Normal() : AdempierePLAF.getFieldBackground_Error());
}
/**
* Add Action Listener
*/
public synchronized void addActionListener(final ActionListener l)
{
listenerList.add(ActionListener.class, l);
} // addActionListener
/**
* Fire Action Performed
*/
private void fireActionPerformed()
{
ActionEvent e = null;
ActionListener[] listeners = listenerList.getListeners(ActionListener.class);
for (int i = 0; i < listeners.length; i++)
{
if (e == null)
e = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "actionPerformed");
listeners[i].actionPerformed(e);
}
} // fireActionPerformed
private void actionEditConnection()
{
if (!isEnabled() || !m_rw)
{
return;
}
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
try
{
final CConnection connection = getValue();
final CConnectionDialog dialog = new CConnectionDialog(connection);
if (dialog.isCancel())
{
return;
}
final CConnection connectionNew = dialog.getConnection();
setValue(connectionNew);
DB.setDBTarget(connectionNew);
|
fireActionPerformed();
}
finally
{
setCursor(Cursor.getDefaultCursor());
}
}
/**
* MouseListener
*/
private class CConnectionEditor_MouseListener extends MouseAdapter
{
/** Mouse Clicked - Open connection editor */
@Override
public void mouseClicked(final MouseEvent e)
{
if (m_active)
return;
m_active = true;
try
{
actionEditConnection();
}
finally
{
m_active = false;
}
}
private boolean m_active = false;
}
} // CConnectionEditor
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\db\CConnectionEditor.java
| 1
|
请完成以下Java代码
|
public void attachState(MigratingScopeInstance newOwningInstance) {
attachTo(newOwningInstance.resolveRepresentativeExecution());
}
@Override
public void attachState(MigratingTransitionInstance targetTransitionInstance) {
attachTo(targetTransitionInstance.resolveRepresentativeExecution());
}
public void migrateState() {
incident.setActivityId(targetScope.getId());
incident.setProcessDefinitionId(targetScope.getProcessDefinition().getId());
incident.setJobDefinitionId(targetJobDefinitionId);
migrateHistory();
}
protected void migrateHistory() {
HistoryLevel historyLevel = Context.getProcessEngineConfiguration().getHistoryLevel();
if (historyLevel.isHistoryEventProduced(HistoryEventTypes.INCIDENT_MIGRATE, this)) {
HistoryEventProcessor.processHistoryEvents(new HistoryEventProcessor.HistoryEventCreator() {
@Override
|
public HistoryEvent createHistoryEvent(HistoryEventProducer producer) {
return producer.createHistoricIncidentMigrateEvt(incident);
}
});
}
}
public void migrateDependentEntities() {
// nothing to do
}
protected void attachTo(ExecutionEntity execution) {
incident.setExecution(execution);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\instance\MigratingIncident.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public PatientNoteMapping updatedAt(String updatedAt) {
this.updatedAt = updatedAt;
return this;
}
/**
* Der Zeitstempel der letzten Änderung
* @return updatedAt
**/
@Schema(example = "2019-11-28T08:37:39.637Z", description = "Der Zeitstempel der letzten Änderung")
public String getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(String updatedAt) {
this.updatedAt = updatedAt;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
PatientNoteMapping patientNoteMapping = (PatientNoteMapping) o;
return Objects.equals(this._id, patientNoteMapping._id) &&
Objects.equals(this.updatedAt, patientNoteMapping.updatedAt);
}
@Override
|
public int hashCode() {
return Objects.hash(_id, updatedAt);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class PatientNoteMapping {\n");
sb.append(" _id: ").append(toIndentedString(_id)).append("\n");
sb.append(" updatedAt: ").append(toIndentedString(updatedAt)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-patient-api\src\main\java\io\swagger\client\model\PatientNoteMapping.java
| 2
|
请完成以下Java代码
|
public boolean contains(int x, int y) {
return ((x >= x0 && x <= x1) && (y >= y0 && y <= y1));
}
}
/**
* Creates and returns an array of integers from the String
* <code>stringCoords</code>. If one of the values represents a
* % the returned value with be negative. If a parse error results
* from trying to parse one of the numbers null is returned.
*/
static protected int[] extractCoords(Object stringCoords) {
if (stringCoords == null || !(stringCoords instanceof String)) {
return null;
}
StringTokenizer st = new StringTokenizer((String) stringCoords, ", \t\n\r");
int[] retValue = null;
int numCoords = 0;
while (st.hasMoreElements()) {
String token = st.nextToken();
int scale;
if (token.endsWith("%")) {
scale = -1;
token = token.substring(0, token.length() - 1);
}
else {
scale = 1;
}
try {
int intValue = Integer.parseInt(token);
if (retValue == null) {
retValue = new int[4];
}
else if (numCoords == retValue.length) {
int[] temp = new int[retValue.length * 2];
System.arraycopy(retValue, 0, temp, 0, retValue.length);
retValue = temp;
}
retValue[numCoords++] = intValue * scale;
}
catch (NumberFormatException nfe) {
return null;
}
}
|
if (numCoords > 0 && numCoords != retValue.length) {
int[] temp = new int[numCoords];
System.arraycopy(retValue, 0, temp, 0, numCoords);
retValue = temp;
}
return retValue;
}
/**
* Defines the interface used for to check if a point is inside a
* region.
*/
interface RegionContainment {
/**
* Returns true if the location <code>x</code>, <code>y</code>
* falls inside the region defined in the receiver.
* <code>width</code>, <code>height</code> is the size of
* the enclosing region.
*/
public boolean contains(int x, int y, int width, int height);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\net\sf\memoranda\ui\htmleditor\AltHTMLWriter.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class StateHandlerAnnotationBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
private ProcessEngine processEngine ;
private Logger log = Logger.getLogger(getClass().getName());
public void setProcessEngine(ProcessEngine processEngine) {
this.processEngine = processEngine;
}
private void configureDefaultActivitiRegistry(String registryBeanName, BeanDefinitionRegistry registry) {
if (!beanAlreadyConfigured(registry, registryBeanName, ActivitiStateHandlerRegistry.class)) {
String registryName =ActivitiStateHandlerRegistry.class.getName();
log.info( "registering a " + registryName + " instance under bean name "+ ActivitiContextUtils.ACTIVITI_REGISTRY_BEAN_NAME+ ".");
RootBeanDefinition rootBeanDefinition = new RootBeanDefinition();
rootBeanDefinition.setBeanClassName( registryName );
rootBeanDefinition.getPropertyValues().addPropertyValue("processEngine", this.processEngine);
BeanDefinitionHolder holder = new BeanDefinitionHolder(rootBeanDefinition, registryBeanName);
BeanDefinitionReaderUtils.registerBeanDefinition(holder, registry);
}
}
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
if (beanFactory instanceof BeanDefinitionRegistry) {
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
configureDefaultActivitiRegistry(ActivitiContextUtils.ACTIVITI_REGISTRY_BEAN_NAME, registry);
} else {
log.info("BeanFactory is not a BeanDefinitionRegistry. The default '"
|
+ ActivitiContextUtils.ACTIVITI_REGISTRY_BEAN_NAME + "' cannot be configured.");
}
}
private boolean beanAlreadyConfigured(BeanDefinitionRegistry registry, String beanName, Class clz) {
if (registry.isBeanNameInUse(beanName)) {
BeanDefinition bDef = registry.getBeanDefinition(beanName);
if (bDef.getBeanClassName().equals(clz.getName())) {
return true; // so the beans already registered, and of the right type. so we assume the user is overriding our configuration
} else {
throw new IllegalStateException("The bean name '" + beanName + "' is reserved.");
}
}
return false;
}
}
|
repos\camunda-bpm-platform-master\engine-spring\core\src\main\java\org\camunda\bpm\engine\spring\components\config\xml\StateHandlerAnnotationBeanFactoryPostProcessor.java
| 2
|
请完成以下Java代码
|
public class Product {
/**
* 商品ID
*/
private String id;
/**
* 商品名称
*/
private String name;
/**
* 商品价格
*/
private BigDecimal price;
|
/**
* 商品分类
*/
private String category;
/**
* 商品描述
*/
private String description;
/**
* 库存数量
*/
private Integer stock;
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-module\jeecg-module-demo\src\main\java\org\jeecg\modules\demo\shop\entity\Product.java
| 1
|
请完成以下Java代码
|
public class WalletKit {
static Logger logger = LoggerFactory.getLogger(WalletKit.class);
public static void main(String[] args) throws InsufficientMoneyException {
NetworkParameters params = TestNet3Params.get();
WalletAppKit kit = new WalletAppKit(params, new File("."), "baeldungkit") {
@Override
protected void onSetupCompleted() {
logger.info("Wallet created and loaded successfully.");
logger.info("Receive address: " + wallet().currentReceiveAddress());
logger.info("Seed Phrase: " + wallet().getKeyChainSeed());
logger.info("Balance: " + wallet().getBalance()
.toFriendlyString());
logger.info("Public Key: " + wallet().findKeyFromAddress(wallet().currentReceiveAddress())
.getPublicKeyAsHex());
logger.info("Private Key: " + wallet().findKeyFromAddress(wallet().currentReceiveAddress())
.getPrivateKeyAsHex());
wallet().encrypt("password");
}
};
|
kit.startAsync();
kit.awaitRunning();
kit.setAutoSave(true);
kit.wallet()
.addCoinsReceivedEventListener((wallet, tx, prevBalance, newBalance) -> {
logger.info("-----> coins resceived: " + tx.getTxId());
logger.info("received: " + tx.getValue(wallet));
});
String receiveAddress = "n1vb1YZXyMQxvEjkc53VULi5KTiRtcAA9G";
Coin value = Coin.valueOf(200);
final Coin amountToSend = value.subtract(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE);
final Wallet.SendResult sendResult = kit.wallet()
.sendCoins(kit.peerGroup(), Address.fromString(params, receiveAddress), amountToSend);
kit.wallet()
.addCoinsSentEventListener((wallet, tx, prevBalance, newBalance) -> logger.info("new balance: " + newBalance.toFriendlyString()));
}
}
|
repos\tutorials-master\java-blockchain\src\main\java\com\baeldung\bitcoinj\WalletKit.java
| 1
|
请完成以下Java代码
|
public String getProcessInstanceId() {
return processInstanceId;
}
@Override
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
@Override
public String getActivityInstanceId() {
return activityInstanceId;
}
@Override
public void setActivityInstanceId(String activityInstanceId) {
this.activityInstanceId = activityInstanceId;
}
@Override
public String getTaskId() {
return taskId;
}
@Override
public void setTaskId(String taskId) {
this.taskId = taskId;
}
@Override
public String getExecutionId() {
return executionId;
}
@Override
public void setExecutionId(String executionId) {
this.executionId = executionId;
}
|
@Override
public Date getTime() {
return time;
}
@Override
public void setTime(Date time) {
this.time = time;
}
@Override
public String getDetailType() {
return detailType;
}
@Override
public void setDetailType(String detailType) {
this.detailType = detailType;
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\HistoricDetailEntityImpl.java
| 1
|
请完成以下Java代码
|
public int getM_ProductPrice_Base_ID()
{
return get_ValueAsInt(COLUMNNAME_M_ProductPrice_Base_ID);
}
@Override
public void setM_ProductPrice_ID (final int M_ProductPrice_ID)
{
if (M_ProductPrice_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_ProductPrice_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_ProductPrice_ID, M_ProductPrice_ID);
}
@Override
public int getM_ProductPrice_ID()
{
return get_ValueAsInt(COLUMNNAME_M_ProductPrice_ID);
}
@Override
public void setMatchSeqNo (final int MatchSeqNo)
{
set_Value (COLUMNNAME_MatchSeqNo, MatchSeqNo);
}
@Override
public int getMatchSeqNo()
{
return get_ValueAsInt(COLUMNNAME_MatchSeqNo);
}
@Override
public void setPriceLimit (final BigDecimal PriceLimit)
{
set_Value (COLUMNNAME_PriceLimit, PriceLimit);
}
@Override
public BigDecimal getPriceLimit()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PriceLimit);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setPriceList (final BigDecimal PriceList)
{
set_Value (COLUMNNAME_PriceList, PriceList);
}
@Override
public BigDecimal getPriceList()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PriceList);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setPriceStd (final BigDecimal PriceStd)
{
set_Value (COLUMNNAME_PriceStd, PriceStd);
}
|
@Override
public BigDecimal getPriceStd()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PriceStd);
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);
}
/**
* UseScalePrice AD_Reference_ID=541376
* Reference name: UseScalePrice
*/
public static final int USESCALEPRICE_AD_Reference_ID=541376;
/** Use scale price, fallback to product price = Y */
public static final String USESCALEPRICE_UseScalePriceFallbackToProductPrice = "Y";
/** Don't use scale price = N */
public static final String USESCALEPRICE_DonTUseScalePrice = "N";
/** Use scale price (strict) = S */
public static final String USESCALEPRICE_UseScalePriceStrict = "S";
@Override
public void setUseScalePrice (final java.lang.String UseScalePrice)
{
set_Value (COLUMNNAME_UseScalePrice, UseScalePrice);
}
@Override
public java.lang.String getUseScalePrice()
{
return get_ValueAsString(COLUMNNAME_UseScalePrice);
}
@Override
public void setValidFrom (final @Nullable java.sql.Timestamp ValidFrom)
{
throw new IllegalArgumentException ("ValidFrom is virtual column"); }
@Override
public java.sql.Timestamp getValidFrom()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidFrom);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_ProductPrice.java
| 1
|
请完成以下Java代码
|
public class CQueue
{
private QueueElement pHead = null;
private QueueElement pLastAccess = null;
/**
* 将QueueElement根据eWeight由小到大的顺序插入队列
* @param newElement
*/
public void enQueue(QueueElement newElement)
{
QueueElement pCur = pHead, pPre = null;
while (pCur != null && pCur.weight < newElement.weight)
{
pPre = pCur;
pCur = pCur.next;
}
newElement.next = pCur;
if (pPre == null)
pHead = newElement;
else
pPre.next = newElement;
}
/**
* 从队列中取出前面的一个元素
* @return
*/
public QueueElement deQueue()
{
if (pHead == null)
return null;
QueueElement pRet = pHead;
pHead = pHead.next;
return pRet;
}
/**
* 读取第一个元素,但不执行DeQueue操作
* @return
*/
public QueueElement GetFirst()
{
pLastAccess = pHead;
return pLastAccess;
}
/**
* 读取上次读取后的下一个元素,不执行DeQueue操作
|
* @return
*/
public QueueElement GetNext()
{
if (pLastAccess != null)
pLastAccess = pLastAccess.next;
return pLastAccess;
}
/**
* 是否仍然有下一个元素可供读取
* @return
*/
public boolean CanGetNext()
{
return (pLastAccess.next != null);
}
/**
* 清除所有元素
*/
public void clear()
{
pHead = null;
pLastAccess = null;
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\seg\NShort\Path\CQueue.java
| 1
|
请完成以下Java代码
|
public UserTask clone() {
UserTask clone = new UserTask();
clone.setValues(this);
return clone;
}
public void setValues(UserTask otherElement) {
super.setValues(otherElement);
setAssignee(otherElement.getAssignee());
setOwner(otherElement.getOwner());
setFormKey(otherElement.getFormKey());
setDueDate(otherElement.getDueDate());
setPriority(otherElement.getPriority());
setCategory(otherElement.getCategory());
setExtensionId(otherElement.getExtensionId());
setSkipExpression(otherElement.getSkipExpression());
setCandidateGroups(new ArrayList<String>(otherElement.getCandidateGroups()));
setCandidateUsers(new ArrayList<String>(otherElement.getCandidateUsers()));
setCustomGroupIdentityLinks(otherElement.customGroupIdentityLinks);
|
setCustomUserIdentityLinks(otherElement.customUserIdentityLinks);
formProperties = new ArrayList<FormProperty>();
if (otherElement.getFormProperties() != null && !otherElement.getFormProperties().isEmpty()) {
for (FormProperty property : otherElement.getFormProperties()) {
formProperties.add(property.clone());
}
}
taskListeners = new ArrayList<ActivitiListener>();
if (otherElement.getTaskListeners() != null && !otherElement.getTaskListeners().isEmpty()) {
for (ActivitiListener listener : otherElement.getTaskListeners()) {
taskListeners.add(listener.clone());
}
}
}
@Override
public void accept(ReferenceOverrider referenceOverrider) {
referenceOverrider.override(this);
}
}
|
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\UserTask.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private static int getAdTableId(final Document document)
{
final String tableName = document.getEntityDescriptor().getTableNameOrNull();
if (tableName == null)
{
// cannot apply security because this is not table based
return -1; // OK
}
return Services.get(IADTableDAO.class).retrieveTableId(tableName);
}
private static int getRecordId(final Document document)
{
if (document.isNew())
{
return -1;
}
else
|
{
return document.getDocumentId().toIntOr(-1);
}
}
public static boolean isNewDocumentAllowed(@NonNull final DocumentEntityDescriptor entityDescriptor, @NonNull final UserSession userSession)
{
final AdWindowId adWindowId = entityDescriptor.getWindowId().toAdWindowIdOrNull();
if (adWindowId == null) {return true;}
final IUserRolePermissions permissions = userSession.getUserRolePermissions();
final ElementPermission windowPermission = permissions.checkWindowPermission(adWindowId);
if (!windowPermission.hasWriteAccess()) {return false;}
final ILogicExpression allowExpr = entityDescriptor.getAllowCreateNewLogic();
final LogicExpressionResult allow = allowExpr.evaluateToResult(userSession.toEvaluatee(), IExpressionEvaluator.OnVariableNotFound.ReturnNoResult);
return allow.isTrue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\controller\DocumentPermissionsHelper.java
| 2
|
请完成以下Java代码
|
public Object register(UserForm userForm, BindingResult binding, Model model) {
userForm.validate(binding, userManagement);
if (binding.hasErrors()) {
return "users";
}
userManagement.register(new Username(userForm.getUsername()), Password.raw(userForm.getPassword()));
var redirectView = new RedirectView("redirect:/users");
redirectView.setPropagateQueryParams(true);
return redirectView;
}
/**
* Populates the {@link Model} with the {@link UserForm} automatically created by Spring Data web components. It will
* create a {@link Map}-backed proxy for the interface.
*
* @param model will never be {@literal null}.
* @param userForm will never be {@literal null}.
* @return
*/
@RequestMapping(method = RequestMethod.GET)
public String listUsers(Model model, UserForm userForm) {
model.addAttribute("userForm", userForm);
return "users";
}
/**
* An interface to represent the form to be used
*
* @author Oliver Gierke
*/
interface UserForm {
String getUsername();
String getPassword();
String getRepeatedPassword();
/**
|
* Validates the {@link UserForm}.
*
* @param errors
* @param userManagement
*/
default void validate(BindingResult errors, UserManagement userManagement) {
rejectIfEmptyOrWhitespace(errors, "username", "user.username.empty");
rejectIfEmptyOrWhitespace(errors, "password", "user.password.empty");
rejectIfEmptyOrWhitespace(errors, "repeatedPassword", "user.repeatedPassword.empty");
if (!getPassword().equals(getRepeatedPassword())) {
errors.rejectValue("repeatedPassword", "user.password.no-match");
}
try {
userManagement.findByUsername(new Username(getUsername())).ifPresent(
user -> errors.rejectValue("username", "user.username.exists"));
} catch (IllegalArgumentException o_O) {
errors.rejectValue("username", "user.username.invalidFormat");
}
}
}
}
|
repos\spring-data-examples-main\web\example\src\main\java\example\users\web\UserController.java
| 1
|
请完成以下Java代码
|
public Builder tbMsgId(UUID tbMsgId) {
this.tbMsgId = tbMsgId;
return this;
}
public Builder tbMsgType(TbMsgType tbMsgType) {
this.tbMsgType = tbMsgType;
return this;
}
public Builder callback(FutureCallback<Void> callback) {
this.callback = callback;
return this;
}
public Builder future(SettableFuture<Void> future) {
return callback(new FutureCallback<>() {
@Override
public void onSuccess(Void result) {
future.set(result);
|
}
@Override
public void onFailure(Throwable t) {
future.setException(t);
}
});
}
public AttributesDeleteRequest build() {
return new AttributesDeleteRequest(
tenantId, entityId, scope, keys, notifyDevice, previousCalculatedFieldIds, tbMsgId, tbMsgType, requireNonNullElse(callback, NoOpFutureCallback.instance())
);
}
}
}
|
repos\thingsboard-master\rule-engine\rule-engine-api\src\main\java\org\thingsboard\rule\engine\api\AttributesDeleteRequest.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class AppController {
private final AppService appService;
@ApiOperation("导出应用数据")
@GetMapping(value = "/download")
@PreAuthorize("@el.check('app:list')")
public void exportApp(HttpServletResponse response, AppQueryCriteria criteria) throws IOException {
appService.download(appService.queryAll(criteria), response);
}
@ApiOperation(value = "查询应用")
@GetMapping
@PreAuthorize("@el.check('app:list')")
public ResponseEntity<PageResult<AppDto>> queryApp(AppQueryCriteria criteria, Pageable pageable){
return new ResponseEntity<>(appService.queryAll(criteria,pageable),HttpStatus.OK);
}
@Log("新增应用")
@ApiOperation(value = "新增应用")
@PostMapping
@PreAuthorize("@el.check('app:add')")
public ResponseEntity<Object> createApp(@Validated @RequestBody App resources){
appService.create(resources);
|
return new ResponseEntity<>(HttpStatus.CREATED);
}
@Log("修改应用")
@ApiOperation(value = "修改应用")
@PutMapping
@PreAuthorize("@el.check('app:edit')")
public ResponseEntity<Object> updateApp(@Validated @RequestBody App resources){
appService.update(resources);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
@Log("删除应用")
@ApiOperation(value = "删除应用")
@DeleteMapping
@PreAuthorize("@el.check('app:del')")
public ResponseEntity<Object> deleteApp(@RequestBody Set<Long> ids){
appService.delete(ids);
return new ResponseEntity<>(HttpStatus.OK);
}
}
|
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\maint\rest\AppController.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public List<HistoricEntityLinkEntity> findHistoricEntityLinksByQuery(InternalEntityLinkQuery<HistoricEntityLinkEntity> query) {
return getList("selectHistoricEntityLinksByQuery", query, (CachedEntityMatcher<HistoricEntityLinkEntity>) query, true);
}
@Override
@SuppressWarnings("unchecked")
public HistoricEntityLinkEntity findHistoricEntityLinkByQuery(InternalEntityLinkQuery<HistoricEntityLinkEntity> query) {
return getEntity("selectHistoricEntityLinksByQuery", query, (SingleCachedEntityMatcher<HistoricEntityLinkEntity>) query, true);
}
@Override
public void deleteHistoricEntityLinksByScopeIdAndType(String scopeId, String scopeType) {
Map<String, String> parameters = new HashMap<>();
parameters.put("scopeId", scopeId);
parameters.put("scopeType", scopeType);
getDbSqlSession().delete("deleteHistoricEntityLinksByScopeIdAndScopeType", parameters, HistoricEntityLinkEntityImpl.class);
}
@Override
public void deleteHistoricEntityLinksByScopeDefinitionIdAndType(String scopeDefinitionId, String scopeType) {
Map<String, String> parameters = new HashMap<>();
parameters.put("scopeDefinitionId", scopeDefinitionId);
parameters.put("scopeType", scopeType);
getDbSqlSession().delete("deleteHistoricEntityLinksByScopeDefinitionIdAndScopeType", parameters, HistoricEntityLinkEntityImpl.class);
}
@Override
public void bulkDeleteHistoricEntityLinksForScopeTypeAndScopeIds(String scopeType, Collection<String> scopeIds) {
Map<String, Object> parameters = new HashMap<>();
parameters.put("scopeType", scopeType);
parameters.put("scopeIds", createSafeInValuesList(scopeIds));
getDbSqlSession().delete("bulkDeleteHistoricEntityLinksForScopeTypeAndScopeIds", parameters, HistoricEntityLinkEntityImpl.class);
}
@Override
|
public void deleteHistoricEntityLinksForNonExistingProcessInstances() {
getDbSqlSession().delete("bulkDeleteHistoricProcessEntityLinks", null, HistoricEntityLinkEntityImpl.class);
}
@Override
public void deleteHistoricEntityLinksForNonExistingCaseInstances() {
getDbSqlSession().delete("bulkDeleteHistoricCaseEntityLinks", null, HistoricEntityLinkEntityImpl.class);
}
@Override
protected IdGenerator getIdGenerator() {
return entityLinkServiceConfiguration.getIdGenerator();
}
}
|
repos\flowable-engine-main\modules\flowable-entitylink-service\src\main\java\org\flowable\entitylink\service\impl\persistence\entity\data\impl\MybatisHistoricEntityLinkDataManager.java
| 2
|
请完成以下Java代码
|
public class SubscriptionState {
@Getter private final String wsSessionId;
@Getter private final int subscriptionId;
@Getter private final TenantId tenantId;
@Getter private final EntityId entityId;
@Getter private final TelemetryFeature type;
@Getter private final boolean allKeys;
@Getter private final Map<String, Long> keyStates;
@Getter private final String scope;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SubscriptionState that = (SubscriptionState) o;
if (subscriptionId != that.subscriptionId) return false;
if (wsSessionId != null ? !wsSessionId.equals(that.wsSessionId) : that.wsSessionId != null) return false;
if (entityId != null ? !entityId.equals(that.entityId) : that.entityId != null) return false;
return type == that.type;
}
@Override
public int hashCode() {
int result = wsSessionId != null ? wsSessionId.hashCode() : 0;
|
result = 31 * result + subscriptionId;
result = 31 * result + (entityId != null ? entityId.hashCode() : 0);
result = 31 * result + (type != null ? type.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "SubscriptionState{" +
"type=" + type +
", entityId=" + entityId +
", subscriptionId=" + subscriptionId +
", wsSessionId='" + wsSessionId + '\'' +
'}';
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\ws\telemetry\sub\SubscriptionState.java
| 1
|
请完成以下Java代码
|
public void setAuthenticationFailureHandler(AuthenticationFailureHandler authenticationFailureHandler) {
Assert.notNull(authenticationFailureHandler, "authenticationFailureHandler cannot be null");
this.authenticationFailureHandler = authenticationFailureHandler;
}
private Authentication createAuthentication(HttpServletRequest request) {
Authentication principal = SecurityContextHolder.getContext().getAuthentication();
return new OidcUserInfoAuthenticationToken(principal);
}
private void sendUserInfoResponse(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException {
OidcUserInfoAuthenticationToken userInfoAuthenticationToken = (OidcUserInfoAuthenticationToken) authentication;
ServletServerHttpResponse httpResponse = new ServletServerHttpResponse(response);
this.userInfoHttpMessageConverter.write(userInfoAuthenticationToken.getUserInfo(), null, httpResponse);
}
private void sendErrorResponse(HttpServletRequest request, HttpServletResponse response,
|
AuthenticationException authenticationException) throws IOException {
OAuth2Error error = ((OAuth2AuthenticationException) authenticationException).getError();
HttpStatus httpStatus = HttpStatus.BAD_REQUEST;
if (error.getErrorCode().equals(OAuth2ErrorCodes.INVALID_TOKEN)) {
httpStatus = HttpStatus.UNAUTHORIZED;
}
else if (error.getErrorCode().equals(OAuth2ErrorCodes.INSUFFICIENT_SCOPE)) {
httpStatus = HttpStatus.FORBIDDEN;
}
ServletServerHttpResponse httpResponse = new ServletServerHttpResponse(response);
httpResponse.setStatusCode(httpStatus);
this.errorHttpResponseConverter.write(error, null, httpResponse);
}
}
|
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\oidc\web\OidcUserInfoEndpointFilter.java
| 1
|
请完成以下Java代码
|
protected static JobEntity createJob(VariableContainer variableContainer, BaseElement baseElement, String jobHandlerType, CmmnEngineConfiguration cmmnEngineConfiguration) {
JobService jobService = cmmnEngineConfiguration.getJobServiceConfiguration().getJobService();
JobEntity job = jobService.createJob();
job.setJobHandlerType(jobHandlerType);
job.setScopeType(ScopeTypes.CMMN);
job.setElementId(baseElement.getId());
if (baseElement instanceof CaseElement) {
job.setElementName(((CaseElement) baseElement).getName());
}
List<ExtensionElement> jobCategoryElements = baseElement.getExtensionElements().get("jobCategory");
if (jobCategoryElements != null && jobCategoryElements.size() > 0) {
ExtensionElement jobCategoryElement = jobCategoryElements.get(0);
if (StringUtils.isNotEmpty(jobCategoryElement.getElementText())) {
|
Expression categoryExpression = cmmnEngineConfiguration.getExpressionManager().createExpression(jobCategoryElement.getElementText());
Object categoryValue = categoryExpression.getValue(variableContainer);
if (categoryValue != null) {
job.setCategory(categoryValue.toString());
}
}
}
job.setTenantId(variableContainer.getTenantId());
return job;
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\util\JobUtil.java
| 1
|
请完成以下Java代码
|
private List<I_M_PriceList_Version> retrieveLatestPriceListVersion()
{
final List<I_M_PriceList_Version> priceListVersions = new ArrayList<>();
final Set<PriceListId> priceListIds = retrievePriceLists();
priceListIds.forEach(priceListId -> {
final I_M_PriceList_Version plv = Services.get(IPriceListDAO.class).retrieveNewestPriceListVersion(priceListId);
if (plv != null)
{
priceListVersions.add(plv);
}
});
return priceListVersions;
}
/**
* create a set of price lists from the records which don't have the price copies <code>I_I_Pharma_Product.COLUMNNAME_IsPriceCopied</code> on 'N'
*/
private Set<PriceListId> retrievePriceLists()
{
final IQueryBL queryBL = Services.get(IQueryBL.class);
final String trxName = ITrx.TRXNAME_None;
final IQuery<I_I_Pharma_Product> pharmaPriceListQuery = queryBL.createQueryBuilder(I_I_Pharma_Product.class, trxName)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_I_Pharma_Product.COLUMNNAME_IsPriceCopied, false)
.create();
return queryBL.createQueryBuilder(I_M_PriceList.class, trxName)
.setJoinOr()
.addInSubQueryFilter(I_M_PriceList.COLUMNNAME_M_PriceList_ID, I_I_Pharma_Product.COLUMNNAME_AEP_Price_List_ID, pharmaPriceListQuery)
.addInSubQueryFilter(I_M_PriceList.COLUMNNAME_M_PriceList_ID, I_I_Pharma_Product.COLUMNNAME_APU_Price_List_ID, pharmaPriceListQuery)
.addInSubQueryFilter(I_M_PriceList.COLUMNNAME_M_PriceList_ID, I_I_Pharma_Product.COLUMNNAME_AVP_Price_List_ID, pharmaPriceListQuery)
|
.addInSubQueryFilter(I_M_PriceList.COLUMNNAME_M_PriceList_ID, I_I_Pharma_Product.COLUMNNAME_KAEP_Price_List_ID, pharmaPriceListQuery)
.addInSubQueryFilter(I_M_PriceList.COLUMNNAME_M_PriceList_ID, I_I_Pharma_Product.COLUMNNAME_UVP_Price_List_ID, pharmaPriceListQuery)
.addInSubQueryFilter(I_M_PriceList.COLUMNNAME_M_PriceList_ID, I_I_Pharma_Product.COLUMNNAME_ZBV_Price_List_ID, pharmaPriceListQuery)
.setOption(IQueryBuilder.OPTION_Explode_OR_Joins_To_SQL_Unions)
.create()
.setOption(IQuery.OPTION_IteratorBufferSize, 1000)
.listDistinct(I_M_PriceList.COLUMNNAME_M_PriceList_ID)
.stream()
.map(this::extractPriceListIdorNull)
.filter(Objects::nonNull)
.collect(ImmutableSet.toImmutableSet());
}
@Nullable private PriceListId extractPriceListIdorNull(@NonNull final Map<String, Object> map)
{
final int priceListId = NumberUtils.asInt(map.get(I_M_PriceList.COLUMNNAME_M_PriceList_ID), -1);
if (priceListId <= 0)
{
// shall not happen
return null;
}
return PriceListId.ofRepoId(priceListId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma\src\main\java\de\metas\impexp\product\IFAProductImportProcess.java
| 1
|
请完成以下Java代码
|
public static String getProperties(String property) {
return getProperties(property, null, String.class);
}
/**
* 获取SpringBoot 配置信息
*
* @param property 属性key
* @param requiredType 返回类型
* @return /
*/
public static <T> T getProperties(String property, Class<T> requiredType) {
return getProperties(property, null, requiredType);
}
/**
* 检查ApplicationContext不为空.
*/
private static void assertContextInjected() {
if (applicationContext == null) {
throw new IllegalStateException("applicaitonContext属性未注入, 请在applicationContext" +
".xml中定义SpringContextHolder或在SpringBoot启动类中注册SpringContextHolder.");
}
}
/**
* 清除SpringContextHolder中的ApplicationContext为Null.
*/
private static void clearHolder() {
log.debug("清除SpringContextHolder中的ApplicationContext:"
+ applicationContext);
applicationContext = null;
}
@Override
public void destroy() {
SpringBeanHolder.clearHolder();
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if (SpringBeanHolder.applicationContext != null) {
log.warn("SpringContextHolder中的ApplicationContext被覆盖, 原有ApplicationContext为:" + SpringBeanHolder.applicationContext);
}
SpringBeanHolder.applicationContext = applicationContext;
if (addCallback) {
for (SpringBeanHolder.CallBack callBack : SpringBeanHolder.CALL_BACKS) {
|
callBack.executor();
}
CALL_BACKS.clear();
}
SpringBeanHolder.addCallback = false;
}
/**
* 获取 @Service 的所有 bean 名称
* @return /
*/
public static List<String> getAllServiceBeanName() {
return new ArrayList<>(Arrays.asList(applicationContext
.getBeanNamesForAnnotation(Service.class)));
}
interface CallBack {
/**
* 回调执行方法
*/
void executor();
/**
* 本回调任务名称
* @return /
*/
default String getCallBackName() {
return Thread.currentThread().getId() + ":" + this.getClass().getName();
}
}
}
|
repos\eladmin-master\eladmin-common\src\main\java\me\zhengjie\utils\SpringBeanHolder.java
| 1
|
请完成以下Java代码
|
public void setVehicles(List<Vehicle> vehicles) {
this.vehicles = vehicles;
}
}
public static abstract class Vehicle {
private String make;
private String model;
protected Vehicle(String make, String model) {
this.make = make;
this.model = model;
}
public String getMake() {
return make;
}
public void setMake(String make) {
this.make = make;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
}
public static class Car extends Vehicle {
private int seatingCapacity;
private double topSpeed;
@JsonCreator
public Car(@JsonProperty("make") String make, @JsonProperty("model") String model, @JsonProperty("seating") int seatingCapacity, @JsonProperty("topSpeed") double topSpeed) {
super(make, model);
this.seatingCapacity = seatingCapacity;
this.topSpeed = topSpeed;
}
public int getSeatingCapacity() {
return seatingCapacity;
}
public void setSeatingCapacity(int seatingCapacity) {
this.seatingCapacity = seatingCapacity;
}
public double getTopSpeed() {
return topSpeed;
|
}
public void setTopSpeed(double topSpeed) {
this.topSpeed = topSpeed;
}
}
public static class Truck extends Vehicle {
private double payloadCapacity;
@JsonCreator
public Truck(@JsonProperty("make") String make, @JsonProperty("model") String model, @JsonProperty("payload") double payloadCapacity) {
super(make, model);
this.payloadCapacity = payloadCapacity;
}
public double getPayloadCapacity() {
return payloadCapacity;
}
public void setPayloadCapacity(double payloadCapacity) {
this.payloadCapacity = payloadCapacity;
}
}
}
|
repos\tutorials-master\jackson-modules\jackson-core\src\main\java\com\baeldung\jackson\inheritance\SubTypeConstructorStructure.java
| 1
|
请完成以下Java代码
|
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getCategoryId() {
return categoryId;
}
public void setCategoryId(Long categoryId) {
this.categoryId = categoryId;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Integer getShowStatus() {
return showStatus;
}
public void setShowStatus(Integer showStatus) {
this.showStatus = showStatus;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Integer getReadCount() {
return readCount;
}
|
public void setReadCount(Integer readCount) {
this.readCount = readCount;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
@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(", categoryId=").append(categoryId);
sb.append(", icon=").append(icon);
sb.append(", title=").append(title);
sb.append(", showStatus=").append(showStatus);
sb.append(", createTime=").append(createTime);
sb.append(", readCount=").append(readCount);
sb.append(", content=").append(content);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}
|
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\CmsHelp.java
| 1
|
请完成以下Java代码
|
public Class<? extends DeadLetterJobEntity> getManagedEntityClass() {
return DeadLetterJobEntityImpl.class;
}
@Override
public DeadLetterJobEntity create() {
return new DeadLetterJobEntityImpl();
}
@Override
public void delete(DeadLetterJobEntity entity) {
getDbSqlSession().delete(entity);
}
@Override
@SuppressWarnings("unchecked")
public List<Job> findJobsByQueryCriteria(DeadLetterJobQueryImpl jobQuery, Page page) {
String query = "selectDeadLetterJobByQueryCriteria";
return getDbSqlSession().selectList(query, jobQuery, page);
|
}
@Override
public long findJobCountByQueryCriteria(DeadLetterJobQueryImpl jobQuery) {
return (Long) getDbSqlSession().selectOne("selectDeadLetterJobCountByQueryCriteria", jobQuery);
}
@Override
public List<DeadLetterJobEntity> findJobsByExecutionId(String executionId) {
return getList("selectDeadLetterJobsByExecutionId", executionId, deadLetterByExecutionIdMatcher, true);
}
@Override
public void updateJobTenantIdForDeployment(String deploymentId, String newTenantId) {
HashMap<String, Object> params = new HashMap<String, Object>();
params.put("deploymentId", deploymentId);
params.put("tenantId", newTenantId);
getDbSqlSession().update("updateDeadLetterJobTenantIdForDeployment", params);
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\data\impl\MybatisDeadLetterJobDataManager.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class EmailServiceImpl implements EmailService {
private final EmailRepository emailRepository;
@Override
@CachePut(key = "'config'")
@Transactional(rollbackFor = Exception.class)
public EmailConfig config(EmailConfig emailConfig, EmailConfig old) throws Exception {
emailConfig.setId(1L);
if(!emailConfig.getPass().equals(old.getPass())){
// 对称加密
emailConfig.setPass(EncryptUtils.desEncrypt(emailConfig.getPass()));
}
return emailRepository.save(emailConfig);
}
@Override
@Cacheable(key = "'config'")
public EmailConfig find() {
Optional<EmailConfig> emailConfig = emailRepository.findById(1L);
return emailConfig.orElseGet(EmailConfig::new);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void send(EmailVo emailVo, EmailConfig emailConfig){
if(emailConfig.getId() == null){
throw new BadRequestException("请先配置,再操作");
}
// 封装
MailAccount account = new MailAccount();
// 设置用户
String user = emailConfig.getFromUser().split("@")[0];
account.setUser(user);
account.setHost(emailConfig.getHost());
|
account.setPort(Integer.parseInt(emailConfig.getPort()));
account.setAuth(true);
try {
// 对称解密
account.setPass(EncryptUtils.desDecrypt(emailConfig.getPass()));
} catch (Exception e) {
throw new BadRequestException(e.getMessage());
}
account.setFrom(emailConfig.getUser()+"<"+emailConfig.getFromUser()+">");
// ssl方式发送
account.setSslEnable(true);
// 使用STARTTLS安全连接
account.setStarttlsEnable(true);
// 解决jdk8之后默认禁用部分tls协议,导致邮件发送失败的问题
account.setSslProtocols("TLSv1 TLSv1.1 TLSv1.2");
String content = emailVo.getContent();
// 发送
try {
int size = emailVo.getTos().size();
Mail.create(account)
.setTos(emailVo.getTos().toArray(new String[size]))
.setTitle(emailVo.getSubject())
.setContent(content)
.setHtml(true)
//关闭session
.setUseGlobalSession(false)
.send();
}catch (Exception e){
throw new BadRequestException(e.getMessage());
}
}
}
|
repos\eladmin-master\eladmin-tools\src\main\java\me\zhengjie\service\impl\EmailServiceImpl.java
| 2
|
请完成以下Java代码
|
protected Set<String> getAllGroups() {
if(availableAuthorizedGroupIds == null) {
availableAuthorizedGroupIds = new HashSet<String>();
List<String> groupsFromDatabase = getDbEntityManager().selectList("selectAuthorizedGroupIds");
groupsFromDatabase.stream()
.filter(Objects::nonNull)
.forEach(availableAuthorizedGroupIds::add);
}
return availableAuthorizedGroupIds;
}
protected boolean isAuthCheckExecuted() {
Authentication currentAuthentication = getCurrentAuthentication();
CommandContext commandContext = Context.getCommandContext();
return isAuthorizationEnabled()
&& commandContext.isAuthorizationCheckEnabled()
&& currentAuthentication != null
&& currentAuthentication.getUserId() != null;
}
public boolean isEnsureSpecificVariablePermission() {
return Context.getProcessEngineConfiguration().isEnforceSpecificVariablePermission();
}
protected boolean isHistoricInstancePermissionsEnabled() {
return Context.getProcessEngineConfiguration().isEnableHistoricInstancePermissions();
}
public DbOperation addRemovalTimeToAuthorizationsByRootProcessInstanceId(String rootProcessInstanceId,
Date removalTime, Integer batchSize) {
Map<String, Object> parameters = new HashMap<>();
parameters.put("rootProcessInstanceId", rootProcessInstanceId);
parameters.put("removalTime", removalTime);
parameters.put("maxResults", batchSize);
return getDbEntityManager()
.updatePreserveOrder(AuthorizationEntity.class,
"updateAuthorizationsByRootProcessInstanceId", parameters);
}
public DbOperation addRemovalTimeToAuthorizationsByProcessInstanceId(String processInstanceId,
Date removalTime, Integer batchSize) {
Map<String, Object> parameters = new HashMap<>();
parameters.put("processInstanceId", processInstanceId);
parameters.put("removalTime", removalTime);
parameters.put("maxResults", batchSize);
|
return getDbEntityManager()
.updatePreserveOrder(AuthorizationEntity.class,
"updateAuthorizationsByProcessInstanceId", parameters);
}
public DbOperation deleteAuthorizationsByRemovalTime(Date removalTime, int minuteFrom,
int minuteTo, int batchSize) {
Map<String, Object> parameters = new HashMap<>();
parameters.put("removalTime", removalTime);
if (minuteTo - minuteFrom + 1 < 60) {
parameters.put("minuteFrom", minuteFrom);
parameters.put("minuteTo", minuteTo);
}
parameters.put("batchSize", batchSize);
return getDbEntityManager()
.deletePreserveOrder(AuthorizationEntity.class, "deleteAuthorizationsByRemovalTime",
new ListQueryParameterObject(parameters, 0, batchSize));
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\AuthorizationManager.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public int getM_InOutLine_ID()
{
return inOutLineId;
}
}
private static final WorkpackagesOnCommitSchedulerTemplate<InOutLineWithQualityIssues> SCHEDULER = new WorkpackagesOnCommitSchedulerTemplate<InOutLineWithQualityIssues>(C_Request_CreateFromInout_Async.class)
{
@Override
protected boolean isEligibleForScheduling(final InOutLineWithQualityIssues model)
{
return model != null && model.getM_InOutLine_ID() > 0;
}
;
@Override
protected Properties extractCtxFromItem(final InOutLineWithQualityIssues item)
{
return Env.getCtx();
}
@Override
protected String extractTrxNameFromItem(final InOutLineWithQualityIssues item)
{
return ITrx.TRXNAME_ThreadInherited;
}
@Override
|
protected Object extractModelToEnqueueFromItem(final Collector collector, final InOutLineWithQualityIssues item)
{
return TableRecordReference.of(I_M_InOutLine.Table_Name, item.getM_InOutLine_ID());
}
};
@Override
public Result processWorkPackage(final I_C_Queue_WorkPackage workPackage, final String localTrxName)
{
// Services
final IQueueDAO queueDAO = Services.get(IQueueDAO.class);
final IRequestBL requestBL = Services.get(IRequestBL.class);
// retrieve the items (inout lines) that were enqueued and put them in a list
final List<I_M_InOutLine> lines = queueDAO.retrieveAllItems(workPackage, I_M_InOutLine.class);
// for each line that was enqueued, create a R_Request containing the information from the inout line and inout
for (final I_M_InOutLine line : lines)
{
requestBL.createRequestFromInOutLineWithQualityIssues(line);
}
return Result.SUCCESS;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\request\service\async\spi\impl\C_Request_CreateFromInout_Async.java
| 2
|
请完成以下Java代码
|
public Boolean get_ValueAsBoolean(final String variableName, final Boolean defaultValue_IGNORED)
{
return params.getParameterAsBool(variableName);
}
@Override
public Date get_ValueAsDate(final String variableName, final Date defaultValue)
{
final Timestamp value = params.getParameterAsTimestamp(variableName);
return value != null ? value : defaultValue;
}
@Override
public Integer get_ValueAsInt(final String variableName, final Integer defaultValue)
{
final int defaultValueInt = defaultValue != null ? defaultValue : 0;
|
return params.getParameterAsInt(variableName, defaultValueInt);
}
@Override
public String get_ValueAsString(final String variableName)
{
return params.getParameterAsString(variableName);
}
@Override
public String get_ValueOldAsString(final String variableName)
{
return get_ValueAsString(variableName);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\util\Evaluatees.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class CancelJobsCmd implements Command<Void>, Serializable {
private static final long serialVersionUID = 1L;
protected JobServiceConfiguration jobServiceConfiguration;
protected List<String> jobIds;
public CancelJobsCmd(List<String> jobIds, JobServiceConfiguration jobServiceConfiguration) {
this.jobIds = jobIds;
this.jobServiceConfiguration = jobServiceConfiguration;
}
public CancelJobsCmd(String jobId, JobServiceConfiguration jobServiceConfiguration) {
this.jobIds = new ArrayList<>();
jobIds.add(jobId);
this.jobServiceConfiguration = jobServiceConfiguration;
}
@Override
public Void execute(CommandContext commandContext) {
JobEntity jobToDelete = null;
for (String jobId : jobIds) {
jobToDelete = jobServiceConfiguration.getJobEntityManager().findById(jobId);
FlowableEventDispatcher eventDispatcher = jobServiceConfiguration.getEventDispatcher();
if (jobToDelete != null) {
// When given job doesn't exist, ignore
if (eventDispatcher != null && eventDispatcher.isEnabled()) {
eventDispatcher.dispatchEvent(FlowableJobEventBuilder.createEntityEvent(FlowableEngineEventType.JOB_CANCELED, jobToDelete),
jobServiceConfiguration.getEngineName());
}
|
jobServiceConfiguration.getJobEntityManager().delete(jobToDelete);
} else {
TimerJobEntity timerJobToDelete = jobServiceConfiguration.getTimerJobEntityManager().findById(jobId);
if (timerJobToDelete != null) {
// When given job doesn't exist, ignore
if (eventDispatcher != null && eventDispatcher.isEnabled()) {
eventDispatcher.dispatchEvent(FlowableJobEventBuilder.createEntityEvent(FlowableEngineEventType.JOB_CANCELED, timerJobToDelete),
jobServiceConfiguration.getEngineName());
}
jobServiceConfiguration.getTimerJobEntityManager().delete(timerJobToDelete);
}
}
}
return null;
}
}
|
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\cmd\CancelJobsCmd.java
| 2
|
请完成以下Java代码
|
public void handleAddIdentityLinkToTask(TaskEntity taskEntity, IdentityLinkEntity identityLinkEntity) {
addUserIdentityLinkToParent(taskEntity, identityLinkEntity.getUserId());
}
@Override
public void handleAddAssigneeIdentityLinkToTask(TaskEntity taskEntity, String assignee) {
addUserIdentityLinkToParent(taskEntity, assignee);
}
@Override
public void handleAddOwnerIdentityLinkToTask(TaskEntity taskEntity, String owner) {
addUserIdentityLinkToParent(taskEntity, owner);
}
@Override
public void handleCreateProcessInstance(ExecutionEntity processInstanceExecution) {
String authenticatedUserId = Authentication.getAuthenticatedUserId();
if (authenticatedUserId != null) {
IdentityLinkUtil.createProcessInstanceIdentityLink(processInstanceExecution, authenticatedUserId, null, IdentityLinkType.STARTER);
}
}
|
@Override
public void handleCreateSubProcessInstance(ExecutionEntity subProcessInstanceExecution, ExecutionEntity superExecution) {
String authenticatedUserId = Authentication.getAuthenticatedUserId();
if (authenticatedUserId != null) {
IdentityLinkUtil.createProcessInstanceIdentityLink(subProcessInstanceExecution, authenticatedUserId, null, IdentityLinkType.STARTER);
}
}
protected void addUserIdentityLinkToParent(Task task, String userId) {
if (userId != null && task.getProcessInstanceId() != null) {
ExecutionEntity processInstanceEntity = CommandContextUtil.getExecutionEntityManager().findById(task.getProcessInstanceId());
for (IdentityLinkEntity identityLink : processInstanceEntity.getIdentityLinks()) {
if (identityLink.isUser() && identityLink.getUserId().equals(userId) && IdentityLinkType.PARTICIPANT.equals(identityLink.getType())) {
return;
}
}
IdentityLinkUtil.createProcessInstanceIdentityLink(processInstanceEntity, userId, null, IdentityLinkType.PARTICIPANT);
}
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\interceptor\DefaultIdentityLinkInterceptor.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class InvoiceCandUpdateSchedulerRequest implements IInvoiceCandUpdateSchedulerRequest
{
public static InvoiceCandUpdateSchedulerRequest of(
@NonNull final Properties ctx,
@Nullable final String trxName,
@Nullable final AsyncBatchId asyncBatchId)
{
return new InvoiceCandUpdateSchedulerRequest(ctx, trxName, asyncBatchId);
}
public static InvoiceCandUpdateSchedulerRequest of(@NonNull final I_C_Invoice_Candidate invoiceCandidate)
{
final Properties ctx = InterfaceWrapperHelper.getCtx(invoiceCandidate);
final String trxName = InterfaceWrapperHelper.getTrxName(invoiceCandidate);
final AsyncBatchId asyncBatchId = AsyncBatchId.ofRepoIdOrNull(invoiceCandidate.getC_Async_Batch_ID());
return InvoiceCandUpdateSchedulerRequest.of(ctx, trxName, asyncBatchId);
}
String trxName;
|
Properties ctx;
AsyncBatchId asyncBatchId;
private InvoiceCandUpdateSchedulerRequest(
@NonNull final Properties ctx,
@Nullable final String trxName,
@Nullable final AsyncBatchId asyncBatchId)
{
this.ctx = ctx;
// transaction name it's OK to be null
this.trxName = trxName;
this.asyncBatchId = asyncBatchId;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceCandUpdateSchedulerRequest.java
| 2
|
请完成以下Java代码
|
public void setAttributes(Map<String, List<ExtensionAttribute>> attributes) {
this.attributes = attributes;
}
public void setValues(BaseElement otherElement) {
setId(otherElement.getId());
if (otherElement.getExtensionElements() != null && !otherElement.getExtensionElements().isEmpty()) {
Map<String, List<ExtensionElement>> validExtensionElements = otherElement
.getExtensionElements()
.entrySet()
.stream()
.filter(e -> hasElements(e.getValue()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
extensionElements.putAll(validExtensionElements);
}
if (otherElement.getAttributes() != null && !otherElement.getAttributes().isEmpty()) {
Map<String, List<ExtensionAttribute>> validAttributes = otherElement
|
.getAttributes()
.entrySet()
.stream()
.filter(e -> hasElements(e.getValue()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
attributes.putAll(validAttributes);
}
}
private boolean hasElements(List<?> listOfElements) {
return listOfElements != null && !listOfElements.isEmpty();
}
public abstract BaseElement clone();
}
|
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\BaseElement.java
| 1
|
请完成以下Java代码
|
public ArrayList<Object> getData (boolean mandatory, boolean onlyValidated, boolean onlyActive, boolean temporary)
{
log.error("Not implemented");
return null;
} // getArray
@Override
public String getTableName()
{
return I_M_AttributeSetInstance.Table_Name;
}
/**
* Get underlying fully qualified Table.Column Name.
* Used for VLookup.actionButton (Zoom)
|
* @return column name
*/
@Override
public String getColumnName()
{
return I_M_AttributeSetInstance.Table_Name
+ "."
+ I_M_AttributeSetInstance.COLUMNNAME_M_AttributeSetInstance_ID;
} // getColumnName
@Override
public String getColumnNameNotFQ()
{
return I_M_AttributeSetInstance.COLUMNNAME_M_AttributeSetInstance_ID;
}
} // MPAttribute
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MPAttributeLookup.java
| 1
|
请完成以下Java代码
|
public String sayHello() {
return "Hello! What are you learning today?";
}
@RequestMapping("say-hello-html")
@ResponseBody
public String sayHelloHtml() {
StringBuffer sb = new StringBuffer();
sb.append("<html>");
sb.append("<head>");
sb.append("<title> My First HTML Page - Changed</title>");
sb.append("</head>");
sb.append("<body>");
sb.append("My first html page with body - Changed");
sb.append("</body>");
|
sb.append("</html>");
return sb.toString();
}
//
// "say-hello-jsp" => sayHello.jsp
// /src/main/resources/META-INF/resources/WEB-INF/jsp/sayHello.jsp
// /src/main/resources/META-INF/resources/WEB-INF/jsp/welcome.jsp
// /src/main/resources/META-INF/resources/WEB-INF/jsp/login.jsp
// /src/main/resources/META-INF/resources/WEB-INF/jsp/todos.jsp
@RequestMapping("say-hello-jsp")
public String sayHelloJsp() {
return "sayHello";
}
}
|
repos\master-spring-and-spring-boot-main\11-web-application\src\main\java\com\in28minutes\springboot\myfirstwebapp\hello\SayHelloController.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void addListener(@NonNull final IBankStatementListener listener)
{
final boolean added = listeners.addListener(listener);
if (added)
{
logger.info("Registered listener: `" + listener + "`");
}
else
{
logger.warn("Failed registering listener `" + listener + "` because it was already registered: `" + listeners + "`");
}
}
@Override
public void firePaymentLinked(@NonNull final PaymentLinkResult payment)
{
listeners.onPaymentsLinked(ImmutableList.of(payment));
}
|
@Override
public void firePaymentsLinked(@NonNull final List<PaymentLinkResult> payments)
{
if (payments.isEmpty())
{
return;
}
listeners.onPaymentsLinked(payments);
}
@Override
public void firePaymentsUnlinkedFromBankStatementLineReferences(@NonNull BankStatementLineReferenceList lineRefs)
{
listeners.onPaymentsUnlinkedFromBankStatementLineReferences(lineRefs);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\service\impl\BankStatementListenerService.java
| 2
|
请完成以下Java代码
|
public void setConfigurationLevel (final @Nullable java.lang.String ConfigurationLevel)
{
set_Value (COLUMNNAME_ConfigurationLevel, ConfigurationLevel);
}
@Override
public java.lang.String getConfigurationLevel()
{
return get_ValueAsString(COLUMNNAME_ConfigurationLevel);
}
/**
* EntityType AD_Reference_ID=389
* Reference name: _EntityTypeNew
*/
public static final int ENTITYTYPE_AD_Reference_ID=389;
@Override
public void setEntityType (final java.lang.String EntityType)
{
set_Value (COLUMNNAME_EntityType, EntityType);
}
@Override
public java.lang.String getEntityType()
{
return get_ValueAsString(COLUMNNAME_EntityType);
}
@Override
public void setIsSubcontracting (final boolean IsSubcontracting)
{
set_Value (COLUMNNAME_IsSubcontracting, IsSubcontracting);
}
@Override
public boolean isSubcontracting()
{
return get_ValueAsBoolean(COLUMNNAME_IsSubcontracting);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setPP_WF_Node_Product_ID (final int PP_WF_Node_Product_ID)
{
if (PP_WF_Node_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_PP_WF_Node_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PP_WF_Node_Product_ID, PP_WF_Node_Product_ID);
}
@Override
public int getPP_WF_Node_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_WF_Node_Product_ID);
}
|
@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);
}
@Override
public void setSpecification (final @Nullable java.lang.String Specification)
{
set_Value (COLUMNNAME_Specification, Specification);
}
@Override
public java.lang.String getSpecification()
{
return get_ValueAsString(COLUMNNAME_Specification);
}
@Override
public void setYield (final @Nullable BigDecimal Yield)
{
set_Value (COLUMNNAME_Yield, Yield);
}
@Override
public BigDecimal getYield()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Yield);
return bd != null ? bd : BigDecimal.ZERO;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_WF_Node_Product.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public int getC_POS_Journal_ID()
{
return get_ValueAsInt(COLUMNNAME_C_POS_Journal_ID);
}
@Override
public void setC_POS_JournalLine_ID (final int C_POS_JournalLine_ID)
{
if (C_POS_JournalLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_POS_JournalLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_POS_JournalLine_ID, C_POS_JournalLine_ID);
}
@Override
public int getC_POS_JournalLine_ID()
{
return get_ValueAsInt(COLUMNNAME_C_POS_JournalLine_ID);
}
@Override
public de.metas.pos.repository.model.I_C_POS_Order getC_POS_Order()
{
return get_ValueAsPO(COLUMNNAME_C_POS_Order_ID, de.metas.pos.repository.model.I_C_POS_Order.class);
}
@Override
public void setC_POS_Order(final de.metas.pos.repository.model.I_C_POS_Order C_POS_Order)
{
set_ValueFromPO(COLUMNNAME_C_POS_Order_ID, de.metas.pos.repository.model.I_C_POS_Order.class, C_POS_Order);
}
@Override
public void setC_POS_Order_ID (final int C_POS_Order_ID)
{
if (C_POS_Order_ID < 1)
set_Value (COLUMNNAME_C_POS_Order_ID, null);
else
set_Value (COLUMNNAME_C_POS_Order_ID, C_POS_Order_ID);
}
@Override
public int getC_POS_Order_ID()
{
return get_ValueAsInt(COLUMNNAME_C_POS_Order_ID);
}
@Override
public de.metas.pos.repository.model.I_C_POS_Payment getC_POS_Payment()
{
return get_ValueAsPO(COLUMNNAME_C_POS_Payment_ID, de.metas.pos.repository.model.I_C_POS_Payment.class);
}
@Override
public void setC_POS_Payment(final de.metas.pos.repository.model.I_C_POS_Payment C_POS_Payment)
{
set_ValueFromPO(COLUMNNAME_C_POS_Payment_ID, de.metas.pos.repository.model.I_C_POS_Payment.class, C_POS_Payment);
}
@Override
public void setC_POS_Payment_ID (final int C_POS_Payment_ID)
{
if (C_POS_Payment_ID < 1)
set_Value (COLUMNNAME_C_POS_Payment_ID, null);
else
set_Value (COLUMNNAME_C_POS_Payment_ID, C_POS_Payment_ID);
}
@Override
public int getC_POS_Payment_ID()
{
return get_ValueAsInt(COLUMNNAME_C_POS_Payment_ID);
}
|
@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);
}
/**
* Type AD_Reference_ID=541892
* Reference name: C_POS_JournalLine_Type
*/
public static final int TYPE_AD_Reference_ID=541892;
/** CashPayment = CASH_PAY */
public static final String TYPE_CashPayment = "CASH_PAY";
/** CardPayment = CARD_PAY */
public static final String TYPE_CardPayment = "CARD_PAY";
/** CashInOut = CASH_INOUT */
public static final String TYPE_CashInOut = "CASH_INOUT";
/** CashClosingDifference = CASH_DIFF */
public static final String TYPE_CashClosingDifference = "CASH_DIFF";
@Override
public void setType (final java.lang.String Type)
{
set_Value (COLUMNNAME_Type, Type);
}
@Override
public java.lang.String getType()
{
return get_ValueAsString(COLUMNNAME_Type);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java-gen\de\metas\pos\repository\model\X_C_POS_JournalLine.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public @Nullable Duration getReadTimeout() {
return this.readTimeout;
}
public void setReadTimeout(@Nullable Duration readTimeout) {
this.readTimeout = readTimeout;
}
public Ssl getSsl() {
return this.ssl;
}
/**
* SSL configuration.
*/
@ConfigurationPropertiesSource
public static class Ssl {
|
/**
* SSL bundle to use.
*/
private @Nullable String bundle;
public @Nullable String getBundle() {
return this.bundle;
}
public void setBundle(@Nullable String bundle) {
this.bundle = bundle;
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-http-client\src\main\java\org\springframework\boot\http\client\autoconfigure\HttpClientSettingsProperties.java
| 2
|
请完成以下Java代码
|
private boolean resolveBoolean(LogbackConfigurator config, String val) {
return Boolean.parseBoolean(resolve(config, val));
}
private int resolveInt(LogbackConfigurator config, String val) {
return Integer.parseInt(resolve(config, val));
}
private FileSize resolveFileSize(LogbackConfigurator config, String val) {
return FileSize.valueOf(resolve(config, val));
}
private Charset resolveCharset(LogbackConfigurator config, String val) {
return Charset.forName(resolve(config, val));
}
private String resolve(LogbackConfigurator config, String val) {
try {
return OptionHelper.substVars(val, config.getContext());
}
catch (ScanException ex) {
throw new RuntimeException(ex);
}
}
|
private static String faint(String value) {
return color(value, AnsiStyle.FAINT);
}
private static String cyan(String value) {
return color(value, AnsiColor.CYAN);
}
private static String magenta(String value) {
return color(value, AnsiColor.MAGENTA);
}
private static String colorByLevel(String value) {
return "%clr(" + value + "){}";
}
private static String color(String value, AnsiElement ansiElement) {
return "%clr(" + value + "){" + ColorConverter.getName(ansiElement) + "}";
}
}
|
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\logging\logback\DefaultLogbackConfiguration.java
| 1
|
请完成以下Java代码
|
protected void executeParse(BpmnParse bpmnParse, IntermediateCatchEvent intermediateCatchEvent) {
EventDefinition eventDefinition = null;
if (!intermediateCatchEvent.getEventDefinitions().isEmpty()) {
eventDefinition = intermediateCatchEvent.getEventDefinitions().get(0);
}
if (eventDefinition == null) {
Map<String, List<ExtensionElement>> extensionElements = intermediateCatchEvent.getExtensionElements();
if (!extensionElements.isEmpty()) {
List<ExtensionElement> eventTypeExtensionElements = intermediateCatchEvent.getExtensionElements().get(BpmnXMLConstants.ELEMENT_EVENT_TYPE);
if (eventTypeExtensionElements != null && !eventTypeExtensionElements.isEmpty()) {
String eventTypeValue = eventTypeExtensionElements.get(0).getElementText();
if (StringUtils.isNotEmpty(eventTypeValue)) {
intermediateCatchEvent.setBehavior(bpmnParse.getActivityBehaviorFactory().createIntermediateCatchEventRegistryEventActivityBehavior(intermediateCatchEvent, eventTypeValue));
return;
}
}
}
|
intermediateCatchEvent.setBehavior(bpmnParse.getActivityBehaviorFactory().createIntermediateCatchEventActivityBehavior(intermediateCatchEvent));
} else {
if (eventDefinition instanceof TimerEventDefinition ||
eventDefinition instanceof SignalEventDefinition ||
eventDefinition instanceof MessageEventDefinition ||
eventDefinition instanceof ConditionalEventDefinition ||
eventDefinition instanceof VariableListenerEventDefinition) {
bpmnParse.getBpmnParserHandlers().parseElement(bpmnParse, eventDefinition);
} else {
LOGGER.warn("Unsupported intermediate catch event type for event {}", intermediateCatchEvent.getId());
}
}
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\bpmn\parser\handler\IntermediateCatchEventParseHandler.java
| 1
|
请完成以下Java代码
|
public String getAppId() {
return appId;
}
public String getUrl() {
return url;
}
public String getQueryString() {
return queryString;
}
public String getBody() {
return body;
}
public String getEncoding() {
return encoding;
}
public String getMethod() {
return method;
}
public Map<String, String> getCookies() {
return cookies;
}
public String getContentType() {
return contentType;
|
}
public Map<String, List<String>> getHeaders() {
return headers;
}
public String getProtocol() {
return protocol;
}
public String getRemoteInfo() {
return remoteInfo;
}
}
|
repos\spring-examples-java-17\spring-demo\src\main\java\itx\examples\springboot\demo\dto\RequestInfo.java
| 1
|
请完成以下Java代码
|
public int getC_BP_BankAccount_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BP_BankAccount_ID);
}
@Override
public org.compiere.model.I_C_ValidCombination getPayBankFee_A()
{
return get_ValueAsPO(COLUMNNAME_PayBankFee_Acct, org.compiere.model.I_C_ValidCombination.class);
}
@Override
public void setPayBankFee_A(final org.compiere.model.I_C_ValidCombination PayBankFee_A)
{
set_ValueFromPO(COLUMNNAME_PayBankFee_Acct, org.compiere.model.I_C_ValidCombination.class, PayBankFee_A);
}
@Override
public void setPayBankFee_Acct (final int PayBankFee_Acct)
{
set_Value (COLUMNNAME_PayBankFee_Acct, PayBankFee_Acct);
}
@Override
public int getPayBankFee_Acct()
{
return get_ValueAsInt(COLUMNNAME_PayBankFee_Acct);
}
@Override
public org.compiere.model.I_C_ValidCombination getPayment_WriteOff_A()
{
return get_ValueAsPO(COLUMNNAME_Payment_WriteOff_Acct, org.compiere.model.I_C_ValidCombination.class);
}
@Override
public void setPayment_WriteOff_A(final org.compiere.model.I_C_ValidCombination Payment_WriteOff_A)
{
set_ValueFromPO(COLUMNNAME_Payment_WriteOff_Acct, org.compiere.model.I_C_ValidCombination.class, Payment_WriteOff_A);
}
@Override
public void setPayment_WriteOff_Acct (final int Payment_WriteOff_Acct)
{
set_Value (COLUMNNAME_Payment_WriteOff_Acct, Payment_WriteOff_Acct);
}
@Override
public int getPayment_WriteOff_Acct()
{
return get_ValueAsInt(COLUMNNAME_Payment_WriteOff_Acct);
|
}
@Override
public org.compiere.model.I_C_ValidCombination getRealizedGain_A()
{
return get_ValueAsPO(COLUMNNAME_RealizedGain_Acct, org.compiere.model.I_C_ValidCombination.class);
}
@Override
public void setRealizedGain_A(final org.compiere.model.I_C_ValidCombination RealizedGain_A)
{
set_ValueFromPO(COLUMNNAME_RealizedGain_Acct, org.compiere.model.I_C_ValidCombination.class, RealizedGain_A);
}
@Override
public void setRealizedGain_Acct (final int RealizedGain_Acct)
{
set_Value (COLUMNNAME_RealizedGain_Acct, RealizedGain_Acct);
}
@Override
public int getRealizedGain_Acct()
{
return get_ValueAsInt(COLUMNNAME_RealizedGain_Acct);
}
@Override
public org.compiere.model.I_C_ValidCombination getRealizedLoss_A()
{
return get_ValueAsPO(COLUMNNAME_RealizedLoss_Acct, org.compiere.model.I_C_ValidCombination.class);
}
@Override
public void setRealizedLoss_A(final org.compiere.model.I_C_ValidCombination RealizedLoss_A)
{
set_ValueFromPO(COLUMNNAME_RealizedLoss_Acct, org.compiere.model.I_C_ValidCombination.class, RealizedLoss_A);
}
@Override
public void setRealizedLoss_Acct (final int RealizedLoss_Acct)
{
set_Value (COLUMNNAME_RealizedLoss_Acct, RealizedLoss_Acct);
}
@Override
public int getRealizedLoss_Acct()
{
return get_ValueAsInt(COLUMNNAME_RealizedLoss_Acct);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BP_BankAccount_Acct.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private IQuery<I_MD_Candidate_ATP_QueryResult> createDBQueryForMaterialQueryOrNull(
@NonNull final AvailableToPromiseMultiQuery multiQuery)
{
return multiQuery.getQueries()
.stream()
.filter(Objects::nonNull)
.map(AvailableToPromiseSqlHelper::createDBQueryForStockQuery)
.reduce(IQuery.unionDistict())
.orElse(null);
}
@VisibleForTesting
static AddToResultGroupRequest createAddToResultGroupRequest(final I_MD_Candidate_ATP_QueryResult stockRecord)
{
final BPartnerId customerId = BPartnerId.ofRepoIdOrNull(stockRecord.getC_BPartner_Customer_ID());
return AddToResultGroupRequest.builder()
.productId(ProductId.ofRepoId(stockRecord.getM_Product_ID()))
.bpartner(BPartnerClassifier.specificOrAny(customerId)) // records that have no bPartner-ID are applicable to any bpartner
.warehouseId(WarehouseId.ofRepoId(stockRecord.getM_Warehouse_ID()))
.storageAttributesKey(AttributesKey.ofString(stockRecord.getStorageAttributesKey()))
.qty(stockRecord.getQty())
|
.date(TimeUtil.asInstant(stockRecord.getDateProjected()))
.seqNo(stockRecord.getSeqNo())
.build();
}
public Set<AttributesKeyPattern> getPredefinedStorageAttributeKeys()
{
final ISysConfigBL sysConfigBL = Services.get(ISysConfigBL.class);
final int clientId = Env.getAD_Client_ID(Env.getCtx());
final int orgId = Env.getAD_Org_ID(Env.getCtx());
final String storageAttributesKeys = sysConfigBL.getValue(
SYSCONFIG_AVAILABILITY_INFO_ATTRIBUTES_KEYS,
AttributesKey.ALL.getAsString(),
clientId, orgId);
return AttributesKeyPatternsUtil.parseCommaSeparatedString(storageAttributesKeys);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\material\dispo\commons\repository\atp\AvailableToPromiseRepository.java
| 2
|
请完成以下Java代码
|
public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException {
if (this.currentPosition == this.size) {
this.originalChain.doFilter(request, response);
return;
}
this.currentPosition++;
Filter nextFilter = this.additionalFilters.get(this.currentPosition - 1);
if (logger.isTraceEnabled()) {
String name = nextFilter.getClass().getSimpleName();
logger.trace(LogMessage.format("Invoking %s (%d/%d)", name, this.currentPosition, this.size));
}
nextFilter.doFilter(request, response, this);
}
}
public interface FilterChainValidator {
void validate(FilterChainProxy filterChainProxy);
}
private static class NullFilterChainValidator implements FilterChainValidator {
@Override
public void validate(FilterChainProxy filterChainProxy) {
}
}
/**
* A strategy for decorating the provided filter chain with one that accounts for the
* {@link SecurityFilterChain} for a given request.
*
* @author Josh Cummings
* @since 6.0
*/
public interface FilterChainDecorator {
/**
* Provide a new {@link FilterChain} that accounts for needed security
* considerations when there are no security filters.
* @param original the original {@link FilterChain}
* @return a security-enabled {@link FilterChain}
*/
default FilterChain decorate(FilterChain original) {
return decorate(original, Collections.emptyList());
}
/**
* Provide a new {@link FilterChain} that accounts for the provided filters as
* well as the original filter chain.
* @param original the original {@link FilterChain}
* @param filters the security filters
* @return a security-enabled {@link FilterChain} that includes the provided
* filters
*/
FilterChain decorate(FilterChain original, List<Filter> filters);
}
/**
* A {@link FilterChainDecorator} that uses the {@link VirtualFilterChain}
*
* @author Josh Cummings
* @since 6.0
*/
public static final class VirtualFilterChainDecorator implements FilterChainDecorator {
|
/**
* {@inheritDoc}
*/
@Override
public FilterChain decorate(FilterChain original) {
return original;
}
/**
* {@inheritDoc}
*/
@Override
public FilterChain decorate(FilterChain original, List<Filter> filters) {
return new VirtualFilterChain(original, filters);
}
}
private static final class FirewallFilter implements Filter {
private final HttpFirewall firewall;
private FirewallFilter(HttpFirewall firewall) {
this.firewall = firewall;
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
filterChain.doFilter(this.firewall.getFirewalledRequest(request),
this.firewall.getFirewalledResponse(response));
}
}
}
|
repos\spring-security-main\web\src\main\java\org\springframework\security\web\FilterChainProxy.java
| 1
|
请完成以下Java代码
|
public Mono<ResponseEntity<Flux<ByteBuffer>>> downloadFile(@PathVariable("filekey") String filekey) {
GetObjectRequest request = GetObjectRequest.builder()
.bucket(s3config.getBucket())
.key(filekey)
.build();
return Mono.fromFuture(s3client.getObject(request, AsyncResponseTransformer.toPublisher()))
.map(response -> {
checkResult(response.response());
String filename = getMetadataItem(response.response(), "filename", filekey);
log.info("[I65] filename={}, length={}", filename, response.response()
.contentLength());
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_TYPE, response.response()
.contentType())
.header(HttpHeaders.CONTENT_LENGTH, Long.toString(response.response()
.contentLength()))
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"")
.body(Flux.from(response));
});
}
/**
* Lookup a metadata key in a case-insensitive way.
* @param sdkResponse
* @param key
* @param defaultValue
* @return
*/
private String getMetadataItem(GetObjectResponse sdkResponse, String key, String defaultValue) {
|
for (Entry<String, String> entry : sdkResponse.metadata()
.entrySet()) {
if (entry.getKey()
.equalsIgnoreCase(key)) {
return entry.getValue();
}
}
return defaultValue;
}
// Helper used to check return codes from an API call
private static void checkResult(GetObjectResponse response) {
SdkHttpResponse sdkResponse = response.sdkHttpResponse();
if (sdkResponse != null && sdkResponse.isSuccessful()) {
return;
}
throw new DownloadFailedException(response);
}
}
|
repos\tutorials-master\aws-modules\aws-reactive\src\main\java\com\baeldung\aws\reactive\s3\DownloadResource.java
| 1
|
请完成以下Java代码
|
public boolean isEmpty() {
return referenceDocs().isEmpty() && guides().isEmpty() && additionalLinks().isEmpty() && super.isEmpty();
}
@Override
protected List<Section> resolveSubSections(List<Section> sections) {
List<Section> allSections = new ArrayList<>();
allSections.add(this.referenceDocs);
allSections.add(this.guides);
allSections.add(this.additionalLinks);
allSections.addAll(sections);
return allSections;
}
public GettingStartedSection addReferenceDocLink(String href, String description) {
this.referenceDocs.addItem(new Link(href, description));
return this;
}
public BulletedSection<Link> referenceDocs() {
return this.referenceDocs;
}
public GettingStartedSection addGuideLink(String href, String description) {
this.guides.addItem(new Link(href, description));
return this;
}
public BulletedSection<Link> guides() {
return this.guides;
}
public GettingStartedSection addAdditionalLink(String href, String description) {
this.additionalLinks.addItem(new Link(href, description));
return this;
}
public BulletedSection<Link> additionalLinks() {
return this.additionalLinks;
}
/**
* Internal representation of a link.
|
*/
public static class Link {
private final String href;
private final String description;
Link(String href, String description) {
this.href = href;
this.description = description;
}
public String getHref() {
return this.href;
}
public String getDescription() {
return this.description;
}
}
}
|
repos\initializr-main\initializr-generator-spring\src\main\java\io\spring\initializr\generator\spring\documentation\GettingStartedSection.java
| 1
|
请完成以下Java代码
|
public boolean isCreateSingleOrder ()
{
Object oo = get_Value(COLUMNNAME_IsCreateSingleOrder);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Distribution Run.
@param M_DistributionRun_ID
Distribution Run create Orders to distribute products to a selected list of partners
*/
public void setM_DistributionRun_ID (int M_DistributionRun_ID)
{
if (M_DistributionRun_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_DistributionRun_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_DistributionRun_ID, Integer.valueOf(M_DistributionRun_ID));
}
/** Get Distribution Run.
@return Distribution Run create Orders to distribute products to a selected list of partners
*/
public int getM_DistributionRun_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_DistributionRun_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
|
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_DistributionRun.java
| 1
|
请完成以下Java代码
|
private void addMappingInCaseAnnotationIsEmpty(
Class<?>[] methodParamTypes,
Set<Class<? extends Throwable>> exceptionsToBeMapped) {
@SuppressWarnings("unchecked")
Function<Class<?>, Class<? extends Throwable>> convertSafely = clazz -> (Class<? extends Throwable>) clazz;
Arrays.stream(methodParamTypes)
.filter(param -> exceptionsToBeMapped.isEmpty())
.filter(Throwable.class::isAssignableFrom)
.map(convertSafely) // safe to call, since check for Throwable superclass
.forEach(exceptionsToBeMapped::add);
}
private void addExceptionMapping(Class<? extends Throwable> exceptionType, Method method) {
Method oldMethod = mappedMethods.put(exceptionType, method);
if (oldMethod != null && !oldMethod.equals(method)) {
throw new IllegalStateException("Ambiguous @GrpcExceptionHandler method mapped for [" +
exceptionType + "]: {" + oldMethod + ", " + method + "}");
}
}
/**
* When given exception type is subtype of already provided mapped exception, this returns a valid mapped method to
* be later executed.
*
* @param exceptionType exception to check
* @param <E> type of exception
* @return mapped method instance with its method
*/
@NonNull
public <E extends Throwable> Map.Entry<Object, Method> resolveMethodWithInstance(Class<E> exceptionType) {
Method value = extractExtendedThrowable(exceptionType);
|
if (value == null) {
return new SimpleImmutableEntry<>(null, null);
}
Class<?> methodClass = value.getDeclaringClass();
Object key = grpcAdviceDiscoverer.getAnnotatedBeans()
.values()
.stream()
.filter(obj -> methodClass.isAssignableFrom(obj.getClass()))
.findFirst()
.orElse(null);
return new SimpleImmutableEntry<>(key, value);
}
/**
* Lookup if a method is mapped to given exception.
*
* @param exception exception to check
* @param <E> type of exception
* @return true if mapped to valid method
*/
public <E extends Throwable> boolean isMethodMappedForException(Class<E> exception) {
return extractExtendedThrowable(exception) != null;
}
@Nullable
private <E extends Throwable> Method extractExtendedThrowable(Class<E> exceptionType) {
return mappedMethods.keySet()
.stream()
.filter(ex -> ex.isAssignableFrom(exceptionType))
.min(new ExceptionDepthComparator(exceptionType))
.map(mappedMethods::get)
.orElse(null);
}
}
|
repos\grpc-spring-master\grpc-server-spring-boot-starter\src\main\java\net\devh\boot\grpc\server\advice\GrpcExceptionHandlerMethodResolver.java
| 1
|
请完成以下Java代码
|
public ExpressionManager getExpressionManager() {
return expressionManager;
}
public void setExpressionManager(ExpressionManager expressionManager) {
this.expressionManager = expressionManager;
}
public ThrowMessageDelegateFactory getThrowMessageDelegateFactory() {
return throwMessageDelegateFactory;
}
public void setThrowMessageDelegateFactory(ThrowMessageDelegateFactory throwMessageDelegateFactory) {
this.throwMessageDelegateFactory = throwMessageDelegateFactory;
}
public MessagePayloadMappingProviderFactory getMessagePayloadMappingProviderFactory() {
return messagePayloadMappingProviderFactory;
|
}
public void setMessagePayloadMappingProviderFactory(
MessagePayloadMappingProviderFactory messagePayloadMappingProviderFactory
) {
this.messagePayloadMappingProviderFactory = messagePayloadMappingProviderFactory;
}
public MessageExecutionContextFactory getMessageExecutionContextFactory() {
return messageExecutionContextFactory;
}
public void setMessageExecutionContextFactory(MessageExecutionContextFactory messageExecutionContextFactory) {
this.messageExecutionContextFactory = messageExecutionContextFactory;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\factory\AbstractBehaviorFactory.java
| 1
|
请完成以下Java代码
|
public String getId() {
return id;
}
@Override
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDeploymentId() {
return deploymentId;
}
public void setDeploymentId(String deploymentId) {
this.deploymentId = deploymentId;
}
public void setBytes(byte[] bytes) {
this.bytes = bytes;
}
@Override
public int getRevision() {
return revision;
}
@Override
public void setRevision(int revision) {
this.revision = revision;
}
@Override
public String toString() {
return "ByteArrayEntity[id=" + id + ", name=" + name + ", size=" + (bytes != null ? bytes.length : 0) + "]";
}
// Wrapper for a byte array, needed to do byte array comparisons
// See https://activiti.atlassian.net/browse/ACT-1524
private static class PersistentState {
private final String name;
|
private final byte[] bytes;
public PersistentState(String name, byte[] bytes) {
this.name = name;
this.bytes = bytes;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof PersistentState) {
PersistentState other = (PersistentState) obj;
return Objects.equals(this.name, other.name)
&& Arrays.equals(this.bytes, other.bytes);
}
return false;
}
@Override
public int hashCode() {
throw new UnsupportedOperationException();
}
}
}
|
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\ByteArrayEntity.java
| 1
|
请完成以下Java代码
|
public List<ExecutionEntity> findEventScopeExecutionsByActivityId(String activityRef, String parentExecutionId) {
Map<String, String> parameters = new HashMap<>();
parameters.put("activityId", activityRef);
parameters.put("parentExecutionId", parentExecutionId);
return getDbSqlSession().selectList("selectExecutionsByParentExecutionId", parameters);
}
@SuppressWarnings("unchecked")
public List<Execution> findExecutionsByNativeQuery(Map<String, Object> parameterMap, int firstResult, int maxResults) {
return getDbSqlSession().selectListWithRawParameter("selectExecutionByNativeQuery", parameterMap, firstResult, maxResults);
}
@SuppressWarnings("unchecked")
public List<ProcessInstance> findProcessInstanceByNativeQuery(Map<String, Object> parameterMap, int firstResult, int maxResults) {
return getDbSqlSession().selectListWithRawParameter("selectExecutionByNativeQuery", parameterMap, firstResult, maxResults);
}
public long findExecutionCountByNativeQuery(Map<String, Object> parameterMap) {
return (Long) getDbSqlSession().selectOne("selectExecutionCountByNativeQuery", parameterMap);
}
public void updateExecutionTenantIdForDeployment(String deploymentId, String newTenantId) {
HashMap<String, Object> params = new HashMap<>();
params.put("deploymentId", deploymentId);
params.put("tenantId", newTenantId);
getDbSqlSession().update("updateExecutionTenantIdForDeployment", params);
}
public void updateProcessInstanceLockTime(String processInstanceId) {
CommandContext commandContext = Context.getCommandContext();
Date expirationTime = commandContext.getProcessEngineConfiguration().getClock().getCurrentTime();
int lockMillis = commandContext.getProcessEngineConfiguration().getAsyncExecutorAsyncJobLockTimeInMillis();
GregorianCalendar lockCal = new GregorianCalendar();
lockCal.setTime(expirationTime);
lockCal.add(Calendar.MILLISECOND, lockMillis);
HashMap<String, Object> params = new HashMap<>();
params.put("id", processInstanceId);
|
params.put("lockTime", lockCal.getTime());
params.put("expirationTime", expirationTime);
int result = getDbSqlSession().update("updateProcessInstanceLockTime", params);
if (result == 0) {
throw new ActivitiOptimisticLockingException("Could not lock process instance");
}
}
public void clearProcessInstanceLockTime(String processInstanceId) {
HashMap<String, Object> params = new HashMap<>();
params.put("id", processInstanceId);
getDbSqlSession().update("clearProcessInstanceLockTime", params);
}
}
|
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\ExecutionEntityManager.java
| 1
|
请完成以下Java代码
|
private static boolean isSkipLogging(@NonNull final String sqlCommand)
{
// Always log DDL (flagged) commands
if (sqlCommand.startsWith(DDL_PREFIX))
{
return false;
}
final String sqlCommandUC = sqlCommand.toUpperCase().trim();
//
// Don't log selects
if (sqlCommandUC.startsWith("SELECT "))
{
return true;
}
//
// Don't log DELETE FROM Some_Table WHERE AD_Table_ID=? AND Record_ID=?
if (sqlCommandUC.startsWith("DELETE FROM ") && sqlCommandUC.endsWith(" WHERE AD_TABLE_ID=? AND RECORD_ID=?"))
{
return true;
}
//
// Check that INSERT/UPDATE/DELETE statements are about our ignored tables
final ImmutableSet<String> exceptionTablesUC = Services.get(IMigrationLogger.class).getTablesToIgnoreUC(Env.getClientIdOrSystem());
for (final String tableNameUC : exceptionTablesUC)
{
|
if (sqlCommandUC.startsWith("INSERT INTO " + tableNameUC + " "))
return true;
if (sqlCommandUC.startsWith("DELETE FROM " + tableNameUC + " "))
return true;
if (sqlCommandUC.startsWith("DELETE " + tableNameUC + " "))
return true;
if (sqlCommandUC.startsWith("UPDATE " + tableNameUC + " "))
return true;
if (sqlCommandUC.startsWith("INSERT INTO " + tableNameUC + "("))
return true;
}
return false;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\logger\MigrationScriptFileLoggerHolder.java
| 1
|
请完成以下Java代码
|
public class DLMPermanentSysConfigCustomizer extends AbstractDLMCustomizer
{
private static final String SYSCONFIG_DLM_COALESCE_LEVEL = "de.metas.dlm.DLM_Coalesce_Level";
private static final String SYSCONFIG_DLM_LEVEL = "de.metas.dlm.DLM_Level";
public static AbstractDLMCustomizer PERMANENT_SYSCONFIG_INSTANCE = new DLMPermanentSysConfigCustomizer();
private DLMPermanentSysConfigCustomizer()
{
}
/**
* Returns the DLM_Level set in the SysConfig. If none is set, it returns {@link IMigratorService#DLM_Level_TEST},
* so by default, only records that are "live/operational" and records that are currently processed by {@link IMigratorService#testMigratePartition(de.metas.dlm.Partition)}
* are visible to the system.
*
* @param c_IGNOREDignored, can also be {@code null}
*
|
*/
@Override
public int getDlmLevel()
{
return Services.get(ISysConfigBL.class).getIntValue(SYSCONFIG_DLM_LEVEL, IMigratorService.DLM_Level_TEST);
}
/**
* Returns the DLM_Coalesce_Level set in the SysConfig. If none is set, it returns {@link IMigratorService#DLM_Level_LIVE} to make sure that by default,
* everything that was not yet explicitly moved to a DLM level is visible.
*/
@Override
public int getDlmCoalesceLevel()
{
return Services.get(ISysConfigBL.class).getIntValue(SYSCONFIG_DLM_COALESCE_LEVEL, IMigratorService.DLM_Level_LIVE);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\connection\DLMPermanentSysConfigCustomizer.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class AssignmentToRefundCandidate
{
@NonNull
RefundConfigId refundConfigId;
@NonNull
InvoiceCandidateId assignableInvoiceCandidateId;
@NonNull
RefundInvoiceCandidate refundInvoiceCandidate;
/** Relevant money amount of the assignable invoice candidate. */
@NonNull
Money moneyBase;
@NonNull
Money moneyAssignedToRefundCandidate;
|
@NonNull
Quantity quantityAssigendToRefundCandidate;
boolean useAssignedQtyInSum;
public AssignmentToRefundCandidate withRefundInvoiceCandidate(@NonNull final RefundInvoiceCandidate refundInvoiceCandidate)
{
return new AssignmentToRefundCandidate(
refundConfigId,
assignableInvoiceCandidateId,
refundInvoiceCandidate,
moneyBase,
moneyAssignedToRefundCandidate,
quantityAssigendToRefundCandidate,
useAssignedQtyInSum);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\refund\AssignmentToRefundCandidate.java
| 2
|
请完成以下Java代码
|
CostAmount getStandardCosts(final AcctSchema acctSchema)
{
final CostSegment costSegment = CostSegment.builder()
.costingLevel(getProductCostingLevel(acctSchema))
.acctSchemaId(acctSchema.getId())
.costTypeId(acctSchema.getCosting().getCostTypeId())
.clientId(getClientId())
.orgId(getOrgId())
.productId(getProductId())
.attributeSetInstanceId(getAttributeSetInstanceId())
.build();
final CostPrice costPrice = services.getCurrentCostPrice(costSegment, CostingMethod.StandardCosting)
.orElseThrow(() -> newPostingException()
.setAcctSchema(acctSchema)
.setDetailMessage("No standard costs found for " + costSegment));
return costPrice.multiply(getQty());
}
void createCostDetails(final AcctSchema as)
{
final I_M_InOut receipt = getReceipt();
final Quantity qty = isReturnTrx() ? getQty().negate() : getQty();
final CostAmount amt = CostAmount.multiply(getOrderLineCostPriceInStockingUOM(), qty);
// NOTE: there is no need to fail if no cost details were created because:
// * not all costing methods are creating cost details for MatchPO
// * we are not using the result of cost details
services.createCostDetailOrEmpty(
CostDetailCreateRequest.builder()
.acctSchemaId(as.getId())
.clientId(ClientId.ofRepoId(receipt.getAD_Client_ID()))
.orgId(OrgId.ofRepoId(receipt.getAD_Org_ID()))
.productId(getProductId())
.attributeSetInstanceId(getAttributeSetInstanceId())
.documentRef(CostingDocumentRef.ofMatchPOId(getM_MatchPO_ID()))
.qty(qty)
.amt(amt)
.currencyConversionContext(getCurrencyConversionContext())
.date(getReceiptDateAcct())
.description(getOrderLine().getDescription())
.build());
|
}
I_C_OrderLine getOrderLine()
{
return orderLine;
}
I_M_InOutLine getReceiptLine()
{
return this._receiptLine;
}
I_M_InOut getReceipt()
{
return this._receipt;
}
private CurrencyConversionContext getCurrencyConversionContext()
{
return this._currencyConversionContext;
}
Instant getReceiptDateAcct()
{
final I_M_InOut receipt = getReceipt();
final Timestamp receiptDateAcct = receipt.getDateAcct();
return receiptDateAcct.toInstant();
}
boolean isReturnTrx()
{
final I_M_InOut receipt = getReceipt();
return X_M_InOut.MOVEMENTTYPE_VendorReturns.equals(receipt.getMovementType());
}
private int getM_MatchPO_ID()
{
return get_ID();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\DocLine_MatchPO.java
| 1
|
请完成以下Java代码
|
public ResponseEntity createArticle(@Valid @RequestBody NewArticleParam newArticleParam,
BindingResult bindingResult,
@AuthenticationPrincipal User user) {
if (bindingResult.hasErrors()) {
throw new InvalidRequestException(bindingResult);
}
Article article = new Article(
newArticleParam.getTitle(),
newArticleParam.getDescription(),
newArticleParam.getBody(),
newArticleParam.getTagList(),
user.getId());
articleRepository.save(article);
return ResponseEntity.ok(new HashMap<String, Object>() {{
put("article", articleQueryService.findById(article.getId(), user).get());
}});
}
@GetMapping(path = "feed")
public ResponseEntity getFeed(@RequestParam(value = "offset", defaultValue = "0") int offset,
@RequestParam(value = "limit", defaultValue = "20") int limit,
@AuthenticationPrincipal User user) {
return ResponseEntity.ok(articleQueryService.findUserFeed(user, new Page(offset, limit)));
}
@GetMapping
public ResponseEntity getArticles(@RequestParam(value = "offset", defaultValue = "0") int offset,
@RequestParam(value = "limit", defaultValue = "20") int limit,
@RequestParam(value = "tag", required = false) String tag,
@RequestParam(value = "favorited", required = false) String favoritedBy,
@RequestParam(value = "author", required = false) String author,
@AuthenticationPrincipal User user) {
return ResponseEntity.ok(articleQueryService.findRecentArticles(tag, author, favoritedBy, new Page(offset, limit), user));
|
}
}
@Getter
@JsonRootName("article")
@NoArgsConstructor
class NewArticleParam {
@NotBlank(message = "can't be empty")
private String title;
@NotBlank(message = "can't be empty")
private String description;
@NotBlank(message = "can't be empty")
private String body;
private String[] tagList;
}
|
repos\spring-boot-realworld-example-app-master (1)\src\main\java\io\spring\api\ArticlesApi.java
| 1
|
请完成以下Java代码
|
private int getToRealValueMultiplier()
{
int toRealValueMultiplier = this.toRealValueMultiplier;
if (toRealValueMultiplier == 0)
{
toRealValueMultiplier = this.toRealValueMultiplier = computeToRealValueMultiplier();
}
return toRealValueMultiplier;
}
private int computeToRealValueMultiplier()
{
int multiplier = 1;
// Adjust by SOTrx if needed
if (!isAPAdjusted)
{
final int multiplierAP = soTrx.isPurchase() ? -1 : +1;
multiplier *= multiplierAP;
}
// Adjust by Credit Memo if needed
if (!isCreditMemoAdjusted)
{
final int multiplierCM = isCreditMemo ? -1 : +1;
multiplier *= multiplierCM;
}
return multiplier;
}
private int getToRelativeValueMultiplier()
{
// NOTE: the relative->real and real->relative value multipliers are the same
return getToRealValueMultiplier();
}
public Money fromNotAdjustedAmount(@NonNull final Money money)
{
final int multiplier = computeFromNotAdjustedAmountMultiplier();
return multiplier > 0 ? money : money.negate();
}
private int computeFromNotAdjustedAmountMultiplier()
{
int multiplier = 1;
// Do we have to SO adjust?
if (isAPAdjusted)
{
final int multiplierAP = soTrx.isPurchase() ? -1 : +1;
multiplier *= multiplierAP;
}
// Do we have to adjust by Credit Memo?
|
if (isCreditMemoAdjusted)
{
final int multiplierCM = isCreditMemo ? -1 : +1;
multiplier *= multiplierCM;
}
return multiplier;
}
/**
* @return {@code true} for purchase-invoice and sales-creditmemo. {@code false} otherwise.
*/
public boolean isOutgoingMoney()
{
return isCreditMemo ^ soTrx.isPurchase();
}
public InvoiceAmtMultiplier withAPAdjusted(final boolean isAPAdjustedNew)
{
return isAPAdjusted == isAPAdjustedNew ? this : toBuilder().isAPAdjusted(isAPAdjustedNew).build().intern();
}
public InvoiceAmtMultiplier withCMAdjusted(final boolean isCreditMemoAdjustedNew)
{
return isCreditMemoAdjusted == isCreditMemoAdjustedNew ? this : toBuilder().isCreditMemoAdjusted(isCreditMemoAdjustedNew).build().intern();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\InvoiceAmtMultiplier.java
| 1
|
请完成以下Java代码
|
private void asserNotDestroyed()
{
if (destroyed)
{
throw new AdempiereException("already destroyed: " + this);
}
}
private void markAsDestroyed()
{
asserNotDestroyed();
destroyed = true;
}
@Override
public ParentType end()
{
markAsDestroyed();
final InSubQueryFilter<ModelType> inSubQueryFilter = inSubQueryBuilder.build();
finisher.accept(inSubQueryFilter);
return parent;
}
@Override
public IInSubQueryFilterClause<ModelType, ParentType> subQuery(final IQuery<?> subQuery)
|
{
asserNotDestroyed();
inSubQueryBuilder.subQuery(subQuery);
return this;
}
@Override
public IInSubQueryFilterClause<ModelType, ParentType> matchingColumnNames(final String columnName, final String subQueryColumnName, final IQueryFilterModifier modifier)
{
asserNotDestroyed();
inSubQueryBuilder.matchingColumnNames(columnName, subQueryColumnName, modifier);
return this;
}
@Override
public IInSubQueryFilterClause<ModelType, ParentType> matchingColumnNames(final String columnName, final String subQueryColumnName)
{
asserNotDestroyed();
inSubQueryBuilder.matchingColumnNames(columnName, subQueryColumnName);
return this;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\InSubQueryFilterClause.java
| 1
|
请完成以下Java代码
|
public boolean doCatch(Throwable e) throws Throwable
{
final String errmsg = "Error processing: " + source;
logger.error(errmsg, e);
// notify monitor too about this issue
Loggables.addLog(errmsg);
return true; // rollback
}
@Override
public void doFinally()
{
// nothing
}
});
}
return countWriteOff.getValue();
}
/**
*
* @param candidate
* @param writeOffDescription
* @return true if candidate's invoice was written-off
*/
protected boolean writeOffDunningCandidate(final I_C_Dunning_Candidate candidate, final String writeOffDescription)
{
final Properties ctx = InterfaceWrapperHelper.getCtx(candidate);
final String trxName = InterfaceWrapperHelper.getTrxName(candidate);
// services
final IADTableDAO adTableDAO = Services.get(IADTableDAO.class);
final IInvoiceBL invoiceBL = Services.get(IInvoiceBL.class);
final IDunningEventDispatcher dunningEventDispatcher = Services.get(IDunningEventDispatcher.class);
|
if (candidate.getAD_Table_ID() == adTableDAO.retrieveTableId(I_C_Invoice.Table_Name))
{
final I_C_Invoice invoice = InterfaceWrapperHelper.create(ctx, candidate.getRecord_ID(), I_C_Invoice.class, trxName);
Check.assumeNotNull(invoice, "No invoice found for candidate {}", candidate);
invoiceBL.writeOffInvoice(invoice, candidate.getOpenAmt(), writeOffDescription);
dunningEventDispatcher.fireDunningCandidateEvent(IInvoiceSourceBL.EVENT_AfterInvoiceWriteOff, candidate);
return true;
}
// other document types are ignored for now
return false;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\invoice\api\impl\InvoiceSourceBL.java
| 1
|
请完成以下Java代码
|
public void setPA_Goal_ID (int PA_Goal_ID)
{
if (PA_Goal_ID < 1)
set_Value (COLUMNNAME_PA_Goal_ID, null);
else
set_Value (COLUMNNAME_PA_Goal_ID, Integer.valueOf(PA_Goal_ID));
}
/** Get Goal.
@return Performance Goal
*/
public int getPA_Goal_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_Goal_ID);
if (ii == null)
return 0;
return ii.intValue();
}
|
/** Set ZUL File Path.
@param ZulFilePath
Absolute path to zul file
*/
public void setZulFilePath (String ZulFilePath)
{
set_Value (COLUMNNAME_ZulFilePath, ZulFilePath);
}
/** Get ZUL File Path.
@return Absolute path to zul file
*/
public String getZulFilePath ()
{
return (String)get_Value(COLUMNNAME_ZulFilePath);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_DashboardContent.java
| 1
|
请完成以下Java代码
|
public BigDecimal getQtyCUsPerTU()
{
return qtyCUsPerTU;
}
public void setQtyCUsPerTU(final BigDecimal qtyCU)
{
this.qtyCUsPerTU = qtyCU;
}
/**
* Called from the process class to set the TU qty from the process parameter.
*/
public void setQtyTU(final BigDecimal qtyTU)
{
this.qtyTU = qtyTU;
}
public void setQtyLU(final BigDecimal qtyLU)
{
this.qtyLU = qtyLU;
}
private boolean getIsReceiveIndividualCUs()
{
|
if (isReceiveIndividualCUs == null)
{
isReceiveIndividualCUs = computeIsReceiveIndividualCUs();
}
return isReceiveIndividualCUs;
}
private boolean computeIsReceiveIndividualCUs()
{
if (selectedRow.getType() != PPOrderLineType.MainProduct
|| selectedRow.getUomId() == null
|| !selectedRow.getUomId().isEach())
{
return false;
}
return Optional.ofNullable(selectedRow.getOrderId())
.flatMap(ppOrderBOMBL::getSerialNoSequenceId)
.isPresent();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pporder\process\PackingInfoProcessParams.java
| 1
|
请完成以下Java代码
|
public BatchResource getBatch(String batchId) {
return new BatchResourceImpl(getProcessEngine(), batchId);
}
@Override
public List<BatchDto> getBatches(UriInfo uriInfo, Integer firstResult, Integer maxResults) {
BatchQueryDto queryDto = new BatchQueryDto(getObjectMapper(), uriInfo.getQueryParameters());
BatchQuery query = queryDto.toQuery(getProcessEngine());
List<Batch> matchingBatches = QueryUtil.list(query, firstResult, maxResults);
List<BatchDto> batchResults = new ArrayList<BatchDto>();
for (Batch matchingBatch : matchingBatches) {
batchResults.add(BatchDto.fromBatch(matchingBatch));
}
return batchResults;
}
@Override
public CountResultDto getBatchesCount(UriInfo uriInfo) {
ProcessEngine processEngine = getProcessEngine();
BatchQueryDto queryDto = new BatchQueryDto(getObjectMapper(), uriInfo.getQueryParameters());
BatchQuery query = queryDto.toQuery(processEngine);
long count = query.count();
return new CountResultDto(count);
}
@Override
public List<BatchStatisticsDto> getStatistics(UriInfo uriInfo, Integer firstResult, Integer maxResults) {
BatchStatisticsQueryDto queryDto = new BatchStatisticsQueryDto(getObjectMapper(), uriInfo.getQueryParameters());
BatchStatisticsQuery query = queryDto.toQuery(getProcessEngine());
List<BatchStatistics> batchStatisticsList = QueryUtil.list(query, firstResult, maxResults);
List<BatchStatisticsDto> statisticsResults = new ArrayList<BatchStatisticsDto>();
for (BatchStatistics batchStatistics : batchStatisticsList) {
|
statisticsResults.add(BatchStatisticsDto.fromBatchStatistics(batchStatistics));
}
return statisticsResults;
}
@Override
public CountResultDto getStatisticsCount(UriInfo uriInfo) {
BatchStatisticsQueryDto queryDto = new BatchStatisticsQueryDto(getObjectMapper(), uriInfo.getQueryParameters());
BatchStatisticsQuery query = queryDto.toQuery(getProcessEngine());
long count = query.count();
return new CountResultDto(count);
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\BatchRestServiceImpl.java
| 1
|
请完成以下Java代码
|
public String getFilename()
{
final String contentType = getContentType();
final String fileExtension = MimeType.getExtensionByType(contentType);
final String name = archive.getName();
return FileUtil.changeFileExtension(name, fileExtension);
}
@Override
public byte[] getData()
{
return archiveBL.getBinaryData(archive);
}
@Override
public String getContentType()
|
{
return archiveBL.getContentType(archive);
}
@Override
public URI getUrl()
{
return null;
}
@Override
public Instant getCreated()
{
return archive.getCreated().toInstant();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\attachments\DocumentArchiveEntry.java
| 1
|
请完成以下Java代码
|
public Date getStartTime() {
return startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
public Date getEndTime() {
return endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public Integer getClickCount() {
return clickCount;
}
public void setClickCount(Integer clickCount) {
this.clickCount = clickCount;
}
public Integer getOrderCount() {
return orderCount;
}
public void setOrderCount(Integer orderCount) {
this.orderCount = orderCount;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public Integer getSort() {
return sort;
}
|
public void setSort(Integer sort) {
this.sort = sort;
}
@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(", name=").append(name);
sb.append(", type=").append(type);
sb.append(", pic=").append(pic);
sb.append(", startTime=").append(startTime);
sb.append(", endTime=").append(endTime);
sb.append(", status=").append(status);
sb.append(", clickCount=").append(clickCount);
sb.append(", orderCount=").append(orderCount);
sb.append(", url=").append(url);
sb.append(", note=").append(note);
sb.append(", sort=").append(sort);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}
|
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\SmsHomeAdvertise.java
| 1
|
请完成以下Java代码
|
public String getTaskState() {
return taskState;
}
public void setTaskState(String taskState) {
this.taskState = taskState;
}
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
public void setRootProcessInstanceId(String rootProcessInstanceId) {
this.rootProcessInstanceId = rootProcessInstanceId;
}
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[taskId" + taskId
+ ", assignee=" + assignee
+ ", owner=" + owner
+ ", name=" + name
+ ", description=" + description
+ ", dueDate=" + dueDate
+ ", followUpDate=" + followUpDate
+ ", priority=" + priority
|
+ ", parentTaskId=" + parentTaskId
+ ", deleteReason=" + deleteReason
+ ", taskDefinitionKey=" + taskDefinitionKey
+ ", durationInMillis=" + durationInMillis
+ ", startTime=" + startTime
+ ", endTime=" + endTime
+ ", id=" + id
+ ", eventType=" + eventType
+ ", executionId=" + executionId
+ ", processDefinitionId=" + processDefinitionId
+ ", rootProcessInstanceId=" + rootProcessInstanceId
+ ", processInstanceId=" + processInstanceId
+ ", activityInstanceId=" + activityInstanceId
+ ", tenantId=" + tenantId
+ ", taskState=" + taskState
+ "]";
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricTaskInstanceEventEntity.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public @Nullable Resource getPublicKeyLocation() {
return this.publicKeyLocation;
}
public void setPublicKeyLocation(@Nullable Resource publicKeyLocation) {
this.publicKeyLocation = publicKeyLocation;
}
public List<String> getAudiences() {
return this.audiences;
}
public void setAudiences(List<String> audiences) {
this.audiences = audiences;
}
public @Nullable String getAuthorityPrefix() {
return this.authorityPrefix;
}
public void setAuthorityPrefix(@Nullable String authorityPrefix) {
this.authorityPrefix = authorityPrefix;
}
public @Nullable String getAuthoritiesClaimDelimiter() {
return this.authoritiesClaimDelimiter;
}
public void setAuthoritiesClaimDelimiter(@Nullable String authoritiesClaimDelimiter) {
this.authoritiesClaimDelimiter = authoritiesClaimDelimiter;
}
public @Nullable String getAuthoritiesClaimName() {
return this.authoritiesClaimName;
}
public void setAuthoritiesClaimName(@Nullable String authoritiesClaimName) {
this.authoritiesClaimName = authoritiesClaimName;
}
public @Nullable String getPrincipalClaimName() {
return this.principalClaimName;
}
public void setPrincipalClaimName(@Nullable String principalClaimName) {
this.principalClaimName = principalClaimName;
}
public String readPublicKey() throws IOException {
String key = "spring.security.oauth2.resourceserver.jwt.public-key-location";
if (this.publicKeyLocation == null) {
throw new InvalidConfigurationPropertyValueException(key, this.publicKeyLocation,
"No public key location specified");
}
|
if (!this.publicKeyLocation.exists()) {
throw new InvalidConfigurationPropertyValueException(key, this.publicKeyLocation,
"Public key location does not exist");
}
try (InputStream inputStream = this.publicKeyLocation.getInputStream()) {
return StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
}
}
}
public static class Opaquetoken {
/**
* Client id used to authenticate with the token introspection endpoint.
*/
private @Nullable String clientId;
/**
* Client secret used to authenticate with the token introspection endpoint.
*/
private @Nullable String clientSecret;
/**
* OAuth 2.0 endpoint through which token introspection is accomplished.
*/
private @Nullable String introspectionUri;
public @Nullable String getClientId() {
return this.clientId;
}
public void setClientId(@Nullable String clientId) {
this.clientId = clientId;
}
public @Nullable String getClientSecret() {
return this.clientSecret;
}
public void setClientSecret(@Nullable String clientSecret) {
this.clientSecret = clientSecret;
}
public @Nullable String getIntrospectionUri() {
return this.introspectionUri;
}
public void setIntrospectionUri(@Nullable String introspectionUri) {
this.introspectionUri = introspectionUri;
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-security-oauth2-resource-server\src\main\java\org\springframework\boot\security\oauth2\server\resource\autoconfigure\OAuth2ResourceServerProperties.java
| 2
|
请完成以下Java代码
|
I_PP_Order createProductionOrder(@NonNull final PPOrderRequestedEvent ppOrderRequestedEvent)
{
final PPOrder ppOrder = ppOrderRequestedEvent.getPpOrder();
final PPOrderData ppOrderData = ppOrder.getPpOrderData();
final Instant dateOrdered = ppOrderRequestedEvent.getDateOrdered();
final ProductId productId = ProductId.ofRepoId(ppOrderData.getProductDescriptor().getProductId());
final I_C_UOM uom = productBL.getStockUOM(productId);
final Quantity qtyRequired = Quantity.of(ppOrderData.getQtyRequired(), uom);
return ppOrderService.createOrder(PPOrderCreateRequest.builder()
.clientAndOrgId(ppOrderData.getClientAndOrgId())
.productPlanningId(ProductPlanningId.ofRepoIdOrNull(ppOrderData.getProductPlanningId()))
.materialDispoGroupId(ppOrderData.getMaterialDispoGroupId())
.plantId(ppOrderData.getPlantId())
.workstationId(ppOrderData.getWorkstationId())
.warehouseId(ppOrderData.getWarehouseId())
|
//
.productId(productId)
.attributeSetInstanceId(AttributeSetInstanceId.ofRepoIdOrNone(ppOrderData.getProductDescriptor().getAttributeSetInstanceId()))
.qtyRequired(qtyRequired)
//
.dateOrdered(dateOrdered)
.datePromised(ppOrderData.getDatePromised())
.dateStartSchedule(ppOrderData.getDateStartSchedule())
//
.shipmentScheduleId(ShipmentScheduleId.ofRepoIdOrNull(ppOrderData.getShipmentScheduleIdAsRepoId()))
.salesOrderLineId(OrderLineId.ofRepoIdOrNull(ppOrderData.getOrderLineIdAsRepoId()))
//
.build());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\event\PPOrderRequestedEventHandler.java
| 1
|
请完成以下Java代码
|
public int getM_PackagingContainer_ID()
{
return get_ValueAsInt(COLUMNNAME_M_PackagingContainer_ID);
}
@Override
public void setM_Product_ID(final int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value(COLUMNNAME_M_Product_ID, null);
else
set_Value(COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setName(final java.lang.String Name)
{
set_Value(COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setValue(final @Nullable java.lang.String Value)
{
set_Value(COLUMNNAME_Value, Value);
}
|
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
@Override
public void setWidth(final @Nullable BigDecimal Width)
{
set_Value(COLUMNNAME_Width, Width);
}
@Override
public BigDecimal getWidth()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Width);
return bd != null ? bd : BigDecimal.ZERO;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_PackagingContainer.java
| 1
|
请完成以下Java代码
|
public void mouseEntered(final MouseEvent e)
{
// nothing to do
}
@Override
public void mouseExited(final MouseEvent e)
{
// nothing to do
}
@Override
public void mousePressed(final MouseEvent e)
{
// nothing to do
}
@Override
public void mouseReleased(final MouseEvent e)
{
// nothing to do
}
@Override
public void mouseClicked(final MouseEvent e)
{
if (e == null || listBox.getSelectedValue().equals(ITEM_More))
{
setUserObject(null);
return;
}
popup.setVisible(false); // 02027: tsa: hide popup when an item is selected
final Object selected = listBox.getSelectedValue();
setUserObject(selected);
textBox.setText(convertUserObjectForTextField(selected));
}
public void addPropertyChangeListener(final PropertyChangeListener listener)
{
listBox.addPropertyChangeListener(listener);
}
public void setMaxItems(final int maxItems)
{
m_maxItems = maxItems;
|
listBox.setVisibleRowCount(m_maxItems + 1);
}
public int getMaxItems()
{
return m_maxItems;
}
public final String getText()
{
return textBox.getText();
}
protected final int getTextCaretPosition()
{
return textBox.getCaretPosition();
}
protected final void setTextCaretPosition(final int caretPosition)
{
textBox.setCaretPosition(caretPosition);
}
protected final void setText(final String text)
{
textBox.setText(text);
}
public final boolean isEnabled()
{
final boolean textBoxHasFocus = textBox.isFocusOwner();
return textBoxHasFocus;
}
public void setPopupMinimumChars(final int popupMinimumChars)
{
m_popupMinimumChars = popupMinimumChars;
}
public int getPopupMinimumChars()
{
return m_popupMinimumChars;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\apps\search\FieldAutoCompleter.java
| 1
|
请完成以下Java代码
|
public ReturnsInOutHeaderFiller setMovementType(final String movementType)
{
this.movementType = movementType;
return this;
}
private String getMovementType()
{
return movementType;
}
public ReturnsInOutHeaderFiller setReturnsDocTypeIdProvider(final IReturnsDocTypeIdProvider returnsDocTypeIdProvider)
{
this.returnsDocTypeIdProvider = returnsDocTypeIdProvider;
return this;
}
private int getReturnsDocTypeId(final String docBaseType, final boolean isSOTrx, final int adClientId, final int adOrgId)
{
return returnsDocTypeIdProvider.getReturnsDocTypeId(docBaseType, isSOTrx, adClientId, adOrgId);
}
public ReturnsInOutHeaderFiller setBPartnerId(final int bpartnerId)
{
this.bpartnerId = bpartnerId;
return this;
}
private int getBPartnerId()
{
return bpartnerId;
}
public ReturnsInOutHeaderFiller setBPartnerLocationId(final int bpartnerLocationId)
{
this.bpartnerLocationId = bpartnerLocationId;
return this;
}
private int getBPartnerLocationId()
{
return bpartnerLocationId;
}
public ReturnsInOutHeaderFiller setMovementDate(final Timestamp movementDate)
{
this.movementDate = movementDate;
return this;
}
private Timestamp getMovementDate()
{
return movementDate;
}
public ReturnsInOutHeaderFiller setWarehouseId(final int warehouseId)
{
this.warehouseId = warehouseId;
return this;
}
private int getWarehouseId()
{
return warehouseId;
}
public ReturnsInOutHeaderFiller setOrder(@Nullable final I_C_Order order)
{
this.order = order;
return this;
}
|
private I_C_Order getOrder()
{
return order;
}
public ReturnsInOutHeaderFiller setExternalId(@Nullable final String externalId)
{
this.externalId = externalId;
return this;
}
private String getExternalId()
{
return this.externalId;
}
private String getExternalResourceURL()
{
return this.externalResourceURL;
}
public ReturnsInOutHeaderFiller setExternalResourceURL(@Nullable final String externalResourceURL)
{
this.externalResourceURL = externalResourceURL;
return this;
}
public ReturnsInOutHeaderFiller setDateReceived(@Nullable final Timestamp dateReceived)
{
this.dateReceived = dateReceived;
return this;
}
private Timestamp getDateReceived()
{
return dateReceived;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inout\returns\ReturnsInOutHeaderFiller.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getName() {
return name;
}
public String getNameLike() {
return nameLike;
}
public String getCategory() {
return category;
}
public String getCategoryNotEquals() {
return categoryNotEquals;
}
public String getKey() {
return key;
}
public boolean isLatest() {
return latest;
|
}
public String getTenantId() {
return tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
}
|
repos\flowable-engine-main\modules\flowable-app-engine\src\main\java\org\flowable\app\engine\impl\repository\AppDeploymentQueryImpl.java
| 2
|
请完成以下Java代码
|
public static MGLCategory getDefault (Properties ctx, String CategoryType)
{
MGLCategory retValue = null;
String sql = "SELECT * FROM GL_Category "
+ "WHERE AD_Client_ID=? AND IsDefault='Y'";
PreparedStatement pstmt = null;
try
{
pstmt = DB.prepareStatement (sql, null);
pstmt.setInt (1, Env.getAD_Client_ID(ctx));
ResultSet rs = pstmt.executeQuery ();
while (rs.next ())
{
MGLCategory temp = new MGLCategory (ctx, rs, null);
if (CategoryType != null && CategoryType.equals(temp.getCategoryType()))
{
retValue = temp;
break;
}
if (retValue == null)
retValue = temp;
}
rs.close ();
pstmt.close ();
pstmt = null;
}
catch (Exception e)
{
s_log.error(sql, e);
}
try
{
if (pstmt != null)
pstmt.close ();
pstmt = null;
}
catch (Exception e)
{
pstmt = null;
}
return retValue;
} // getDefault
/**
* Get Default System Category
* @param ctx context
* @return GL Category
*/
public static MGLCategory getDefaultSystem (Properties ctx)
{
MGLCategory retValue = getDefault(ctx, CATEGORYTYPE_SystemGenerated);
if (retValue == null
|| !retValue.getCategoryType().equals(CATEGORYTYPE_SystemGenerated))
{
retValue = new MGLCategory(ctx, 0, null);
retValue.setName("Default System");
retValue.setCategoryType(CATEGORYTYPE_SystemGenerated);
|
retValue.setIsDefault(true);
if (!retValue.save())
throw new IllegalStateException("Could not save default system GL Category");
}
return retValue;
} // getDefaultSystem
/** Logger */
private static Logger s_log = LogManager.getLogger(MGLCategory.class);
/** Cache */
private static CCache<Integer, MGLCategory> s_cache
= new CCache<Integer, MGLCategory> ("GL_Category", 5);
/**************************************************************************
* Standard Constructor
* @param ctx context
* @param GL_Category_ID id
* @param trxName transaction
*/
public MGLCategory (Properties ctx, int GL_Category_ID, String trxName)
{
super (ctx, GL_Category_ID, trxName);
if (GL_Category_ID == 0)
{
// setName (null);
setCategoryType (CATEGORYTYPE_Manual);
setIsDefault (false);
}
} // MGLCategory
/**
* Load Constructor
* @param ctx context
* @param rs result set
* @param trxName transaction
*/
public MGLCategory (Properties ctx, ResultSet rs, String trxName)
{
super(ctx, rs, trxName);
} // MGLCategory
@Override
public String toString()
{
return getClass().getSimpleName()+"["+get_ID()
+", Name="+getName()
+", IsDefault="+isDefault()
+", IsActive="+isActive()
+", CategoryType="+getCategoryType()
+"]";
}
} // MGLCategory
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MGLCategory.java
| 1
|
请完成以下Java代码
|
public static Class getClassByScn(String className) {
Class myclass = null;
try {
myclass = Class.forName(className);
} catch (ClassNotFoundException e) {
e.printStackTrace();
throw new RuntimeException(className+" not found!");
}
return myclass;
}
/**
* 获得类的全名,包括包名
* @param object
* @return
*/
public static String getPackPath(Object object) {
// 检查用户传入的参数是否为空
if (object == null) {
throw new java.lang.IllegalArgumentException("参数不能为空!");
}
// 获得类的全名,包括包名
String clsName = object.getClass().getName();
return clsName;
}
public static String getAppPath(Class cls) {
// 检查用户传入的参数是否为空
if (cls == null) {
throw new java.lang.IllegalArgumentException("参数不能为空!");
}
ClassLoader loader = cls.getClassLoader();
// 获得类的全名,包括包名
String clsName = cls.getName() + ".class";
// 获得传入参数所在的包
Package pack = cls.getPackage();
String path = "";
// 如果不是匿名包,将包名转化为路径
if (pack != null) {
String packName = pack.getName();
String javaSpot="java.";
String javaxSpot="javax.";
// 此处简单判定是否是Java基础类库,防止用户传入JDK内置的类库
if (packName.startsWith(javaSpot) || packName.startsWith(javaxSpot)) {
throw new java.lang.IllegalArgumentException("不要传送系统类!");
}
// 在类的名称中,去掉包名的部分,获得类的文件名
clsName = clsName.substring(packName.length() + 1);
// 判定包名是否是简单包名,如果是,则直接将包名转换为路径,
|
if (packName.indexOf(SymbolConstant.SPOT) < 0) {
path = packName + "/";
} else {
// 否则按照包名的组成部分,将包名转换为路径
int start = 0, end = 0;
end = packName.indexOf(".");
StringBuilder pathBuilder = new StringBuilder();
while (end != -1) {
pathBuilder.append(packName, start, end).append("/");
start = end + 1;
end = packName.indexOf(".", start);
}
if(oConvertUtils.isNotEmpty(pathBuilder.toString())){
path = pathBuilder.toString();
}
path = path + packName.substring(start) + "/";
}
}
// 调用ClassLoader的getResource方法,传入包含路径信息的类文件名
java.net.URL url = loader.getResource(path + clsName);
// 从URL对象中获取路径信息
String realPath = url.getPath();
// 去掉路径信息中的协议名"file:"
int pos = realPath.indexOf("file:");
if (pos > -1) {
realPath = realPath.substring(pos + 5);
}
// 去掉路径信息最后包含类文件信息的部分,得到类所在的路径
pos = realPath.indexOf(path + clsName);
realPath = realPath.substring(0, pos - 1);
// 如果类文件被打包到JAR等文件中时,去掉对应的JAR等打包文件名
if (realPath.endsWith(SymbolConstant.EXCLAMATORY_MARK)) {
realPath = realPath.substring(0, realPath.lastIndexOf("/"));
}
/*------------------------------------------------------------
ClassLoader的getResource方法使用了utf-8对路径信息进行了编码,当路径
中存在中文和空格时,他会对这些字符进行转换,这样,得到的往往不是我们想要
的真实路径,在此,调用了URLDecoder的decode方法进行解码,以便得到原始的
中文及空格路径
-------------------------------------------------------------*/
try {
realPath = java.net.URLDecoder.decode(realPath, "utf-8");
} catch (Exception e) {
throw new RuntimeException(e);
}
return realPath;
}// getAppPath定义结束
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\MyClassLoader.java
| 1
|
请完成以下Java代码
|
public String getSummary(final I_C_Dunning_Candidate candidate)
{
if (candidate == null)
{
return null;
}
return "#" + candidate.getC_Dunning_Candidate_ID();
}
@Override
public boolean isExpired(final I_C_Dunning_Candidate candidate, final Timestamp dunningGraceDate)
{
Check.assumeNotNull(candidate, "candidate not null");
if (candidate.isProcessed())
{
// candidate already processed => not expired
return false;
}
if (dunningGraceDate == null)
{
// no dunning grace date => not expired
return false;
}
final Timestamp dunningDate = candidate.getDunningDate();
if (dunningDate.compareTo(dunningGraceDate) >= 0)
{
// DunningDate >= DunningGrace => candidate is perfectly valid. It's date is after dunningGrace date
return false;
}
// DunningDate < DunningGrace => candidate is no longer valid
return true;
|
}
@Override
public I_C_Dunning_Candidate getLastLevelCandidate(final List<I_C_Dunning_Candidate> candidates)
{
Check.errorIf(candidates.isEmpty(), "Error: No candidates selected.");
I_C_Dunning_Candidate result = candidates.get(0);
BigDecimal maxDaysAfterDue = result.getC_DunningLevel().getDaysAfterDue();
for (final I_C_Dunning_Candidate candidate : candidates)
{
if (maxDaysAfterDue.compareTo(candidate.getC_DunningLevel().getDaysAfterDue()) < 0)
{
result = candidate;
maxDaysAfterDue = candidate.getC_DunningLevel().getDaysAfterDue();
}
}
return result;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\api\impl\DunningBL.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
static class OAuth2SecurityFilterChainConfiguration {
@Bean
@ConditionalOnBean(JwtDecoder.class)
SecurityFilterChain jwtSecurityFilterChain(HttpSecurity http) {
http.authorizeHttpRequests((requests) -> requests.anyRequest().authenticated());
http.oauth2ResourceServer((resourceServer) -> resourceServer.jwt(withDefaults()));
return http.build();
}
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnMissingBean(JwtAuthenticationConverter.class)
@Conditional(JwtConverterPropertiesCondition.class)
static class JwtConverterConfiguration {
private final OAuth2ResourceServerProperties.Jwt properties;
JwtConverterConfiguration(OAuth2ResourceServerProperties properties) {
this.properties = properties.getJwt();
}
@Bean
JwtAuthenticationConverter getJwtAuthenticationConverter() {
JwtGrantedAuthoritiesConverter grantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
PropertyMapper map = PropertyMapper.get();
map.from(this.properties.getAuthorityPrefix()).to(grantedAuthoritiesConverter::setAuthorityPrefix);
map.from(this.properties.getAuthoritiesClaimDelimiter())
.to(grantedAuthoritiesConverter::setAuthoritiesClaimDelimiter);
map.from(this.properties.getAuthoritiesClaimName())
.to(grantedAuthoritiesConverter::setAuthoritiesClaimName);
JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();
map.from(this.properties.getPrincipalClaimName()).to(jwtAuthenticationConverter::setPrincipalClaimName);
jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(grantedAuthoritiesConverter);
return jwtAuthenticationConverter;
}
}
private static class JwtConverterPropertiesCondition extends AnyNestedCondition {
JwtConverterPropertiesCondition() {
super(ConfigurationPhase.REGISTER_BEAN);
|
}
@ConditionalOnProperty("spring.security.oauth2.resourceserver.jwt.authority-prefix")
static class OnAuthorityPrefix {
}
@ConditionalOnProperty("spring.security.oauth2.resourceserver.jwt.principal-claim-name")
static class OnPrincipalClaimName {
}
@ConditionalOnProperty("spring.security.oauth2.resourceserver.jwt.authorities-claim-name")
static class OnAuthoritiesClaimName {
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-security-oauth2-resource-server\src\main\java\org\springframework\boot\security\oauth2\server\resource\autoconfigure\servlet\OAuth2ResourceServerJwtConfiguration.java
| 2
|
请完成以下Java代码
|
void doNothingWithWrongContract() {
}
@Contract("_, null -> null; null, _ -> param2; _, !null -> !null")
String concatenateOnlyIfSecondArgumentIsNotNull(String head, String tail) {
if (tail == null) {
return null;
}
if (head == null) {
return tail;
}
return head + tail;
}
void uselessNullCheck() {
String head = "1234";
String tail = "5678";
String concatenation = concatenateOnlyIfSecondArgumentIsNotNull(head, tail);
if (concatenation != null) {
System.out.println(concatenation);
}
}
void uselessNullCheckOnInferredAnnotation() {
if (StringUtils.isEmpty(null)) {
System.out.println("baeldung");
}
}
@Contract(pure = true)
String replace(String string, char oldChar, char newChar) {
return string.replace(oldChar, newChar);
}
@Contract(value = "true -> false; false -> true", pure = true)
boolean not(boolean input) {
return !input;
}
@Contract("true -> new")
void contractExpectsWrongParameterType(List<Integer> integers) {
}
@Contract("_, _ -> new")
void contractExpectsMoreParametersThanMethodHas(String s) {
}
@Contract("_ -> _; null -> !null")
String secondContractClauseNotReachable(String s) {
return "";
}
@Contract("_ -> true")
void contractExpectsWrongReturnType(String s) {
}
|
// NB: the following examples demonstrate how to use the mutates attribute of the annotation
// This attribute is currently experimental and could be changed or removed in the future
@Contract(mutates = "param")
void incrementArrayFirstElement(Integer[] integers) {
if (integers.length > 0) {
integers[0] = integers[0] + 1;
}
}
@Contract(pure = true, mutates = "param")
void impossibleToMutateParamInPureFunction(List<String> strings) {
if (strings != null) {
strings.forEach(System.out::println);
}
}
@Contract(mutates = "param3")
void impossibleToMutateThirdParamWhenMethodHasOnlyTwoParams(int a, int b) {
}
@Contract(mutates = "param")
void impossibleToMutableImmutableType(String s) {
}
@Contract(mutates = "this")
static void impossibleToMutateThisInStaticMethod() {
}
}
|
repos\tutorials-master\jetbrains-annotations\src\main\java\com\baeldung\annotations\Demo.java
| 1
|
请完成以下Java代码
|
public boolean isLogTableName(final String tableName, final ClientId clientId)
{
final Set<String> tablesToIgnoreUC = getTablesToIgnoreUC(clientId);
return !tablesToIgnoreUC.contains(tableName.toUpperCase());
}
public void addTablesToIgnoreList(@NonNull final String... tableNames)
{
addTablesToIgnoreList(ImmutableSet.copyOf(tableNames));
}
public synchronized void addTablesToIgnoreList(@NonNull final Collection<String> tableNames)
{
if (tableNames.isEmpty())
{
return;
}
this._tablesIgnoreSystemUC = addTableNamesUC(this._tablesIgnoreSystemUC, tableNames);
this._tablesIgnoreClientUC = addTableNamesUC(this._tablesIgnoreClientUC, tableNames);
logger.info("Skip migration scripts logging for: {}", tableNames);
}
public ImmutableSet<String> getTablesToIgnoreUC(final ClientId clientId)
{
return clientId.isSystem() ? _tablesIgnoreSystemUC : _tablesIgnoreClientUC;
}
|
private static ImmutableSet<String> addTableNamesUC(
@NonNull final ImmutableSet<String> targetListUC,
@NonNull final Collection<String> tableNamesToAdd)
{
if (tableNamesToAdd.isEmpty())
{
return targetListUC;
}
final ImmutableSet.Builder<String> builder = ImmutableSet.builder();
builder.addAll(targetListUC);
tableNamesToAdd.stream().map(String::toUpperCase).forEach(builder::add);
final ImmutableSet<String> result = builder.build();
if (targetListUC.size() == result.size())
{
return targetListUC; // no change
}
return result;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\logger\TableNamesSkipList.java
| 1
|
请完成以下Java代码
|
public void execute()
{
final ImmutableMap<InOutAndLineId, InOutAndLineId> initialReversalLineId2lineId = inoutBL.getLines(inoutId)
.stream()
.collect(ImmutableMap.toImmutableMap(
inoutLine -> InOutAndLineId.ofRepoId(initialReversalId, inoutLine.getReversalLine_ID()),
inoutLine -> InOutAndLineId.ofRepoId(inoutLine.getM_InOut_ID(), inoutLine.getM_InOutLine_ID())
));
final ImmutableList<InOutCost> initialCosts = inOutCostRepository.getByInOutId(initialReversalId);
if (initialCosts.isEmpty())
{
return;
}
final ImmutableSet<OrderCostId> orderCostIds = initialCosts.stream().map(InOutCost::getOrderCostId).collect(ImmutableSet.toImmutableSet());
final ImmutableMap<OrderCostId, OrderCost> orderCostsById = Maps.uniqueIndex(orderCostRepository.getByIds(orderCostIds), OrderCost::getId);
for (final InOutCost initialCost : initialCosts)
{
final InOutAndLineId initialReversalLineId = initialCost.getInoutAndLineId();
final InOutAndLineId lineId = initialReversalLineId2lineId.get(initialReversalLineId);
if (lineId == null)
{
continue;
}
final InOutCost reversalCost = inOutCostRepository.create(InOutCostCreateRequest.builder()
.reversalId(initialCost.getReversalId())
.orgId(initialCost.getOrgId())
.orderCostDetailId(initialCost.getOrderCostDetailId())
.orderAndLineId(initialCost.getOrderAndLineId())
.soTrx(initialCost.getSoTrx())
.inoutAndLineId(lineId)
.bpartnerId(initialCost.getBpartnerId())
.costTypeId(initialCost.getCostTypeId())
.costElementId(initialCost.getCostElementId())
|
.qty(initialCost.getQty().negate())
.costAmount(initialCost.getCostAmount().negate())
.build());
initialCost.setReversalId(reversalCost.getId());
final OrderCost orderCost = orderCostsById.get(reversalCost.getOrderCostId());
orderCost.addInOutCost(
OrderCostAddInOutRequest.builder()
.orderLineId(reversalCost.getOrderLineId())
.qty(reversalCost.getQty())
.costAmount(reversalCost.getCostAmount())
.build());
}
inOutCostRepository.saveAll(initialCosts); // so have the reversal link
orderCostRepository.saveAll(orderCostsById.values());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\costs\inout\InOutCostReverseCommand.java
| 1
|
请完成以下Java代码
|
public void add(@NonNull final HUToReport hu, @NonNull final HULabelConfig labelConfig)
{
// Don't add it if we already considered it
if (!huIdsCollected.add(hu.getHUId()))
{
return;
}
final BatchToPrint lastBatch = !batches.isEmpty() ? batches.get(batches.size() - 1) : null;
final BatchToPrint batch;
if (lastBatch == null || !lastBatch.isMatching(labelConfig))
{
batch = new BatchToPrint(labelConfig.getPrintFormatProcessId());
batches.add(batch);
}
else
{
batch = lastBatch;
}
batch.addHU(hu);
}
public void forEach(@NonNull final Consumer<BatchToPrint> action)
{
batches.forEach(action);
}
|
}
@Getter
private static class BatchToPrint
{
@NonNull
private final AdProcessId printFormatProcessId;
@NonNull
private final ArrayList<HUToReport> hus = new ArrayList<>();
private BatchToPrint(final @NonNull AdProcessId printFormatProcessId)
{
this.printFormatProcessId = printFormatProcessId;
}
public boolean isMatching(@NonNull final HULabelConfig labelConfig)
{
return AdProcessId.equals(printFormatProcessId, labelConfig.getPrintFormatProcessId());
}
public void addHU(@NonNull final HUToReport hu)
{
this.hus.add(hu);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\workflows_api\activity_handlers\printReceivedHUQRCodes\PrintReceivedHUQRCodesActivityHandler.java
| 1
|
请完成以下Java代码
|
public class WebClientStatusCodeHandler {
public static Mono<String> getResponseBodyUsingExchangeFilterFunction(String uri) {
ExchangeFilterFunction errorResponseFilter = ExchangeFilterFunction
.ofResponseProcessor(WebClientStatusCodeHandler::exchangeFilterResponseProcessor);
return WebClient
.builder()
.filter(errorResponseFilter)
.build()
.post()
.uri(uri)
.retrieve()
.bodyToMono(String.class);
}
public static Mono<String> getResponseBodyUsingOnStatus(String uri) {
return WebClient
.builder()
.build()
.post()
.uri(uri)
.retrieve()
.onStatus(
HttpStatus.INTERNAL_SERVER_ERROR::equals,
response -> response.bodyToMono(String.class).map(CustomServerErrorException::new))
.onStatus(
HttpStatus.BAD_REQUEST::equals,
|
response -> response.bodyToMono(String.class).map(CustomBadRequestException::new))
.bodyToMono(String.class);
}
private static Mono<ClientResponse> exchangeFilterResponseProcessor(ClientResponse response) {
HttpStatusCode status = response.statusCode();
if (HttpStatus.INTERNAL_SERVER_ERROR.equals(status)) {
return response.bodyToMono(String.class)
.flatMap(body -> Mono.error(new CustomServerErrorException(body)));
}
if (HttpStatus.BAD_REQUEST.equals(status)) {
return response.bodyToMono(String.class)
.flatMap(body -> Mono.error(new CustomBadRequestException(body)));
}
return Mono.just(response);
}
}
|
repos\tutorials-master\spring-reactive-modules\spring-reactive-client\src\main\java\com\baeldung\webclient\status\WebClientStatusCodeHandler.java
| 1
|
请完成以下Java代码
|
public static class JsonLookupResult {
private String id;
private String name;
private JsonNode jsonNode;
public JsonLookupResult(String id, String name, JsonNode jsonNode) {
this(name, jsonNode);
this.id = id;
}
public JsonLookupResult(String name, JsonNode jsonNode) {
this.name = name;
this.jsonNode = jsonNode;
}
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 JsonNode getJsonNode() {
return jsonNode;
}
public void setJsonNode(JsonNode jsonNode) {
this.jsonNode = jsonNode;
}
}
}
|
repos\Activiti-develop\activiti-core\activiti-json-converter\src\main\java\org\activiti\editor\language\json\converter\util\JsonConverterUtil.java
| 1
|
请完成以下Java代码
|
public static void printTextNTimesUpTo50(String textToPrint, int times) {
int counter = 1;
while (counter < 50) {
System.out.println(textToPrint);
if (counter == times) {
break;
}
}
}
/**
* Finds the index of {@code name} in a list
* @param name The name to look for
* @param names The list of names
* @return The index where the name was found or -1 otherwise
*/
public static int findFirstInstanceOfName(String name, String[] names) {
int index = 0;
for ( ; index < names.length; index++) {
if (names[index].equals(name)) {
break;
}
}
return index == names.length ? -1 : index;
}
/**
* Takes several names and makes a list, skipping the specified {@code name}.
*
* @param name The name to skip
* @param names The list of names
* @return The list of names as a single string, missing the specified {@code name}.
*/
public static String makeListSkippingName(String name, String[] names) {
String list = "";
for (int i = 0; i < names.length; i++) {
if (names[i].equals(name)) {
continue;
}
list += names[i];
}
return list;
}
/**
* Prints an specified amount of even numbers. Shows usage of both {@code break} and {@code continue} branching statements.
* @param amountToPrint Amount of even numbers to print.
*/
public static void printEvenNumbers(int amountToPrint) {
if (amountToPrint <= 0) { // Invalid input
return;
}
int iterator = 0;
int amountPrinted = 0;
while (true) {
if (iterator % 2 == 0) { // Is an even number
System.out.println(iterator);
amountPrinted++;
iterator++;
} else {
iterator++;
continue; // Won't print
}
|
if (amountPrinted == amountToPrint) {
break;
}
}
}
/**
* Prints an specified amount of even numbers, up to 100. Shows usage of both {@code break} and {@code continue} branching statements.
* @param amountToPrint Amount of even numbers to print.
*/
public static void printEvenNumbersToAMaxOf100(int amountToPrint) {
if (amountToPrint <= 0) { // Invalid input
return;
}
int iterator = 0;
int amountPrinted = 0;
while (amountPrinted < 100) {
if (iterator % 2 == 0) { // Is an even number
System.out.println(iterator);
amountPrinted++;
iterator++;
} else {
iterator++;
continue; // Won't print
}
if (amountPrinted == amountToPrint) {
break;
}
}
}
}
|
repos\tutorials-master\core-java-modules\core-java-lang-syntax\src\main\java\com\baeldung\core\controlstructures\Loops.java
| 1
|
请完成以下Java代码
|
public abstract class AbstractRuleEntity<T extends AbstractRule> implements RuleEntity {
protected Long id;
protected String app;
protected String ip;
protected Integer port;
protected T rule;
private Date gmtCreate;
private Date gmtModified;
@Override
public Long getId() {
return id;
}
@Override
public void setId(Long id) {
this.id = id;
}
@Override
public String getApp() {
return app;
}
public AbstractRuleEntity<T> setApp(String app) {
this.app = app;
return this;
}
@Override
public String getIp() {
return ip;
}
public AbstractRuleEntity<T> setIp(String ip) {
this.ip = ip;
return this;
}
|
@Override
public Integer getPort() {
return port;
}
public AbstractRuleEntity<T> setPort(Integer port) {
this.port = port;
return this;
}
public T getRule() {
return rule;
}
public AbstractRuleEntity<T> setRule(T rule) {
this.rule = rule;
return this;
}
@Override
public Date getGmtCreate() {
return gmtCreate;
}
public AbstractRuleEntity<T> setGmtCreate(Date gmtCreate) {
this.gmtCreate = gmtCreate;
return this;
}
public Date getGmtModified() {
return gmtModified;
}
public AbstractRuleEntity<T> setGmtModified(Date gmtModified) {
this.gmtModified = gmtModified;
return this;
}
@Override
public T toRule() {
return rule;
}
}
|
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\datasource\entity\rule\AbstractRuleEntity.java
| 1
|
请完成以下Java代码
|
default <ChildType, ExtChildType extends ChildType> IQueryBuilder<ExtChildType> andCollectChildren(
@NonNull final ModelColumn<ChildType, ?> linkColumnInChildTable,
@NonNull final Class<ExtChildType> childType)
{
final String linkColumnNameInChildTable = linkColumnInChildTable.getColumnName();
return andCollectChildren(linkColumnNameInChildTable, childType);
}
/**
* Returns a query to retrieve those records that reference the result of the query which was specified so far.<br>
* .
* <p>
* This is a convenient version of {@link #andCollectChildren(String, Class)} for the case when you don't have to retrieve an extended interface of the child type.
*
* @param linkColumnInChildTable the column in child model which will be used to join the child records to current record's primary key
* @return query build for <code>ChildType</code>
*/
default <ChildType> IQueryBuilder<ChildType> andCollectChildren(final ModelColumn<ChildType, ?> linkColumnInChildTable)
{
final String linkColumnNameInChildTable = linkColumnInChildTable.getColumnName();
final Class<ChildType> childType = linkColumnInChildTable.getModelClass();
return andCollectChildren(linkColumnNameInChildTable, childType);
}
/**
* Sets the join mode of this instance's internal composite filter.
*
* @return this
* @see ICompositeQueryFilter#setJoinOr()
*/
IQueryBuilder<T> setJoinOr();
/**
* Sets the join mode of this instance's internal composite filter.
*
* @return this
* @see ICompositeQueryFilter#setJoinAnd()
|
*/
IQueryBuilder<T> setJoinAnd();
/**
* Will only return records that are referenced by a <code>T_Selection</code> records which has the given selection ID.
*/
IQueryBuilder<T> setOnlySelection(PInstanceId pinstanceId);
/**
* Start an aggregation of different columns, everything grouped by given <code>column</code>
*
* @return aggregation builder
*/
<TargetModelType> IQueryAggregateBuilder<T, TargetModelType> aggregateOnColumn(ModelColumn<T, TargetModelType> column);
<TargetModelType> IQueryAggregateBuilder<T, TargetModelType> aggregateOnColumn(String collectOnColumnName, Class<TargetModelType> targetModelType);
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\IQueryBuilder.java
| 1
|
请完成以下Java代码
|
public class Post extends TenantEntity {
@Serial
private static final long serialVersionUID = 1L;
/**
* 主键id
*/
@Schema(description = "主键")
@TableId(value = "id", type = IdType.ASSIGN_ID)
@JsonSerialize(using = ToStringSerializer.class)
private Long id;
/**
* 类型
*/
@Schema(description = "类型")
private Integer category;
/**
* 岗位编号
*/
|
@Schema(description = "岗位编号")
private String postCode;
/**
* 岗位名称
*/
@Schema(description = "岗位名称")
private String postName;
/**
* 岗位排序
*/
@Schema(description = "岗位排序")
private Integer sort;
/**
* 岗位描述
*/
@Schema(description = "岗位描述")
private String remark;
}
|
repos\SpringBlade-master\blade-service-api\blade-system-api\src\main\java\org\springblade\system\entity\Post.java
| 1
|
请完成以下Java代码
|
public String getText()
{
return value.toString();
}
@Override
public String toString()
{
return getText();
}
@Override
public int hashCode()
{
return new HashcodeBuilder()
.append(value)
.toHashcode();
}
@Override
public boolean equals(Object obj)
{
|
if (this == obj)
{
return true;
}
final ResultItemWrapper<ValueType> other = EqualsBuilder.getOther(this, obj);
if (other == null)
{
return false;
}
return new EqualsBuilder()
.append(this.value, other.value)
.isEqual();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\swing\autocomplete\ResultItemWrapper.java
| 1
|
请完成以下Java代码
|
public void setResourceName(String resourceName) {
this.resourceName = resourceName;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public Integer getHistoryLevel() {
return historyLevel;
}
public void setHistoryLevel(Integer historyLevel) {
this.historyLevel = historyLevel;
}
public Map<String, Object> getVariables() {
return variables;
}
public void setVariables(Map<String, Object> variables) {
this.variables = variables;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getDiagramResourceName() {
return diagramResourceName;
}
public void setDiagramResourceName(String diagramResourceName) {
this.diagramResourceName = diagramResourceName;
}
public boolean hasStartFormKey() {
return hasStartFormKey;
}
public boolean getHasStartFormKey() {
return hasStartFormKey;
}
public void setStartFormKey(boolean hasStartFormKey) {
this.hasStartFormKey = hasStartFormKey;
}
public void setHasStartFormKey(boolean hasStartFormKey) {
this.hasStartFormKey = hasStartFormKey;
}
public boolean isGraphicalNotationDefined() {
return isGraphicalNotationDefined;
}
public boolean hasGraphicalNotation() {
return isGraphicalNotationDefined;
}
public void setGraphicalNotationDefined(boolean isGraphicalNotationDefined) {
this.isGraphicalNotationDefined = isGraphicalNotationDefined;
}
public int getSuspensionState() {
return suspensionState;
}
public void setSuspensionState(int suspensionState) {
|
this.suspensionState = suspensionState;
}
public boolean isSuspended() {
return suspensionState == SuspensionState.SUSPENDED.getStateCode();
}
public String getEngineVersion() {
return engineVersion;
}
public void setEngineVersion(String engineVersion) {
this.engineVersion = engineVersion;
}
public IOSpecification getIoSpecification() {
return ioSpecification;
}
public void setIoSpecification(IOSpecification ioSpecification) {
this.ioSpecification = ioSpecification;
}
public String toString() {
return "ProcessDefinitionEntity[" + id + "]";
}
public void setAppVersion(Integer appVersion) {
this.appVersion = appVersion;
}
public Integer getAppVersion() {
return this.appVersion;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\ProcessDefinitionEntityImpl.java
| 1
|
请完成以下Java代码
|
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 String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getKey() {
return key;
}
|
public void setKey(String key) {
this.key = key;
}
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
public FormModel getFormModel() {
return formModel;
}
public void setFormModel(FormModel formModel) {
this.formModel = formModel;
}
}
|
repos\flowable-engine-main\modules\flowable-form-api\src\main\java\org\flowable\form\api\FormInfo.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.