instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public String getNewState() { return PlanItemInstanceState.ASYNC_ACTIVE; } @Override protected void internalExecute() { planItemInstanceEntity.setLastStartedTime(getCurrentTime(commandContext)); CommandContextUtil.getCmmnHistoryManager(commandContext).recordPlanItemInstanceStarted(planItemInstanceEntity); createAsyncJob((Task) planItemInstanceEntity.getPlanItem().getPlanItemDefinition()); } protected void createAsyncJob(Task task) { CmmnEngineConfiguration cmmnEngineConfiguration = CommandContextUtil.getCmmnEngineConfiguration(commandContext); JobService jobService = cmmnEngineConfiguration.getJobServiceConfiguration().getJobService(); JobEntity job = JobUtil.createJob(planItemInstanceEntity, task, AsyncActivatePlanItemInstanceJobHandler.TYPE, cmmnEngineConfiguration); job.setJobHandlerConfiguration(entryCriterionId); jobService.createAsyncJob(job, task.isExclusive()); jobService.scheduleAsyncJob(job); if (cmmnEngineConfiguration.isLoggingSessionEnabled()) { CmmnLoggingSessionUtil.addAsyncActivityLoggingData("Created async job for " + planItemInstanceEntity.getPlanItemDefinitionId() + ", with job id " + job.getId(), CmmnLoggingSessionConstants.TYPE_SERVICE_TASK_ASYNC_JOB, job, planItemInstanceEntity.getPlanItemDefinition(), planItemInstanceEntity, cmmnEngineConfiguration.getObjectMapper()); } }
@Override public String toString() { PlanItem planItem = planItemInstanceEntity.getPlanItem(); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("[Async activate PlanItem] "); stringBuilder.append(planItem); if (entryCriterionId != null) { stringBuilder.append(" via entry criterion ").append(entryCriterionId); } return stringBuilder.toString(); } @Override public String getOperationName() { return "[Async activate plan item]"; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\agenda\operation\ActivateAsyncPlanItemInstanceOperation.java
1
请完成以下Java代码
public int getC_AcctSchema_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_AcctSchema_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Buchungsdatum. @param DateAcct Accounting Date */ @Override public void setDateAcct (java.sql.Timestamp DateAcct) { set_ValueNoCheck (COLUMNNAME_DateAcct, DateAcct); } /** Get Buchungsdatum. @return Accounting Date */ @Override public java.sql.Timestamp getDateAcct () { return (java.sql.Timestamp)get_Value(COLUMNNAME_DateAcct); } /** Set Accounting Fact. @param Fact_Acct_ID Accounting Fact */ @Override public void setFact_Acct_ID (int Fact_Acct_ID) { if (Fact_Acct_ID < 1) set_ValueNoCheck (COLUMNNAME_Fact_Acct_ID, null); else set_ValueNoCheck (COLUMNNAME_Fact_Acct_ID, Integer.valueOf(Fact_Acct_ID)); } /** Get Accounting Fact. @return Accounting Fact */ @Override public int getFact_Acct_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Fact_Acct_ID); if (ii == null) return 0; return ii.intValue(); }
/** * PostingType AD_Reference_ID=125 * Reference name: _Posting Type */ public static final int POSTINGTYPE_AD_Reference_ID=125; /** Actual = A */ public static final String POSTINGTYPE_Actual = "A"; /** Budget = B */ public static final String POSTINGTYPE_Budget = "B"; /** Commitment = E */ public static final String POSTINGTYPE_Commitment = "E"; /** Statistical = S */ public static final String POSTINGTYPE_Statistical = "S"; /** Reservation = R */ public static final String POSTINGTYPE_Reservation = "R"; /** Actual Year End = Y */ public static final String POSTINGTYPE_ActualYearEnd = "Y"; /** Set Buchungsart. @param PostingType Die Art des gebuchten Betrages dieser Transaktion */ @Override public void setPostingType (java.lang.String PostingType) { set_ValueNoCheck (COLUMNNAME_PostingType, PostingType); } /** Get Buchungsart. @return Die Art des gebuchten Betrages dieser Transaktion */ @Override public java.lang.String getPostingType () { return (java.lang.String)get_Value(COLUMNNAME_PostingType); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-gen\de\metas\acct\model\X_Fact_Acct_EndingBalance.java
1
请完成以下Java代码
public T getNotNull() {return Check.assumeNotNull(get(), "Supplier is expected to return non null value");} /** * @return memorized value or <code>null</code> if not initialized */ @Nullable public T peek() { synchronized (this) { return value; } } /** * Forget memorized value * * @return current value if any */ @Nullable public T forget() { // https://github.com/metasfresh/metasfresh-webui-api/issues/787 - similar to the code of get(); // if the instance known to not be initialized // then don't attempt to acquire lock (and to other time consuming stuff..) if (initialized) { synchronized (this) { if (initialized) {
final T valueOld = this.value; initialized = false; value = null; return valueOld; } } } return null; } /** * @return true if this supplier has a value memorized */ public boolean isInitialized() { return initialized; } @Override public String toString() { return "ExtendedMemorizingSupplier[" + delegate + "]"; } private static final long serialVersionUID = 0; }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\lang\ExtendedMemorizingSupplier.java
1
请完成以下Java代码
public void closeOthers(Window window) { for (Window w : windows) { w.removeComponentListener(eventListener); w.removeWindowListener(eventListener); if (!w.equals(window)) { w.dispose(); } } windows = new ArrayList<>(); add(window); } /** * Remove window * * @param window */ public void remove(Window window) { if (windows.remove(window)) { window.removeComponentListener(eventListener); window.removeWindowListener(eventListener); } } /** * Get list of windows managed by this window manager * * @return Array of windows */ public Window[] getWindows() { Window[] a = new Window[windows.size()]; return windows.toArray(a); } /** * @return Number of windows managed by this window manager */ public int getWindowCount() { return windows.size(); } /** * Find window by ID * * @param AD_Window_ID * @return AWindow reference, null if not found */ public AWindow find(final AdWindowId adWindowId) { for (Window w : windows) { if (w instanceof AWindow) { AWindow a = (AWindow)w; if (AdWindowId.equals(a.getAdWindowId(), adWindowId)) { return a; } } } return null; } public FormFrame findForm(int AD_FORM_ID) { for (Window w : windows) { if (w instanceof FormFrame) { FormFrame ff = (FormFrame)w; if (ff.getAD_Form_ID() == AD_FORM_ID) { return ff; } } } return null; } } class WindowEventListener implements ComponentListener, WindowListener { WindowManager windowManager; protected WindowEventListener(WindowManager windowManager) { this.windowManager = windowManager; } @Override public void componentHidden(ComponentEvent e) { Component c = e.getComponent(); if (c instanceof Window) { c.removeComponentListener(this); ((Window)c).removeWindowListener(this); windowManager.remove((Window)c); } } @Override public void componentMoved(ComponentEvent e)
{ } @Override public void componentResized(ComponentEvent e) { } @Override public void componentShown(ComponentEvent e) { } @Override public void windowActivated(WindowEvent e) { } @Override public void windowClosed(WindowEvent e) { Window w = e.getWindow(); if (w instanceof Window) { w.removeComponentListener(this); w.removeWindowListener(this); windowManager.remove(w); } } @Override public void windowClosing(WindowEvent e) { } @Override public void windowDeactivated(WindowEvent e) { } @Override public void windowDeiconified(WindowEvent e) { } @Override public void windowIconified(WindowEvent e) { } @Override public void windowOpened(WindowEvent e) { } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\WindowManager.java
1
请完成以下Java代码
public BigDecimal getA_Salvage_Value () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_A_Salvage_Value); if (bd == null) return Env.ZERO; return bd; } /** Set Split Percentage. @param A_Split_Percent Split Percentage */ public void setA_Split_Percent (BigDecimal A_Split_Percent) { set_Value (COLUMNNAME_A_Split_Percent, A_Split_Percent); } /** Get Split Percentage. @return Split Percentage */ public BigDecimal getA_Split_Percent () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_A_Split_Percent); if (bd == null) return Env.ZERO; return bd; } public I_C_AcctSchema getC_AcctSchema() throws RuntimeException { return (I_C_AcctSchema)MTable.get(getCtx(), I_C_AcctSchema.Table_Name) .getPO(getC_AcctSchema_ID(), get_TrxName()); } /** Set Accounting Schema. @param C_AcctSchema_ID Rules for accounting */ public void setC_AcctSchema_ID (int C_AcctSchema_ID) { if (C_AcctSchema_ID < 1) set_Value (COLUMNNAME_C_AcctSchema_ID, null); else set_Value (COLUMNNAME_C_AcctSchema_ID, Integer.valueOf(C_AcctSchema_ID)); } /** Get Accounting Schema. @return Rules for accounting */ public int getC_AcctSchema_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_AcctSchema_ID); if (ii == null) return 0; return ii.intValue(); } /** PostingType AD_Reference_ID=125 */ public static final int POSTINGTYPE_AD_Reference_ID=125; /** Actual = A */ public static final String POSTINGTYPE_Actual = "A"; /** Budget = B */ public static final String POSTINGTYPE_Budget = "B"; /** Commitment = E */ public static final String POSTINGTYPE_Commitment = "E";
/** Statistical = S */ public static final String POSTINGTYPE_Statistical = "S"; /** Reservation = R */ public static final String POSTINGTYPE_Reservation = "R"; /** Set PostingType. @param PostingType The type of posted amount for the transaction */ public void setPostingType (String PostingType) { set_Value (COLUMNNAME_PostingType, PostingType); } /** Get PostingType. @return The type of posted amount for the transaction */ public String getPostingType () { return (String)get_Value(COLUMNNAME_PostingType); } /** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Asset_Acct.java
1
请完成以下Java代码
public String toString() { return "Movie [imdbId=" + imdbId + ", director=" + director + ", actors=" + actors + "]"; } public String getImdbID() { return imdbId; } public void setImdbID(String imdbID) { this.imdbId = imdbID; } public String getDirector() { return director; }
public void setDirector(String director) { this.director = director; } public List<ActorGson> getActors() { return actors; } public void setActors(List<ActorGson> actors) { this.actors = actors; } }
repos\tutorials-master\json-modules\gson\src\main\java\com\baeldung\gson\entities\Movie.java
1
请在Spring Boot框架中完成以下Java代码
private IXlsDataSource retrieveDataSource(final ReportContext reportContext) { // // Get SQL Statement final String sql = reportContext.getSQLStatement(); if (Check.isEmpty(sql, true)) { throw new AdempiereException("SQL Statement is not set in " + reportContext); } // // Parse the SQL Statement final IStringExpression sqlExpression = Services.get(IExpressionFactory.class).compile(sql, IStringExpression.class); final Evaluatee evalCtx = createEvaluationContext(reportContext); String sqlFinal = sqlExpression.evaluate(evalCtx, OnVariableNotFound.Fail); // // Add debugging query info { String sqlQueryInfo = "jxls report=" + reportContext.getReportTemplatePath() + ", AD_PInstance_ID=" + reportContext.getPinstanceId(); sqlQueryInfo = "/* " + sqlQueryInfo.replace("/*", " ").replace("*/", " ") + " */ "; sqlFinal = sqlQueryInfo + sqlFinal; } // // Create & return the data source return JdbcXlsDataSource.of(sqlFinal); } private Evaluatee createEvaluationContext(final ReportContext reportContext) { final Map<String, Object> reportContextAsMap = createContextAsMap(reportContext); final Evaluatee2 reportContextAsEvaluatee = Evaluatees.ofMap(reportContextAsMap); final Evaluatee ctxEvaluatee = Evaluatees.ofCtx(reportContext.getCtx(), Env.WINDOW_MAIN, false); // onlyWindow=false return Evaluatees.compose(reportContextAsEvaluatee, ctxEvaluatee); } private Map<String, Object> createContextAsMap(final ReportContext reportContext) { final Collection<ProcessInfoParameter> processInfoParams = reportContext.getProcessInfoParameters(); if (processInfoParams.isEmpty()) { return ImmutableMap.of(); } final TreeMap<String, Object> map = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
map.put("AD_Process_ID", reportContext.getAD_Process_ID()); map.put("AD_PInstance_ID", PInstanceId.toRepoId(reportContext.getPinstanceId())); map.put("AD_Table_ID", reportContext.getAD_Table_ID()); map.put("Record_ID", reportContext.getRecord_ID()); map.put("AD_Language", reportContext.getAD_Language()); map.put("OutputType", reportContext.getOutputType()); for (final ProcessInfoParameter param : processInfoParams) { final String parameterName = param.getParameterName(); map.put(parameterName, param.getParameter()); map.put(parameterName + "_Info", param.getInfo()); map.put(parameterName + "_From", param.getParameter()); map.put(parameterName + "_From_Info", param.getInfo()); map.put(parameterName + "_To", param.getParameter_To()); map.put(parameterName + "_To_Info", param.getInfo_To()); } return Collections.unmodifiableMap(map); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.report\metasfresh-report-service\src\main\java\de\metas\report\xls\engine\XlsReportEngine.java
2
请在Spring Boot框架中完成以下Java代码
public class AccountServiceImpl implements AccountService { @Autowired private AccountDao accountDao; @Override @Transactional(propagation = Propagation.REQUIRES_NEW) // <1> 开启新事物 public void reduceBalance(Long userId, Integer price) throws Exception { log.info("[reduceBalance] 当前 XID: {}", RootContext.getXID()); // <2> 检查余额 checkBalance(userId, price); log.info("[reduceBalance] 开始扣减用户 {} 余额", userId); // <3> 扣除余额 int updateCount = accountDao.reduceBalance(price); // 扣除成功
if (updateCount == 0) { log.warn("[reduceBalance] 扣除用户 {} 余额失败", userId); throw new Exception("余额不足"); } log.info("[reduceBalance] 扣除用户 {} 余额成功", userId); } private void checkBalance(Long userId, Integer price) throws Exception { log.info("[checkBalance] 检查用户 {} 余额", userId); Integer balance = accountDao.getBalance(userId); if (balance < price) { log.warn("[checkBalance] 用户 {} 余额不足,当前余额:{}", userId, balance); throw new Exception("余额不足"); } } }
repos\springboot-demo-master\seata\seata-balance\src\main\java\com\et\seata\balance\service\AccountServiceImpl.java
2
请完成以下Java代码
public final class PayPalClientResponse<ResultType, ErrorType> { public static <ResponseType, ErrorType> PayPalClientResponse<ResponseType, ErrorType> ofResult(@NonNull final ResponseType response) { final ErrorType error = null; Throwable errorCause = null; return new PayPalClientResponse<>(response, error, errorCause); } public static <ResultType, ErrorType> PayPalClientResponse<ResultType, ErrorType> ofError( @NonNull final ErrorType error, @Nullable Throwable errorCause) { final ResultType result = null; return new PayPalClientResponse<>(result, error, errorCause); } private final ResultType result; private final ErrorType error; private final Throwable errorCause; private PayPalClientResponse( final ResultType result, final ErrorType error, Throwable errorCause) { this.result = result; this.error = error; this.errorCause = errorCause; } public boolean isOK() { return error == null; } public boolean isError() { return error != null; }
public ResultType getResult() { if (result == null) { throw toException(); } return result; } public ErrorType getError() { if (error == null) { throw new AdempiereException("Not an error response: " + this); } return error; } public AdempiereException toException() { if (error == null) { throw new AdempiereException("Not an error response: " + this); } if (errorCause != null) { return AdempiereException.wrapIfNeeded(errorCause) .setParameter("error", error); } else { return new AdempiereException(error.toString()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.paypal\src\main\java\de\metas\payment\paypal\PayPalClientResponse.java
1
请完成以下Java代码
private Optional<AlbertaBPartnerReference> toOptionalAlbertaBPartnerReference(final @NonNull AlbertaRole albertaRole) { final AlbertaBPartnerReference.AlbertaBPartnerReferenceBuilder builder = AlbertaBPartnerReference.builder(); builder.albertaRoleType(albertaRole.getRole()); final GetExternalReferenceByRecordIdReq getExternalRefRequest = GetExternalReferenceByRecordIdReq.builder() .externalReferenceType(BPartnerExternalReferenceType.BPARTNER) .externalSystem(externalSystemRepository.getByType(ExternalSystemType.Alberta)) .recordId(albertaRole.getBPartnerId().getRepoId()) .build(); return externalReferenceRepository.getExternalReferenceByMFReference(getExternalRefRequest) .map(ExternalReference::getExternalReference) .map(externalRef -> builder.externalReference(externalRef).build()); } @NonNull private JsonExternalSystemRequest toSyncBPartnerExternalSystemRequest( @NonNull final OrgId orgId, @NonNull final ExternalSystemAlbertaConfigId configId, @NonNull final PInstanceId pInstanceId, @NonNull final AlbertaBPartnerReference albertaBPartnerReference) { final ExternalSystemParentConfig config = externalSystemConfigDAO.getById(configId); return JsonExternalSystemRequest.builder() .externalSystemConfigId(JsonMetasfreshId.of(config.getId().getRepoId())) .externalSystemName(JsonExternalSystemName.of(ExternalSystemType.Alberta.getValue())) .parameters(extractParameters(config, albertaBPartnerReference)) .orgCode(orgDAO.getById(orgId).getValue()) .command(EXTERNAL_SYSTEM_COMMAND_SYNC_BPARTNER) .adPInstanceId(JsonMetasfreshId.of(PInstanceId.toRepoId(pInstanceId)))
.traceId(externalSystemConfigService.getTraceId()) .externalSystemChildConfigValue(config.getChildConfig().getValue()) .writeAuditEndpoint(config.getAuditEndpointIfEnabled()) .build(); } @NonNull private Map<String, String> extractParameters( @NonNull final ExternalSystemParentConfig externalSystemParentConfig, @NonNull final AlbertaBPartnerReference albertaBPartnerReference) { final ExternalSystemAlbertaConfig albertaConfig = ExternalSystemAlbertaConfig.cast(externalSystemParentConfig.getChildConfig()); final Map<String, String> parameters = new HashMap<>(); parameters.put(ExternalSystemConstants.PARAM_API_KEY, albertaConfig.getApiKey()); parameters.put(ExternalSystemConstants.PARAM_BASE_PATH, albertaConfig.getBaseUrl()); parameters.put(ExternalSystemConstants.PARAM_TENANT, albertaConfig.getTenant()); parameters.put(ExternalSystemConstants.PARAM_ALBERTA_ID, albertaBPartnerReference.getExternalReference()); parameters.put(ExternalSystemConstants.PARAM_ALBERTA_ROLE, albertaBPartnerReference.getAlbertaRoleType().name()); parameters.put(ExternalSystemConstants.PARAM_CHILD_CONFIG_VALUE, albertaConfig.getValue()); return parameters; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\process\InvokeAlbertaService.java
1
请完成以下Java代码
public Activity getAttachedToRef() { return attachedToRef; } public void setAttachedToRef(Activity attachedToRef) { this.attachedToRef = attachedToRef; } public String getAttachedToRefId() { return attachedToRefId; } public void setAttachedToRefId(String attachedToRefId) { this.attachedToRefId = attachedToRefId; } public boolean isCancelActivity() { return cancelActivity; } public void setCancelActivity(boolean cancelActivity) { this.cancelActivity = cancelActivity; } public boolean hasErrorEventDefinition() {
if (this.eventDefinitions != null && !this.eventDefinitions.isEmpty()) { return this.eventDefinitions.stream().anyMatch(eventDefinition -> ErrorEventDefinition.class.isInstance(eventDefinition) ); } return false; } public BoundaryEvent clone() { BoundaryEvent clone = new BoundaryEvent(); clone.setValues(this); return clone; } public void setValues(BoundaryEvent otherEvent) { super.setValues(otherEvent); setAttachedToRefId(otherEvent.getAttachedToRefId()); setAttachedToRef(otherEvent.getAttachedToRef()); setCancelActivity(otherEvent.isCancelActivity()); } }
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\BoundaryEvent.java
1
请完成以下Java代码
public class UserDto1 { private long id; private String email; // constructors public UserDto1() { super(); } public UserDto1(long id, String email) { super(); this.id = id; this.email = email; } // getters and setters public long getId() { return id;
} public void setId(long id) { this.id = id; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @Override public String toString() { return "UserDto [id=" + id + ", email=" + email + "]"; } }
repos\tutorials-master\libraries-data-2\src\main\java\com\baeldung\jmapper\UserDto1.java
1
请完成以下Java代码
public void setM_ProductPrice_ID (int M_ProductPrice_ID) { if (M_ProductPrice_ID < 1) set_ValueNoCheck (COLUMNNAME_M_ProductPrice_ID, null); else set_ValueNoCheck (COLUMNNAME_M_ProductPrice_ID, Integer.valueOf(M_ProductPrice_ID)); } /** Get Produkt-Preis. @return Produkt-Preis */ @Override public int getM_ProductPrice_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_ProductPrice_ID); if (ii == null) return 0; return ii.intValue(); } /** Set packingmaterialname. @param packingmaterialname packingmaterialname */ @Override public void setpackingmaterialname (java.lang.String packingmaterialname) { set_ValueNoCheck (COLUMNNAME_packingmaterialname, packingmaterialname); } /** Get packingmaterialname. @return packingmaterialname */ @Override public java.lang.String getpackingmaterialname () { return (java.lang.String)get_Value(COLUMNNAME_packingmaterialname); } /** Set Standardpreis. @param PriceStd Standardpreis */ @Override public void setPriceStd (java.math.BigDecimal PriceStd) { set_ValueNoCheck (COLUMNNAME_PriceStd, PriceStd); } /** Get Standardpreis. @return Standardpreis */ @Override public java.math.BigDecimal getPriceStd () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PriceStd); if (bd == null) return BigDecimal.ZERO; return bd; }
/** Set Produktname. @param ProductName Name des Produktes */ @Override public void setProductName (java.lang.String ProductName) { set_ValueNoCheck (COLUMNNAME_ProductName, ProductName); } /** Get Produktname. @return Name des Produktes */ @Override public java.lang.String getProductName () { return (java.lang.String)get_Value(COLUMNNAME_ProductName); } /** Set Produktschlüssel. @param ProductValue Schlüssel des Produktes */ @Override public void setProductValue (java.lang.String ProductValue) { set_ValueNoCheck (COLUMNNAME_ProductValue, ProductValue); } /** Get Produktschlüssel. @return Schlüssel des Produktes */ @Override public java.lang.String getProductValue () { return (java.lang.String)get_Value(COLUMNNAME_ProductValue); } /** Set Reihenfolge. @param SeqNo Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public void setSeqNo (java.lang.String SeqNo) { set_ValueNoCheck (COLUMNNAME_SeqNo, SeqNo); } /** Get Reihenfolge. @return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public java.lang.String getSeqNo () { return (java.lang.String)get_Value(COLUMNNAME_SeqNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java-gen\de\metas\fresh\model\X_M_PriceList_V.java
1
请完成以下Java代码
public static void SFTPUpload(SSHClient ssh, String filePath) throws IOException { final SFTPClient sftp = ssh.newSFTPClient(); sftp.put(new FileSystemFile(filePath), "/upload/"); } public static void SFTPDownLoad(SSHClient ssh, String downloadPath, String fileName) throws IOException { final SFTPClient sftp = ssh.newSFTPClient(); try { sftp.get("/upload/" + fileName, downloadPath); } finally { sftp.close(); } } public static LocalPortForwarder localPortForwarding(SSHClient ssh) throws IOException, InterruptedException { LocalPortForwarder locForwarder; final Parameters params = new Parameters(ssh.getRemoteHostname(), 8081, "google.com", 80); final ServerSocket ss = new ServerSocket(); ss.setReuseAddress(true); ss.bind(new InetSocketAddress(params.getLocalHost(), params.getLocalPort())); locForwarder = ssh.newLocalPortForwarder(params, ss); new Thread(() -> { try { locForwarder.listen(); } catch (Exception e) { e.printStackTrace(); } }).start(); return locForwarder; } public static RemotePortForwarder remotePortForwarding(SSHClient ssh) throws IOException, InterruptedException { RemotePortForwarder rpf; ssh.getConnection() .getKeepAlive() .setKeepAliveInterval(5); rpf = ssh.getRemotePortForwarder(); new Thread(() -> { try { rpf.bind(new Forward(8083), new SocketForwardingConnectListener(new InetSocketAddress("google.com", 80))); ssh.getTransport() .join(); } catch (Exception e) { e.printStackTrace(); } }).start(); return rpf; } public static String KeepAlive(String hostName, String userName, String password) throws IOException, InterruptedException {
String response = ""; DefaultConfig defaultConfig = new DefaultConfig(); defaultConfig.setKeepAliveProvider(KeepAliveProvider.KEEP_ALIVE); final SSHClient ssh = new SSHClient(defaultConfig); try { ssh.addHostKeyVerifier(new PromiscuousVerifier()); ssh.connect(hostName, 22); ssh.getConnection() .getKeepAlive() .setKeepAliveInterval(5); ssh.authPassword(userName, password); Session session = ssh.startSession(); session.allocateDefaultPTY(); new CountDownLatch(1).await(); try { session.allocateDefaultPTY(); } finally { session.close(); } } finally { ssh.disconnect(); } response = "success"; return response; } }
repos\tutorials-master\libraries-security-2\src\main\java\com\baeldung\sshj\SSHJAppDemo.java
1
请完成以下Java代码
protected Date calculateDueDate(CommandContext commandContext, int waitTimeInSeconds, Date oldDate) { Calendar newDateCal = new GregorianCalendar(); if (oldDate != null) { newDateCal.setTime(oldDate); } else { newDateCal.setTime(CommandContextUtil.getProcessEngineConfiguration(commandContext).getClock().getCurrentTime()); } newDateCal.add(Calendar.SECOND, waitTimeInSeconds); return newDateCal.getTime(); } protected String getExceptionStacktrace() { StringWriter stringWriter = new StringWriter();
exception.printStackTrace(new PrintWriter(stringWriter)); return stringWriter.toString(); } protected ExecutionEntity fetchExecutionEntity(CommandContext commandContext, String executionId) { if (executionId == null) { return null; } return CommandContextUtil.getExecutionEntityManager(commandContext).findById(executionId); } protected boolean isUnrecoverableException() { return ExceptionUtil.containsCause(exception, FlowableUnrecoverableJobException.class); } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\cmd\JobRetryCmd.java
1
请完成以下Java代码
public static Builder builder() { return new Builder(); } private Mono<Boolean> isMatch(ServerWebExchange exchange, ServerWebExchangeMatcherEntry<ReactiveAuthenticationManager> entry) { ServerWebExchangeMatcher matcher = entry.getMatcher(); return matcher.matches(exchange).map(ServerWebExchangeMatcher.MatchResult::isMatch); } /** * A builder for * {@link ServerWebExchangeDelegatingReactiveAuthenticationManagerResolver}. */ public static final class Builder { private final List<ServerWebExchangeMatcherEntry<ReactiveAuthenticationManager>> entries = new ArrayList<>(); private Builder() { } /** * Maps a {@link ServerWebExchangeMatcher} to an * {@link ReactiveAuthenticationManager}. * @param matcher the {@link ServerWebExchangeMatcher} to use * @param manager the {@link ReactiveAuthenticationManager} to use * @return the * {@link ServerWebExchangeDelegatingReactiveAuthenticationManagerResolver.Builder} * for further customizations */ public ServerWebExchangeDelegatingReactiveAuthenticationManagerResolver.Builder add( ServerWebExchangeMatcher matcher, ReactiveAuthenticationManager manager) { Assert.notNull(matcher, "matcher cannot be null");
Assert.notNull(manager, "manager cannot be null"); this.entries.add(new ServerWebExchangeMatcherEntry<>(matcher, manager)); return this; } /** * Creates a * {@link ServerWebExchangeDelegatingReactiveAuthenticationManagerResolver} * instance. * @return the * {@link ServerWebExchangeDelegatingReactiveAuthenticationManagerResolver} * instance */ public ServerWebExchangeDelegatingReactiveAuthenticationManagerResolver build() { return new ServerWebExchangeDelegatingReactiveAuthenticationManagerResolver(this.entries); } } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\authentication\ServerWebExchangeDelegatingReactiveAuthenticationManagerResolver.java
1
请完成以下Java代码
public Set<CtxName> getParameters() { return ImmutableSet.of(); } @Override public String evaluate(final Evaluatee ctx, final boolean ignoreUnparsable) { return EMPTY_RESULT; } @Override public String evaluate(final Evaluatee ctx, final OnVariableNotFound onVariableNotFound) { return EMPTY_RESULT; } @Override public final IStringExpression resolvePartial(final Evaluatee ctx)
{ return this; } @Override public boolean isNullExpression() { return true; } @Override public Class<String> getValueClass() { // TODO Auto-generated method stub return null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\NullStringExpression.java
1
请完成以下Java代码
public String toString() {return toSql();} public boolean isEmpty() {return sqlCommand2 == null && comment == null;} public String getSqlCommand() {return sqlCommand2 != null ? sqlCommand2 : "";} public String toSql() { String sqlWithInlinedParams = this._sqlWithInlinedParams; if (sqlWithInlinedParams == null) { sqlWithInlinedParams = this._sqlWithInlinedParams = buildFinalSql(); } return sqlWithInlinedParams; } private String buildFinalSql() { final StringBuilder finalSql = new StringBuilder(); final String sqlComment = toSqlCommentLine(comment); if (sqlComment != null) { finalSql.append(sqlComment); } if (sqlCommand2 != null && !sqlCommand2.isEmpty()) { finalSql.append(toSqlCommentLine(timestamp.toString())); final String sqlWithParams = !sqlParams.isEmpty() ? sqlParamsInliner.inline(sqlCommand2, sqlParams.toList()) : sqlCommand2; finalSql.append(sqlWithParams).append("\n;\n\n"); } return finalSql.toString();
} private static String toSqlCommentLine(@Nullable final String comment) { final String commentNorm = StringUtils.trimBlankToNull(comment); if (commentNorm == null) { return null; } return "-- " + commentNorm .replace("\r\n", "\n") .replace("\n", "\n-- ") + "\n"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\logger\Sql.java
1
请完成以下Java代码
public class Msv3ClientMultiException extends AdempiereException implements AvailabilityRequestException { public static Msv3ClientMultiException createAllItemsSameThrowable( @NonNull final Collection<AvailabilityRequestItem> items, @NonNull final Throwable throwable) { final Map<AvailabilityRequestItem, Throwable> allItemsWithSameThrowable = Maps.toMap(items, requestItem -> throwable); return new Msv3ClientMultiException(allItemsWithSameThrowable, throwable); } public static Msv3ClientMultiException createAllItemsSameFaultInfo( @NonNull final Collection<AvailabilityRequestItem> items, @NonNull final FaultInfo msv3FaultInfo) { final Msv3ClientException msv3ClientException = Msv3ClientException.builder() .msv3FaultInfo(msv3FaultInfo) .build();
final Map<AvailabilityRequestItem, Throwable> allItemsWithSameThrowable = Maps.toMap(items, requestItem -> msv3ClientException); return new Msv3ClientMultiException(allItemsWithSameThrowable, msv3ClientException); } private static final long serialVersionUID = -8058915938494697758L; @Getter private final Map<AvailabilityRequestItem, Throwable> requestItem2Exception; private Msv3ClientMultiException(@NonNull final Map<AvailabilityRequestItem, Throwable> requestItem2Exception, final Throwable cause) { super(TranslatableStrings.empty(), cause); this.requestItem2Exception = ImmutableMap.copyOf(requestItem2Exception); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.vendor.gateway.msv3\src\main\java\de\metas\vertical\pharma\vendor\gateway\msv3\common\Msv3ClientMultiException.java
1
请在Spring Boot框架中完成以下Java代码
private String buildVoidDescription(final I_C_BankStatementLine line) { final Properties ctx = Env.getCtx(); String description = services.getMsg(ctx, MSG_VOIDED) + " (" + services.translate(ctx, "StmtAmt") + "=" + line.getStmtAmt(); if (line.getTrxAmt().signum() != 0) { description += ", " + services.translate(ctx, "TrxAmt") + "=" + line.getTrxAmt(); } if (line.getBankFeeAmt().signum() != 0) { description += ", " + services.translate(ctx, "BankFeeAmt") + "=" + line.getBankFeeAmt(); } if (line.getChargeAmt().signum() != 0) { description += ", " + services.translate(ctx, "ChargeAmt") + "=" + line.getChargeAmt(); } if (line.getInterestAmt().signum() != 0) { description += ", " + services.translate(ctx, "InterestAmt") + "=" + line.getInterestAmt(); } description += ")"; return description; } @Override public void reactivateIt(final DocumentTableFields docFields) { throw new UnsupportedOperationException(); } private static void addDescription(final I_C_BankStatement bankStatement, final String description) {
final String desc = bankStatement.getDescription(); if (desc == null) { bankStatement.setDescription(description); } else { bankStatement.setDescription(desc + " | " + description); } } private static void addDescription(final I_C_BankStatementLine line, final String description) { final String desc = line.getDescription(); if (desc == null) { line.setDescription(description); } else { line.setDescription(desc + " | " + description); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\service\BankStatementDocumentHandler.java
2
请完成以下Java代码
public int getRemindDays () { Integer ii = (Integer)get_Value(COLUMNNAME_RemindDays); if (ii == null) return 0; return ii.intValue(); } public I_AD_User getSupervisor() throws RuntimeException { return (I_AD_User)MTable.get(getCtx(), I_AD_User.Table_Name) .getPO(getSupervisor_ID(), get_TrxName()); } /** Set Supervisor. @param Supervisor_ID Supervisor for this user/organization - used for escalation and approval */ public void setSupervisor_ID (int Supervisor_ID) { if (Supervisor_ID < 1) set_Value (COLUMNNAME_Supervisor_ID, null);
else set_Value (COLUMNNAME_Supervisor_ID, Integer.valueOf(Supervisor_ID)); } /** Get Supervisor. @return Supervisor for this user/organization - used for escalation and approval */ public int getSupervisor_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Supervisor_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_WorkflowProcessor.java
1
请完成以下Java代码
public boolean isQuoted(CharSequence buffer, int pos) { int closingQuote = searchBackwards(buffer, pos - 1, getQuoteChars()); if (closingQuote == -1) { return false; } int openingQuote = searchBackwards(buffer, closingQuote - 1, buffer.charAt(closingQuote)); if (openingQuote == -1) { return true; } return isQuoted(buffer, openingQuote - 1); } private int searchBackwards(CharSequence buffer, int pos, char... chars) { while (pos >= 0) { for (char c : chars) { if (buffer.charAt(pos) == c && !isEscaped(buffer, pos)) { return pos; } } pos--; } return -1; } String[] parseArguments(String line) { ArgumentList delimit = delimit(line, 0); return cleanArguments(delimit.getArguments()); } private String[] cleanArguments(String[] arguments) { String[] cleanArguments = new String[arguments.length]; for (int i = 0; i < arguments.length; i++) { cleanArguments[i] = cleanArgument(arguments[i]); } return cleanArguments; } private String cleanArgument(String argument) { for (char c : getQuoteChars()) {
String quote = String.valueOf(c); if (argument.startsWith(quote) && argument.endsWith(quote)) { return replaceEscapes(argument.substring(1, argument.length() - 1)); } } return replaceEscapes(argument); } private String replaceEscapes(String string) { string = string.replace("\\ ", " "); string = string.replace("\\\\", "\\"); string = string.replace("\\t", "\t"); string = string.replace("\\\"", "\""); string = string.replace("\\'", "'"); return string; } }
repos\spring-boot-4.0.1\cli\spring-boot-cli\src\main\java\org\springframework\boot\cli\command\shell\EscapeAwareWhiteSpaceArgumentDelimiter.java
1
请完成以下Java代码
public AiModelService getAiModelService() { return mainCtx.getAiModelService(); } @Override public MqttClientSettings getMqttClientSettings() { return mainCtx.getMqttClientSettings(); } private TbMsgMetaData getActionMetaData(RuleNodeId ruleNodeId) { TbMsgMetaData metaData = new TbMsgMetaData(); metaData.putValue("ruleNodeId", ruleNodeId.toString()); return metaData; } @Override public void schedule(Runnable runnable, long delay, TimeUnit timeUnit) { mainCtx.getScheduler().schedule(runnable, delay, timeUnit); } @Override public void checkTenantEntity(EntityId entityId) throws TbNodeException { TenantId actualTenantId = TenantIdLoader.findTenantId(this, entityId); if (!getTenantId().equals(actualTenantId)) { throw new TbNodeException("Entity with id: '" + entityId + "' specified in the configuration doesn't belong to the current tenant.", true); } } @Override public <E extends HasId<I> & HasTenantId, I extends EntityId> void checkTenantOrSystemEntity(E entity) throws TbNodeException { TenantId actualTenantId = entity.getTenantId(); if (!getTenantId().equals(actualTenantId) && !actualTenantId.isSysTenantId()) { throw new TbNodeException("Entity with id: '" + entity.getId() + "' specified in the configuration doesn't belong to the current or system tenant.", true); } } private static String getFailureMessage(Throwable th) { String failureMessage; if (th != null) { if (!StringUtils.isEmpty(th.getMessage())) { failureMessage = th.getMessage(); } else { failureMessage = th.getClass().getSimpleName(); }
} else { failureMessage = null; } return failureMessage; } private void persistDebugOutput(TbMsg msg, String relationType) { persistDebugOutput(msg, Set.of(relationType)); } private void persistDebugOutput(TbMsg msg, Set<String> relationTypes) { persistDebugOutput(msg, relationTypes, null, null); } private void persistDebugOutput(TbMsg msg, Set<String> relationTypes, Throwable error, String failureMessage) { RuleNode ruleNode = nodeCtx.getSelf(); if (DebugModeUtil.isDebugAllAvailable(ruleNode)) { relationTypes.forEach(relationType -> mainCtx.persistDebugOutput(getTenantId(), ruleNode.getId(), msg, relationType, error, failureMessage)); } else if (DebugModeUtil.isDebugFailuresAvailable(ruleNode, relationTypes)) { mainCtx.persistDebugOutput(getTenantId(), ruleNode.getId(), msg, TbNodeConnectionType.FAILURE, error, failureMessage); } } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\actors\ruleChain\DefaultTbContext.java
1
请完成以下Java代码
public void logDataFormats(Collection<DataFormat> formats) { if (isInfoEnabled()) { for (DataFormat format : formats) { logDataFormat(format); } } } protected void logDataFormat(DataFormat dataFormat) { logInfo("025", "Discovered data format: {}[name = {}]", dataFormat.getClass().getName(), dataFormat.getName()); } public void logDataFormatProvider(DataFormatProvider provider) { if (isInfoEnabled()) { logInfo("026", "Discovered data format provider: {}[name = {}]", provider.getClass().getName(), provider.getDataFormatName()); } } @SuppressWarnings("rawtypes")
public void logDataFormatConfigurator(DataFormatConfigurator configurator) { if (isInfoEnabled()) { logInfo("027", "Discovered data format configurator: {}[dataformat = {}]", configurator.getClass(), configurator.getDataFormatClass().getName()); } } public ExternalTaskClientException multipleProvidersForDataformat(String dataFormatName) { return new ExternalTaskClientException(exceptionMessage("028", "Multiple providers found for dataformat '{}'", dataFormatName)); } public ExternalTaskClientException passNullValueParameter(String parameterName) { return new ExternalTaskClientException(exceptionMessage( "030", "Null value is not allowed as '{}'", parameterName)); } }
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\impl\ExternalTaskClientLogger.java
1
请完成以下Java代码
public ImmutableList<HuId> retrieveAvailableHUIdsToPick(@NonNull final PickingHUsQuery query) { return retrieveAvailableHUsToPick(query) .stream() .map(I_M_HU::getM_HU_ID) .map(HuId::ofRepoId) .collect(ImmutableList.toImmutableList()); } @Override public ImmutableList<HuId> retrieveAvailableHUIdsToPickForShipmentSchedule(@NonNull final RetrieveAvailableHUIdsToPickRequest request) { final I_M_ShipmentSchedule schedule = loadOutOfTrx(request.getScheduleId(), I_M_ShipmentSchedule.class); final PickingHUsQuery query = PickingHUsQuery .builder() .onlyTopLevelHUs(request.isOnlyTopLevel()) .shipmentSchedule(schedule) .onlyIfAttributesMatchWithShipmentSchedules(request.isConsiderAttributes()) .build(); return retrieveAvailableHUIdsToPick(query); }
public boolean clearPickingSlotQueue(@NonNull final PickingSlotId pickingSlotId, final boolean removeQueuedHUsFromSlot) { final I_M_PickingSlot slot = pickingSlotDAO.getById(pickingSlotId, I_M_PickingSlot.class); if (removeQueuedHUsFromSlot) { huPickingSlotDAO.retrieveAllHUs(slot) .stream() .map(hu -> HuId.ofRepoId(hu.getM_HU_ID())) .forEach(queuedHU -> removeFromPickingSlotQueue(slot, queuedHU)); } return huPickingSlotDAO.isEmpty(slot); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\slot\impl\HUPickingSlotBL.java
1
请在Spring Boot框架中完成以下Java代码
public String getDOCUMENTID() { return documentid; } /** * Sets the value of the documentid property. * * @param value * allowed object is * {@link String } * */ public void setDOCUMENTID(String value) { this.documentid = value; } /** * Gets the value of the handlinginstrcode property. * * @return * possible object is * {@link String } * */ public String getHANDLINGINSTRCODE() { return handlinginstrcode; } /** * Sets the value of the handlinginstrcode property. * * @param value * allowed object is * {@link String } * */ public void setHANDLINGINSTRCODE(String value) { this.handlinginstrcode = value; } /** * Gets the value of the handlinginstrdesc property. * * @return * possible object is * {@link String } * */ public String getHANDLINGINSTRDESC() { return handlinginstrdesc; } /** * Sets the value of the handlinginstrdesc property. * * @param value * allowed object is * {@link String } * */ public void setHANDLINGINSTRDESC(String value) { this.handlinginstrdesc = value; } /** * Gets the value of the hazardousmatcode property. * * @return * possible object is * {@link String } * */
public String getHAZARDOUSMATCODE() { return hazardousmatcode; } /** * Sets the value of the hazardousmatcode property. * * @param value * allowed object is * {@link String } * */ public void setHAZARDOUSMATCODE(String value) { this.hazardousmatcode = value; } /** * Gets the value of the hazardousmatname property. * * @return * possible object is * {@link String } * */ public String getHAZARDOUSMATNAME() { return hazardousmatname; } /** * Sets the value of the hazardousmatname property. * * @param value * allowed object is * {@link String } * */ public void setHAZARDOUSMATNAME(String value) { this.hazardousmatname = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\PHAND1.java
2
请完成以下Java代码
public static int nthPadovanTermIterativeMethodWithArray(int n) { int[] memo = new int[n + 1]; if (n == 0 || n == 1 || n == 2) { return 1; } memo[0] = 1; memo[1] = 1; memo[2] = 1; for (int i = 3; i <= n; i++) { memo[i] = memo[i - 2] + memo[i - 3]; } return memo[n]; } public static int nthPadovanTermIterativeMethodWithVariables(int n) { if (n == 0 || n == 1 || n == 2) { return 1; } int p0 = 1, p1 = 1, p2 = 1; int tempNthTerm; for (int i = 3; i <= n; i++) { tempNthTerm = p0 + p1; p0 = p1; p1 = p2; p2 = tempNthTerm; } return p2; }
public static int nthPadovanTermUsingFormula(int n) { if (n == 0 || n == 1 || n == 2) { return 1; } // Padovan spiral constant (plastic number) - the real root of x^3 - x - 1 = 0 final double PADOVAN_CONSTANT = 1.32471795724474602596; // Normalization factor to approximate Padovan sequence values final double NORMALIZATION_FACTOR = 1.045356793252532962; double p = Math.pow(PADOVAN_CONSTANT, n - 1); return (int) Math.round(p / NORMALIZATION_FACTOR); } }
repos\tutorials-master\core-java-modules\core-java-numbers-3\src\main\java\com\baeldung\padovan\PadovanSeriesUtils.java
1
请完成以下Java代码
public AuthenticationConverter authenticationConverter() { return new BasicAuthenticationConverter(); } public AuthenticationManagerResolver<HttpServletRequest> resolver() { return request -> { if (request .getPathInfo() .startsWith("/employee")) { return employeesAuthenticationManager(); } return customersAuthenticationManager(); }; } public AuthenticationManager customersAuthenticationManager() { return authentication -> { if (isCustomer(authentication)) { return new UsernamePasswordAuthenticationToken( authentication.getPrincipal(), authentication.getCredentials(), Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER")) ); } throw new UsernameNotFoundException(authentication .getPrincipal() .toString()); }; } private boolean isCustomer(Authentication authentication) { return (authentication .getPrincipal() .toString() .startsWith("customer")); } private boolean isEmployee(Authentication authentication) { return (authentication .getPrincipal() .toString() .startsWith("employee")); } private AuthenticationFilter authenticationFilter() { AuthenticationFilter filter = new AuthenticationFilter( resolver(), authenticationConverter()); filter.setSuccessHandler((request, response, auth) -> {}); return filter;
} private AuthenticationManager employeesAuthenticationManager() { return authentication -> { if (isEmployee(authentication)) { return new UsernamePasswordAuthenticationToken( authentication.getPrincipal(), authentication.getCredentials(), Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER")) ); } throw new UsernameNotFoundException(authentication .getPrincipal() .toString()); }; } @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.addFilterBefore(authenticationFilter(), BasicAuthenticationFilter.class); return http.build(); } }
repos\tutorials-master\spring-security-modules\spring-security-core\src\main\java\com\baeldung\authresolver\CustomWebSecurityConfigurer.java
1
请完成以下Java代码
public boolean isNew(final Object model) { Check.assumeNotNull(model, "model not null"); return getHelperThatCanHandle(model) .isNew(model); } @Override public <T> T getValue( @NonNull final Object model, @NonNull final String columnName, final boolean throwExIfColumnNotFound, final boolean useOverrideColumnIfAvailable) { return getHelperThatCanHandle(model) .getValue(model, columnName, throwExIfColumnNotFound, useOverrideColumnIfAvailable); } @Override public boolean isValueChanged(final Object model, final String columnName) { return getHelperThatCanHandle(model) .isValueChanged(model, columnName); } @Override public boolean isValueChanged(final Object model, final Set<String> columnNames) { return getHelperThatCanHandle(model) .isValueChanged(model, columnNames); } @Override public boolean isNull(final Object model, final String columnName) { if (model == null) { return true; } return getHelperThatCanHandle(model) .isNull(model, columnName); } @Nullable @Override public <T> T getDynAttribute(@NonNull final Object model, @NonNull final String attributeName) { return getHelperThatCanHandle(model) .getDynAttribute(model, attributeName); } @Override public Object setDynAttribute(final Object model, final String attributeName, final Object value) { return getHelperThatCanHandle(model) .setDynAttribute(model, attributeName, value); } @Nullable @Override public <T> T computeDynAttributeIfAbsent(@NonNull final Object model, @NonNull final String attributeName, @NonNull final Supplier<T> supplier) { return getHelperThatCanHandle(model).computeDynAttributeIfAbsent(model, attributeName, supplier); } @Override
public <T extends PO> T getPO(final Object model, final boolean strict) { if (model == null) { return null; } // Short-circuit: model is already a PO instance if (model instanceof PO) { @SuppressWarnings("unchecked") final T po = (T)model; return po; } return getHelperThatCanHandle(model) .getPO(model, strict); } @Override public Evaluatee getEvaluatee(final Object model) { if (model == null) { return null; } else if (model instanceof Evaluatee) { final Evaluatee evaluatee = (Evaluatee)model; return evaluatee; } return getHelperThatCanHandle(model) .getEvaluatee(model); } @Override public boolean isCopy(@NonNull final Object model) { return getHelperThatCanHandle(model).isCopy(model); } @Override public boolean isCopying(@NonNull final Object model) { return getHelperThatCanHandle(model).isCopying(model); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\wrapper\CompositeInterfaceWrapperHelper.java
1
请在Spring Boot框架中完成以下Java代码
public String getActivityId() { return activityId; } @Override public String getSubScopeId() { return subScopeId; } @Override public String getScopeId() { return scopeId; } @Override public String getScopeDefinitionId() { return scopeDefinitionId; } @Override
public String getScopeDefinitionKey() { return scopeDefinitionKey; } @Override public String getScopeType() { return scopeType; } @Override public String getTenantId() { return tenantId; } @Override public String getConfiguration() { return configuration; } }
repos\flowable-engine-main\modules\flowable-eventsubscription-service\src\main\java\org\flowable\eventsubscription\service\impl\EventSubscriptionBuilderImpl.java
2
请完成以下Java代码
public int getPP_Weighting_Spec_ID() { return get_ValueAsInt(COLUMNNAME_PP_Weighting_Spec_ID); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setTargetWeight (final BigDecimal TargetWeight) { set_Value (COLUMNNAME_TargetWeight, TargetWeight); } @Override public BigDecimal getTargetWeight() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TargetWeight); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setTolerance_Perc (final BigDecimal Tolerance_Perc) { set_Value (COLUMNNAME_Tolerance_Perc, Tolerance_Perc); }
@Override public BigDecimal getTolerance_Perc() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Tolerance_Perc); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setWeightChecksRequired (final int WeightChecksRequired) { set_Value (COLUMNNAME_WeightChecksRequired, WeightChecksRequired); } @Override public int getWeightChecksRequired() { return get_ValueAsInt(COLUMNNAME_WeightChecksRequired); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Order_Weighting_Run.java
1
请完成以下Java代码
public int add(String tag) { // assertUnlock(); Integer id = stringIdMap.get(tag); if (id == null) { id = stringIdMap.size(); stringIdMap.put(tag, id); idStringMap.add(tag); } return id; } public int size() { return stringIdMap.size(); } public int sizeIncludingBos() { return size() + 1; } public int bosId() { return size(); } public void lock() { // assertUnlock(); allTags = new int[size()]; for (int i = 0; i < size(); i++) { allTags[i] = i; } } // private void assertUnlock() // { // if (allTags != null) // { // throw new IllegalStateException("标注集已锁定,无法修改"); // } // } @Override public String stringOf(int id) { return idStringMap.get(id); } @Override public int idOf(String string) { Integer id = stringIdMap.get(string); if (id == null) id = -1; return id; } @Override public Iterator<Map.Entry<String, Integer>> iterator() { return stringIdMap.entrySet().iterator(); }
/** * 获取所有标签及其下标 * * @return */ public int[] allTags() { return allTags; } public void save(DataOutputStream out) throws IOException { out.writeInt(type.ordinal()); out.writeInt(size()); for (String tag : idStringMap) { out.writeUTF(tag); } } @Override public boolean load(ByteArray byteArray) { idStringMap.clear(); stringIdMap.clear(); int size = byteArray.nextInt(); for (int i = 0; i < size; i++) { String tag = byteArray.nextUTF(); idStringMap.add(tag); stringIdMap.put(tag, i); } lock(); return true; } public void load(DataInputStream in) throws IOException { idStringMap.clear(); stringIdMap.clear(); int size = in.readInt(); for (int i = 0; i < size; i++) { String tag = in.readUTF(); idStringMap.add(tag); stringIdMap.put(tag, i); } lock(); } public Collection<String> tags() { return idStringMap; } public boolean contains(String tag) { return idStringMap.contains(tag); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\perceptron\tagset\TagSet.java
1
请完成以下Java代码
public DatabaseDto getDatabase() { return database; } public void setDatabase(DatabaseDto database) { this.database = database; } public ApplicationServerDto getApplicationServer() { return applicationServer; } public void setApplicationServer(ApplicationServerDto applicationServer) { this.applicationServer = applicationServer; } public Map<String, CommandDto> getCommands() { return commands; } public void setCommands(Map<String, CommandDto> commands) { this.commands = commands; } public Map<String, MetricDto> getMetrics() { return metrics; } public void setMetrics(Map<String, MetricDto> metrics) { this.metrics = metrics; } public JdkDto getJdk() { return jdk; } public void setJdk(JdkDto jdk) { this.jdk = jdk; } public Set<String> getCamundaIntegration() { return camundaIntegration; } public void setCamundaIntegration(Set<String> camundaIntegration) { this.camundaIntegration = camundaIntegration; } public LicenseKeyDataDto getLicenseKey() { return licenseKey; } public void setLicenseKey(LicenseKeyDataDto licenseKey) { this.licenseKey = licenseKey;
} public Set<String> getWebapps() { return webapps; } public void setWebapps(Set<String> webapps) { this.webapps = webapps; } public Date getDataCollectionStartDate() { return dataCollectionStartDate; } public void setDataCollectionStartDate(Date dataCollectionStartDate) { this.dataCollectionStartDate = dataCollectionStartDate; } public static InternalsDto fromEngineDto(Internals other) { LicenseKeyData licenseKey = other.getLicenseKey(); InternalsDto dto = new InternalsDto( DatabaseDto.fromEngineDto(other.getDatabase()), ApplicationServerDto.fromEngineDto(other.getApplicationServer()), licenseKey != null ? LicenseKeyDataDto.fromEngineDto(licenseKey) : null, JdkDto.fromEngineDto(other.getJdk())); dto.dataCollectionStartDate = other.getDataCollectionStartDate(); dto.commands = new HashMap<>(); other.getCommands().forEach((name, command) -> dto.commands.put(name, new CommandDto(command.getCount()))); dto.metrics = new HashMap<>(); other.getMetrics().forEach((name, metric) -> dto.metrics.put(name, new MetricDto(metric.getCount()))); dto.setWebapps(other.getWebapps()); dto.setCamundaIntegration(other.getCamundaIntegration()); return dto; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\telemetry\InternalsDto.java
1
请完成以下Java代码
private static void fixSkippingNextLineMethodV1() { try (Scanner scanner = new Scanner(System.in)) { System.out.print("Enter your age: "); int age = scanner.nextInt(); scanner.nextLine(); System.out.print("Enter your first name: "); String firstName = scanner.nextLine(); System.out.println(age + ":" + firstName); } } private static void fixSkippingNextLineMethodV2() { try (Scanner scanner = new Scanner(System.in)) { System.out.print("Enter your age: "); int age = Integer.parseInt(scanner.nextLine()); System.out.print("Enter your first name: "); String firstName = scanner.nextLine(); System.out.println(age + ":" + firstName); } } private static void fixSkippingNextLineMethodV3() { try (Scanner scanner = new Scanner(System.in)) { System.out.print("Enter your age: ");
int age = scanner.nextInt(); scanner.skip("\r\n"); System.out.print("Enter your first name: "); String firstName = scanner.nextLine(); System.out.println(age + ":" + firstName); } } public static void main(String[] args) { produceSkippingNextLineMethod(); fixSkippingNextLineMethodV1(); fixSkippingNextLineMethodV2(); fixSkippingNextLineMethodV3(); } }
repos\tutorials-master\core-java-modules\core-java-scanner\src\main\java\com\baeldung\scanner\NextLineAfterNextMethods.java
1
请完成以下Java代码
public String toString() { return pattern; } public void assertValid() { final boolean existsBPName = hasToken(Addressvars.BPartnerName); final boolean existsBP = hasToken(Addressvars.BPartner); final boolean existsBPGreeting = hasToken(Addressvars.BPartnerGreeting); if ((existsBP && existsBPName) || (existsBP && existsBPGreeting)) { throw new AdempiereException(MSG_AddressBuilder_WrongDisplaySequence) //.appendParametersToMessage() .setParameter("displaySequence", this); } } public boolean hasToken(@NonNull final Addressvars token) {
// TODO: optimize it! this is just some crap refactored code final Scanner scan = new Scanner(pattern); scan.useDelimiter("@"); while (scan.hasNext()) { if (scan.next().equals(token.getName())) { scan.close(); return true; } } scan.close(); return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\location\AddressDisplaySequence.java
1
请完成以下Java代码
public Date getRemovalTime() { return removalTime; } public void setRemovalTime(Date removalTime) { this.removalTime = removalTime; } @Override public String toString() { return this.getClass().getSimpleName() + "[id=" + id + ", processDefinitionKey=" + processDefinitionKey + ", processDefinitionId=" + processDefinitionId + ", rootProcessInstanceId=" + rootProcessInstanceId + ", removalTime=" + removalTime + ", processInstanceId=" + processInstanceId + ", taskId=" + taskId + ", executionId=" + executionId + ", tenantId=" + tenantId + ", activityInstanceId=" + activityInstanceId + ", caseDefinitionKey=" + caseDefinitionKey + ", caseDefinitionId=" + caseDefinitionId
+ ", caseInstanceId=" + caseInstanceId + ", caseExecutionId=" + caseExecutionId + ", name=" + name + ", createTime=" + createTime + ", revision=" + revision + ", serializerName=" + getSerializerName() + ", longValue=" + longValue + ", doubleValue=" + doubleValue + ", textValue=" + textValue + ", textValue2=" + textValue2 + ", state=" + state + ", byteArrayId=" + getByteArrayId() + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\HistoricVariableInstanceEntity.java
1
请完成以下Java代码
public final void setCharacterStream(final String parameterName, final Reader reader) throws SQLException { getCCallableStatementImpl().setCharacterStream(parameterName, reader); } @Override public final void setNCharacterStream(final String parameterName, final Reader value) throws SQLException { getCCallableStatementImpl().setNCharacterStream(parameterName, value); } @Override public final void setClob(final String parameterName, final Reader reader) throws SQLException { getCCallableStatementImpl().setClob(parameterName, reader); } @Override public final void setBlob(final String parameterName, final InputStream inputStream) throws SQLException { getCCallableStatementImpl().setBlob(parameterName, inputStream);
} @Override public final void setNClob(final String parameterName, final Reader reader) throws SQLException { getCCallableStatementImpl().setNClob(parameterName, reader); } @Override public <T> T getObject(int parameterIndex, Class<T> type) throws SQLException { return getCCallableStatementImpl().getObject(parameterIndex, type); } @Override public <T> T getObject(String parameterName, Class<T> type) throws SQLException { return getCCallableStatementImpl().getObject(parameterName, type); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\sql\impl\CCallableStatementProxy.java
1
请在Spring Boot框架中完成以下Java代码
public class GirlController { @Autowired private GirlRep girlRep; /** * 查询所有女生列表 * @return */ @RequestMapping(value = "/girls",method = RequestMethod.GET) public List<Girl> getGirlList(){ return girlRep.findAll(); } /** * 添加一个女生 * @param cupSize * @param age * @return */ @RequestMapping(value = "/girls",method = RequestMethod.POST) public Girl addGirl(@RequestParam("cupSize") String cupSize, @RequestParam("age") Integer age){ Girl girl = new Girl(); girl.setAge(age); girl.setCupSize(cupSize); return girlRep.save(girl); } /** * 根据Id查询女生 * @param id * @return */ @RequestMapping(value = "/girls/{id}",method = RequestMethod.POST) public Girl getGirl(@PathVariable("id") Integer id){ return girlRep.findOne(id); } /** * 更新女生信息 * @param id * @param cupSize * @param age * @return */ @RequestMapping(value = "/girls/{id}",method = RequestMethod.PUT) public Girl updateGirl(@PathVariable("id") Integer id,
@RequestParam("cupSize") String cupSize, @RequestParam("age") Integer age){ Girl girl = new Girl(); girl.setId(id); girl.setCupSize(cupSize); girl.setAge(age); return girlRep.save(girl); } /** * 删除ID * @param id */ @DeleteMapping(value = "/girls/{id}") public void updateGirl(@PathVariable("id") Integer id){ girlRep.delete(id); } @RequestMapping(value = "girls/age/{age}",method = RequestMethod.GET) public List<Girl> getGirls(@PathVariable("age") Integer age){ return girlRep.findByAge(age); } }
repos\SpringBootLearning-master\firstspringboot-2h\src\main\java\com\forezp\GirlController.java
2
请完成以下Java代码
public FilterSql getSql( @NonNull final DocumentFilter filter, final SqlOptions sqlOpts_NOTUSED, @NonNull final SqlDocumentFilterConverterContext context) { final String barcodeString = StringUtils.trimBlankToNull(filter.getParameterValueAsString(PARAM_Barcode, null)); if (barcodeString == null) { // shall not happen throw new AdempiereException("Barcode parameter is not set: " + filter); } // // Get M_HU_IDs by barcode final ImmutableSet<HuId> huIds; final GlobalQRCode globalQRCode = GlobalQRCode.parse(barcodeString).orNullIfError(); if (globalQRCode != null) { final HUQRCode huQRCode = HUQRCode.fromGlobalQRCode(globalQRCode); final HUQRCodesService huQRCodesService = SpringContextHolder.instance.getBean(HUQRCodesService.class); final HuId huId = huQRCodesService.getHuIdByQRCodeIfExists(huQRCode).orElse(null); huIds = huId != null ? ImmutableSet.of(huId) : ImmutableSet.of(); } else { final IHandlingUnitsDAO handlingUnitsDAO = Services.get(IHandlingUnitsDAO.class); huIds = handlingUnitsDAO.createHUQueryBuilder() .setContext(PlainContextAware.newOutOfTrx()) .onlyContextClient(false) // avoid enforcing context AD_Client_ID because it might be that we are not in a user thread (so no context) .setOnlyWithBarcode(barcodeString) .setOnlyTopLevelHUs(false) .createQueryBuilder() .setOption(IQueryBuilder.OPTION_Explode_OR_Joins_To_SQL_Unions) .create() .idsAsSet(HuId::ofRepoId); } if (huIds.isEmpty()) { return FilterSql.ALLOW_NONE; } final IHandlingUnitsBL handlingUnitsBL = Services.get(IHandlingUnitsBL.class); final ImmutableSet<HuId> topLevelHuIds = handlingUnitsBL.getTopLevelHUs(huIds); final ISqlQueryFilter sqlQueryFilter = new InArrayQueryFilter<>(I_M_HU.COLUMNNAME_M_HU_ID, topLevelHuIds); return FilterSql.ofWhereClause(SqlAndParams.of(sqlQueryFilter.getSql(), sqlQueryFilter.getSqlParams(Env.getCtx()))); } }
protected boolean isAlwaysUseSameLayout() { return Services.get(ISysConfigBL.class).getBooleanValue(SYSCFG_AlwaysUseSameLayout, false); } protected RelatedProcessDescriptor createProcessDescriptor(@NonNull final Class<?> processClass) { return RelatedProcessDescriptor.builder() .processId(adProcessDAO.retrieveProcessIdByClassIfUnique(processClass)) .displayPlace(RelatedProcessDescriptor.DisplayPlace.ViewQuickActions) .build(); } @Value(staticConstructor = "of") private static class ViewLayoutKey { @NonNull WindowId windowId; @NonNull JSONViewDataType viewDataType; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\HUEditorViewFactoryTemplate.java
1
请完成以下Java代码
public List<String> getExtensions() { return extensions; } public String getLanguageName() { return "JSP 2.1 EL"; } public String getLanguageVersion() { return "2.1"; } public String getMethodCallSyntax(String obj, String method, String... arguments) { throw new UnsupportedOperationException("Method getMethodCallSyntax is not supported"); } public List<String> getMimeTypes() { return mimeTypes; } public List<String> getNames() { return names; } public String getOutputStatement(String toDisplay) { // We will use out:print function to output statements StringBuilder stringBuffer = new StringBuilder(); stringBuffer.append("out:print(\""); int length = toDisplay.length(); for (int i = 0; i < length; i++) { char c = toDisplay.charAt(i); switch (c) { case '"': stringBuffer.append("\\\""); break; case '\\': stringBuffer.append("\\\\"); break; default: stringBuffer.append(c); break; } } stringBuffer.append("\")"); return stringBuffer.toString(); } public String getParameter(String key) { if (key.equals(ScriptEngine.NAME)) { return getLanguageName(); } else if (key.equals(ScriptEngine.ENGINE)) {
return getEngineName(); } else if (key.equals(ScriptEngine.ENGINE_VERSION)) { return getEngineVersion(); } else if (key.equals(ScriptEngine.LANGUAGE)) { return getLanguageName(); } else if (key.equals(ScriptEngine.LANGUAGE_VERSION)) { return getLanguageVersion(); } else if (key.equals("THREADING")) { return "MULTITHREADED"; } else { return null; } } public String getProgram(String... statements) { // Each statement is wrapped in '${}' to comply with EL StringBuilder buf = new StringBuilder(); if (statements.length != 0) { for (int i = 0; i < statements.length; i++) { buf.append("${"); buf.append(statements[i]); buf.append("} "); } } return buf.toString(); } public ScriptEngine getScriptEngine() { return new JuelScriptEngine(this); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\scripting\JuelScriptEngineFactory.java
1
请完成以下Java代码
String removeDuplicatesUsinglinkedHashSet(String str) { StringBuilder sb = new StringBuilder(); Set<Character> linkedHashSet = new LinkedHashSet<>(); for (int i = 0; i < str.length(); i++) { linkedHashSet.add(str.charAt(i)); } for (Character c : linkedHashSet) { sb.append(c); } return sb.toString(); } String removeDuplicatesUsingSorting(String str) { StringBuilder sb = new StringBuilder(); if(!str.isEmpty()) { char[] chars = str.toCharArray(); Arrays.sort(chars); sb.append(chars[0]); for (int i = 1; i < chars.length; i++) { if (chars[i] != chars[i - 1]) { sb.append(chars[i]); } } } return sb.toString(); } String removeDuplicatesUsingHashSet(String str) { StringBuilder sb = new StringBuilder(); Set<Character> hashSet = new HashSet<>(); for (int i = 0; i < str.length(); i++) { hashSet.add(str.charAt(i));
} for (Character c : hashSet) { sb.append(c); } return sb.toString(); } String removeDuplicatesUsingIndexOf(String str) { StringBuilder sb = new StringBuilder(); int idx; for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); idx = str.indexOf(c, i + 1); if (idx == -1) { sb.append(c); } } return sb.toString(); } String removeDuplicatesUsingDistinct(String str) { StringBuilder sb = new StringBuilder(); str.chars().distinct().forEach(c -> sb.append((char) c)); return sb.toString(); } }
repos\tutorials-master\core-java-modules\core-java-string-algorithms-4\src\main\java\com\baeldung\removeduplicates\RemoveDuplicateFromString.java
1
请在Spring Boot框架中完成以下Java代码
private ServiceRepairProjectTaskStatus computeStatusForRepairOrderType() { if (getRepairOrderId() == null) { return ServiceRepairProjectTaskStatus.NOT_STARTED; } else { return isRepairOrderDone() ? ServiceRepairProjectTaskStatus.COMPLETED : ServiceRepairProjectTaskStatus.IN_PROGRESS; } } private ServiceRepairProjectTaskStatus computeStatusForSparePartsType() { if (getQtyToReserve().signum() <= 0) { return ServiceRepairProjectTaskStatus.COMPLETED; } else if (getQtyReservedOrConsumed().signum() == 0) { return ServiceRepairProjectTaskStatus.NOT_STARTED; } else { return ServiceRepairProjectTaskStatus.IN_PROGRESS; } } public ServiceRepairProjectTask withRepairOrderId(@NonNull final PPOrderId repairOrderId) { return toBuilder() .repairOrderId(repairOrderId) .build()
.withUpdatedStatus(); } public ServiceRepairProjectTask withRepairOrderDone( @Nullable final String repairOrderSummary, @Nullable final ProductId repairServicePerformedId) { return toBuilder() .isRepairOrderDone(true) .repairOrderSummary(repairOrderSummary) .repairServicePerformedId(repairServicePerformedId) .build() .withUpdatedStatus(); } public ServiceRepairProjectTask withRepairOrderNotDone() { return toBuilder() .isRepairOrderDone(false) .repairOrderSummary(null) .repairServicePerformedId(null) .build() .withUpdatedStatus(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.base\src\main\java\de\metas\servicerepair\project\model\ServiceRepairProjectTask.java
2
请完成以下Java代码
public void setRawMaterialsIssueStrategy (final @Nullable java.lang.String RawMaterialsIssueStrategy) { set_Value (COLUMNNAME_RawMaterialsIssueStrategy, RawMaterialsIssueStrategy); } @Override public java.lang.String getRawMaterialsIssueStrategy() { return get_ValueAsString(COLUMNNAME_RawMaterialsIssueStrategy); } @Override public org.compiere.model.I_S_Resource getS_Resource() { return get_ValueAsPO(COLUMNNAME_S_Resource_ID, org.compiere.model.I_S_Resource.class); } @Override public void setS_Resource(final org.compiere.model.I_S_Resource S_Resource) { set_ValueFromPO(COLUMNNAME_S_Resource_ID, org.compiere.model.I_S_Resource.class, S_Resource); } @Override public void setS_Resource_ID (final int S_Resource_ID) { if (S_Resource_ID < 1) set_Value (COLUMNNAME_S_Resource_ID, null); else set_Value (COLUMNNAME_S_Resource_ID, S_Resource_ID); } @Override public int getS_Resource_ID() { return get_ValueAsInt(COLUMNNAME_S_Resource_ID); } @Override public void setScannedQRCode (final @Nullable java.lang.String ScannedQRCode) { set_Value (COLUMNNAME_ScannedQRCode, ScannedQRCode); } @Override public java.lang.String getScannedQRCode() { return get_ValueAsString(COLUMNNAME_ScannedQRCode); } @Override public void setSetupTime (final int SetupTime) { set_Value (COLUMNNAME_SetupTime, SetupTime); } @Override public int getSetupTime() { return get_ValueAsInt(COLUMNNAME_SetupTime); } @Override public void setSetupTimeReal (final int SetupTimeReal) { set_Value (COLUMNNAME_SetupTimeReal, SetupTimeReal); } @Override public int getSetupTimeReal() { return get_ValueAsInt(COLUMNNAME_SetupTimeReal); }
@Override public void setSetupTimeRequiered (final int SetupTimeRequiered) { set_Value (COLUMNNAME_SetupTimeRequiered, SetupTimeRequiered); } @Override public int getSetupTimeRequiered() { return get_ValueAsInt(COLUMNNAME_SetupTimeRequiered); } @Override public void setValue (final java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } @Override public void setWaitingTime (final int WaitingTime) { set_Value (COLUMNNAME_WaitingTime, WaitingTime); } @Override public int getWaitingTime() { return get_ValueAsInt(COLUMNNAME_WaitingTime); } @Override public void setYield (final int Yield) { set_Value (COLUMNNAME_Yield, Yield); } @Override public int getYield() { return get_ValueAsInt(COLUMNNAME_Yield); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Order_Node.java
1
请完成以下Java代码
private DocumentId getDocumentId() { return _documentValuesSupplier.getDocumentId(); } private FieldInitializationMode getFieldInitializerMode() { return _fieldInitializerMode; } private boolean isNewDocument() { return _fieldInitializerMode == FieldInitializationMode.NewDocument; } private Document getParentDocument() { return _parentDocument; } private DocumentPath getDocumentPath() { if (_documentPath == null) { final DocumentEntityDescriptor entityDescriptor = getEntityDescriptor(); final DocumentId documentId = getDocumentId(); final Document parentDocument = getParentDocument(); if (parentDocument == null) { _documentPath = DocumentPath.rootDocumentPath(entityDescriptor.getDocumentType(), entityDescriptor.getDocumentTypeId(), documentId); } else { _documentPath = parentDocument.getDocumentPath().createChildPath(entityDescriptor.getDetailId(), documentId); } } return _documentPath; } private int getWindowNo() { if (_windowNo == null) { final Document parentDocument = getParentDocument(); if (parentDocument == null) { _windowNo = _nextWindowNo.incrementAndGet(); } else { _windowNo = parentDocument.getWindowNo(); } } return _windowNo;
} private boolean isWritable() { final Document parentDocument = getParentDocument(); if (parentDocument == null) { return isNewDocument(); } else { return parentDocument.isWritable(); } } private ReentrantReadWriteLock createLock() { // don't create locks for any other entity which is not window final DocumentEntityDescriptor entityDescriptor = getEntityDescriptor(); if (entityDescriptor.getDocumentType() != DocumentType.Window) { return null; } // final Document parentDocument = getParentDocument(); if (parentDocument == null) { return new ReentrantReadWriteLock(); } else { // don't create lock for included documents return null; } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\Document.java
1
请完成以下Java代码
public Map<String, Object> getVariables() { return this.variables; } @Override public Map<String, Object> getExtensions() { return this.extensions; } @Override public Map<String, Object> toMap() { Map<String, Object> map = new LinkedHashMap<>(3); map.put(QUERY_KEY, getDocument()); if (getOperationName() != null) { map.put(OPERATION_NAME_KEY, getOperationName()); } if (!CollectionUtils.isEmpty(getVariables())) { map.put(VARIABLES_KEY, new LinkedHashMap<>(getVariables())); } if (!CollectionUtils.isEmpty(getExtensions())) { map.put(EXTENSIONS_KEY, new LinkedHashMap<>(getExtensions())); } return map; } @Override public boolean equals(Object o) { if (!(o instanceof DefaultGraphQlRequest)) { return false; } DefaultGraphQlRequest other = (DefaultGraphQlRequest) o; return (getDocument().equals(other.getDocument()) && ObjectUtils.nullSafeEquals(getOperationName(), other.getOperationName()) && ObjectUtils.nullSafeEquals(getVariables(), other.getVariables()) && ObjectUtils.nullSafeEquals(getExtensions(), other.getExtensions()));
} @Override public int hashCode() { return this.document.hashCode() + 31 * ObjectUtils.nullSafeHashCode(this.operationName) + 31 * this.variables.hashCode() + 31 * this.extensions.hashCode(); } @Override public String toString() { return "document='" + getDocument() + "'" + ((getOperationName() != null) ? ", operationName='" + getOperationName() + "'" : "") + (!CollectionUtils.isEmpty(getVariables()) ? ", variables=" + getVariables() : "" + (!CollectionUtils.isEmpty(getExtensions()) ? ", extensions=" + getExtensions() : "")); } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\support\DefaultGraphQlRequest.java
1
请完成以下Java代码
public SqlViewRowsWhereClause getSqlWhereClause(final DocumentIdsSelection rowIds, final SqlOptions sqlOpts) { // TODO Auto-generated method stub return null; } @Override public <T> List<T> retrieveModelsByIds(final DocumentIdsSelection rowIds, final Class<T> modelClass) { throw new UnsupportedOperationException(); } @Override public Stream<? extends IViewRow> streamByIds(final DocumentIdsSelection rowIds) { return rows.streamByIds(rowIds); } @Override public void notifyRecordsChanged( @NonNull final TableRecordReferenceSet recordRefs, final boolean watchedByFrontend) { // TODO Auto-generated method stub }
@Override public List<RelatedProcessDescriptor> getAdditionalRelatedProcessDescriptors() { return additionalRelatedProcessDescriptors; } /** * @return the {@code M_ShipmentSchedule_ID} of the packageable line that is currently selected within the {@link PackageableView}. */ @NonNull public ShipmentScheduleId getCurrentShipmentScheduleId() { return currentShipmentScheduleId; } @Override public void invalidateAll() { rows.invalidateAll(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\pickingslot\PickingSlotView.java
1
请在Spring Boot框架中完成以下Java代码
public class ProductHUInventory { @NonNull ProductId productId; @NonNull ImmutableList<HuForInventoryLine> huForInventoryLineList; public static ProductHUInventory of(@NonNull final ProductId productId, @NonNull final List<HuForInventoryLine> huForInventoryLineList) { final boolean notAllLinesMatchTheProduct = huForInventoryLineList.stream() .anyMatch(huForInventoryLine -> !huForInventoryLine.getProductId().equals(productId)); if (notAllLinesMatchTheProduct) { throw new AdempiereException("Not all huForInventoryLineList match the given product!") .appendParametersToMessage() .setParameter("huForInventoryLineList", huForInventoryLineList) .setParameter("productId", productId); } return new ProductHUInventory(productId, ImmutableList.copyOf(huForInventoryLineList)); } @NonNull public Quantity getTotalQtyBooked( @NonNull final IUOMConversionBL uomConversionBL, @NonNull final I_C_UOM uom) { return huForInventoryLineList.stream() .map(HuForInventoryLine::getQuantityBooked) .map(qty -> uomConversionBL.convertQuantityTo(qty, productId, UomId.ofRepoId(uom.getC_UOM_ID()))) .reduce(Quantity::add) .orElseGet(() -> Quantity.zero(uom)); } @NonNull public Map<LocatorId, ProductHUInventory> mapByLocatorId() { return mapByKey(HuForInventoryLine::getLocatorId); } @NonNull public Map<WarehouseId, ProductHUInventory> mapByWarehouseId() { return mapByKey(huForInventoryLine -> huForInventoryLine.getLocatorId().getWarehouseId()); } @NonNull public List<InventoryLineHU> toInventoryLineHUs( @NonNull final IUOMConversionBL uomConversionBL, @NonNull final UomId targetUomId)
{ final UnaryOperator<Quantity> uomConverter = qty -> uomConversionBL.convertQuantityTo(qty, productId, targetUomId); return huForInventoryLineList.stream() .map(DraftInventoryLinesCreateCommand::toInventoryLineHU) .map(inventoryLineHU -> inventoryLineHU.convertQuantities(uomConverter)) .collect(ImmutableList.toImmutableList()); } @NonNull public Set<HuId> getHuIds() { return huForInventoryLineList.stream() .map(HuForInventoryLine::getHuId) .filter(Objects::nonNull) .collect(ImmutableSet.toImmutableSet()); } @NonNull private <K> Map<K, ProductHUInventory> mapByKey(final Function<HuForInventoryLine, K> keyProvider) { final Map<K, List<HuForInventoryLine>> key2Hus = new HashMap<>(); huForInventoryLineList.forEach(hu -> { final ArrayList<HuForInventoryLine> husFromTargetWarehouse = new ArrayList<>(); husFromTargetWarehouse.add(hu); key2Hus.merge(keyProvider.apply(hu), husFromTargetWarehouse, (oldList, newList) -> { oldList.addAll(newList); return oldList; }); }); return key2Hus.keySet() .stream() .collect(ImmutableMap.toImmutableMap(Function.identity(), warehouseId -> ProductHUInventory.of(this.productId, key2Hus.get(warehouseId)))); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inventory\draftlinescreator\ProductHUInventory.java
2
请完成以下Java代码
private static ImmutableMap<String, SaveHandler> indexByTableName(@NotNull final Optional<List<SaveHandler>> optionalHandlers) { final ImmutableMap.Builder<String, SaveHandler> builder = ImmutableMap.builder(); optionalHandlers.ifPresent(handlers -> { for (SaveHandler handler : handlers) { final Set<String> handledTableNames = handler.getHandledTableName(); if (handledTableNames.isEmpty()) { throw new AdempiereException("SaveHandler " + handler + " has no handled table names"); } handledTableNames.forEach(handledTableName -> builder.put(handledTableName, handler)); } }); return builder.build(); } private SaveHandler getHandler(@NonNull final String tableName) {return byTableName.getOrDefault(tableName, defaultHandler);}
public boolean isReadonly(@NonNull final GridTabVO gridTabVO) { final String tableName = gridTabVO.getTableName(); return getHandler(tableName).isReadonly(gridTabVO); } public SaveHandler.SaveResult save(@NonNull final Document document) { final String tableName = document.getEntityDescriptor().getTableName(); return getHandler(tableName).save(document); } public void delete(final Document document) { final String tableName = document.getEntityDescriptor().getTableName(); getHandler(tableName).delete(document); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\sql\save\CompositeSaveHandlers.java
1
请完成以下Java代码
public ZoneId getTimeZone() { final OrgId orgId = getOrgId(); final OrgInfo orgInfo = orgDAO.getOrgInfoById(orgId); if (orgInfo.getTimeZone() != null) { return orgInfo.getTimeZone(); } return de.metas.common.util.time.SystemTime.zoneId(); } /** * @deprecated avoid using this method; usually it's workaround-ish / quick and dirty fix */ @Deprecated public static ZoneId getTimeZoneOrSystemDefault() { final UserSession userSession = getCurrentOrNull(); return userSession != null ? userSession.getTimeZone() : SystemTime.zoneId(); } public boolean isWorkplacesEnabled() { return workplaceService.isAnyWorkplaceActive(); }
public @NonNull Optional<Workplace> getWorkplace() { if (!isWorkplacesEnabled()) { return Optional.empty(); } return getLoggedUserIdIfExists().flatMap(workplaceService::getWorkplaceByUserId); } /** * Event fired when the user language was changed. * Usually it is user triggered. * * @author metas-dev <dev@metasfresh.com> */ @lombok.Value public static class LanguagedChangedEvent { @NonNull String adLanguage; UserId adUserId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\session\UserSession.java
1
请完成以下Java代码
protected void addTransactionListener(TransactionState transactionState, final TransactionListener transactionListener, CommandContext commandContext) throws Exception{ getTransaction().registerSynchronization(new JtaTransactionStateSynchronization(transactionState, transactionListener, commandContext)); } protected Transaction getTransaction() { try { return transactionManager.getTransaction(); } catch (Exception e) { throw LOG.exceptionWhileInteractingWithTransaction("getting transaction", e); } } @Override protected boolean isTransactionActiveInternal() throws Exception { return transactionManager.getStatus() != Status.STATUS_MARKED_ROLLBACK && transactionManager.getStatus() != Status.STATUS_NO_TRANSACTION; } public static class JtaTransactionStateSynchronization extends TransactionStateSynchronization implements Synchronization {
public JtaTransactionStateSynchronization(TransactionState transactionState, TransactionListener transactionListener, CommandContext commandContext) { super(transactionState, transactionListener, commandContext); } @Override protected boolean isRolledBack(int status) { return Status.STATUS_ROLLEDBACK == status; } @Override protected boolean isCommitted(int status) { return Status.STATUS_COMMITTED == status; } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cfg\jta\JakartaTransactionContext.java
1
请完成以下Java代码
public class CategoryDto implements Serializable { private static final long serialVersionUID = 1L; String namet; String namem; String nameb; public CategoryDto(String namet, String namem, String nameb) { this.namet = namet; this.namem = namem; this.nameb = nameb; } public String getNamet() { return namet; } public void setNamet(String namet) { this.namet = namet; } public String getNamem() { return namem; } public void setNamem(String namem) {
this.namem = namem; } public String getNameb() { return nameb; } public void setNameb(String nameb) { this.nameb = nameb; } @Override public String toString() { return "CategoryDto{" + "namet=" + namet + ", namem=" + namem + ", nameb=" + nameb + '}'; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootDtoSqlResultSetMapping\src\main\java\com\app\dto\CategoryDto.java
1
请完成以下Java代码
public HttpHeaders getHeaders(Instance instance) { String username = getMetadataValue(instance, USERNAME_KEYS); String password = getMetadataValue(instance, PASSWORD_KEYS); if (!(StringUtils.hasText(username) && StringUtils.hasText(password))) { String registeredName = instance.getRegistration().getName(); InstanceCredentials credentials = this.serviceMap.get(registeredName); if (credentials != null) { username = credentials.getUserName(); password = credentials.getUserPassword(); } else { username = this.defaultUserName; password = this.defaultPassword; } } HttpHeaders headers = new HttpHeaders(); if (StringUtils.hasText(username) && StringUtils.hasText(password)) { headers.set(HttpHeaders.AUTHORIZATION, encode(username, password)); } return headers; } protected String encode(String username, String password) { String token = base64Encode((username + ":" + password).getBytes(StandardCharsets.UTF_8)); return "Basic " + token; } private static @Nullable String getMetadataValue(Instance instance, String[] keys) { Map<String, String> metadata = instance.getRegistration().getMetadata(); for (String key : keys) { String value = metadata.get(key); if (value != null) { return value; } } return null; } private static String base64Encode(byte[] src) { if (src.length == 0) { return ""; } byte[] dest = Base64.getEncoder().encode(src); return new String(dest, StandardCharsets.UTF_8);
} @lombok.Data @lombok.NoArgsConstructor @lombok.AllArgsConstructor public static class InstanceCredentials { /** * user name for this instance */ @lombok.NonNull private String userName; /** * user password for this instance */ @lombok.NonNull private String userPassword; } }
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\web\client\BasicAuthHttpHeaderProvider.java
1
请完成以下Java代码
public ImmutableSetMultimap<InOutLineId, HuId> getHUIdsByInOutLineIds(@NonNull final Set<InOutLineId> inoutLineIds) { if (inoutLineIds.isEmpty()) { return ImmutableSetMultimap.of(); } final TableRecordReferenceSet recordRefs = TableRecordReferenceSet.of(I_M_InOutLine.Table_Name, inoutLineIds); final ImmutableSetMultimap<TableRecordReference, HuId> huIdsByRecordRefs = huAssignmentBL.getHUsByRecordRefs(recordRefs); return huIdsByRecordRefs.entries() .stream() .collect(ImmutableSetMultimap.toImmutableSetMultimap( entry -> entry.getKey().getIdAssumingTableName(I_M_InOutLine.Table_Name, InOutLineId::ofRepoId), Map.Entry::getValue)); } @Override public Set<HuId> getHUIdsByInOutIds(@NonNull final Set<InOutId> inoutIds) { if (inoutIds.isEmpty()) { return ImmutableSet.of(); } final ImmutableSet<InOutLineId> inoutLineIds = inOutDAO.retrieveActiveLineIdsByInOutIds(inoutIds); final ImmutableSetMultimap<InOutLineId, HuId> huIds = getHUIdsByInOutLineIds(inoutLineIds); return ImmutableSet.copyOf(huIds.values()); } @Override public boolean isValidHuForReturn(final InOutId inOutId, final HuId huId) { final Optional<AttributeId> serialNoAttributeIdOptional = serialNoBL.getSerialNoAttributeId(); if (!serialNoAttributeIdOptional.isPresent()) { return false; } final AttributeId serialNoAttributeId = serialNoAttributeIdOptional.get(); final I_M_HU hu = handlingUnitsDAO.getById(huId); final I_M_HU_Attribute serialNoAttr = huAttributesDAO.retrieveAttribute(hu, serialNoAttributeId); if (serialNoAttr == null) {
//no S/N defined. Should not be a valid scenario return false; } final Set<HuId> huIds = getHUIdsByInOutIds(Collections.singleton(inOutId)); if (huIds.isEmpty()) { return true; } final ImmutableSet<HuId> topLevelHUs = handlingUnitsBL.getTopLevelHUs(huIds); return !handlingUnitsBL.createHUQueryBuilder().addOnlyHUIds(topLevelHUs) .addHUStatusToInclude(X_M_HU.HUSTATUS_Planning) .addOnlyWithAttribute(AttributeConstants.ATTR_SerialNo, serialNoAttr.getValue()) .createQueryBuilder() .create() .anyMatch(); } @Override public void validateMandatoryOnShipmentAttributes(@NonNull final I_M_InOut shipment) { final List<I_M_InOutLine> inOutLines = retrieveLines(shipment, I_M_InOutLine.class); for (final I_M_InOutLine line : inOutLines) { final AttributeSetInstanceId asiID = AttributeSetInstanceId.ofRepoIdOrNull(line.getM_AttributeSetInstance_ID()); if (asiID == null) { continue; } final ProductId productId = ProductId.ofRepoId(line.getM_Product_ID()); final List<I_M_HU> husForLine = huAssignmentDAO.retrieveTopLevelHUsForModel(line); for (final I_M_HU hu : husForLine) { huAttributesBL.validateMandatoryShipmentAttributes(HuId.ofRepoId(hu.getM_HU_ID()), productId); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inout\impl\HUInOutBL.java
1
请在Spring Boot框架中完成以下Java代码
public class EmployeeController { @Autowired private EmployeeRepository employeeRepository; //get all employees @GetMapping("/employees") public List<Employee> getAllEmployees(){ return employeeRepository.findAll(); } // create employee rest api @PostMapping("/employees") public Employee createEmployee(@RequestBody Employee employee){ return employeeRepository.save(employee); } // get employee by id rest api @GetMapping("/employees/{id}") public ResponseEntity<Employee> getEmployeeById(@PathVariable Long id){ Employee employee = employeeRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException(" Employee not exist id: " + id)); return ResponseEntity.ok(employee); } //update employee rest api @PutMapping("/employees/{id}") public ResponseEntity<Employee> updateEmployee(@PathVariable Long id, @RequestBody Employee employeeDetails){ Employee employee1 = employeeRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException(" Employee not exist with id: " + id));
employee1.setFirstName(employeeDetails.getFirstName()); employee1.setLastName(employeeDetails.getLastName()); employee1.setEmailId(employeeDetails.getEmailId()); Employee updateEmployee = employeeRepository.save(employee1); return ResponseEntity.ok(updateEmployee); } // delete employee rest api @DeleteMapping("/employees/{id}") public ResponseEntity<Map<String, Boolean>> deleteEmployee(@PathVariable Long id) { Employee employee = employeeRepository.findById(id) .orElseThrow(() -> new ResourceNotFoundException("Employee not exist with id: "+ id)); employeeRepository.delete(employee); Map<String, Boolean> response = new HashMap<>(); response.put("delete", Boolean.TRUE); return ResponseEntity.ok(response); } }
repos\SpringBoot-Projects-FullStack-master\Part-9.SpringBoot-React-Projects\Project-1.SpringBoot-React-CRUD\fullstack\backend\src\main\java\com\urunov\controller\EmployeeController.java
2
请完成以下Java代码
public Optional<ZonedDateTime> calculatePurchaseDatePromised( @NonNull final ZonedDateTime salesPreparationDate, @NonNull final BPPurchaseSchedule schedule) { final IBusinessDayMatcher businessDayMatcher; if (schedule.getNonBusinessDaysCalendarId() != null) { final ICalendarDAO calendarRepo = Services.get(ICalendarDAO.class); businessDayMatcher = calendarRepo.getCalendarNonBusinessDays(schedule.getNonBusinessDaysCalendarId()); } else { businessDayMatcher = NullBusinessDayMatcher.instance; } final IDateShifter dateShifter = BusinessDayShifter.builder() .businessDayMatcher(businessDayMatcher)
.onNonBussinessDay(OnNonBussinessDay.MoveToClosestBusinessDay) .build(); final Optional<LocalDate> purchaseDayPromised = DateSequenceGenerator.builder() .dateFrom(LocalDate.MIN) .dateTo(LocalDate.MAX) .shifter(dateShifter) .frequency(schedule.getFrequency()) .build() .calculatePrevious(salesPreparationDate.toLocalDate()); // TODO: make sure that after applying the time, our date is BEFORE sales preparation time! return purchaseDayPromised .map(day -> schedule.applyTimeTo(day).atZone(salesPreparationDate.getZone())); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\BPPurchaseScheduleService.java
1
请完成以下Java代码
public <T extends TypedValue> T getVariableLocalTyped(String variableName, boolean deserializeValue) { return wrappedScope.getVariableLocalTyped(variableName, deserializeValue); } public Set<String> getVariableNames() { return getVariableNamesLocal(); } public Set<String> getVariableNamesLocal() { return wrappedScope.getVariableNamesLocal(); } public void setVariable(String variableName, Object value) { setVariableLocal(variableName, value); } public void setVariableLocal(String variableName, Object value) { wrappedScope.setVariableLocal(variableName, value); } public void setVariables(Map<String, ? extends Object> variables) { setVariablesLocal(variables); } public void setVariablesLocal(Map<String, ? extends Object> variables) { wrappedScope.setVariablesLocal(variables); } public boolean hasVariables() { return hasVariablesLocal(); } public boolean hasVariablesLocal() { return wrappedScope.hasVariablesLocal(); } public boolean hasVariable(String variableName) { return hasVariableLocal(variableName); } public boolean hasVariableLocal(String variableName) { return wrappedScope.hasVariableLocal(variableName); } public void removeVariable(String variableName) { removeVariableLocal(variableName); }
public void removeVariableLocal(String variableName) { wrappedScope.removeVariableLocal(variableName); } public void removeVariables(Collection<String> variableNames) { removeVariablesLocal(variableNames); } public void removeVariablesLocal(Collection<String> variableNames) { wrappedScope.removeVariablesLocal(variableNames); } public void removeVariables() { removeVariablesLocal(); } public void removeVariablesLocal() { wrappedScope.removeVariablesLocal(); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\core\variable\scope\VariableScopeLocalAdapter.java
1
请完成以下Java代码
public class TimeAgoCalculator { private static LocalDateTime getCurrentTimeByTimeZone(ZoneId zone) { LocalDateTime localDateTime = LocalDateTime.of(2020, 1, 1, 12, 0, 0); return localDateTime.atZone(zone) .toLocalDateTime(); //We return a fixed date and time in order to avoid issues related to getting time from local in unit tests. //return LocalDateTime.now(zone); } public static String calculateTimeAgoWithPeriodAndDuration(LocalDateTime pastTime, ZoneId zone) { Period period = Period.between(pastTime.toLocalDate(), getCurrentTimeByTimeZone(zone).toLocalDate()); Duration duration = Duration.between(pastTime, getCurrentTimeByTimeZone(zone)); if (period.getYears() != 0) return "several years ago"; else if (period.getMonths() != 0) return "several months ago"; else if (period.getDays() != 0) return "several days ago"; else if (duration.toHours() != 0) return "several hours ago";
else if (duration.toMinutes() != 0) return "several minutes ago"; else if (duration.getSeconds() != 0) return "several seconds ago"; else return "moments ago"; } public static String calculateTimeAgoWithPrettyTime(Date pastTime) { PrettyTime prettyTime = new PrettyTime(); return prettyTime.format(pastTime); } public static String calculateTimeAgoWithTime4J(Date pastTime, ZoneId zone, Locale locale) { return net.time4j.PrettyTime.of(locale) .printRelative(pastTime.toInstant(), zone); } }
repos\tutorials-master\core-java-modules\core-java-date-operations-2\src\main\java\com\baeldung\timeago\version8\TimeAgoCalculator.java
1
请在Spring Boot框架中完成以下Java代码
protected JobServiceConfiguration getJobServiceConfiguration(AbstractEngineConfiguration engineConfiguration) { if (engineConfiguration.getServiceConfigurations().containsKey(EngineConfigurationConstants.KEY_JOB_SERVICE_CONFIG)) { return (JobServiceConfiguration) engineConfiguration.getServiceConfigurations().get(EngineConfigurationConstants.KEY_JOB_SERVICE_CONFIG); } return null; } protected void initProcessInstanceService(ProcessEngineConfigurationImpl processEngineConfiguration) { cmmnEngineConfiguration.setProcessInstanceService(new DefaultProcessInstanceService(processEngineConfiguration)); } protected void initCaseInstanceService(ProcessEngineConfigurationImpl processEngineConfiguration) { processEngineConfiguration.setCaseInstanceService(new DefaultCaseInstanceService(cmmnEngineConfiguration)); } protected void initProcessInstanceStateChangedCallbacks(ProcessEngineConfigurationImpl processEngineConfiguration) { if (processEngineConfiguration.getProcessInstanceStateChangedCallbacks() == null) { processEngineConfiguration.setProcessInstanceStateChangedCallbacks(new HashMap<>()); } Map<String, List<RuntimeInstanceStateChangeCallback>> callbacks = processEngineConfiguration.getProcessInstanceStateChangedCallbacks(); if (!callbacks.containsKey(CallbackTypes.PLAN_ITEM_CHILD_PROCESS)) { callbacks.put(CallbackTypes.PLAN_ITEM_CHILD_PROCESS, new ArrayList<>()); } callbacks.get(CallbackTypes.PLAN_ITEM_CHILD_PROCESS).add(new ChildProcessInstanceStateChangeCallback(cmmnEngineConfiguration)); } @Override protected List<Class<? extends Entity>> getEntityInsertionOrder() {
return EntityDependencyOrder.INSERT_ORDER; } @Override protected List<Class<? extends Entity>> getEntityDeletionOrder() { return EntityDependencyOrder.DELETE_ORDER; } @Override protected CmmnEngine buildEngine() { if (cmmnEngineConfiguration == null) { throw new FlowableException("CmmnEngineConfiguration is required"); } return cmmnEngineConfiguration.buildCmmnEngine(); } public CmmnEngineConfiguration getCmmnEngineConfiguration() { return cmmnEngineConfiguration; } public CmmnEngineConfigurator setCmmnEngineConfiguration(CmmnEngineConfiguration cmmnEngineConfiguration) { this.cmmnEngineConfiguration = cmmnEngineConfiguration; return this; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine-configurator\src\main\java\org\flowable\cmmn\engine\configurator\CmmnEngineConfigurator.java
2
请完成以下Java代码
public static Matrix zero(int m, int n) { Matrix A = new Matrix(m, n); double[][] X = A.getArray(); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { X[i][j] = 0.0; } } return A; } public int rows() { return getRowDimension(); } public int cols() { return getColumnDimension(); } /** * 取出第j列作为一个列向量 * @param j * @return */ public Matrix col(int j) { double[][] X = new double[m][1]; for (int i = 0; i < m; i++) { X[i][0] = A[i][j]; } return new Matrix(X); } /** * 取出第i行作为一个行向量 * @param i * @return */ public Matrix row(int i) { double[][] X = new double[1][n]; for (int j = 0; j < n; j++) { X[0][j] = A[i][j]; } return new Matrix(X); } public Matrix block(int i, int j, int p, int q) { return getMatrix(i, i + p - 1, j, j + q - 1); } /** * 返回矩阵的立方(以数组形式) * @return */ public double[][] cube()
{ double[][] X = new double[m][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { X[i][j] = Math.pow(A[i][j], 3.); } } return X; } public void setZero() { for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { A[i][j] = 0.; } } } public void save(DataOutputStream out) throws Exception { out.writeInt(m); out.writeInt(n); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { out.writeDouble(A[i][j]); } } } public boolean load(ByteArray byteArray) { m = byteArray.nextInt(); n = byteArray.nextInt(); A = new double[m][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { A[i][j] = byteArray.nextDouble(); } } return true; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dependency\nnparser\Matrix.java
1
请完成以下Java代码
public static int waitForExample() throws IOException, InterruptedException { ProcessBuilder builder = new ProcessBuilder("notepad.exe"); Process process = builder.start(); return process.waitFor(); } public static int exitValueExample() throws IOException { ProcessBuilder builder = new ProcessBuilder("notepad.exe"); Process process = builder.start(); process.destroy(); return process.exitValue(); } public static void destroyExample() throws IOException, InterruptedException { ProcessBuilder builder = new ProcessBuilder("notepad.exe"); Process process = builder.start(); Thread.sleep(10000); process.destroy(); } public static void destroyForciblyExample() throws IOException, InterruptedException { ProcessBuilder builder = new ProcessBuilder("notepad.exe"); Process process = builder.start(); Thread.sleep(10000); process.destroy(); if (process.isAlive()) { process.destroyForcibly(); } }
public static void outputStreamDemo() throws IOException, InterruptedException { Logger log = Logger.getLogger(ProcessUnderstanding.class.getName()); Process pr = Runtime.getRuntime() .exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\ChildProcess.java"); final Process process = Runtime.getRuntime() .exec("java -cp src/main/java com.baeldung.java9.process.ChildProcess"); try (Writer w = new OutputStreamWriter(process.getOutputStream(), "UTF-8")) { w.write("send to child\n"); } new Thread(() -> { try { int c; while ((c = process.getInputStream() .read()) != -1) System.out.write((byte) c); } catch (Exception e) { e.printStackTrace(); } }).start(); // send to child log.log(Level.INFO, "rc=" + process.waitFor()); } }
repos\tutorials-master\core-java-modules\core-java-os-2\src\main\java\com\baeldung\java9\process\ProcessUnderstanding.java
1
请在Spring Boot框架中完成以下Java代码
public RestVariable getVariableFromRequest(boolean includeBinary, String varInstanceId) { HistoricVariableInstance varObject = historyService.createHistoricVariableInstanceQuery().id(varInstanceId).singleResult(); if (varObject == null) { throw new FlowableObjectNotFoundException("Historic variable instance '" + varInstanceId + "' couldn't be found.", VariableInstanceEntity.class); } else { if (restApiInterceptor != null) { restApiInterceptor.accessHistoryVariableInfoById(varObject); } return restResponseFactory.createRestVariable(varObject.getVariableName(), varObject.getValue(), null, varInstanceId, CmmnRestResponseFactory.VARIABLE_HISTORY_VARINSTANCE, includeBinary); } } protected void addVariables(HistoricVariableInstanceQuery variableInstanceQuery, List<QueryVariable> variables) { for (QueryVariable variable : variables) { if (variable.getVariableOperation() == null) { throw new FlowableIllegalArgumentException("Variable operation is missing for variable: " + variable.getName()); } if (variable.getValue() == null) { throw new FlowableIllegalArgumentException("Variable value is missing for variable: " + variable.getName()); }
boolean nameLess = variable.getName() == null; Object actualValue = restResponseFactory.getVariableValue(variable); // A value-only query is only possible using equals-operator if (nameLess) { throw new FlowableIllegalArgumentException("Value-only query (without a variable-name) is not supported"); } switch (variable.getVariableOperation()) { case EQUALS: variableInstanceQuery.variableValueEquals(variable.getName(), actualValue); break; default: throw new FlowableIllegalArgumentException("Unsupported variable query operation: " + variable.getVariableOperation()); } } } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\history\variable\HistoricVariableInstanceBaseResource.java
2
请完成以下Java代码
public void process(ToEdqsMsg edqsMsg, boolean backup) { log.trace("Processing message: {}", edqsMsg); if (edqsMsg.hasEventMsg()) { EdqsEventMsg eventMsg = edqsMsg.getEventMsg(); TenantId tenantId = getTenantId(edqsMsg); ObjectType objectType = ObjectType.valueOf(eventMsg.getObjectType()); EdqsEventType eventType = EdqsEventType.valueOf(eventMsg.getEventType()); Long version = eventMsg.hasVersion() ? eventMsg.getVersion() : null; EdqsObject object = mapper.deserialize(objectType, eventMsg.getData().toByteArray(), false); if (version != null) { if (!versionsStore.isNew(mapper.getKey(object), version)) { return; } } else if (!ObjectType.unversionedTypes.contains(objectType)) { log.warn("[{}] {} doesn't have version: {}", tenantId, objectType, object); } if (backup) { stateService.save(tenantId, objectType, object.stringKey(), eventType, edqsMsg); } int count = counter.incrementAndGet(); if (count % 100000 == 0) { log.info("Processed {} events", count); } EdqsEvent event = EdqsEvent.builder() .tenantId(tenantId) .objectType(objectType) .eventType(eventType) .object(object) .build(); log.debug("Processing event: {}", event); repository.processEvent(event); }
} private TenantId getTenantId(ToEdqsMsg edqsMsg) { return TenantId.fromUUID(new UUID(edqsMsg.getTenantIdMSB(), edqsMsg.getTenantIdLSB())); } private CustomerId getCustomerId(ToEdqsMsg edqsMsg) { if (edqsMsg.getCustomerIdMSB() != 0 && edqsMsg.getCustomerIdLSB() != 0) { return new CustomerId(new UUID(edqsMsg.getCustomerIdMSB(), edqsMsg.getCustomerIdLSB())); } else { return null; } } @PreDestroy public void destroy() throws InterruptedException { eventConsumer.stop(); eventConsumer.awaitStop(); responseTemplate.stop(); stateService.stop(); versionsStore.shutdown(); } }
repos\thingsboard-master\common\edqs\src\main\java\org\thingsboard\server\edqs\processor\EdqsProcessor.java
1
请完成以下Java代码
public void setC_BPartner_ID (int C_BPartner_ID) { if (C_BPartner_ID < 1) set_ValueNoCheck (COLUMNNAME_C_BPartner_ID, null); else set_ValueNoCheck (COLUMNNAME_C_BPartner_ID, Integer.valueOf(C_BPartner_ID)); } /** Get Geschäftspartner. @return Bezeichnet einen Geschäftspartner */ @Override public int getC_BPartner_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_BPartner_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Zugesagter Termin. @param DatePromised Zugesagter Termin für diesen Auftrag */ @Override public void setDatePromised (java.sql.Timestamp DatePromised) { set_ValueNoCheck (COLUMNNAME_DatePromised, DatePromised); } /** Get Zugesagter Termin. @return Zugesagter Termin für diesen Auftrag */ @Override public java.sql.Timestamp getDatePromised () { return (java.sql.Timestamp)get_Value(COLUMNNAME_DatePromised); } @Override public org.compiere.model.I_M_Product getM_Product() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class); } @Override public void setM_Product(org.compiere.model.I_M_Product M_Product) { set_ValueFromPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class, M_Product); } /** Set Produkt. @param M_Product_ID Produkt, Leistung, Artikel */ @Override public void setM_Product_ID (int M_Product_ID) { if (M_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID)); } /** Get Produkt. @return Produkt, Leistung, Artikel */ @Override public int getM_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Bestellte Menge.
@param QtyOrdered Bestellte Menge */ @Override public void setQtyOrdered (java.math.BigDecimal QtyOrdered) { set_Value (COLUMNNAME_QtyOrdered, QtyOrdered); } /** Get Bestellte Menge. @return Bestellte Menge */ @Override public java.math.BigDecimal getQtyOrdered () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyOrdered); if (bd == null) return Env.ZERO; return bd; } /** Set Zusagbar. @param QtyPromised Zusagbar */ @Override public void setQtyPromised (java.math.BigDecimal QtyPromised) { set_Value (COLUMNNAME_QtyPromised, QtyPromised); } /** Get Zusagbar. @return Zusagbar */ @Override public java.math.BigDecimal getQtyPromised () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyPromised); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java-gen\de\metas\procurement\base\model\X_PMM_PurchaseCandidate_Weekly.java
1
请完成以下Java代码
public void setDescription (java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Beschreibung. @return Beschreibung */ @Override public java.lang.String getDescription () { return (java.lang.String)get_Value(COLUMNNAME_Description); } /** Set MSV3 Customer Config. @param MSV3_Customer_Config_ID MSV3 Customer Config */ @Override public void setMSV3_Customer_Config_ID (int MSV3_Customer_Config_ID) { if (MSV3_Customer_Config_ID < 1) set_ValueNoCheck (COLUMNNAME_MSV3_Customer_Config_ID, null); else set_ValueNoCheck (COLUMNNAME_MSV3_Customer_Config_ID, Integer.valueOf(MSV3_Customer_Config_ID)); } /** Get MSV3 Customer Config. @return MSV3 Customer Config */ @Override public int getMSV3_Customer_Config_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_Customer_Config_ID); if (ii == null) return 0; return ii.intValue();
} /** Set Kennwort. @param Password Kennwort */ @Override public void setPassword (java.lang.String Password) { set_Value (COLUMNNAME_Password, Password); } /** Get Kennwort. @return Kennwort */ @Override public java.lang.String getPassword () { return (java.lang.String)get_Value(COLUMNNAME_Password); } /** Set Nutzerkennung. @param UserID Nutzerkennung */ @Override public void setUserID (java.lang.String UserID) { set_Value (COLUMNNAME_UserID, UserID); } /** Get Nutzerkennung. @return Nutzerkennung */ @Override public java.lang.String getUserID () { return (java.lang.String)get_Value(COLUMNNAME_UserID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.server-peer-metasfresh\src\main\java-gen\de\metas\vertical\pharma\msv3\server\model\X_MSV3_Customer_Config.java
1
请完成以下Java代码
public void setUserElementString5 (final @Nullable java.lang.String UserElementString5) { set_Value (COLUMNNAME_UserElementString5, UserElementString5); } @Override public java.lang.String getUserElementString5() { return get_ValueAsString(COLUMNNAME_UserElementString5); } @Override public void setUserElementString6 (final @Nullable java.lang.String UserElementString6) { set_Value (COLUMNNAME_UserElementString6, UserElementString6); } @Override public java.lang.String getUserElementString6()
{ return get_ValueAsString(COLUMNNAME_UserElementString6); } @Override public void setUserElementString7 (final @Nullable java.lang.String UserElementString7) { set_Value (COLUMNNAME_UserElementString7, UserElementString7); } @Override public java.lang.String getUserElementString7() { return get_ValueAsString(COLUMNNAME_UserElementString7); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-gen\de\metas\acct\model\X_SAP_GLJournalLine.java
1
请完成以下Java代码
public String getExtension() { return m_extension; } /** * Accept File * @param file file to be tested * @return true if OK */ public boolean accept(File file) { // Need to accept directories if (file.isDirectory()) return true; String ext = file.getName(); int pos = ext.lastIndexOf('.'); // No extension if (pos == -1) return false; ext = ext.substring(pos+1); if (m_extension.equalsIgnoreCase(ext)) return true; return false; } // accept /** * Verify file name with filer * @param file file * @param filter filter * @return file name */ public static String getFileName(File file, FileFilter filter) { return getFile(file, filter).getAbsolutePath(); } // getFileName /** * Verify file with filter * @param file file * @param filter filter * @return file */ public static File getFile(File file, FileFilter filter) { String fName = file.getAbsolutePath(); if (fName == null || fName.equals("")) fName = "Adempiere"; // ExtensionFileFilter eff = null;
if (filter instanceof ExtensionFileFilter) eff = (ExtensionFileFilter)filter; else return file; // int pos = fName.lastIndexOf('.'); // No extension if (pos == -1) { fName += '.' + eff.getExtension(); return new File(fName); } String ext = fName.substring(pos+1); // correct extension if (ext.equalsIgnoreCase(eff.getExtension())) return file; fName += '.' + eff.getExtension(); return new File(fName); } // getFile } // ExtensionFileFilter
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\ExtensionFileFilter.java
1
请完成以下Java代码
public DefaultHttpGraphQlClientBuilder codecConfigurer(Consumer<CodecConfigurer> codecConfigurerConsumer) { this.webClientBuilder.codecs(codecConfigurerConsumer::accept); return this; } @Override public DefaultHttpGraphQlClientBuilder webClient(Consumer<WebClient.Builder> configurer) { configurer.accept(this.webClientBuilder); return this; } @Override public HttpGraphQlClient build() { // Pass the codecs to the parent for response decoding this.webClientBuilder.codecs((configurer) -> setJsonCodecs( CodecDelegate.findJsonEncoder(configurer), CodecDelegate.findJsonDecoder(configurer))); WebClient webClient = this.webClientBuilder.build(); GraphQlClient graphQlClient = super.buildGraphQlClient(new HttpGraphQlTransport(webClient)); return new DefaultHttpGraphQlClient(graphQlClient, webClient, getBuilderInitializer()); } /** * Default {@link HttpGraphQlClient} implementation. */ private static class DefaultHttpGraphQlClient extends AbstractDelegatingGraphQlClient implements HttpGraphQlClient { private final WebClient webClient; private final Consumer<AbstractGraphQlClientBuilder<?>> builderInitializer; DefaultHttpGraphQlClient( GraphQlClient delegate, WebClient webClient, Consumer<AbstractGraphQlClientBuilder<?>> builderInitializer) {
super(delegate); Assert.notNull(webClient, "WebClient is required"); Assert.notNull(builderInitializer, "`builderInitializer` is required"); this.webClient = webClient; this.builderInitializer = builderInitializer; } @Override public DefaultHttpGraphQlClientBuilder mutate() { DefaultHttpGraphQlClientBuilder builder = new DefaultHttpGraphQlClientBuilder(this.webClient); this.builderInitializer.accept(builder); return builder; } } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\client\DefaultHttpGraphQlClientBuilder.java
1
请完成以下Java代码
default void setShipmentSchedule(final I_C_Invoice_Candidate ic) { /* do nothing */ }; /** * * Method responsible for setting * <ul> * <li>Bill_BPartner_ID * <li>Bill_Location_ID * <li>Bill_User_ID * </ul> * of the given invoice candidate. */ void setBPartnerData(I_C_Invoice_Candidate ic); default void setInvoiceScheduleAndDateToInvoice(@NonNull final I_C_Invoice_Candidate ic) { final IBPartnerDAO bpartnerDAO = Services.get(IBPartnerDAO.class); final IInvoiceCandBL invoiceCandBL = Services.get(IInvoiceCandBL.class); ic.setC_InvoiceSchedule_ID(bpartnerDAO.getById(ic.getBill_BPartner_ID()).getC_InvoiceSchedule_ID()); invoiceCandBL.set_DateToInvoice_DefaultImpl(ic); } /** * Price and tax info calculation result. * <p> * All fields are optional and only those filled will be set back to invoice candidate. */ @lombok.Value
@lombok.Builder class PriceAndTax { public static final PriceAndTax NONE = builder().build(); PricingSystemId pricingSystemId; PriceListVersionId priceListVersionId; CurrencyId currencyId; BigDecimal priceEntered; BigDecimal priceActual; UomId priceUOMId; Percent discount; InvoicableQtyBasedOn invoicableQtyBasedOn; Boolean taxIncluded; TaxId taxId; TaxCategoryId taxCategoryId; BigDecimal compensationGroupBaseAmt; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\spi\IInvoiceCandidateHandler.java
1
请完成以下Java代码
public static void main(String[] args) { String serviceUrl = "https://cas.8f8.com.cn:8443/cas/p3/serviceValidate"; String service = "http://localhost:3003/user/login"; String ticket = "ST-5-1g-9cNES6KXNRwq-GuRET103sm0-DESKTOP-VKLS8B3"; String res = getStValidate(serviceUrl,ticket, service); System.out.println("---------res-----"+res); } /** * 验证ST */ public static String getStValidate(String url, String st, String service){ try { url = url+"?service="+service+"&ticket="+st; CloseableHttpClient httpclient = createHttpClientWithNoSsl(); HttpGet httpget = new HttpGet(url); HttpResponse response = httpclient.execute(httpget); String res = readResponse(response); return res == null ? null : (res == "" ? null : res); } catch (Exception e) { e.printStackTrace(); } return ""; } /** * 读取 response body 内容为字符串 * * @param response * @return * @throws IOException */ private static String readResponse(HttpResponse response) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String result = new String(); String line; while ((line = in.readLine()) != null) { result += line; } return result;
} /** * 创建模拟客户端(针对 https 客户端禁用 SSL 验证) * * @param cookieStore 缓存的 Cookies 信息 * @return * @throws Exception */ private static CloseableHttpClient createHttpClientWithNoSsl() throws Exception { // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[]{ new X509TrustManager() { @Override public X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkClientTrusted(X509Certificate[] certs, String authType) { // don't check } @Override public void checkServerTrusted(X509Certificate[] certs, String authType) { // don't check } } }; SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(null, trustAllCerts, null); LayeredConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(ctx); return HttpClients.custom() .setSSLSocketFactory(sslSocketFactory) .build(); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\cas\util\CasServiceUtil.java
1
请完成以下Java代码
public class ProgramaticCalloutProvider implements ICalloutProvider, IProgramaticCalloutProvider { private static final transient Logger logger = LogManager.getLogger(ProgramaticCalloutProvider.class); private final Map<String, TableCalloutsMap> registeredCalloutsByTableId = new ConcurrentHashMap<>(); @Override public TableCalloutsMap getCallouts(final Properties ctx, final String tableName) { final TableCalloutsMap callouts = registeredCalloutsByTableId.get(tableName.toLowerCase()); return callouts == null ? TableCalloutsMap.EMPTY : callouts; } @Override public boolean registerCallout( @NonNull final String tableName, @NonNull final String columnName, @NonNull final ICalloutInstance callout) { final String tableNameToUse = tableName.toLowerCase(); // // Add the new callout to our internal map final AtomicBoolean registered = new AtomicBoolean(false); registeredCalloutsByTableId.compute(tableNameToUse, (tableNameKey, currentTabCalloutsMap) -> { if (currentTabCalloutsMap == null) { registered.set(true); return TableCalloutsMap.of(columnName, callout); } else { final TableCalloutsMap newTabCalloutsMap = currentTabCalloutsMap.compose(columnName, callout); registered.set(newTabCalloutsMap != currentTabCalloutsMap); return newTabCalloutsMap; } }); // Stop here if it was not registered if (!registered.get()) { return false; } logger.debug("Registered callout for {}.{}: {}", tableNameToUse, columnName, callout); // Make sure this provider is registered to ICalloutFactory. // We assume the factory won't register it twice. Services.get(ICalloutFactory.class).registerCalloutProvider(this); return true; } @Override public boolean registerAnnotatedCallout(final Object annotatedCalloutObj) {
final List<AnnotatedCalloutInstance> calloutInstances = new AnnotatedCalloutInstanceFactory() .setAnnotatedCalloutObject(annotatedCalloutObj) .create(); if (calloutInstances.isEmpty()) { throw new AdempiereException("No binding columns found for " + annotatedCalloutObj + " (class=" + annotatedCalloutObj.getClass() + ")"); } boolean registered = false; for (final AnnotatedCalloutInstance calloutInstance : calloutInstances) { final String tableName = calloutInstance.getTableName(); for (final String columnName : calloutInstance.getColumnNames()) { final boolean columNameRegistered = registerCallout(tableName, columnName, calloutInstance); if (columNameRegistered) { registered = true; } } } return registered; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\callout\spi\impl\ProgramaticCalloutProvider.java
1
请完成以下Java代码
private List<PurchaseCandidate> saveRows(@NonNull final PurchaseView purchaseView) { final List<PurchaseRow> rows = purchaseView.getRows(); return PurchaseRowsSaver.builder() .purchaseCandidatesRepo(purchaseCandidatesRepo) .build() .save(rows); } private boolean isSalesOrderCompleted(@NonNull final List<PurchaseCandidate> purchaseCandidates) { final IOrderDAO ordersRepo = Services.get(IOrderDAO.class); final OrderId salesOrderId = getSingleSalesOrderId(purchaseCandidates); final I_C_Order salesOrder = ordersRepo.getById(salesOrderId); final DocStatus docStatus = DocStatus.ofCode(salesOrder.getDocStatus()); return docStatus.isCompleted();
} private static final OrderId getSingleSalesOrderId(@NonNull final List<PurchaseCandidate> purchaseCandidates) { Check.assumeNotEmpty(purchaseCandidates, "purchaseCandidates not empty"); return purchaseCandidates.stream() .map(PurchaseCandidate::getSalesOrderAndLineIdOrNull) .filter(Objects::nonNull) .map(OrderAndLineId::getOrderId) .distinct() .collect(GuavaCollectors.singleElementOrThrow(() -> new AdempiereException("More or less than one salesOrderId found in the given purchaseCandidates") .appendParametersToMessage() .setParameter("purchaseCandidates", purchaseCandidates))); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\sales\purchasePlanning\view\SalesOrder2PurchaseViewFactory.java
1
请完成以下Java代码
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); } /** Direction AD_Reference_ID=540086 */ public static final int DIRECTION_AD_Reference_ID=540086; /** Import = I */ public static final String DIRECTION_Import = "I"; /** Export = E */ public static final String DIRECTION_Export = "E"; /** Set Richtung. @param Direction Richtung */ public void setDirection (String Direction) { set_Value (COLUMNNAME_Direction, Direction); } /** Get Richtung. @return Richtung */ public String getDirection () { return (String)get_Value(COLUMNNAME_Direction); } /** Set Konnektor-Typ. @param ImpEx_ConnectorType_ID Konnektor-Typ */ public void setImpEx_ConnectorType_ID (int ImpEx_ConnectorType_ID) { if (ImpEx_ConnectorType_ID < 1) set_ValueNoCheck (COLUMNNAME_ImpEx_ConnectorType_ID, null); else set_ValueNoCheck (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_ConnectorType.java
1
请完成以下Java代码
public class RcCaptchaFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { int width = 57;// 图像宽度 int height = 21;// 图像高度 // 定义输出格式 response.setContentType("image/jpeg"); ServletOutputStream out = response.getOutputStream(); // 准备缓冲图像,不支持表单 BufferedImage bimg = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR); Random r = new Random(); // 获取图形上下文环境 Graphics gc = bimg.getGraphics(); // 设定背景色并进行填充 gc.setColor(getRandColor(200, 250)); gc.fillRect(0, 0, width, height); // 设置图形上下文环境字体 gc.setFont(new Font("Times New Roman", Font.PLAIN, 18)); // 随机产生200条干扰线条,使图像中的认证码不易被其他分析程序探测到 gc.setColor(getRandColor(160, 200)); for (int i = 0; i < 200; i++) { int x1 = r.nextInt(width); int y1 = r.nextInt(height); int x2 = r.nextInt(15); int y2 = r.nextInt(15); gc.drawLine(x1, y1, x1 + x2, y1 + y2); } // 随机产生100个干扰点,使图像中的验证码不易被其他分析程序探测到 gc.setColor(getRandColor(120, 240)); for (int i = 0; i < 100; i++) { int x = r.nextInt(width); int y = r.nextInt(height); gc.drawOval(x, y, 0, 0); } // 随机产生4个数字的验证码 String rs = ""; String rn = ""; for (int i = 0; i < 4; i++) { rn = String.valueOf(r.nextInt(10));
rs += rn; gc.setColor(new Color(20 + r.nextInt(110), 20 + r.nextInt(110), 20 + r.nextInt(110))); gc.drawString(rn, 13 * i + 1, 16); } // 释放图形上下文环境 gc.dispose(); request.getSession().setAttribute("rcCaptcha", rs); ImageIO.write(bimg, "jpeg", out); try { out.flush(); } finally { out.close(); } } public Color getRandColor(int fc, int bc) { Random r = new Random(); if (fc > 255) { fc = 255; } if (bc > 255) { bc = 255; } int red = fc + r.nextInt(bc - fc);// 红 int green = fc + r.nextInt(bc - fc);// 绿 int blue = fc + r.nextInt(bc - fc);// 蓝 return new Color(red, green, blue); } }
repos\roncoo-pay-master\roncoo-pay-web-boss\src\main\java\com\roncoo\pay\permission\shiro\filter\RcCaptchaFilter.java
1
请完成以下Java代码
public void addEntryCriteria(CmmnSentryDeclaration entryCriteria) { this.entryCriteria.add(entryCriteria); } // exitCriteria public List<CmmnSentryDeclaration> getExitCriteria() { return exitCriteria; } public void setExitCriteria(List<CmmnSentryDeclaration> exitCriteria) { this.exitCriteria = exitCriteria; } public void addExitCriteria(CmmnSentryDeclaration exitCriteria) { this.exitCriteria.add(exitCriteria); } // variable listeners /** * Returns a map of all variable listeners defined on this activity or any of * its parents activities. The map's key is the id of the respective activity * the listener is defined on. */ public Map<String, List<VariableListener<?>>> getVariableListeners(String eventName, boolean includeCustomListeners) { Map<String, Map<String, List<VariableListener<?>>>> listenerCache; if (includeCustomListeners) { if (resolvedVariableListeners == null) { resolvedVariableListeners = new HashMap<String, Map<String,List<VariableListener<?>>>>(); } listenerCache = resolvedVariableListeners; } else { if (resolvedBuiltInVariableListeners == null) { resolvedBuiltInVariableListeners = new HashMap<String, Map<String,List<VariableListener<?>>>>(); } listenerCache = resolvedBuiltInVariableListeners;
} Map<String, List<VariableListener<?>>> resolvedListenersForEvent = listenerCache.get(eventName); if (resolvedListenersForEvent == null) { resolvedListenersForEvent = new HashMap<String, List<VariableListener<?>>>(); listenerCache.put(eventName, resolvedListenersForEvent); CmmnActivity currentActivity = this; while (currentActivity != null) { List<VariableListener<?>> localListeners = null; if (includeCustomListeners) { localListeners = currentActivity.getVariableListenersLocal(eventName); } else { localListeners = currentActivity.getBuiltInVariableListenersLocal(eventName); } if (localListeners != null && !localListeners.isEmpty()) { resolvedListenersForEvent.put(currentActivity.getId(), localListeners); } currentActivity = currentActivity.getParent(); } } return resolvedListenersForEvent; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\model\CmmnActivity.java
1
请完成以下Java代码
public AbstractVariableCmd disableLogUserOperation() { this.preventLogUserOperation = true; return this; } public Void execute(CommandContext commandContext) { this.commandContext = commandContext; AbstractVariableScope scope = getEntity(); if (scope != null) { executeOperation(scope); onSuccess(scope); if(!preventLogUserOperation) { logVariableOperation(scope); } } return null;
}; protected abstract AbstractVariableScope getEntity(); protected abstract ExecutionEntity getContextExecution(); protected abstract void logVariableOperation(AbstractVariableScope scope); protected abstract void executeOperation(AbstractVariableScope scope); protected abstract String getLogEntryOperation(); protected void onSuccess(AbstractVariableScope scope) { ExecutionEntity contextExecution = getContextExecution(); if (contextExecution != null) { contextExecution.dispatchDelayedEventsAndPerformOperation((Callback<PvmExecutionImpl, Void>) null); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\AbstractVariableCmd.java
1
请完成以下Java代码
public boolean accept(T model) { final Object value = InterfaceWrapperHelper.getValueOrNull(model, columnName); if (value == null) { return false; } else if (value instanceof String) { return ((String)value).endsWith(endsWithString); } else { throw new IllegalArgumentException("Invalid '" + columnName + "' value for " + model); } } private boolean sqlBuilt = false; private String sqlWhereClause = null; private List<Object> sqlParams = null;
private void buildSql() { if (sqlBuilt) { return; } final String sqlWhereClause = columnName + " LIKE " + "'%'||? "; this.sqlParams = Collections.singletonList(endsWithString); this.sqlWhereClause = sqlWhereClause; this.sqlBuilt = true; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\EndsWithQueryFilter.java
1
请完成以下Java代码
public <T1> T1[] toArray(T1[] a) { Collection<T> modelElementCollection = ModelUtil.getModelElementCollection(getView(referenceSourceElement), (ModelInstanceImpl) referenceSourceElement.getModelInstance()); return modelElementCollection.toArray(a); } public boolean add(T t) { if (!contains(t)) { performAddOperation(referenceSourceElement, t); } return true; } public boolean remove(Object o) { ModelUtil.ensureInstanceOf(o, ModelElementInstanceImpl.class); performRemoveOperation(referenceSourceElement, o); return true; } public boolean containsAll(Collection<?> c) { Collection<T> modelElementCollection = ModelUtil.getModelElementCollection(getView(referenceSourceElement), (ModelInstanceImpl) referenceSourceElement.getModelInstance()); return modelElementCollection.containsAll(c); } public boolean addAll(Collection<? extends T> c) { boolean result = false; for (T o: c) { result |= add(o); } return result; } public boolean removeAll(Collection<?> c) { boolean result = false; for (Object o: c) { result |= remove(o); } return result; } public boolean retainAll(Collection<?> c) { throw new UnsupportedModelOperationException("retainAll()", "not implemented"); } public void clear() { performClearOperation(referenceSourceElement); } }; } protected void performClearOperation(ModelElementInstance referenceSourceElement) { setReferenceIdentifier(referenceSourceElement, ""); }
@Override protected void setReferenceIdentifier(ModelElementInstance referenceSourceElement, String referenceIdentifier) { if (referenceIdentifier != null && !referenceIdentifier.isEmpty()) { super.setReferenceIdentifier(referenceSourceElement, referenceIdentifier); } else { referenceSourceAttribute.removeAttribute(referenceSourceElement); } } /** * @param referenceSourceElement * @param o */ protected void performRemoveOperation(ModelElementInstance referenceSourceElement, Object o) { removeReference(referenceSourceElement, (ModelElementInstance) o); } protected void performAddOperation(ModelElementInstance referenceSourceElement, T referenceTargetElement) { String identifier = getReferenceIdentifier(referenceSourceElement); List<String> references = StringUtil.splitListBySeparator(identifier, separator); String targetIdentifier = getTargetElementIdentifier(referenceTargetElement); references.add(targetIdentifier); identifier = StringUtil.joinList(references, separator); setReferenceIdentifier(referenceSourceElement, identifier); } }
repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\type\reference\AttributeReferenceCollection.java
1
请完成以下Java代码
public static void main(String[] args) throws ExecutionException, InterruptedException { setup(); publishMessagesWithoutKey(); consumeMessages(); publishMessagesWithKey(); consumeMessages(); } private static void consumeMessages() { consumer.subscribe(Arrays.asList(TOPIC)); ConsumerRecords<String, String> records = consumer.poll(Duration.ofSeconds(5)); for (ConsumerRecord<String, String> record : records) { logger.info("Key : {}, Value : {}", record.key(), record.value()); } } private static void publishMessagesWithKey() throws ExecutionException, InterruptedException { for (int i = 1; i <= 10; i++) { ProducerRecord<String, String> record = new ProducerRecord<>(TOPIC, MESSAGE_KEY, String.valueOf(i)); Future<RecordMetadata> future = producer.send(record); RecordMetadata metadata = future.get(); logger.info(String.valueOf(metadata.partition())); } } private static void publishMessagesWithoutKey() throws ExecutionException, InterruptedException { for (int i = 1; i <= 10; i++) { ProducerRecord<String, String> record = new ProducerRecord<>(TOPIC, String.valueOf(i)); Future<RecordMetadata> future = producer.send(record); RecordMetadata metadata = future.get(); logger.info(String.valueOf(metadata.partition()));
} } private static void setup() { Properties adminProperties = new Properties(); adminProperties.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); Properties producerProperties = new Properties(); producerProperties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); producerProperties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); producerProperties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); Properties consumerProperties = new Properties(); consumerProperties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); consumerProperties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); consumerProperties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); consumerProperties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); consumerProperties.put(ConsumerConfig.GROUP_ID_CONFIG, UUID.randomUUID() .toString()); admin = Admin.create(adminProperties); producer = new KafkaProducer<>(producerProperties); consumer = new KafkaConsumer<>(consumerProperties); admin.createTopics(Collections.singleton(new NewTopic(TOPIC, PARTITIONS, REPLICATION_FACTOR))); } }
repos\tutorials-master\apache-kafka\src\main\java\com\baeldung\kafka\message\MessageWithKey.java
1
请完成以下Java代码
public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public BigDecimal getPrice() { return price; }
public void setPrice(BigDecimal price) { this.price = price; } public Date getCreatedAt() { return createdAt; } public void setCreatedAt(Date createdAt) { this.createdAt = createdAt; } public Date getUpdatedAt() { return updatedAt; } public void setUpdatedAt(Date updatedAt) { this.updatedAt = updatedAt; } }
repos\Spring-Boot-Advanced-Projects-main\springboot-crud-hibernate-example\src\main\java\net\alanbinu\springboot\model\Product.java
1
请完成以下Java代码
public void onAuthenticationSuccess(final HttpServletRequest request, final HttpServletResponse response, final Authentication authentication) throws IOException { handle(request, response, authentication); clearAuthenticationAttributes(request); } // IMPL protected void handle(final HttpServletRequest request, final HttpServletResponse response, final Authentication authentication) throws IOException { final String targetUrl = determineTargetUrl(authentication); if (response.isCommitted()) { logger.debug("Response has already been committed. Unable to redirect to " + targetUrl); return; } redirectStrategy.sendRedirect(request, response, targetUrl); } protected String determineTargetUrl(final Authentication authentication) { boolean isUser = false; boolean isAdmin = false; final Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities(); for (final GrantedAuthority grantedAuthority : authorities) { if (grantedAuthority.getAuthority().equals("ROLE_USER")) { isUser = true; break; } else if (grantedAuthority.getAuthority().equals("ROLE_ADMIN")) { isAdmin = true; break; } }
if (isUser) { return "/homepage"; } else if (isAdmin) { return "/console"; } else { throw new IllegalStateException(); } } /** * Removes temporary authentication-related data which may have been stored in the session * during the authentication process. */ protected final void clearAuthenticationAttributes(final HttpServletRequest request) { final HttpSession session = request.getSession(false); if (session == null) { return; } session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION); } public void setRedirectStrategy(final RedirectStrategy redirectStrategy) { this.redirectStrategy = redirectStrategy; } protected RedirectStrategy getRedirectStrategy() { return redirectStrategy; } }
repos\tutorials-master\spring-security-modules\spring-security-web-mvc\src\main\java\com\baeldung\security\MySimpleUrlAuthenticationSuccessHandler.java
1
请完成以下Java代码
public Object getParameterDefaultValue(final IProcessDefaultParameter parameter) { if (PARAM_IsAllQty.equals(parameter.getColumnName())) { return getSelectedPickingSlotRows().size() > 1; } else if (PARAM_QtyCUsPerTU.equals(parameter.getColumnName())) { final List<PickingSlotRow> pickingSlotRows = getSelectedPickingSlotRows(); if (pickingSlotRows.size() != 1) { return DEFAULT_VALUE_NOTAVAILABLE; } return pickingSlotRows.get(0).getHuQtyCU(); } else { return DEFAULT_VALUE_NOTAVAILABLE; } } @Override protected String doIt() { final List<I_M_HU> fromCUs = getSourceCUs(); final IAllocationSource source = HUListAllocationSourceDestination.of(fromCUs) .setDestroyEmptyHUs(true); final IAllocationDestination destination = HUListAllocationSourceDestination.of(getTargetTU()); final HULoader huLoader = HULoader.of(source, destination) .setAllowPartialUnloads(false) .setAllowPartialLoads(false); // // Unload CU/CUs and Load to selected TU final List<Integer> huIdsDestroyedCollector = new ArrayList<>(); if (fromCUs.size() == 1) { huLoader.load(prepareUnloadRequest(fromCUs.get(0), getQtyCUsPerTU()) .setForceQtyAllocation(true) .addEmptyHUListener(EmptyHUListener.doBeforeDestroyed(hu -> huIdsDestroyedCollector.add(hu.getM_HU_ID()))) .create()); } else { final IHUContextFactory huContextFactory = Services.get(IHUContextFactory.class); final IMutableHUContext huContext = huContextFactory.createMutableHUContext(); huContext.addEmptyHUListener(EmptyHUListener.doBeforeDestroyed(hu -> huIdsDestroyedCollector.add(hu.getM_HU_ID()))); huLoader.unloadAllFromSource(huContext); } // Remove from picking slots all destroyed HUs pickingCandidateService.inactivateForHUIds(HuId.fromRepoIds(huIdsDestroyedCollector));
return MSG_OK; } @Override protected void postProcess(final boolean success) { if (!success) { return; } // Invalidate views getPickingSlotsClearingView().invalidateAll(); getPackingHUsView().invalidateAll(); } private BigDecimal getQtyCUsPerTU() { if (isAllQty) { return getSingleSelectedPickingSlotRow().getHuQtyCU(); } else { final BigDecimal qtyCU = this.qtyCUsPerTU; if (qtyCU == null || qtyCU.signum() <= 0) { throw new FillMandatoryException(PARAM_QtyCUsPerTU); } return qtyCU; } } private List<I_M_HU> getSourceCUs() { return getSelectedPickingSlotRows() .stream() .peek(huRow -> Check.assume(huRow.isCU(), "row {} shall be a CU", huRow)) .map(PickingSlotRow::getHuId) .distinct() .map(huId -> load(huId, I_M_HU.class)) .collect(ImmutableList.toImmutableList()); } private I_M_HU getTargetTU() { final HUEditorRow huRow = getSingleSelectedPackingHUsRow(); Check.assume(huRow.isTU(), "row {} shall be a TU", huRow); return huRow.getM_HU(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingslotsClearing\process\WEBUI_PickingSlotsClearingView_TakeOutCUsAndAddToTU.java
1
请完成以下Java代码
private void applyCandidateProcessors(final Properties ctx, final IShipmentSchedulesDuringUpdate candidates) { candidateProcessors.doUpdateAfterFirstPass(ctx, candidates); } /** * 07400 also update the M_Warehouse_ID; an order might have been reactivated and the warehouse might have been changed. */ private void updateWarehouseId(@NonNull final I_M_ShipmentSchedule sched) { final WarehouseId warehouseId = shipmentScheduleReferencedLineFactory .createFor(sched) .getWarehouseId(); sched.setM_Warehouse_ID(warehouseId.getRepoId()); } private void updateCatchUomId(@NonNull final I_M_ShipmentSchedule sched) { final UomId catchUOMId = sched.isCatchWeight() ? productsService.getCatchUOMId(ProductId.ofRepoId(sched.getM_Product_ID())).orElse(null) : null; sched.setCatch_UOM_ID(UomId.toRepoId(catchUOMId)); } private void invalidatePickingBOMProducts(@NonNull final List<OlAndSched> olsAndScheds, final PInstanceId addToSelectionId) { if (olsAndScheds.isEmpty()) { return; } final ImmutableSet<IShipmentScheduleSegment> pickingBOMsSegments = olsAndScheds.stream() .flatMap(this::extractPickingBOMsStorageSegments) .collect(ImmutableSet.toImmutableSet()); if (pickingBOMsSegments.isEmpty()) { return; } invalidSchedulesRepo.invalidateStorageSegments(pickingBOMsSegments, addToSelectionId); } private Stream<IShipmentScheduleSegment> extractPickingBOMsStorageSegments(final OlAndSched olAndSched) { try (final MDCCloseable ignored = ShipmentSchedulesMDC.putShipmentScheduleId(olAndSched.getShipmentScheduleId())) { final PickingBOMsReversedIndex pickingBOMsReversedIndex = pickingBOMService.getPickingBOMsReversedIndex(); final ProductId componentId = olAndSched.getProductId();
final ImmutableSet<ProductId> pickingBOMProductIds = pickingBOMsReversedIndex.getBOMProductIdsByComponentId(componentId); if (pickingBOMProductIds.isEmpty()) { return Stream.empty(); } final Set<WarehouseId> warehouseIds = warehousesRepo.getWarehouseIdsOfSamePickingGroup(olAndSched.getWarehouseId()); final LinkedHashSet<IShipmentScheduleSegment> segments = new LinkedHashSet<>(); for (final WarehouseId warehouseId : warehouseIds) { final Set<Integer> locatorRepoIds = warehousesRepo.getLocatorIds(warehouseId) .stream() .map(LocatorId::getRepoId) .collect(ImmutableSet.toImmutableSet()); for (final ProductId pickingBOMProductId : pickingBOMProductIds) { final ImmutableShipmentScheduleSegment segment = ImmutableShipmentScheduleSegment.builder() .anyBPartner() .productId(pickingBOMProductId.getRepoId()) .locatorIds(locatorRepoIds) .build(); logger.debug("Add for pickingBOMProductId={} warehouseId={}: segment={}", pickingBOMProductId.getRepoId(), warehouseId.getRepoId(), segment); segments.add(segment); } } return segments.stream(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\api\impl\ShipmentScheduleUpdater.java
1
请完成以下Java代码
class WebMvcWebApplicationTypeDeducer implements WebApplicationType.Deducer { private static final String[] INDICATOR_CLASSES = { "jakarta.servlet.Servlet", "org.springframework.web.servlet.DispatcherServlet", "org.springframework.web.context.ConfigurableWebApplicationContext" }; @Override public @Nullable WebApplicationType deduceWebApplicationType() { // Guard in case the classic module is being used and dependencies are excluded for (String indicatorClass : INDICATOR_CLASSES) { if (!ClassUtils.isPresent(indicatorClass, null)) { return null; } } return WebApplicationType.SERVLET; } static class WebMvcWebApplicationTypeDeducerRuntimeHints implements RuntimeHintsRegistrar { @Override
public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) { for (String servletIndicatorClass : INDICATOR_CLASSES) { registerTypeIfPresent(servletIndicatorClass, classLoader, hints); } } private void registerTypeIfPresent(String typeName, @Nullable ClassLoader classLoader, RuntimeHints hints) { if (ClassUtils.isPresent(typeName, classLoader)) { hints.reflection().registerType(TypeReference.of(typeName)); } } } }
repos\spring-boot-4.0.1\module\spring-boot-webmvc\src\main\java\org\springframework\boot\webmvc\WebMvcWebApplicationTypeDeducer.java
1
请完成以下Spring Boot application配置
server: port: 8888 spring: application: name: zuul-application # Zuul 配置项,对应 ZuulProperties 配置类 zuul: servlet-path: / # ZuulServlet 匹配的路径,默认为 /zuul # 路由配置项,对应 ZuulRoute Map routes: route_yudaoyuanma: path: /blog/** url: http://www.iocoder.cn route_oschina: path: /oschina/** url: https://www.oschina.net management: endpoints: web: exposure: include: '*' # 需要开放的端点。默认值只打开 health 和 info 两个端点。通过设置 * ,可以开放所有端点。 endpoint: # Health 端点配置项,对应 Health
Properties 配置类 health: enabled: true # 是否开启。默认为 true 开启。 show-details: ALWAYS # 何时显示完整的健康信息。默认为 NEVER 都不展示。可选 WHEN_AUTHORIZED 当经过授权的用户;可选 ALWAYS 总是展示。 server: port: 18888 # 单独设置端口,因为 8888 端口全部给 Zuul 了
repos\SpringBoot-Labs-master\labx-21\labx-21-sc-zuul-demo09-actuator\src\main\resources\application.yaml
2
请在Spring Boot框架中完成以下Java代码
public Recipient findByAccountName(String accountName) { Assert.hasLength(accountName); return repository.findByAccountName(accountName); } /** * {@inheritDoc} */ @Override public Recipient save(String accountName, Recipient recipient) { recipient.setAccountName(accountName); recipient.getScheduledNotifications().values() .forEach(settings -> { if (settings.getLastNotified() == null) { settings.setLastNotified(new Date()); } }); repository.save(recipient); log.info("recipient {} settings has been updated", recipient); return recipient; }
/** * {@inheritDoc} */ @Override public List<Recipient> findReadyToNotify(NotificationType type) { switch (type) { case BACKUP: return repository.findReadyForBackup(); case REMIND: return repository.findReadyForRemind(); default: throw new IllegalArgumentException(); } } /** * {@inheritDoc} */ @Override public void markNotified(NotificationType type, Recipient recipient) { recipient.getScheduledNotifications().get(type).setLastNotified(new Date()); repository.save(recipient); } }
repos\piggymetrics-master\notification-service\src\main\java\com\piggymetrics\notification\service\RecipientServiceImpl.java
2
请完成以下Spring Boot application配置
logging.structured.format.console=ecs #--- spring.config.activate.on-profile=custom logging.structured.format.console=smoketest.structuredlogging.log4j2.CustomStructuredLogFormatter #--- spring.config.activate.on-profile=on-error
logging.structured.json.customizer=smoketest.structuredlogging.log4j2.DuplicateJsonMembersCustomizer
repos\spring-boot-4.0.1\smoke-test\spring-boot-smoke-test-structured-logging-log4j2\src\main\resources\application.properties
2
请完成以下Java代码
public void init() { // Do nothing } @Benchmark @OutputTimeUnit(TimeUnit.NANOSECONDS) @BenchmarkMode(Mode.AverageTime) public void doNothing() { } @Benchmark @OutputTimeUnit(TimeUnit.NANOSECONDS) @BenchmarkMode(Mode.AverageTime) public void objectCreation() { new Object(); } @Benchmark @OutputTimeUnit(TimeUnit.NANOSECONDS) @BenchmarkMode(Mode.AverageTime) public Object pillarsOfCreation() { return new Object(); } @Benchmark @OutputTimeUnit(TimeUnit.NANOSECONDS) @BenchmarkMode(Mode.AverageTime)
public void blackHole(Blackhole blackhole) { blackhole.consume(new Object()); } @Benchmark public double foldedLog() { int x = 8; return Math.log(x); } @Benchmark public double log(Log input) { return Math.log(input.x); } }
repos\tutorials-master\jmh\src\main\java\com\baeldung\BenchMark.java
1
请完成以下Java代码
public ITrxConstraints addAllowedTrxNamePrefix(String trxNamePrefix) { return this; } @Override public ITrxConstraints removeAllowedTrxNamePrefix(String trxNamePrefix) { return this; } @Override public Set<String> getAllowedTrxNamePrefixes() { return Collections.emptySet(); } @Override public ITrxConstraints setTrxTimeoutSecs(int secs, boolean logOnly) { return this; } @Override public int getTrxTimeoutSecs() { return 0; } @Override public boolean isTrxTimeoutLogOnly() { return false; } @Override public ITrxConstraints setMaxTrx(int max) { return this; } @Override public ITrxConstraints incMaxTrx(int num) { return this; } @Override public int getMaxTrx() { return 0; } @Override public int getMaxSavepoints() { return 0; } @Override
public ITrxConstraints setMaxSavepoints(int maxSavePoints) { return this; } @Override public boolean isAllowTrxAfterThreadEnd() { return false; } @Override public ITrxConstraints setAllowTrxAfterThreadEnd(boolean allow) { return this; } @Override public void reset() { } @Override public String toString() { return "TrxConstraints have been globally disabled. Add or change AD_SysConfig " + TrxConstraintsBL.SYSCONFIG_TRX_CONSTRAINTS_DISABLED + " to enable them"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\util\trxConstraints\api\impl\TrxConstraintsDisabled.java
1
请完成以下Java代码
public List<Rating> findAllCachedRatings() { List<Rating> ratings = null; ratings = redisTemplate.keys("rating*") .stream() .map(rtId -> { try { return jsonMapper.readValue(valueOps.get(rtId), Rating.class); } catch (IOException e) { return null; } }) .collect(Collectors.toList()); return ratings; } public boolean createRating(Rating persisted) { try { valueOps.set("rating-" + persisted.getId(), jsonMapper.writeValueAsString(persisted)); setOps.add("book-" + persisted.getBookId(), "rating-" + persisted.getId()); return true; } catch (JsonProcessingException ex) { return false; } } public boolean updateRating(Rating persisted) { try { valueOps.set("rating-" + persisted.getId(), jsonMapper.writeValueAsString(persisted));
return true; } catch (JsonProcessingException e) { e.printStackTrace(); } return false; } public boolean deleteRating(Long ratingId) { Rating toDel; try { toDel = jsonMapper.readValue(valueOps.get("rating-" + ratingId), Rating.class); setOps.remove("book-" + toDel.getBookId(), "rating-" + ratingId); redisTemplate.delete("rating-" + ratingId); return true; } catch (IOException e) { e.printStackTrace(); } return false; } @Override public void afterPropertiesSet() throws Exception { this.redisTemplate = new StringRedisTemplate(cacheConnectionFactory); this.valueOps = redisTemplate.opsForValue(); this.setOps = redisTemplate.opsForSet(); jsonMapper = new ObjectMapper(); jsonMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); } }
repos\tutorials-master\spring-cloud-modules\spring-cloud-bootstrap\zipkin-log-svc-rating\src\main\java\com\baeldung\spring\cloud\bootstrap\svcrating\rating\RatingCacheRepository.java
1
请完成以下Java代码
public class ExecuteDecisionWithAuditTrailCmd extends AbstractExecuteDecisionCmd implements Command<Void> { private static final long serialVersionUID = 1L; public ExecuteDecisionWithAuditTrailCmd(ExecuteDecisionBuilderImpl decisionBuilder) { super(decisionBuilder); } public ExecuteDecisionWithAuditTrailCmd(ExecuteDecisionContext executeDecisionContext) { super(executeDecisionContext); } public ExecuteDecisionWithAuditTrailCmd(String decisionKey, Map<String, Object> variables) { super(decisionKey, variables); } public ExecuteDecisionWithAuditTrailCmd(String decisionKey, String parentDeploymentId, Map<String, Object> variables) { this(decisionKey, variables); executeDecisionContext.setParentDeploymentId(parentDeploymentId); } public ExecuteDecisionWithAuditTrailCmd(String decisionKey, String parentDeploymentId, Map<String, Object> variables, String tenantId) { this(decisionKey, parentDeploymentId, variables); executeDecisionContext.setTenantId(tenantId); } @Override public Void execute(CommandContext commandContext) {
if (executeDecisionContext.getDecisionKey() == null) { throw new FlowableIllegalArgumentException("decisionKey is null"); } DmnDefinition definition; try { definition = resolveDefinition(); } catch (FlowableException e) { DecisionExecutionAuditContainer container = new DecisionExecutionAuditContainer(); container.setFailed(); container.setExceptionMessage(e.getMessage()); executeDecisionContext.setDecisionExecution(container); return null; } execute(commandContext, definition); return null; } }
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\cmd\ExecuteDecisionWithAuditTrailCmd.java
1
请完成以下Java代码
private void expandNode(Node node) { List<State> possibleStates = node.getState().getAllPossibleStates(); possibleStates.forEach(state -> { Node newNode = new Node(state); newNode.setParent(node); newNode.getState().setPlayerNo(node.getState().getOpponent()); node.getChildArray().add(newNode); }); } private void backPropogation(Node nodeToExplore, int playerNo) { Node tempNode = nodeToExplore; while (tempNode != null) { tempNode.getState().incrementVisit(); if (tempNode.getState().getPlayerNo() == playerNo) tempNode.getState().addScore(WIN_SCORE); tempNode = tempNode.getParent(); } }
private int simulateRandomPlayout(Node node) { Node tempNode = new Node(node); State tempState = tempNode.getState(); int boardStatus = tempState.getBoard().checkStatus(); if (boardStatus == opponent) { tempNode.getParent().getState().setWinScore(Integer.MIN_VALUE); return boardStatus; } while (boardStatus == Board.IN_PROGRESS) { tempState.togglePlayer(); tempState.randomPlay(); boardStatus = tempState.getBoard().checkStatus(); } return boardStatus; } }
repos\tutorials-master\algorithms-modules\algorithms-searching\src\main\java\com\baeldung\algorithms\mcts\montecarlo\MonteCarloTreeSearch.java
1
请完成以下Java代码
public class LoopsInJava { private static final Logger LOGGER = LoggerFactory.getLogger(LoopsInJava.class); public int[] simple_for_loop() { int[] arr = new int[5]; for (int i = 0; i < 5; i++) { arr[i] = i; LOGGER.debug("Simple for loop: i - " + i); } return arr; } public int[] enhanced_for_each_loop() { int[] intArr = { 0, 1, 2, 3, 4 }; int[] arr = new int[5]; for (int num : intArr) { arr[num] = num; LOGGER.debug("Enhanced for-each loop: i - " + num); } return arr; } public int[] while_loop() { int i = 0;
int[] arr = new int[5]; while (i < 5) { arr[i] = i; LOGGER.debug("While loop: i - " + i++); } return arr; } public int[] do_while_loop() { int i = 0; int[] arr = new int[5]; do { arr[i] = i; LOGGER.debug("Do-While loop: i - " + i++); } while (i < 5); return arr; } }
repos\tutorials-master\core-java-modules\core-java-lang-syntax-3\src\main\java\com\baeldung\loops\LoopsInJava.java
1
请完成以下Java代码
public void convertAndPublish(final List<JSONDocument> jsonDocumentEvents) { if (jsonDocumentEvents == null || jsonDocumentEvents.isEmpty()) { return; } final JSONDocumentChangedWebSocketEventCollector collectorToMerge = JSONDocumentChangedWebSocketEventCollector.newInstance(); for (final JSONDocument jsonDocumentEvent : jsonDocumentEvents) { collectFrom(collectorToMerge, jsonDocumentEvent); } if (collectorToMerge.isEmpty()) { return; } forCollector(collector -> collector.mergeFrom(collectorToMerge)); } private static void collectFrom(final JSONDocumentChangedWebSocketEventCollector collector, final JSONDocument event) { final WindowId windowId = event.getWindowId(); if (windowId == null) { return; } // Included document => nothing to publish about it if (event.getTabId() != null) { return; } final DocumentId documentId = event.getId(); collector.staleRootDocument(windowId, documentId); event.getIncludedTabsInfos().forEach(tabInfo -> collector.mergeFrom(windowId, documentId, tabInfo)); } public CloseableCollector temporaryCollectOnThisThread() { final CloseableCollector closeableCollector = new CloseableCollector(); closeableCollector.open(); return closeableCollector; } public class CloseableCollector implements IAutoCloseable {
@NonNull private final JSONDocumentChangedWebSocketEventCollector collector = JSONDocumentChangedWebSocketEventCollector.newInstance(); @NonNull private final AtomicBoolean closed = new AtomicBoolean(false); @Override public String toString() { return "CloseableCollector[" + collector + "]"; } private void open() { if (THREAD_LOCAL_COLLECTOR.get() != null) { throw new AdempiereException("A thread level collector was already set"); } THREAD_LOCAL_COLLECTOR.set(collector); } @Override public void close() { if (closed.getAndSet(true)) { return; // already closed } THREAD_LOCAL_COLLECTOR.set(null); sendAllAndClose(collector, websocketSender); } @VisibleForTesting ImmutableList<JSONDocumentChangedWebSocketEvent> getEvents() {return collector.getEvents();} } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\events\DocumentWebsocketPublisher.java
1
请完成以下Java代码
public void setTotal_Size (int Total_Size) { set_ValueNoCheck (COLUMNNAME_Total_Size, Integer.valueOf(Total_Size)); } /** Get Total_Size. @return Total_Size */ @Override public int getTotal_Size () { Integer ii = (Integer)get_Value(COLUMNNAME_Total_Size); if (ii == null) return 0; return ii.intValue(); } /** Set UUID.
@param UUID UUID */ @Override public void setUUID (java.lang.String UUID) { set_ValueNoCheck (COLUMNNAME_UUID, UUID); } /** Get UUID. @return UUID */ @Override public java.lang.String getUUID () { return (java.lang.String)get_Value(COLUMNNAME_UUID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\dao\selection\model\X_T_Query_Selection_Pagination.java
1
请完成以下Java代码
public class SimpleKotlinProjectSettings implements KotlinProjectSettings { private static final Version KOTLIN_2_2_OR_LATER = Version.parse("2.2.0"); private final String version; private final String jvmTarget; /** * Create an instance with the kotlin version to use. * @param version the kotlin version to use */ public SimpleKotlinProjectSettings(String version) { this(version, Language.DEFAULT_JVM_VERSION); } /** * Create an instance with the kotlin version and the target version of the generated * JVM bytecode. * @param version the kotlin version to use * @param jvmTarget the target version of the generated JVM bytecode */ public SimpleKotlinProjectSettings(String version, String jvmTarget) { this.version = version; this.jvmTarget = jvmTarget; } @Override public String getVersion() {
return this.version; } @Override public String getJvmTarget() { return this.jvmTarget; } @Override public List<String> getCompilerArgs() { List<String> result = new ArrayList<>(KotlinProjectSettings.super.getCompilerArgs()); Version kotlinVersion = Version.parse(this.version); if (kotlinVersion.compareTo(KOTLIN_2_2_OR_LATER) >= 0) { result.add("-Xannotation-default-target=param-property"); } return result; } }
repos\initializr-main\initializr-generator-spring\src\main\java\io\spring\initializr\generator\spring\code\kotlin\SimpleKotlinProjectSettings.java
1
请在Spring Boot框架中完成以下Java代码
public static double max(double x, double y) { return x>y?x:y; } public static double min(double x, double y) { return x>y?y:x; } public static double editDistanceAll(String s1, String s2) { return Math.round(editDistance(s1, s2) / max(s1.length(), s2.length()) * 100); } public static String clean(String s) { String ss; ss = s.replace(".", " ").replace(",", " ").replace(";", " ").replace("*", " ").replace("#", " ").replace("-", " "); return ss; } public static double editDistanceWord(String s1, String s2) { String[] w1 = clean(s1).split("\\s+"); String[] w2 = clean(s2).split("\\s+"); for (int i = 0; i < w1.length; i++) { for (int j = 0; j < w2.length; j++) if (w1[i].toLowerCase().equals(w2[j].toLowerCase())) { w1[i] = ""; w2[j] = ""; break; } } double d = 0.0; int count = 0; int w1l = w1.length>0?w1.length:1; int w2l = w2.length>0?w2.length:1; for (int i = 0; i < w1.length; i++) for (int j = 0; j < w2.length; j++) { if (!w1[i].isEmpty() && !w2[j].isEmpty()) d = d + editDistance(w1[i].toLowerCase(), w2[j].toLowerCase()) / max(w1[i].length(), w2[j].length()); else if (w1[i].isEmpty() && w2[j].isEmpty()); else if (w1[i].isEmpty()) d = d + 1.0 / w1l; else if (w2[j].isEmpty()) d = d + 1.0 / w2l; count++; }
if (count == 0) count = 1; return Math.round(d / count * 100); } public static double similarity2(String s1, String s2) { return editDistanceWord(s1, s2); } @Override public int compare(Address o1, Address o2) { double f1 = similarity2(o1.getAddr(), baseToCompare); double f2 = similarity2(o2.getAddr(), baseToCompare); if (f1 > f2) return 1; else if (Math.abs(f1 - f2) < 0.000001) return 0; else return -1; } }
repos\SpringBoot-Projects-FullStack-master\Part-9.SpringBoot-React-Projects\Project-2.SpringBoot-React-ShoppingMall\fullstack\backend\src\main\java\com\urunov\service\taxiMaster\StringSimilarity.java
2
请完成以下Java代码
public String getDeregisterActivitySubtitle() { return deregisterActivitySubtitle.getExpressionString(); } public void setDeregisterActivitySubtitle(String deregisterActivitySubtitle) { this.deregisterActivitySubtitle = parser.parseExpression(deregisterActivitySubtitle, ParserContext.TEMPLATE_EXPRESSION); } public String getRegisterActivitySubtitle() { return registerActivitySubtitle.getExpressionString(); } public void setRegisterActivitySubtitle(String registerActivitySubtitle) { this.registerActivitySubtitle = parser.parseExpression(registerActivitySubtitle, ParserContext.TEMPLATE_EXPRESSION); } public String getStatusActivitySubtitle() { return statusActivitySubtitle.getExpressionString(); } public void setStatusActivitySubtitle(String statusActivitySubtitle) { this.statusActivitySubtitle = parser.parseExpression(statusActivitySubtitle, ParserContext.TEMPLATE_EXPRESSION); } @Data @Builder public static class Message { private final String summary; private final String themeColor; private final String title; @Builder.Default private final List<Section> sections = new ArrayList<>(); }
@Data @Builder public static class Section { private final String activityTitle; private final String activitySubtitle; @Builder.Default private final List<Fact> facts = new ArrayList<>(); } public record Fact(String name, @Nullable String value) { } }
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\notify\MicrosoftTeamsNotifier.java
1
请完成以下Java代码
public void deleteComments() { ensureHistoryEnabled(Status.FORBIDDEN); ensureTaskExists(Status.NOT_FOUND); TaskService taskService = engine.getTaskService(); try { taskService.deleteTaskComments(taskId); } catch (AuthorizationException e) { throw e; } catch (NullValueException e) { throw new InvalidRequestException(Status.BAD_REQUEST, e.getMessage()); } } public CommentDto createComment(UriInfo uriInfo, CommentDto commentDto) { ensureHistoryEnabled(Status.FORBIDDEN); ensureTaskExists(Status.BAD_REQUEST); Comment comment; String processInstanceId = commentDto.getProcessInstanceId(); try { comment = engine.getTaskService().createComment(taskId, processInstanceId, commentDto.getMessage()); } catch (ProcessEngineException e) { throw new InvalidRequestException(Status.BAD_REQUEST, e, "Not enough parameters submitted"); } URI uri = uriInfo.getBaseUriBuilder() .path(rootResourcePath) .path(TaskRestService.PATH) .path(taskId + "/comment/" + comment.getId()) .build(); CommentDto resultDto = CommentDto.fromComment(comment); // GET / resultDto.addReflexiveLink(uri, HttpMethod.GET, "self"); return resultDto;
} private boolean isHistoryEnabled() { IdentityService identityService = engine.getIdentityService(); Authentication currentAuthentication = identityService.getCurrentAuthentication(); try { identityService.clearAuthentication(); int historyLevel = engine.getManagementService().getHistoryLevel(); return historyLevel > ProcessEngineConfigurationImpl.HISTORYLEVEL_NONE; } finally { identityService.setAuthentication(currentAuthentication); } } private void ensureHistoryEnabled(Status status) { if (!isHistoryEnabled()) { throw new InvalidRequestException(status, "History is not enabled"); } } private void ensureTaskExists(Status status) { HistoricTaskInstance historicTaskInstance = engine.getHistoryService().createHistoricTaskInstanceQuery().taskId(taskId).singleResult(); if (historicTaskInstance == null) { throw new InvalidRequestException(status, "No task found for task id " + taskId); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\sub\task\impl\TaskCommentResourceImpl.java
1
请完成以下Java代码
protected VariableStore<CoreVariableInstance> getVariableStore() { return (VariableStore) variableStore; } @Override protected VariableInstanceFactory<CoreVariableInstance> getVariableInstanceFactory() { return (VariableInstanceFactory) SimpleVariableInstanceFactory.INSTANCE; } @Override protected List<VariableInstanceLifecycleListener<CoreVariableInstance>> getVariableInstanceLifecycleListeners() { return Collections.emptyList(); } // toString ///////////////////////////////////////////////////////////////// public String toString() { if (isCaseInstanceExecution()) { return "CaseInstance[" + getToStringIdentity() + "]"; } else { return "CmmnExecution["+getToStringIdentity() + "]"; } } protected String getToStringIdentity() { return Integer.toString(System.identityHashCode(this)); } public String getId() { return String.valueOf(System.identityHashCode(this)); }
public ProcessEngineServices getProcessEngineServices() { throw LOG.unsupportedTransientOperationException(ProcessEngineServicesAware.class.getName()); } public ProcessEngine getProcessEngine() { throw LOG.unsupportedTransientOperationException(ProcessEngineServicesAware.class.getName()); } public CmmnElement getCmmnModelElementInstance() { throw LOG.unsupportedTransientOperationException(CmmnModelExecutionContext.class.getName()); } public CmmnModelInstance getCmmnModelInstance() { throw LOG.unsupportedTransientOperationException(CmmnModelExecutionContext.class.getName()); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\execution\CaseExecutionImpl.java
1
请完成以下Java代码
public int getM_Warehouse_ID() { return get_ValueAsInt(COLUMNNAME_M_Warehouse_ID); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } /** * POSPaymentProcessor AD_Reference_ID=541896 * Reference name: POSPaymentProcessor */ public static final int POSPAYMENTPROCESSOR_AD_Reference_ID=541896; /** SumUp = sumup */ public static final String POSPAYMENTPROCESSOR_SumUp = "sumup"; @Override public void setPOSPaymentProcessor (final @Nullable java.lang.String POSPaymentProcessor) { set_Value (COLUMNNAME_POSPaymentProcessor, POSPaymentProcessor); } @Override public java.lang.String getPOSPaymentProcessor() { return get_ValueAsString(COLUMNNAME_POSPaymentProcessor); } @Override public void setPrinterName (final @Nullable java.lang.String PrinterName) { set_Value (COLUMNNAME_PrinterName, PrinterName); }
@Override public java.lang.String getPrinterName() { return get_ValueAsString(COLUMNNAME_PrinterName); } @Override public void setSUMUP_Config_ID (final int SUMUP_Config_ID) { if (SUMUP_Config_ID < 1) set_Value (COLUMNNAME_SUMUP_Config_ID, null); else set_Value (COLUMNNAME_SUMUP_Config_ID, SUMUP_Config_ID); } @Override public int getSUMUP_Config_ID() { return get_ValueAsInt(COLUMNNAME_SUMUP_Config_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_POS.java
1