instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | class PropertiesFileLoader
{
@NonNull
private final DirectoryChecker directoryChecker;
public Properties loadFromFile(@NonNull final String dir, @NonNull final String filename)
{
return loadFromFile(new File(dir), filename);
}
public Properties loadFromFile(@NonNull final File dir, @NonNull final String filename)
{
final File settingsFile = new File(
directoryChecker.checkDirectory(filename, dir),
filename);
return loadFromFile(settingsFile);
}
public Properties loadFromFile(@NonNull final File settingsFile)
{
final Properties fileProperties = new Properties();
try (final FileInputStream in = new FileInputStream(settingsFile);) | {
fileProperties.load(in);
}
catch (final IOException e)
{
throw new CantLoadPropertiesException("Cannot load " + settingsFile, e);
}
return fileProperties;
}
public static final class CantLoadPropertiesException extends RuntimeException
{
private static final long serialVersionUID = 4240250517349321980L;
public CantLoadPropertiesException(@NonNull final String msg, @NonNull final Exception e)
{
super(msg, e);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.cli\src\main\java\de\metas\migration\cli\rollout_migrate\PropertiesFileLoader.java | 1 |
请完成以下Java代码 | public final String toString ()
{
StringBuffer retVal = new StringBuffer ();
if (codeset != null)
{
for (int i = 0; i < prolog.size (); i++)
{
ConcreteElement e = (ConcreteElement)prolog.elementAt (i);
retVal.append (e.toString (getCodeset ()) + "\n");
}
if (content != null)
retVal.append (content.toString (getCodeset ()));
}
else
{
for (int i = 0; i < prolog.size (); i++)
{
ConcreteElement e = (ConcreteElement)prolog.elementAt (i);
retVal.append (e.toString () + "\n");
}
if (content != null)
retVal.append (content.toString ());
}
/**
* FIXME: The other part of the version hack! Add the version
* declaration to the beginning of the document.
*/
return versionDecl + retVal.toString ();
}
/**
* Override toString so it prints something useful
*
* @param codeset -
* String codeset to use
* @return String - representation of the document
*/
public final String toString (String codeset)
{
StringBuffer retVal = new StringBuffer (); | for (int i = 0; i < prolog.size (); i++)
{
ConcreteElement e = (ConcreteElement)prolog.elementAt (i);
retVal.append (e.toString (getCodeset ()) + "\n");
}
if (content != null)
retVal.append (content.toString (getCodeset ()) + "\n");
/**
* FIXME: The other part of the version hack! Add the version
* declaration to the beginning of the document.
*/
return versionDecl + retVal.toString ();
}
/**
* Clone this document
*
* @return Object - cloned XMLDocument
*/
public Object clone ()
{
return content.clone ();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xml\XMLDocument.java | 1 |
请完成以下Java代码 | private String toBOMLineString(final I_PP_Product_BOMLine bomLine)
{
if (!bomLine.isActive())
{
return null;
}
final I_M_Product product = productsRepo.getById(bomLine.getM_Product_ID());
final String qtyStr = toBOMLineQtyAndUOMString(bomLine);
return (product.getName() + " " + qtyStr).trim();
}
private String toBOMLineQtyAndUOMString(final I_PP_Product_BOMLine bomLine)
{
if (bomLine.isQtyPercentage())
{
return NumberUtils.stripTrailingDecimalZeros(bomLine.getQtyBatch()) + "%";
}
else if (BigDecimal.ONE.equals(bomLine.getQtyBOM()))
{
return "";
} | else
{
final StringBuilder qtyStr = new StringBuilder();
qtyStr.append(NumberUtils.stripTrailingDecimalZeros(bomLine.getQtyBOM()));
final int uomId = bomLine.getC_UOM_ID();
if (uomId > 0)
{
final I_C_UOM uom = uomsRepo.getById(uomId);
qtyStr.append(" ").append(uom.getUOMSymbol());
}
return qtyStr.toString();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\eevolution\api\impl\ProductBOMDescriptionBuilder.java | 1 |
请完成以下Java代码 | protected String doIt()
{
final IPPOrderReceiptHUProducer producer = newReceiptCandidatesProducer()
.bestBeforeDate(computeBestBeforeDate());
if (isReceiveIndividualCUs)
{
producer.withPPOrderLocatorId()
.receiveIndividualPlanningCUs(getIndividualCUsCount());
}
else
{
producer.packUsingLUTUConfiguration(getPackingInfoParams().createAndSaveNewLUTUConfig())
.createDraftReceiptCandidatesAndPlanningHUs();
}
return MSG_OK;
}
@Override
protected void postProcess(final boolean success)
{
// Invalidate the view because for sure we have changes
final PPOrderLinesView ppOrderLinesView = getView();
ppOrderLinesView.invalidateAll();
getViewsRepo().notifyRecordsChangedAsync(I_PP_Order.Table_Name, ppOrderLinesView.getPpOrderId().getRepoId());
}
@Nullable
LocalDate computeBestBeforeDate()
{
if (attributesBL.isAutomaticallySetBestBeforeDate())
{
final PPOrderLineRow row = getSingleSelectedRow();
final int guaranteeDaysMin = productDAO.getProductGuaranteeDaysMinFallbackProductCategory(row.getProductId());
if (guaranteeDaysMin <= 0)
{
return null;
}
final I_PP_Order ppOrderPO = huPPOrderBL.getById(row.getOrderId());
final LocalDate datePromised = TimeUtil.asLocalDate(ppOrderPO.getDatePromised());
return datePromised.plusDays(guaranteeDaysMin);
}
else
{
return null;
}
} | private IPPOrderReceiptHUProducer newReceiptCandidatesProducer()
{
final PPOrderLineRow row = getSingleSelectedRow();
final PPOrderLineType type = row.getType();
if (type == PPOrderLineType.MainProduct)
{
final PPOrderId ppOrderId = row.getOrderId();
return huPPOrderBL.receivingMainProduct(ppOrderId);
}
else if (type == PPOrderLineType.BOMLine_ByCoProduct)
{
final PPOrderBOMLineId ppOrderBOMLineId = row.getOrderBOMLineId();
return huPPOrderBL.receivingByOrCoProduct(ppOrderBOMLineId);
}
else
{
throw new AdempiereException("Receiving is not allowed");
}
}
@NonNull
private Quantity getIndividualCUsCount()
{
if (p_NumberOfCUs <= 0)
{
throw new FillMandatoryException(PARAM_NumberOfCUs);
}
return Quantity.of(p_NumberOfCUs, getSingleSelectedRow().getUomNotNull());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pporder\process\WEBUI_PP_Order_Receipt.java | 1 |
请完成以下Java代码 | protected WorkManager lookupWorkMananger() {
try {
InitialContext initialContext = new InitialContext();
return (WorkManager) initialContext.lookup(commonJWorkManagerName);
} catch (Exception e) {
throw new RuntimeException("Error while starting JobExecutor: could not look up CommonJ WorkManager in Jndi: "+e.getMessage(), e);
}
}
public CommonJWorkManagerExecutorService(JcaExecutorServiceConnector ra, String commonJWorkManagerName) {
this.ra = ra;
this.commonJWorkManagerName = commonJWorkManagerName;
}
public boolean schedule(Runnable runnable, boolean isLongRunning) {
if(isLongRunning) {
return scheduleLongRunning(runnable);
} else {
return executeShortRunning(runnable);
}
}
protected boolean executeShortRunning(Runnable runnable) {
try {
workManager.schedule(new CommonjWorkRunnableAdapter(runnable));
return true;
} catch (WorkRejectedException e) {
logger.log(Level.FINE, "Work rejected", e);
} catch (WorkException e) {
logger.log(Level.WARNING, "WorkException while scheduling jobs for execution", e);
}
return false;
}
protected boolean scheduleLongRunning(Runnable acquisitionRunnable) {
// initialize the workManager here, because we have access to the initial context | // of the calling thread (application), so the jndi lookup is working -> see JCA 1.6 specification
if(workManager == null) {
workManager = lookupWorkMananger();
}
try {
workManager.schedule(new CommonjDeamonWorkRunnableAdapter(acquisitionRunnable));
return true;
} catch (WorkException e) {
logger.log(Level.WARNING, "Could not schedule Job Acquisition Runnable: "+e.getMessage(), e);
return false;
}
}
public Runnable getExecuteJobsRunnable(List<String> jobIds, ProcessEngineImpl processEngine) {
return new JcaInflowExecuteJobsRunnable(jobIds, processEngine, ra);
}
// getters / setters ////////////////////////////////////
public WorkManager getWorkManager() {
return workManager;
}
} | repos\camunda-bpm-platform-master\javaee\jobexecutor-ra\src\main\java\org\camunda\bpm\container\impl\threading\ra\commonj\CommonJWorkManagerExecutorService.java | 1 |
请完成以下Java代码 | public Iterator<GolfTournament.Pairing> iterator() {
return Collections.unmodifiableList(this.pairings).iterator();
}
public GolfTournament play() {
Assert.state(this.golfCourse != null, "No golf course was declared");
Assert.state(!this.players.isEmpty(), "Golfers must register to play before the golf tournament is played");
Assert.state(!this.pairings.isEmpty(), "Pairings must be formed before the golf tournament is played");
Assert.state(!isFinished(), () -> String.format("Golf tournament [%s] has already been played", getName()));
return this;
}
public GolfTournament register(Golfer... players) {
return register(Arrays.asList(ArrayUtils.nullSafeArray(players, Golfer.class)));
}
public GolfTournament register(Iterable<Golfer> players) {
StreamSupport.stream(CollectionUtils.nullSafeIterable(players).spliterator(), false)
.filter(Objects::nonNull)
.forEach(this.players::add);
return this;
}
@Getter
@ToString
@EqualsAndHashCode
@RequiredArgsConstructor(staticName = "of")
public static class Pairing {
private final AtomicBoolean signedScorecard = new AtomicBoolean(false);
@NonNull
private final Golfer playerOne;
@NonNull | private final Golfer playerTwo;
public synchronized void setHole(int hole) {
this.playerOne.setHole(hole);
this.playerTwo.setHole(hole);
}
public synchronized int getHole() {
return getPlayerOne().getHole();
}
public boolean in(@NonNull Golfer golfer) {
return this.playerOne.equals(golfer) || this.playerTwo.equals(golfer);
}
public synchronized int nextHole() {
return getHole() + 1;
}
public synchronized boolean signScorecard() {
return getHole() >= 18
&& this.signedScorecard.compareAndSet(false, true);
}
}
} | repos\spring-boot-data-geode-main\spring-geode-samples\caching\inline-async\src\main\java\example\app\caching\inline\async\client\model\GolfTournament.java | 1 |
请完成以下Java代码 | public int getEXP_ReplicationTrxLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_EXP_ReplicationTrxLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Datensatz-ID.
@param Record_ID
Direct internal record ID
*/
@Override
public void setRecord_ID (int Record_ID)
{
if (Record_ID < 0)
set_Value (COLUMNNAME_Record_ID, null);
else
set_Value (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID));
}
/** Get Datensatz-ID.
@return Direct internal record ID
*/
@Override
public int getRecord_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/**
* ReplicationTrxStatus AD_Reference_ID=540491
* Reference name: EXP_ReplicationTrxStatus
*/
public static final int REPLICATIONTRXSTATUS_AD_Reference_ID=540491;
/** Vollständig = Completed */ | public static final String REPLICATIONTRXSTATUS_Vollstaendig = "Completed";
/** Nicht vollständig importiert = ImportedWithIssues */
public static final String REPLICATIONTRXSTATUS_NichtVollstaendigImportiert = "ImportedWithIssues";
/** Fehler = Failed */
public static final String REPLICATIONTRXSTATUS_Fehler = "Failed";
/** Set Replikationsstatus.
@param ReplicationTrxStatus Replikationsstatus */
@Override
public void setReplicationTrxStatus (java.lang.String ReplicationTrxStatus)
{
set_Value (COLUMNNAME_ReplicationTrxStatus, ReplicationTrxStatus);
}
/** Get Replikationsstatus.
@return Replikationsstatus */
@Override
public java.lang.String getReplicationTrxStatus ()
{
return (java.lang.String)get_Value(COLUMNNAME_ReplicationTrxStatus);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\adempiere\process\rpl\model\X_EXP_ReplicationTrxLine.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Date getLastUpdateTime() {
return lastUpdateTime;
}
public void setLastUpdateTime(Date lastUpdateTime) {
this.lastUpdateTime = lastUpdateTime;
}
@ApiModelProperty(example = "http://localhost:8182/repository/deployments/2")
public String getDeploymentUrl() {
return deploymentUrl;
}
public void setDeploymentUrl(String deploymentUrl) {
this.deploymentUrl = deploymentUrl;
}
@ApiModelProperty(example = "null")
@Override
public String getTenantId() {
return tenantId;
}
@Override
public void setTenantId(String tenantId) { | this.tenantId = tenantId;
}
public String getSourceUrl() {
return sourceUrl;
}
public void setSourceUrl(String sourceUrl) {
this.sourceUrl = sourceUrl;
}
public String getSourceExtraUrl() {
return sourceExtraUrl;
}
public void setSourceExtraUrl(String sourceExtraUrl) {
this.sourceExtraUrl = sourceExtraUrl;
}
} | repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\repository\ModelResponse.java | 2 |
请完成以下Java代码 | public class HUAttributePropagatorFactory implements IHUAttributePropagatorFactory
{
private final Map<String, IHUAttributePropagator> propagators = new ConcurrentHashMap<String, IHUAttributePropagator>();
public HUAttributePropagatorFactory()
{
// Register defaults
registerPropagator(new TopDownHUAttributePropagator());
registerPropagator(new BottomUpHUAttributePropagator());
registerPropagator(new NoPropagationHUAttributePropagator());
}
@Override
public void registerPropagator(final IHUAttributePropagator propagator)
{
propagator.setHUAttributePropagatorFactory(this);
propagators.put(propagator.getPropagationType(), propagator);
}
@Override
public IHUAttributePropagator getPropagator(final IAttributeStorage attributeSet, final I_M_Attribute attribute)
{
final String propagationType = attributeSet.getPropagationType(attribute);
return getPropagator(propagationType);
}
@Override
public IHUAttributePropagator getPropagator(final String propagationType)
{
Check.assumeNotNull(propagationType, "propagationType not null"); | final IHUAttributePropagator propagator = propagators.get(propagationType);
if (propagator == null)
{
throw new IllegalStateException("No propagator was found for type: " + propagationType);
}
return propagator;
}
@Override
public IHUAttributePropagator getReversalPropagator(final String propagationType)
{
final IHUAttributePropagator propagator = getPropagator(propagationType);
return getReversalPropagator(propagator);
}
@Override
public IHUAttributePropagator getReversalPropagator(final IHUAttributePropagator propagator)
{
final String reversalPropagationType = propagator.getReversalPropagationType();
return getPropagator(reversalPropagationType);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\propagation\impl\HUAttributePropagatorFactory.java | 1 |
请完成以下Java代码 | public int getIncrementNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_IncrementNo);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Serial No Control.
@param M_SerNoCtl_ID
Product Serial Number Control
*/
public void setM_SerNoCtl_ID (int M_SerNoCtl_ID)
{
if (M_SerNoCtl_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_SerNoCtl_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_SerNoCtl_ID, Integer.valueOf(M_SerNoCtl_ID));
}
/** Get Serial No Control.
@return Product Serial Number Control
*/
public int getM_SerNoCtl_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_SerNoCtl_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 Prefix.
@param Prefix
Prefix before the sequence number
*/
public void setPrefix (String Prefix)
{
set_Value (COLUMNNAME_Prefix, Prefix); | }
/** Get Prefix.
@return Prefix before the sequence number
*/
public String getPrefix ()
{
return (String)get_Value(COLUMNNAME_Prefix);
}
/** Set Start No.
@param StartNo
Starting number/position
*/
public void setStartNo (int StartNo)
{
set_Value (COLUMNNAME_StartNo, Integer.valueOf(StartNo));
}
/** Get Start No.
@return Starting number/position
*/
public int getStartNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_StartNo);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Suffix.
@param Suffix
Suffix after the number
*/
public void setSuffix (String Suffix)
{
set_Value (COLUMNNAME_Suffix, Suffix);
}
/** Get Suffix.
@return Suffix after the number
*/
public String getSuffix ()
{
return (String)get_Value(COLUMNNAME_Suffix);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_SerNoCtl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setMaxConcurrentRequests(@Nullable Integer maxConcurrentRequests) {
this.maxConcurrentRequests = maxConcurrentRequests;
}
public @Nullable Integer getMaxRequestsPerSecond() {
return this.maxRequestsPerSecond;
}
public void setMaxRequestsPerSecond(@Nullable Integer maxRequestsPerSecond) {
this.maxRequestsPerSecond = maxRequestsPerSecond;
}
public @Nullable Duration getDrainInterval() {
return this.drainInterval;
}
public void setDrainInterval(@Nullable Duration drainInterval) {
this.drainInterval = drainInterval;
}
}
/**
* Name of the algorithm used to compress protocol frames.
*/
public enum Compression {
/**
* Requires 'net.jpountz.lz4:lz4'.
*/
LZ4,
/**
* Requires org.xerial.snappy:snappy-java.
*/
SNAPPY,
/**
* No compression.
*/
NONE
}
public enum ThrottlerType {
/**
* Limit the number of requests that can be executed in parallel. | */
CONCURRENCY_LIMITING("ConcurrencyLimitingRequestThrottler"),
/**
* Limits the request rate per second.
*/
RATE_LIMITING("RateLimitingRequestThrottler"),
/**
* No request throttling.
*/
NONE("PassThroughRequestThrottler");
private final String type;
ThrottlerType(String type) {
this.type = type;
}
public String type() {
return this.type;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-cassandra\src\main\java\org\springframework\boot\cassandra\autoconfigure\CassandraProperties.java | 2 |
请完成以下Java代码 | protected List<FormDefinition> getFormDefinitionsFromModel(Case caseModel, CaseDefinition caseDefinition) {
Set<String> formKeys = new HashSet<>();
List<FormDefinition> formDefinitions = new ArrayList<>();
// for all user tasks
List<HumanTask> humanTasks = caseModel.getPlanModel().findPlanItemDefinitionsOfType(HumanTask.class, true);
for (HumanTask humanTask : humanTasks) {
if (StringUtils.isNotEmpty(humanTask.getFormKey())) {
formKeys.add(humanTask.getFormKey());
}
}
for (String formKey : formKeys) {
addFormDefinitionToCollection(formDefinitions, formKey, caseDefinition);
}
return formDefinitions;
}
protected void addFormDefinitionToCollection(List<FormDefinition> formDefinitions, String formKey, CaseDefinition caseDefinition) {
FormDefinitionQuery formDefinitionQuery = formRepositoryService.createFormDefinitionQuery().formDefinitionKey(formKey); | CmmnDeployment deployment = CommandContextUtil.getCmmnDeploymentEntityManager().findById(caseDefinition.getDeploymentId());
if (deployment.getParentDeploymentId() != null) {
List<FormDeployment> formDeployments = formRepositoryService.createDeploymentQuery().parentDeploymentId(deployment.getParentDeploymentId()).list();
if (formDeployments != null && formDeployments.size() > 0) {
formDefinitionQuery.deploymentId(formDeployments.get(0).getId());
} else {
formDefinitionQuery.latestVersion();
}
} else {
formDefinitionQuery.latestVersion();
}
FormDefinition formDefinition = formDefinitionQuery.singleResult();
if (formDefinition != null) {
formDefinitions.add(formDefinition);
}
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\cmd\GetFormDefinitionsForCaseDefinitionCmd.java | 1 |
请完成以下Java代码 | protected boolean isConcurrentStart(ActivityStartBehavior startBehavior) {
return startBehavior == ActivityStartBehavior.DEFAULT
|| startBehavior == ActivityStartBehavior.CONCURRENT_IN_FLOW_SCOPE;
}
protected void instantiate(ExecutionEntity ancestorScopeExecution, List<PvmActivity> parentFlowScopes, CoreModelElement targetElement) {
if (PvmTransition.class.isAssignableFrom(targetElement.getClass())) {
ancestorScopeExecution.executeActivities(parentFlowScopes, null, (PvmTransition) targetElement, variables, variablesLocal,
skipCustomListeners, skipIoMappings);
}
else if (PvmActivity.class.isAssignableFrom(targetElement.getClass())) {
ancestorScopeExecution.executeActivities(parentFlowScopes, (PvmActivity) targetElement, null, variables, variablesLocal,
skipCustomListeners, skipIoMappings);
}
else {
throw new ProcessEngineException("Cannot instantiate element " + targetElement);
}
}
protected void instantiateConcurrent(ExecutionEntity ancestorScopeExecution, List<PvmActivity> parentFlowScopes, CoreModelElement targetElement) {
if (PvmTransition.class.isAssignableFrom(targetElement.getClass())) {
ancestorScopeExecution.executeActivitiesConcurrent(parentFlowScopes, null, (PvmTransition) targetElement, variables,
variablesLocal, skipCustomListeners, skipIoMappings);
}
else if (PvmActivity.class.isAssignableFrom(targetElement.getClass())) {
ancestorScopeExecution.executeActivitiesConcurrent(parentFlowScopes, (PvmActivity) targetElement, null, variables, | variablesLocal, skipCustomListeners, skipIoMappings);
}
else {
throw new ProcessEngineException("Cannot instantiate element " + targetElement);
}
}
protected abstract ScopeImpl getTargetFlowScope(ProcessDefinitionImpl processDefinition);
protected abstract CoreModelElement getTargetElement(ProcessDefinitionImpl processDefinition);
protected abstract String getTargetElementId();
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\AbstractInstantiationCmd.java | 1 |
请完成以下Java代码 | protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_M_PromotionGroupLine[")
.append(get_ID()).append("]");
return sb.toString();
}
public I_M_Product getM_Product() throws RuntimeException
{
return (I_M_Product)MTable.get(getCtx(), I_M_Product.Table_Name)
.getPO(getM_Product_ID(), get_TrxName()); }
/** Set Product.
@param M_Product_ID
Product, Service, Item
*/
public void setM_Product_ID (int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID));
}
/** Get Product.
@return Product, Service, Item
*/
public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_M_PromotionGroup getM_PromotionGroup() throws RuntimeException
{
return (I_M_PromotionGroup)MTable.get(getCtx(), I_M_PromotionGroup.Table_Name)
.getPO(getM_PromotionGroup_ID(), get_TrxName()); }
/** Set Promotion Group.
@param M_PromotionGroup_ID Promotion Group */
public void setM_PromotionGroup_ID (int M_PromotionGroup_ID)
{
if (M_PromotionGroup_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_PromotionGroup_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_PromotionGroup_ID, Integer.valueOf(M_PromotionGroup_ID));
} | /** Get Promotion Group.
@return Promotion Group */
public int getM_PromotionGroup_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_PromotionGroup_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Promotion Group Line.
@param M_PromotionGroupLine_ID Promotion Group Line */
public void setM_PromotionGroupLine_ID (int M_PromotionGroupLine_ID)
{
if (M_PromotionGroupLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_PromotionGroupLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_PromotionGroupLine_ID, Integer.valueOf(M_PromotionGroupLine_ID));
}
/** Get Promotion Group Line.
@return Promotion Group Line */
public int getM_PromotionGroupLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_PromotionGroupLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_PromotionGroupLine.java | 1 |
请完成以下Java代码 | private static SessionFactory createSessionFactory() {
Map<String, Object> settings = new HashMap<>();
settings.put(URL, System.getenv("DB_URL"));
settings.put(DIALECT, "org.hibernate.dialect.PostgreSQLDialect");
settings.put(DEFAULT_SCHEMA, "shipping");
settings.put(DRIVER, "org.postgresql.Driver");
settings.put(USER, System.getenv("DB_USER"));
settings.put(PASS, System.getenv("DB_PASSWORD"));
settings.put("hibernate.hikari.connectionTimeout", "20000");
settings.put("hibernate.hikari.minimumIdle", "1");
settings.put("hibernate.hikari.maximumPoolSize", "2");
settings.put("hibernate.hikari.idleTimeout", "30000");
// commented out as we only need them on first use
// settings.put(HBM2DDL_AUTO, "create-only");
// settings.put(HBM2DDL_DATABASE_ACTION, "create");
StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
.applySettings(settings)
.build(); | return new MetadataSources(registry)
.addAnnotatedClass(Consignment.class)
.addAnnotatedClass(Item.class)
.addAnnotatedClass(Checkin.class)
.buildMetadata()
.buildSessionFactory();
}
private void flushConnectionPool() {
ConnectionProvider connectionProvider = sessionFactory.getSessionFactoryOptions()
.getServiceRegistry()
.getService(ConnectionProvider.class);
HikariDataSource hikariDataSource = connectionProvider.unwrap(HikariDataSource.class);
hikariDataSource.getHikariPoolMXBean().softEvictConnections();
}
} | repos\tutorials-master\aws-modules\aws-lambda-modules\shipping-tracker-lambda\ShippingFunction\src\main\java\com\baeldung\lambda\shipping\App.java | 1 |
请完成以下Java代码 | public void initialize(final ModelValidationEngine engine, final MClient client)
{
if (client != null)
{
m_AD_Client_ID = client.getAD_Client_ID();
}
final String tableName = getTableName();
if (isDocument())
{
engine.addDocValidate(tableName, this);
}
else
{
engine.addModelChange(tableName, this);
}
}
@Override
public int getAD_Client_ID()
{
return m_AD_Client_ID;
}
@Override
public String login(final int AD_Org_ID, final int AD_Role_ID, final int AD_User_ID)
{
return null; // nothing
}
@Override
public String modelChange(final PO po, final int type)
{
if (type == TYPE_AFTER_NEW || type == TYPE_AFTER_CHANGE)
{
if (isDocument())
{
if (!acceptDocument(po))
{
return null;
}
if (po.is_ValueChanged(IDocument.COLUMNNAME_DocStatus) && Services.get(IDocumentBL.class).isDocumentReversedOrVoided(po))
{
voidDocOutbound(po);
}
}
if (isJustProcessed(po, type))
{
createDocOutbound(po);
}
}
return null;
}
@Override
public String docValidate(@NonNull final PO po, final int timing)
{
Check.assume(isDocument(), "PO '{}' is a document", po);
if (!acceptDocument(po))
{
return null;
}
if (timing == ModelValidator.TIMING_AFTER_COMPLETE
&& !Services.get(IDocumentBL.class).isReversalDocument(po))
{
createDocOutbound(po);
}
if (timing == ModelValidator.TIMING_AFTER_VOID
|| timing == ModelValidator.TIMING_AFTER_REVERSEACCRUAL
|| timing == ModelValidator.TIMING_AFTER_REVERSECORRECT) | {
voidDocOutbound(po);
}
return null;
}
/**
* @return true if the given PO was just processed
*/
private boolean isJustProcessed(final PO po, final int changeType)
{
if (!po.isActive())
{
return false;
}
final boolean isNew = changeType == ModelValidator.TYPE_BEFORE_NEW || changeType == ModelValidator.TYPE_AFTER_NEW;
final int idxProcessed = po.get_ColumnIndex(DocOutboundProducerValidator.COLUMNNAME_Processed);
final boolean processedColumnAvailable = idxProcessed > 0;
final boolean processed = processedColumnAvailable ? po.get_ValueAsBoolean(idxProcessed) : true;
if (processedColumnAvailable)
{
if (isNew)
{
return processed;
}
else if (po.is_ValueChanged(idxProcessed))
{
return processed;
}
else
{
return false;
}
}
else
// Processed column is not available
{
// If is not available, we always consider the record as processed right after it was created
// This condition was introduced because we need to archive/print records which does not have such a column (e.g. letters)
return isNew;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java\de\metas\document\archive\interceptor\DocOutboundProducerValidator.java | 1 |
请完成以下Java代码 | public class MEntityType extends X_AD_EntityType
{
/**
*
*/
private static final long serialVersionUID = -2183955192373166750L;
public MEntityType(final Properties ctx, final int AD_EntityType_ID, final String trxName)
{
super(ctx, AD_EntityType_ID, trxName);
}
public MEntityType(final Properties ctx, final ResultSet rs, final String trxName)
{
super(ctx, rs, trxName);
}
@Override
protected boolean beforeSave(final boolean newRecord)
{
if (!newRecord)
{
if (is_ValueChanged(COLUMNNAME_EntityType))
{
throw new AdempiereException("You cannot modify EntityType");
} | }
CacheMgt.get().reset(I_AD_EntityType.Table_Name);
return true;
}
@Override
protected boolean beforeDelete()
{
if (EntityTypesCache.instance.isSystemMaintained(getEntityType())) // all pre-defined
{
throw new AdempiereException("You cannot delete a System maintained entity");
}
return true;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MEntityType.java | 1 |
请完成以下Java代码 | public Integer getStatus() {
return status.value();
}
@Schema(description = "Error message", example = "Authentication failed", accessMode = Schema.AccessMode.READ_ONLY)
public String getMessage() {
return message;
}
@Schema(description = "Platform error code:" +
"\n* `2` - General error (HTTP: 500 - Internal Server Error)" +
"\n\n* `10` - Authentication failed (HTTP: 401 - Unauthorized)" +
"\n\n* `11` - JWT token expired (HTTP: 401 - Unauthorized)" +
"\n\n* `15` - Credentials expired (HTTP: 401 - Unauthorized)" +
"\n\n* `20` - Permission denied (HTTP: 403 - Forbidden)" +
"\n\n* `30` - Invalid arguments (HTTP: 400 - Bad Request)" + | "\n\n* `31` - Bad request params (HTTP: 400 - Bad Request)" +
"\n\n* `32` - Item not found (HTTP: 404 - Not Found)" +
"\n\n* `33` - Too many requests (HTTP: 429 - Too Many Requests)" +
"\n\n* `34` - Too many updates (Too many updates over Websocket session)" +
"\n\n* `40` - Subscription violation (HTTP: 403 - Forbidden)" +
"\n\n* `41` - Entities limit exceeded (HTTP: 403 - Forbidden)",
example = "10", type = "integer",
accessMode = Schema.AccessMode.READ_ONLY)
public ThingsboardErrorCode getErrorCode() {
return errorCode;
}
@Schema(description = "Timestamp", accessMode = Schema.AccessMode.READ_ONLY)
public long getTimestamp() {
return timestamp;
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\exception\ThingsboardErrorResponse.java | 1 |
请完成以下Java代码 | public void setEntityType (final java.lang.String EntityType)
{
set_Value (COLUMNNAME_EntityType, EntityType);
}
@Override
public java.lang.String getEntityType()
{
return get_ValueAsString(COLUMNNAME_EntityType);
}
@Override
public void 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 |
请完成以下Java代码 | public static SealedObject encryptObject(String algorithm, Serializable object, SecretKey key,
GCMParameterSpec iv) throws NoSuchPaddingException, NoSuchAlgorithmException,
InvalidAlgorithmParameterException, InvalidKeyException, IOException, IllegalBlockSizeException {
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.ENCRYPT_MODE, key, iv);
SealedObject sealedObject = new SealedObject(object, cipher);
return sealedObject;
}
public static Serializable decryptObject(String algorithm, SealedObject sealedObject, SecretKey key,
GCMParameterSpec iv) throws NoSuchPaddingException, NoSuchAlgorithmException,
InvalidAlgorithmParameterException, InvalidKeyException, ClassNotFoundException,
BadPaddingException, IllegalBlockSizeException, IOException {
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.DECRYPT_MODE, key, iv);
Serializable unsealObject = (Serializable) sealedObject.getObject(cipher);
return unsealObject;
}
public static String encryptPasswordBased(String plainText, SecretKey key, GCMParameterSpec iv)
throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, | InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, key, iv);
return Base64.getEncoder()
.encodeToString(cipher.doFinal(plainText.getBytes()));
}
public static String decryptPasswordBased(String cipherText, SecretKey key, GCMParameterSpec iv)
throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException,
InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, key, iv);
return new String(cipher.doFinal(Base64.getDecoder()
.decode(cipherText)));
}
} | repos\tutorials-master\core-java-modules\core-java-security-algorithms\src\main\java\com\baeldung\aes\AESUtil.java | 1 |
请完成以下Java代码 | public List<I_M_ReceiptSchedule_Alloc> getReceiptScheduleAllocs()
{
return receiptScheduleAllocsRO;
}
private final void updateIfStale()
{
if (!_stale)
{
return;
}
final HUReceiptLinePartAttributes attributes = getAttributes();
//
// Qty & Quality
final Percent qualityDiscountPercent = Percent.of(attributes.getQualityDiscountPercent());
final ReceiptQty qtyAndQuality;
final Optional<Quantity> weight = attributes.getWeight();
if (weight.isPresent())
{
qtyAndQuality = ReceiptQty.newWithCatchWeight(productId, weight.get().getUomId());
final StockQtyAndUOMQty stockAndCatchQty = StockQtyAndUOMQtys.createConvert(_qty, productId, weight.get());
qtyAndQuality.addQtyAndQualityDiscountPercent(stockAndCatchQty, qualityDiscountPercent);
}
else
{
qtyAndQuality = ReceiptQty.newWithoutCatchWeight(productId);
qtyAndQuality.addQtyAndQualityDiscountPercent(_qty, qualityDiscountPercent);
}
I_M_QualityNote qualityNote = null;
//
// Quality Notice (only if we have a discount percentage)
if (qualityDiscountPercent.signum() != 0)
{
qualityNote = attributes.getQualityNote();
final String qualityNoticeDisplayName = attributes.getQualityNoticeDisplayName();
qtyAndQuality.addQualityNotices(QualityNoticesCollection.valueOfQualityNote(qualityNoticeDisplayName));
}
//
// Update values
if (_qualityNote == null)
{
// set the quality note only if it was not set before. Only the first one is needed
_qualityNote = qualityNote;
}
_qtyAndQuality = qtyAndQuality;
_subProducerBPartnerId = attributes.getSubProducer_BPartner_ID();
_attributeStorageAggregationKey = attributes.getAttributeStorageAggregationKey();
_stale = false; // not stale anymore
}
/**
* @return part attributes; never return null
*/ | // package level access for testing purposes
HUReceiptLinePartAttributes getAttributes()
{
return _attributes;
}
/**
* @return qty & quality; never returns null
*/
public final ReceiptQty getQtyAndQuality()
{
updateIfStale();
return _qtyAndQuality;
}
public int getSubProducer_BPartner_ID()
{
updateIfStale();
return _subProducerBPartnerId;
}
public Object getAttributeStorageAggregationKey()
{
updateIfStale();
return _attributeStorageAggregationKey;
}
/**
* Get the quality note linked with the part candidate
*
* @return
*/
public I_M_QualityNote getQualityNote()
{
return _qualityNote;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\inoutcandidate\spi\impl\HUReceiptLinePartCandidate.java | 1 |
请完成以下Java代码 | public static Service with(String name) {
return new Service(name);
}
private final String name;
/**
* Constructs a new {@link Service} initialized with a {@link String name}.
*
* @param name {@link String} containing the name of the {@link Service}.
* @throws IllegalArgumentException if the {@link String name} is {@literal null} or empty.
*/
Service(String name) {
Assert.hasText(name, String.format("Service name [%s] is required", name));
this.name = name; | }
/**
* Returns the {@link String name} of this {@link Service}.
*
* @return this {@link Service Service's} {@link String name}.
*/
public String getName() {
return this.name;
}
@Override
public String toString() {
return getName();
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\core\env\support\Service.java | 1 |
请完成以下Java代码 | public ActivityInstanceQueryImpl orderByActivityType() {
orderBy(ActivityInstanceQueryProperty.ACTIVITY_TYPE);
return this;
}
@Override
public ActivityInstanceQueryImpl orderByTenantId() {
orderBy(ActivityInstanceQueryProperty.TENANT_ID);
return this;
}
@Override
public ActivityInstanceQueryImpl activityInstanceId(String activityInstanceId) {
this.activityInstanceId = activityInstanceId;
return this;
}
// getters and setters
// //////////////////////////////////////////////////////
public String getProcessInstanceId() {
return processInstanceId;
}
public String getExecutionId() {
return executionId;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public String getActivityId() {
return activityId;
}
public String getActivityName() {
return activityName;
}
public String getActivityType() {
return activityType;
} | public String getAssignee() {
return assignee;
}
public String getCompletedBy() {
return completedBy;
}
public boolean isFinished() {
return finished;
}
public boolean isUnfinished() {
return unfinished;
}
public String getActivityInstanceId() {
return activityInstanceId;
}
public String getDeleteReason() {
return deleteReason;
}
public String getDeleteReasonLike() {
return deleteReasonLike;
}
public List<List<String>> getSafeProcessInstanceIds() {
return safeProcessInstanceIds;
}
public void setSafeProcessInstanceIds(List<List<String>> safeProcessInstanceIds) {
this.safeProcessInstanceIds = safeProcessInstanceIds;
}
public Collection<String> getProcessInstanceIds() {
return processInstanceIds;
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\ActivityInstanceQueryImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getReplacement() {
return this.replacement;
}
public void setReplacement(String replacement) {
this.replacement = replacement;
}
public String getSince() {
return this.since;
}
public void setSince(String since) {
this.since = since;
}
public String getLevel() {
return this.level;
}
public void setLevel(String level) {
this.level = level;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ItemDeprecation other = (ItemDeprecation) o;
return nullSafeEquals(this.reason, other.reason) && nullSafeEquals(this.replacement, other.replacement)
&& nullSafeEquals(this.level, other.level) && nullSafeEquals(this.since, other.since);
} | @Override
public int hashCode() {
int result = nullSafeHashCode(this.reason);
result = 31 * result + nullSafeHashCode(this.replacement);
result = 31 * result + nullSafeHashCode(this.level);
result = 31 * result + nullSafeHashCode(this.since);
return result;
}
@Override
public String toString() {
return "ItemDeprecation{reason='" + this.reason + '\'' + ", replacement='" + this.replacement + '\''
+ ", level='" + this.level + '\'' + ", since='" + this.since + '\'' + '}';
}
private boolean nullSafeEquals(Object o1, Object o2) {
if (o1 == o2) {
return true;
}
if (o1 == null || o2 == null) {
return false;
}
return o1.equals(o2);
}
private int nullSafeHashCode(Object o) {
return (o != null) ? o.hashCode() : 0;
}
} | repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-processor\src\main\java\org\springframework\boot\configurationprocessor\metadata\ItemDeprecation.java | 2 |
请完成以下Java代码 | public class InvalidConfigurationPropertyValueException extends RuntimeException {
private final String name;
private final @Nullable Object value;
private final @Nullable String reason;
/**
* Creates a new instance for the specified property {@code name} and {@code value},
* including a {@code reason} why the value is invalid.
* @param name the name of the property in canonical format
* @param value the value of the property, can be {@code null}
* @param reason a human-readable text that describes why the reason is invalid.
* Starts with an upper-case and ends with a dot. Several sentences and carriage
* returns are allowed.
*/
public InvalidConfigurationPropertyValueException(String name, @Nullable Object value, @Nullable String reason) {
this(name, value, reason, null);
}
InvalidConfigurationPropertyValueException(String name, @Nullable Object value, @Nullable String reason,
@Nullable Throwable cause) {
super("Property " + name + " with value '" + value + "' is invalid: " + reason, cause);
Assert.notNull(name, "'name' must not be null");
this.name = name;
this.value = value;
this.reason = reason;
}
/**
* Return the name of the property.
* @return the property name
*/
public String getName() {
return this.name;
} | /**
* Return the invalid value, can be {@code null}.
* @return the invalid value
*/
public @Nullable Object getValue() {
return this.value;
}
/**
* Return the reason why the value is invalid.
* @return the reason
*/
public @Nullable String getReason() {
return this.reason;
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\properties\source\InvalidConfigurationPropertyValueException.java | 1 |
请完成以下Java代码 | public class X_AD_Printer_Tray extends org.compiere.model.PO implements I_AD_Printer_Tray, org.compiere.model.I_Persistent
{
private static final long serialVersionUID = -593882204L;
/** Standard Constructor */
public X_AD_Printer_Tray (Properties ctx, int AD_Printer_Tray_ID, String trxName)
{
super (ctx, AD_Printer_Tray_ID, trxName);
}
/** Load Constructor */
public X_AD_Printer_Tray (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO(Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setAD_Printer_ID (int AD_Printer_ID)
{
if (AD_Printer_ID < 1)
set_Value (COLUMNNAME_AD_Printer_ID, null);
else
set_Value (COLUMNNAME_AD_Printer_ID, Integer.valueOf(AD_Printer_ID));
}
@Override
public int getAD_Printer_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Printer_ID);
}
@Override
public void setAD_Printer_Tray_ID (int AD_Printer_Tray_ID)
{
if (AD_Printer_Tray_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Printer_Tray_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Printer_Tray_ID, Integer.valueOf(AD_Printer_Tray_ID));
} | @Override
public int getAD_Printer_Tray_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Printer_Tray_ID);
}
@Override
public void setDescription (java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return (java.lang.String)get_Value(COLUMNNAME_Description);
}
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_AD_Printer_Tray.java | 1 |
请完成以下Java代码 | public final void create(final T entity) {
Preconditions.checkNotNull(entity);
// getCurrentSession().persist(entity);
getCurrentSession().saveOrUpdate(entity);
}
@Override
public final T update(final T entity) {
Preconditions.checkNotNull(entity);
return (T) getCurrentSession().merge(entity);
}
@Override
public final void delete(final T entity) {
Preconditions.checkNotNull(entity); | getCurrentSession().delete(entity);
}
@Override
public final void deleteById(final long entityId) {
final T entity = findOne(entityId);
Preconditions.checkState(entity != null);
delete(entity);
}
protected final Session getCurrentSession() {
return sessionFactory.getCurrentSession();
}
} | repos\tutorials-master\spring-exceptions\src\main\java\com\baeldung\persistence\common\AbstractHibernateDao.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class RequestParticipant
{
/** two-letter ISO-3166 */
String country;
String zip;
@JsonFormat(shape = Shape.STRING, pattern = TIME_FORMAT)
LocalTime timeFrom;
@JsonFormat(shape = Shape.STRING, pattern = TIME_FORMAT)
LocalTime timeTo;
String desiredStation;
@Builder | @JsonCreator
public RequestParticipant(
@JsonProperty("country") final String country,
@JsonProperty("zip") final String zip,
@JsonProperty("timeFrom") final LocalTime timeFrom,
@JsonProperty("timeTo") final LocalTime timeTo,
@JsonProperty("desiredStation") final String desiredStation)
{
this.country = Check.assumeNotEmpty(country, "Parameter country may not be empty");
this.zip = Check.assumeNotEmpty(zip, "Parameter zip may not be empty");
this.timeFrom = timeFrom;
this.timeTo = timeTo;
this.desiredStation = desiredStation;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.derkurier\src\main\java\de\metas\shipper\gateway\derkurier\restapi\models\RequestParticipant.java | 2 |
请完成以下Java代码 | public void onFailure(@NonNull Throwable t) {
ctx.tellFailure(msg, t);
}
};
Futures.addCallback(future, futureCallback, ctx.getDbCallbackExecutor());
} else {
List<ListenableFuture<Void>> futures = new ArrayList<>();
PageDataIterableByTenantIdEntityId<EdgeId> edgeIds = new PageDataIterableByTenantIdEntityId<>(
ctx.getEdgeService()::findRelatedEdgeIdsByEntityId, ctx.getTenantId(), msg.getOriginator(), RELATED_EDGES_CACHE_ITEMS);
for (EdgeId edgeId : edgeIds) {
EdgeEvent edgeEvent = buildEvent(msg, ctx);
futures.add(notifyEdge(ctx, edgeEvent, edgeId));
}
if (futures.isEmpty()) {
// ack in case no edges are related to provided entity
ctx.ack(msg);
} else {
Futures.addCallback(Futures.allAsList(futures), new FutureCallback<>() {
@Override
public void onSuccess(@Nullable List<Void> voids) {
ctx.tellSuccess(msg);
} | @Override
public void onFailure(Throwable t) {
ctx.tellFailure(msg, t);
}
}, ctx.getDbCallbackExecutor());
}
}
} catch (Exception e) {
log.error("Failed to build edge event", e);
ctx.tellFailure(msg, e);
}
}
private ListenableFuture<Void> notifyEdge(TbContext ctx, EdgeEvent edgeEvent, EdgeId edgeId) {
edgeEvent.setEdgeId(edgeId);
return ctx.getEdgeEventService().saveAsync(edgeEvent);
}
} | repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\edge\TbMsgPushToEdgeNode.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public final void persistState(CalculatedFieldEntityCtxId stateId, CalculatedFieldState state, TbCallback callback) {
if (state.isSizeExceedsLimit()) {
throw new CalculatedFieldStateException("State size exceeds the maximum allowed limit. The state will not be persisted to RocksDB.");
}
doPersist(stateId, toProto(stateId, state), callback);
}
protected abstract void doPersist(CalculatedFieldEntityCtxId stateId, CalculatedFieldStateProto stateMsgProto, TbCallback callback);
@Override
public final void deleteState(CalculatedFieldEntityCtxId stateId, TbCallback callback) {
doRemove(stateId, callback);
}
protected abstract void doRemove(CalculatedFieldEntityCtxId stateId, TbCallback callback);
protected void processRestoredState(CalculatedFieldStateProto stateMsg, TopicPartitionInfo partition, TbCallback callback) {
var id = fromProto(stateMsg.getId());
if (partition == null) {
try {
partition = actorSystemContext.resolve(ServiceType.TB_RULE_ENGINE, DataConstants.CF_QUEUE_NAME, id.tenantId(), id.entityId());
} catch (TenantNotFoundException e) {
log.debug("Skipping CF state msg for non-existing tenant {}", id.tenantId());
return;
}
}
var state = fromProto(id, stateMsg);
processRestoredState(id, state, partition, callback);
}
protected void processRestoredState(CalculatedFieldEntityCtxId id, CalculatedFieldState state, TopicPartitionInfo partition, TbCallback callback) {
partition = partition.withTopic(DataConstants.CF_STATES_QUEUE_NAME);
actorSystemContext.tellWithHighPriority(new CalculatedFieldStateRestoreMsg(id, state, partition, callback));
}
@Override
public void restore(QueueKey queueKey, Set<TopicPartitionInfo> partitions) {
stateService.update(queueKey, partitions, new QueueStateService.RestoreCallback() {
@Override
public void onAllPartitionsRestored() { | }
@Override
public void onPartitionRestored(TopicPartitionInfo partition) {
partition = partition.withTopic(DataConstants.CF_STATES_QUEUE_NAME);
actorSystemContext.tellWithHighPriority(new CalculatedFieldStatePartitionRestoreMsg(partition));
}
});
}
@Override
public void delete(Set<TopicPartitionInfo> partitions) {
stateService.delete(partitions);
}
@Override
public Set<TopicPartitionInfo> getPartitions() {
return stateService.getPartitions().values().stream().flatMap(Collection::stream).collect(Collectors.toSet());
}
@Override
public void stop() {
stateService.stop();
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\cf\AbstractCalculatedFieldStateService.java | 2 |
请完成以下Java代码 | public void setRolePrefix(String rolePrefix) {
this.rolePrefix = rolePrefix;
}
@Override
public boolean supports(ConfigAttribute attribute) {
return (attribute.getAttribute() != null) && attribute.getAttribute().startsWith(getRolePrefix());
}
/**
* This implementation supports any type of class, because it does not query the
* presented secure object.
* @param clazz the secure object
* @return always <code>true</code>
*/
@Override
public boolean supports(Class<?> clazz) {
return true;
}
@Override
public int vote(Authentication authentication, Object object, Collection<ConfigAttribute> attributes) {
if (authentication == null) {
return ACCESS_DENIED;
}
int result = ACCESS_ABSTAIN;
Collection<? extends GrantedAuthority> authorities = extractAuthorities(authentication);
for (ConfigAttribute attribute : attributes) { | if (this.supports(attribute)) {
result = ACCESS_DENIED;
// Attempt to find a matching granted authority
for (GrantedAuthority authority : authorities) {
if (attribute.getAttribute().equals(authority.getAuthority())) {
return ACCESS_GRANTED;
}
}
}
}
return result;
}
Collection<? extends GrantedAuthority> extractAuthorities(Authentication authentication) {
return authentication.getAuthorities();
}
} | repos\spring-security-main\access\src\main\java\org\springframework\security\access\vote\RoleVoter.java | 1 |
请完成以下Java代码 | public static Document columnToJson(List<CanalEntry.Column> columns) {
Document obj = new Document();
for (CanalEntry.Column column : columns) {
Object value = dataTypeConvert(column.getMysqlType(), column.getValue());
obj.put(column.getName(), value);
}
return obj;
}
/**
* 数据类型转换
*
* @param mysqlType
* @param value
* @return
*/
private static Object dataTypeConvert(String mysqlType, String value) {
try {
if (mysqlType.startsWith("int") || mysqlType.startsWith("tinyint") || mysqlType.startsWith("smallint") || mysqlType.startsWith("mediumint")) {
//int(32)
return StringUtils.isBlank(value) ? null : Integer.parseInt(value);
} else if (mysqlType.startsWith("bigint")) {
//int(64)
return StringUtils.isBlank(value) ? null : Long.parseLong(value);
} else if (mysqlType.startsWith("float") || mysqlType.startsWith("double")) {
return StringUtils.isBlank(value) ? null : Double.parseDouble(value);
} else if (mysqlType.startsWith("decimal")) {
//小数精度为0时转换成long类型,否则转换为double类型
int lenBegin = mysqlType.indexOf('(');
int lenCenter = mysqlType.indexOf(',');
int lenEnd = mysqlType.indexOf(')');
if (lenBegin > 0 && lenEnd > 0 && lenCenter > 0) { | int length = Integer.parseInt(mysqlType.substring(lenCenter + 1, lenEnd));
if (length == 0) {
return StringUtils.isBlank(value) ? null : Long.parseLong(value);
}
}
return StringUtils.isBlank(value) ? null : Double.parseDouble(value);
} else if (mysqlType.startsWith("datetime") || mysqlType.startsWith("timestamp")) {
return StringUtils.isBlank(value) ? null : DATE_TIME_FORMAT.parse(value);
} else if (mysqlType.equals("date")) {
return StringUtils.isBlank(value) ? null : DATE_FORMAT.parse(value);
} else if (mysqlType.startsWith("varchar")) {
//设置默认空串
return value == null ? "" : value;
} else {
logger.error("unknown data type :[{}]-[{}]", mysqlType, value);
}
} catch (Exception e) {
logger.error("data type convert error ", e);
}
return value;
}
} | repos\spring-boot-leaning-master\2.x_data\3-3 使用 canal 将业务数据从 Mysql 同步到 MongoDB\spring-boot-canal-mongodb\src\main\java\com\neo\util\DBConvertUtil.java | 1 |
请完成以下Java代码 | public Timestamp getNextInspectionDate()
{
return nextInspectionDate;
}
public int getDLM_Partition_ID()
{
return DLM_Partition_ID;
}
public boolean isAborted()
{
return aborted;
}
@Override
public String toString()
{
return "Partition [DLM_Partition_ID=" + DLM_Partition_ID + ", records.size()=" + records.size() + ", recordsChanged=" + recordsChanged + ", configChanged=" + configChanged + ", targetDLMLevel=" + targetDLMLevel + ", currentDLMLevel=" + currentDLMLevel + ", nextInspectionDate=" + nextInspectionDate + "]";
}
public static class WorkQueue
{
public static WorkQueue of(final I_DLM_Partition_Workqueue workqueueDB)
{
final ITableRecordReference tableRecordRef = TableRecordReference.ofReferencedOrNull(workqueueDB);
final WorkQueue result = new WorkQueue(tableRecordRef);
result.setDLM_Partition_Workqueue_ID(workqueueDB.getDLM_Partition_Workqueue_ID());
return result;
}
public static WorkQueue of(final ITableRecordReference tableRecordRef)
{
return new WorkQueue(tableRecordRef);
}
private final ITableRecordReference tableRecordReference;
private int dlmPartitionWorkqueueId;
private WorkQueue(final ITableRecordReference tableRecordReference)
{
this.tableRecordReference = tableRecordReference;
} | public ITableRecordReference getTableRecordReference()
{
return tableRecordReference;
}
public int getDLM_Partition_Workqueue_ID()
{
return dlmPartitionWorkqueueId;
}
public void setDLM_Partition_Workqueue_ID(final int dlm_Partition_Workqueue_ID)
{
dlmPartitionWorkqueueId = dlm_Partition_Workqueue_ID;
}
@Override
public String toString()
{
return "Partition.WorkQueue [DLM_Partition_Workqueue_ID=" + dlmPartitionWorkqueueId + ", tableRecordReference=" + tableRecordReference + "]";
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\Partition.java | 1 |
请完成以下Java代码 | public FactLineBuilder description(@Nullable final String description)
{
assertNotBuild();
this.description = StringUtils.trimBlankToOptional(description);
return this;
}
public FactLineBuilder additionalDescription(@Nullable final String additionalDescription)
{
assertNotBuild();
this.additionalDescription = StringUtils.trimBlankToNull(additionalDescription);
return this;
}
public FactLineBuilder openItemKey(@Nullable FAOpenItemTrxInfo openItemTrxInfo)
{
assertNotBuild();
this.openItemTrxInfo = openItemTrxInfo;
return this;
}
public FactLineBuilder productId(@Nullable ProductId productId)
{
assertNotBuild(); | this.productId = Optional.ofNullable(productId);
return this;
}
public FactLineBuilder userElementString1(@Nullable final String userElementString1)
{
assertNotBuild();
this.userElementString1 = StringUtils.trimBlankToOptional(userElementString1);
return this;
}
public FactLineBuilder salesOrderId(@Nullable final OrderId salesOrderId)
{
assertNotBuild();
this.salesOrderId = Optional.ofNullable(salesOrderId);
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\FactLineBuilder.java | 1 |
请完成以下Java代码 | public TokenQuery orderByTokenId() {
return orderBy(TokenQueryProperty.TOKEN_ID);
}
@Override
public TokenQuery orderByTokenDate() {
return orderBy(TokenQueryProperty.TOKEN_DATE);
}
// results //////////////////////////////////////////////////////////
@Override
public long executeCount(CommandContext commandContext) {
return CommandContextUtil.getTokenEntityManager(commandContext).findTokenCountByQueryCriteria(this);
}
@Override
public List<Token> executeList(CommandContext commandContext) {
return CommandContextUtil.getTokenEntityManager(commandContext).findTokenByQueryCriteria(this);
}
// getters //////////////////////////////////////////////////////////
@Override
public String getId() {
return id;
}
public List<String> getIds() {
return ids;
}
public String getTokenValue() {
return tokenValue;
}
public Date getTokenDate() {
return tokenDate;
}
public Date getTokenDateBefore() {
return tokenDateBefore;
}
public Date getTokenDateAfter() {
return tokenDateAfter;
} | public String getIpAddress() {
return ipAddress;
}
public String getIpAddressLike() {
return ipAddressLike;
}
public String getUserAgent() {
return userAgent;
}
public String getUserAgentLike() {
return userAgentLike;
}
public String getUserId() {
return userId;
}
public String getUserIdLike() {
return userIdLike;
}
public String getTokenData() {
return tokenData;
}
public String getTokenDataLike() {
return tokenDataLike;
}
} | repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\impl\TokenQueryImpl.java | 1 |
请完成以下Java代码 | public List<Job> executeList(CommandContext commandContext, Page page) {
checkQueryOk();
return commandContext.getDeadLetterJobEntityManager().findJobsByQueryCriteria(this, page);
}
// getters //////////////////////////////////////////
public String getProcessInstanceId() {
return processInstanceId;
}
public String getExecutionId() {
return executionId;
}
public boolean getExecutable() {
return executable;
}
public Date getNow() {
return Context.getProcessEngineConfiguration().getClock().getCurrentTime();
}
public boolean isWithException() {
return withException;
}
public String getExceptionMessage() {
return exceptionMessage;
}
public String getTenantId() {
return tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
public static long getSerialversionuid() {
return serialVersionUID;
} | public String getId() {
return id;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public boolean isOnlyTimers() {
return onlyTimers;
}
public boolean isOnlyMessages() {
return onlyMessages;
}
public Date getDuedateHigherThan() {
return duedateHigherThan;
}
public Date getDuedateLowerThan() {
return duedateLowerThan;
}
public Date getDuedateHigherThanOrEqual() {
return duedateHigherThanOrEqual;
}
public Date getDuedateLowerThanOrEqual() {
return duedateLowerThanOrEqual;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\DeadLetterJobQueryImpl.java | 1 |
请完成以下Java代码 | public class Polynom {
private double a;
private double b;
private double c;
public Polynom(double a, double b, double c) {
if (a == 0) {
throw new IllegalArgumentException("a can not be equal to 0");
}
this.a = a;
this.b = b;
this.c = c;
}
public double getA() { | return a;
}
public double getB() {
return b;
}
public double getC() {
return c;
}
public double getDiscriminant() {
return b * b - 4 * a * c;
}
} | repos\tutorials-master\core-java-modules\core-java-lang-math-3\src\main\java\com\baeldung\math\quadraticequationroot\Polynom.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public CommonResult updateBrand(@PathVariable("id") Long id, @Validated @RequestBody PmsBrandDto pmsBrandDto) {
CommonResult commonResult;
int count = demoService.updateBrand(id, pmsBrandDto);
if (count == 1) {
commonResult = CommonResult.success(pmsBrandDto);
LOGGER.debug("updateBrand success:{}", pmsBrandDto);
} else {
commonResult = CommonResult.failed("操作失败");
LOGGER.debug("updateBrand failed:{}", pmsBrandDto);
}
return commonResult;
}
@ApiOperation(value = "删除品牌")
@RequestMapping(value = "/brand/delete/{id}", method = RequestMethod.GET)
@ResponseBody
public CommonResult deleteBrand(@PathVariable("id") Long id) {
int count = demoService.deleteBrand(id);
if (count == 1) {
LOGGER.debug("deleteBrand success :id={}", id);
return CommonResult.success(null); | } else {
LOGGER.debug("deleteBrand failed :id={}", id);
return CommonResult.failed("操作失败");
}
}
@ApiOperation(value = "分页获取品牌列表")
@RequestMapping(value = "/brand/list", method = RequestMethod.GET)
@ResponseBody
public CommonResult<CommonPage<PmsBrand>> listBrand(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
@RequestParam(value = "pageSize", defaultValue = "3") Integer pageSize) {
List<PmsBrand> brandList = demoService.listBrand(pageNum, pageSize);
return CommonResult.success(CommonPage.restPage(brandList));
}
@ApiOperation(value = "根据编号查询品牌信息")
@RequestMapping(value = "/brand/{id}", method = RequestMethod.GET)
@ResponseBody
public CommonResult<PmsBrand> brand(@PathVariable("id") Long id) {
return CommonResult.success(demoService.getBrand(id));
}
} | repos\mall-master\mall-demo\src\main\java\com\macro\mall\demo\controller\DemoController.java | 2 |
请完成以下Java代码 | public class RecieverMDB implements MessageListener {
@Resource
private ConnectionFactory connectionFactory;
@Resource(name = "ackQueue")
private Queue ackQueue;
public void onMessage(Message message) {
try {
TextMessage textMessage = (TextMessage) message;
String producerPing = textMessage.getText();
if (producerPing.equals("marco")) {
acknowledge("polo");
}
} catch (JMSException e) {
throw new IllegalStateException(e);
}
}
private void acknowledge(String text) throws JMSException { | Connection connection = null;
Session session = null;
try {
connection = connectionFactory.createConnection();
connection.start();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer ackSender = session.createProducer(ackQueue);
ackSender.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
TextMessage message = session.createTextMessage(text);
ackSender.send(message);
} finally {
session.close();
connection.close();
}
}
} | repos\tutorials-master\spring-ejb-modules\ejb-beans\src\main\java\com\baeldung\ejbspringcomparison\ejb\messagedriven\RecieverMDB.java | 1 |
请完成以下Java代码 | public LoginDto pass(String pass) {
this.pass = pass;
return this;
}
/**
* Get pass
* @return pass
*/
@Schema(name = "pass", required = true)
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
LoginDto login = (LoginDto) o;
return Objects.equals(this.user, login.user) && Objects.equals(this.pass, login.pass);
}
@Override
public int hashCode() {
return Objects.hash(user, pass);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class LoginDto {\n"); | sb.append(" user: ")
.append(toIndentedString(user))
.append("\n");
sb.append(" pass: ")
.append(toIndentedString(pass))
.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(Object o) {
if (o == null) {
return "null";
}
return o.toString()
.replace("\n", "\n ");
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-springdoc-2\src\main\java\com\baeldung\defaultglobalsecurityscheme\dto\LoginDto.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public List<BusinessEntityType> getAdditionalBusinessPartner() {
if (additionalBusinessPartner == null) {
additionalBusinessPartner = new ArrayList<BusinessEntityType>();
}
return this.additionalBusinessPartner;
}
/**
* Arbitrary free text, which is sent with the forecast - e.g., "Factory closed due to holidays between 20.06. and 01.07."
*
* @return
* possible object is
* {@link FreeTextType }
*
*/
public FreeTextType getFreeText() {
return freeText;
}
/**
* Sets the value of the freeText property.
*
* @param value
* allowed object is
* {@link FreeTextType }
*
*/
public void setFreeText(FreeTextType value) {
this.freeText = value;
}
/**
* Additional duration information for MaterialAuthorization (.../ForecastListLineItem/AdditionalForecastInformation/MaterialAuthorization) coded in ISO 8601/durations format.
*
* @return
* possible object is
* {@link Duration }
*
*/
public Duration getMaterialAuthorizationDuration() {
return materialAuthorizationDuration;
}
/**
* Sets the value of the materialAuthorizationDuration property.
*
* @param value | * allowed object is
* {@link Duration }
*
*/
public void setMaterialAuthorizationDuration(Duration value) {
this.materialAuthorizationDuration = value;
}
/**
* Additional duration information for ProductionAuthorization (.../ForecastListLineItem/AdditionalForecastInformation/ProductionAuthorization) coded in ISO 8601/durations format.
*
* @return
* possible object is
* {@link Duration }
*
*/
public Duration getProductionAuthorizationDuration() {
return productionAuthorizationDuration;
}
/**
* Sets the value of the productionAuthorizationDuration property.
*
* @param value
* allowed object is
* {@link Duration }
*
*/
public void setProductionAuthorizationDuration(Duration value) {
this.productionAuthorizationDuration = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\ForecastListLineItemExtensionType.java | 2 |
请完成以下Java代码 | public class DeptDto extends BaseDTO implements Serializable {
@ApiModelProperty(value = "ID")
private Long id;
@ApiModelProperty(value = "名称")
private String name;
@ApiModelProperty(value = "是否启用")
private Boolean enabled;
@ApiModelProperty(value = "排序")
private Integer deptSort;
@ApiModelProperty(value = "子部门")
private List<DeptDto> children;
@ApiModelProperty(value = "上级部门")
private Long pid;
@ApiModelProperty(value = "子部门数量", hidden = true)
private Integer subCount;
@ApiModelProperty(value = "是否有子节点")
public Boolean getHasChildren() {
return subCount > 0;
}
@ApiModelProperty(value = "是否为叶子")
public Boolean getLeaf() {
return subCount <= 0;
}
@ApiModelProperty(value = "部门全名")
public String getLabel() {
return name; | }
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DeptDto deptDto = (DeptDto) o;
return Objects.equals(id, deptDto.id) &&
Objects.equals(name, deptDto.name);
}
@Override
public int hashCode() {
return Objects.hash(id, name);
}
} | repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\system\service\dto\DeptDto.java | 1 |
请完成以下Java代码 | public static Optional<EMailAddress> optionalOfNullable(@Nullable final String emailStr)
{
return Optional.ofNullable(ofNullableString(emailStr));
}
@JsonCreator
public static EMailAddress ofString(@NonNull final String emailStr)
{
return new EMailAddress(emailStr);
}
public static List<EMailAddress> ofSemicolonSeparatedList(@Nullable final String emailsListStr)
{
if (emailsListStr == null || Check.isBlank(emailsListStr))
{
return ImmutableList.of();
}
return Splitter.on(";")
.trimResults()
.omitEmptyStrings()
.splitToList(emailsListStr)
.stream()
.map(EMailAddress::ofNullableString)
.filter(Objects::nonNull)
.collect(ImmutableList.toImmutableList());
}
@Nullable
public static ITranslatableString checkEMailValid(@Nullable final EMailAddress email)
{
if (email == null)
{
return TranslatableStrings.constant("no email");
}
return checkEMailValid(email.getAsString());
}
@Nullable
public static ITranslatableString checkEMailValid(@Nullable final String email)
{
if (email == null || Check.isBlank(email))
{
return TranslatableStrings.constant("no email");
}
try
{
final InternetAddress ia = new InternetAddress(email, true);
ia.validate(); // throws AddressException
if (ia.getAddress() == null)
{
return TranslatableStrings.constant("invalid email");
}
return null; // OK
}
catch (final AddressException ex)
{
logger.warn("Invalid email address: {}", email, ex); | return TranslatableStrings.constant(ex.getLocalizedMessage());
}
}
private static final Logger logger = LogManager.getLogger(EMailAddress.class);
private final String emailStr;
private EMailAddress(@NonNull final String emailStr)
{
this.emailStr = emailStr.trim();
if (this.emailStr.isEmpty())
{
throw new AdempiereException("Empty email address is not valid");
}
}
@JsonValue
public String getAsString()
{
return emailStr;
}
@Nullable
public static String toStringOrNull(@Nullable final EMailAddress emailAddress)
{
return emailAddress != null ? emailAddress.getAsString() : null;
}
@Deprecated
@Override
public String toString()
{
return getAsString();
}
public InternetAddress toInternetAddress() throws AddressException
{
return new InternetAddress(emailStr, true);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\email\EMailAddress.java | 1 |
请完成以下Java代码 | public void onParameterChanged(final String parameterName)
{
if (I_M_Shipper.COLUMNNAME_M_Shipper_ID.equals(parameterName))
{
shipperTransportationId = getNextTransportationOrderId();
}
}
private int getNextTransportationOrderId()
{
final ShipperId shipperId = ShipperId.ofRepoId(shipperRecordId);
final ShipperTransportationId nextShipperTransportationForShipper = shipperTransportationRepo.retrieveNextOpenShipperTransportationIdOrNull(shipperId, null);
return nextShipperTransportationForShipper == null ? -1 : nextShipperTransportationForShipper.getRepoId();
}
@Override
protected String doIt()
{
if (!isPartialDeliveryAllowed())
{
if (!getView().isApproved())
{
throw new AdempiereException("Not all rows were approved");
}
}
final ImmutableSet<PickingCandidateId> validPickingCandidates = getValidPickingCandidates();
if (!validPickingCandidates.isEmpty())
{
deliverAndInvoice(validPickingCandidates);
}
return MSG_OK;
}
private ImmutableSet<PickingCandidateId> getValidPickingCandidates()
{
return getRowsNotAlreadyProcessed()
.stream()
.filter(ProductsToPickRow::isEligibleForProcessing)
.map(ProductsToPickRow::getPickingCandidateId)
.filter(Objects::nonNull)
.collect(ImmutableSet.toImmutableSet());
}
private void deliverAndInvoice(final ImmutableSet<PickingCandidateId> validPickingCandidates)
{
final List<PickingCandidate> pickingCandidates = processAllPickingCandidates(validPickingCandidates);
final Set<HuId> huIdsToDeliver = pickingCandidates
.stream() | .filter(PickingCandidate::isPacked)
.map(PickingCandidate::getPackedToHuId)
.collect(ImmutableSet.toImmutableSet());
final List<I_M_HU> husToDeliver = handlingUnitsRepo.getByIds(huIdsToDeliver);
HUShippingFacade.builder()
.hus(husToDeliver)
.addToShipperTransportationId(shipperTransportationId)
.completeShipments(true)
.failIfNoShipmentCandidatesFound(true)
.invoiceMode(BillAssociatedInvoiceCandidates.IF_INVOICE_SCHEDULE_PERMITS)
.createShipperDeliveryOrders(true)
.build()
.generateShippingDocuments();
}
private List<ProductsToPickRow> getRowsNotAlreadyProcessed()
{
return streamAllRows()
.filter(row -> !row.isProcessed())
.collect(ImmutableList.toImmutableList());
}
private boolean isPartialDeliveryAllowed()
{
return sysConfigBL.getBooleanValue(SYSCONFIG_AllowPartialDelivery, false);
}
private ImmutableList<PickingCandidate> processAllPickingCandidates(final ImmutableSet<PickingCandidateId> pickingCandidateIdsToProcess)
{
return trxManager.callInNewTrx(() -> pickingCandidatesService
.process(pickingCandidateIdsToProcess)
.getPickingCandidates());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingV2\productsToPick\process\ProductsToPick_4EyesReview_ProcessAll.java | 1 |
请完成以下Java代码 | public final void setService(final String service) {
this.service = service;
}
public final String getArtifactParameter() {
return this.artifactParameter;
}
/**
* Configures the Request Parameter to look for when attempting to see if a CAS ticket
* was sent from the server.
* @param artifactParameter the id to use. Default is "ticket".
*/
public final void setArtifactParameter(final String artifactParameter) {
this.artifactParameter = artifactParameter;
}
/**
* Configures the Request parameter to look for when attempting to send a request to
* CAS.
* @return the service parameter to use. Default is "service".
*/
public final String getServiceParameter() {
return this.serviceParameter; | }
public final void setServiceParameter(final String serviceParameter) {
this.serviceParameter = serviceParameter;
}
public final boolean isAuthenticateAllArtifacts() {
return this.authenticateAllArtifacts;
}
/**
* If true, then any non-null artifact (ticket) should be authenticated. Additionally,
* the service will be determined dynamically in order to ensure the service matches
* the expected value for this artifact.
* @param authenticateAllArtifacts
*/
public final void setAuthenticateAllArtifacts(final boolean authenticateAllArtifacts) {
this.authenticateAllArtifacts = authenticateAllArtifacts;
}
} | repos\spring-security-main\cas\src\main\java\org\springframework\security\cas\ServiceProperties.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public static String mkOwnOrderNumber(final String documentNo)
{
final String sevenDigitString = documentNo.length() <= 7 ? documentNo : documentNo.substring(documentNo.length() - 7);
return "006" + lpadZero(sevenDigitString, 7);
}
/**
* Remove trailing zeros after decimal separator
*
* @return <code>bd</code> without trailing zeros after separator; if argument is NULL then NULL will be retu
*/
// NOTE: this is copy-paste of de.metas.util.NumberUtils.stripTrailingDecimalZeros(BigDecimal)
public static BigDecimal stripTrailingDecimalZeros(final BigDecimal bd)
{
if (bd == null)
{
return null;
}
//
// Remove all trailing zeros
BigDecimal result = bd.stripTrailingZeros();
// Fix very weird java 6 bug: stripTrailingZeros doesn't work on 0 itself | // http://stackoverflow.com/questions/5239137/clarification-on-behavior-of-bigdecimal-striptrailingzeroes
if (result.signum() == 0)
{
result = BigDecimal.ZERO;
}
//
// If after removing our scale is negative, we can safely set the scale to ZERO because we don't want to get rid of zeros before decimal point
if (result.scale() < 0)
{
result = result.setScale(0, RoundingMode.UNNECESSARY);
}
return result;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\commons\Util.java | 2 |
请完成以下Java代码 | public SetJobRetriesByProcessAsyncBuilder processInstanceIds(List<String> processInstanceIds) {
this.processInstanceIds = processInstanceIds;
return this;
}
@Override
public SetJobRetriesByProcessAsyncBuilder processInstanceQuery(ProcessInstanceQuery query) {
this.processInstanceQuery = query;
return this;
}
@Override
public SetJobRetriesByProcessAsyncBuilder historicProcessInstanceQuery(HistoricProcessInstanceQuery query) {
this.historicProcessInstanceQuery = query;
return this;
}
@Override
public SetJobRetriesByProcessAsyncBuilder dueDate(Date dueDate) {
this.dueDate = dueDate;
isDueDateSet = true;
return this;
}
@Override
public Batch executeAsync() { | validateParameters();
return commandExecutor.execute(new SetJobsRetriesByProcessBatchCmd(processInstanceIds, processInstanceQuery,
historicProcessInstanceQuery, retries, dueDate, isDueDateSet));
}
protected void validateParameters() {
ensureNotNull("commandExecutor", commandExecutor);
ensureNotNull("retries", retries);
boolean isProcessInstanceIdsNull = processInstanceIds == null || processInstanceIds.isEmpty();
boolean isProcessInstanceQueryNull = processInstanceQuery == null;
boolean isHistoricProcessInstanceQueryNull = historicProcessInstanceQuery == null;
if(isProcessInstanceIdsNull && isProcessInstanceQueryNull && isHistoricProcessInstanceQueryNull) {
throw LOG.exceptionSettingJobRetriesAsyncNoProcessesSpecified();
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\management\SetJobRetriesByProcessAsyncBuilderImpl.java | 1 |
请完成以下Java代码 | void mutate() {
// tag::mutate[]
String url = "wss://spring.io/graphql";
WebSocketClient client = new ReactorNettyWebSocketClient();
WebSocketGraphQlClient graphQlClient = WebSocketGraphQlClient.builder(url, client)
.headers((headers) -> headers.setBasicAuth("joe", "..."))
.build();
// Use graphQlClient...
WebSocketGraphQlClient anotherGraphQlClient = graphQlClient.mutate()
.headers((headers) -> headers.setBasicAuth("peter", "..."))
.build();
// Use anotherGraphQlClient... | // end::mutate[]
}
void keepAlive() {
// tag::keepAlive[]
String url = "wss://spring.io/graphql";
WebSocketClient client = new ReactorNettyWebSocketClient();
WebSocketGraphQlClient graphQlClient = WebSocketGraphQlClient.builder(url, client)
.keepAlive(Duration.ofSeconds(30))
.build();
// end::keepAlive[]
}
} | repos\spring-graphql-main\spring-graphql-docs\src\main\java\org\springframework\graphql\docs\client\websocketgraphqlclient\WebSocketClientUsage.java | 1 |
请完成以下Java代码 | public Integer getFinishOvertime() {
return finishOvertime;
}
public void setFinishOvertime(Integer finishOvertime) {
this.finishOvertime = finishOvertime;
}
public Integer getCommentOvertime() {
return commentOvertime;
}
public void setCommentOvertime(Integer commentOvertime) {
this.commentOvertime = commentOvertime;
}
@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(", flashOrderOvertime=").append(flashOrderOvertime);
sb.append(", normalOrderOvertime=").append(normalOrderOvertime);
sb.append(", confirmOvertime=").append(confirmOvertime);
sb.append(", finishOvertime=").append(finishOvertime);
sb.append(", commentOvertime=").append(commentOvertime);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\OmsOrderSetting.java | 1 |
请完成以下Java代码 | public void invalidateAll()
{
}
private void changeRow(final DocumentId rowId, final UnaryOperator<PricingConditionsRow> mapper)
{
if (!rowIds.contains(rowId))
{
throw new EntityNotFoundException(rowId.toJson());
}
rowsById.compute(rowId, (key, oldRow) -> {
if (oldRow == null)
{
throw new EntityNotFoundException(rowId.toJson());
}
return mapper.apply(oldRow);
});
}
@Override
public void patchRow(final RowEditingContext ctx, final List<JSONDocumentChangedEvent> fieldChangeRequests)
{
final PricingConditionsRowChangeRequest request = PricingConditionsRowActions.toChangeRequest(fieldChangeRequests, getDefaultCurrencyId());
changeRow(ctx.getRowId(), row -> PricingConditionsRowReducers.copyAndChange(request, row));
}
public void patchEditableRow(final PricingConditionsRowChangeRequest request)
{
changeRow(getEditableRowId(), editableRow -> PricingConditionsRowReducers.copyAndChange(request, editableRow));
}
public boolean hasEditableRow()
{
return editableRowId != null;
}
public DocumentId getEditableRowId()
{
if (editableRowId == null) | {
throw new AdempiereException("No editable row found");
}
return editableRowId;
}
public PricingConditionsRow getEditableRow()
{
return getById(getEditableRowId());
}
public DocumentFilterList getFilters()
{
return filters;
}
public PricingConditionsRowData filter(@NonNull final DocumentFilterList filters)
{
if (DocumentFilterList.equals(this.filters, filters))
{
return this;
}
if (filters.isEmpty())
{
return getAllRowsData();
}
return new PricingConditionsRowData(this, filters);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\pricingconditions\view\PricingConditionsRowData.java | 1 |
请完成以下Java代码 | public boolean isIncludeExtensionProperties() {
return includeExtensionProperties;
}
public void setIncludeExtensionProperties(boolean includeExtensionProperties) {
this.includeExtensionProperties = includeExtensionProperties;
}
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((topicName == null) ? 0 : topicName.hashCode());
return result;
}
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false; | }
if (getClass() != obj.getClass()) {
return false;
}
TopicSubscriptionImpl other = (TopicSubscriptionImpl) obj;
if (topicName == null) {
if (other.topicName != null)
return false;
} else if (!topicName.equals(other.topicName)) {
return false;
}
return true;
}
} | repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\topic\impl\TopicSubscriptionImpl.java | 1 |
请完成以下Java代码 | public int compare(IAllocableDocRow row1, IAllocableDocRow row2)
{
return ComparisonChain.start()
.compare(row1.getDocumentDate(), row2.getDocumentDate())
.compare(row1.getDocumentNo(), row2.getDocumentNo())
.result();
}
};
//@formatter:off
String PROPERTY_Selected = "Selected";
boolean isSelected();
void setSelected(boolean selected);
//@formatter:on
String getDocumentNo();
//@formatter:off
BigDecimal getOpenAmtConv();
BigDecimal getOpenAmtConv_APAdjusted();
//@formatter:on
//@formatter:off
String PROPERTY_AppliedAmt = "AppliedAmt";
BigDecimal getAppliedAmt();
BigDecimal getAppliedAmt_APAdjusted();
void setAppliedAmt(BigDecimal appliedAmt);
/** Sets applied amount and update the other write-off amounts, if needed. */
void setAppliedAmtAndUpdate(PaymentAllocationContext context, BigDecimal appliedAmt);
//@formatter:on
/** @return true if automatic calculations and updating are allowed on this row; false if user manually set the amounts and we don't want to change them for him/her */
boolean isTaboo();
/**
* @param taboo <ul>
* <li>true if automatic calculations shall be disallowed on this row | * <li>false if automatic calculations are allowed on this row
* </ul>
*/
void setTaboo(boolean taboo);
/** @return document's date */
Date getDocumentDate();
// task 09643: separate the accounting date from the transaction date
Date getDateAcct();
int getC_BPartner_ID();
/** @return AP Multiplier, i.e. Vendor=-1, Customer=+1 */
BigDecimal getMultiplierAP();
boolean isVendorDocument();
boolean isCustomerDocument();
boolean isCreditMemo();
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.swingui\src\main\java\de\metas\banking\payment\paymentallocation\model\IAllocableDocRow.java | 1 |
请完成以下Java代码 | public class Book {
private String isbn;
private String title;
public Book(String isbn, String title) {
this.isbn = isbn;
this.title = title;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn; | }
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Override
public String toString() {
return "Book{" + "isbn='" + isbn + '\'' + ", title='" + title + '\'' + '}';
}
} | repos\SpringBootLearning-master\springboot-cacahe-data-with-spring\src\main\java\forezp\entity\Book.java | 1 |
请完成以下Java代码 | public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
public void setEmail(String email) {
this.email = email;
}
public Timestamp getCreatedOn() {
return createdOn;
}
public void setCreatedOn(Timestamp createdOn) {
this.createdOn = createdOn; | }
public void setLastLogin(Timestamp lastLogin) {
this.lastLogin = lastLogin;
}
public Permission getPermission() {
return permission;
}
public void setPermission(Permission permission) {
this.permission = permission;
}
@Override
public String toString() {
return "Account{" + "userId=" + userId + ", username='" + username + '\'' + ", password='" + password + '\'' + ", email='" + email + '\'' + ", createdOn=" + createdOn + ", lastLogin=" + lastLogin + ", permission=" + permission + '}';
}
} | repos\tutorials-master\persistence-modules\spring-boot-persistence\src\main\java\com\baeldung\countrows\entity\Account.java | 1 |
请完成以下Java代码 | public org.compiere.model.I_M_InOutLine getReversalLine() throws RuntimeException
{
return (org.compiere.model.I_M_InOutLine)MTable.get(getCtx(), org.compiere.model.I_M_InOutLine.Table_Name)
.getPO(getReversalLine_ID(), get_TrxName()); }
/** Set Reversal Line.
@param ReversalLine_ID
Use to keep the reversal line ID for reversing costing purpose
*/
public void setReversalLine_ID (int ReversalLine_ID)
{
if (ReversalLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_ReversalLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_ReversalLine_ID, Integer.valueOf(ReversalLine_ID));
}
/** Get Reversal Line.
@return Use to keep the reversal line ID for reversing costing purpose
*/
public int getReversalLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_ReversalLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Verworfene Menge.
@param ScrappedQty
Durch QA verworfene Menge
*/
public void setScrappedQty (BigDecimal ScrappedQty)
{
set_ValueNoCheck (COLUMNNAME_ScrappedQty, ScrappedQty);
}
/** Get Verworfene Menge.
@return Durch QA verworfene Menge
*/
public BigDecimal getScrappedQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_ScrappedQty);
if (bd == null)
return Env.ZERO;
return bd;
} | /** Set Zielmenge.
@param TargetQty
Zielmenge der Warenbewegung
*/
public void setTargetQty (BigDecimal TargetQty)
{
set_ValueNoCheck (COLUMNNAME_TargetQty, TargetQty);
}
/** Get Zielmenge.
@return Zielmenge der Warenbewegung
*/
public BigDecimal getTargetQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TargetQty);
if (bd == null)
return Env.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\org\adempiere\model\X_RV_M_InOutLine_Overview.java | 1 |
请完成以下Java代码 | public class LargeHtmlDocument {
private final String content;
private LargeHtmlDocument(String html) {
this.content = html;
}
public LargeHtmlDocument() {
this("");
}
public String html() {
return format("<html>%s</html>", content);
} | public LargeHtmlDocument head(HtmlElement head) {
return new LargeHtmlDocument(format("%s <head>%s</head>", content, head.html()));
}
public LargeHtmlDocument body(HtmlElement body) {
return new LargeHtmlDocument(format("%s <body>%s</body>", content, body.html()));
}
public LargeHtmlDocument footer(HtmlElement footer) {
return new LargeHtmlDocument(format("%s <footer>%s</footer>", content, footer.html()));
}
private LargeHtmlDocument append(String html) {
return new LargeHtmlDocument(format("%s %s", content, html));
}
} | repos\tutorials-master\patterns-modules\design-patterns-behavioral-2\src\main\java\com\baeldung\fluentinterface\LargeHtmlDocument.java | 1 |
请完成以下Java代码 | public I_M_Material_Tracking_Report_Line createMaterialTrackingReportLine(final I_M_Material_Tracking_Report report, final I_M_InOutLine iol, final String lineAggregationKey)
{
final I_M_Material_Tracking_Report_Line newLine = InterfaceWrapperHelper.newInstance(I_M_Material_Tracking_Report_Line.class, iol);
newLine.setM_Material_Tracking_Report(report);
newLine.setM_Product_ID(iol.getM_Product_ID());
final I_M_AttributeSetInstance asi = createASIFromRef(iol);
newLine.setM_AttributeSetInstance(asi);
newLine.setLineAggregationKey(lineAggregationKey);
return newLine;
}
private I_M_AttributeSetInstance createASIFromRef(final I_M_InOutLine iol)
{
final IDimensionspecDAO dimSpecDAO = Services.get(IDimensionspecDAO.class);
final ISysConfigBL sysConfigBL = Services.get(ISysConfigBL.class);
final String internalName = sysConfigBL.getValue(MaterialTrackingConstants.SYSCONFIG_M_Material_Tracking_Report_Dimension);
final DimensionSpec dimensionSpec = dimSpecDAO.retrieveForInternalNameOrNull(internalName);
Check.errorIf(dimensionSpec == null, "Unable to load DIM_Dimension_Spec record with InternalName={}", internalName);
final I_M_AttributeSetInstance resultASI = dimensionSpec.createASIForDimensionSpec(iol.getM_AttributeSetInstance());
return resultASI;
} | @Override
public void createMaterialTrackingReportLineAllocation(final I_M_Material_Tracking_Report_Line reportLine,
final MaterialTrackingReportAgregationItem items)
{
final I_M_Material_Tracking_Report_Line_Alloc alloc = InterfaceWrapperHelper.newInstance(I_M_Material_Tracking_Report_Line_Alloc.class, reportLine);
alloc.setM_Material_Tracking_Report_Line(reportLine);
alloc.setPP_Order(items.getPPOrder());
alloc.setM_InOutLine(items.getInOutLine());
alloc.setM_Material_Tracking(items.getMaterialTracking());
if (items.getPPOrder() != null)
{
alloc.setQtyIssued(items.getQty());
}
else
{
alloc.setQtyReceived(items.getQty());
}
InterfaceWrapperHelper.save(alloc);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\impl\MaterialTrackingReportBL.java | 1 |
请完成以下Java代码 | public Mono<OAuth2AuthorizationRequest> removeAuthorizationRequest(ServerWebExchange exchange) {
String state = getStateParameter(exchange);
if (state == null) {
return Mono.empty();
}
// @formatter:off
return getSessionAttributes(exchange)
.filter((sessionAttrs) -> sessionAttrs.containsKey(this.sessionAttributeName))
.flatMap((sessionAttrs) -> {
OAuth2AuthorizationRequest authorizationRequest = (OAuth2AuthorizationRequest) sessionAttrs.get(this.sessionAttributeName);
if (state.equals(authorizationRequest.getState())) {
sessionAttrs.remove(this.sessionAttributeName);
return Mono.just(authorizationRequest);
}
return Mono.empty();
});
// @formatter:on
}
/**
* Gets the state parameter from the {@link ServerHttpRequest}
* @param exchange the exchange to use | * @return the state parameter or null if not found
*/
private String getStateParameter(ServerWebExchange exchange) {
Assert.notNull(exchange, "exchange cannot be null");
return exchange.getRequest().getQueryParams().getFirst(OAuth2ParameterNames.STATE);
}
private Mono<Map<String, Object>> getSessionAttributes(ServerWebExchange exchange) {
return exchange.getSession().map(WebSession::getAttributes);
}
private OAuth2AuthorizationRequest getAuthorizationRequest(Map<String, Object> sessionAttrs) {
return (OAuth2AuthorizationRequest) sessionAttrs.get(this.sessionAttributeName);
}
} | repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\web\server\WebSessionOAuth2ServerAuthorizationRequestRepository.java | 1 |
请完成以下Java代码 | public static void ifNotEmpty(@Nullable Map<String, Object> source,
@Nullable Consumer<DefaultPropertiesPropertySource> action) {
if (!CollectionUtils.isEmpty(source) && action != null) {
action.accept(new DefaultPropertiesPropertySource(source));
}
}
/**
* Add a new {@link DefaultPropertiesPropertySource} or merge with an existing one.
* @param source the {@code Map} source
* @param sources the existing sources
* @since 2.4.4
*/
public static void addOrMerge(Map<String, Object> source, MutablePropertySources sources) {
if (!CollectionUtils.isEmpty(source)) {
Map<String, Object> resultingSource = new HashMap<>();
DefaultPropertiesPropertySource propertySource = new DefaultPropertiesPropertySource(resultingSource);
if (sources.contains(NAME)) {
mergeIfPossible(source, sources, resultingSource);
sources.replace(NAME, propertySource);
}
else {
resultingSource.putAll(source);
sources.addLast(propertySource);
}
}
}
@SuppressWarnings("unchecked")
private static void mergeIfPossible(Map<String, Object> source, MutablePropertySources sources,
Map<String, Object> resultingSource) {
PropertySource<?> existingSource = sources.get(NAME);
if (existingSource != null) {
Object underlyingSource = existingSource.getSource();
if (underlyingSource instanceof Map) {
resultingSource.putAll((Map<String, Object>) underlyingSource);
}
resultingSource.putAll(source);
}
}
/**
* Move the 'defaultProperties' property source so that it's the last source in the
* given {@link ConfigurableEnvironment}. | * @param environment the environment to update
*/
public static void moveToEnd(ConfigurableEnvironment environment) {
moveToEnd(environment.getPropertySources());
}
/**
* Move the 'defaultProperties' property source so that it's the last source in the
* given {@link MutablePropertySources}.
* @param propertySources the property sources to update
*/
public static void moveToEnd(MutablePropertySources propertySources) {
PropertySource<?> propertySource = propertySources.remove(NAME);
if (propertySource != null) {
propertySources.addLast(propertySource);
}
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\env\DefaultPropertiesPropertySource.java | 1 |
请完成以下Java代码 | public int getInitialCapacity()
{
if (initialCapacity > 0)
{
return initialCapacity;
}
else if (template != null)
{
return template.getInitialCapacity();
}
throw new IllegalStateException("Cannot get InitialCapacity");
}
@Override
public ITableCacheConfigBuilder setInitialCapacity(final int initialCapacity)
{
this.initialCapacity = initialCapacity;
return this;
}
public int getMaxCapacity()
{
if (maxCapacity > 0)
{
return maxCapacity;
}
else if (template != null)
{
return template.getMaxCapacity();
}
return -1;
}
@Override
public ITableCacheConfigBuilder setMaxCapacity(final int maxCapacity)
{ | this.maxCapacity = maxCapacity;
return this;
}
public int getExpireMinutes()
{
if (expireMinutes > 0 || expireMinutes == ITableCacheConfig.EXPIREMINUTES_Never)
{
return expireMinutes;
}
else if (template != null)
{
return template.getExpireMinutes();
}
throw new IllegalStateException("Cannot get ExpireMinutes");
}
@Override
public ITableCacheConfigBuilder setExpireMinutes(final int expireMinutes)
{
this.expireMinutes = expireMinutes;
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\model\impl\TableCacheConfigBuilder.java | 1 |
请完成以下Java代码 | private XmlAddress createEsrBank(final @NonNull Bank bank, @NonNull final Location location)
{
return XmlAddress.builder()
.company(XmlCompany.builder()
.companyname(bank.getBankName())
.postal(XmlPostal.builder()
.zip(location.getPostal())
.city(location.getCity())
.countryCode(location.getCountryCode())
.build())
.build())
.build();
}
private boolean isXmlEsr9(final XmlRequest xAugmentedRequest)
{ | return xAugmentedRequest.getPayload().getBody().getEsr() instanceof XmlEsr9;
}
@Nullable
private BPartnerBankAccount getBPartnerBankAccountOrNull(final BPartnerId bpartnerID)
{
return bpBankAccountDAO.getBpartnerBankAccount(BankAccountQuery.builder()
.bpBankAcctUses(ImmutableSet.of(BPBankAcctUse.DEBIT_OR_DEPOSIT, BPBankAcctUse.DEPOSIT))
.containsQRIBAN(true)
.bPartnerId(bpartnerID)
.build())
.stream()
.findFirst()
.orElse(null);
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_450_request\src\main\java\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_450\Invoice450FromCrossVersionModelTool.java | 1 |
请完成以下Java代码 | private static PrivateKey readPrivateKey(Reader reader, String passStr) throws IOException, PKCSException {
char[] password = getPassword(passStr);
PrivateKey privateKey = null;
JcaPEMKeyConverter keyConverter = new JcaPEMKeyConverter();
try (PEMParser pemParser = new PEMParser(reader)) {
Object object;
while ((object = pemParser.readObject()) != null) {
if (object instanceof PEMEncryptedKeyPair) {
PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().build(password);
privateKey = keyConverter.getKeyPair(((PEMEncryptedKeyPair) object).decryptKeyPair(decProv)).getPrivate();
break;
} else if (object instanceof PKCS8EncryptedPrivateKeyInfo) {
InputDecryptorProvider decProv =
new JcePKCSPBEInputDecryptorProviderBuilder().setProvider(DEFAULT_PROVIDER).build(password);
privateKey = keyConverter.getPrivateKey(((PKCS8EncryptedPrivateKeyInfo) object).decryptPrivateKeyInfo(decProv));
break; | } else if (object instanceof PEMKeyPair) {
privateKey = keyConverter.getKeyPair((PEMKeyPair) object).getPrivate();
break;
} else if (object instanceof PrivateKeyInfo) {
privateKey = keyConverter.getPrivateKey((PrivateKeyInfo) object);
}
}
}
return privateKey;
}
public static char[] getPassword(String passStr) {
return StringUtils.isEmpty(passStr) ? EMPTY_PASS : passStr.toCharArray();
}
} | repos\thingsboard-master\common\util\src\main\java\org\thingsboard\common\util\SslUtil.java | 1 |
请完成以下Java代码 | public boolean supports(Class<?> authentication) {
return OidcClientRegistrationAuthenticationToken.class.isAssignableFrom(authentication);
}
private OidcClientRegistrationAuthenticationToken findRegistration(
OidcClientRegistrationAuthenticationToken clientRegistrationAuthentication,
OAuth2Authorization authorization) {
RegisteredClient registeredClient = this.registeredClientRepository
.findByClientId(clientRegistrationAuthentication.getClientId());
if (registeredClient == null) {
throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_CLIENT);
}
if (!registeredClient.getId().equals(authorization.getRegisteredClientId())) {
throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_CLIENT);
}
if (this.logger.isTraceEnabled()) {
this.logger.trace("Validated client configuration request parameters");
}
OidcClientRegistration clientRegistration = this.clientRegistrationConverter.convert(registeredClient);
if (this.logger.isTraceEnabled()) {
this.logger.trace("Authenticated client configuration request");
}
return new OidcClientRegistrationAuthenticationToken(
(Authentication) clientRegistrationAuthentication.getPrincipal(), clientRegistration);
}
@SuppressWarnings("unchecked")
private static void checkScope(OAuth2Authorization.Token<OAuth2AccessToken> authorizedAccessToken, | Set<String> requiredScope) {
Collection<String> authorizedScope = Collections.emptySet();
if (authorizedAccessToken.getClaims().containsKey(OAuth2ParameterNames.SCOPE)) {
authorizedScope = (Collection<String>) authorizedAccessToken.getClaims().get(OAuth2ParameterNames.SCOPE);
}
if (!authorizedScope.containsAll(requiredScope)) {
throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INSUFFICIENT_SCOPE);
}
else if (authorizedScope.size() != requiredScope.size()) {
// Restrict the access token to only contain the required scope
throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_TOKEN);
}
}
} | repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\oidc\authentication\OidcClientConfigurationAuthenticationProvider.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
if (element.hasAttribute(ADDRESSES) &&
(element.hasAttribute(HOST_ATTRIBUTE) || element.hasAttribute(PORT_ATTRIBUTE))) {
parserContext.getReaderContext().error("If the 'addresses' attribute is provided, a connection " +
"factory can not have 'host' or 'port' attributes.", element);
}
NamespaceUtils.addConstructorArgParentRefIfAttributeDefined(builder, element, CONNECTION_FACTORY_ATTRIBUTE);
NamespaceUtils.setValueIfAttributeDefined(builder, element, CHANNEL_CACHE_SIZE_ATTRIBUTE);
NamespaceUtils.setValueIfAttributeDefined(builder, element, HOST_ATTRIBUTE);
NamespaceUtils.setValueIfAttributeDefined(builder, element, PORT_ATTRIBUTE);
NamespaceUtils.setValueIfAttributeDefined(builder, element, USER_ATTRIBUTE);
NamespaceUtils.setValueIfAttributeDefined(builder, element, PASSWORD_ATTRIBUTE);
NamespaceUtils.setValueIfAttributeDefined(builder, element, VIRTUAL_HOST_ATTRIBUTE);
NamespaceUtils.setReferenceIfAttributeDefined(builder, element, EXECUTOR_ATTRIBUTE);
NamespaceUtils.setValueIfAttributeDefined(builder, element, ADDRESSES);
NamespaceUtils.setValueIfAttributeDefined(builder, element, SHUFFLE_ADDRESSES);
if (element.hasAttribute(SHUFFLE_ADDRESSES) && element.hasAttribute(SHUFFLE_MODE)) { | parserContext.getReaderContext()
.error("You must not specify both '" + SHUFFLE_ADDRESSES + "' and '" + SHUFFLE_MODE + "'", element);
}
NamespaceUtils.setValueIfAttributeDefined(builder, element, SHUFFLE_MODE);
NamespaceUtils.setReferenceIfAttributeDefined(builder, element, ADDRESS_RESOLVER);
NamespaceUtils.setValueIfAttributeDefined(builder, element, PUBLISHER_RETURNS);
NamespaceUtils.setValueIfAttributeDefined(builder, element, REQUESTED_HEARTBEAT, "requestedHeartBeat");
NamespaceUtils.setValueIfAttributeDefined(builder, element, CONNECTION_TIMEOUT);
NamespaceUtils.setValueIfAttributeDefined(builder, element, CACHE_MODE);
NamespaceUtils.setValueIfAttributeDefined(builder, element, CONNECTION_CACHE_SIZE_ATTRIBUTE);
NamespaceUtils.setReferenceIfAttributeDefined(builder, element, THREAD_FACTORY, "connectionThreadFactory");
NamespaceUtils.setValueIfAttributeDefined(builder, element, FACTORY_TIMEOUT, "channelCheckoutTimeout");
NamespaceUtils.setValueIfAttributeDefined(builder, element, CONNECTION_LIMIT);
NamespaceUtils.setReferenceIfAttributeDefined(builder, element, "connection-name-strategy");
NamespaceUtils.setValueIfAttributeDefined(builder, element, CONFIRM_TYPE, "publisherConfirmType");
}
} | repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\config\ConnectionFactoryParser.java | 2 |
请完成以下Java代码 | public void setAD_Table_ID (int AD_Table_ID)
{
if (AD_Table_ID < 1)
set_Value (COLUMNNAME_AD_Table_ID, null);
else
set_Value (COLUMNNAME_AD_Table_ID, Integer.valueOf(AD_Table_ID));
}
/** Get Table.
@return Database Table information
*/
public int getAD_Table_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Table_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_C_DocType getC_DocType() throws RuntimeException
{
return (I_C_DocType)MTable.get(getCtx(), I_C_DocType.Table_Name)
.getPO(getC_DocType_ID(), get_TrxName()); }
/** Set Document Type.
@param C_DocType_ID
Document type or rules
*/
public void setC_DocType_ID (int C_DocType_ID)
{
if (C_DocType_ID < 0)
set_Value (COLUMNNAME_C_DocType_ID, null);
else
set_Value (COLUMNNAME_C_DocType_ID, Integer.valueOf(C_DocType_ID));
}
/** Get Document Type.
@return Document type or rules
*/
public int getC_DocType_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_DocType_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{ | set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** ReplicationType AD_Reference_ID=126 */
public static final int REPLICATIONTYPE_AD_Reference_ID=126;
/** Local = L */
public static final String REPLICATIONTYPE_Local = "L";
/** Merge = M */
public static final String REPLICATIONTYPE_Merge = "M";
/** Reference = R */
public static final String REPLICATIONTYPE_Reference = "R";
/** Broadcast = B */
public static final String REPLICATIONTYPE_Broadcast = "B";
/** Set Replication Type.
@param ReplicationType
Type of Data Replication
*/
public void setReplicationType (String ReplicationType)
{
set_Value (COLUMNNAME_ReplicationType, ReplicationType);
}
/** Get Replication Type.
@return Type of Data Replication
*/
public String getReplicationType ()
{
return (String)get_Value(COLUMNNAME_ReplicationType);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_ReplicationDocument.java | 1 |
请完成以下Java代码 | public int getM_AttributeSetInstance_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeSetInstance_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_M_InventoryLine getM_InventoryLine()
{
return get_ValueAsPO(COLUMNNAME_M_InventoryLine_ID, org.compiere.model.I_M_InventoryLine.class);
}
@Override
public void setM_InventoryLine(org.compiere.model.I_M_InventoryLine M_InventoryLine)
{
set_ValueFromPO(COLUMNNAME_M_InventoryLine_ID, org.compiere.model.I_M_InventoryLine.class, M_InventoryLine);
}
/** Set Inventur-Position.
@param M_InventoryLine_ID
Unique line in an Inventory document
*/
@Override
public void setM_InventoryLine_ID (int M_InventoryLine_ID)
{
if (M_InventoryLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_InventoryLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_InventoryLine_ID, Integer.valueOf(M_InventoryLine_ID));
}
/** Get Inventur-Position.
@return Unique line in an Inventory document
*/
@Override
public int getM_InventoryLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_InventoryLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set M_InventoryLineMA.
@param M_InventoryLineMA_ID M_InventoryLineMA */
@Override | public void setM_InventoryLineMA_ID (int M_InventoryLineMA_ID)
{
if (M_InventoryLineMA_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_InventoryLineMA_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_InventoryLineMA_ID, Integer.valueOf(M_InventoryLineMA_ID));
}
/** Get M_InventoryLineMA.
@return M_InventoryLineMA */
@Override
public int getM_InventoryLineMA_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_InventoryLineMA_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Bewegungs-Menge.
@param MovementQty
Quantity of a product moved.
*/
@Override
public void setMovementQty (java.math.BigDecimal MovementQty)
{
set_Value (COLUMNNAME_MovementQty, MovementQty);
}
/** Get Bewegungs-Menge.
@return Quantity of a product moved.
*/
@Override
public java.math.BigDecimal getMovementQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_MovementQty);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_InventoryLineMA.java | 1 |
请完成以下Java代码 | public boolean hasDifferences()
{
return differenceAmt.signum() != 0;
}
public BankStatementLineAmounts assertNoDifferences()
{
if (differenceAmt.signum() != 0)
{
throw new AdempiereException("Amounts are not completelly balanced: " + this);
}
return this;
}
public BankStatementLineAmounts addDifferenceToTrxAmt()
{
if (differenceAmt.signum() == 0)
{
return this;
}
return toBuilder()
.trxAmt(this.trxAmt.add(differenceAmt))
.build();
}
public BankStatementLineAmounts withTrxAmt(@NonNull final BigDecimal trxAmt)
{
return !this.trxAmt.equals(trxAmt) | ? toBuilder().trxAmt(trxAmt).build()
: this;
}
public BankStatementLineAmounts addDifferenceToBankFeeAmt()
{
if (differenceAmt.signum() == 0)
{
return this;
}
return toBuilder()
.bankFeeAmt(this.bankFeeAmt.subtract(differenceAmt))
.build();
}
public BankStatementLineAmounts withBankFeeAmt(@NonNull final BigDecimal bankFeeAmt)
{
return !this.bankFeeAmt.equals(bankFeeAmt)
? toBuilder().bankFeeAmt(bankFeeAmt).build()
: this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\model\BankStatementLineAmounts.java | 1 |
请完成以下Java代码 | public Class<?> getType(ELContext context, Object base, Object property) {
Objects.requireNonNull(context, "context is null");
if (isResolvable(base)) {
context.setPropertyResolved(base, property);
if (readOnly || base.getClass() == UNMODIFIABLE) {
return null;
}
return Object.class;
}
return null;
}
@Override
public Object getValue(ELContext context, Object base, Object property) {
Objects.requireNonNull(context, "context is null");
if (isResolvable(base)) {
context.setPropertyResolved(base, property);
return ((Map<?, ?>) base).get(property);
}
return null;
}
@Override
public void setValue(ELContext context, Object base, Object property, Object value) {
Objects.requireNonNull(context, "context is null");
if (isResolvable(base)) {
context.setPropertyResolved(base, property);
if (readOnly) {
throw new PropertyNotWritableException("resolver is read-only");
}
try {
@SuppressWarnings("unchecked") // Must be OK
Map<Object, Object> map = ((Map<Object, Object>) base);
map.put(property, value);
} catch (UnsupportedOperationException e) {
throw new PropertyNotWritableException(e);
} | }
}
@Override
public boolean isReadOnly(ELContext context, Object base, Object property) {
Objects.requireNonNull(context, "context is null");
if (isResolvable(base)) {
context.setPropertyResolved(base, property);
return this.readOnly || UNMODIFIABLE.equals(base.getClass());
}
return readOnly;
}
@Override
public Class<?> getCommonPropertyType(ELContext context, Object base) {
return isResolvable(base) ? Object.class : null;
}
/**
* Test whether the given base should be resolved by this ELResolver.
*
* @param base
* The bean to analyze.
* @return base instanceof Map
*/
private boolean isResolvable(Object base) {
return base instanceof Map<?,?>;
}
} | repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\javax\el\MapELResolver.java | 1 |
请完成以下Java代码 | void registerLoggedException(Throwable exception) {
this.loggedExceptions.add(exception);
}
void registerExitCode(int exitCode) {
this.exitCode = exitCode;
}
@Override
public void uncaughtException(Thread thread, Throwable ex) {
try {
if (isPassedToParent(ex) && this.parent != null) {
this.parent.uncaughtException(thread, ex);
}
}
finally {
this.loggedExceptions.clear();
if (this.exitCode != 0) {
System.exit(this.exitCode);
}
}
}
private boolean isPassedToParent(Throwable ex) {
return isLogConfigurationMessage(ex) || !isRegistered(ex);
}
/**
* Check if the exception is a log configuration message, i.e. the log call might not
* have actually output anything.
* @param ex the source exception
* @return {@code true} if the exception contains a log configuration message
*/
private boolean isLogConfigurationMessage(@Nullable Throwable ex) {
if (ex == null) {
return false;
}
if (ex instanceof InvocationTargetException) {
return isLogConfigurationMessage(ex.getCause());
}
String message = ex.getMessage();
if (message != null) {
for (String candidate : LOG_CONFIGURATION_MESSAGES) {
if (message.contains(candidate)) {
return true;
}
}
}
return false;
}
private boolean isRegistered(@Nullable Throwable ex) { | if (ex == null) {
return false;
}
if (this.loggedExceptions.contains(ex)) {
return true;
}
if (ex instanceof InvocationTargetException) {
return isRegistered(ex.getCause());
}
return false;
}
static SpringBootExceptionHandler forCurrentThread() {
return handler.get();
}
/**
* Thread local used to attach and track handlers.
*/
private static final class LoggedExceptionHandlerThreadLocal extends ThreadLocal<SpringBootExceptionHandler> {
@Override
protected SpringBootExceptionHandler initialValue() {
SpringBootExceptionHandler handler = new SpringBootExceptionHandler(
Thread.currentThread().getUncaughtExceptionHandler());
Thread.currentThread().setUncaughtExceptionHandler(handler);
return handler;
}
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\SpringBootExceptionHandler.java | 1 |
请完成以下Java代码 | public String getBusinessKey() {
return businessKey;
}
public void setBusinessKey(String businessKey) {
this.businessKey = businessKey;
}
public Date getStartTime() {
return startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
} | public List<IncidentStatisticsDto> getIncidents() {
return incidents;
}
public void setIncidents(List<IncidentStatisticsDto> incidents) {
this.incidents = incidents;
}
public boolean isSuspended() {
return SuspensionState.SUSPENDED.getStateCode() == suspensionState;
}
protected void setSuspensionState(int state) {
this.suspensionState = state;
}
} | repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\cockpit\impl\plugin\base\dto\ProcessInstanceDto.java | 1 |
请完成以下Java代码 | public MInvoice getInvoice()
{
if (m_invoice == null && getC_Invoice_ID() != 0)
m_invoice = new MInvoice(getCtx(), getC_Invoice_ID(), get_TrxName());
return m_invoice;
} // getInvoice
/**
* Get BPartner of Invoice
* @return bp
*/
public int getC_BPartner_ID()
{
if (m_invoice == null)
getInvoice();
if (m_invoice == null)
return 0;
return m_invoice.getC_BPartner_ID();
} // getC_BPartner_ID
/**
* Before Save
* @param newRecord new
* @return true
*/
@Override
protected boolean beforeSave (boolean newRecord)
{
MPayment payment = new MPayment (getCtx(), getC_Payment_ID(), get_TrxName());
if ((newRecord || is_ValueChanged("C_Invoice_ID"))
&& (payment.getC_Charge_ID() != 0
|| payment.getC_Invoice_ID() != 0
|| payment.getC_Order_ID() != 0))
{
throw new AdempiereException("@PaymentIsAllocated@");
}
BigDecimal check = getAmount()
.add(getDiscountAmt())
.add(getWriteOffAmt())
.add(getOverUnderAmt());
if (check.compareTo(getInvoiceAmt()) != 0)
{
throw new AdempiereException("@InvoiceAmt@(" + getInvoiceAmt() + ") <> @Totals@(" + check + ")");
}
// Org
if (newRecord || is_ValueChanged("C_Invoice_ID"))
{ | getInvoice();
if (m_invoice != null)
setAD_Org_ID(m_invoice.getAD_Org_ID());
}
return true;
} // beforeSave
@Override
protected boolean afterSave(boolean newRecord, boolean success)
{
//metas start: cg task us025b
if (success)
{
updateAmounts();
}
return success;
//metas end: cg task us025b
}
@Override
protected boolean afterDelete(boolean success)
{
//metas start: cg task us025b
if (success)
{
updateAmounts();
}
return success;
//metas end: cg task us025b
}
/**
* metas cg task us025b
* method for updating amounts in payment
*/
private void updateAmounts()
{
String updateSQL = "UPDATE C_Payment "
+ " set PayAmt = (SELECT SUM(Amount) from C_PaymentAllocate WHERE C_Payment_ID=?), "
+ " DiscountAmt = (SELECT SUM(DiscountAmt) from C_PaymentAllocate WHERE C_Payment_ID=?), "
+ " WriteOffAmt = (SELECT SUM(WriteOffAmt) from C_PaymentAllocate WHERE C_Payment_ID=?), "
+ " OverUnderAmt = (SELECT SUM(OverUnderAmt) from C_PaymentAllocate WHERE C_Payment_ID=?), "
+ " IsOverUnderPayment = (SELECT CASE WHEN sum(OverUnderAmt)!=0 THEN 'Y' ELSE 'N' END FROM C_PaymentAllocate WHERE C_Payment_ID=?) "
+ " WHERE C_Payment_ID=?";
DB.executeUpdateAndIgnoreErrorOnFail(updateSQL, new Object[] { getC_Payment_ID(), getC_Payment_ID(), getC_Payment_ID(),
getC_Payment_ID(), getC_Payment_ID(), getC_Payment_ID() },
false, get_TrxName());
}
} // MPaymentAllocate | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MPaymentAllocate.java | 1 |
请完成以下Java代码 | public Integer encrypt(Integer value)
{
return value;
} // encrypt
/**
* Decryption.
* The methods must recognize clear text values
*
* @param value encrypted value
* @return decrypted String
*/
@Override
public Integer decrypt(Integer value)
{
return value;
} // decrypt
/**
* Encryption.
* The methods must recognize clear text values
*
* @param value clear value
* @return encrypted String
*/
@Override
public BigDecimal encrypt(BigDecimal value)
{
return value;
} // encrypt
/**
* Decryption.
* The methods must recognize clear text values
*
* @param value encrypted value
* @return decrypted String
*/
@Override
public BigDecimal decrypt(BigDecimal value)
{
return value;
} // decrypt
/**
* Encryption.
* The methods must recognize clear text values
*
* @param value clear value
* @return encrypted String
*/
@Override
public Timestamp encrypt(Timestamp value)
{
return value;
} // encrypt
/**
* Decryption.
* The methods must recognize clear text values
*
* @param value encrypted value
* @return decrypted String
*/
@Override
public Timestamp decrypt(Timestamp value)
{
return value;
} // decrypt
/**
* Convert String to Digest.
* JavaScript version see - http://pajhome.org.uk/crypt/md5/index.html
*
* @param value message
* @return HexString of message (length = 32 characters)
*/
@Override
public String getDigest(String value)
{
if (m_md == null)
{ | try
{
m_md = MessageDigest.getInstance("MD5");
// m_md = MessageDigest.getInstance("SHA-1");
}
catch (NoSuchAlgorithmException nsae)
{
nsae.printStackTrace();
}
}
// Reset MessageDigest object
m_md.reset();
// Convert String to array of bytes
byte[] input = value.getBytes(StandardCharsets.UTF_8);
// feed this array of bytes to the MessageDigest object
m_md.update(input);
// Get the resulting bytes after the encryption process
byte[] output = m_md.digest();
m_md.reset();
//
return convertToHexString(output);
} // getDigest
/**
* Checks, if value is a valid digest
*
* @param value digest string
* @return true if valid digest
*/
@Override
public boolean isDigest(String value)
{
if (value == null || value.length() != 32)
return false;
// needs to be a hex string, so try to convert it
return (convertHexString(value) != null);
} // isDigest
/**
* String Representation
*
* @return info
*/
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.add("cipher", m_cipher)
.toString();
}
} // Secure | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\Secure.java | 1 |
请在Spring Boot框架中完成以下Java代码 | static class JacksonJsonStrategyConfiguration {
private static final MediaType[] SUPPORTED_TYPES = { MediaType.APPLICATION_JSON,
new MediaType("application", "*+json") };
@Bean
@Order(1)
@ConditionalOnBean(JsonMapper.class)
RSocketStrategiesCustomizer jacksonJsonRSocketStrategyCustomizer(JsonMapper jsonMapper) {
return (strategy) -> {
strategy.decoder(new JacksonJsonDecoder(jsonMapper, SUPPORTED_TYPES));
strategy.encoder(new JacksonJsonEncoder(jsonMapper, SUPPORTED_TYPES));
};
}
}
}
@Configuration(proxyBeanMethods = false)
@Conditional(NoJacksonOrJackson2Preferred.class)
@SuppressWarnings("removal")
@Deprecated(since = "4.0.0", forRemoval = true)
static class Jackson2StrategyConfiguration {
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass({ ObjectMapper.class, CBORFactory.class })
static class Jackson2CborStrategyConfiguration {
private static final MediaType[] SUPPORTED_TYPES = { MediaType.APPLICATION_CBOR };
@Bean
@Order(0)
@ConditionalOnBean(org.springframework.http.converter.json.Jackson2ObjectMapperBuilder.class)
RSocketStrategiesCustomizer jackson2CborRSocketStrategyCustomizer(
org.springframework.http.converter.json.Jackson2ObjectMapperBuilder builder) {
return (strategy) -> {
ObjectMapper objectMapper = builder.createXmlMapper(false)
.factory(new com.fasterxml.jackson.dataformat.cbor.CBORFactory())
.build();
strategy.decoder(
new org.springframework.http.codec.cbor.Jackson2CborDecoder(objectMapper, SUPPORTED_TYPES));
strategy.encoder(
new org.springframework.http.codec.cbor.Jackson2CborEncoder(objectMapper, SUPPORTED_TYPES));
};
}
}
@ConditionalOnClass(ObjectMapper.class)
static class Jackson2JsonStrategyConfiguration {
private static final MediaType[] SUPPORTED_TYPES = { MediaType.APPLICATION_JSON,
new MediaType("application", "*+json") };
@Bean
@Order(1)
@ConditionalOnBean(ObjectMapper.class)
RSocketStrategiesCustomizer jackson2JsonRSocketStrategyCustomizer(ObjectMapper objectMapper) {
return (strategy) -> {
strategy.decoder( | new org.springframework.http.codec.json.Jackson2JsonDecoder(objectMapper, SUPPORTED_TYPES));
strategy.encoder(
new org.springframework.http.codec.json.Jackson2JsonEncoder(objectMapper, SUPPORTED_TYPES));
};
}
}
}
static class NoJacksonOrJackson2Preferred extends AnyNestedCondition {
NoJacksonOrJackson2Preferred() {
super(ConfigurationPhase.PARSE_CONFIGURATION);
}
@ConditionalOnMissingClass("tools.jackson.databind.json.JsonMapper")
static class NoJackson {
}
@ConditionalOnProperty(name = "spring.rsocket.preferred-mapper", havingValue = "jackson2")
static class Jackson2Preferred {
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-rsocket\src\main\java\org\springframework\boot\rsocket\autoconfigure\RSocketStrategiesAutoConfiguration.java | 2 |
请完成以下Java代码 | public void throwSignal(SignalDto dto) {
String name = dto.getName();
if (name == null) {
throw new InvalidRequestException(Status.BAD_REQUEST, "No signal name given");
}
SignalEventReceivedBuilder signalEvent = createSignalEventReceivedBuilder(dto);
try {
signalEvent.send();
} catch (NotFoundException e) {
// keeping compatibility with older versions where ProcessEngineException (=> 500) was
// thrown; NotFoundException translates to 400 by default
throw new RestException(Status.INTERNAL_SERVER_ERROR, e, e.getMessage());
}
}
protected SignalEventReceivedBuilder createSignalEventReceivedBuilder(SignalDto dto) {
RuntimeService runtimeService = getProcessEngine().getRuntimeService();
String name = dto.getName();
SignalEventReceivedBuilder signalEvent = runtimeService.createSignalEvent(name);
String executionId = dto.getExecutionId();
if (executionId != null) {
signalEvent.executionId(executionId);
}
Map<String, VariableValueDto> variablesDto = dto.getVariables();
if (variablesDto != null) {
Map<String, Object> variables = VariableValueDto.toMap(variablesDto, getProcessEngine(), objectMapper); | signalEvent.setVariables(variables);
}
String tenantId = dto.getTenantId();
if (tenantId != null) {
signalEvent.tenantId(tenantId);
}
boolean isWithoutTenantId = dto.isWithoutTenantId();
if (isWithoutTenantId) {
signalEvent.withoutTenantId();
}
return signalEvent;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\SignalRestServiceImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class TaxExtensionType {
@XmlElement(name = "TaxExtension", namespace = "http://erpel.at/schemas/1p0/documents/extensions/edifact")
protected at.erpel.schemas._1p0.documents.extensions.edifact.TaxExtensionType taxExtension;
@XmlElement(name = "ErpelTaxExtension")
protected CustomType erpelTaxExtension;
/**
* Gets the value of the taxExtension property.
*
* @return
* possible object is
* {@link at.erpel.schemas._1p0.documents.extensions.edifact.TaxExtensionType }
*
*/
public at.erpel.schemas._1p0.documents.extensions.edifact.TaxExtensionType getTaxExtension() {
return taxExtension;
}
/**
* Sets the value of the taxExtension property.
*
* @param value
* allowed object is
* {@link at.erpel.schemas._1p0.documents.extensions.edifact.TaxExtensionType }
*
*/
public void setTaxExtension(at.erpel.schemas._1p0.documents.extensions.edifact.TaxExtensionType value) {
this.taxExtension = value;
}
/**
* Gets the value of the erpelTaxExtension property. | *
* @return
* possible object is
* {@link CustomType }
*
*/
public CustomType getErpelTaxExtension() {
return erpelTaxExtension;
}
/**
* Sets the value of the erpelTaxExtension property.
*
* @param value
* allowed object is
* {@link CustomType }
*
*/
public void setErpelTaxExtension(CustomType value) {
this.erpelTaxExtension = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\ext\TaxExtensionType.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public ImmutableMap<FlatrateTermId, CommissionConfig> createForExistingInstance(@NonNull final CommissionConfigProvider.ConfigRequestForExistingInstance commissionConfigRequest)
{
final ImmutableMap.Builder<FlatrateTermId, CommissionConfig> resultBuilder = ImmutableMap.builder();
priorityOrderedConfigFactories.stream()
.map(configFactory -> configFactory.createForExistingInstance(commissionConfigRequest))
.forEach(resultBuilder::putAll);
final ImmutableMap<FlatrateTermId, CommissionConfig> result = resultBuilder.build();
if (result.isEmpty())
{
throw new AdempiereException("The given commissionConfigRequest needs at least one commissionConfig")
.appendParametersToMessage()
.setParameter("result.size()", result.size())
.setParameter("commissionConfigRequest", commissionConfigRequest)
.setParameter("result", result);
}
return result;
}
@Builder
@Value
public static class ConfigRequestForNewInstance
{
@NonNull
OrgId orgId;
@NonNull
BPartnerId salesRepBPartnerId;
/**
* Needed because config settings can be specific to the customer's group.
*/
@NonNull
BPartnerId customerBPartnerId;
/**
* Needed because config settings can be specific to the product's category.
*/
@NonNull | ProductId salesProductId;
@NonNull
LocalDate commissionDate;
@NonNull
Hierarchy commissionHierarchy;
@NonNull
CommissionTriggerType commissionTriggerType;
public boolean isCustomerTheSalesRep()
{
return customerBPartnerId.equals(salesRepBPartnerId);
}
}
@Builder
@Value
public static class ConfigRequestForExistingInstance
{
@NonNull
ImmutableList<FlatrateTermId> contractIds;
@NonNull
BPartnerId customerBPartnerId;
@NonNull
ProductId salesProductId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\commissioninstance\services\CommissionConfigProvider.java | 2 |
请在Spring Boot框架中完成以下Java代码 | protected AssetProfile prepare(EntitiesImportCtx ctx, AssetProfile assetProfile, AssetProfile old, EntityExportData<AssetProfile> exportData, IdProvider idProvider) {
assetProfile.setDefaultRuleChainId(idProvider.getInternalId(assetProfile.getDefaultRuleChainId()));
assetProfile.setDefaultDashboardId(idProvider.getInternalId(assetProfile.getDefaultDashboardId()));
assetProfile.setDefaultEdgeRuleChainId(idProvider.getInternalId(assetProfile.getDefaultEdgeRuleChainId()));
return assetProfile;
}
@Override
protected AssetProfile saveOrUpdate(EntitiesImportCtx ctx, AssetProfile assetProfile, EntityExportData<AssetProfile> exportData, IdProvider idProvider, CompareResult compareResult) {
AssetProfile saved = assetProfileService.saveAssetProfile(assetProfile);
if (ctx.isFinalImportAttempt() || ctx.getCurrentImportResult().isUpdatedAllExternalIds()) {
importCalculatedFields(ctx, saved, exportData, idProvider);
}
return saved;
}
@Override
protected void onEntitySaved(User user, AssetProfile savedAssetProfile, AssetProfile oldAssetProfile) {
logEntityActionService.logEntityAction(savedAssetProfile.getTenantId(), savedAssetProfile.getId(),
savedAssetProfile, null, oldAssetProfile == null ? ActionType.ADDED : ActionType.UPDATED, user);
} | @Override
protected AssetProfile deepCopy(AssetProfile assetProfile) {
return new AssetProfile(assetProfile);
}
@Override
protected void cleanupForComparison(AssetProfile assetProfile) {
super.cleanupForComparison(assetProfile);
}
@Override
public EntityType getEntityType() {
return EntityType.ASSET_PROFILE;
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\sync\ie\importing\impl\AssetProfileImportService.java | 2 |
请完成以下Spring Boot application配置 | # Spring boot application
spring.application.name=dubbo-auto-configuration-provider-demo
# Base packages to scan Dubbo Component: @org.apache.dubbo.config.annotation.Service
dubbo.scan.base-packages=org.apache.dubbo.spring.boot.sample.provider.service
# Dubbo Application
## The default value of dubbo.application.name is ${spring.application.name}
## dubbo.ap | plication.name=${spring.application.name}
# Dubbo Protocol
dubbo.protocol.name=dubbo
dubbo.protocol.port=12345
## Dubbo Registry
dubbo.registry.address=N/A | repos\dubbo-spring-boot-project-master\dubbo-spring-boot-samples\auto-configure-samples\provider-sample\src\main\resources\application.properties | 2 |
请完成以下Java代码 | private GrantedAuthority getRequiredAuthority(int changeType) {
if (changeType == CHANGE_AUDITING) {
return this.gaModifyAuditing;
}
if (changeType == CHANGE_GENERAL) {
return this.gaGeneralChanges;
}
if (changeType == CHANGE_OWNERSHIP) {
return this.gaTakeOwnership;
}
throw new IllegalArgumentException("Unknown change type");
}
/**
* Creates a principal-like sid from the authentication information.
* @param authentication the authentication information that can provide principal and
* thus the sid's id will be dependant on the value inside
* @return a sid with the ID taken from the authentication information
*/
protected Sid createCurrentUser(Authentication authentication) {
return new PrincipalSid(authentication);
}
public void setSidRetrievalStrategy(SidRetrievalStrategy sidRetrievalStrategy) {
Assert.notNull(sidRetrievalStrategy, "SidRetrievalStrategy required");
this.sidRetrievalStrategy = sidRetrievalStrategy;
}
/** | * Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use
* the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}.
*
* @since 5.8
*/
public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) {
Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null");
this.securityContextHolderStrategy = securityContextHolderStrategy;
}
/**
* Sets the {@link RoleHierarchy} to use. The default is to use a
* {@link NullRoleHierarchy}
* @since 6.4
*/
public void setRoleHierarchy(RoleHierarchy roleHierarchy) {
Assert.notNull(roleHierarchy, "roleHierarchy cannot be null");
this.roleHierarchy = roleHierarchy;
}
} | repos\spring-security-main\acl\src\main\java\org\springframework\security\acls\domain\AclAuthorizationStrategyImpl.java | 1 |
请完成以下Java代码 | public String toString()
{
StringBuffer sb = new StringBuffer ("X_ImpEx_Connector[")
.append(get_ID()).append("]");
return sb.toString();
}
/** Set Beschreibung.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Beschreibung.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Konnektor.
@param ImpEx_Connector_ID Konnektor */
public void setImpEx_Connector_ID (int ImpEx_Connector_ID)
{
if (ImpEx_Connector_ID < 1)
set_ValueNoCheck (COLUMNNAME_ImpEx_Connector_ID, null);
else
set_ValueNoCheck (COLUMNNAME_ImpEx_Connector_ID, Integer.valueOf(ImpEx_Connector_ID));
}
/** Get Konnektor.
@return Konnektor */
public int getImpEx_Connector_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_ImpEx_Connector_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public de.metas.impex.model.I_ImpEx_ConnectorType getImpEx_ConnectorType() throws RuntimeException
{
return (de.metas.impex.model.I_ImpEx_ConnectorType)MTable.get(getCtx(), de.metas.impex.model.I_ImpEx_ConnectorType.Table_Name)
.getPO(getImpEx_ConnectorType_ID(), get_TrxName()); }
/** Set Konnektor-Typ.
@param ImpEx_ConnectorType_ID Konnektor-Typ */
public void setImpEx_ConnectorType_ID (int ImpEx_ConnectorType_ID)
{
if (ImpEx_ConnectorType_ID < 1) | set_Value (COLUMNNAME_ImpEx_ConnectorType_ID, null);
else
set_Value (COLUMNNAME_ImpEx_ConnectorType_ID, Integer.valueOf(ImpEx_ConnectorType_ID));
}
/** Get Konnektor-Typ.
@return Konnektor-Typ */
public int getImpEx_ConnectorType_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_ImpEx_ConnectorType_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());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\impex\model\X_ImpEx_Connector.java | 1 |
请完成以下Java代码 | public Stage getPlanModel() {
return planModel;
}
public void setPlanModel(Stage planModel) {
this.planModel = planModel;
}
public String getStartEventType() {
return startEventType;
}
public void setStartEventType(String startEventType) {
this.startEventType = startEventType;
}
public List<String> getCandidateStarterUsers() {
return candidateStarterUsers;
}
public void setCandidateStarterUsers(List<String> candidateStarterUsers) {
this.candidateStarterUsers = candidateStarterUsers;
}
public List<String> getCandidateStarterGroups() {
return candidateStarterGroups;
}
public void setCandidateStarterGroups(List<String> candidateStarterGroups) {
this.candidateStarterGroups = candidateStarterGroups;
}
public boolean isAsync() {
return async;
}
public void setAsync(boolean async) {
this.async = async;
}
public Map<String, CaseElement> getAllCaseElements() { | return allCaseElements;
}
public void setAllCaseElements(Map<String, CaseElement> allCaseElements) {
this.allCaseElements = allCaseElements;
}
public <T extends PlanItemDefinition> List<T> findPlanItemDefinitionsOfType(Class<T> type) {
return planModel.findPlanItemDefinitionsOfType(type, true);
}
public ReactivateEventListener getReactivateEventListener() {
return reactivateEventListener;
}
public void setReactivateEventListener(ReactivateEventListener reactivateEventListener) {
this.reactivateEventListener = reactivateEventListener;
}
@Override
public List<FlowableListener> getLifecycleListeners() {
return this.lifecycleListeners;
}
@Override
public void setLifecycleListeners(List<FlowableListener> lifecycleListeners) {
this.lifecycleListeners = lifecycleListeners;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\Case.java | 1 |
请完成以下Java代码 | private boolean isProcessDefinitionResource(String resource) {
return resource.endsWith(".bpmn20.xml") || resource.endsWith(".bpmn");
}
protected DeploymentBuilder loadApplicationUpgradeContext(DeploymentBuilder deploymentBuilder) {
if (applicationUpgradeContextService != null) {
loadProjectManifest(deploymentBuilder);
loadEnforcedAppVersion(deploymentBuilder);
}
return deploymentBuilder;
}
private void loadProjectManifest(DeploymentBuilder deploymentBuilder) {
if (applicationUpgradeContextService.hasProjectManifest()) {
try {
deploymentBuilder.setProjectManifest(applicationUpgradeContextService.loadProjectManifest());
} catch (IOException e) {
LOGGER.warn(
"Manifest of application not found. Project release version will not be set for deployment." | );
}
}
}
private void loadEnforcedAppVersion(DeploymentBuilder deploymentBuilder) {
if (applicationUpgradeContextService.hasEnforcedAppVersion()) {
deploymentBuilder.setEnforcedAppVersion(applicationUpgradeContextService.getEnforcedAppVersion());
LOGGER.warn(
"Enforced application version set to " +
applicationUpgradeContextService.getEnforcedAppVersion().toString()
);
} else {
LOGGER.warn("Enforced application version not set.");
}
}
} | repos\Activiti-develop\activiti-core\activiti-spring\src\main\java\org\activiti\spring\autodeployment\AbstractAutoDeploymentStrategy.java | 1 |
请完成以下Java代码 | public final class ModelByIdComparator<ModelType> implements Comparator<ModelType>
{
public static final transient ModelByIdComparator<Object> instance = new ModelByIdComparator<>();
public static final <ModelType> ModelByIdComparator<ModelType> getInstance()
{
@SuppressWarnings("unchecked")
final ModelByIdComparator<ModelType> instanceCasted = (ModelByIdComparator<ModelType>)instance;
return instanceCasted;
}
private ModelByIdComparator()
{
super();
}
@Override
public int compare(final ModelType model1, final ModelType model2)
{
if (model1 == model2)
{
return 0; | }
Check.assumeNotNull(model1, "model1 not null"); // shall not happen
Check.assumeNotNull(model2, "model2 not null"); // shall not happen
final int modelId1 = InterfaceWrapperHelper.getId(model1);
final int modelId2 = InterfaceWrapperHelper.getId(model2);
return modelId1 - modelId2;
}
/**
* Returns a comparator that imposes the reverse ordering of this comparator.
*
* @return a comparator that imposes the reverse ordering of this comparator.
*/
public final Comparator<ModelType> reversed()
{
// NOTE: when we will switch to java8 this method shall be dropped
return Collections.reverseOrder(this);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\model\util\ModelByIdComparator.java | 1 |
请完成以下Java代码 | public void setResources(Resource[] resources) {
this.resources = resources;
}
/**
* The name of the key for the file name in each {@link ExecutionContext}.
* Defaults to "fileName".
* @param keyName the value of the key
*/
public void setKeyName(String keyName) {
this.keyName = keyName;
}
/**
* Assign the filename of each of the injected resources to an
* {@link ExecutionContext}.
*
* @see Partitioner#partition(int) | */
@Override
public Map<String, ExecutionContext> partition(int gridSize) {
Map<String, ExecutionContext> map = new HashMap<>(gridSize);
int i = 0, k = 1;
for (Resource resource : resources) {
ExecutionContext context = new ExecutionContext();
Assert.state(resource.exists(), "Resource does not exist: " + resource);
context.putString(keyName, resource.getFilename());
context.putString("opFileName", "output" + k++ + ".xml");
map.put(PARTITION_KEY + i, context);
i++;
}
return map;
}
} | repos\tutorials-master\spring-batch\src\main\java\com\baeldung\batch\partitioner\CustomMultiResourcePartitioner.java | 1 |
请完成以下Java代码 | public class Anagram {
// This definition only works for single byte encoding character set.
// For multibyte encoding, such as UTF-8, 16, 32 etc.,
// we need to increase this number so that it can contain all possible characters.
private static int CHARACTER_RANGE = 256;
public boolean isAnagramSort(String string1, String string2) {
if (string1.length() != string2.length()) {
return false;
}
char[] a1 = string1.toCharArray();
char[] a2 = string2.toCharArray();
Arrays.sort(a1);
Arrays.sort(a2);
return Arrays.equals(a1, a2);
}
public boolean isAnagramCounting(String string1, String string2) {
if (string1.length() != string2.length()) {
return false;
}
int count[] = new int[CHARACTER_RANGE];
for (int i = 0; i < string1.length(); i++) {
count[string1.charAt(i)]++;
count[string2.charAt(i)]--;
}
for (int i = 0; i < CHARACTER_RANGE; i++) {
if (count[i] != 0) {
return false;
}
}
return true;
}
public boolean isAnagramMultiset(String string1, String string2) { | if (string1.length() != string2.length()) {
return false;
}
Multiset<Character> multiset1 = HashMultiset.create();
Multiset<Character> multiset2 = HashMultiset.create();
for (int i = 0; i < string1.length(); i++) {
multiset1.add(string1.charAt(i));
multiset2.add(string2.charAt(i));
}
return multiset1.equals(multiset2);
}
public boolean isLetterBasedAnagramMultiset(String string1, String string2) {
return isAnagramMultiset(preprocess(string1), preprocess(string2));
}
private String preprocess(String source) {
return source.replaceAll("[^a-zA-Z]", "").toLowerCase();
}
} | repos\tutorials-master\core-java-modules\core-java-string-algorithms-3\src\main\java\com\baeldung\anagram\Anagram.java | 1 |
请完成以下Java代码 | public final class DuplicateLookupObjectException extends ReplicationException
{
private static final long serialVersionUID = 5099228399627874129L;
@Getter
private final List<PO> lookedUpPOs;
private final I_EXP_ReplicationTrxLine trxLineDraft;
@Getter
private final boolean doLookup;
/**
* Constructs a {@link DuplicateLookupObjectException} with <code>lookedUpPOs=null</code>, <code>trxLineDraft=null</code>, and <code>doLookup=false</code>
*/
public DuplicateLookupObjectException(final String adMessage)
{
this(adMessage, null, null, false); | }
public DuplicateLookupObjectException(final String adMessage, final List<PO> lookedUpPOs, final I_EXP_ReplicationTrxLine trxLineDraft, final boolean doLookup)
{
super(adMessage);
this.lookedUpPOs = lookedUpPOs;
this.trxLineDraft = trxLineDraft;
this.doLookup = doLookup;
}
public I_EXP_ReplicationTrxLine getTrxLineDraftOrNull()
{
return trxLineDraft;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\server\rpl\exceptions\DuplicateLookupObjectException.java | 1 |
请完成以下Java代码 | public static ProductId ofRepoId(final int repoId)
{
return new ProductId(repoId);
}
@Nullable
public static ProductId ofRepoIdOrNull(@Nullable final Integer repoId)
{
return repoId != null && repoId > 0 ? new ProductId(repoId) : null;
}
@Nullable
public static ProductId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? new ProductId(repoId) : null;
}
public static Optional<ProductId> optionalOfRepoId(final int repoId) {return Optional.ofNullable(ofRepoIdOrNull(repoId));}
public static Set<ProductId> ofRepoIds(final Collection<Integer> repoIds)
{
return repoIds.stream()
.filter(repoId -> repoId != null && repoId > 0)
.map(ProductId::ofRepoId)
.collect(ImmutableSet.toImmutableSet());
}
public static int toRepoId(@Nullable final ProductId productId)
{
return productId != null ? productId.getRepoId() : -1;
}
public static Set<Integer> toRepoIds(final Collection<ProductId> productIds)
{
return productIds.stream()
.filter(Objects::nonNull)
.map(ProductId::toRepoId)
.collect(ImmutableSet.toImmutableSet()); | }
public static boolean equals(@Nullable final ProductId o1, @Nullable final ProductId o2)
{
return Objects.equals(o1, o2);
}
private ProductId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "productId");
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
public String getAsString() {return String.valueOf(getRepoId());}
public TableRecordReference toTableRecordReference()
{
return TableRecordReference.of(I_M_Product.Table_Name, getRepoId());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\product\ProductId.java | 1 |
请完成以下Java代码 | public static CurrencyId createCurrencyId(@NonNull final CurrencyCode currencyCode)
{
Adempiere.assertUnitTestMode();
return createCurrency(currencyCode).getId();
}
public static Currency createCurrency(@NonNull final CurrencyCode currencyCode)
{
Adempiere.assertUnitTestMode();
return prepareCurrency()
.currencyCode(currencyCode)
.build();
}
public static Currency createCurrency(
@NonNull final CurrencyCode currencyCode,
@NonNull final CurrencyPrecision precision)
{
Adempiere.assertUnitTestMode();
return prepareCurrency()
.currencyCode(currencyCode)
.precision(precision)
.build();
}
@Builder(builderMethodName = "prepareCurrency", builderClassName = "CurrencyBuilder")
private static Currency createCurrency(
@NonNull final CurrencyCode currencyCode, | @Nullable final CurrencyPrecision precision,
@Nullable final CurrencyId currencyId)
{
Adempiere.assertUnitTestMode();
final CurrencyPrecision precisionToUse = precision != null ? precision : CurrencyPrecision.TWO;
final I_C_Currency record = newInstanceOutOfTrx(I_C_Currency.class);
record.setISO_Code(currencyCode.toThreeLetterCode());
record.setCurSymbol(currencyCode.toThreeLetterCode());
record.setIsEuro(currencyCode.isEuro());
record.setStdPrecision(precisionToUse.toInt());
record.setCostingPrecision(precisionToUse.toInt() + 2);
if (currencyId != null)
{
record.setC_Currency_ID(currencyId.getRepoId());
}
else if (CurrencyCode.EUR.equals(currencyCode))
{
record.setC_Currency_ID(CurrencyId.EUR.getRepoId());
}
saveRecord(record);
POJOWrapper.enableStrictValues(record);
return toCurrency(record);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\currency\impl\PlainCurrencyDAO.java | 1 |
请完成以下Java代码 | public PaySelectionLineType extractType(final I_C_PaySelectionLine line)
{
final OrderId orderId = OrderId.ofRepoIdOrNull(line.getC_Order_ID());
final InvoiceId invoiceId = InvoiceId.ofRepoIdOrNull(line.getC_Invoice_ID());
if (orderId != null)
{
return PaySelectionLineType.Order;
}
else if (invoiceId != null)
{
return PaySelectionLineType.Invoice;
}
else
{
throw new AdempiereException("Unsupported pay selection type, for line: ")
.appendParametersToMessage()
.setParameter("line", line.getLine())
.setParameter("InvoiceId", invoiceId)
.setParameter("originalPaymentId", orderId);
}
}
@Override
public I_C_PaySelectionLine getPaySelectionLineById(@NonNull final PaySelectionLineId paySelectionLineId)
{ | return paySelectionDAO.getPaySelectionLinesById(paySelectionLineId);
}
@Override
public List<I_C_PaySelectionLine> retrievePaySelectionLines(@NonNull final I_C_PaySelection paySelection)
{
return paySelectionDAO.retrievePaySelectionLines(paySelection);
}
@Override
public List<I_C_PaySelectionLine> retrievePaySelectionLines(@NonNull final PaySelectionId paySelectionId)
{
return paySelectionDAO.retrievePaySelectionLines(paySelectionId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\payment\impl\PaySelectionBL.java | 1 |
请完成以下Java代码 | private Polyline2D createGateway(GraphicInfo graphicInfo) {
double middleX = graphicInfo.getX() + (graphicInfo.getWidth() / 2);
double middleY = graphicInfo.getY() + (graphicInfo.getHeight() / 2);
Polyline2D gatewayRectangle = new Polyline2D(
new Point2D(graphicInfo.getX(), middleY),
new Point2D(middleX, graphicInfo.getY()),
new Point2D(graphicInfo.getX() + graphicInfo.getWidth(), middleY),
new Point2D(middleX, graphicInfo.getY() + graphicInfo.getHeight()),
new Point2D(graphicInfo.getX(), middleY)
);
return gatewayRectangle;
}
private GraphicInfo createGraphicInfo(double x, double y) {
GraphicInfo graphicInfo = new GraphicInfo();
graphicInfo.setX(x);
graphicInfo.setY(y);
return graphicInfo;
}
class FlowWithContainer {
protected SequenceFlow sequenceFlow;
protected FlowElementsContainer flowContainer;
public FlowWithContainer(SequenceFlow sequenceFlow, FlowElementsContainer flowContainer) {
this.sequenceFlow = sequenceFlow;
this.flowContainer = flowContainer;
} | public SequenceFlow getSequenceFlow() {
return sequenceFlow;
}
public void setSequenceFlow(SequenceFlow sequenceFlow) {
this.sequenceFlow = sequenceFlow;
}
public FlowElementsContainer getFlowContainer() {
return flowContainer;
}
public void setFlowContainer(FlowElementsContainer flowContainer) {
this.flowContainer = flowContainer;
}
}
} | repos\Activiti-develop\activiti-core\activiti-json-converter\src\main\java\org\activiti\editor\language\json\converter\BpmnJsonConverter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Map<String, Object> getVariables() {
return variables;
}
@Override
public Date getDuedate() {
return job.getDuedate();
}
@Override
public String getProcessInstanceId() {
return job.getProcessInstanceId();
}
@Override
public String getExecutionId() {
return job.getExecutionId();
}
@Override
public String getProcessDefinitionId() {
return job.getProcessDefinitionId();
}
@Override
public String getCategory() {
return job.getCategory();
}
@Override
public String getJobType() {
return job.getJobType();
}
@Override
public String getElementId() {
return job.getElementId();
}
@Override
public String getElementName() {
return job.getElementName();
}
@Override
public String getScopeId() {
return job.getScopeId();
}
@Override
public String getSubScopeId() {
return job.getSubScopeId();
}
@Override
public String getScopeType() {
return job.getScopeType();
}
@Override
public String getScopeDefinitionId() {
return job.getScopeDefinitionId();
}
@Override
public String getCorrelationId() {
return job.getCorrelationId();
} | @Override
public boolean isExclusive() {
return job.isExclusive();
}
@Override
public Date getCreateTime() {
return job.getCreateTime();
}
@Override
public String getId() {
return job.getId();
}
@Override
public int getRetries() {
return job.getRetries();
}
@Override
public String getExceptionMessage() {
return job.getExceptionMessage();
}
@Override
public String getTenantId() {
return job.getTenantId();
}
@Override
public String getJobHandlerType() {
return job.getJobHandlerType();
}
@Override
public String getJobHandlerConfiguration() {
return job.getJobHandlerConfiguration();
}
@Override
public String getCustomValues() {
return job.getCustomValues();
}
@Override
public String getLockOwner() {
return job.getLockOwner();
}
@Override
public Date getLockExpirationTime() {
return job.getLockExpirationTime();
}
@Override
public String toString() {
return new StringJoiner(", ", AcquiredExternalWorkerJobImpl.class.getSimpleName() + "[", "]")
.add("job=" + job)
.toString();
}
} | repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\AcquiredExternalWorkerJobImpl.java | 2 |
请完成以下Java代码 | default SyncGraphQlClientInterceptor andThen(SyncGraphQlClientInterceptor interceptor) {
return new SyncGraphQlClientInterceptor() {
@Override
public ClientGraphQlResponse intercept(ClientGraphQlRequest request, Chain chain) {
return SyncGraphQlClientInterceptor.this.intercept(
request, (nextRequest) -> interceptor.intercept(nextRequest, chain));
}
};
}
/**
* Contract to delegate to the rest of a blocking execution chain.
*/ | interface Chain {
/**
* Delegate to the rest of the chain to perform the request.
* @param request the request to perform
* @return the GraphQL response
* @throws GraphQlTransportException in case of errors due to transport or
* other issues related to encoding and decoding the request and response.
* @see GraphQlClient.RequestSpec#executeSync()
*/
ClientGraphQlResponse next(ClientGraphQlRequest request);
}
} | repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\client\SyncGraphQlClientInterceptor.java | 1 |
请完成以下Java代码 | final class ShipmentScheduleSegmentChangedProcessor
{
private static final String TRX_PROPERTYNAME = ShipmentScheduleSegmentChangedProcessor.class.getName();
public static ShipmentScheduleSegmentChangedProcessor getOrCreateIfThreadInheritedElseNull(
@NonNull final ShipmentScheduleInvalidateBL shipmentScheduleInvalidator)
{
final ITrxManager trxManager = Services.get(ITrxManager.class);
final ITrx trx = trxManager.getThreadInheritedTrx(OnTrxMissingPolicy.ReturnTrxNone);
if (trxManager.isNull(trx))
{
return null;
}
return getOrCreate(trx, shipmentScheduleInvalidator);
}
private static ShipmentScheduleSegmentChangedProcessor getOrCreate(
@NonNull final ITrx trx,
@NonNull final ShipmentScheduleInvalidateBL shipmentScheduleInvalidator)
{
ShipmentScheduleSegmentChangedProcessor processor = trx.getProperty(TRX_PROPERTYNAME);
if (processor == null)
{
processor = new ShipmentScheduleSegmentChangedProcessor(shipmentScheduleInvalidator);
trx.setProperty(TRX_PROPERTYNAME, processor);
// register our listener: we will actually fire the storage segment changed when the transaction is commited
// Listens the {@link ITrx} and on commit actually fires the segment changed event
trx.getTrxListenerManager()
.newEventListener(TrxEventTiming.AFTER_COMMIT)
.invokeMethodJustOnce(false) // invoke the handling method on *every* commit, because that's how it was and I can't check now if it's really needed
.registerHandlingMethod(innerTrx -> {
final ShipmentScheduleSegmentChangedProcessor innerProcessor = innerTrx.getProperty(TRX_PROPERTYNAME);
if (innerProcessor == null)
{
// nothing to do
return;
}
innerProcessor.process();
});
}
return processor;
}
private final List<IShipmentScheduleSegment> segments = new ArrayList<>();
private final ShipmentScheduleInvalidateBL shipmentScheduleInvalidator;
private ShipmentScheduleSegmentChangedProcessor(@NonNull final ShipmentScheduleInvalidateBL shipmentScheduleInvalidator) | {
this.shipmentScheduleInvalidator = shipmentScheduleInvalidator;
}
private void process()
{
if (segments.isEmpty())
{
return;
}
final List<IShipmentScheduleSegment> segmentsCopy = new ArrayList<>(segments);
segments.clear();
shipmentScheduleInvalidator.flagSegmentForRecompute(segmentsCopy);
}
public void addSegment(final IShipmentScheduleSegment segment)
{
if (segment == null)
{
return;
}
this.segments.add(segment);
}
public void addSegments(final Collection<IShipmentScheduleSegment> segments)
{
if (segments == null || segments.isEmpty())
{
return;
}
this.segments.addAll(segments);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\invalidation\impl\ShipmentScheduleSegmentChangedProcessor.java | 1 |
请完成以下Java代码 | private void assertUOMOrSourceUOM(@NonNull final UomId uomId)
{
if (!getUomId().equals(uomId) && !getSourceUomId().equals(uomId))
{
throw new QuantitiesUOMNotMatchingExpection("UOMs are not compatible")
.appendParametersToMessage()
.setParameter("Qty.UOM", getUomId())
.setParameter("assertUOM", uomId);
}
}
@NonNull
public BigDecimal toBigDecimalAssumingUOM(@NonNull final UomId uomId)
{
assertUOMOrSourceUOM(uomId);
return getUomId().equals(uomId) ? toBigDecimal() : getSourceQty();
}
public List<Quantity> spreadEqually(final int count)
{
if (count <= 0)
{
throw new AdempiereException("count shall be greater than zero, but it was " + count);
}
else if (count == 1)
{
return ImmutableList.of(this);
} | else // count > 1
{
final ImmutableList.Builder<Quantity> result = ImmutableList.builder();
final Quantity qtyPerPart = divide(count);
Quantity qtyRemainingToSpread = this;
for (int i = 1; i <= count; i++)
{
final boolean isLast = i == count;
if (isLast)
{
result.add(qtyRemainingToSpread);
}
else
{
result.add(qtyPerPart);
qtyRemainingToSpread = qtyRemainingToSpread.subtract(qtyPerPart);
}
}
return result.build();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\quantity\Quantity.java | 1 |
请完成以下Java代码 | public Criteria andLastUpdateNotBetween(Date value1, Date value2) {
addCriterion("last_update not between", value1, value2, "lastUpdate");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true; | }
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
} | repos\spring-boot-quick-master\quick-multi-data\src\main\java\com\quick\mulit\entity\primary\CityExample.java | 1 |
请完成以下Java代码 | private void shutdown(Connector connector, boolean getResult) {
Future<Void> result;
try {
result = connector.shutdown();
}
catch (NoSuchMethodError ex) {
Method shutdown = ReflectionUtils.findMethod(connector.getClass(), "shutdown");
Assert.state(shutdown != null, "'shutdown' must not be null");
result = (Future<Void>) ReflectionUtils.invokeMethod(shutdown, connector);
}
if (getResult) {
try {
Assert.state(result != null, "'result' must not be null");
result.get();
}
catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
catch (ExecutionException ex) {
// Continue
}
}
}
private boolean isJetty10() {
try {
return CompletableFuture.class.equals(Connector.class.getMethod("shutdown").getReturnType());
}
catch (Exception ex) {
return false;
} | }
private void awaitShutdown(GracefulShutdownCallback callback) {
while (!this.aborted && this.activeRequests.get() > 0) {
sleep(100);
}
if (this.aborted) {
logger.info("Graceful shutdown aborted with one or more requests still active");
callback.shutdownComplete(GracefulShutdownResult.REQUESTS_ACTIVE);
}
else {
logger.info("Graceful shutdown complete");
callback.shutdownComplete(GracefulShutdownResult.IDLE);
}
}
private void sleep(long millis) {
try {
Thread.sleep(millis);
}
catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
void abort() {
this.aborted = true;
}
} | repos\spring-boot-4.0.1\module\spring-boot-jetty\src\main\java\org\springframework\boot\jetty\GracefulShutdown.java | 1 |
请完成以下Java代码 | protected String doIt() throws Exception
{
final DATEVExportFormat exportFormat = exportFormatRepo.getById(datevExportFormatId);
final I_DATEV_Export datevExport = getRecord(I_DATEV_Export.class);
final IExportDataSource dataSource = createDataSource(exportFormat, datevExport.getDATEV_Export_ID());
final ByteArrayOutputStream out = new ByteArrayOutputStream();
DATEVCsvExporter.builder()
.exportFormat(exportFormat)
.dataSource(dataSource)
.build()
.export(out);
getResult().setReportData(
new ByteArrayResource(out.toByteArray()), // data
buildFilename(datevExport), // filename
"text/csv"); // content type
return MSG_OK;
}
private IExportDataSource createDataSource(@NonNull final DATEVExportFormat exportFormat, final int datevExportId)
{
Check.assume(datevExportId > 0, "datevExportId > 0");
final JdbcExporterBuilder builder = new JdbcExporterBuilder(I_DATEV_ExportLine.Table_Name) | .addEqualsWhereClause(I_DATEV_ExportLine.COLUMNNAME_DATEV_Export_ID, datevExportId)
.addEqualsWhereClause(I_DATEV_ExportLine.COLUMNNAME_IsActive, true)
.addOrderBy(I_DATEV_ExportLine.COLUMNNAME_DocumentNo)
.addOrderBy(I_DATEV_ExportLine.COLUMNNAME_DATEV_ExportLine_ID);
exportFormat
.getColumns()
.forEach(formatColumn -> builder.addField(formatColumn.getCsvHeaderName(), formatColumn.getColumnName()));
return builder.createDataSource();
}
private static String buildFilename(final I_DATEV_Export datevExport)
{
final DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");
final Timestamp dateAcctFrom = datevExport.getDateAcctFrom();
final Timestamp dateAcctTo = datevExport.getDateAcctTo();
return Joiner.on("_")
.skipNulls()
.join("datev",
dateAcctFrom != null ? dateFormatter.format(TimeUtil.asLocalDate(dateAcctFrom)) : null,
dateAcctTo != null ? dateFormatter.format(TimeUtil.asLocalDate(dateAcctTo)) : null)
+ ".csv";
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.datev\src\main\java\de\metas\datev\process\DATEV_ExportFile.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class HuId implements RepoIdAware
{
public static HuId ofRepoId(final int repoId)
{
return new HuId(repoId);
}
@JsonCreator
public static HuId ofObject(@NonNull final Object object)
{
return RepoIdAwares.ofObject(object, HuId.class);
}
@Nullable
public static HuId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? ofRepoId(repoId) : null;
}
public static int toRepoId(@Nullable final HuId huId)
{
return huId != null ? huId.getRepoId() : -1;
}
public static Set<HuId> ofRepoIds(@NonNull final Collection<Integer> repoIds)
{
return repoIds.stream().map(HuId::ofRepoId).collect(ImmutableSet.toImmutableSet());
}
public static Set<Integer> toRepoIds(@NonNull final Collection<HuId> huIds)
{
return huIds.stream().map(HuId::getRepoId).collect(ImmutableSet.toImmutableSet());
}
public static Set<HuId> fromRepoIds(@Nullable final Collection<Integer> huRepoIds)
{
if (huRepoIds == null || huRepoIds.isEmpty())
{
return ImmutableSet.of();
}
return huRepoIds.stream().map(HuId::ofRepoIdOrNull).filter(Objects::nonNull).collect(ImmutableSet.toImmutableSet());
}
public static HuId ofHUValue(@NonNull final String huValue)
{
try
{
return ofRepoId(Integer.parseInt(huValue));
}
catch (final Exception ex)
{
final AdempiereException metasfreshException = new AdempiereException("Invalid HUValue `" + huValue + "`. It cannot be converted to M_HU_ID.");
metasfreshException.addSuppressed(ex); | throw metasfreshException;
}
}
public static HuId ofHUValueOrNull(@Nullable final String huValue)
{
final String huValueNorm = StringUtils.trimBlankToNull(huValue);
if (huValueNorm == null) {return null;}
try
{
return ofRepoIdOrNull(NumberUtils.asIntOrZero(huValueNorm));
}
catch (final Exception ex)
{
return null;
}
}
public String toHUValue() {return String.valueOf(repoId);}
int repoId;
private HuId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "M_HU_ID");
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
public static boolean equals(@Nullable final HuId o1, @Nullable final HuId o2)
{
return Objects.equals(o1, o2);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\handlingunits\HuId.java | 2 |
请完成以下Java代码 | public void sendSimpleMessage(String to, String subject, String text) {
try {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(NOREPLY_ADDRESS);
message.setTo(to);
message.setSubject(subject);
message.setText(text);
emailSender.send(message);
} catch (MailException exception) {
exception.printStackTrace();
}
}
@Override
public void sendMessageWithAttachment(String to,
String subject,
String text,
String pathToAttachment) {
try {
MimeMessage message = emailSender.createMimeMessage();
// pass 'true' to the constructor to create a multipart message
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(NOREPLY_ADDRESS);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(text);
FileSystemResource file = new FileSystemResource(new File(pathToAttachment)); | helper.addAttachment("Invoice", file);
emailSender.send(message);
} catch (MessagingException e) {
e.printStackTrace();
}
}
@Override
public void sendMessageWithInputStreamAttachment(
String to, String subject, String text, String attachmentName, InputStream attachmentStream) {
try {
MimeMessage message = emailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(NOREPLY_ADDRESS);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(text);
// Add the attachment from InputStream
helper.addAttachment(attachmentName, new InputStreamResource(attachmentStream));
emailSender.send(message);
} catch (MessagingException e) {
e.printStackTrace();
}
}
} | repos\tutorials-master\spring-web-modules\spring-mvc-basics\src\main\java\com\baeldung\spring\mail\EmailServiceImpl.java | 1 |
请完成以下Java代码 | public void convertUsingCustomisedJOOQ() throws ClassNotFoundException, SQLException {
Class.forName("org.h2.Driver");
Connection dbConnection = DriverManager.getConnection("jdbc:h2:mem:rs2jdbc", "user", "password");
// Create a table
Statement stmt = dbConnection.createStatement();
stmt.execute("CREATE TABLE words AS SELECT * FROM CSVREAD('./example.csv')");
ResultSet resultSet = stmt.executeQuery("SELECT * FROM words");
JSONArray result1 = resultSet2JdbcUsingCustomisedJOOQ(resultSet, dbConnection);
System.out.println(result1);
resultSet.close();
}
public static JSONArray resultSet2JdbcWithoutJOOQ(ResultSet resultSet) throws SQLException {
ResultSetMetaData md = resultSet.getMetaData();
int numCols = md.getColumnCount();
List<String> colNames = IntStream.range(0, numCols)
.mapToObj(i -> {
try {
return md.getColumnName(i + 1);
} catch (SQLException e) {
e.printStackTrace();
return "?";
}
})
.collect(Collectors.toList());
JSONArray result = new JSONArray();
while (resultSet.next()) {
JSONObject row = new JSONObject();
colNames.forEach(cn -> {
try {
row.put(cn, resultSet.getObject(cn));
} catch (JSONException | SQLException e) {
e.printStackTrace();
}
});
result.put(row);
}
return result;
}
public static JSONObject resultSet2JdbcUsingJOOQDefaultApproach(ResultSet resultSet, Connection dbConnection) throws SQLException {
JSONObject result = new JSONObject(DSL.using(dbConnection)
.fetch(resultSet)
.formatJSON());
return result;
}
public static JSONArray resultSet2JdbcUsingCustomisedJOOQ(ResultSet resultSet, Connection dbConnection) throws SQLException {
ResultSetMetaData md = resultSet.getMetaData();
int numCols = md.getColumnCount();
List<String> colNames = IntStream.range(0, numCols) | .mapToObj(i -> {
try {
return md.getColumnName(i + 1);
} catch (SQLException e) {
e.printStackTrace();
return "?";
}
})
.collect(Collectors.toList());
List<JSONObject> json = DSL.using(dbConnection)
.fetch(resultSet)
.map(new RecordMapper<Record, JSONObject>() {
@Override
public JSONObject map(Record r) {
JSONObject obj = new JSONObject();
colNames.forEach(cn -> obj.put(cn, r.get(cn)));
return obj;
}
});
return new JSONArray(json);
}
} | repos\tutorials-master\persistence-modules\core-java-persistence-2\src\main\java\com\baeldung\resultset2json\ResultSet2JSON.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.