instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public void writeEndTag(HtmlWriteContext context) {
if(!isSelfClosing) {
writeLeadingWhitespace(context);
writeEndTagElement(context);
writeEndLine(context);
}
}
protected void writeEndTagElement(HtmlWriteContext context) {
StringWriter writer = context.getWriter();
writer.write("</");
writer.write(tagName);
writer.write(">");
}
protected void writeTextContent(HtmlWriteContext context) {
StringWriter writer = context.getWriter();
writer.write(" "); // add additional whitespace
writer.write(textContent);
}
protected void writeStartTagOpen(HtmlWriteContext context) {
StringWriter writer = context.getWriter();
writer.write("<");
writer.write(tagName);
}
protected void writeAttributes(HtmlWriteContext context) {
StringWriter writer = context.getWriter();
for (Entry<String, String> attribute : attributes.entrySet()) {
writer.write(" ");
writer.write(attribute.getKey());
if(attribute.getValue() != null) {
writer.write("=\"");
String attributeValue = escapeQuotes(attribute.getValue());
writer.write(attributeValue);
writer.write("\"");
}
}
}
protected String escapeQuotes(String attributeValue){
String escapedHtmlQuote = """;
String escapedJavaQuote = "\"";
return attributeValue.replaceAll(escapedJavaQuote, escapedHtmlQuote);
}
protected void writeEndLine(HtmlWriteContext context) {
StringWriter writer = context.getWriter();
writer.write("\n");
}
protected void writeStartTagClose(HtmlWriteContext context) {
StringWriter writer = context.getWriter();
if(isSelfClosing) {
writer.write(" /");
} | writer.write(">");
}
protected void writeLeadingWhitespace(HtmlWriteContext context) {
int stackSize = context.getElementStackSize();
StringWriter writer = context.getWriter();
for (int i = 0; i < stackSize; i++) {
writer.write(" ");
}
}
// builder /////////////////////////////////////
public HtmlElementWriter attribute(String name, String value) {
attributes.put(name, value);
return this;
}
public HtmlElementWriter textContent(String text) {
if(isSelfClosing) {
throw new IllegalStateException("Self-closing element cannot have text content.");
}
this.textContent = text;
return this;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\form\engine\HtmlElementWriter.java | 1 |
请完成以下Java代码 | public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getCustomerEmail() {
return customerEmail;
}
public void setCustomerEmail(String customerEmail) {
this.customerEmail = customerEmail;
}
public LocalDate getOrderDate() {
return orderDate;
}
public void setOrderDate(LocalDate orderDate) {
this.orderDate = orderDate;
}
public String getProductName() {
return productName; | }
public void setProductName(String productName) {
this.productName = productName;
}
public Double getProductPrice() {
return productPrice;
}
public void setProductPrice(Double productPrice) {
this.productPrice = productPrice;
}
} | repos\tutorials-master\persistence-modules\spring-data-jpa-repo-3\src\main\java\com\baeldung\spring\data\jpa\joinquery\DTO\ResultDTO_wo_Ids.java | 1 |
请完成以下Java代码 | protected String getDefinitionKey(CmmnActivityExecution execution) {
CmmnExecution caseExecution = (CmmnExecution) execution;
return getCallableElement().getDefinitionKey(caseExecution);
}
protected Integer getVersion(CmmnActivityExecution execution) {
CmmnExecution caseExecution = (CmmnExecution) execution;
return getCallableElement().getVersion(caseExecution);
}
protected String getDeploymentId(CmmnActivityExecution execution) {
return getCallableElement().getDeploymentId();
}
protected CallableElementBinding getBinding() {
return getCallableElement().getBinding();
}
protected boolean isLatestBinding() { | return getCallableElement().isLatestBinding();
}
protected boolean isDeploymentBinding() {
return getCallableElement().isDeploymentBinding();
}
protected boolean isVersionBinding() {
return getCallableElement().isVersionBinding();
}
protected boolean isVersionTagBinding() {
return getCallableElement().isVersionTagBinding();
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\behavior\CallingTaskActivityBehavior.java | 1 |
请完成以下Java代码 | public class Student {
private static final String NAME_REGEX = "^[a-zA-Z .'-]+$";
@Id
private String id;
@Field
@NotNull
@Size(min = 1, max = 20)
@Pattern(regexp = NAME_REGEX)
private String firstName;
@Field
@NotNull
@Size(min = 1, max = 20)
@Pattern(regexp = NAME_REGEX)
private String lastName;
@Field
@Past
private DateTime dateOfBirth;
@Field
@NotNull
private DateTime created;
@Field
private DateTime updated;
@Version
private long version;
public Student() {
}
public Student(String id, String firstName, String lastName, DateTime dateOfBirth) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.dateOfBirth = dateOfBirth;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public DateTime getDateOfBirth() {
return dateOfBirth;
} | public void setDateOfBirth(DateTime dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public DateTime getCreated() {
return created;
}
public void setCreated(DateTime created) {
this.created = created;
}
public DateTime getUpdated() {
return updated;
}
public void setUpdated(DateTime updated) {
this.updated = updated;
}
@Override
public int hashCode() {
int hash = 1;
if (id != null) {
hash = hash * 31 + id.hashCode();
}
if (firstName != null) {
hash = hash * 31 + firstName.hashCode();
}
if (lastName != null) {
hash = hash * 31 + lastName.hashCode();
}
if (dateOfBirth != null) {
hash = hash * 31 + dateOfBirth.hashCode();
}
return hash;
}
@Override
public boolean equals(Object obj) {
if ((obj == null) || (obj.getClass() != this.getClass()))
return false;
if (obj == this)
return true;
Student other = (Student) obj;
return this.hashCode() == other.hashCode();
}
} | repos\tutorials-master\persistence-modules\spring-data-couchbase-2\src\main\java\com\baeldung\spring\data\couchbase\model\Student.java | 1 |
请完成以下Java代码 | public void setIsReceipt (boolean IsReceipt)
{
set_Value (COLUMNNAME_IsReceipt, Boolean.valueOf(IsReceipt));
}
/** Get Zahlungseingang.
@return Dies ist eine Verkaufs-Transaktion (Zahlungseingang)
*/
@Override
public boolean isReceipt ()
{
Object oo = get_Value(COLUMNNAME_IsReceipt);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Zahlungsbetrag.
@param PayAmt
Gezahlter Betrag
*/
@Override
public void setPayAmt (BigDecimal PayAmt)
{
set_Value (COLUMNNAME_PayAmt, PayAmt);
}
/** Get Zahlungsbetrag.
@return Gezahlter Betrag
*/
@Override
public BigDecimal getPayAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PayAmt);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Verarbeitet.
@param Processed
Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Verarbeitet.
@return Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed); | if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Process Now.
@param Processing Process Now */
@Override
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
@Override
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;
}
/** Set Transaction Code.
@param TransactionCode
The transaction code represents the search definition
*/
@Override
public void setTransactionCode (java.lang.String TransactionCode)
{
set_Value (COLUMNNAME_TransactionCode, TransactionCode);
}
/** Get Transaction Code.
@return The transaction code represents the search definition
*/
@Override
public java.lang.String getTransactionCode ()
{
return (java.lang.String)get_Value(COLUMNNAME_TransactionCode);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-gen\de\metas\banking\model\X_I_Datev_Payment.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public int nextContraintCounter() {
return ++constraintCounter;
}
public String getNextConstraintStringValue(CassandraToSqlColumn column) {
int counter = this.nextContraintCounter();
String newValue = this.originalValue + counter;
int overflow = newValue.length() - column.getSize();
if (overflow > 0) {
newValue = this.originalValue.substring(0, this.originalValue.length()-overflow) + counter;
}
return newValue;
}
public String getNextConstraintEmailValue(CassandraToSqlColumn column) {
int counter = this.nextContraintCounter();
String[] emailValues = this.originalValue.split("@");
String newValue = emailValues[0] + "+" + counter + "@" + emailValues[1]; | int overflow = newValue.length() - column.getSize();
if (overflow > 0) {
newValue = emailValues[0].substring(0, emailValues[0].length()-overflow) + "+" + counter + "@" + emailValues[1];
}
return newValue;
}
public String getLogValue() {
if (this.value != null && this.value.length() > 255) {
return this.value.substring(0, 255) + "...[truncated " + (this.value.length() - 255) + " symbols]";
}
return this.value;
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\install\migrate\CassandraToSqlColumnData.java | 2 |
请完成以下Java代码 | public static WorkflowLauncherId ofString(@NonNull final String stringRepresentation)
{
MobileApplicationId applicationId = null;
final ImmutableList.Builder<String> parts = ImmutableList.builder();
for (final String part : SPLITTER.split(stringRepresentation))
{
if (applicationId == null)
{
applicationId = MobileApplicationId.ofString(part);
}
else
{
parts.add(part);
}
}
if (applicationId == null)
{
throw new AdempiereException("Invalid string: " + stringRepresentation);
}
final WorkflowLauncherId result = new WorkflowLauncherId(applicationId, parts.build());
result._stringRepresentation = stringRepresentation;
return result;
}
@Getter
private final MobileApplicationId applicationId;
private final ImmutableList<String> parts;
private String _stringRepresentation;
private WorkflowLauncherId(
@NonNull final MobileApplicationId applicationId,
@NonNull final ImmutableList<String> parts) | {
this.applicationId = applicationId;
this.parts = parts;
}
@Override
@Deprecated
public String toString()
{
return getAsString();
}
@JsonValue
public String getAsString()
{
String stringRepresentation = _stringRepresentation;
if (stringRepresentation == null)
{
_stringRepresentation = stringRepresentation = JOINER
.join(Iterables.concat(
ImmutableList.of(applicationId.getAsString()),
parts));
}
return stringRepresentation;
}
public String getPartAsString(final int index)
{
return parts.get(index);
}
public Integer getPartAsInt(final int index)
{
return NumberUtils.asIntegerOrNull(getPartAsString(index));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.workflow.rest-api\src\main\java\de\metas\workflow\rest_api\model\WorkflowLauncherId.java | 1 |
请完成以下Java代码 | protected void updateZoomRotate() {
final Cursor oldCursor = getCursor();
try {
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
decoder.setPageParameters(zoomFactors[scaleStep],
currentPage,
rotation);
decoder.invalidate();
decoder.repaint();
zoomInAction.setEnabled(scaleStep < zoomFactors.length - 1);
zoomOutAction.setEnabled(scaleStep > 0);
} finally {
setCursor(oldCursor);
}
}
public void setScale(final int percent) {
int step;
for (step = 0; step < zoomFactors.length - 1; step++) {
if (zoomFactors[step] * 100 >= percent) {
break;
}
}
setScaleStep(step);
}
public boolean loadPDF(final byte[] data)
{
return loadPDF(new ByteArrayInputStream(data));
}
public boolean loadPDF(final InputStream is)
{
if (tmpFile != null) {
tmpFile.delete();
}
try {
tmpFile = File.createTempFile("adempiere", ".pdf"); | tmpFile.deleteOnExit();
} catch (IOException e) {
e.printStackTrace();
return false;
}
try {
final OutputStream os = new FileOutputStream(tmpFile);
try {
final byte[] buffer = new byte[32768];
for (int read; (read = is.read(buffer)) != -1; ) {
os.write(buffer, 0, read);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return loadPDF(tmpFile.getAbsolutePath());
}
@Override
protected void finalize() throws Throwable {
if (tmpFile != null) {
tmpFile.delete();
}
decoder.closePdfFile();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\pdf\viewer\PDFViewerBean.java | 1 |
请完成以下Java代码 | public final class CacheControlHeadersWriter implements HeaderWriter {
private static final String EXPIRES = "Expires";
private static final String PRAGMA = "Pragma";
private static final String CACHE_CONTROL = "Cache-Control";
private final HeaderWriter delegate;
/**
* Creates a new instance
*/
public CacheControlHeadersWriter() {
this.delegate = new StaticHeadersWriter(createHeaders());
}
@Override
public void writeHeaders(HttpServletRequest request, HttpServletResponse response) {
if (hasHeader(response, CACHE_CONTROL) || hasHeader(response, EXPIRES) || hasHeader(response, PRAGMA)
|| response.getStatus() == HttpStatus.NOT_MODIFIED.value()) {
return; | }
this.delegate.writeHeaders(request, response);
}
private boolean hasHeader(HttpServletResponse response, String headerName) {
return response.getHeader(headerName) != null;
}
private static List<Header> createHeaders() {
List<Header> headers = new ArrayList<>(3);
headers.add(new Header(CACHE_CONTROL, "no-cache, no-store, max-age=0, must-revalidate"));
headers.add(new Header(PRAGMA, "no-cache"));
headers.add(new Header(EXPIRES, "0"));
return headers;
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\header\writers\CacheControlHeadersWriter.java | 1 |
请完成以下Java代码 | public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
// Grab credentials and map them to login viewmodel
LoginViewModel credentials = null;
try {
credentials = new ObjectMapper().readValue(request.getInputStream(), LoginViewModel.class);
} catch (IOException e){
e.printStackTrace();
}
// Create login token
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
credentials.getUsername(),
credentials.getPassword(),
new ArrayList<>());
// Authenciate user
Authentication auth = authenticationManager.authenticate(authenticationToken);
return auth; | }
@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
//Grab principal
UserPrincipal principal = (UserPrincipal) authResult.getPrincipal();
// Create JWT Token
String token = JWT.create()
.withSubject(principal.getUsername())
.withExpiresAt(new Date(System.currentTimeMillis() + JwtProperties.EXPIRATION_TIME))
.sign(HMAC512(JwtProperties.SECRET.getBytes()));
// add token in response
response.addHeader(JwtProperties.HEADER_STRING, JwtProperties.TOKEN_PREFIX + token);
}
} | repos\SpringBoot-Projects-FullStack-master\Part-6 Spring Boot Security\11.SpringSecurityJwt\src\main\java\spring\security\security\JwtAuthenticationFilter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public ReturnT<String> remove(HttpServletRequest request, int id) {
// avoid opt login seft
XxlJobUser loginUser = (XxlJobUser) request.getAttribute(LoginService.LOGIN_IDENTITY_KEY);
if (loginUser.getId() == id) {
return new ReturnT<String>(ReturnT.FAIL.getCode(), I18nUtil.getString("user_update_loginuser_limit"));
}
xxlJobUserDao.delete(id);
return ReturnT.SUCCESS;
}
@RequestMapping("/updatePwd")
@ResponseBody
public ReturnT<String> updatePwd(HttpServletRequest request, String password){
// valid password
if (password==null || password.trim().length()==0){
return new ReturnT<String>(ReturnT.FAIL.getCode(), "密码不可为空");
} | password = password.trim();
if (!(password.length()>=4 && password.length()<=20)) {
return new ReturnT<String>(ReturnT.FAIL_CODE, I18nUtil.getString("system_lengh_limit")+"[4-20]" );
}
// md5 password
String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
// update pwd
XxlJobUser loginUser = (XxlJobUser) request.getAttribute(LoginService.LOGIN_IDENTITY_KEY);
// do write
XxlJobUser existUser = xxlJobUserDao.loadByUserName(loginUser.getUsername());
existUser.setPassword(md5Password);
xxlJobUserDao.update(existUser);
return ReturnT.SUCCESS;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\controller\UserController.java | 2 |
请完成以下Java代码 | public class Item {
private int itemId;
private String itemDesc;
private double itemPrice;
public int getItemId() {
return itemId;
}
public void setItemId(int itemId) {
this.itemId = itemId;
}
public String getItemDesc() { | return itemDesc;
}
public void setItemDesc(String itemDesc) {
this.itemDesc = itemDesc;
}
public double getItemPrice() {
return itemPrice;
}
public void setItemPrice(double itemPrice) {
this.itemPrice = itemPrice;
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-caching\src\main\java\com\baeldung\multiplecachemanager\entity\Item.java | 1 |
请完成以下Java代码 | public ProcessPreconditionsResolution checkPreconditionsApplicable(final IProcessPreconditionsContext context)
{
if (!context.isSingleSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection();
}
// Receipt schedule shall not be already closed
final IReceiptScheduleBL receiptScheduleBL = Services.get(IReceiptScheduleBL.class);
final I_M_ReceiptSchedule receiptSchedule = context.getSelectedModel(I_M_ReceiptSchedule.class);
if(receiptScheduleBL.isClosed(receiptSchedule))
{
return ProcessPreconditionsResolution.rejectWithInternalReason("already closed");
}
// Receipt schedule shall not be about packing materials
if (receiptSchedule.isPackagingMaterial())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("not applying for packing materials");
}
if(receiptSchedule.getQtyMoved().signum()<=0)
{
return ProcessPreconditionsResolution.rejectWithInternalReason("no receipts to be reversed");
} | return ProcessPreconditionsResolution.accept();
}
@Override
protected String doIt() throws Exception
{
final I_M_ReceiptSchedule receiptSchedule = getRecord(I_M_ReceiptSchedule.class);
final List<I_M_HU> hus = ReceiptCorrectHUsProcessor.builder()
.setM_ReceiptSchedule(receiptSchedule)
.build()
.getAvailableHUsToReverse();
if (hus.isEmpty())
{
throw new AdempiereException("@NotFound@ @M_HU_ID@");
}
getResult().setRecordsToOpen(TableRecordReference.ofCollection(hus));
return MSG_OK;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_M_ReceiptSchedule_SelectHUsToReverse.java | 1 |
请完成以下Java代码 | public static IntegerLookupValue of(final StringLookupValue stringLookupValue)
{
if (stringLookupValue == null)
{
return null;
}
return new IntegerLookupValue(
stringLookupValue.getIdAsInt(),
stringLookupValue.displayName,
stringLookupValue.description,
null /* attributes */,
stringLookupValue.getActive());
}
public static IntegerLookupValue unknown(final int id)
{
return new IntegerLookupValue(
id,
unknownCaption(id),
null/* description */,
null/* attributes */,
false/* not active */);
}
@Builder
private IntegerLookupValue(
final int id,
@Nullable final ITranslatableString displayName, | @Nullable final ITranslatableString description,
@Nullable @Singular final Map<String, Object> attributes,
@Nullable final Boolean active)
{
super(id,
displayName,
description,
attributes,
active);
}
@Override
public int getIdAsInt()
{
return (Integer)id;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\LookupValue.java | 1 |
请完成以下Java代码 | public String getElementName() {
return ELEMENT_CUSTOM_RESOURCE;
}
@Override
public void parseChildElement(XMLStreamReader xtr, BaseElement parentElement, BpmnModel model)
throws Exception {
String identityLinkType = xtr.getAttributeValue(ACTIVITI_EXTENSIONS_NAMESPACE, ATTRIBUTE_NAME);
// the attribute value may be unqualified
if (identityLinkType == null) {
identityLinkType = xtr.getAttributeValue(null, ATTRIBUTE_NAME);
}
if (identityLinkType == null) return;
String resourceElement = XMLStreamReaderUtil.moveDown(xtr);
if (StringUtils.isNotEmpty(resourceElement) && ELEMENT_RESOURCE_ASSIGNMENT.equals(resourceElement)) {
String expression = XMLStreamReaderUtil.moveDown(xtr);
if (StringUtils.isNotEmpty(expression) && ELEMENT_FORMAL_EXPRESSION.equals(expression)) {
List<String> assignmentList = CommaSplitter.splitCommas(xtr.getElementText());
for (String assignmentValue : assignmentList) {
if (assignmentValue == null) {
continue;
} | assignmentValue = assignmentValue.trim();
if (assignmentValue.length() == 0) {
continue;
}
String userPrefix = "user(";
String groupPrefix = "group(";
if (assignmentValue.startsWith(userPrefix)) {
assignmentValue = assignmentValue
.substring(userPrefix.length(), assignmentValue.length() - 1)
.trim();
((UserTask) parentElement).addCustomUserIdentityLink(assignmentValue, identityLinkType);
} else if (assignmentValue.startsWith(groupPrefix)) {
assignmentValue = assignmentValue
.substring(groupPrefix.length(), assignmentValue.length() - 1)
.trim();
((UserTask) parentElement).addCustomGroupIdentityLink(assignmentValue, identityLinkType);
} else {
((UserTask) parentElement).addCustomGroupIdentityLink(assignmentValue, identityLinkType);
}
}
}
}
}
}
} | repos\Activiti-develop\activiti-core\activiti-bpmn-converter\src\main\java\org\activiti\bpmn\converter\UserTaskXMLConverter.java | 1 |
请完成以下Java代码 | public List<OrderAttachmentRow> buildRowsFor(@NonNull final AttachmentEntry attachmentEntry)
{
final TableRecordReference purchaseOrderRecordRef = TableRecordReference.of(I_C_Order.Table_Name, purchaseOrderId.getRepoId());
final Set<TableRecordReference> matchingRecordReferences = attachmentEntry.getLinkedRecords()
.stream()
.filter(tableRecordReference -> !tableRecordReference.equals(purchaseOrderRecordRef))
.filter(targetRecordReferences::contains)
.collect(ImmutableSet.toImmutableSet());
final Priority highestPriorityFound = matchingRecordReferences
.stream()
.map(TableRecordReference::getTableName)
.map(tableName2PriorityRowBuilder::get)
.filter(Objects::nonNull)
.map(PriorityRowBuilder::getPriority)
.max(Priority::compareTo)
.orElse(Priority.NO_PRIORITY);
final ImmutableList.Builder<OrderAttachmentRow> attachmentRows = ImmutableList.builder();
if (highestPriorityFound.equals(Priority.NO_PRIORITY))
{
return attachmentRows
.add(purchaseOrderRowBuilder.apply(attachmentEntry))
.build();
}
for (final TableRecordReference linkedRecord : matchingRecordReferences)
{
Optional.ofNullable(tableName2PriorityRowBuilder.get(linkedRecord.getTableName()))
.filter(priorityRowBuilder -> priorityRowBuilder.getPriority().equals(highestPriorityFound))
.map(PriorityRowBuilder::getBuildRowFunction)
.map(buildFunction -> buildFunction.apply(linkedRecord, attachmentEntry))
.ifPresent(attachmentRows::add);
}
return attachmentRows.build();
}
@Value
public static class Priority implements Comparable<Priority>
{ | public static final Priority NO_PRIORITY = Priority.of(-1);
public static Priority of(final int priority)
{
return new Priority(priority);
}
int priority;
@Override
public int compareTo(@NonNull final Priority o)
{
return Integer.compare(this.priority, o.priority);
}
}
@Value
@Getter
public static class PriorityRowBuilder
{
Priority priority;
BiFunction<TableRecordReference, AttachmentEntry, OrderAttachmentRow> buildRowFunction;
public static PriorityRowBuilder of(final Priority priority, @NonNull final BiFunction<TableRecordReference, AttachmentEntry, OrderAttachmentRow> buildRowFunction)
{
return new PriorityRowBuilder(priority, buildRowFunction);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\attachmenteditor\AttachmentRowBuilder.java | 1 |
请完成以下Java代码 | public Object getPersistentState() {
return new PersistentState(name, bytes);
}
// getters and setters ////////////////////////////////////////////////////////
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDeploymentId() {
return deploymentId;
}
public void setDeploymentId(String deploymentId) {
this.deploymentId = deploymentId;
}
public void setBytes(byte[] bytes) {
this.bytes = bytes;
}
@Override
public String toString() {
return "ByteArrayEntity[id=" + id + ", name=" + name + ", size=" + (bytes != null ? bytes.length : 0) + "]";
}
// Wrapper for a byte array, needed to do byte array comparisons
// See https://activiti.atlassian.net/browse/ACT-1524
private static class PersistentState {
private final String name;
private final byte[] bytes;
public PersistentState(String name, byte[] bytes) { | this.name = name;
this.bytes = bytes;
}
public boolean equals(Object obj) {
if (obj instanceof PersistentState) {
PersistentState other = (PersistentState) obj;
return StringUtils.equals(this.name, other.name) && Arrays.equals(this.bytes, other.bytes);
}
return false;
}
@Override
public int hashCode() {
throw new UnsupportedOperationException();
}
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\ByteArrayEntityImpl.java | 1 |
请完成以下Java代码 | public class OrderProductPK implements Serializable {
private static final long serialVersionUID = 476151177562655457L;
@ManyToOne(optional = false, fetch = FetchType.LAZY)
@JoinColumn(name = "order_id")
private Order order;
@ManyToOne(optional = false, fetch = FetchType.LAZY)
@JoinColumn(name = "product_id")
private Product product;
public Order getOrder() {
return order;
}
public void setOrder(Order order) {
this.order = order;
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((order.getId() == null)
? 0
: order
.getId()
.hashCode());
result = prime * result + ((product.getId() == null)
? 0
: product
.getId()
.hashCode());
return result;
} | @Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
OrderProductPK other = (OrderProductPK) obj;
if (order == null) {
if (other.order != null) {
return false;
}
} else if (!order.equals(other.order)) {
return false;
}
if (product == null) {
if (other.product != null) {
return false;
}
} else if (!product.equals(other.product)) {
return false;
}
return true;
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-angular\src\main\java\com\baeldung\ecommerce\model\OrderProductPK.java | 1 |
请完成以下Java代码 | public class DoubleRestVariableConverter implements RestVariableConverter {
@Override
public String getRestTypeName() {
return "double";
}
@Override
public Class<?> getVariableType() {
return Double.class;
}
@Override
public Object getVariableValue(EngineRestVariable result) {
if (result.getValue() != null) {
if (!(result.getValue() instanceof Number)) {
throw new FlowableIllegalArgumentException("Converter can only convert doubles");
}
return ((Number) result.getValue()).doubleValue(); | }
return null;
}
@Override
public void convertVariableValue(Object variableValue, EngineRestVariable result) {
if (variableValue != null) {
if (!(variableValue instanceof Double)) {
throw new FlowableIllegalArgumentException("Converter can only convert doubles");
}
result.setValue(variableValue);
} else {
result.setValue(null);
}
}
} | repos\flowable-engine-main\modules\flowable-common-rest\src\main\java\org\flowable\common\rest\variable\DoubleRestVariableConverter.java | 1 |
请完成以下Java代码 | void clear()
{
feature_.clear();
}
/**
* Apply IDF(inverse document frequency) weighting.
*
* @param df document frequencies
* @param ndocs the number of documents
*/
void idf(HashMap<Integer, Integer> df, int ndocs)
{
for (Map.Entry<Integer, Double> entry : feature_.entrySet())
{
Integer denom = df.get(entry.getKey());
if (denom == null) denom = 1;
entry.setValue((double) (entry.getValue() * Math.log(ndocs / denom)));
} | }
@Override
public boolean equals(Object o)
{
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Document<?> document = (Document<?>) o;
return id_ != null ? id_.equals(document.id_) : document.id_ == null;
}
@Override
public int hashCode()
{
return id_ != null ? id_.hashCode() : 0;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\cluster\Document.java | 1 |
请完成以下Java代码 | private static final class ManageAsyncBatchRequestHandlerAsEventListener implements IEventListener
{
private final EventLogUserService eventLogUserService;
private final AsyncBatchNotifyRequestHandler handler;
@lombok.Builder
private ManageAsyncBatchRequestHandlerAsEventListener(
@NonNull final AsyncBatchNotifyRequestHandler handler,
@NonNull final EventLogUserService eventLogUserService)
{
this.handler = handler;
this.eventLogUserService = eventLogUserService;
}
@Override
public void onEvent(@NonNull final IEventBus eventBus, @NonNull final Event event)
{
final AsyncBatchNotifyRequest request = extractAsyncBatchNotifyRequest(event);
try (final IAutoCloseable ignored = switchCtx(request);
final MDC.MDCCloseable ignored1 = MDC.putCloseable("eventHandler.className", handler.getClass().getName()))
{
eventLogUserService.invokeHandlerAndLog(EventLogUserService.InvokeHandlerAndLogRequest.builder()
.handlerClass(handler.getClass()) | .invokaction(() -> handleRequest(request))
.build());
}
}
private void handleRequest(@NonNull final AsyncBatchNotifyRequest request)
{
handler.handleRequest(request);
}
private IAutoCloseable switchCtx(@NonNull final AsyncBatchNotifyRequest request)
{
final Properties ctx = createCtx(request);
return Env.switchContext(ctx);
}
private Properties createCtx(@NonNull final AsyncBatchNotifyRequest request)
{
final Properties ctx = Env.newTemporaryCtx();
Env.setClientId(ctx, request.getClientId());
return ctx;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\eventbus\AsyncBatchEventBusService.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public PaymentCurrencyContext getPaymentCurrencyContext(@NonNull final I_C_BankStatementLine bankStatementLine)
{
final PaymentCurrencyContext.PaymentCurrencyContextBuilder result = PaymentCurrencyContext.builder()
.currencyConversionTypeId(null);
final BigDecimal fixedCurrencyRate = bankStatementLine.getCurrencyRate();
if (fixedCurrencyRate != null && fixedCurrencyRate.signum() != 0)
{
final CurrencyId paymentCurrencyId = CurrencyId.ofRepoId(bankStatementLine.getC_Currency_ID());
final ClientAndOrgId clientAndOrgId = ClientAndOrgId.ofClientAndOrg(bankStatementLine.getAD_Client_ID(), bankStatementLine.getAD_Org_ID());
final CurrencyId acctSchemaCurrencyId = moneyService.getBaseCurrencyId(clientAndOrgId);
result.paymentCurrencyId(paymentCurrencyId)
.sourceCurrencyId(acctSchemaCurrencyId)
.currencyRate(fixedCurrencyRate);
}
return result.build();
}
@Override
public void changeCurrencyRate(@NonNull final BankStatementLineId bankStatementLineId, @NonNull final BigDecimal currencyRate)
{
if (currencyRate.signum() == 0)
{
throw new AdempiereException("Invalid currency rate: " + currencyRate);
}
final I_C_BankStatementLine line = getLineById(bankStatementLineId);
final BankStatementId bankStatementId = BankStatementId.ofRepoId(line.getC_BankStatement_ID());
final I_C_BankStatement bankStatement = getById(bankStatementId);
assertBankStatementIsDraftOrInProcessOrCompleted(bankStatement);
final CurrencyId currencyId = CurrencyId.ofRepoId(line.getC_Currency_ID());
final CurrencyId baseCurrencyId = getBaseCurrencyId(line);
if (CurrencyId.equals(currencyId, baseCurrencyId))
{ | throw new AdempiereException("line is not in foreign currency");
}
line.setCurrencyRate(currencyRate);
InterfaceWrapperHelper.save(line);
unpost(bankStatement);
}
@Override
public CurrencyId getBaseCurrencyId(final I_C_BankStatementLine line)
{
final ClientAndOrgId clientAndOrgId = ClientAndOrgId.ofClientAndOrg(line.getAD_Client_ID(), line.getAD_Org_ID());
return moneyService.getBaseCurrencyId(clientAndOrgId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\service\impl\BankStatementBL.java | 2 |
请在Spring Boot框架中完成以下Java代码 | protected static class StringHttpMessageConverterConfiguration {
@Bean
@ConditionalOnMissingBean(StringHttpMessageConverter.class)
StringHttpMessageConvertersCustomizer stringHttpMessageConvertersCustomizer(
HttpMessageConvertersProperties properties) {
return new StringHttpMessageConvertersCustomizer(properties);
}
}
static class StringHttpMessageConvertersCustomizer
implements ClientHttpMessageConvertersCustomizer, ServerHttpMessageConvertersCustomizer {
StringHttpMessageConverter converter;
StringHttpMessageConvertersCustomizer(HttpMessageConvertersProperties properties) {
this.converter = new StringHttpMessageConverter(properties.getStringEncodingCharset());
this.converter.setWriteAcceptCharset(false);
}
@Override
public void customize(ClientBuilder builder) {
builder.withStringConverter(this.converter);
}
@Override
public void customize(ServerBuilder builder) {
builder.withStringConverter(this.converter);
}
} | static class NotReactiveWebApplicationCondition extends NoneNestedConditions {
NotReactiveWebApplicationCondition() {
super(ConfigurationPhase.PARSE_CONFIGURATION);
}
@ConditionalOnWebApplication(type = Type.REACTIVE)
private static final class ReactiveWebApplication {
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-http-converter\src\main\java\org\springframework\boot\http\converter\autoconfigure\HttpMessageConvertersAutoConfiguration.java | 2 |
请完成以下Java代码 | public java.lang.String getPhone ()
{
return (java.lang.String)get_Value(COLUMNNAME_Phone);
}
/** Set Anrufdatum.
@param PhonecallDate Anrufdatum */
@Override
public void setPhonecallDate (java.sql.Timestamp PhonecallDate)
{
set_Value (COLUMNNAME_PhonecallDate, PhonecallDate);
}
/** Get Anrufdatum.
@return Anrufdatum */
@Override
public java.sql.Timestamp getPhonecallDate ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_PhonecallDate);
}
/** Set Erreichbar bis.
@param PhonecallTimeMax Erreichbar bis */
@Override
public void setPhonecallTimeMax (java.sql.Timestamp PhonecallTimeMax)
{
set_Value (COLUMNNAME_PhonecallTimeMax, PhonecallTimeMax);
}
/** Get Erreichbar bis.
@return Erreichbar bis */
@Override
public java.sql.Timestamp getPhonecallTimeMax ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_PhonecallTimeMax);
}
/** Set Erreichbar von.
@param PhonecallTimeMin Erreichbar von */
@Override
public void setPhonecallTimeMin (java.sql.Timestamp PhonecallTimeMin)
{
set_Value (COLUMNNAME_PhonecallTimeMin, PhonecallTimeMin);
}
/** Get Erreichbar von.
@return Erreichbar von */
@Override
public java.sql.Timestamp getPhonecallTimeMin ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_PhonecallTimeMin); | }
/** Set Kundenbetreuer.
@param SalesRep_ID Kundenbetreuer */
@Override
public void setSalesRep_ID (int SalesRep_ID)
{
if (SalesRep_ID < 1)
set_Value (COLUMNNAME_SalesRep_ID, null);
else
set_Value (COLUMNNAME_SalesRep_ID, Integer.valueOf(SalesRep_ID));
}
/** Get Kundenbetreuer.
@return Kundenbetreuer */
@Override
public int getSalesRep_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SalesRep_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_C_Phonecall_Schedule.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DubboProviderAutoConfiguration extends DubboCommonAutoConfiguration {
@Autowired
private ApplicationContext applicationContext;
@Autowired
private DubboProperties properties;
@PostConstruct
public void init() throws Exception {
Map<String, Object> beanMap = this.applicationContext.getBeansWithAnnotation(Service.class);
if (beanMap != null && beanMap.size() > 0) {
this.initIdConfigMap(this.properties);
for (Map.Entry<String, Object> entry : beanMap.entrySet()) {
this.initProviderBean(entry.getKey(), entry.getValue());
}
}
}
private void initProviderBean(String beanName, Object bean) throws Exception {
Service service = this.applicationContext.findAnnotationOnBean(beanName, Service.class);
ServiceBean<Object> serviceConfig = new ServiceBean<Object>(service);
if ((service.interfaceClass() == null || service.interfaceClass() == void.class)
&& (service.interfaceName() == null || "".equals(service.interfaceName()))) {
Class<?>[] interfaces = bean.getClass().getInterfaces();
if (interfaces.length > 0) {
serviceConfig.setInterface(interfaces[0]);
}
}
Environment environment = this.applicationContext.getEnvironment();
String application = service.application();
serviceConfig.setApplication(this.parseApplication(application, this.properties, environment,
beanName, "application", application));
String module = service.module();
serviceConfig.setModule(
this.parseModule(module, this.properties, environment, beanName, "module", module));
String[] registries = service.registry();
serviceConfig.setRegistries(
this.parseRegistries(registries, this.properties, environment, beanName, "registry"));
String[] protocols = service.protocol();
serviceConfig.setProtocols(
this.parseProtocols(protocols, this.properties, environment, beanName, "registry"));
String monitor = service.monitor();
serviceConfig.setMonitor(
this.parseMonitor(monitor, this.properties, environment, beanName, "monitor", monitor)); | String provider = service.provider();
serviceConfig.setProvider(
this.parseProvider(provider, this.properties, environment, beanName, "provider", provider));
serviceConfig.setApplicationContext(this.applicationContext);
serviceConfig.afterPropertiesSet();
serviceConfig.setRef(bean);
serviceConfig.export();
}
@Override
protected String buildErrorMsg(String... errors) {
if (errors == null || errors.length != 3) {
return super.buildErrorMsg(errors);
}
return new StringBuilder().append("beanName=").append(errors[0]).append(", ").append(errors[1])
.append("=").append(errors[2]).append(" not found in multi configs").toString();
}
} | repos\dubbo-spring-boot-starter-master\src\main\java\com\alibaba\dubbo\spring\boot\DubboProviderAutoConfiguration.java | 2 |
请完成以下Java代码 | class ReverseList extends ArrayList<String> {
List<String> list = Arrays.asList("A", "B", "C", "D");
Consumer<String> removeElement = s -> {
System.out.println(s + " " + list.size());
if (s != null && s.equals("A")) {
list.remove("D");
}
};
@Override
public Iterator<String> iterator() {
final int startIndex = this.size() - 1;
final List<String> list = this;
return new Iterator<String>() {
int currentIndex = startIndex;
@Override
public boolean hasNext() {
return currentIndex >= 0;
}
@Override
public String next() {
String next = list.get(currentIndex);
currentIndex--;
return next;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
} | public void forEach(Consumer<? super String> action) {
for (String s : this) {
action.accept(s);
}
}
public void iterateParallel() {
list.forEach(System.out::print);
System.out.print(" ");
list.parallelStream().forEach(System.out::print);
}
public void iterateReverse() {
List<String> myList = new ReverseList();
myList.addAll(list);
myList.forEach(System.out::print);
System.out.print(" ");
myList.stream().forEach(System.out::print);
}
public void removeInCollectionForEach() {
list.forEach(removeElement);
}
public void removeInStreamForEach() {
list.stream().forEach(removeElement);
}
public static void main(String[] argv) {
ReverseList collectionForEach = new ReverseList();
collectionForEach.iterateParallel();
collectionForEach.iterateReverse();
collectionForEach.removeInCollectionForEach();
collectionForEach.removeInStreamForEach();
}
} | repos\tutorials-master\core-java-modules\core-java-streams\src\main\java\com\baeldung\stream\forEach\ReverseList.java | 1 |
请完成以下Java代码 | protected <S> S readAggregate(ConversionContext context, RowDocumentAccessor documentAccessor,
TypeInformation<? extends S> typeHint) {
RelationalPersistentEntity<?> implementationEntity = getImplementationEntity(mappingContext,
mappingContext.getRequiredPersistentEntity(typeHint));
return (S) super.readAggregate(context, documentAccessor, implementationEntity.getTypeInformation());
}
};
}
/**
* Returns if the entity passed as an argument is an interface the implementation provided by Immutable is provided
* instead. In all other cases the entity passed as an argument is returned.
*/
@SuppressWarnings("unchecked")
private <T> RelationalPersistentEntity<T> getImplementationEntity(JdbcMappingContext mappingContext,
RelationalPersistentEntity<T> entity) { | Class<T> type = entity.getType();
if (type.isInterface()) {
var immutableClass = String.format(IMMUTABLE_IMPLEMENTATION_CLASS, type.getPackageName(), type.getSimpleName());
if (ClassUtils.isPresent(immutableClass, resourceLoader.getClassLoader())) {
return (RelationalPersistentEntity<T>) mappingContext
.getPersistentEntity(ClassUtils.resolveClassName(immutableClass, resourceLoader.getClassLoader()));
}
}
return entity;
}
}
} | repos\spring-data-examples-main\jdbc\immutables\src\main\java\example\springdata\jdbc\immutables\Application.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class UserController {
@Autowired
UserService userService; // 用户服务层
/**
* 获取用户分页列表
* 处理 "/users" 的 GET 请求,用来获取用户分页列表
* 通过 @RequestParam 传递参数,进一步实现条件查询或者分页查询
*
* Pageable 支持的分页参数如下
* page - 当前页 从 0 开始
* size - 每页大小 默认值在 application.properties 配置
*/
@RequestMapping(method = RequestMethod.GET) | public Page<User> getUserPage(Pageable pageable) {
return userService.findByPage(pageable);
}
/**
* 创建用户
* 处理 "/users" 的 POST 请求,用来获取用户列表
* 通过 @RequestBody 绑定实体类参数
*/
@RequestMapping(value = "/create", method = RequestMethod.POST)
public User postUser(@RequestBody User user) {
return userService.insertByUser(user);
}
} | repos\springboot-learning-example-master\chapter-5-spring-boot-paging-sorting\src\main\java\spring\boot\core\web\UserController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | BeanDefinition getCsrfLogoutHandler() {
BeanDefinitionBuilder csrfAuthenticationStrategy = BeanDefinitionBuilder
.rootBeanDefinition(CsrfLogoutHandler.class);
csrfAuthenticationStrategy.addConstructorArgReference(this.csrfRepositoryRef);
return csrfAuthenticationStrategy.getBeanDefinition();
}
void setIgnoreCsrfRequestMatchers(List<BeanDefinition> requestMatchers) {
if (!requestMatchers.isEmpty()) {
BeanMetadataElement requestMatcher = (!StringUtils.hasText(this.requestMatcherRef))
? new RootBeanDefinition(DefaultRequiresCsrfMatcher.class)
: new RuntimeBeanReference(this.requestMatcherRef);
BeanDefinitionBuilder and = BeanDefinitionBuilder.rootBeanDefinition(AndRequestMatcher.class);
BeanDefinitionBuilder negated = BeanDefinitionBuilder.rootBeanDefinition(NegatedRequestMatcher.class);
BeanDefinitionBuilder or = BeanDefinitionBuilder.rootBeanDefinition(OrRequestMatcher.class);
or.addConstructorArgValue(requestMatchers);
negated.addConstructorArgValue(or.getBeanDefinition());
List<BeanMetadataElement> ands = new ManagedList<>();
ands.add(requestMatcher);
ands.add(negated.getBeanDefinition()); | and.addConstructorArgValue(ands);
this.csrfFilter.getPropertyValues().add("requireCsrfProtectionMatcher", and.getBeanDefinition());
}
}
void setObservationRegistry(BeanMetadataElement observationRegistry) {
this.observationRegistry = observationRegistry;
}
private static final class DefaultRequiresCsrfMatcher implements RequestMatcher {
private final HashSet<String> allowedMethods = new HashSet<>(Arrays.asList("GET", "HEAD", "TRACE", "OPTIONS"));
@Override
public boolean matches(HttpServletRequest request) {
return !this.allowedMethods.contains(request.getMethod());
}
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\http\CsrfBeanDefinitionParser.java | 2 |
请完成以下Java代码 | public String getLocalizedDescription() {
return localizedDescription;
}
@Override
public void setLocalizedDescription(String localizedDescription) {
this.localizedDescription = localizedDescription;
}
@Override
public Map<String, Object> getProcessVariables() {
Map<String, Object> variables = new HashMap<>();
if (queryVariables != null) {
for (HistoricVariableInstanceEntity variableInstance : queryVariables) {
if (variableInstance.getId() != null && variableInstance.getTaskId() == null) {
variables.put(variableInstance.getName(), variableInstance.getValue());
}
}
}
return variables;
} | public List<HistoricVariableInstanceEntity> getQueryVariables() {
if (queryVariables == null && Context.getCommandContext() != null) {
queryVariables = new HistoricVariableInitializingList();
}
return queryVariables;
}
public void setQueryVariables(List<HistoricVariableInstanceEntity> queryVariables) {
this.queryVariables = queryVariables;
}
// common methods //////////////////////////////////////////////////////////
@Override
public String toString() {
return "HistoricProcessInstanceEntity[superProcessInstanceId=" + superProcessInstanceId + "]";
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\HistoricProcessInstanceEntity.java | 1 |
请完成以下Java代码 | public void setUser2(final org.compiere.model.I_C_ElementValue User2)
{
set_ValueFromPO(COLUMNNAME_User2_ID, org.compiere.model.I_C_ElementValue.class, User2);
}
@Override
public void setUser2_ID (final int User2_ID)
{
if (User2_ID < 1)
set_Value (COLUMNNAME_User2_ID, null);
else
set_Value (COLUMNNAME_User2_ID, User2_ID);
}
@Override
public int getUser2_ID()
{
return get_ValueAsInt(COLUMNNAME_User2_ID);
}
@Override
public void setVoiceAuthCode (final @Nullable java.lang.String VoiceAuthCode)
{ | set_Value (COLUMNNAME_VoiceAuthCode, VoiceAuthCode);
}
@Override
public java.lang.String getVoiceAuthCode()
{
return get_ValueAsString(COLUMNNAME_VoiceAuthCode);
}
@Override
public void setWriteOffAmt (final @Nullable BigDecimal WriteOffAmt)
{
set_Value (COLUMNNAME_WriteOffAmt, WriteOffAmt);
}
@Override
public BigDecimal getWriteOffAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_WriteOffAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Payment.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getTransportStageCode() {
return transportStageCode;
}
/**
* Sets the value of the transportStageCode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTransportStageCode(String value) {
this.transportStageCode = value;
}
/**
* Gets the value of the transportModeCode property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTransportModeCode() {
return transportModeCode;
}
/**
* Sets the value of the transportModeCode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTransportModeCode(String value) {
this.transportModeCode = value;
}
/**
* Gets the value of the transportMeansCode property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTransportMeansCode() {
return transportMeansCode;
}
/**
* Sets the value of the transportMeansCode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTransportMeansCode(String value) {
this.transportMeansCode = value;
}
/**
* Gets the value of the transportMeansIdentification property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTransportMeansIdentification() { | return transportMeansIdentification;
}
/**
* Sets the value of the transportMeansIdentification property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTransportMeansIdentification(String value) {
this.transportMeansIdentification = value;
}
/**
* Gets the value of the carrierIdentifier property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCarrierIdentifier() {
return carrierIdentifier;
}
/**
* Sets the value of the carrierIdentifier property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCarrierIdentifier(String value) {
this.carrierIdentifier = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\TransportDetailType.java | 2 |
请完成以下Java代码 | public void setIsManual (final boolean IsManual)
{
set_Value (COLUMNNAME_IsManual, IsManual);
}
@Override
public boolean isManual()
{
return get_ValueAsBoolean(COLUMNNAME_IsManual);
}
@Override
public void setIsValid (final boolean IsValid)
{
set_Value (COLUMNNAME_IsValid, IsValid);
}
@Override
public boolean isValid()
{
return get_ValueAsBoolean(COLUMNNAME_IsValid);
}
@Override
public void setLineNo (final int LineNo)
{
set_Value (COLUMNNAME_LineNo, LineNo);
}
@Override
public int getLineNo()
{
return get_ValueAsInt(COLUMNNAME_LineNo);
}
@Override
public void setMatchErrorMsg (final @Nullable java.lang.String MatchErrorMsg)
{
set_Value (COLUMNNAME_MatchErrorMsg, MatchErrorMsg);
}
@Override
public java.lang.String getMatchErrorMsg()
{
return get_ValueAsString(COLUMNNAME_MatchErrorMsg);
}
@Override
public void setOrg_ID (final int Org_ID)
{
if (Org_ID < 1)
set_Value (COLUMNNAME_Org_ID, null);
else
set_Value (COLUMNNAME_Org_ID, Org_ID);
}
@Override
public int getOrg_ID()
{
return get_ValueAsInt(COLUMNNAME_Org_ID);
}
@Override
public void setPaymentDate (final @Nullable java.sql.Timestamp PaymentDate)
{
set_Value (COLUMNNAME_PaymentDate, PaymentDate);
}
@Override | public java.sql.Timestamp getPaymentDate()
{
return get_ValueAsTimestamp(COLUMNNAME_PaymentDate);
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setSektionNo (final @Nullable java.lang.String SektionNo)
{
set_Value (COLUMNNAME_SektionNo, SektionNo);
}
@Override
public java.lang.String getSektionNo()
{
return get_ValueAsString(COLUMNNAME_SektionNo);
}
/**
* Type AD_Reference_ID=541287
* Reference name: ESR_Type
*/
public static final int TYPE_AD_Reference_ID=541287;
/** QRR = QRR */
public static final String TYPE_QRR = "QRR";
/** ESR = ISR Reference */
public static final String TYPE_ESR = "ISR Reference";
/** SCOR = SCOR Reference */
public static final String TYPE_SCOR = "SCOR";
@Override
public void setType (final java.lang.String Type)
{
set_Value (COLUMNNAME_Type, Type);
}
@Override
public java.lang.String getType()
{
return get_ValueAsString(COLUMNNAME_Type);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java-gen\de\metas\payment\esr\model\X_ESR_ImportLine.java | 1 |
请完成以下Java代码 | public boolean isTablePrefixIsSchema() {
return tablePrefixIsSchema;
}
public String getDatabaseCatalog() {
return databaseCatalog;
}
public ProcessEngineConfiguration setDatabaseCatalog(String databaseCatalog) {
this.databaseCatalog = databaseCatalog;
return this;
}
public String getDatabaseSchema() {
return databaseSchema;
}
public ProcessEngineConfiguration setDatabaseSchema(String databaseSchema) {
this.databaseSchema = databaseSchema;
return this;
}
public String getXmlEncoding() {
return xmlEncoding;
}
public ProcessEngineConfiguration setXmlEncoding(String xmlEncoding) {
this.xmlEncoding = xmlEncoding;
return this;
}
public Clock getClock() {
return clock;
}
public ProcessEngineConfiguration setClock(Clock clock) {
this.clock = clock;
return this;
}
public ProcessDiagramGenerator getProcessDiagramGenerator() {
return this.processDiagramGenerator;
}
public ProcessEngineConfiguration setProcessDiagramGenerator(ProcessDiagramGenerator processDiagramGenerator) {
this.processDiagramGenerator = processDiagramGenerator;
return this;
}
public AsyncExecutor getAsyncExecutor() {
return asyncExecutor;
}
public ProcessEngineConfiguration setAsyncExecutor(AsyncExecutor asyncExecutor) {
this.asyncExecutor = asyncExecutor;
return this;
} | public int getLockTimeAsyncJobWaitTime() {
return lockTimeAsyncJobWaitTime;
}
public ProcessEngineConfiguration setLockTimeAsyncJobWaitTime(int lockTimeAsyncJobWaitTime) {
this.lockTimeAsyncJobWaitTime = lockTimeAsyncJobWaitTime;
return this;
}
public int getDefaultFailedJobWaitTime() {
return defaultFailedJobWaitTime;
}
public ProcessEngineConfiguration setDefaultFailedJobWaitTime(int defaultFailedJobWaitTime) {
this.defaultFailedJobWaitTime = defaultFailedJobWaitTime;
return this;
}
public int getAsyncFailedJobWaitTime() {
return asyncFailedJobWaitTime;
}
public ProcessEngineConfiguration setAsyncFailedJobWaitTime(int asyncFailedJobWaitTime) {
this.asyncFailedJobWaitTime = asyncFailedJobWaitTime;
return this;
}
public boolean isEnableProcessDefinitionInfoCache() {
return enableProcessDefinitionInfoCache;
}
public ProcessEngineConfiguration setEnableProcessDefinitionInfoCache(boolean enableProcessDefinitionInfoCache) {
this.enableProcessDefinitionInfoCache = enableProcessDefinitionInfoCache;
return this;
}
public List<JobProcessor> getJobProcessors() {
return jobProcessors;
}
public ProcessEngineConfiguration setJobProcessors(List<JobProcessor> jobProcessors) {
this.jobProcessors = jobProcessors;
return this;
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\ProcessEngineConfiguration.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getCategory() {
return category;
}
public String getCategoryLike() {
return categoryLike;
}
public String getElementId() {
return elementId;
}
public String getElementName() {
return elementName;
}
public String getScopeId() {
return scopeId;
}
public boolean isWithoutScopeId() {
return withoutScopeId;
}
public String getSubScopeId() {
return subScopeId;
}
public String getScopeType() {
return scopeType;
}
public String getScopeDefinitionId() {
return scopeDefinitionId;
}
public String getCaseDefinitionKey() {
return caseDefinitionKey;
}
public String getCorrelationId() {
return correlationId;
}
public boolean isOnlyTimers() {
return onlyTimers; | }
public boolean isOnlyMessages() {
return onlyMessages;
}
public Date getDuedateHigherThan() {
return duedateHigherThan;
}
public Date getDuedateLowerThan() {
return duedateLowerThan;
}
public Date getDuedateHigherThanOrEqual() {
return duedateHigherThanOrEqual;
}
public Date getDuedateLowerThanOrEqual() {
return duedateLowerThanOrEqual;
}
public String getLockOwner() {
return lockOwner;
}
public boolean isOnlyLocked() {
return onlyLocked;
}
public boolean isOnlyUnlocked() {
return onlyUnlocked;
}
public boolean isWithoutScopeType() {
return withoutScopeType;
}
} | repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\JobQueryImpl.java | 2 |
请完成以下Java代码 | private String getStaleErrorMsg()
{
if (!Check.isEmpty(_staleErrorMsg, true))
{
return _staleErrorMsg;
}
// Get the default
return sysConfigBL.getValue(SYSCONFIG_StaleErrorMsg, DEFAULT_StaleErrorMsg);
}
/**
* Sets AD_PInstance_ID to be used and tag all those workpackages which were deactivated.
*
* This is optional.
*
* @param adPInstanceId
*/
public WorkpackageCleanupStaleEntries setAD_PInstance_ID(final PInstanceId adPInstanceId) | {
this._adPInstanceId = adPInstanceId;
return this;
}
private PInstanceId getPinstanceId()
{
return _adPInstanceId;
}
public WorkpackageCleanupStaleEntries setLogger(final ILoggable logger)
{
Check.assumeNotNull(logger, "logger not null");
this.logger = logger;
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\api\impl\WorkpackageCleanupStaleEntries.java | 1 |
请完成以下Java代码 | public Integer getDeleteStatus() {
return deleteStatus;
}
public void setDeleteStatus(Integer deleteStatus) {
this.deleteStatus = deleteStatus;
}
public Long getProductCategoryId() {
return productCategoryId;
}
public void setProductCategoryId(Long productCategoryId) {
this.productCategoryId = productCategoryId;
}
public String getProductBrand() {
return productBrand;
}
public void setProductBrand(String productBrand) {
this.productBrand = productBrand;
}
public String getProductSn() {
return productSn;
}
public void setProductSn(String productSn) {
this.productSn = productSn;
}
public String getProductAttr() {
return productAttr;
}
public void setProductAttr(String productAttr) {
this.productAttr = productAttr;
} | @Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", productId=").append(productId);
sb.append(", productSkuId=").append(productSkuId);
sb.append(", memberId=").append(memberId);
sb.append(", quantity=").append(quantity);
sb.append(", price=").append(price);
sb.append(", productPic=").append(productPic);
sb.append(", productName=").append(productName);
sb.append(", productSubTitle=").append(productSubTitle);
sb.append(", productSkuCode=").append(productSkuCode);
sb.append(", memberNickname=").append(memberNickname);
sb.append(", createDate=").append(createDate);
sb.append(", modifyDate=").append(modifyDate);
sb.append(", deleteStatus=").append(deleteStatus);
sb.append(", productCategoryId=").append(productCategoryId);
sb.append(", productBrand=").append(productBrand);
sb.append(", productSn=").append(productSn);
sb.append(", productAttr=").append(productAttr);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\OmsCartItem.java | 1 |
请在Spring Boot框架中完成以下Java代码 | SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(
auth -> {
auth.anyRequest().authenticated();
});
http.sessionManagement(
session ->
session.sessionCreationPolicy(
SessionCreationPolicy.STATELESS)
);
http.httpBasic(withDefaults());
http.csrf(csrf -> csrf.disable());
http.headers(headers -> headers.frameOptions(frameOptionsConfig-> frameOptionsConfig.disable()));
http.oauth2ResourceServer(oauth2 -> oauth2.jwt(withDefaults()));
return http.build();
}
@Bean
public DataSource dataSource() {
return new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.H2)
.addScript(JdbcDaoImpl.DEFAULT_USER_SCHEMA_DDL_LOCATION)
.build();
}
@Bean
public UserDetailsService userDetailService(DataSource dataSource) {
var user = User.withUsername("in28minutes")
//.password("{noop}dummy")
.password("dummy")
.passwordEncoder(str -> passwordEncoder().encode(str))
.roles("USER")
.build();
var admin = User.withUsername("admin")
//.password("{noop}dummy")
.password("dummy")
.passwordEncoder(str -> passwordEncoder().encode(str))
.roles("ADMIN", "USER")
.build();
var jdbcUserDetailsManager = new JdbcUserDetailsManager(dataSource);
jdbcUserDetailsManager.createUser(user);
jdbcUserDetailsManager.createUser(admin); | return jdbcUserDetailsManager;
}
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public KeyPair keyPair() {
try {
var keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
return keyPairGenerator.generateKeyPair();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
@Bean
public RSAKey rsaKey(KeyPair keyPair) {
return new RSAKey
.Builder((RSAPublicKey)keyPair.getPublic())
.privateKey(keyPair.getPrivate())
.keyID(UUID.randomUUID().toString())
.build();
}
@Bean
public JWKSource<SecurityContext> jwkSource(RSAKey rsaKey) {
var jwkSet = new JWKSet(rsaKey);
return (jwkSelector, context) -> jwkSelector.select(jwkSet);
}
@Bean
public JwtDecoder jwtDecoder(RSAKey rsaKey) throws JOSEException {
return NimbusJwtDecoder
.withPublicKey(rsaKey.toRSAPublicKey())
.build();
}
@Bean
public JwtEncoder jwtEncoder(JWKSource<SecurityContext> jwkSource) {
return new NimbusJwtEncoder(jwkSource);
}
} | repos\master-spring-and-spring-boot-main\71-spring-security\src\main\java\com\in28minutes\learnspringsecurity\jwt\JwtSecurityConfiguration.java | 2 |
请完成以下Java代码 | public double beta(int i, int j)
{
return 0.0;
}
public double emissionCost(int i, int j)
{
return 0.0;
}
public double nextTransitionCost(int i, int j, int k)
{
return 0.0;
}
public double prevTransitionCost(int i, int j, int k)
{
return 0.0;
}
public double bestCost(int i, int j)
{
return 0.0;
}
public List<Integer> emissionVector(int i, int j)
{
return null;
}
public List<Integer> nextTransitionVector(int i, int j, int k)
{
return null;
}
public List<Integer> prevTransitionVector(int i, int j, int k)
{
return null;
}
public double Z()
{
return 0.0;
}
public boolean parse()
{
return true;
}
public boolean empty()
{
return true; | }
public boolean clear()
{
return true;
}
public boolean next()
{
return true;
}
public String parse(String str)
{
return "";
}
public String toString()
{
return "";
}
public String toString(String result, int size)
{
return "";
}
public String parse(String str, int size)
{
return "";
}
public String parse(String str, int size1, String result, int size2)
{
return "";
}
// set token-level penalty. It would be useful for implementing
// Dual decompositon decoding.
// e.g.
// "Dual Decomposition for Parsing with Non-Projective Head Automata"
// Terry Koo Alexander M. Rush Michael Collins Tommi Jaakkola David Sontag
public void setPenalty(int i, int j, double penalty)
{
}
public double penalty(int i, int j)
{
return 0.0;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\crf\crfpp\Tagger.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected void initClient() throws Exception {
if (lwm2mClient == null || lwm2mClient.getLeshanClient() == null || lwm2mClient.isDestroyed()) {
String endpoint = target.getDevice().getCredentials().getCredentialsId();
lwm2mClient = new Lwm2mClient(target.getBaseUrl(), endpoint);
lwm2mClient.initClient();
log.debug("Initialized LwM2M client for endpoint '{}'", endpoint);
}
}
@Override
protected void sendTestPayload(String payload) throws Exception {
lwm2mClient.send(payload, 0);
}
@Override
protected String createTestPayload(String testValue) {
return testValue;
} | @Override
protected void destroyClient() throws Exception {
if (lwm2mClient != null) {
lwm2mClient.destroy();
lwm2mClient = null;
}
}
@Override
protected TransportType getTransportType() {
return TransportType.LWM2M;
}
} | repos\thingsboard-master\monitoring\src\main\java\org\thingsboard\monitoring\service\transport\impl\Lwm2mTransportHealthChecker.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public CoffeeItemProcessor processor() {
return new CoffeeItemProcessor();
}
@Bean
public JdbcBatchItemWriter<Coffee> writer(DataSource dataSource) {
return new JdbcBatchItemWriterBuilder<Coffee>().itemSqlParameterSourceProvider(new BeanPropertyItemSqlParameterSourceProvider<>())
.sql("INSERT INTO coffee (brand, origin, characteristics) VALUES (:brand, :origin, :characteristics)")
.dataSource(dataSource)
.build();
}
@Bean
public Job importUserJob(JobRepository jobRepository, JobCompletionNotificationListener listener, Step step1) {
return new JobBuilder("importUserJob", jobRepository)
.incrementer(new RunIdIncrementer())
.listener(listener)
.flow(step1)
.end() | .build();
}
@Bean
public Step step1(JobRepository jobRepository, PlatformTransactionManager transactionManager, JdbcBatchItemWriter<Coffee> writer, VirtualThreadTaskExecutor taskExecutor) {
return new StepBuilder("step1", jobRepository)
.<Coffee, Coffee> chunk(10, transactionManager)
.reader(reader())
.processor(processor())
.writer(writer)
.taskExecutor(taskExecutor)
.build();
}
} | repos\tutorials-master\spring-batch\src\main\java\com\baeldung\bootbatch\BatchConfiguration.java | 2 |
请完成以下Java代码 | public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
} | public void setName(String name) {
this.name = name;
}
public String getEmpNumber() {
return empNumber;
}
public void setEmpNumber(String empNumber) {
this.empNumber = empNumber;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
} | repos\tutorials-master\persistence-modules\java-jpa\src\main\java\com\baeldung\jpa\queryparams\Employee.java | 1 |
请完成以下Java代码 | public void noTerminationInPast(final I_C_BPartner_Location bpLocation)
{
final Timestamp validFrom = bpLocation.getValidFrom();
if (validFrom != null && validFrom.before(Env.getDate()))
{
throw new AdempiereException("@AddressTerminatedInThePast@");
}
}
@ModelChange(timings = ModelValidator.TYPE_AFTER_CHANGE, ifColumnsChanged = I_C_BPartner_Location.COLUMNNAME_C_Location_ID)
public void updateWarehouseLocation(@NonNull final I_C_BPartner_Location bpLocation)
{
final LocationId newLocationId = LocationId.ofRepoId(bpLocation.getC_Location_ID());
final I_C_BPartner_Location bpLocationOld = InterfaceWrapperHelper.createOld(bpLocation, I_C_BPartner_Location.class);
final LocationId oldLocationId = LocationId.ofRepoId(bpLocationOld.getC_Location_ID());
warehouseBL.updateWarehouseLocation(oldLocationId, newLocationId);
}
@ModelChange(timings = ModelValidator.TYPE_BEFORE_CHANGE)
public void updateName(@NonNull final I_C_BPartner_Location bpLocation)
{
final String name = bpLocation.getName();
if (!bpLocation.isNameReadWrite() || BPARTNER_LOCATION_NAME_DEFAULT.equals(name))
{
updateBPLocationName(bpLocation);
}
}
@ModelChange(timings = ModelValidator.TYPE_BEFORE_NEW)
public void newName(@NonNull final I_C_BPartner_Location bpLocation)
{
updateBPLocationName(bpLocation); | }
private void updateBPLocationName(final @NonNull I_C_BPartner_Location bpLocation)
{
final BPartnerId bPartnerId = BPartnerId.ofRepoId(bpLocation.getC_BPartner_ID());
final BPartnerLocationId bPartnerLocationId = BPartnerLocationId.ofRepoIdOrNull(bPartnerId, bpLocation.getC_BPartner_Location_ID());
final IBPartnerDAO bpartnerDAO = Services.get(IBPartnerDAO.class);
bpLocation.setName(MakeUniqueLocationNameCommand.builder()
.name(bpLocation.getName())
.address(bpLocation.getC_Location())
.companyName(bpartnerDAO.getBPartnerNameById(bPartnerId))
.existingNames(bpartnerDAO.getOtherLocationNamesOfBPartner(bPartnerId, bPartnerLocationId))
.build()
.execute());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\bpartner\interceptor\C_BPartner_Location.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ReconciliationValidateBiz {
private static final Log LOG = LogFactory.getLog(ReconciliationValidateBiz.class);
@Autowired
private RpAccountCheckBatchService rpAccountCheckBatchService;
@Autowired
private RpAccountCheckTransactionService rpAccountCheckTransactionService;
@Autowired
private RpAccountCheckMistakeScratchPoolService rpAccountCheckMistakeScratchPoolService;
/**
* 判断某支付方式某天是否对过账,避免重复对账
*
* @param interfaceCode
* 支付方式
* @param billDate
* 账单日
* @return
*/
public Boolean isChecked(String interfaceCode, Date billDate) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String billDateStr = sdf.format(billDate);
LOG.info("检查,支付方式[" + interfaceCode + "],订单日期[" + billDateStr + "]");
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("billDate", billDateStr);
paramMap.put("interfaceCode", interfaceCode);
// 除非对账错误或者对账异常才可以发起第二次对账
paramMap.put("status", BatchStatusEnum.ERROR.name() + "," + BatchStatusEnum.FAIL.name());
List<RpAccountCheckBatch> list = rpAccountCheckBatchService.listBy(paramMap);
if (list.isEmpty()) {
return false;
}
return true;
}
/** | * 如果缓冲池中有三天前的数据就清理掉并记录差错
*/
public void validateScratchPool() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String dateStr = sdf.format(DateUtil.addDay(new Date(), -3));
// 查询是否有创建时间是三天前的数据
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("maxDate", dateStr);
List<RpAccountCheckMistakeScratchPool> list = rpAccountCheckMistakeScratchPoolService.listScratchPoolRecord(paramMap);
List<RpAccountCheckMistake> mistakeList = null;
// 如果有数据
if (!list.isEmpty()) {
mistakeList = new ArrayList<RpAccountCheckMistake>();
for (RpAccountCheckMistakeScratchPool scratchRecord : list) {
// 创建差错记录
RpAccountCheckMistake mistake = new RpAccountCheckMistake();
mistake.setAccountCheckBatchNo(scratchRecord.getBatchNo());
mistake.setBillDate(scratchRecord.getBillDate());
mistake.setErrType(ReconciliationMistakeTypeEnum.BANK_MISS.name());
mistake.setHandleStatus(MistakeHandleStatusEnum.NOHANDLE.name());
mistake.setBankType(scratchRecord.getPayWayCode());
mistake.setOrderNo(scratchRecord.getMerchantOrderNo());
mistake.setTradeTime(scratchRecord.getPaySuccessTime());
mistake.setTrxNo(scratchRecord.getTrxNo());
mistake.setOrderAmount(scratchRecord.getOrderAmount());
mistake.setRefundAmount(scratchRecord.getSuccessRefundAmount());
mistake.setTradeStatus(scratchRecord.getStatus());
mistake.setFee(scratchRecord.getPlatCost());
mistakeList.add(mistake);
}
rpAccountCheckTransactionService.removeDateFromPool(list, mistakeList);
}
}
} | repos\roncoo-pay-master\roncoo-pay-app-reconciliation\src\main\java\com\roncoo\pay\app\reconciliation\biz\ReconciliationValidateBiz.java | 2 |
请完成以下Java代码 | private static WritableCellFormat getHeaderFormat() throws WriteException {
WritableFont font = new WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD);
WritableCellFormat format = new WritableCellFormat(font);
// 线条
format.setBorder(Border.ALL, BorderLineStyle.THIN);
// 文字垂直对齐
format.setVerticalAlignment(VerticalAlignment.CENTRE);
// 文字水平对齐
format.setAlignment(Alignment.CENTRE);
// 文字是否换行
format.setWrap(false);
return format;
}
/**
* 数据样式
*
* @return
* @throws WriteException
*/ | private static WritableCellFormat getContentFormat() throws WriteException {
WritableFont font = new WritableFont(WritableFont.ARIAL, 10);
WritableCellFormat format = new WritableCellFormat(font);
// 线条
format.setBorder(Border.NONE, BorderLineStyle.THIN);
// 文字垂直对齐
format.setVerticalAlignment(VerticalAlignment.CENTRE);
// 文字水平对齐
format.setAlignment(Alignment.LEFT);
// 文字是否换行
format.setWrap(false);
return format;
}
} | repos\spring-boot-student-master\spring-boot-student-export\src\main\java\com\xiaolyuh\utils\ExcelExportUtils.java | 1 |
请完成以下Java代码 | public int getSalesRep_ID()
{
return get_ValueAsInt(COLUMNNAME_SalesRep_ID);
}
@Override
public void setSalesRep_Name (final @Nullable java.lang.String SalesRep_Name)
{
set_ValueNoCheck (COLUMNNAME_SalesRep_Name, SalesRep_Name);
}
@Override
public java.lang.String getSalesRep_Name()
{
return get_ValueAsString(COLUMNNAME_SalesRep_Name);
}
@Override
public void setTaxID (final java.lang.String TaxID)
{
set_ValueNoCheck (COLUMNNAME_TaxID, TaxID);
}
@Override
public java.lang.String getTaxID()
{
return get_ValueAsString(COLUMNNAME_TaxID);
} | @Override
public void setTitle (final @Nullable java.lang.String Title)
{
set_ValueNoCheck (COLUMNNAME_Title, Title);
}
@Override
public java.lang.String getTitle()
{
return get_ValueAsString(COLUMNNAME_Title);
}
@Override
public void setValue (final java.lang.String Value)
{
set_ValueNoCheck (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Project_Header_v.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Document countLate90sMovies(String keywords) {
List<Bson> pipeline = asList(
searchMeta(
compound()
.must(asList(
numberRange(
fieldPath("year"))
.gteLt(1995, 2000),
text(
fieldPath("fullplot"), keywords
)
)),
searchOptions()
.index(config.getQueryIndex())
.count(total())
)
);
debug(pipeline);
return collection.aggregate(pipeline)
.first();
}
public Collection<Document> moviesByKeywords(String keywords) {
List<Bson> pipeline = asList(
search(
text(
fieldPath("fullplot"), keywords
),
searchOptions()
.index(config.getQueryIndex())
),
project(fields(
excludeId(),
include("title", "year", "fullplot", "imdb.rating")
))
);
debug(pipeline);
return collection.aggregate(pipeline)
.into(new ArrayList<>()); | }
public Document genresThroughTheDecades(String genre) {
List<Bson> pipeline = asList(
searchMeta(
facet(
text(
fieldPath("genres"), genre
),
asList(
stringFacet("genresFacet",
fieldPath("genres")
).numBuckets(5),
numberFacet("yearFacet",
fieldPath("year"),
asList(1900, 1930, 1960, 1990, 2020)
)
)
),
searchOptions()
.index(config.getFacetIndex())
)
);
debug(pipeline);
return collection.aggregate(pipeline)
.first();
}
} | repos\tutorials-master\persistence-modules\spring-boot-persistence-mongodb-3\src\main\java\com\baeldung\boot\atlassearch\service\MovieAtlasSearchService.java | 2 |
请完成以下Java代码 | public void setPassword(String password) {
this.password = password;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
public class Service {
private String url;
private String token;
private String description;
public String getUrl() {
return url;
} | public void setUrl(String url) {
this.url = url;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-properties\src\main\java\com\baeldung\yaml\YAMLConfig.java | 1 |
请完成以下Java代码 | public class GrpcAdviceDiscoverer implements InitializingBean, ApplicationContextAware {
/**
* A filter for selecting {@code @GrpcExceptionHandler} methods.
*/
public static final MethodFilter EXCEPTION_HANDLER_METHODS =
method -> AnnotatedElementUtils.hasAnnotation(method, GrpcExceptionHandler.class);
private ApplicationContext applicationContext;
private Map<String, Object> annotatedBeans;
private Set<Method> annotatedMethods;
@Override
public void setApplicationContext(final ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
@Override
public void afterPropertiesSet() {
annotatedBeans = applicationContext.getBeansWithAnnotation(GrpcAdvice.class);
annotatedBeans.forEach(
(key, value) -> log.debug("Found gRPC advice: " + key + ", class: " + value.getClass().getName()));
annotatedMethods = findAnnotatedMethods();
}
private Set<Method> findAnnotatedMethods() {
return this.annotatedBeans.values().stream()
.map(Object::getClass)
.map(this::findAnnotatedMethods)
.flatMap(Collection::stream)
.collect(Collectors.toSet()); | }
private Set<Method> findAnnotatedMethods(final Class<?> clazz) {
return MethodIntrospector.selectMethods(clazz, EXCEPTION_HANDLER_METHODS);
}
public Map<String, Object> getAnnotatedBeans() {
Assert.state(annotatedBeans != null, "@GrpcAdvice annotation scanning failed.");
return annotatedBeans;
}
public Set<Method> getAnnotatedMethods() {
Assert.state(annotatedMethods != null, "@GrpcExceptionHandler annotation scanning failed.");
return annotatedMethods;
}
} | repos\grpc-spring-master\grpc-server-spring-boot-starter\src\main\java\net\devh\boot\grpc\server\advice\GrpcAdviceDiscoverer.java | 1 |
请完成以下Java代码 | private @Nullable String getQueryString(final HttpServletRequest request, final Pattern artifactPattern) {
final String query = request.getQueryString();
if (query == null) {
return null;
}
String result = artifactPattern.matcher(query).replaceFirst("");
if (result.length() == 0) {
return null;
}
// strip off the trailing & only if the artifact was the first query param
return result.startsWith("&") ? result.substring(1) : result;
}
/**
* Creates a {@link Pattern} that can be passed into the constructor. This allows the
* {@link Pattern} to be reused for every instance of
* {@link DefaultServiceAuthenticationDetails}.
* @param artifactParameterName
* @return
*/
static Pattern createArtifactPattern(String artifactParameterName) {
Assert.hasLength(artifactParameterName, "artifactParameterName is expected to have a length");
return Pattern.compile("&?" + Pattern.quote(artifactParameterName) + "=[^&]*");
} | /**
* Gets the port from the casServiceURL ensuring to return the proper value if the
* default port is being used.
* @param casServiceUrl the casServerUrl to be used (i.e.
* "https://example.com/context/login/cas")
* @return the port that is configured for the casServerUrl
*/
private static int getServicePort(URL casServiceUrl) {
int port = casServiceUrl.getPort();
if (port == -1) {
port = casServiceUrl.getDefaultPort();
}
return port;
}
} | repos\spring-security-main\cas\src\main\java\org\springframework\security\cas\web\authentication\DefaultServiceAuthenticationDetails.java | 1 |
请完成以下Java代码 | public void output (OutputStream out)
{
m_html.output(out);
} // output
/**
* Output Document
* @param out out
*/
public void output (PrintWriter out)
{
m_html.output(out);
} // output
/**
* Add Popup Center | * @param nowrap set nowrap in td
* @return null or center single td
*/
public td addPopupCenter(boolean nowrap)
{
if (m_table == null)
return null;
//
td center = new td ("popupCenter", AlignType.CENTER, AlignType.MIDDLE, nowrap);
center.setColSpan(2);
m_table.addElement(new tr()
.addElement(center));
return center;
} // addPopupCenter
} // WDoc | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\WebDoc.java | 1 |
请完成以下Java代码 | private static final class OidcProviderConfigurationConverter
implements Converter<Map<String, Object>, OidcProviderConfiguration> {
private static final ClaimConversionService CLAIM_CONVERSION_SERVICE = ClaimConversionService
.getSharedInstance();
private static final TypeDescriptor OBJECT_TYPE_DESCRIPTOR = TypeDescriptor.valueOf(Object.class);
private static final TypeDescriptor STRING_TYPE_DESCRIPTOR = TypeDescriptor.valueOf(String.class);
private static final TypeDescriptor URL_TYPE_DESCRIPTOR = TypeDescriptor.valueOf(URL.class);
private final ClaimTypeConverter claimTypeConverter;
private OidcProviderConfigurationConverter() {
Converter<Object, ?> collectionStringConverter = getConverter(
TypeDescriptor.collection(Collection.class, STRING_TYPE_DESCRIPTOR));
Converter<Object, ?> urlConverter = getConverter(URL_TYPE_DESCRIPTOR);
Map<String, Converter<Object, ?>> claimConverters = new HashMap<>();
claimConverters.put(OidcProviderMetadataClaimNames.ISSUER, urlConverter);
claimConverters.put(OidcProviderMetadataClaimNames.AUTHORIZATION_ENDPOINT, urlConverter);
claimConverters.put(OidcProviderMetadataClaimNames.TOKEN_ENDPOINT, urlConverter);
claimConverters.put(OidcProviderMetadataClaimNames.TOKEN_ENDPOINT_AUTH_METHODS_SUPPORTED,
collectionStringConverter);
claimConverters.put(OidcProviderMetadataClaimNames.JWKS_URI, urlConverter);
claimConverters.put(OidcProviderMetadataClaimNames.USER_INFO_ENDPOINT, urlConverter);
claimConverters.put(OidcProviderMetadataClaimNames.RESPONSE_TYPES_SUPPORTED, collectionStringConverter);
claimConverters.put(OidcProviderMetadataClaimNames.GRANT_TYPES_SUPPORTED, collectionStringConverter);
claimConverters.put(OidcProviderMetadataClaimNames.SUBJECT_TYPES_SUPPORTED, collectionStringConverter);
claimConverters.put(OidcProviderMetadataClaimNames.ID_TOKEN_SIGNING_ALG_VALUES_SUPPORTED,
collectionStringConverter);
claimConverters.put(OidcProviderMetadataClaimNames.SCOPES_SUPPORTED, collectionStringConverter); | this.claimTypeConverter = new ClaimTypeConverter(claimConverters);
}
@Override
public OidcProviderConfiguration convert(Map<String, Object> source) {
Map<String, Object> parsedClaims = this.claimTypeConverter.convert(source);
return OidcProviderConfiguration.withClaims(parsedClaims).build();
}
private static Converter<Object, ?> getConverter(TypeDescriptor targetDescriptor) {
return (source) -> CLAIM_CONVERSION_SERVICE.convert(source, OBJECT_TYPE_DESCRIPTOR, targetDescriptor);
}
}
} | repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\oidc\http\converter\OidcProviderConfigurationHttpMessageConverter.java | 1 |
请完成以下Java代码 | public String getActivityInstanceId() {
return activityInstanceId;
}
public String getDeleteReason() {
return deleteReason;
}
public String getDeleteReasonLike() {
return deleteReasonLike;
}
public Date getStartedAfter() {
return startedAfter;
}
public Date getStartedBefore() {
return startedBefore;
}
public Date getFinishedAfter() {
return finishedAfter;
}
public Date getFinishedBefore() {
return finishedBefore;
}
public List<String> getTenantIds() {
return tenantIds;
}
public List<List<String>> getSafeProcessInstanceIds() {
return safeProcessInstanceIds; | }
public void setSafeProcessInstanceIds(List<List<String>> safeProcessInstanceIds) {
this.safeProcessInstanceIds = safeProcessInstanceIds;
}
public Collection<String> getProcessInstanceIds() {
return processInstanceIds;
}
public Set<String> getCalledProcessInstanceIds() {
return calledProcessInstanceIds;
}
public void setCalledProcessInstanceIds(Set<String> calledProcessInstanceIds) {
this.calledProcessInstanceIds = calledProcessInstanceIds;
}
public List<List<String>> getSafeCalledProcessInstanceIds() {
return safeCalledProcessInstanceIds;
}
public void setSafeCalledProcessInstanceIds(List<List<String>> safeCalledProcessInstanceIds) {
this.safeCalledProcessInstanceIds = safeCalledProcessInstanceIds;
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\HistoricActivityInstanceQueryImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private static IExternalSystemChildConfigId toExternalSystemChildConfigId(final ExternalSystemType externalSystemType, final int repoId)
{
if (externalSystemType.isAlberta())
{
return ExternalSystemAlbertaConfigId.ofRepoId(repoId);
}
else if (externalSystemType.isShopware6())
{
return ExternalSystemShopware6ConfigId.ofRepoId(repoId);
}
// else if (externalSystemType.isOther())
// {
// return ExternalSystemOtherConfigId.ofRepoId(repoId);
// }
else if (externalSystemType.isRabbitMQ())
{
return ExternalSystemRabbitMQConfigId.ofRepoId(repoId);
}
else if (externalSystemType.isWOO())
{
return ExternalSystemWooCommerceConfigId.ofRepoId(repoId);
}
else if (externalSystemType.isGRSSignum())
{
return ExternalSystemGRSSignumConfigId.ofRepoId(repoId);
}
else if (externalSystemType.isLeichUndMehl())
{
return ExternalSystemLeichMehlConfigId.ofRepoId(repoId); | }
throw new AdempiereException("Unsupported externalSystemType: " + externalSystemType);
}
//
//
//
@Value
@Builder
@Jacksonized
public static class JsonPayload
{
@NonNull String externalSystemType;
int childConfigId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\config\qrcode\v1\JsonConverterV1.java | 2 |
请完成以下Java代码 | public void setURL (String URL)
{
set_Value (COLUMNNAME_URL, URL);
}
/** Get URL.
@return Full URL address - e.g. http://www.adempiere.org
*/
public String getURL ()
{
return (String)get_Value(COLUMNNAME_URL);
}
/** Set Registered EMail.
@param UserName | Email of the responsible for the System
*/
public void setUserName (String UserName)
{
set_Value (COLUMNNAME_UserName, UserName);
}
/** Get Registered EMail.
@return Email of the responsible for the System
*/
public String getUserName ()
{
return (String)get_Value(COLUMNNAME_UserName);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_Media_Server.java | 1 |
请完成以下Java代码 | public CamundaConnector newInstance(ModelTypeInstanceContext instanceContext) {
return new CamundaConnectorImpl(instanceContext);
}
});
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
camundaConnectorIdChild = sequenceBuilder.element(CamundaConnectorId.class)
.required()
.build();
camundaInputOutputChild = sequenceBuilder.element(CamundaInputOutput.class)
.build();
typeBuilder.build();
}
public CamundaConnectorImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
} | public CamundaConnectorId getCamundaConnectorId() {
return camundaConnectorIdChild.getChild(this);
}
public void setCamundaConnectorId(CamundaConnectorId camundaConnectorId) {
camundaConnectorIdChild.setChild(this, camundaConnectorId);
}
public CamundaInputOutput getCamundaInputOutput() {
return camundaInputOutputChild.getChild(this);
}
public void setCamundaInputOutput(CamundaInputOutput camundaInputOutput) {
camundaInputOutputChild.setChild(this, camundaInputOutput);
}
} | repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\camunda\CamundaConnectorImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void notify(@NonNull final CamelEvent event)
{
try
{
if (event instanceof CamelEvent.ExchangeSendingEvent)
{
handleSendingEvent((CamelEvent.ExchangeSendingEvent)event);
}
else if (event instanceof CamelEvent.ExchangeSentEvent)
{
handleSentEvent((CamelEvent.ExchangeSentEvent)event);
}
}
catch (final Exception exception)
{
logger.log(Level.SEVERE, "Exception caught while trying to attach metasfresh Authorization header!");
}
}
private void handleSendingEvent(@NonNull final CamelEvent.ExchangeSendingEvent event)
{
final Endpoint endpoint = event.getEndpoint();
if (endpoint.getEndpointUri() == null
|| (!metasfreshAPIURL.contains(endpoint.getEndpointUri()) && !endpoint.getEndpointUri().contains(metasfreshAPIURL)))
{
return;
}
final String authToken = metasfreshAuthProvider.getAuthToken();
if (Check.isBlank(authToken))
{
throw new RuntimeCamelException("No authorization token provided by MetasfreshAuthProvider!");
}
final Message in = event.getExchange().getIn();
in.setHeader(CoreConstants.AUTHORIZATION, authToken);
in.setHeader(CoreConstants.ACCEPT, "application/json;charset=UTF-8");
}
private void handleSentEvent(@NonNull final CamelEvent.ExchangeSentEvent sentEvent)
{
final Endpoint endpoint = sentEvent.getEndpoint(); | final Exception exception = sentEvent.getExchange().getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class);
if (!(exception instanceof HttpOperationFailedException))
{
return;
}
final HttpOperationFailedException httpOperationFailedException = (HttpOperationFailedException)exception;
if (httpOperationFailedException.getStatusCode() == 401)
{
if (endpoint.getEndpointUri() == null || !metasfreshAPIURL.contains(endpoint.getEndpointUri()))
{
logger.info("Received a 401 HttpStatusCode from: " + endpoint.getEndpointUri() +"; considered a non-MF-API URL based on: " + metasfreshAPIURL);
return;
}
final String usedAuthToken = String.valueOf(sentEvent.getExchange().getIn().getHeader(CoreConstants.AUTHORIZATION));
logger.info("MF-API responded with 401, stopping all routes; "
+ " Request sent had the following auth token:" + StringUtils.maskString(usedAuthToken)
+ "; metasfreshAuthProvider has: " + StringUtils.maskString(metasfreshAuthProvider.getAuthToken()));
this.customRouteController.stopAllRoutes();
producerTemplate.sendBody("direct:" + CUSTOM_TO_MF_ROUTE_ID, "Trigger external system authentication for metasfresh!");
}
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\core\src\main\java\de\metas\camel\externalsystems\core\authorization\MetasfreshAuthorizationTokenNotifier.java | 2 |
请完成以下Spring Boot application配置 | # ===================================================================
# Spring Boot configuration for the "dev" profile.
#
# This configuration overrides the application.yml file.
#
# More information on profiles: https://www.jhipster.tech/profiles/
# More information on configuration properties: https://www.jhipster.tech/common-application-properties/
# ===================================================================
# ===================================================================
# Standard Spring Boot properties.
# Full reference is available at:
# http://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html
# ===================================================================
logging:
level:
ROOT: DEBUG
io.github.jhipster: DEBUG
com.baeldung.jhipster6: DEBUG
spring:
profiles:
active: dev
include:
- swagger
# Uncomment to activate TLS for the dev profile
#- tls
devtools:
restart:
enabled: true
additional-exclude: .h2.server.properties
livereload:
enabled: false # we use Webpack dev server + BrowserSync for livereload
jackson:
serialization:
indent-output: true
datasource:
type: com.zaxxer.hikari.HikariDataSource
url: jdbc:h2:mem:bookstore;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
username: Bookstore
password:
hikari:
poolName: Hikari
auto-commit: false
h2:
console:
enabled: false
jpa:
database-platform: io.github.jhipster.domain.util.FixedH2Dialect
database: H2
show-sql: true
properties:
hibernate.id.new_generator_mappings: true
hibernate.connection.provider_disables_autocommit: true
hibernate.cache.use_second_level_cache: false
hibernate.cache.use_query_cache: false
hibernate.generate_statistics: true
liquibase:
contexts: dev
mail:
host: localhost
port: 25
username:
password:
messages:
cache-duration: PT1S # 1 second, see the ISO 8601 standard
thymeleaf:
cache: false
server:
port: 8080
# ===================================================================
# JHipster specific properties
#
# Full reference is available at: https://www.jhipster.tech/common-application-properties/
# ===================================================================
jhipster:
http:
version: V_1_1 # To use HTTP/2 you will need to activate TLS (see application-tls.yml)
# CORS is only enabled by default with the "dev" profile, so BrowserSync can access the API
cors:
allowed-origins: "*"
allowed-methods: "*"
allowed-headers: "*"
exposed-headers: "Authorization,Link,X-Total-Count"
allow-credentials: true
max-age: 1800
security:
authentication:
jwt:
# This token must be encoded using Base64 and be at least 256 bits long (you can type `openssl rand -base64 | 64` on your command line to generate a 512 bits one)
base64-secret: NDJmOTVlZjI2NzhlZDRjNmVkNTM1NDE2NjkyNDljZDJiNzBlMjI5YmZjMjY3MzdjZmZlMjI3NjE4OTRkNzc5MWYzNDNlYWMzYmJjOWRmMjc5ZWQyZTZmOWZkOTMxZWZhNWE1MTVmM2U2NjFmYjhlNDc2Y2Q3NzliMGY0YzFkNmI=
# Token is valid 24 hours
token-validity-in-seconds: 86400
token-validity-in-seconds-for-remember-me: 2592000
mail: # specific JHipster mail property, for standard properties see MailProperties
from: Bookstore@localhost
base-url: http://127.0.0.1:8080
metrics:
logs: # Reports metrics in the logs
enabled: false
report-frequency: 60 # in seconds
logging:
logstash: # Forward logs to logstash over a socket, used by LoggingConfiguration
enabled: false
host: localhost
port: 5000
queue-size: 512
# ===================================================================
# Application specific properties
# Add your own application properties here, see the ApplicationProperties class
# to have type-safe configuration, like in the JHipsterProperties above
#
# More documentation is available at:
# https://www.jhipster.tech/common-application-properties/
# ===================================================================
# application: | repos\tutorials-master\jhipster-6\bookstore-monolith\src\main\resources\config\application-dev.yml | 2 |
请完成以下Java代码 | public void setR_RequestProcessor_ID (int R_RequestProcessor_ID)
{
if (R_RequestProcessor_ID < 1)
set_ValueNoCheck (COLUMNNAME_R_RequestProcessor_ID, null);
else
set_ValueNoCheck (COLUMNNAME_R_RequestProcessor_ID, Integer.valueOf(R_RequestProcessor_ID));
}
/** Get Request Processor.
@return Processor for Requests
*/
public int getR_RequestProcessor_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_RequestProcessor_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Request Routing.
@param R_RequestProcessor_Route_ID
Automatic routing of requests
*/
public void setR_RequestProcessor_Route_ID (int R_RequestProcessor_Route_ID)
{
if (R_RequestProcessor_Route_ID < 1)
set_ValueNoCheck (COLUMNNAME_R_RequestProcessor_Route_ID, null);
else
set_ValueNoCheck (COLUMNNAME_R_RequestProcessor_Route_ID, Integer.valueOf(R_RequestProcessor_Route_ID));
}
/** Get Request Routing.
@return Automatic routing of requests
*/
public int getR_RequestProcessor_Route_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_RequestProcessor_Route_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_R_RequestType getR_RequestType() throws RuntimeException
{
return (I_R_RequestType)MTable.get(getCtx(), I_R_RequestType.Table_Name)
.getPO(getR_RequestType_ID(), get_TrxName()); }
/** Set Request Type.
@param R_RequestType_ID
Type of request (e.g. Inquiry, Complaint, ..)
*/
public void setR_RequestType_ID (int R_RequestType_ID)
{ | if (R_RequestType_ID < 1)
set_Value (COLUMNNAME_R_RequestType_ID, null);
else
set_Value (COLUMNNAME_R_RequestType_ID, Integer.valueOf(R_RequestType_ID));
}
/** Get Request Type.
@return Type of request (e.g. Inquiry, Complaint, ..)
*/
public int getR_RequestType_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_RequestType_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), String.valueOf(getSeqNo()));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_RequestProcessor_Route.java | 1 |
请完成以下Java代码 | public static String join(String delimiter, Collection<String> stringCollection)
{
StringBuilder sb = new StringBuilder(stringCollection.size() * (16 + delimiter.length()));
for (String str : stringCollection)
{
sb.append(str).append(delimiter);
}
return sb.toString();
}
public static String combine(String... termArray)
{
StringBuilder sbSentence = new StringBuilder();
for (String word : termArray)
{
sbSentence.append(word);
}
return sbSentence.toString();
}
public static String join(Iterable<? extends CharSequence> s, String delimiter)
{
Iterator<? extends CharSequence> iter = s.iterator();
if (!iter.hasNext()) return "";
StringBuilder buffer = new StringBuilder(iter.next());
while (iter.hasNext()) buffer.append(delimiter).append(iter.next());
return buffer.toString();
}
public static String combine(Sentence sentence)
{
StringBuilder sb = new StringBuilder(sentence.wordList.size() * 3);
for (IWord word : sentence.wordList)
{
sb.append(word.getValue()); | }
return sb.toString();
}
public static String combine(List<Word> wordList)
{
StringBuilder sb = new StringBuilder(wordList.size() * 3);
for (IWord word : wordList)
{
sb.append(word.getValue());
}
return sb.toString();
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\utility\TextUtility.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class PersistenceConfig {
@Autowired
private Environment env;
@Bean
public LocalSessionFactoryBean sessionFactory() {
final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan(new String[] { "com.baeldung.hibernate.immutable" });
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
@Bean
public DataSource dataSource() {
final BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName")));
dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url")));
dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user")));
dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass")));
return dataSource;
}
@Bean
public PlatformTransactionManager hibernateTransactionManager() {
final HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory().getObject());
return transactionManager;
} | @Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
private final Properties hibernateProperties() {
final Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
hibernateProperties.setProperty("hibernate.show_sql", "false");
return hibernateProperties;
}
} | repos\tutorials-master\persistence-modules\hibernate-annotations\src\main\java\com\baeldung\hibernate\immutable\PersistenceConfig.java | 2 |
请完成以下Java代码 | public ReturnReasonInformation10 getRtrInf() {
return rtrInf;
}
/**
* Sets the value of the rtrInf property.
*
* @param value
* allowed object is
* {@link ReturnReasonInformation10 }
*
*/
public void setRtrInf(ReturnReasonInformation10 value) {
this.rtrInf = value;
}
/**
* Gets the value of the corpActn property.
*
* @return
* possible object is
* {@link CorporateAction1 }
*
*/
public CorporateAction1 getCorpActn() {
return corpActn;
}
/**
* Sets the value of the corpActn property.
*
* @param value
* allowed object is
* {@link CorporateAction1 }
*
*/
public void setCorpActn(CorporateAction1 value) {
this.corpActn = value;
}
/**
* Gets the value of the sfkpgAcct property.
*
* @return
* possible object is
* {@link CashAccount16 }
*
*/
public CashAccount16 getSfkpgAcct() {
return sfkpgAcct;
} | /**
* Sets the value of the sfkpgAcct property.
*
* @param value
* allowed object is
* {@link CashAccount16 }
*
*/
public void setSfkpgAcct(CashAccount16 value) {
this.sfkpgAcct = value;
}
/**
* Gets the value of the addtlTxInf property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAddtlTxInf() {
return addtlTxInf;
}
/**
* Sets the value of the addtlTxInf property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAddtlTxInf(String value) {
this.addtlTxInf = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\EntryTransaction2.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public boolean isOverride() {
return override;
}
public void setOverride(boolean override) {
this.override = override;
}
public boolean isMultiple() {
return multiple;
}
public void setMultiple(boolean multiple) {
this.multiple = multiple;
}
} | static class Scan {
/**
* The basePackages to scan , the multiple-value is delimited by comma
*
* @see EnableDubbo#scanBasePackages()
*/
private Set<String> basePackages = new LinkedHashSet<>();
public Set<String> getBasePackages() {
return basePackages;
}
public void setBasePackages(Set<String> basePackages) {
this.basePackages = basePackages;
}
}
} | repos\dubbo-spring-boot-project-master\dubbo-spring-boot-compatible\autoconfigure\src\main\java\org\apache\dubbo\spring\boot\autoconfigure\DubboConfigurationProperties.java | 2 |
请完成以下Java代码 | public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
}
public static class Car extends Vehicle {
private int seatingCapacity;
private double topSpeed;
@JsonCreator
public Car(@JsonProperty("make") String make, @JsonProperty("model") String model, @JsonProperty("seating") int seatingCapacity, @JsonProperty("topSpeed") double topSpeed) {
super(make, model);
this.seatingCapacity = seatingCapacity;
this.topSpeed = topSpeed;
}
public int getSeatingCapacity() {
return seatingCapacity;
}
public void setSeatingCapacity(int seatingCapacity) {
this.seatingCapacity = seatingCapacity;
} | public double getTopSpeed() {
return topSpeed;
}
public void setTopSpeed(double topSpeed) {
this.topSpeed = topSpeed;
}
}
public static class Truck extends Vehicle {
private double payloadCapacity;
@JsonCreator
public Truck(@JsonProperty("make") String make, @JsonProperty("model") String model, @JsonProperty("payload") double payloadCapacity) {
super(make, model);
this.payloadCapacity = payloadCapacity;
}
public double getPayloadCapacity() {
return payloadCapacity;
}
public void setPayloadCapacity(double payloadCapacity) {
this.payloadCapacity = payloadCapacity;
}
}
} | repos\tutorials-master\jackson-modules\jackson-core\src\main\java\com\baeldung\jackson\inheritance\SubTypeConstructorStructure.java | 1 |
请完成以下Java代码 | public void exportDatabase(HttpServletResponse response, DatabaseQueryCriteria criteria) throws IOException {
databaseService.download(databaseService.queryAll(criteria), response);
}
@ApiOperation(value = "查询数据库")
@GetMapping
@PreAuthorize("@el.check('database:list')")
public ResponseEntity<PageResult<DatabaseDto>> queryDatabase(DatabaseQueryCriteria criteria, Pageable pageable){
return new ResponseEntity<>(databaseService.queryAll(criteria,pageable),HttpStatus.OK);
}
@Log("新增数据库")
@ApiOperation(value = "新增数据库")
@PostMapping
@PreAuthorize("@el.check('database:add')")
public ResponseEntity<Object> createDatabase(@Validated @RequestBody Database resources){
databaseService.create(resources);
return new ResponseEntity<>(HttpStatus.CREATED);
}
@Log("修改数据库")
@ApiOperation(value = "修改数据库")
@PutMapping
@PreAuthorize("@el.check('database:edit')")
public ResponseEntity<Object> updateDatabase(@Validated @RequestBody Database resources){
databaseService.update(resources);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
@Log("删除数据库")
@ApiOperation(value = "删除数据库")
@DeleteMapping
@PreAuthorize("@el.check('database:del')")
public ResponseEntity<Object> deleteDatabase(@RequestBody Set<String> ids){
databaseService.delete(ids);
return new ResponseEntity<>(HttpStatus.OK);
}
@Log("测试数据库链接")
@ApiOperation(value = "测试数据库链接")
@PostMapping("/testConnect")
@PreAuthorize("@el.check('database:testConnect')")
public ResponseEntity<Object> testConnect(@Validated @RequestBody Database resources){
return new ResponseEntity<>(databaseService.testConnection(resources),HttpStatus.CREATED);
} | @Log("执行SQL脚本")
@ApiOperation(value = "执行SQL脚本")
@PostMapping(value = "/upload")
@PreAuthorize("@el.check('database:add')")
public ResponseEntity<Object> uploadDatabase(@RequestBody MultipartFile file, HttpServletRequest request)throws Exception{
String id = request.getParameter("id");
DatabaseDto database = databaseService.findById(id);
String fileName;
if(database != null){
fileName = FileUtil.verifyFilename(file.getOriginalFilename());
File executeFile = new File(fileSavePath + fileName);
FileUtil.del(executeFile);
file.transferTo(executeFile);
String result = SqlUtils.executeFile(database.getJdbcUrl(), database.getUserName(), database.getPwd(), executeFile);
return new ResponseEntity<>(result,HttpStatus.OK);
}else{
throw new BadRequestException("Database not exist");
}
}
} | repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\maint\rest\DatabaseController.java | 1 |
请完成以下Java代码 | public final VLookup getVLookup(final int windowNo,
final int tabNo,
final int displayType,
final String tableName,
final String columnName,
final boolean mandatory,
final boolean autocomplete)
{
final Properties ctx = Env.getCtx();
final I_AD_Column column = Services.get(IADTableDAO.class).retrieveColumn(tableName, columnName);
final Lookup lookup = MLookupFactory.newInstance().get(ctx, windowNo, tabNo, column.getAD_Column_ID(), displayType);
lookup.setMandatory(mandatory);
final VLookup lookupField = new VLookup(columnName,
mandatory, // mandatory
false, // isReadOnly
true, // isUpdateable
lookup);
if (autocomplete)
{
lookupField.enableLookupAutocomplete();
}
//
// For firing validation rules
lookupField.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(final ActionEvent e)
{
final Object value = lookupField.getValue();
Env.setContext(ctx, windowNo, columnName, value == null ? "" : value.toString());
}
});
return lookupField;
} | @Override
public final VNumber getVNumber(final String columnName, final boolean mandatory)
{
final Properties ctx = Env.getCtx();
final String title = Services.get(IMsgBL.class).translate(ctx, columnName);
return new VNumber(columnName,
mandatory,
false, // isReadOnly
true, // isUpdateable
DisplayType.Number, // displayType
title);
}
@Override
public final void disposeDialogForColumnData(final int windowNo, final JDialog dialog, final List<String> columnNames)
{
if (columnNames == null || columnNames.isEmpty())
{
return;
}
final StringBuilder missingColumnsBuilder = new StringBuilder();
final Iterator<String> columnNamesIt = columnNames.iterator();
while (columnNamesIt.hasNext())
{
final String columnName = columnNamesIt.next();
missingColumnsBuilder.append("@").append(columnName).append("@");
if (columnNamesIt.hasNext())
{
missingColumnsBuilder.append(", ");
}
}
final Exception ex = new AdempiereException("@NotFound@ " + missingColumnsBuilder.toString());
ADialog.error(windowNo, dialog.getContentPane(), ex.getLocalizedMessage());
dialog.dispose();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\ed\api\impl\SwingEditorFactory.java | 1 |
请完成以下Java代码 | public class MessageEventPayload implements Payload {
private String id;
private String name;
private String correlationKey;
private String businessKey;
private Map<String, Object> variables;
public MessageEventPayload() {
this.id = UUID.randomUUID().toString();
}
public MessageEventPayload(String name, String correlationKey, String businessKey, Map<String, Object> variables) {
this();
this.name = name;
this.businessKey = businessKey;
this.correlationKey = correlationKey;
this.variables = variables;
}
@Override
public String getId() {
return id;
}
public String getName() {
return name;
}
public Map<String, Object> getVariables() {
return variables;
}
public String getCorrelationKey() {
return correlationKey;
}
public String getBusinessKey() {
return businessKey;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("MessageEventPayload [id=");
builder.append(id);
builder.append(", messageName=");
builder.append(name);
builder.append(", correlationKey=");
builder.append(correlationKey);
builder.append(", businessKey=");
builder.append(businessKey);
builder.append(", variables="); | builder.append(variables);
builder.append("]");
return builder.toString();
}
@Override
public int hashCode() {
return Objects.hash(businessKey, correlationKey, id, name, variables);
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
MessageEventPayload other = (MessageEventPayload) obj;
return (
Objects.equals(businessKey, other.businessKey) &&
Objects.equals(correlationKey, other.correlationKey) &&
Objects.equals(id, other.id) &&
Objects.equals(name, other.name) &&
Objects.equals(variables, other.variables)
);
}
} | repos\Activiti-develop\activiti-api\activiti-api-process-model\src\main\java\org\activiti\api\process\model\payloads\MessageEventPayload.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Author {
@Id
@GeneratedValue
private Long id;
private String name;
@OneToMany(cascade = CascadeType.ALL)
private Set<Book> books;
protected Author() {
}
public Author(Long id, String name, Set<Book> books) {
this.id = id;
this.name = name;
this.books = books;
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<Book> getBooks() {
return books;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true; | }
if (o == null || getClass() != o.getClass()) {
return false;
}
Author author = (Author) o;
return Objects.equals(id, author.id) && Objects.equals(name, author.name)
&& Objects.equals(books, author.books);
}
@Override
public int hashCode() {
return Objects.hash(id, name, books);
}
@Override
public String toString() {
return "Author{" + "name='" + name + '\'' + '}';
}
} | repos\spring-data-examples-main\jpa\graalvm-native\src\main\java\com\example\data\jpa\model\Author.java | 2 |
请完成以下Java代码 | private static long filesInside(File it) {
if (it.isFile()) {
return 1;
} else if (it.isDirectory()) {
return numberOfFilesIn_Stream(it.getAbsolutePath());
} else {
return 0;
}
}
public static long numberOfFilesIn_Walk(String path) {
Path dir = Path.of(path);
try (Stream<Path> stream = Files.walk(dir)) {
return stream.parallel()
.map(getFileOrEmpty())
.flatMap(Optional::stream)
.filter(it -> !it.isDirectory())
.count();
} catch (IOException e) {
throw new RuntimeException(e);
}
} | private static Function<Path, Optional<File>> getFileOrEmpty() {
return it -> {
try {
return Optional.of(it.toFile());
} catch (UnsupportedOperationException e) {
println(e);
return Optional.empty();
}
};
}
public static long numberOfFilesIn_NIO(String path) {
try (Stream<Path> stream = Files.find(
Paths.get(path),
Integer.MAX_VALUE,
(__, attr) -> attr.isRegularFile())
) {
return stream.count();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
} | repos\tutorials-master\core-java-modules\core-java-23\src\main\java\com\baeldung\javafeatures\FindFolder.java | 1 |
请完成以下Java代码 | public String getEventField() {
return eventField;
}
public void setEventField(String eventField) {
this.eventField = eventField;
}
public String getRoundRobin() {
return roundRobin;
}
public void setRoundRobin(String roundRobin) {
this.roundRobin = roundRobin;
}
public String getDelegateExpression() {
return delegateExpression;
}
public void setDelegateExpression(String delegateExpression) {
this.delegateExpression = delegateExpression;
}
}
@JsonInclude(Include.NON_NULL)
public static class RecordKey {
protected String fixedValue;
protected String eventField;
protected String delegateExpression; | public String getFixedValue() {
return fixedValue;
}
public void setFixedValue(String fixedValue) {
this.fixedValue = fixedValue;
}
public String getEventField() {
return eventField;
}
public void setEventField(String eventField) {
this.eventField = eventField;
}
public String getDelegateExpression() {
return delegateExpression;
}
public void setDelegateExpression(String delegateExpression) {
this.delegateExpression = delegateExpression;
}
// backward compatibility
@JsonCreator(mode = JsonCreator.Mode.DELEGATING)
public static RecordKey fromFixedValue(String fixedValue) {
RecordKey recordKey = new RecordKey();
recordKey.setFixedValue(fixedValue);
return recordKey;
}
}
} | repos\flowable-engine-main\modules\flowable-event-registry-model\src\main\java\org\flowable\eventregistry\model\KafkaOutboundChannelModel.java | 1 |
请完成以下Java代码 | protected ProcessPreconditionsResolution checkPreconditionsApplicable()
{
if (!isPickerProfile())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("only picker shall pack");
}
if (!rowsService.anyRowsEligibleForPacking(getSelectedRows()))
{
return ProcessPreconditionsResolution.rejectWithInternalReason("no eligible rows were selected");
}
return ProcessPreconditionsResolution.accept();
}
@Override | @RunOutOfTrx
protected String doIt()
{
final ImmutableList<WebuiPickHUResult> result = rowsService.setPackingInstruction(getSelectedRows(), getPackToSpec());
updateViewRowFromPickingCandidate(result);
invalidateView();
return MSG_OK;
}
private PackToSpec getPackToSpec() {return PackToSpec.ofGenericPackingInstructionsId(p_M_HU_PI_ID);}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingV2\productsToPick\process\ProductsToPick_SetPackingInstructions.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getRef() {
return ref;
}
/**
* Sets the value of the ref property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRef(String value) {
this.ref = value;
}
/**
* Gets the value of the refQualifier property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRefQualifier() { | return refQualifier;
}
/**
* Sets the value of the refQualifier property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRefQualifier(String value) {
this.refQualifier = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\messaging\header\RecipientRefType.java | 2 |
请完成以下Java代码 | public String getId() {
return id;
}
@Override
public String getName() {
return name;
}
@Override
public FormType getType() {
return type;
}
@Override
public String getValue() {
return value;
} | @Override
public boolean isRequired() {
return isRequired;
}
@Override
public boolean isReadable() {
return isReadable;
}
public void setValue(String value) {
this.value = value;
}
@Override
public boolean isWritable() {
return isWritable;
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\form\FormPropertyImpl.java | 1 |
请完成以下Java代码 | public static void fillJsonTypes(Map<String, Class<? extends BaseBpmnJsonConverter>> convertersToBpmnMap) {
convertersToBpmnMap.put(STENCIL_EVENT_CATCH_TIMER, CatchEventJsonConverter.class);
convertersToBpmnMap.put(STENCIL_EVENT_CATCH_MESSAGE, CatchEventJsonConverter.class);
convertersToBpmnMap.put(STENCIL_EVENT_CATCH_SIGNAL, CatchEventJsonConverter.class);
}
public static void fillBpmnTypes(
Map<Class<? extends BaseElement>, Class<? extends BaseBpmnJsonConverter>> convertersToJsonMap
) {
convertersToJsonMap.put(IntermediateCatchEvent.class, CatchEventJsonConverter.class);
}
protected String getStencilId(BaseElement baseElement) {
IntermediateCatchEvent catchEvent = (IntermediateCatchEvent) baseElement;
List<EventDefinition> eventDefinitions = catchEvent.getEventDefinitions();
if (eventDefinitions.size() != 1) {
// return timer event as default;
return STENCIL_EVENT_CATCH_TIMER;
}
EventDefinition eventDefinition = eventDefinitions.get(0);
if (eventDefinition instanceof MessageEventDefinition) {
return STENCIL_EVENT_CATCH_MESSAGE;
} else if (eventDefinition instanceof SignalEventDefinition) {
return STENCIL_EVENT_CATCH_SIGNAL;
} else {
return STENCIL_EVENT_CATCH_TIMER;
}
}
protected void convertElementToJson(ObjectNode propertiesNode, BaseElement baseElement) {
IntermediateCatchEvent catchEvent = (IntermediateCatchEvent) baseElement; | addEventProperties(catchEvent, propertiesNode);
}
protected FlowElement convertJsonToElement(
JsonNode elementNode,
JsonNode modelNode,
Map<String, JsonNode> shapeMap
) {
IntermediateCatchEvent catchEvent = new IntermediateCatchEvent();
String stencilId = BpmnJsonConverterUtil.getStencilId(elementNode);
if (STENCIL_EVENT_CATCH_TIMER.equals(stencilId)) {
convertJsonToTimerDefinition(elementNode, catchEvent);
} else if (STENCIL_EVENT_CATCH_MESSAGE.equals(stencilId)) {
convertJsonToMessageDefinition(elementNode, catchEvent);
} else if (STENCIL_EVENT_CATCH_SIGNAL.equals(stencilId)) {
convertJsonToSignalDefinition(elementNode, catchEvent);
}
return catchEvent;
}
} | repos\Activiti-develop\activiti-core\activiti-json-converter\src\main\java\org\activiti\editor\language\json\converter\CatchEventJsonConverter.java | 1 |
请完成以下Java代码 | protected Object getProcessVariableLocal(InjectionPoint ip) {
String processVariableName = getVariableLocalName(ip);
if (logger.isLoggable(Level.FINE)) {
logger.fine("Getting local process variable '" + processVariableName + "' from ProcessInstance[" + businessProcess.getProcessInstanceId() + "].");
}
return businessProcess.getVariableLocal(processVariableName);
}
/**
* @since 7.3
*/
@Produces
@ProcessVariableLocalTyped
protected TypedValue getProcessVariableLocalTyped(InjectionPoint ip) {
String processVariableName = getVariableLocalTypedName(ip);
if (logger.isLoggable(Level.FINE)) {
logger.fine("Getting local typed process variable '" + processVariableName + "' from ProcessInstance[" + businessProcess.getProcessInstanceId() + "].");
} | return businessProcess.getVariableLocalTyped(processVariableName);
}
@Produces
@Named
protected Map<String, Object> processVariablesLocal() {
return processVariableLocalMap;
}
/**
* @since 7.3
*/
@Produces
@Named
protected VariableMap processVariableMapLocal() {
return processVariableLocalMap;
}
} | repos\camunda-bpm-platform-master\engine-cdi\core\src\main\java\org\camunda\bpm\engine\cdi\ProcessVariables.java | 1 |
请完成以下Java代码 | public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getTargetDate() {
return targetDate; | }
public void setTargetDate(Date targetDate) {
this.targetDate = targetDate;
}
public Todo(){super();}
public Todo(String user, String desc, Date targetDate, boolean isDone) {
super();
this.userName = user;
this.description = desc;
this.targetDate = targetDate;
}
} | repos\SpringBoot-Projects-FullStack-master\Part-8 Spring Boot Real Projects\0.ProjectToDoinDB\src\main\java\spring\hibernate\model\Todo.java | 1 |
请完成以下Java代码 | public void onApplicationEvent(T event) {
if (!filterTbApplicationEvent(event)) {
log.trace("Skipping event due to filter: {}", event);
return;
}
boolean validUpdate = false;
seqNumberLock.lock();
try {
if (event.getSequenceNumber() > lastProcessedSequenceNumber) {
validUpdate = true;
lastProcessedSequenceNumber = event.getSequenceNumber();
}
} finally {
seqNumberLock.unlock();
}
if (validUpdate) { | try {
onTbApplicationEvent(event);
} catch (Exception e) {
log.error("Failed to handle partition change event: {}", event, e);
}
} else {
log.info("Application event ignored due to invalid sequence number ({} > {}). Event: {}", lastProcessedSequenceNumber, event.getSequenceNumber(), event);
}
}
protected abstract void onTbApplicationEvent(T event);
protected boolean filterTbApplicationEvent(T event) {
return true;
}
} | repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\discovery\TbApplicationEventListener.java | 1 |
请完成以下Java代码 | public void setCM_AccessProfile_ID (int CM_AccessProfile_ID)
{
if (CM_AccessProfile_ID < 1)
set_ValueNoCheck (COLUMNNAME_CM_AccessProfile_ID, null);
else
set_ValueNoCheck (COLUMNNAME_CM_AccessProfile_ID, Integer.valueOf(CM_AccessProfile_ID));
}
/** Get Web Access Profile.
@return Web Access Profile
*/
public int getCM_AccessProfile_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_CM_AccessProfile_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Comment/Help.
@param Help
Comment or Hint
*/
public void setHelp (String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
/** Get Comment/Help.
@return Comment or Hint
*/
public String getHelp ()
{
return (String)get_Value(COLUMNNAME_Help);
}
/** Set Exclude.
@param IsExclude | Exclude access to the data - if not selected Include access to the data
*/
public void setIsExclude (boolean IsExclude)
{
set_Value (COLUMNNAME_IsExclude, Boolean.valueOf(IsExclude));
}
/** Get Exclude.
@return Exclude access to the data - if not selected Include access to the data
*/
public boolean isExclude ()
{
Object oo = get_Value(COLUMNNAME_IsExclude);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_AccessProfile.java | 1 |
请完成以下Java代码 | public Segment enableJapaneseNameRecognize(boolean enable)
{
config.japaneseNameRecognize = enable;
config.updateNerConfig();
return this;
}
/**
* 是否启用偏移量计算(开启后Term.offset才会被计算)
*
* @param enable
* @return
*/
public Segment enableOffset(boolean enable)
{
config.offset = enable;
return this;
}
/**
* 是否启用数词和数量词识别<br>
* 即[二, 十, 一] => [二十一],[十, 九, 元] => [十九元]
*
* @param enable
* @return
*/
public Segment enableNumberQuantifierRecognize(boolean enable)
{
config.numberQuantifierRecognize = enable;
return this;
}
/**
* 是否启用所有的命名实体识别
*
* @param enable
* @return
*/
public Segment enableAllNamedEntityRecognize(boolean enable)
{
config.nameRecognize = enable;
config.japaneseNameRecognize = enable;
config.translatedNameRecognize = enable;
config.placeRecognize = enable;
config.organizationRecognize = enable;
config.updateNerConfig();
return this;
}
class WorkThread extends Thread
{
String[] sentenceArray;
List<Term>[] termListArray;
int from;
int to;
public WorkThread(String[] sentenceArray, List<Term>[] termListArray, int from, int to)
{
this.sentenceArray = sentenceArray;
this.termListArray = termListArray;
this.from = from;
this.to = to;
}
@Override
public void run()
{
for (int i = from; i < to; ++i)
{
termListArray[i] = segSentence(sentenceArray[i].toCharArray());
}
}
} | /**
* 开启多线程
*
* @param enable true表示开启[系统CPU核心数]个线程,false表示单线程
* @return
*/
public Segment enableMultithreading(boolean enable)
{
if (enable) config.threadNumber = Runtime.getRuntime().availableProcessors();
else config.threadNumber = 1;
return this;
}
/**
* 开启多线程
*
* @param threadNumber 线程数量
* @return
*/
public Segment enableMultithreading(int threadNumber)
{
config.threadNumber = threadNumber;
return this;
}
/**
* 是否执行字符正规化(繁体->简体,全角->半角,大写->小写),切换配置后必须删CustomDictionary.txt.bin缓存
*/
public Segment enableNormalization(boolean normalization)
{
config.normalization = normalization;
return this;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\seg\Segment.java | 1 |
请完成以下Java代码 | public int getHeightInCm ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_HeightInCm);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Length In Cm.
@param LengthInCm Length In Cm */
@Override
public void setLengthInCm (int LengthInCm)
{
set_Value (COLUMNNAME_LengthInCm, Integer.valueOf(LengthInCm));
}
/** Get Length In Cm.
@return Length In Cm */
@Override
public int getLengthInCm ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_LengthInCm);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_M_Package getM_Package()
{
return get_ValueAsPO(COLUMNNAME_M_Package_ID, org.compiere.model.I_M_Package.class);
}
@Override
public void setM_Package(org.compiere.model.I_M_Package M_Package)
{
set_ValueFromPO(COLUMNNAME_M_Package_ID, org.compiere.model.I_M_Package.class, M_Package);
}
/** Set Packstück.
@param M_Package_ID
Shipment Package
*/
@Override
public void setM_Package_ID (int M_Package_ID)
{
if (M_Package_ID < 1)
set_Value (COLUMNNAME_M_Package_ID, null);
else
set_Value (COLUMNNAME_M_Package_ID, Integer.valueOf(M_Package_ID));
}
/** Get Packstück.
@return Shipment Package
*/
@Override
public int getM_Package_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Package_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Package Content.
@param PackageContent Package Content */
@Override
public void setPackageContent (java.lang.String PackageContent)
{
set_Value (COLUMNNAME_PackageContent, PackageContent);
}
/** Get Package Content.
@return Package Content */ | @Override
public java.lang.String getPackageContent ()
{
return (java.lang.String)get_Value(COLUMNNAME_PackageContent);
}
/** Set Weight In Kg.
@param WeightInKg Weight In Kg */
@Override
public void setWeightInKg (int WeightInKg)
{
set_Value (COLUMNNAME_WeightInKg, Integer.valueOf(WeightInKg));
}
/** Get Weight In Kg.
@return Weight In Kg */
@Override
public int getWeightInKg ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_WeightInKg);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Width In Cm.
@param WidthInCm Width In Cm */
@Override
public void setWidthInCm (int WidthInCm)
{
set_Value (COLUMNNAME_WidthInCm, Integer.valueOf(WidthInCm));
}
/** Get Width In Cm.
@return Width In Cm */
@Override
public int getWidthInCm ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_WidthInCm);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-gen\de\metas\shipper\gateway\dpd\model\X_DPD_StoreOrderLine.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Object execute(CommandContext commandContext) {
DeadLetterJobEntity jobToDelete = getJobToDelete(commandContext);
sendCancelEvent(jobToDelete);
jobServiceConfiguration.getDeadLetterJobEntityManager().delete(jobToDelete);
return null;
}
protected void sendCancelEvent(DeadLetterJobEntity jobToDelete) {
FlowableEventDispatcher eventDispatcher = jobServiceConfiguration.getEventDispatcher();
if (eventDispatcher != null && eventDispatcher.isEnabled()) {
eventDispatcher.dispatchEvent(FlowableJobEventBuilder.createEntityEvent(FlowableEngineEventType.JOB_CANCELED, jobToDelete),
jobServiceConfiguration.getEngineName());
}
} | protected DeadLetterJobEntity getJobToDelete(CommandContext commandContext) {
if (deadLetterJobId == null) {
throw new FlowableIllegalArgumentException("jobId is null");
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Deleting job {}", deadLetterJobId);
}
DeadLetterJobEntity job = jobServiceConfiguration.getDeadLetterJobEntityManager().findById(deadLetterJobId);
if (job == null) {
throw new FlowableObjectNotFoundException("No dead letter job found with id '" + deadLetterJobId + "'", Job.class);
}
return job;
}
} | repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\cmd\DeleteDeadLetterJobCmd.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class SecurityConfig extends WebSecurityConfigurerAdapter {
/**
* 数据源 DataSource
*/
@Autowired
private DataSource dataSource;
@Override
@Bean(name = BeanIds.AUTHENTICATION_MANAGER)
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Bean
public static NoOpPasswordEncoder passwordEncoder() {
return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
} | @Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication()
.dataSource(dataSource);
}
// @Override
// protected void configure(HttpSecurity http) throws Exception {
// http
// .authorizeRequests()
// .antMatchers("/oauth/**").permitAll() // 允许无权限访问
// .anyRequest().authenticated()
// .and()
// .formLogin().and()
// .httpBasic();
// }
} | repos\SpringBoot-Labs-master\lab-68-spring-security-oauth\lab-68-demo21-authorization-server-on-sso\src\main\java\cn\iocoder\springboot\lab68\authorizationserverdemo\config\SecurityConfig.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void addToFavorite(@RequestBody @NonNull final JsonAddProductsToFavoriteRequest request)
{
final User user = loginService.getLoggedInUser();
for (final String productIdStr : request.getProductIds())
{
final Product product = productSuppliesService.getProductById(Long.parseLong(productIdStr));
productSuppliesService.addUserFavoriteProduct(user, product);
}
}
@PostMapping("/favorite/remove")
public void removeFromFavorite(@RequestBody @NonNull final JsonRemoveProductsFromFavoriteRequest request)
{
final User user = loginService.getLoggedInUser();
for (final String productIdStr : request.getProductIds())
{
final Product product = productSuppliesService.getProductById(Long.parseLong(productIdStr));
productSuppliesService.removeUserFavoriteProduct(user, product);
}
}
@GetMapping("/notFavorite")
public JsonProductToAddResponse getProductsNotFavorite()
{
final User user = loginService.getLoggedInUser();
final List<Product> productsContracted = contractsService.getContracts(user.getBpartner()).getProducts();
final List<Product> productsFavorite = productSuppliesService.getUserFavoriteProducts(user);
final List<Product> productsShared = productSuppliesService.getAllSharedProducts();
final ArrayList<Product> productsNotSelected = new ArrayList<>(productsContracted);
productsNotSelected.removeAll(productsFavorite); | final ArrayList<Product> productsNotContracted = new ArrayList<>(productsShared);
productsNotContracted.removeAll(productsFavorite);
productsNotContracted.removeAll(productsContracted);
final Locale locale = loginService.getLocale();
return JsonProductToAddResponse.builder()
.products(toJsonProductOrderedList(productsNotSelected, locale))
.moreProducts(toJsonProductOrderedList(productsNotContracted, locale))
.build();
}
private static ArrayList<JsonProduct> toJsonProductOrderedList(@NonNull final List<Product> products, @NonNull final Locale locale)
{
return products.stream()
.map(product -> toJsonProduct(product, locale))
.sorted(Comparator.comparing(JsonProduct::getProductName))
.collect(Collectors.toCollection(ArrayList::new));
}
private static JsonProduct toJsonProduct(@NonNull final Product product, @NonNull final Locale locale)
{
return JsonProduct.builder()
.productId(product.getIdAsString())
.productName(product.getName(locale))
.packingInfo(product.getPackingInfo(locale))
.build();
}
} | repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\rest\products\ProductsRestController.java | 2 |
请完成以下Java代码 | public Object get(int i, Scriptable scriptable) {
return null;
}
@Override
public boolean has(String s, Scriptable scriptable) {
return variableContainer.hasVariable(s);
}
@Override
public boolean has(int i, Scriptable scriptable) {
return false;
}
@Override
public void put(String s, Scriptable scriptable, Object o) {
}
@Override
public void put(int i, Scriptable scriptable, Object o) {
}
@Override
public void delete(String s) {
}
@Override
public void delete(int i) {
}
@Override
public Scriptable getPrototype() {
return null;
}
@Override
public void setPrototype(Scriptable scriptable) { | }
@Override
public Scriptable getParentScope() {
return null;
}
@Override
public void setParentScope(Scriptable scriptable) {
}
@Override
public Object[] getIds() {
return null;
}
@Override
public Object getDefaultValue(Class<?> aClass) {
return null;
}
@Override
public boolean hasInstance(Scriptable scriptable) {
return false;
}
} | repos\flowable-engine-main\modules\flowable-secure-javascript\src\main\java\org\flowable\scripting\secure\impl\SecureScriptScope.java | 1 |
请完成以下Java代码 | public void onValueChanged0(final IAttributeValueContext attributeValueContext_IGNORED,
final IAttributeSet attributeSet,
final I_M_Attribute attribute_IGNORED,
final Object valueOld_IGNORED,
final Object valueNew_IGNORED)
{
recalculateWeightNet(attributeSet);
}
/**
* Returns the summed weight of the packing material of the given <code>attributeSet</code>'s HU.
* <p>
* NOTE: does <b>not</b> descent into sub-HUs to also add their tare values. This is good, because this value is used in bottom-up-propagation, i.e. the children tare values are added during
* propagation.
*/
@Override
public Object generateSeedValue(final IAttributeSet attributeSet, final I_M_Attribute attribute, final Object valueInitialDefault)
{
// we don't support a value different from null
Check.assumeNull(valueInitialDefault, "valueInitialDefault null");
return BigDecimal.ZERO;
}
@Override
public String getAttributeValueType()
{
return X_M_Attribute.ATTRIBUTEVALUETYPE_Number;
}
@Override
public boolean canGenerateValue(final Properties ctx, final IAttributeSet attributeSet, final I_M_Attribute attribute)
{
return true; | }
@Override
public BigDecimal generateNumericValue(final Properties ctx, final IAttributeSet attributeSet, final I_M_Attribute attribute)
{
return BigDecimal.ZERO;
}
@Override
protected boolean isExecuteCallout(final IAttributeValueContext attributeValueContext,
final IAttributeSet attributeSet,
final I_M_Attribute attribute,
final Object valueOld,
final Object valueNew)
{
return !Objects.equals(valueOld, valueNew);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\org\adempiere\mm\attributes\spi\impl\WeightTareAdjustAttributeValueCallout.java | 1 |
请完成以下Java代码 | private void assertReadWrite()
{
if (readOnly)
{
throw new AdempiereException("Changing readonly instance is not allowed: " + this);
}
}
void setId(@NonNull final DataEntryRecordId id)
{
this.id = Optional.of(id);
}
/**
* @return {@code true} if the given value is different from the previous one.
*/
public boolean setRecordField(
@NonNull final DataEntryFieldId dataEntryFieldId,
@NonNull final UserId updatedBy,
@Nullable final Object value)
{
assertReadWrite();
final DataEntryRecordField<?> previousFieldVersion = fields.get(dataEntryFieldId);
final Object previousValue = previousFieldVersion == null ? null : previousFieldVersion.getValue();
final boolean valueChanged = !Objects.equals(previousValue, value);
if (!valueChanged)
{
return false;
}
final ZonedDateTime updated = ZonedDateTime.now();
final CreatedUpdatedInfo createdUpdatedInfo;
if (previousFieldVersion == null)
{
createdUpdatedInfo = CreatedUpdatedInfo.createNew(updatedBy, updated);
}
else
{
createdUpdatedInfo = previousFieldVersion.getCreatedUpdatedInfo().updated(updatedBy, updated);
}
final DataEntryRecordField<?> dataEntryRecordField = value != null
? DataEntryRecordField.createDataEntryRecordField(dataEntryFieldId, createdUpdatedInfo, value)
: DataEntryRecordFieldString.of(dataEntryFieldId, createdUpdatedInfo, null);
fields.put(dataEntryFieldId, dataEntryRecordField);
return true;
}
public boolean isEmpty()
{
return fields.isEmpty();
}
public ImmutableList<DataEntryRecordField<?>> getFields()
{
return ImmutableList.copyOf(fields.values());
}
public Optional<ZonedDateTime> getCreatedValue(@NonNull final DataEntryFieldId fieldId)
{
return getCreatedUpdatedInfo(fieldId)
.map(CreatedUpdatedInfo::getCreated);
} | public Optional<UserId> getCreatedByValue(@NonNull final DataEntryFieldId fieldId)
{
return getCreatedUpdatedInfo(fieldId)
.map(CreatedUpdatedInfo::getCreatedBy);
}
public Optional<ZonedDateTime> getUpdatedValue(@NonNull final DataEntryFieldId fieldId)
{
return getCreatedUpdatedInfo(fieldId)
.map(CreatedUpdatedInfo::getUpdated);
}
public Optional<UserId> getUpdatedByValue(@NonNull final DataEntryFieldId fieldId)
{
return getCreatedUpdatedInfo(fieldId)
.map(CreatedUpdatedInfo::getUpdatedBy);
}
public Optional<CreatedUpdatedInfo> getCreatedUpdatedInfo(@NonNull final DataEntryFieldId fieldId)
{
return getOptional(fieldId)
.map(DataEntryRecordField::getCreatedUpdatedInfo);
}
public Optional<Object> getFieldValue(@NonNull final DataEntryFieldId fieldId)
{
return getOptional(fieldId)
.map(DataEntryRecordField::getValue);
}
private Optional<DataEntryRecordField<?>> getOptional(@NonNull final DataEntryFieldId fieldId)
{
return Optional.ofNullable(fields.get(fieldId));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\dataentry\data\DataEntryRecord.java | 1 |
请完成以下Java代码 | public void setMail(String email) {
((InetOrgPerson) this.instance).mail = email;
}
public void setUid(String uid) {
((InetOrgPerson) this.instance).uid = uid;
if (this.instance.getUsername() == null) {
setUsername(uid);
}
}
public void setInitials(String initials) {
((InetOrgPerson) this.instance).initials = initials;
}
public void setO(String organization) {
((InetOrgPerson) this.instance).o = organization;
}
public void setOu(String ou) {
((InetOrgPerson) this.instance).ou = ou;
}
public void setRoomNumber(String no) {
((InetOrgPerson) this.instance).roomNumber = no;
}
public void setTitle(String title) {
((InetOrgPerson) this.instance).title = title;
}
public void setCarLicense(String carLicense) {
((InetOrgPerson) this.instance).carLicense = carLicense;
}
public void setDepartmentNumber(String departmentNumber) {
((InetOrgPerson) this.instance).departmentNumber = departmentNumber;
}
public void setDisplayName(String displayName) {
((InetOrgPerson) this.instance).displayName = displayName;
}
public void setEmployeeNumber(String no) {
((InetOrgPerson) this.instance).employeeNumber = no; | }
public void setDestinationIndicator(String destination) {
((InetOrgPerson) this.instance).destinationIndicator = destination;
}
public void setHomePhone(String homePhone) {
((InetOrgPerson) this.instance).homePhone = homePhone;
}
public void setStreet(String street) {
((InetOrgPerson) this.instance).street = street;
}
public void setPostalCode(String postalCode) {
((InetOrgPerson) this.instance).postalCode = postalCode;
}
public void setPostalAddress(String postalAddress) {
((InetOrgPerson) this.instance).postalAddress = postalAddress;
}
public void setMobile(String mobile) {
((InetOrgPerson) this.instance).mobile = mobile;
}
public void setHomePostalAddress(String homePostalAddress) {
((InetOrgPerson) this.instance).homePostalAddress = homePostalAddress;
}
}
} | repos\spring-security-main\ldap\src\main\java\org\springframework\security\ldap\userdetails\InetOrgPerson.java | 1 |
请完成以下Java代码 | static PGPPublicKey readPublicKey(InputStream input) throws IOException, PGPException {
PGPPublicKeyRingCollection pgpPub = new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(input), new JcaKeyFingerprintCalculator());
Iterator keyRingIter = pgpPub.getKeyRings();
while (keyRingIter.hasNext()) {
PGPPublicKeyRing keyRing = (PGPPublicKeyRing) keyRingIter.next();
Iterator keyIter = keyRing.getPublicKeys();
while (keyIter.hasNext()) {
PGPPublicKey key = (PGPPublicKey) keyIter.next();
if (key.isEncryptionKey()) {
return key;
}
}
}
throw new IllegalArgumentException("Can't find encryption key in key ring.");
}
static PGPSecretKey readSecretKey(String fileName) throws IOException, PGPException {
InputStream keyIn = new BufferedInputStream(new FileInputStream(fileName));
PGPSecretKey secKey = readSecretKey(keyIn);
keyIn.close();
return secKey;
}
/**
* A simple method that opens a key ring file and loads the first available key
* suitable for signature generation.
*
* @param input stream to read the secret key ring collection from.
* @return a secret key.
* @throws IOException on a problem with using the input stream. | * @throws PGPException if there is an issue parsing the input stream.
*/
static PGPSecretKey readSecretKey(InputStream input) throws IOException, PGPException {
PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(input), new JcaKeyFingerprintCalculator());
Iterator keyRingIter = pgpSec.getKeyRings();
while (keyRingIter.hasNext()) {
PGPSecretKeyRing keyRing = (PGPSecretKeyRing) keyRingIter.next();
Iterator keyIter = keyRing.getSecretKeys();
while (keyIter.hasNext()) {
PGPSecretKey key = (PGPSecretKey) keyIter.next();
if (key.isSigningKey()) {
return key;
}
}
}
throw new IllegalArgumentException("Can't find signing key in key ring.");
}
} | repos\tutorials-master\libraries-security\src\main\java\com\baeldung\bouncycastle\pgp\PGPExampleUtil.java | 1 |
请完成以下Java代码 | public int getAsyncExecutorResetExpiredJobsInterval() {
return asyncExecutorResetExpiredJobsInterval;
}
public ProcessEngineConfigurationImpl setAsyncExecutorResetExpiredJobsInterval(
int asyncExecutorResetExpiredJobsInterval
) {
this.asyncExecutorResetExpiredJobsInterval = asyncExecutorResetExpiredJobsInterval;
return this;
}
public ExecuteAsyncRunnableFactory getAsyncExecutorExecuteAsyncRunnableFactory() {
return asyncExecutorExecuteAsyncRunnableFactory;
}
public ProcessEngineConfigurationImpl setAsyncExecutorExecuteAsyncRunnableFactory(
ExecuteAsyncRunnableFactory asyncExecutorExecuteAsyncRunnableFactory
) {
this.asyncExecutorExecuteAsyncRunnableFactory = asyncExecutorExecuteAsyncRunnableFactory;
return this;
}
public int getAsyncExecutorResetExpiredJobsPageSize() {
return asyncExecutorResetExpiredJobsPageSize;
}
public ProcessEngineConfigurationImpl setAsyncExecutorResetExpiredJobsPageSize(
int asyncExecutorResetExpiredJobsPageSize
) {
this.asyncExecutorResetExpiredJobsPageSize = asyncExecutorResetExpiredJobsPageSize;
return this;
}
public boolean isAsyncExecutorIsMessageQueueMode() {
return asyncExecutorMessageQueueMode;
} | public ProcessEngineConfigurationImpl setAsyncExecutorMessageQueueMode(boolean asyncExecutorMessageQueueMode) {
this.asyncExecutorMessageQueueMode = asyncExecutorMessageQueueMode;
return this;
}
public boolean isRollbackDeployment() {
return isRollbackDeployment;
}
public void setRollbackDeployment(boolean rollbackDeployment) {
isRollbackDeployment = rollbackDeployment;
}
public EventSubscriptionPayloadMappingProvider getEventSubscriptionPayloadMappingProvider() {
return eventSubscriptionPayloadMappingProvider;
}
public void setEventSubscriptionPayloadMappingProvider(
EventSubscriptionPayloadMappingProvider eventSubscriptionPayloadMappingProvider
) {
this.eventSubscriptionPayloadMappingProvider = eventSubscriptionPayloadMappingProvider;
}
public ProcessDefinitionHelper getProcessDefinitionHelper() {
return processDefinitionHelper;
}
public ProcessEngineConfigurationImpl setProcessDefinitionHelper(ProcessDefinitionHelper processDefinitionHelper) {
this.processDefinitionHelper = processDefinitionHelper;
return this;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cfg\ProcessEngineConfigurationImpl.java | 1 |
请完成以下Java代码 | public class AllergensAsEmbeddable {
@Column(name = "peanuts", table = "allergens")
private boolean peanuts;
@Column(name = "celery", table = "allergens")
private boolean celery;
@Column(name = "sesame_seeds", table = "allergens")
private boolean sesameSeeds;
public boolean isPeanuts() {
return peanuts;
}
public void setPeanuts(boolean peanuts) {
this.peanuts = peanuts;
}
public boolean isCelery() {
return celery;
}
public void setCelery(boolean celery) {
this.celery = celery;
} | public boolean isSesameSeeds() {
return sesameSeeds;
}
public void setSesameSeeds(boolean sesameSeeds) {
this.sesameSeeds = sesameSeeds;
}
@Override
public String toString() {
return "AllergensAsEmbeddable [peanuts=" + peanuts + ", celery=" + celery + ", sesameSeeds=" + sesameSeeds + "]";
}
} | repos\tutorials-master\persistence-modules\java-jpa-2\src\main\java\com\baeldung\jpa\multipletables\secondarytable\embeddable\AllergensAsEmbeddable.java | 1 |
请完成以下Java代码 | public int getSpeed() {
return speed;
}
public void setSpeed(int speed) {
this.speed = speed;
}
public int increaseSpeed(int increment) {
if (increment > 0) {
this.speed += increment;
} else {
System.out.println("Increment can't be negative.");
}
return this.speed;
}
public int decreaseSpeed(int decrement) {
if (decrement > 0 && decrement <= this.speed) {
this.speed -= decrement; | } else {
System.out.println("Decrement can't be negative or greater than current speed.");
}
return this.speed;
}
public void openDoors() {
// process to open the doors
}
@Override
public void honk() {
// produces car-specific honk
}
} | repos\tutorials-master\core-java-modules\core-java-lang-oop-others\src\main\java\com\baeldung\oop\Car.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ShoppingCart implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String owner;
// LAZY is default
@ElementCollection(fetch = FetchType.LAZY)
@CollectionTable(name = "shopping_cart_books",
joinColumns = @JoinColumn(name = "shopping_cart_id"))
private List<Book> books = new ArrayList<>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
} | public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public List<Book> getBooks() {
return books;
}
public void setBooks(List<Book> books) {
this.books = books;
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootDtoElementCollection\src\main\java\com\bookstore\entity\ShoppingCart.java | 2 |
请完成以下Java代码 | public class User {
private Integer id;
private String name;
private Date dob;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
} | public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
} | repos\tutorials-master\gradle-modules\gradle-7\multiple-repositories-demo\publish-package\src\main\java\com\baeldung\gradle\publish_package\User.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private void applyKafkaConnectionDetailsForProducer(Map<String, Object> properties,
KafkaConnectionDetails connectionDetails) {
Configuration producer = connectionDetails.getProducer();
properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, producer.getBootstrapServers());
applySecurityProtocol(properties, producer.getSecurityProtocol());
applySslBundle(properties, producer.getSslBundle());
}
private void applyKafkaConnectionDetailsForAdmin(Map<String, Object> properties,
KafkaConnectionDetails connectionDetails) {
Configuration admin = connectionDetails.getAdmin();
properties.put(CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG, admin.getBootstrapServers());
applySecurityProtocol(properties, admin.getSecurityProtocol());
applySslBundle(properties, admin.getSslBundle());
}
static BackOff getBackOff(Backoff retryTopicBackoff) {
PropertyMapper map = PropertyMapper.get();
RetryPolicy.Builder builder = RetryPolicy.builder().maxRetries(Long.MAX_VALUE);
map.from(retryTopicBackoff.getDelay()).to(builder::delay);
map.from(retryTopicBackoff.getMaxDelay()).when(Predicate.not(Duration::isZero)).to(builder::maxDelay);
map.from(retryTopicBackoff.getMultiplier()).to(builder::multiplier);
map.from(retryTopicBackoff.getJitter()).when((Predicate.not(Duration::isZero))).to(builder::jitter);
return builder.build().getBackOff();
}
static void applySslBundle(Map<String, Object> properties, @Nullable SslBundle sslBundle) {
if (sslBundle != null) {
properties.put(SslConfigs.SSL_ENGINE_FACTORY_CLASS_CONFIG, SslBundleSslEngineFactory.class);
properties.put(SslBundle.class.getName(), sslBundle);
}
} | static void applySecurityProtocol(Map<String, Object> properties, @Nullable String securityProtocol) {
if (StringUtils.hasLength(securityProtocol)) {
properties.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, securityProtocol);
}
}
static class KafkaRuntimeHints implements RuntimeHintsRegistrar {
@Override
public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) {
hints.reflection().registerType(SslBundleSslEngineFactory.class, MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS);
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-kafka\src\main\java\org\springframework\boot\kafka\autoconfigure\KafkaAutoConfiguration.java | 2 |
请完成以下Java代码 | public Criteria andMemberLevelNameNotIn(List<String> values) {
addCriterion("member_level_name not in", values, "memberLevelName");
return (Criteria) this;
}
public Criteria andMemberLevelNameBetween(String value1, String value2) {
addCriterion("member_level_name between", value1, value2, "memberLevelName");
return (Criteria) this;
}
public Criteria andMemberLevelNameNotBetween(String value1, String value2) {
addCriterion("member_level_name not between", value1, value2, "memberLevelName");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue; | }
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsMemberPriceExample.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public MessageInstance sendMessage(MessageInstance message, ConcurrentMap<QName, URL> overridenEndpointAddresses)
throws Exception {
return this.implementation.sendFor(message, this, overridenEndpointAddresses);
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public BpmnInterface getInterface() {
return bpmnInterface;
}
public void setInterface(BpmnInterface bpmnInterface) {
this.bpmnInterface = bpmnInterface;
}
public MessageDefinition getInMessage() {
return inMessage;
}
public void setInMessage(MessageDefinition inMessage) { | this.inMessage = inMessage;
}
public MessageDefinition getOutMessage() {
return outMessage;
}
public void setOutMessage(MessageDefinition outMessage) {
this.outMessage = outMessage;
}
public OperationImplementation getImplementation() {
return implementation;
}
public void setImplementation(OperationImplementation implementation) {
this.implementation = implementation;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\webservice\Operation.java | 2 |
请完成以下Java代码 | public String getExtensionId() {
return extensionId;
}
public void setExtensionId(String extensionId) {
this.extensionId = extensionId;
}
public boolean isExtended() {
return extensionId != null && !extensionId.isEmpty();
}
public String getSkipExpression() {
return skipExpression;
}
public void setSkipExpression(String skipExpression) {
this.skipExpression = skipExpression;
}
public boolean hasBoundaryErrorEvents() {
if (this.boundaryEvents != null && !this.boundaryEvents.isEmpty()) {
return this.boundaryEvents.stream().anyMatch(boundaryEvent -> boundaryEvent.hasErrorEventDefinition());
}
return false;
}
public ServiceTask clone() {
ServiceTask clone = new ServiceTask();
clone.setValues(this);
return clone;
}
public void setValues(ServiceTask otherElement) {
super.setValues(otherElement);
setImplementation(otherElement.getImplementation());
setImplementationType(otherElement.getImplementationType()); | setResultVariableName(otherElement.getResultVariableName());
setType(otherElement.getType());
setOperationRef(otherElement.getOperationRef());
setExtensionId(otherElement.getExtensionId());
setSkipExpression(otherElement.getSkipExpression());
fieldExtensions = new ArrayList<FieldExtension>();
if (otherElement.getFieldExtensions() != null && !otherElement.getFieldExtensions().isEmpty()) {
for (FieldExtension extension : otherElement.getFieldExtensions()) {
fieldExtensions.add(extension.clone());
}
}
customProperties = new ArrayList<CustomProperty>();
if (otherElement.getCustomProperties() != null && !otherElement.getCustomProperties().isEmpty()) {
for (CustomProperty property : otherElement.getCustomProperties()) {
customProperties.add(property.clone());
}
}
}
} | repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\ServiceTask.java | 1 |
请完成以下Java代码 | public class ConfigurationPropertiesBindingPostProcessor
implements BeanPostProcessor, PriorityOrdered, ApplicationContextAware, InitializingBean {
/**
* The bean name that this post-processor is registered with.
*/
public static final String BEAN_NAME = ConfigurationPropertiesBindingPostProcessor.class.getName();
@SuppressWarnings("NullAway.Init")
private ApplicationContext applicationContext;
@SuppressWarnings("NullAway.Init")
private BeanDefinitionRegistry registry;
@SuppressWarnings("NullAway.Init")
private ConfigurationPropertiesBinder binder;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
@Override
public void afterPropertiesSet() throws Exception {
// We can't use constructor injection of the application context because
// it causes eager factory bean initialization
this.registry = (BeanDefinitionRegistry) this.applicationContext.getAutowireCapableBeanFactory();
this.binder = ConfigurationPropertiesBinder.get(this.applicationContext);
}
@Override
public int getOrder() {
return Ordered.HIGHEST_PRECEDENCE + 1;
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (!hasBoundValueObject(beanName)) {
bind(ConfigurationPropertiesBean.get(this.applicationContext, bean, beanName));
}
return bean;
} | private boolean hasBoundValueObject(String beanName) {
return BindMethod.VALUE_OBJECT.equals(BindMethodAttribute.get(this.registry, beanName));
}
private void bind(@Nullable ConfigurationPropertiesBean bean) {
if (bean == null) {
return;
}
Assert.state(bean.asBindTarget().getBindMethod() != BindMethod.VALUE_OBJECT,
"Cannot bind @ConfigurationProperties for bean '" + bean.getName()
+ "'. Ensure that @ConstructorBinding has not been applied to regular bean");
try {
this.binder.bind(bean);
}
catch (Exception ex) {
throw new ConfigurationPropertiesBindException(bean, ex);
}
}
/**
* Register a {@link ConfigurationPropertiesBindingPostProcessor} bean if one is not
* already registered.
* @param registry the bean definition registry
* @since 2.2.0
*/
public static void register(BeanDefinitionRegistry registry) {
Assert.notNull(registry, "'registry' must not be null");
if (!registry.containsBeanDefinition(BEAN_NAME)) {
BeanDefinition definition = BeanDefinitionBuilder
.rootBeanDefinition(ConfigurationPropertiesBindingPostProcessor.class)
.getBeanDefinition();
definition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
registry.registerBeanDefinition(BEAN_NAME, definition);
}
ConfigurationPropertiesBinder.register(registry);
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\properties\ConfigurationPropertiesBindingPostProcessor.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 Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
} | repos\spring-boot-student-master\spring-boot-student-mybatis-druid\src\main\java\com\xiaolyuh\domain\model\Person.java | 1 |
请完成以下Java代码 | public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public String getExceptionType() {
return exceptionType;
}
public void setExceptionType(String exceptionType) {
this.exceptionType = exceptionType;
} | public String getJwt() {
return jwt;
}
public void setJwt(String jwt) {
this.jwt = jwt;
}
public Jws<Claims> getJws() {
return jws;
}
public void setJws(Jws<Claims> jws) {
this.jws = jws;
}
} | repos\tutorials-master\security-modules\jjwt\src\main\java\io\jsonwebtoken\jjwtfun\model\JwtResponse.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.