instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请完成以下Java代码
|
public Long convert(final Object value)
{
return value == null ? 0 : ((java.util.Date)value).getTime();
}
};
/** Skip caching predicate: skip if argument is NOT null */
private static final Predicate<Object> SkipCaching_IfNotNull = value -> value != null;
private static final GenericParamDescriptor[] cache = new GenericParamDescriptor[] {
new GenericParamDescriptor(0)
, new GenericParamDescriptor(1)
, new GenericParamDescriptor(2)
, new GenericParamDescriptor(3)
, new GenericParamDescriptor(4)
, new GenericParamDescriptor(5)
, new GenericParamDescriptor(6)
, new GenericParamDescriptor(7)
, new GenericParamDescriptor(8)
, new GenericParamDescriptor(9)
, new GenericParamDescriptor(10)
};
private final int parameterIndex;
private final Converter<Object, Object> argumentConverter;
private final Predicate<Object> skipCachingPredicate;
private GenericParamDescriptor(final int parameterIndex)
{
this(parameterIndex, null, null); // converter = null, skipCachingPredicate = null;
}
private GenericParamDescriptor(final int parameterIndex, final Converter<Object, Object> argumentConverter, final Predicate<Object> skipCachingPredicate)
{
Check.assume(parameterIndex >= 0, "parameterIndex >= 0");
|
this.parameterIndex = parameterIndex;
this.argumentConverter = argumentConverter;
this.skipCachingPredicate = skipCachingPredicate;
}
@Override
public String toString()
{
return ObjectUtils.toString(this);
}
@Override
public void extractKeyParts(final CacheKeyBuilder keyBuilder, final Object targetObject, final Object[] params)
{
final Object param = params[parameterIndex];
//
// Check if we shall skip caching
if (skipCachingPredicate != null && skipCachingPredicate.test(param))
{
keyBuilder.setSkipCaching();
return;
}
//
// Convert argument if needed
final Object paramConverted = argumentConverter == null ? param : argumentConverter.convert(param);
// Add parameter to cache key builder
keyBuilder.add(paramConverted);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\interceptor\GenericParamDescriptor.java
| 1
|
请完成以下Java代码
|
protected Val spinXmlToVal(SpinXmlElement element, Function<Object, Val> innerValueMapper) {
String name = nodeName(element);
Val value = spinXmlElementToVal(element, innerValueMapper);
Map<String, Object> map = Collections.singletonMap(name, value);
return innerValueMapper.apply(map);
}
protected Val spinXmlElementToVal(final SpinXmlElement e,
Function<Object, Val> innerValueMapper) {
Map<String, Object> membersMap = new HashMap<>();
String content = e.textContent().trim();
if (!content.isEmpty()) {
membersMap.put("$content", new ValString(content));
}
Map<String, ValString> attributes = e.attrs()
.stream()
.collect(toMap(this::spinXmlAttributeToKey, attr -> new ValString(attr.value())));
if (!attributes.isEmpty()) {
membersMap.putAll(attributes);
}
Map<String, Val> childrenMap = e.childElements().stream()
.collect(
groupingBy(
this::nodeName,
mapping(el -> spinXmlElementToVal(el, innerValueMapper), toList())
))
.entrySet().stream()
.collect(toMap(Map.Entry::getKey, entry -> {
List<Val> valList = entry.getValue();
if (!valList.isEmpty() && valList.size() > 1) {
return innerValueMapper.apply(valList);
} else {
return valList.get(0);
|
}
}));
membersMap.putAll(childrenMap);
if (membersMap.isEmpty()) {
return innerValueMapper.apply(null);
} else {
return innerValueMapper.apply(membersMap);
}
}
protected String spinXmlAttributeToKey(SpinXmlAttribute attribute) {
return "@" + nodeName(attribute);
}
protected String nodeName(SpinXmlNode n) {
String prefix = n.prefix();
String name = n.name();
return (prefix != null && !prefix.isEmpty())? prefix + "$" + name : name;
}
}
|
repos\camunda-bpm-platform-master\engine-plugins\spin-plugin\src\main\java\org\camunda\spin\plugin\impl\feel\integration\SpinValueMapper.java
| 1
|
请完成以下Java代码
|
public class EntitiesFieldsAsyncLoader {
public static ListenableFuture<EntityFieldsData> findAsync(TbContext ctx, EntityId originatorId) {
switch (originatorId.getEntityType()) { // TODO: use EntityServiceRegistry
case TENANT:
return toEntityFieldsDataAsync(ctx.getTenantService().findTenantByIdAsync(ctx.getTenantId(), (TenantId) originatorId),
EntityFieldsData::new, ctx);
case CUSTOMER:
return toEntityFieldsDataAsync(ctx.getCustomerService().findCustomerByIdAsync(ctx.getTenantId(), (CustomerId) originatorId),
EntityFieldsData::new, ctx);
case USER:
return toEntityFieldsDataAsync(ctx.getUserService().findUserByIdAsync(ctx.getTenantId(), (UserId) originatorId),
EntityFieldsData::new, ctx);
case ASSET:
return toEntityFieldsDataAsync(ctx.getAssetService().findAssetByIdAsync(ctx.getTenantId(), (AssetId) originatorId),
EntityFieldsData::new, ctx);
case DEVICE:
return toEntityFieldsDataAsync(Futures.immediateFuture(ctx.getDeviceService().findDeviceById(ctx.getTenantId(), (DeviceId) originatorId)),
EntityFieldsData::new, ctx);
case ALARM:
return toEntityFieldsDataAsync(ctx.getAlarmService().findAlarmByIdAsync(ctx.getTenantId(), (AlarmId) originatorId),
EntityFieldsData::new, ctx);
case RULE_CHAIN:
|
return toEntityFieldsDataAsync(ctx.getRuleChainService().findRuleChainByIdAsync(ctx.getTenantId(), (RuleChainId) originatorId),
EntityFieldsData::new, ctx);
case ENTITY_VIEW:
return toEntityFieldsDataAsync(ctx.getEntityViewService().findEntityViewByIdAsync(ctx.getTenantId(), (EntityViewId) originatorId),
EntityFieldsData::new, ctx);
case EDGE:
return toEntityFieldsDataAsync(ctx.getEdgeService().findEdgeByIdAsync(ctx.getTenantId(), (EdgeId) originatorId),
EntityFieldsData::new, ctx);
default:
return Futures.immediateFailedFuture(new TbNodeException("Unexpected originator EntityType: " + originatorId.getEntityType()));
}
}
private static <T extends BaseData<? extends UUIDBased>> ListenableFuture<EntityFieldsData> toEntityFieldsDataAsync(
ListenableFuture<T> future,
Function<T, EntityFieldsData> converter,
TbContext ctx
) {
return Futures.transformAsync(future, in -> in != null ?
Futures.immediateFuture(converter.apply(in))
: Futures.immediateFailedFuture(new NoSuchElementException("Entity not found!")), ctx.getDbCallbackExecutor());
}
}
|
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\util\EntitiesFieldsAsyncLoader.java
| 1
|
请完成以下Java代码
|
public int zeroId()
{
return 0;
}
@Override
public int[] toIdList(String key)
{
byte[] bytes = key.getBytes(UTF_8);
int[] res = new int[bytes.length];
for (int i = 0; i < res.length; i++)
{
res[i] = bytes[i] & 0xFF; // unsigned byte
}
if ((res.length == 1) && (res[0] == 0))
{
return EMPTYLIST;
}
return res;
}
/**
* codes ported from iconv lib in utf8.h utf8_codepointtomb
*/
@Override
public int[] toIdList(int codePoint)
{
int count;
if (codePoint < 0x80)
count = 1;
else if (codePoint < 0x800)
count = 2;
else if (codePoint < 0x10000)
count = 3;
else if (codePoint < 0x200000)
count = 4;
else if (codePoint < 0x4000000)
count = 5;
else if (codePoint <= 0x7fffffff)
count = 6;
else
return EMPTYLIST;
int[] r = new int[count];
switch (count)
{ /* note: code falls through cases! */
case 6:
r[5] = (char) (0x80 | (codePoint & 0x3f));
|
codePoint = codePoint >> 6;
codePoint |= 0x4000000;
case 5:
r[4] = (char) (0x80 | (codePoint & 0x3f));
codePoint = codePoint >> 6;
codePoint |= 0x200000;
case 4:
r[3] = (char) (0x80 | (codePoint & 0x3f));
codePoint = codePoint >> 6;
codePoint |= 0x10000;
case 3:
r[2] = (char) (0x80 | (codePoint & 0x3f));
codePoint = codePoint >> 6;
codePoint |= 0x800;
case 2:
r[1] = (char) (0x80 | (codePoint & 0x3f));
codePoint = codePoint >> 6;
codePoint |= 0xc0;
case 1:
r[0] = (char) codePoint;
}
return r;
}
@Override
public String toString(int[] ids)
{
byte[] bytes = new byte[ids.length];
for (int i = 0; i < ids.length; i++)
{
bytes[i] = (byte) ids[i];
}
try
{
return new String(bytes, "UTF-8");
}
catch (UnsupportedEncodingException e)
{
return null;
}
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\trie\datrie\Utf8CharacterMapping.java
| 1
|
请完成以下Java代码
|
private Window getWindow()
{
return window;
}
}
class Loader implements Runnable {
private JDialog dialog;
Loader(JDialog d) {
dialog = d;
}
@Override
public void run() {
Window[] w = windowManager.getWindows();
Container dialogContent = dialog.getContentPane();
dialogContent.setLayout(new BorderLayout());
final CardLayout card = new CardLayout();
final JXPanel cardContainer = new JXPanel(card);
dialogContent.add(cardContainer, BorderLayout.CENTER);
JXPanel p = createSelectionPanel();
cardContainer.add(p, "page1");
Dimension s = Toolkit.getDefaultToolkit().getScreenSize();
int width = ( s.width - 30 ) / 3;
int height = ( s.height - 30 ) / 3;
int count = 0;
JFrame frame = Env.getWindow(0);
if (frame != null && frame instanceof AMenu) {
JXTitledPanel box = createImageBox(p, dialog, width, height,
frame);
p.add(box);
count ++;
firstBox = box;
}
int page = 1;
for(int i = 0; i < w.length; i++) {
count ++;
Window window = w[i];
JXTitledPanel box = createImageBox(p, dialog, width, height,
window);
p.add(box);
if (i == 0 && firstBox == null) firstBox = box;
if ( count == 9) {
count = 0;
page++;
p = createSelectionPanel();
cardContainer.add(p, "page" + page);
}
}
for ( int i = count; i < 9; i++ ) {
p.add(Box.createGlue());
}
dialog.addWindowFocusListener(new WindowFocusListener() {
@Override
public void windowGainedFocus(WindowEvent e) {
if (firstBox != null)
firstBox.requestFocus();
}
@Override
public void windowLostFocus(WindowEvent e) {
}
});
card.first(cardContainer);
|
if (page > 1) {
JXPanel ctrl = new JXPanel();
JXButton previous = new JXButton("<");
JXButton next = new JXButton(">");
previous.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
card.previous(cardContainer);
}
});
next.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
card.next(cardContainer);
}
});
ctrl.add(previous);
ctrl.add(next);
dialogContent.add(ctrl, BorderLayout.NORTH);
}
dialog.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
}
class PreviewMouseAdapter extends MouseAdapter {
private JDialog dialog;
private Window window;
PreviewMouseAdapter(JDialog d, Window w) {
dialog = d;
window = w;
}
@Override
public void mouseClicked(MouseEvent e) {
dialog.dispose();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
AEnv.showWindow(window);
}
});
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\WindowMenu.java
| 1
|
请完成以下Java代码
|
public void setAD_NotificationGroup(final org.compiere.model.I_AD_NotificationGroup AD_NotificationGroup)
{
set_ValueFromPO(COLUMNNAME_AD_NotificationGroup_ID, org.compiere.model.I_AD_NotificationGroup.class, AD_NotificationGroup);
}
@Override
public void setAD_NotificationGroup_ID (final int AD_NotificationGroup_ID)
{
if (AD_NotificationGroup_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_NotificationGroup_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_NotificationGroup_ID, AD_NotificationGroup_ID);
}
@Override
public int getAD_NotificationGroup_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_NotificationGroup_ID);
}
|
@Override
public void setAD_User_ID (final int AD_User_ID)
{
if (AD_User_ID < 0)
set_ValueNoCheck (COLUMNNAME_AD_User_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_User_ID, AD_User_ID);
}
@Override
public int getAD_User_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_User_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_NotificationGroup_CC.java
| 1
|
请完成以下Java代码
|
public void setResult (String Result)
{
set_ValueNoCheck (COLUMNNAME_Result, Result);
}
/** Get Result.
@return Result of the action taken
*/
public String getResult ()
{
return (String)get_Value(COLUMNNAME_Result);
}
public I_R_Request getR_Request() throws RuntimeException
{
return (I_R_Request)MTable.get(getCtx(), I_R_Request.Table_Name)
.getPO(getR_Request_ID(), get_TrxName()); }
/** Set Request.
@param R_Request_ID
Request from a Business Partner or Prospect
*/
public void setR_Request_ID (int R_Request_ID)
{
if (R_Request_ID < 1)
set_ValueNoCheck (COLUMNNAME_R_Request_ID, null);
else
set_ValueNoCheck (COLUMNNAME_R_Request_ID, Integer.valueOf(R_Request_ID));
}
/** Get Request.
@return Request from a Business Partner or Prospect
*/
public int getR_Request_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_Request_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Request Update.
@param R_RequestUpdate_ID
Request Updates
*/
public void setR_RequestUpdate_ID (int R_RequestUpdate_ID)
|
{
if (R_RequestUpdate_ID < 1)
set_ValueNoCheck (COLUMNNAME_R_RequestUpdate_ID, null);
else
set_ValueNoCheck (COLUMNNAME_R_RequestUpdate_ID, Integer.valueOf(R_RequestUpdate_ID));
}
/** Get Request Update.
@return Request Updates
*/
public int getR_RequestUpdate_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_RequestUpdate_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), String.valueOf(getR_RequestUpdate_ID()));
}
/** Set Start Time.
@param StartTime
Time started
*/
public void setStartTime (Timestamp StartTime)
{
set_Value (COLUMNNAME_StartTime, StartTime);
}
/** Get Start Time.
@return Time started
*/
public Timestamp getStartTime ()
{
return (Timestamp)get_Value(COLUMNNAME_StartTime);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_RequestUpdate.java
| 1
|
请完成以下Java代码
|
public BigDecimal getGebuehrenbetrag() {
return gebuehrenbetrag;
}
public void setGebuehrenbetrag(BigDecimal gebuehrenbetrag) {
this.gebuehrenbetrag = gebuehrenbetrag;
}
public String getGebuehrenbetragWaehrung() {
return gebuehrenbetragWaehrung;
}
public void setGebuehrenbetragWaehrung(String gebuehrenbetragWaehrung) {
this.gebuehrenbetragWaehrung = gebuehrenbetragWaehrung;
}
public String getMehrzweckfeld() {
return mehrzweckfeld;
}
public void setMehrzweckfeld(String mehrzweckfeld) {
this.mehrzweckfeld = mehrzweckfeld;
}
public BigInteger getGeschaeftsvorfallCode() {
return geschaeftsvorfallCode;
}
public void setGeschaeftsvorfallCode(BigInteger geschaeftsvorfallCode) {
this.geschaeftsvorfallCode = geschaeftsvorfallCode;
}
public String getBuchungstext() {
return buchungstext;
}
public void setBuchungstext(String buchungstext) {
this.buchungstext = buchungstext;
}
public String getPrimanotennummer() {
return primanotennummer;
}
public void setPrimanotennummer(String primanotennummer) {
this.primanotennummer = primanotennummer;
}
public String getVerwendungszweck() {
return verwendungszweck;
}
public void setVerwendungszweck(String verwendungszweck) {
this.verwendungszweck = verwendungszweck;
}
public String getPartnerBlz() {
return partnerBlz;
}
public void setPartnerBlz(String partnerBlz) {
this.partnerBlz = partnerBlz;
|
}
public String getPartnerKtoNr() {
return partnerKtoNr;
}
public void setPartnerKtoNr(String partnerKtoNr) {
this.partnerKtoNr = partnerKtoNr;
}
public String getPartnerName() {
return partnerName;
}
public void setPartnerName(String partnerName) {
this.partnerName = partnerName;
}
public String getTextschluessel() {
return textschluessel;
}
public void setTextschluessel(String textschluessel) {
this.textschluessel = textschluessel;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\schaeffer\compiere\mt940\BankstatementLine.java
| 1
|
请完成以下Java代码
|
public Text getText() {
return textChild.getChild(this);
}
public void setText(Text text) {
textChild.setChild(this, text);
}
public ImportedValues getImportValues() {
return importedValuesChild.getChild(this);
}
public void setImportValues(ImportedValues importedValues) {
importedValuesChild.setChild(this, importedValues);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(LiteralExpression.class, DMN_ELEMENT_LITERAL_EXPRESSION)
.namespaceUri(LATEST_DMN_NS)
.extendsType(Expression.class)
.instanceProvider(new ModelTypeInstanceProvider<LiteralExpression>() {
public LiteralExpression newInstance(ModelTypeInstanceContext instanceContext) {
return new LiteralExpressionImpl(instanceContext);
}
|
});
expressionLanguageAttribute = typeBuilder.stringAttribute(DMN_ATTRIBUTE_EXPRESSION_LANGUAGE)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
textChild = sequenceBuilder.element(Text.class)
.build();
importedValuesChild = sequenceBuilder.element(ImportedValues.class)
.build();
typeBuilder.build();
}
}
|
repos\camunda-bpm-platform-master\model-api\dmn-model\src\main\java\org\camunda\bpm\model\dmn\impl\instance\LiteralExpressionImpl.java
| 1
|
请完成以下Java代码
|
public static String usingSubstringMethod(String text, int length) {
if (length < 0) {
throw new IllegalArgumentException("length cannot be negative");
}
if (text == null) {
return EMPTY;
}
if (text.length() <= length) {
return text;
} else {
return text.substring(0, length);
}
}
public static String usingSplitMethod(String text, int length) {
if (length < 0) {
throw new IllegalArgumentException("length cannot be negative");
}
if (text == null) {
return EMPTY;
}
String[] results = text.split("(?<=\\G.{" + length + "})");
return results[0];
}
public static String usingPattern(String text, int length) {
if (length < 0) {
throw new IllegalArgumentException("length cannot be negative");
}
if (text == null) {
return EMPTY;
}
Optional<String> result = Pattern.compile(".{1," + length + "}")
.matcher(text)
.results()
.map(MatchResult::group)
.findFirst();
return result.isPresent() ? result.get() : EMPTY;
}
public static String usingCodePointsMethod(String text, int length) {
if (length < 0) {
throw new IllegalArgumentException("length cannot be negative");
}
|
if (text == null) {
return EMPTY;
}
return text.codePoints()
.limit(length)
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
}
public static String usingLeftMethod(String text, int length) {
return StringUtils.left(text, length);
}
public static String usingTruncateMethod(String text, int length) {
return StringUtils.truncate(text, length);
}
public static String usingSplitter(String text, int length) {
if (length < 0) {
throw new IllegalArgumentException("length cannot be negative");
}
if (text == null) {
return EMPTY;
}
Iterable<String> parts = Splitter.fixedLength(length)
.split(text);
return parts.iterator()
.next();
}
}
|
repos\tutorials-master\core-java-modules\core-java-string-operations-11\src\main\java\com\baeldung\truncate\TruncateString.java
| 1
|
请完成以下Java代码
|
public class Prim {
private List<Vertex> graph;
public Prim(List<Vertex> graph){
this.graph = graph;
}
public void run(){
if (graph.size() > 0){
graph.get(0).setVisited(true);
}
while (isDisconnected()){
Edge nextMinimum = new Edge(Integer.MAX_VALUE);
Vertex nextVertex = graph.get(0);
for (Vertex vertex : graph){
if (vertex.isVisited()){
Pair<Vertex, Edge> candidate = vertex.nextMinimum();
if (candidate.getValue().getWeight() < nextMinimum.getWeight()){
nextMinimum = candidate.getValue();
nextVertex = candidate.getKey();
}
}
}
nextMinimum.setIncluded(true);
nextVertex.setVisited(true);
}
}
private boolean isDisconnected(){
for (Vertex vertex : graph){
if (!vertex.isVisited()){
return true;
}
}
return false;
}
|
public String originalGraphToString(){
StringBuilder sb = new StringBuilder();
for (Vertex vertex : graph){
sb.append(vertex.originalToString());
}
return sb.toString();
}
public void resetPrintHistory(){
for (Vertex vertex : graph){
Iterator<Map.Entry<Vertex,Edge>> it = vertex.getEdges().entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Vertex,Edge> pair = it.next();
pair.getValue().setPrinted(false);
}
}
}
public String minimumSpanningTreeToString(){
StringBuilder sb = new StringBuilder();
for (Vertex vertex : graph){
sb.append(vertex.includedToString());
}
return sb.toString();
}
}
|
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-5\src\main\java\com\baeldung\algorithms\prim\Prim.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public I_AD_ClientInfo retrieveClientInfo(final Properties ctx)
{
final int adClientId = Env.getAD_Client_ID(ctx);
return retrieveClientInfo(ctx, adClientId);
} // get
@Override
public ClientEMailConfig getEMailConfigById(@NonNull final ClientId clientId)
{
return emailConfigCache.getOrLoad(clientId, this::retrieveEMailConfigById);
}
private ClientEMailConfig retrieveEMailConfigById(final @NonNull ClientId clientId)
{
final I_AD_Client record = getById(clientId);
return toClientEMailConfig(record);
}
public static ClientEMailConfig toClientEMailConfig(@NonNull final I_AD_Client client)
{
return ClientEMailConfig.builder()
.clientId(ClientId.ofRepoId(client.getAD_Client_ID()))
.mailbox(extractMailbox(client))
.build();
}
private static ExplainedOptional<Mailbox> extractMailbox(@NonNull final I_AD_Client client)
{
final EMailAddress email = EMailAddress.ofNullableString(client.getRequestEMail());
if (email == null)
{
return ExplainedOptional.emptyBecause("AD_Client.RequestEMail not set");
}
return ExplainedOptional.of(
Mailbox.builder()
.type(MailboxType.SMTP)
.email(email)
.smtpConfig(extractSMTPConfig(client))
.build()
);
}
private static SMTPConfig extractSMTPConfig(@NonNull final I_AD_Client client)
{
return SMTPConfig.builder()
.smtpHost(client.getSMTPHost())
.smtpPort(client.getSMTPPort())
.smtpAuthorization(client.isSmtpAuthorization())
.username(client.getRequestUser())
.password(client.getRequestUserPW())
.startTLS(client.isStartTLS())
.build();
}
@Override
|
public ClientMailTemplates getClientMailTemplatesById(final ClientId clientId)
{
return emailTemplatesCache.getOrLoad(clientId, this::retrieveClientMailTemplatesById);
}
private ClientMailTemplates retrieveClientMailTemplatesById(final ClientId clientId)
{
final I_AD_Client record = getById(clientId);
return toClientMailTemplates(record);
}
private static ClientMailTemplates toClientMailTemplates(@NonNull final I_AD_Client record)
{
return ClientMailTemplates.builder()
.passwordResetMailTemplateId(MailTemplateId.optionalOfRepoId(record.getPasswordReset_MailText_ID()))
.build();
}
@Override
public boolean isMultilingualDocumentsEnabled(@NonNull final ClientId adClientId)
{
final I_AD_Client client = getById(adClientId);
return client.isMultiLingualDocument();
}
@Override
public String getClientNameById(@NonNull final ClientId clientId)
{
return getById(clientId).getName();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\service\impl\ClientDAO.java
| 2
|
请完成以下Java代码
|
public boolean isReadOnly(ELContext context, Object base, Object property) {
return resolve(context, base, property) ? readOnly : false;
}
@Override
public void setValue(ELContext context, Object base, Object property, Object value)
throws PropertyNotWritableException {
if (resolve(context, base, property)) {
if (readOnly) {
throw new PropertyNotWritableException("Resolver is read only!");
}
setProperty((String) property, value);
}
}
@Override
public Object invoke(ELContext context, Object base, Object method, Class<?>[] paramTypes, Object[] params) {
if (resolve(context, base, method)) {
throw new NullPointerException("Cannot invoke method " + method + " on null");
}
return null;
}
/**
* Get property value
*
* @param property
* property name
* @return value associated with the given property
*/
public Object getProperty(String property) {
return map.get(property);
}
/**
* Set property value
*
|
* @param property
* property name
* @param value
* property value
*/
public void setProperty(String property, Object value) {
map.put(property, value);
}
/**
* Test property
*
* @param property
* property name
* @return <code>true</code> if the given property is associated with a value
*/
public boolean isProperty(String property) {
return map.containsKey(property);
}
/**
* Get properties
*
* @return all property names (in no particular order)
*/
public Iterable<String> properties() {
return map.keySet();
}
}
|
repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\util\RootPropertyResolver.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public int hashCode()
{
return Objects.hash(fulfillmentId, lineItems, shipmentTrackingNumber, shippedDate, shippingCarrierCode);
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("class ShippingFulfillment {\n");
sb.append(" fulfillmentId: ").append(toIndentedString(fulfillmentId)).append("\n");
sb.append(" lineItems: ").append(toIndentedString(lineItems)).append("\n");
sb.append(" shipmentTrackingNumber: ").append(toIndentedString(shipmentTrackingNumber)).append("\n");
sb.append(" shippedDate: ").append(toIndentedString(shippedDate)).append("\n");
sb.append(" shippingCarrierCode: ").append(toIndentedString(shippingCarrierCode)).append("\n");
sb.append("}");
return sb.toString();
}
|
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o)
{
if (o == null)
{
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\ShippingFulfillment.java
| 2
|
请完成以下Java代码
|
public IAutoCloseable temporaryChangeContext(@NonNull final Consumer<BusinessRuleLoggerContextBuilder> updater)
{
final BusinessRuleLoggerContext previousContext = contextHolder.get();
final BusinessRuleLoggerContext newContext = previousContext.newChild(updater);
contextHolder.set(newContext);
return () -> contextHolder.set(previousContext);
}
public void setTargetRecordRef(@Nullable final TableRecordReference recordRef)
{
changeContext(context -> context.withTargetRecordRef(recordRef));
}
public void setRootTargetRecordRef(@Nullable final TableRecordReference rootRecordRef)
{
changeContext(context -> context.withRootTargetRecordRef(rootRecordRef));
}
public BusinessRuleStopwatch newStopwatch()
{
|
return BusinessRuleStopwatch.createStarted();
}
private void changeContext(@NonNull final UnaryOperator<BusinessRuleLoggerContext> updater)
{
final BusinessRuleLoggerContext previousContext = contextHolder.get();
if (previousContext.isRootContext())
{
throw new AdempiereException("Changing root context not allowed. Use temporaryChangeContext() instead");
}
final BusinessRuleLoggerContext newContext = updater.apply(previousContext);
contextHolder.set(newContext);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\business_rule\log\BusinessRuleLogger.java
| 1
|
请完成以下Java代码
|
public boolean isOverwriteUser2 ()
{
Object oo = get_Value(COLUMNNAME_OverwriteUser2);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Percent.
@param Percent
Percentage
*/
@Override
public void setPercent (java.math.BigDecimal Percent)
{
set_Value (COLUMNNAME_Percent, Percent);
}
/** Get Percent.
@return Percentage
*/
@Override
public java.math.BigDecimal getPercent ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Percent);
if (bd == null)
return Env.ZERO;
return bd;
}
@Override
public org.compiere.model.I_C_ElementValue getUser1() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_User1_ID, org.compiere.model.I_C_ElementValue.class);
}
@Override
public void setUser1(org.compiere.model.I_C_ElementValue User1)
{
set_ValueFromPO(COLUMNNAME_User1_ID, org.compiere.model.I_C_ElementValue.class, User1);
}
/** Set Nutzer 1.
@param User1_ID
User defined list element #1
*/
@Override
public void setUser1_ID (int User1_ID)
{
if (User1_ID < 1)
set_Value (COLUMNNAME_User1_ID, null);
else
set_Value (COLUMNNAME_User1_ID, Integer.valueOf(User1_ID));
}
/** Get Nutzer 1.
@return User defined list element #1
*/
@Override
public int getUser1_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_User1_ID);
if (ii == null)
return 0;
return ii.intValue();
|
}
@Override
public org.compiere.model.I_C_ElementValue getUser2() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_User2_ID, org.compiere.model.I_C_ElementValue.class);
}
@Override
public void setUser2(org.compiere.model.I_C_ElementValue User2)
{
set_ValueFromPO(COLUMNNAME_User2_ID, org.compiere.model.I_C_ElementValue.class, User2);
}
/** Set Nutzer 2.
@param User2_ID
User defined list element #2
*/
@Override
public void setUser2_ID (int User2_ID)
{
if (User2_ID < 1)
set_Value (COLUMNNAME_User2_ID, null);
else
set_Value (COLUMNNAME_User2_ID, Integer.valueOf(User2_ID));
}
/** Get Nutzer 2.
@return User defined list element #2
*/
@Override
public int getUser2_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_User2_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_GL_DistributionLine.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.addFilterAfter(new JwtCsrfValidatorFilter(), CsrfFilter.class)
.csrf()
.csrfTokenRepository(jwtCsrfTokenRepository)
.ignoringAntMatchers(ignoreCsrfAntMatchers)
.and()
.authorizeRequests()
.antMatchers("/**")
.permitAll();
return http.build();
}
private class JwtCsrfValidatorFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
// NOTE: A real implementation should have a nonce cache so the token cannot be reused
CsrfToken token = (CsrfToken) request.getAttribute("_csrf");
if (
// only care if it's a POST
|
"POST".equals(request.getMethod()) &&
// ignore if the request path is in our list
Arrays.binarySearch(ignoreCsrfAntMatchers, request.getServletPath()) < 0 &&
// make sure we have a token
token != null) {
// CsrfFilter already made sure the token matched. Here, we'll make sure it's not expired
try {
Jwts.parser()
.setSigningKeyResolver(secretService.getSigningKeyResolver()).build()
.parseClaimsJws(token.getToken());
} catch (JwtException e) {
// most likely an ExpiredJwtException, but this will handle any
request.setAttribute("exception", e);
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
RequestDispatcher dispatcher = request.getRequestDispatcher("expired-jwt");
dispatcher.forward(request, response);
}
}
filterChain.doFilter(request, response);
}
}
}
|
repos\tutorials-master\security-modules\jjwt\src\main\java\io\jsonwebtoken\jjwtfun\config\WebSecurityConfig.java
| 2
|
请完成以下Java代码
|
public GraphQLSchema loadSchema() {
logger.debug("Attempting to load schema");
try (InputStream schemaStream = getClass().getClassLoader().getResourceAsStream("books.graphql")) {
if (schemaStream == null) {
throw new RuntimeException("GraphQL schema file 'books.graphql' not found in classpath");
}
logger.debug("Schema file found. Parsing...");
TypeDefinitionRegistry registry = new SchemaParser()
.parse(new InputStreamReader(schemaStream));
RuntimeWiring wiring = buildRuntimeWiring();
return new SchemaGenerator().makeExecutableSchema(registry, wiring);
} catch (Exception e) {
logger.error("Failed to load GraphQL schema", e);
throw new RuntimeException("GraphQL schema initialization failed", e);
}
}
private RuntimeWiring buildRuntimeWiring() {
|
return RuntimeWiring.newRuntimeWiring()
.type("Query", builder -> builder
.dataFetcher("books", env -> bookService.getBooks())
.dataFetcher("bookById", env -> bookService.getBookById(env.getArgument("id"))))
.type("Mutation", builder -> builder
.dataFetcher("addBook", env -> {
String id = env.getArgument("id");
String title = env.getArgument("title");
String author = env.getArgument("author");
if (title == null || title.isEmpty()) {
throw new IllegalArgumentException("Title cannot be empty");
}
return bookService.addBook(new Book(id, title, author));
}))
.build();
}
}
|
repos\tutorials-master\apache-libraries-3\src\main\java\com\baeldung\apache\camel\CustomSchemaLoader.java
| 1
|
请完成以下Java代码
|
public class OrderLineBPartnerAware implements IBPartnerAware
{
public static final IBPartnerAwareFactory factory = model -> {
final I_C_OrderLine orderLine = InterfaceWrapperHelper.create(model, I_C_OrderLine.class);
final IBPartnerAware partnerAware = new OrderLineBPartnerAware(orderLine);
return partnerAware;
};
private final I_C_OrderLine orderLine;
private OrderLineBPartnerAware(final I_C_OrderLine orderLine)
{
super();
Check.assumeNotNull(orderLine, "Order line not null");
this.orderLine = orderLine;
}
@Override
public int getAD_Client_ID()
{
return orderLine.getAD_Client_ID();
}
@Override
public int getAD_Org_ID()
{
return orderLine.getAD_Org_ID();
}
@Override
public boolean isSOTrx()
{
|
final I_C_Order order = getOrder();
return order.isSOTrx();
}
@Override
public I_C_BPartner getC_BPartner()
{
final I_C_Order order = getOrder();
return InterfaceWrapperHelper.create(Services.get(IOrderBL.class).getBPartnerOrNull(order), I_C_BPartner.class);
}
private I_C_Order getOrder()
{
final I_C_Order order = orderLine.getC_Order();
if (order == null)
{
throw new AdempiereException("Order not set for" + orderLine);
}
return order;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java\org\adempiere\mm\attributes\api\impl\OrderLineBPartnerAware.java
| 1
|
请完成以下Java代码
|
public LookupValuesList getLocators()
{
if (warehouseRepoId <= 0)
{
return LookupValuesList.EMPTY;
}
return warehouseDAO
.getLocators(warehouseId())
.stream()
.map(locator -> IntegerLookupValue.of(locator.getM_Locator_ID(), locator.getValue()))
.collect(LookupValuesList.collect());
}
@Override
|
protected void customizeParametersBuilder(@NonNull final CreateReceiptsParametersBuilder parametersBuilder)
{
final LocatorId locatorId = LocatorId.ofRepoIdOrNull(warehouseIdOrNull(), locatorRepoId);
parametersBuilder.destinationLocatorIdOrNull(locatorId);
}
private WarehouseId warehouseId()
{
return WarehouseId.ofRepoId(warehouseRepoId);
}
private WarehouseId warehouseIdOrNull()
{
return WarehouseId.ofRepoIdOrNull(warehouseRepoId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_M_HU_CreateReceipt_LocatorParams.java
| 1
|
请完成以下Java代码
|
public abstract class ItemAwareElementImpl extends BaseElementImpl implements ItemAwareElement {
protected static AttributeReference<ItemDefinition> itemSubjectRefAttribute;
protected static ChildElement<DataState> dataStateChild;
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(ItemAwareElement.class, BPMN_ELEMENT_ITEM_AWARE_ELEMENT)
.namespaceUri(BPMN20_NS)
.extendsType(BaseElement.class)
.abstractType();
itemSubjectRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_ITEM_SUBJECT_REF)
.qNameAttributeReference(ItemDefinition.class)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
dataStateChild = sequenceBuilder.element(DataState.class)
.build();
typeBuilder.build();
}
public ItemAwareElementImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
}
public ItemDefinition getItemSubject() {
|
return itemSubjectRefAttribute.getReferenceTargetElement(this);
}
public void setItemSubject(ItemDefinition itemSubject) {
itemSubjectRefAttribute.setReferenceTargetElement(this, itemSubject);
}
public DataState getDataState() {
return dataStateChild.getChild(this);
}
public void setDataState(DataState dataState) {
dataStateChild.setChild(this, dataState);
}
}
|
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\ItemAwareElementImpl.java
| 1
|
请完成以下Java代码
|
public class CalculatedFieldDebugEventFilter extends DebugEventFilter {
@Schema(description = "String value representing the entity id in the event body", example = "57b6bafe-d600-423c-9267-fe31e5218986")
protected String entityId;
@Schema(description = "String value representing the entity type", allowableValues = "DEVICE")
protected String entityType;
@Schema(description = "String value representing the message id in the rule engine", example = "dcf44612-2ce4-4e5d-b462-ebb9c5628228")
protected String msgId;
@Schema(description = "String value representing the message type", example = "POST_TELEMETRY_REQUEST")
protected String msgType;
@Schema(description = "String value representing the arguments that were used in the calculation performed",
example = "{\"x\":{\"ts\":1739432016629,\"value\":20},\"y\":{\"ts\":1739429717656,\"value\":12}}")
protected String arguments;
@Schema(description = "String value representing the result of a calculation",
example = "{\"x + y\":32}")
|
protected String result;
@Override
public EventType getEventType() {
return EventType.DEBUG_CALCULATED_FIELD;
}
@Override
public boolean isNotEmpty() {
return super.isNotEmpty() || !StringUtils.isEmpty(entityId) || !StringUtils.isEmpty(entityType)
|| !StringUtils.isEmpty(msgId) || !StringUtils.isEmpty(msgType)
|| !StringUtils.isEmpty(arguments) || !StringUtils.isEmpty(result);
}
}
|
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\event\CalculatedFieldDebugEventFilter.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class AdMenuId implements RepoIdAware
{
@JsonCreator
public static AdMenuId ofRepoId(final int repoId)
{
return new AdMenuId(repoId);
}
public static AdMenuId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? new AdMenuId(repoId) : null;
}
public static int toRepoId(final AdMenuId id)
{
return id != null ? id.getRepoId() : -1;
|
}
int repoId;
private AdMenuId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "AD_Menu_ID");
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\menu\AdMenuId.java
| 2
|
请完成以下Java代码
|
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public org.compiere.model.I_C_Payment_Reservation getC_Payment_Reservation()
{
return get_ValueAsPO(COLUMNNAME_C_Payment_Reservation_ID, org.compiere.model.I_C_Payment_Reservation.class);
}
@Override
public void setC_Payment_Reservation(final org.compiere.model.I_C_Payment_Reservation C_Payment_Reservation)
{
set_ValueFromPO(COLUMNNAME_C_Payment_Reservation_ID, org.compiere.model.I_C_Payment_Reservation.class, C_Payment_Reservation);
}
@Override
public void setC_Payment_Reservation_ID (final int C_Payment_Reservation_ID)
{
if (C_Payment_Reservation_ID < 1)
set_Value (COLUMNNAME_C_Payment_Reservation_ID, null);
else
set_Value (COLUMNNAME_C_Payment_Reservation_ID, C_Payment_Reservation_ID);
}
@Override
public int getC_Payment_Reservation_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Payment_Reservation_ID);
}
@Override
public void setExternalId (final @Nullable java.lang.String ExternalId)
{
set_Value (COLUMNNAME_ExternalId, ExternalId);
}
@Override
public java.lang.String getExternalId()
{
return get_ValueAsString(COLUMNNAME_ExternalId);
}
@Override
public void setPayPal_AuthorizationId (final @Nullable java.lang.String PayPal_AuthorizationId)
{
set_Value (COLUMNNAME_PayPal_AuthorizationId, PayPal_AuthorizationId);
}
@Override
public java.lang.String getPayPal_AuthorizationId()
{
return get_ValueAsString(COLUMNNAME_PayPal_AuthorizationId);
|
}
@Override
public void setPayPal_Order_ID (final int PayPal_Order_ID)
{
if (PayPal_Order_ID < 1)
set_ValueNoCheck (COLUMNNAME_PayPal_Order_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PayPal_Order_ID, PayPal_Order_ID);
}
@Override
public int getPayPal_Order_ID()
{
return get_ValueAsInt(COLUMNNAME_PayPal_Order_ID);
}
@Override
public void setPayPal_OrderJSON (final @Nullable java.lang.String PayPal_OrderJSON)
{
set_Value (COLUMNNAME_PayPal_OrderJSON, PayPal_OrderJSON);
}
@Override
public java.lang.String getPayPal_OrderJSON()
{
return get_ValueAsString(COLUMNNAME_PayPal_OrderJSON);
}
@Override
public void setPayPal_PayerApproveUrl (final @Nullable java.lang.String PayPal_PayerApproveUrl)
{
set_Value (COLUMNNAME_PayPal_PayerApproveUrl, PayPal_PayerApproveUrl);
}
@Override
public java.lang.String getPayPal_PayerApproveUrl()
{
return get_ValueAsString(COLUMNNAME_PayPal_PayerApproveUrl);
}
@Override
public void setStatus (final java.lang.String Status)
{
set_Value (COLUMNNAME_Status, Status);
}
@Override
public java.lang.String getStatus()
{
return get_ValueAsString(COLUMNNAME_Status);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.paypal\src\main\java-gen\de\metas\payment\paypal\model\X_PayPal_Order.java
| 1
|
请完成以下Java代码
|
public void executeMigrationPlan(MigrationExecutionDto migrationExecution) {
createMigrationPlanExecutionBuilder(migrationExecution).execute();
}
public BatchDto executeMigrationPlanAsync(MigrationExecutionDto migrationExecution) {
Batch batch = createMigrationPlanExecutionBuilder(migrationExecution).executeAsync();
return BatchDto.fromBatch(batch);
}
protected MigrationPlanExecutionBuilder createMigrationPlanExecutionBuilder(MigrationExecutionDto migrationExecution) {
MigrationPlan migrationPlan = createMigrationPlan(migrationExecution.getMigrationPlan());
List<String> processInstanceIds = migrationExecution.getProcessInstanceIds();
MigrationPlanExecutionBuilder executionBuilder = getProcessEngine().getRuntimeService()
.newMigration(migrationPlan).processInstanceIds(processInstanceIds);
ProcessInstanceQueryDto processInstanceQueryDto = migrationExecution.getProcessInstanceQuery();
if (processInstanceQueryDto != null) {
ProcessInstanceQuery processInstanceQuery = processInstanceQueryDto.toQuery(getProcessEngine());
executionBuilder.processInstanceQuery(processInstanceQuery);
}
if (migrationExecution.isSkipCustomListeners()) {
|
executionBuilder.skipCustomListeners();
}
if (migrationExecution.isSkipIoMappings()) {
executionBuilder.skipIoMappings();
}
return executionBuilder;
}
protected MigrationPlan createMigrationPlan(MigrationPlanDto migrationPlanDto) {
try {
return MigrationPlanDto.toMigrationPlan(getProcessEngine(), objectMapper, migrationPlanDto);
}
catch (MigrationPlanValidationException e) {
throw e;
}
catch (BadUserRequestException e) {
throw new InvalidRequestException(Status.BAD_REQUEST, e, e.getMessage());
}
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\MigrationRestServiceImpl.java
| 1
|
请完成以下Java代码
|
public class SEPA_Export_Line
{
/**
* If the given line's account is an ESR account, then this method sets the line's <code>OtherAccountIdentification</code> value to the ESR-account's retrieveESRAccountNo.
* task 07789
*/
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE })
public void updateOtherAccountIdentification(final I_SEPA_Export_Line esrImport)
{
final I_C_BP_BankAccount bpBankAccount = InterfaceWrapperHelper.create(esrImport.getC_BP_BankAccount(), I_C_BP_BankAccount.class);
final String QR_IBAN = bpBankAccount.getQR_IBAN();
if (!bpBankAccount.isEsrAccount())
{
return; // nothing to do if is not ESR or if is a QR account
}
if (Check.isNotBlank(QR_IBAN))
{
esrImport.setOtherAccountIdentification(""); // set nothing, but we need to make sure that tag is closed
return;
}
final IESRBPBankAccountBL esrBankAccountBL = Services.get(IESRBPBankAccountBL.class);
final IESRImportBL esrBL = Services.get(IESRImportBL.class);
final String otherAccountIdentification;
final String esrAccountNo = esrBankAccountBL.retrieveESRAccountNo(bpBankAccount);
if (esrAccountNo.length() == 9)
{
// task 08341: the account should already contain a check digit, but we verify that it is actually the correct check digit.
final int checkDigit = esrBL.calculateESRCheckDigit(esrAccountNo.substring(0, 8));
final String checkDigitStr = Integer.toString(checkDigit);
final String lastcharStr = esrAccountNo.substring(8);
Check.errorUnless(checkDigitStr.equals(lastcharStr), "EsrAccountNo {} has 9 digits and should end with {}, but ends with {}; C_BP_BankAccount={}",
esrAccountNo, checkDigitStr, lastcharStr, bpBankAccount);
otherAccountIdentification = esrAccountNo;
}
else if (esrAccountNo.length() == 5)
{
// task 08341: idk that to do with a 5-digit ESR-Teilnehmernummer, so i just let it be.
|
// i just read about it in http://www.six-interbank-clearing.com/dam/downloads/de/standardization/iso/swiss-recommendations/implementation-guidelines-ct/standardization_isopayments_iso_20022_ch_implementation_guidelines_ct.pdf
// but donT know anything else about it.
otherAccountIdentification = esrAccountNo;
}
else
{ // default: we prepend a check digit
try
{
final int checkDigit = esrBL.calculateESRCheckDigit(esrAccountNo);
otherAccountIdentification = esrAccountNo + checkDigit;
}
catch (final RuntimeException rte)
{ // augment the exception and rethrow it
throw AdempiereException.wrapIfNeeded(rte).appendParametersToMessage()
.setParameter("C_BPartner_ID", bpBankAccount.getC_BPartner_ID())
.setParameter("C_BP_BankAccount_ID",bpBankAccount.getC_BP_BankAccount_ID());
}
}
esrImport.setOtherAccountIdentification(otherAccountIdentification);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\base\src\main\java\de\metas\payment\sepa\model\validator\SEPA_Export_Line.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getId() {
return id;
}
@Override
public String getKey() {
return key;
}
@Override
public String getCategory() {
return category;
}
@Override
public String getDescription() {
return description;
}
@Override
public boolean hasStartFormKey() {
return hasStartFormKey;
}
@Override
public String getName() {
return name;
}
@Override
public int getVersion() {
return version;
}
@Override
public String getResourceName() {
return resourceName;
}
@Override
public String getDeploymentId() {
return deploymentId;
}
@Override
public String getDiagramResourceName() {
|
return diagramResourceName;
}
@Override
public boolean isSuspended() {
return suspended;
}
@Override
public String getTenantId() {
return tenantId;
}
@Override
public String getVersionTag() {
return versionTag;
}
@Override
public Integer getHistoryTimeToLive() {
return historyTimeToLive;
}
@Override
public boolean isStartableInTasklist() {
return isStartableInTasklist;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\repository\CalledProcessDefinitionImpl.java
| 2
|
请完成以下Java代码
|
public class ProductionSimulationViewFactory implements IViewFactory
{
public static final String ProductionSimulationView_String = "simulation";
public static final WindowId WINDOWID = WindowId.fromJson(ProductionSimulationView_String);
private final IADProcessDAO adProcessDAO = Services.get(IADProcessDAO.class);
private final ProductionSimulationRowsRepository rowsRepo;
public ProductionSimulationViewFactory(
@NonNull final CandidateRepositoryRetrieval candidateRepositoryRetrieval,
@NonNull final PPOrderCandidateDAO ppOrderCandidateDAO,
@NonNull final LookupDataSourceFactory lookupDataSourceFactory)
{
this.rowsRepo = ProductionSimulationRowsRepository.builder()
.candidateRepositoryRetrieval(candidateRepositoryRetrieval)
.ppOrderCandidateDAO(ppOrderCandidateDAO)
.lookupDataSourceFactory(lookupDataSourceFactory)
.build();
}
@Override
public IView createView(@NonNull final CreateViewRequest request)
{
final ViewId viewId = request.getViewId();
viewId.assertWindowId(WINDOWID);
final OrderLineDescriptor orderLineDescriptor = request.getParameterAs(VIEW_FACTORY_PARAM_DOCUMENT_LINE_DESCRIPTOR, OrderLineDescriptor.class);
Check.assumeNotNull(orderLineDescriptor, VIEW_FACTORY_PARAM_DOCUMENT_LINE_DESCRIPTOR + " is mandatory!");
|
final ProductionSimulationRows rows = rowsRepo.getByOrderLineDescriptor(orderLineDescriptor);
return ProductionSimulationView.builder()
.viewId(viewId)
.rows(rows)
.build();
}
@Override
public ViewLayout getViewLayout(final WindowId windowId, final JSONViewDataType viewDataType, final ViewProfileId profileId)
{
final ITranslatableString caption = adProcessDAO.retrieveProcessNameByClassIfUnique(C_Order_ProductionSimulationView_Launcher.class)
.orElse(null);
return ViewLayout.builder()
.setWindowId(WINDOWID)
.setCaption(caption)
.allowViewCloseAction(ViewCloseAction.DONE)
.setAllowOpeningRowDetails(false)
.setTreeCollapsible(true)
.setHasTreeSupport(true)
.addElementsFromViewRowClass(ProductionSimulationRow.class, viewDataType)
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\simulation\ProductionSimulationViewFactory.java
| 1
|
请完成以下Java代码
|
public Criteria andProductCategoryIdNotBetween(Long value1, Long value2) {
addCriterion("product_category_id not between", value1, value2, "productCategoryId");
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\UmsMemberProductCategoryRelationExample.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public List<Character> generateListOfCharactersChatModel(@PathVariable int amount) {
if (amount > 10) {
throw new IllegalArgumentException("Amount must be less than 10");
}
return characterService.generateListOfCharactersChatClient(amount);
}
@GetMapping("/chat-client/list/{amount}")
public List<Character> generateListOfCharactersChatClient(@PathVariable int amount) {
if (amount > 10) {
throw new IllegalArgumentException("Amount must be less than 10");
}
return characterService.generateListOfCharactersChatModel(amount);
}
// Map of character names and biographies
@GetMapping("/chat-model/map/{amount}")
public Map<String, Object> generateListOfCharactersChatModelMap(@PathVariable int amount) {
if (amount > 10) {
throw new IllegalArgumentException("Amount must be less than 10");
}
return characterService.generateMapOfCharactersChatModel(amount);
}
@GetMapping("/chat-client/map/{amount}")
public Map<String, Object> generateListOfCharactersChatClientMap(@PathVariable int amount) {
if (amount > 10) {
|
throw new IllegalArgumentException("Amount must be less than 10");
}
return characterService.generateMapOfCharactersChatClient(amount);
}
// List of character names
@GetMapping("/chat-model/names/{amount}")
public List<String> generateListOfCharacterNamesChatModel(@PathVariable int amount) {
return characterService.generateListOfCharacterNamesChatModel(amount);
}
@GetMapping("/chat-client/names/{amount}")
public List<String> generateListOfCharacterNamesChatClient(@PathVariable int amount) {
return characterService.generateListOfCharacterNamesChatClient(amount);
}
// Custom converter
@GetMapping("/custom-converter/{amount}")
public Map<String, Character> generateMapOfCharactersCustomConverterGenerics(@PathVariable int amount) {
return characterService.generateMapOfCharactersCustomConverter(amount);
}
@GetMapping("/custom-converter/chat-client/{amount}")
public Map<String, Character> generateMapOfCharactersCustomConverterChatClient(@PathVariable int amount) {
return characterService.generateMapOfCharactersCustomConverterChatClient(amount);
}
}
|
repos\tutorials-master\spring-ai-modules\spring-ai-3\src\main\java\com\baeldung\springaistructuredoutput\controller\CharacterController.java
| 2
|
请完成以下Java代码
|
protected AbstractDataAssociation createDataInputAssociation(DataAssociation dataAssociationElement) {
if (dataAssociationElement.getAssignments().isEmpty()) {
return new MessageImplicitDataInputAssociation(
dataAssociationElement.getSourceRef(),
dataAssociationElement.getTargetRef()
);
} else {
SimpleDataInputAssociation dataAssociation = new SimpleDataInputAssociation(
dataAssociationElement.getSourceRef(),
dataAssociationElement.getTargetRef()
);
ExpressionManager expressionManager = Context.getProcessEngineConfiguration().getExpressionManager();
for (org.activiti.bpmn.model.Assignment assignmentElement : dataAssociationElement.getAssignments()) {
if (
StringUtils.isNotEmpty(assignmentElement.getFrom()) &&
StringUtils.isNotEmpty(assignmentElement.getTo())
) {
Expression from = expressionManager.createExpression(assignmentElement.getFrom());
Expression to = expressionManager.createExpression(assignmentElement.getTo());
Assignment assignment = new Assignment(from, to);
dataAssociation.addAssignment(assignment);
}
}
return dataAssociation;
}
}
protected AbstractDataAssociation createDataOutputAssociation(DataAssociation dataAssociationElement) {
|
if (StringUtils.isNotEmpty(dataAssociationElement.getSourceRef())) {
return new MessageImplicitDataOutputAssociation(
dataAssociationElement.getTargetRef(),
dataAssociationElement.getSourceRef()
);
} else {
ExpressionManager expressionManager = Context.getProcessEngineConfiguration().getExpressionManager();
Expression transformation = expressionManager.createExpression(dataAssociationElement.getTransformation());
AbstractDataAssociation dataOutputAssociation = new TransformationDataOutputAssociation(
null,
dataAssociationElement.getTargetRef(),
transformation
);
return dataOutputAssociation;
}
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\behavior\WebServiceActivityBehavior.java
| 1
|
请完成以下Java代码
|
public void setIsDebug (final boolean IsDebug)
{
set_Value (COLUMNNAME_IsDebug, IsDebug);
}
@Override
public boolean isDebug()
{
return get_ValueAsBoolean(COLUMNNAME_IsDebug);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
/**
* Severity AD_Reference_ID=541949
* Reference name: Severity
*/
public static final int SEVERITY_AD_Reference_ID=541949;
/** Notice = N */
public static final String SEVERITY_Notice = "N";
/** Error = E */
public static final String SEVERITY_Error = "E";
@Override
public void setSeverity (final java.lang.String Severity)
{
set_Value (COLUMNNAME_Severity, Severity);
}
@Override
public java.lang.String getSeverity()
{
return get_ValueAsString(COLUMNNAME_Severity);
}
|
@Override
public org.compiere.model.I_AD_Val_Rule getValidation_Rule()
{
return get_ValueAsPO(COLUMNNAME_Validation_Rule_ID, org.compiere.model.I_AD_Val_Rule.class);
}
@Override
public void setValidation_Rule(final org.compiere.model.I_AD_Val_Rule Validation_Rule)
{
set_ValueFromPO(COLUMNNAME_Validation_Rule_ID, org.compiere.model.I_AD_Val_Rule.class, Validation_Rule);
}
@Override
public void setValidation_Rule_ID (final int Validation_Rule_ID)
{
if (Validation_Rule_ID < 1)
set_Value (COLUMNNAME_Validation_Rule_ID, null);
else
set_Value (COLUMNNAME_Validation_Rule_ID, Validation_Rule_ID);
}
@Override
public int getValidation_Rule_ID()
{
return get_ValueAsInt(COLUMNNAME_Validation_Rule_ID);
}
@Override
public void setWarning_Message_ID (final int Warning_Message_ID)
{
if (Warning_Message_ID < 1)
set_Value (COLUMNNAME_Warning_Message_ID, null);
else
set_Value (COLUMNNAME_Warning_Message_ID, Warning_Message_ID);
}
@Override
public int getWarning_Message_ID()
{
return get_ValueAsInt(COLUMNNAME_Warning_Message_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_BusinessRule.java
| 1
|
请完成以下Java代码
|
public static class Status {
/**
* The defaults names of {@link StatusChecker}
* <p>
* The defaults : "memory", "load"
*/
private Set<String> defaults = new LinkedHashSet<>(Arrays.asList("memory", "load"));
/**
* The extra names of {@link StatusChecker}
*/
private Set<String> extras = new LinkedHashSet<>();
public Set<String> getDefaults() {
return defaults;
}
|
public void setDefaults(Set<String> defaults) {
this.defaults = defaults;
}
public Set<String> getExtras() {
return extras;
}
public void setExtras(Set<String> extras) {
this.extras = extras;
}
}
}
|
repos\dubbo-spring-boot-project-master\dubbo-spring-boot-compatible\actuator\src\main\java\org\apache\dubbo\spring\boot\actuate\health\DubboHealthIndicatorProperties.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class BaseHistoricDecisionExecutionResource {
@Autowired
protected ContentTypeResolver contentTypeResolver;
@Autowired
protected DmnRestResponseFactory dmnRestResponseFactory;
@Autowired
protected DmnHistoryService dmnHistoryService;
@Autowired(required=false)
protected DmnRestApiInterceptor restApiInterceptor;
/**
* Returns the {@link DmnHistoricDecisionExecution} that is requested. Throws the right exceptions when bad request was made or decision table was not found.
*/
protected DmnHistoricDecisionExecution getHistoricDecisionExecutionFromRequest(String decisionExecutionId) {
DmnHistoricDecisionExecutionQuery historicDecisionExecutionQuery = dmnHistoryService.createHistoricDecisionExecutionQuery().id(decisionExecutionId);
DmnHistoricDecisionExecution decisionExecution = historicDecisionExecutionQuery.singleResult();
|
if (decisionExecution == null) {
throw new FlowableObjectNotFoundException("Could not find a decision execution with id '" + decisionExecutionId + "'");
}
if (restApiInterceptor != null) {
restApiInterceptor.accessDecisionHistoryInfoById(decisionExecution);
}
return decisionExecution;
}
protected String getExecutionAuditData(String decisionExecutionId, HttpServletResponse response) {
if (decisionExecutionId == null) {
throw new FlowableIllegalArgumentException("No decision execution id provided");
}
// Check if deployment exists
DmnHistoricDecisionExecution decisionExecution = getHistoricDecisionExecutionFromRequest(decisionExecutionId);
response.setContentType("application/json");
return decisionExecution.getExecutionJson();
}
}
|
repos\flowable-engine-main\modules\flowable-dmn-rest\src\main\java\org\flowable\dmn\rest\service\api\history\BaseHistoricDecisionExecutionResource.java
| 2
|
请完成以下Java代码
|
public DocumentId getId()
{
final ImmutableList<Object> keyParts = ImmutableList.of(huStockInfo.getHuStorageRepoId(), huStockInfo.getHuAttributeRepoId());
return DocumentId.ofComposedKeyParts(keyParts);
}
@Override
public boolean isProcessed()
{
return true;
}
@Override
public DocumentPath getDocumentPath()
{
return DocumentPath.rootDocumentPath(
MaterialCockpitUtil.WINDOW_MaterialCockpit_StockDetailView,
getId());
}
|
@Override
public Set<String> getFieldNames()
{
return ViewColumnHelper.extractFieldNames(this);
}
@Override
public ViewRowFieldNameAndJsonValues getFieldNameAndJsonValues()
{
return ViewColumnHelper.extractJsonMap(this);
}
@Override
public Collection<? extends IViewRow> getIncludedRows()
{
return ImmutableList.of();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\material\cockpit\stockdetails\StockDetailsRow.java
| 1
|
请完成以下Java代码
|
public String getReferenceId() {
return referenceId;
}
@Override
public void setReferenceId(String referenceId) {
this.referenceId = referenceId;
}
@Override
public String getReferenceType() {
return referenceType;
}
@Override
public void setReferenceType(String referenceType) {
this.referenceType = referenceType;
}
@Override
public String getPropagatedStageInstanceId() {
return propagatedStageInstanceId;
}
@Override
public void setPropagatedStageInstanceId(String propagatedStageInstanceId) {
this.propagatedStageInstanceId = propagatedStageInstanceId;
}
@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;
}
@Override
public List<HistoricVariableInstanceEntity> getQueryVariables() {
if (queryVariables == null && Context.getCommandContext() != null) {
|
queryVariables = new HistoricVariableInitializingList();
}
return queryVariables;
}
@Override
public void setQueryVariables(List<HistoricVariableInstanceEntity> queryVariables) {
this.queryVariables = queryVariables;
}
// common methods //////////////////////////////////////////////////////////
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("HistoricProcessInstanceEntity[id=").append(getId())
.append(", definition=").append(getProcessDefinitionId());
if (superProcessInstanceId != null) {
sb.append(", superProcessInstanceId=").append(superProcessInstanceId);
}
if (referenceId != null) {
sb.append(", referenceId=").append(referenceId)
.append(", referenceType=").append(referenceType);
}
if (StringUtils.isNotEmpty(tenantId)) {
sb.append(", tenantId=").append(tenantId);
}
sb.append("]");
return sb.toString();
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\HistoricProcessInstanceEntityImpl.java
| 1
|
请完成以下Java代码
|
public int getM_Warehouse_ID()
{
return delegate.getM_Warehouse_ID();
}
@Override
public int getDropShip_BPartner_ID()
{
return delegate.getDropShip_BPartner_ID();
}
@Override
public void setDropShip_BPartner_ID(final int DropShip_BPartner_ID)
{
delegate.setDropShip_BPartner_ID(DropShip_BPartner_ID);
}
@Override
public int getDropShip_Location_ID()
{
return delegate.getDropShip_Location_ID();
}
@Override
public void setDropShip_Location_ID(final int DropShip_Location_ID)
{
delegate.setDropShip_Location_ID(DropShip_Location_ID);
}
@Override
public int getDropShip_Location_Value_ID()
{
return delegate.getDropShip_Location_Value_ID();
}
@Override
public void setDropShip_Location_Value_ID(final int DropShip_Location_Value_ID)
{
delegate.setDropShip_Location_Value_ID(DropShip_Location_Value_ID);
}
@Override
public int getDropShip_User_ID()
{
return delegate.getDropShip_User_ID();
}
@Override
public void setDropShip_User_ID(final int DropShip_User_ID)
{
delegate.setDropShip_User_ID(DropShip_User_ID);
}
@Override
public void setRenderedAddressAndCapturedLocation(final @NonNull RenderedAddressAndCapturedLocation from)
{
|
IDocumentDeliveryLocationAdapter.super.setRenderedAddressAndCapturedLocation(from);
}
@Override
public void setRenderedAddress(final @NonNull RenderedAddressAndCapturedLocation from)
{
IDocumentDeliveryLocationAdapter.super.setRenderedAddress(from);
}
@Override
public Optional<DocumentLocation> toPlainDocumentLocation(final IDocumentLocationBL documentLocationBL)
{
return documentLocationBL.toPlainDocumentLocation(this);
}
@Override
public DropShipLocationAdapter toOldValues()
{
InterfaceWrapperHelper.assertNotOldValues(delegate);
return new DropShipLocationAdapter(InterfaceWrapperHelper.createOld(delegate, I_C_OLCand.class));
}
@Override
public I_C_OLCand getWrappedRecord()
{
return delegate;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\ordercandidate\location\adapter\DropShipLocationAdapter.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class VariableValidationService {
private static final Logger logger = LoggerFactory.getLogger(VariableValidationService.class);
public VariableValidationService(Map<String, VariableType> variableTypeMap) {
this.variableTypeMap = variableTypeMap;
}
private Map<String, VariableType> variableTypeMap;
public boolean validate(Object var, VariableDefinition variableDefinition) {
return validateWithErrors(var, variableDefinition).isEmpty();
}
public List<ActivitiException> validateWithErrors(Object var, VariableDefinition variableDefinition) {
List<ActivitiException> errors = new ArrayList<>();
if (variableDefinition.getType() != null) {
VariableType type = variableTypeMap.get(variableDefinition.getType());
|
//if type is not in the map then assume to be json
if (type == null) {
type = variableTypeMap.get("json");
}
type.validate(var, errors);
} else {
errors.add(new ActivitiException(variableDefinition.getName() + " has no type"));
logger.error(variableDefinition.getName() + " has no type");
}
return errors;
}
}
|
repos\Activiti-develop\activiti-core\activiti-spring-process-extensions\src\main\java\org\activiti\spring\process\variable\VariableValidationService.java
| 2
|
请完成以下Java代码
|
public Long getProductId() {
return productId;
}
public void setProductId(Long productId) {
this.productId = productId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public Integer getRecommendStatus() {
return recommendStatus;
}
public void setRecommendStatus(Integer recommendStatus) {
this.recommendStatus = recommendStatus;
}
public Integer getSort() {
return sort;
}
public void setSort(Integer sort) {
|
this.sort = sort;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", productId=").append(productId);
sb.append(", productName=").append(productName);
sb.append(", recommendStatus=").append(recommendStatus);
sb.append(", sort=").append(sort);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}
|
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\SmsHomeNewProduct.java
| 1
|
请完成以下Java代码
|
public State getState() {
if (isSelected() && !isArmed()) {
// CHECKED
return State.CHECKED;
} else if (isSelected() && isArmed()) {
// GREY_CHECKED
return State.GREY_CHECKED;
} else if (!isSelected() && isArmed()) {
// GREY_UNCHECKED
return State.GREY_UNCHECKED;
} else { // (!isSelected() && !isArmed()){
// UNCHECKED
return State.UNCHECKED;
}
}
/**
* We rotate between UNCHECKED, CHECKED, GREY_UNCHECKED, GREY_CHECKED.
*/
public void nextState() {
|
switch (getState()) {
case UNCHECKED:
setState(State.CHECKED);
break;
case CHECKED:
setState(State.GREY_UNCHECKED);
break;
case GREY_UNCHECKED:
setState(State.GREY_CHECKED);
break;
case GREY_CHECKED:
setState(State.UNCHECKED);
break;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\it\cnr\imaa\essi\lablib\gui\checkboxtree\QuadristateButtonModel.java
| 1
|
请完成以下Java代码
|
long calculateIntervalMax(long reconnectIntervalMinSeconds) {
return reconnectIntervalMinSeconds > MAX_RECONNECT_INTERVAL_SEC ? reconnectIntervalMinSeconds : MAX_RECONNECT_INTERVAL_SEC;
}
long calculateIntervalMin(long reconnectIntervalMinSeconds) {
return Math.min((reconnectIntervalMinSeconds > 0 ? reconnectIntervalMinSeconds : DEFAULT_RECONNECT_INTERVAL_SEC), this.reconnectIntervalMaxSeconds);
}
@Override
synchronized public long getNextReconnectDelay() {
final long currentNanoTime = getNanoTime();
final long coolDownSpentNanos = currentNanoTime - lastDisconnectNanoTime;
lastDisconnectNanoTime = currentNanoTime;
if (isCooledDown(coolDownSpentNanos)) {
retryCount = 0;
return reconnectIntervalMinSeconds;
}
return calculateNextReconnectDelay() + calculateJitter();
}
long calculateJitter() {
|
return ThreadLocalRandom.current().nextInt() >= 0 ? JITTER_MAX : 0;
}
long calculateNextReconnectDelay() {
return Math.min(reconnectIntervalMaxSeconds, reconnectIntervalMinSeconds + calculateExp(retryCount++));
}
long calculateExp(long e) {
return 1L << Math.min(e, EXP_MAX);
}
boolean isCooledDown(long coolDownSpentNanos) {
return TimeUnit.NANOSECONDS.toSeconds(coolDownSpentNanos) > reconnectIntervalMaxSeconds + reconnectIntervalMinSeconds;
}
long getNanoTime() {
return System.nanoTime();
}
}
|
repos\thingsboard-master\netty-mqtt\src\main\java\org\thingsboard\mqtt\ReconnectStrategyExponential.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setS_Issue_ID (int S_Issue_ID)
{
if (S_Issue_ID < 1)
set_Value (COLUMNNAME_S_Issue_ID, null);
else
set_Value (COLUMNNAME_S_Issue_ID, Integer.valueOf(S_Issue_ID));
}
/** Get Issue.
@return Issue */
@Override
public int getS_Issue_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_S_Issue_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Art.
|
@param Type Art */
@Override
public void setType (java.lang.String Type)
{
set_ValueNoCheck (COLUMNNAME_Type, Type);
}
/** Get Art.
@return Art */
@Override
public java.lang.String getType ()
{
return (java.lang.String)get_Value(COLUMNNAME_Type);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java-gen\de\metas\serviceprovider\model\X_S_ExternalIssueDetail.java
| 2
|
请完成以下Java代码
|
private static String sqlSelect(final String tableAlias)
{
return sqlSelectColumn(tableAlias, "Value", PREFIX)
+ ", " + sqlSelectColumn(tableAlias, "Classname", PREFIX);
}
private static ADProcessName retrieve(final ResultSet rs) throws SQLException
{
return ADProcessName.builder()
.value(rs.getString(PREFIX + "Value"))
.classname(rs.getString(PREFIX + "Classname"))
.build();
}
}
public static final class ADElementName_Loader
{
public static String retrieveColumnName(@NonNull final AdElementId adElementId)
{
return DB.getSQLValueStringEx(ITrx.TRXNAME_ThreadInherited,
"SELECT ColumnName FROM AD_Element WHERE AD_Element_ID=?",
|
adElementId);
}
}
public static final class ADMessageName_Loader
{
public static String retrieveValue(@NonNull final AdMessageId adMessageId)
{
return DB.getSQLValueStringEx(ITrx.TRXNAME_ThreadInherited,
"SELECT Value FROM AD_Message WHERE AD_Message_ID=?",
adMessageId);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\validator\sql_migration_context_info\names\Names.java
| 1
|
请完成以下Java代码
|
private ImmutableList<PdfDataProvider> retrievePdfDataToConcat(final ShipperTransportationId shipperTransportationId)
{
final ImmutableList.Builder<PdfDataProvider> result = ImmutableList.builder();
final IArchiveBL archiveBL = Services.get(IArchiveBL.class);
final IInOutDAO inOutDAO = Services.get(IInOutDAO.class);
final ImmutableList<InOutId> inOutIds = inOutDAO.retrieveByShipperTransportation(shipperTransportationId);
for (final InOutId io : inOutIds)
{
final TableRecordReference inoutRef = TableRecordReference.of(I_M_InOut.Table_Name, io);
final PdfDataProvider pdfData = archiveBL.getLastArchiveBinaryData(inoutRef)
.map(PdfDataProvider::forData)
.orElse(null);
if(pdfData != null)
{
result.add(pdfData);
}
}
return result.build();
}
// // TODO maybe this needs to be deleted. It all depends on what mark sais. for now, i'll leave it here.
// private ImmutableList<PdfDataProvider> retrievePdfDataToConcat(@NonNull final ShipperTransportationId shipperTransportationId)
// {
// final IArchiveDAO archiveDAO = Services.get(IArchiveDAO.class);
// final IShipperDAO shipperDAO = Services.get(IShipperDAO.class);
//
// final I_M_Shipper shipper = shipperDAO.getByShipperTransportationId(shipperTransportationId);
//
// if (X_M_Shipper.SHIPPERGATEWAY_DPD.equals(shipper.getShipperGateway()))
// {
|
// return retrieveArchivesFromDpd(shipperTransportationId);
// }
// else if (X_M_Shipper.SHIPPERGATEWAY_DHL.equals(shipper.getShipperGateway()))
// {
// // return retrieveArchivesFromDhl();
// }
// return ImmutableList.of();
// }
//
// private ImmutableList<PdfDataProvider> retrieveArchivesFromDpd(final ShipperTransportationId shipperTransportationId)
// {
// Services.get(IQueryBL.class)
// .createQueryBuilder(I_DPD_StoreOrder.class???)
//
// // example code
// final ImmutableList.Builder<PdfDataProvider> result = ImmutableList.builder();
// final List<I_M_ShippingPackage> shippingPackages = shipperTransportationDAO.retrieveShippingPackages(shipperTransportationId);
// for (final I_M_ShippingPackage shippingPackage : shippingPackages)
// {
//
// shippingPackage.getde
// final List<I_AD_Archive> archives = archiveDAO.retrieveLastArchives(Env.getCtx(), TableRecordReference.of(I_M_ShippingPackage.Table_Name, ShippingPackageId.ofRepoId(shippingPackage.getM_ShippingPackage_ID())), 10000);
// result.addAll(archives.stream().map(it -> PdfDataProvider.forData(it.getBinaryData())).collect(GuavaCollectors.toImmutableList()));
// }
//
// return result.build();
// }
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\shipping\process\PrintAllShipmentsDocumentsStrategy.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Map<String, PaginationMultiTypeValuesHelper> filterQuery(String sex, String email, Pageable pageable) {
Types typeInstance;
if (sex.length() == 0 && email.length() == 0) {
typeInstance = new AllType(sex, email, pageable);
} else if (sex.length() > 0 && email.length() > 0) {
typeInstance = new SexEmailType(sex, email, pageable);
} else {
typeInstance = new SexType(sex, email, pageable);
}
|
this.multiValue.setCount(typeInstance.getCount());
this.multiValue.setPage(typeInstance.getPageNumber() + 1);
this.multiValue.setResults(typeInstance.getContent());
this.multiValue.setTotal(typeInstance.getTotal());
this.results.put("data", this.multiValue);
return results;
}
}
|
repos\SpringBoot-vue-master\src\main\java\com\boylegu\springboot_vue\controller\pagination\PaginationFormatting.java
| 2
|
请完成以下Java代码
|
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public double getPrice() {
|
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getStock() {
return stock;
}
public void setStock(int stock) {
this.stock = stock;
}
}
|
repos\tutorials-master\persistence-modules\spring-data-elasticsearch\src\main\java\com\baeldung\elasticsearch\importcsv\Product.java
| 1
|
请完成以下Java代码
|
public void beforeDelete(@NonNull final I_PP_Order ppOrder)
{
//
// Delete depending records
final String docStatus = ppOrder.getDocStatus();
if (X_PP_Order.DOCSTATUS_Drafted.equals(docStatus)
|| X_PP_Order.DOCSTATUS_InProgress.equals(docStatus))
{
final PPOrderId ppOrderId = PPOrderId.ofRepoId(ppOrder.getPP_Order_ID());
orderCostsService.deleteByOrderId(ppOrderId);
deleteWorkflowAndBOM(ppOrderId);
}
}
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_CHANGE, ModelValidator.TYPE_BEFORE_NEW },
ifColumnsChanged = { I_PP_Order.COLUMNNAME_M_Product_ID, I_PP_Order.COLUMNNAME_PP_Product_BOM_ID })
public void validateBOMAndProduct(@NonNull final I_PP_Order ppOrder)
{
final ProductBOMId bomId = ProductBOMId.ofRepoId(ppOrder.getPP_Product_BOM_ID());
final ProductId productIdOfBOM = productBOMDAO.getBOMProductId(bomId);
if (ppOrder.getM_Product_ID() != productIdOfBOM.getRepoId())
{
throw new AdempiereException(AdMessageKey.of("PP_Order_BOM_Doesnt_Match"))
|
.markAsUserValidationError()
.appendParametersToMessage()
.setParameter("PP_Order.M_Product_ID", ppOrder.getM_Product_ID())
.setParameter("PP_Order.PP_Product_BOM_ID.M_Product_ID", productIdOfBOM.getRepoId());
}
}
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE })
public void setSeqNo(final I_PP_Order ppOrder)
{
if (ppOrder.getSeqNo() <= 0)
{
ppOrder.setSeqNo(ppOrderDAO.getNextSeqNoPerDateStartSchedule(ppOrder).toInt());
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\model\validator\PP_Order.java
| 1
|
请完成以下Java代码
|
private ToInvoiceExclOverride computeInvoicableQtysDelivered()
{
final StockQtyAndUOMQty qtysToInvoiceRaw;
final StockQtyAndUOMQty qtysToInvoiceCalc;
if (soTrx.isSales())
{
qtysToInvoiceRaw = deliveredData.getShipmentData().computeInvoicableQtyDelivered(invoicableQtyBasedOn);
qtysToInvoiceCalc = qtysToInvoiceRaw;
}
else
{
qtysToInvoiceRaw = deliveredData.getReceiptData().getQtysTotal(invoicableQtyBasedOn);
qtysToInvoiceCalc = deliveredData.getReceiptData().computeInvoicableQtyDelivered(qualityDiscountOverride, invoicableQtyBasedOn);
}
logger.debug("IsSales={} -> return delivered quantity={}", soTrx.isSales(), qtysToInvoiceCalc);
return new ToInvoiceExclOverride(
ToInvoiceExclOverride.InvoicedQtys.NOT_SUBTRACTED,
qtysToInvoiceRaw, qtysToInvoiceCalc);
}
public StockQtyAndUOMQty computeQtysDelivered()
{
final StockQtyAndUOMQty qtysDelivered;
if (soTrx.isSales())
{
qtysDelivered = deliveredData.getShipmentData().computeInvoicableQtyDelivered(invoicableQtyBasedOn);
}
else
{
qtysDelivered = deliveredData.getReceiptData().getQtysTotal(invoicableQtyBasedOn);
}
return qtysDelivered;
}
@lombok.Value
public static class ToInvoiceExclOverride
{
enum InvoicedQtys
{
SUBTRACTED, NOT_SUBTRACTED
}
InvoicedQtys invoicedQtys;
/**
|
* Excluding possible receipt quantities with quality issues
*/
StockQtyAndUOMQty qtysRaw;
/**
* Computed including possible receipt quality issues, not overridden by a possible qtyToInvoice override.
*/
StockQtyAndUOMQty qtysCalc;
private ToInvoiceExclOverride(
@NonNull final InvoicedQtys invoicedQtys,
@NonNull final StockQtyAndUOMQty qtysRaw,
@NonNull final StockQtyAndUOMQty qtysCalc)
{
this.qtysRaw = qtysRaw;
this.qtysCalc = qtysCalc;
this.invoicedQtys = invoicedQtys;
StockQtyAndUOMQtys.assumeCommonProductAndUom(qtysRaw, qtysCalc);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\internalbusinesslogic\InvoiceCandidate.java
| 1
|
请完成以下Java代码
|
public boolean isEmpty()
{
return termFrequencyMap.isEmpty();
}
@Override
public boolean contains(Object o)
{
if (o instanceof String)
return termFrequencyMap.containsKey(o);
else if (o instanceof TermFrequency)
return termFrequencyMap.containsValue(o);
return false;
}
@Override
public Iterator<TermFrequency> iterator()
{
return termFrequencyMap.values().iterator();
}
@Override
public Object[] toArray()
{
return termFrequencyMap.values().toArray();
}
@Override
public <T> T[] toArray(T[] a)
{
return termFrequencyMap.values().toArray(a);
}
@Override
public boolean add(TermFrequency termFrequency)
{
TermFrequency tf = termFrequencyMap.get(termFrequency.getTerm());
if (tf == null)
{
termFrequencyMap.put(termFrequency.getKey(), termFrequency);
return true;
}
tf.increase(termFrequency.getFrequency());
return false;
}
@Override
public boolean remove(Object o)
{
return termFrequencyMap.remove(o) != null;
}
@Override
public boolean containsAll(Collection<?> c)
{
for (Object o : c)
{
if (!contains(o))
return false;
}
return true;
}
@Override
public boolean addAll(Collection<? extends TermFrequency> c)
{
for (TermFrequency termFrequency : c)
{
add(termFrequency);
}
return !c.isEmpty();
}
@Override
public boolean removeAll(Collection<?> c)
{
for (Object o : c)
{
if (!remove(o))
return false;
}
return true;
}
@Override
|
public boolean retainAll(Collection<?> c)
{
return termFrequencyMap.values().retainAll(c);
}
@Override
public void clear()
{
termFrequencyMap.clear();
}
/**
* 提取关键词(非线程安全)
*
* @param termList
* @param size
* @return
*/
@Override
public List<String> getKeywords(List<Term> termList, int size)
{
clear();
add(termList);
Collection<TermFrequency> topN = top(size);
List<String> r = new ArrayList<String>(topN.size());
for (TermFrequency termFrequency : topN)
{
r.add(termFrequency.getTerm());
}
return r;
}
/**
* 提取关键词(线程安全)
*
* @param document 文档内容
* @param size 希望提取几个关键词
* @return 一个列表
*/
public static List<String> getKeywordList(String document, int size)
{
return new TermFrequencyCounter().getKeywords(document, size);
}
@Override
public String toString()
{
final int max = 100;
return top(Math.min(max, size())).toString();
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\word\TermFrequencyCounter.java
| 1
|
请完成以下Java代码
|
public boolean tryAdvance(Consumer<? super CityRecord> action) {
try {
if(!resultSet.next()) return false;
action.accept(createCityRecord(resultSet));
return true;
} catch(SQLException ex) {
throw new RuntimeException(ex);
}
}
}, false)
.onClose(() -> closeResources(connection, resultSet, preparedStatement));
}
private void closeResources(Connection connection, ResultSet resultSet, PreparedStatement preparedStatement) {
try {
resultSet.close();
preparedStatement.close();
connection.close();
logger.info("Resources closed");
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public Stream<CityRecord> getCitiesStreamUsingJOOQ(Connection connection)
throws SQLException {
PreparedStatement preparedStatement = connection.prepareStatement(QUERY);
connection.setAutoCommit(false);
preparedStatement.setFetchSize(5000);
ResultSet resultSet = preparedStatement.executeQuery();
return DSL.using(connection)
.fetchStream(resultSet)
.map(r -> new CityRecord(r.get("NAME", String.class),
r.get("COUNTRY", String.class)))
.onClose(() -> closeResources(connection, resultSet, preparedStatement));
}
public Stream<CityRecord> getCitiesStreamUsingJdbcStream(Connection connection)
throws SQLException {
|
PreparedStatement preparedStatement = connection.prepareStatement(QUERY);
connection.setAutoCommit(false);
preparedStatement.setFetchSize(5000);
ResultSet resultSet = preparedStatement.executeQuery();
return JdbcStream.stream(resultSet)
.map(r -> {
try {
return createCityRecord(resultSet);
} catch (SQLException e) {
throw new RuntimeException(e);
}
})
.onClose(() -> closeResources(connection, resultSet, preparedStatement));
}
private CityRecord createCityRecord(ResultSet resultSet) throws SQLException {
return new CityRecord(resultSet.getString(1), resultSet.getString(2));
}
}
|
repos\tutorials-master\persistence-modules\core-java-persistence-3\src\main\java\com\baeldung\resultset\streams\JDBCStreamAPIRepository.java
| 1
|
请完成以下Java代码
|
public List<DocumentLayoutElementDescriptor> getElements()
{
return elements;
}
public static final class Builder
{
public DocumentId asiDescriptorId;
private ITranslatableString caption;
private ITranslatableString description;
private final List<DocumentLayoutElementDescriptor.Builder> elementBuilders = new ArrayList<>();
private Builder()
{
super();
}
public ASILayout build()
{
return new ASILayout(this);
}
private List<DocumentLayoutElementDescriptor> buildElements()
{
return elementBuilders
.stream()
.map(elementBuilder -> elementBuilder.build())
.collect(GuavaCollectors.toImmutableList());
}
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.add("asiDescriptorId", asiDescriptorId)
.add("caption", caption)
.add("elements-count", elementBuilders.size())
.toString();
}
public Builder setASIDescriptorId(final DocumentId asiDescriptorId)
{
this.asiDescriptorId = asiDescriptorId;
return this;
|
}
public Builder setCaption(final ITranslatableString caption)
{
this.caption = caption;
return this;
}
public Builder setDescription(final ITranslatableString description)
{
this.description = description;
return this;
}
public Builder addElement(final DocumentLayoutElementDescriptor.Builder elementBuilder)
{
Check.assumeNotNull(elementBuilder, "Parameter elementBuilder is not null");
elementBuilders.add(elementBuilder);
return this;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pattribute\ASILayout.java
| 1
|
请完成以下Java代码
|
private OAuth2AccessTokenResponse getTokenResponse(ClientRegistration clientRegistration,
JwtBearerGrantRequest jwtBearerGrantRequest) {
try {
return this.accessTokenResponseClient.getTokenResponse(jwtBearerGrantRequest);
}
catch (OAuth2AuthorizationException ex) {
throw new ClientAuthorizationException(ex.getError(), clientRegistration.getRegistrationId(), ex);
}
}
private boolean hasTokenExpired(OAuth2Token token) {
return this.clock.instant().isAfter(token.getExpiresAt().minus(this.clockSkew));
}
/**
* Sets the client used when requesting an access token credential at the Token
* Endpoint for the {@code jwt-bearer} grant.
* @param accessTokenResponseClient the client used when requesting an access token
* credential at the Token Endpoint for the {@code jwt-bearer} grant
*/
public void setAccessTokenResponseClient(
OAuth2AccessTokenResponseClient<JwtBearerGrantRequest> accessTokenResponseClient) {
Assert.notNull(accessTokenResponseClient, "accessTokenResponseClient cannot be null");
this.accessTokenResponseClient = accessTokenResponseClient;
}
/**
* Sets the resolver used for resolving the {@link Jwt} assertion.
* @param jwtAssertionResolver the resolver used for resolving the {@link Jwt}
* assertion
* @since 5.7
*/
public void setJwtAssertionResolver(Function<OAuth2AuthorizationContext, Jwt> jwtAssertionResolver) {
Assert.notNull(jwtAssertionResolver, "jwtAssertionResolver cannot be null");
this.jwtAssertionResolver = jwtAssertionResolver;
}
/**
* Sets the maximum acceptable clock skew, which is used when checking the
* {@link OAuth2AuthorizedClient#getAccessToken() access token} expiry. The default is
* 60 seconds.
*
|
* <p>
* An access token is considered expired if
* {@code OAuth2AccessToken#getExpiresAt() - clockSkew} is before the current time
* {@code clock#instant()}.
* @param clockSkew the maximum acceptable clock skew
*/
public void setClockSkew(Duration clockSkew) {
Assert.notNull(clockSkew, "clockSkew cannot be null");
Assert.isTrue(clockSkew.getSeconds() >= 0, "clockSkew must be >= 0");
this.clockSkew = clockSkew;
}
/**
* Sets the {@link Clock} used in {@link Instant#now(Clock)} when checking the access
* token expiry.
* @param clock the clock
*/
public void setClock(Clock clock) {
Assert.notNull(clock, "clock cannot be null");
this.clock = clock;
}
}
|
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\JwtBearerOAuth2AuthorizedClientProvider.java
| 1
|
请完成以下Java代码
|
public String toString() {
return new StringJoiner(", ", "{", "}").add("id='" + this.id + "'")
.add("version='" + this.version + "'")
.add("ip='" + this.ip + "'")
.add("country='" + this.country + "'")
.toString();
}
}
/**
* Additional information about what part of the request is invalid.
*/
public static class ErrorStateInformation {
private boolean invalid = true;
private Boolean javaVersion;
private Boolean language;
private Boolean configurationFileFormat;
private Boolean packaging;
private Boolean type;
private InvalidDependencyInformation dependencies;
private String message;
public boolean isInvalid() {
return this.invalid;
}
public Boolean getJavaVersion() {
return this.javaVersion;
}
public void setJavaVersion(Boolean javaVersion) {
this.javaVersion = javaVersion;
}
public Boolean getLanguage() {
return this.language;
}
public void setLanguage(Boolean language) {
this.language = language;
}
public Boolean getConfigurationFileFormat() {
return this.configurationFileFormat;
}
public void setConfigurationFileFormat(Boolean configurationFileFormat) {
this.configurationFileFormat = configurationFileFormat;
}
public Boolean getPackaging() {
return this.packaging;
}
public void setPackaging(Boolean packaging) {
this.packaging = packaging;
}
public Boolean getType() {
return this.type;
}
public void setType(Boolean type) {
this.type = type;
|
}
public InvalidDependencyInformation getDependencies() {
return this.dependencies;
}
public void triggerInvalidDependencies(List<String> dependencies) {
this.dependencies = new InvalidDependencyInformation(dependencies);
}
public String getMessage() {
return this.message;
}
public void setMessage(String message) {
this.message = message;
}
@Override
public String toString() {
return new StringJoiner(", ", "{", "}").add("invalid=" + this.invalid)
.add("javaVersion=" + this.javaVersion)
.add("language=" + this.language)
.add("configurationFileFormat=" + this.configurationFileFormat)
.add("packaging=" + this.packaging)
.add("type=" + this.type)
.add("dependencies=" + this.dependencies)
.add("message='" + this.message + "'")
.toString();
}
}
/**
* Invalid dependencies information.
*/
public static class InvalidDependencyInformation {
private boolean invalid = true;
private final List<String> values;
public InvalidDependencyInformation(List<String> values) {
this.values = values;
}
public boolean isInvalid() {
return this.invalid;
}
public List<String> getValues() {
return this.values;
}
@Override
public String toString() {
return new StringJoiner(", ", "{", "}").add(String.join(", ", this.values)).toString();
}
}
}
|
repos\initializr-main\initializr-actuator\src\main\java\io\spring\initializr\actuate\stat\ProjectRequestDocument.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class SwaggerConfig extends WebMvcConfigurationSupport {
@Bean
public Docket postsApi() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.urunov.controller"))
.paths(regex("/api/v1.*"))
.build()
.apiInfo(metaData());
}
private ApiInfo metaData() {
return new ApiInfoBuilder()
.title("Spring Boot REST API with Swagger")
.description("\"Spring Boot REST API for Employee")
|
.version("1.0.0")
.license("Apache License Version 2.0")
.licenseUrl("https://www.apache.org/licenses/LICENSE-2.0\"")
.contact(new Contact("Urunov Hamdamboy", "https://github.com/urunov/", "myindexu@gamil.com"))
.build();
}
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
//https://springframework.guru/spring-boot-restful-api-documentation-with-swagger-2/#:~:text=Swagger%202%20is%20an%20open,from%20a%20Swagger%2Dcompliant%20API.
|
repos\SpringBoot-Projects-FullStack-master\Part-9.SpringBoot-React-Projects\Project-1.SpringBoot-React-CRUD\fullstack\backendSwagger\src\main\java\com\urunov\configures\SwaggerConfig.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public PageBean listPage(PageParam pageParam, RpMicroSubmitRecord rpMicroSubmitRecord) {
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("storeName", rpMicroSubmitRecord.getStoreName());
paramMap.put("businessCode", rpMicroSubmitRecord.getBusinessCode());
paramMap.put("dCardName", rpMicroSubmitRecord.getIdCardName());
return rpMicroSubmitRecordDao.listPage(pageParam, paramMap);
}
@Override
public void saveData(RpMicroSubmitRecord rpMicroSubmitRecord) {
rpMicroSubmitRecord.setEditTime(new Date());
if (StringUtil.isEmpty(rpMicroSubmitRecord.getStatus())) {
rpMicroSubmitRecord.setStatus(PublicEnum.YES.name());
}
rpMicroSubmitRecordDao.insert(rpMicroSubmitRecord);
}
@Override
public Map<String, Object> microSubmit(RpMicroSubmitRecord rpMicroSubmitRecord) {
rpMicroSubmitRecord.setBusinessCode(StringUtil.get32UUID());
rpMicroSubmitRecord.setIdCardValidTime("[\"" + rpMicroSubmitRecord.getIdCardValidTimeBegin() + "\",\"" + rpMicroSubmitRecord.getIdCardValidTimeEnd() + "\"]");
Map<String, Object> returnMap = WeiXinMicroUtils.microSubmit(rpMicroSubmitRecord);
rpMicroSubmitRecord.setStoreStreet(WxCityNo.getCityNameByNo(rpMicroSubmitRecord.getStoreAddressCode()) + ":" + rpMicroSubmitRecord.getStoreStreet());
if ("SUCCESS".equals(returnMap.get("result_code"))) {
saveData(rpMicroSubmitRecord);
}
|
return returnMap;
}
@Override
public Map<String, Object> microQuery(String businessCode) {
Map<String, Object> returnMap = WeiXinMicroUtils.microQuery(businessCode);
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("businessCode", businessCode);
RpMicroSubmitRecord rpMicroSubmitRecord = rpMicroSubmitRecordDao.getBy(paramMap);
if (StringUtil.isNotNull(returnMap.get("sub_mch_id")) && StringUtil.isEmpty(rpMicroSubmitRecord.getSubMchId())) {
rpMicroSubmitRecord.setSubMchId(String.valueOf(returnMap.get("sub_mch_id")));
rpMicroSubmitRecordDao.update(rpMicroSubmitRecord);
}
return returnMap;
}
}
|
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\service\impl\RpMicroSubmitRecordServiceImpl.java
| 2
|
请完成以下Java代码
|
public void setIsApplyToLUs (final boolean IsApplyToLUs)
{
set_Value (COLUMNNAME_IsApplyToLUs, IsApplyToLUs);
}
@Override
public boolean isApplyToLUs()
{
return get_ValueAsBoolean(COLUMNNAME_IsApplyToLUs);
}
@Override
public void setIsApplyToTUs (final boolean IsApplyToTUs)
{
set_Value (COLUMNNAME_IsApplyToTUs, IsApplyToTUs);
}
@Override
public boolean isApplyToTUs()
{
return get_ValueAsBoolean(COLUMNNAME_IsApplyToTUs);
}
@Override
public void setIsAutoPrint (final boolean IsAutoPrint)
{
set_Value (COLUMNNAME_IsAutoPrint, IsAutoPrint);
}
@Override
public boolean isAutoPrint()
{
return get_ValueAsBoolean(COLUMNNAME_IsAutoPrint);
}
@Override
public void setLabelReport_Process_ID (final int LabelReport_Process_ID)
{
if (LabelReport_Process_ID < 1)
set_Value (COLUMNNAME_LabelReport_Process_ID, null);
else
set_Value (COLUMNNAME_LabelReport_Process_ID, LabelReport_Process_ID);
}
@Override
public int getLabelReport_Process_ID()
{
return get_ValueAsInt(COLUMNNAME_LabelReport_Process_ID);
|
}
@Override
public void setM_HU_Label_Config_ID (final int M_HU_Label_Config_ID)
{
if (M_HU_Label_Config_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_HU_Label_Config_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_HU_Label_Config_ID, M_HU_Label_Config_ID);
}
@Override
public int getM_HU_Label_Config_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_Label_Config_ID);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_Label_Config.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getUPC() {
return upc;
}
/**
* Sets the value of the upc property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setUPC(String value) {
this.upc = value;
}
/**
* Gets the value of the gln property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getGLN() {
return gln;
}
/**
* Sets the value of the gln property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setGLN(String value) {
this.gln = value;
}
/**
* Gets the value of the storeGLN property.
*
|
* @return
* possible object is
* {@link String }
*
*/
public String getStoreGLN() {
return storeGLN;
}
/**
* Sets the value of the storeGLN property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setStoreGLN(String value) {
this.storeGLN = value;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_metasfreshinhousev2\de\metas\edi\esb\jaxb\metasfreshinhousev2\EDIMHUPIItemProductLookupUPCVType.java
| 2
|
请完成以下Java代码
|
public class C_ElementValue
{
private final IAcctSchemaDAO acctSchemasRepo;
private final IAccountDAO accountDAO;
private final TreeNodeService treeNodeService;
private static final AtomicBoolean updateTreeNodeDisabled = new AtomicBoolean(false);
public C_ElementValue(
@NonNull final IAcctSchemaDAO acctSchemasRepo,
@NonNull final IAccountDAO accountDAO,
@NonNull final TreeNodeService treeNodeService)
{
this.acctSchemasRepo = acctSchemasRepo;
this.accountDAO = accountDAO;
this.treeNodeService = treeNodeService;
}
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE })
public void beforeSave(final I_C_ElementValue elementValue)
{
validate(elementValue);
}
private void validate(final I_C_ElementValue elementValue)
{
if (elementValue.isAutoTaxAccount() && elementValue.getC_Tax_ID() <= 0)
{
throw new FillMandatoryException(I_C_ElementValue.COLUMNNAME_C_Tax_ID);
}
}
@ModelChange(timings = { ModelValidator.TYPE_AFTER_NEW, ModelValidator.TYPE_AFTER_CHANGE })
public void afterSave(final I_C_ElementValue elementValue)
{
createValidCombinationIfNeeded(elementValue);
}
@VisibleForTesting
protected void createValidCombinationIfNeeded(final I_C_ElementValue elementValue)
{
if (elementValue.isSummary())
{
return;
}
final AccountDimension.Builder accountDimensionTemplate = AccountDimension.builder()
//.setAcctSchemaId(acctSchema.getId())
.setC_ElementValue_ID(elementValue.getC_ElementValue_ID())
.setAD_Client_ID(elementValue.getAD_Client_ID())
.setAD_Org_ID(OrgId.ANY.getRepoId());
final ChartOfAccountsId chartOfAccountsId = ChartOfAccountsId.ofRepoId(elementValue.getC_Element_ID());
|
for (final AcctSchema acctSchema : acctSchemasRepo.getByChartOfAccountsId(chartOfAccountsId))
{
accountDAO.getOrCreateWithinTrx(accountDimensionTemplate.setAcctSchemaId(acctSchema.getId()).build());
}
}
public static IAutoCloseable temporaryDisableUpdateTreeNode()
{
final boolean wasDisabled = updateTreeNodeDisabled.getAndSet(true);
return () -> updateTreeNodeDisabled.set(wasDisabled);
}
@ModelChange(timings = { ModelValidator.TYPE_AFTER_CHANGE }, ifColumnsChanged = { I_C_ElementValue.COLUMNNAME_Parent_ID, I_C_ElementValue.COLUMNNAME_SeqNo })
public void updateTreeNode(final I_C_ElementValue record)
{
if (updateTreeNodeDisabled.get())
{
return;
}
final ElementValue elementValue = ElementValueRepository.fromRecord(record);
treeNodeService.updateTreeNode(elementValue);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\interceptor\C_ElementValue.java
| 1
|
请完成以下Java代码
|
public void invalidateCacheByUserId(@NonNull final UserId invokerId)
{
final SynchronizedMutable<ComputedWorkflowLaunchers> userCachedWorkflows = launchersCache.get(invokerId);
if (userCachedWorkflows != null)
{
userCachedWorkflows.setValue(null);
}
}
public QueryLimit getLaunchersLimit()
{
final int limitInt = sysConfigBL.getIntValue(Constants.SYSCONFIG_LaunchersLimit, -100);
return limitInt == -100
? Constants.DEFAULT_LaunchersLimit
: QueryLimit.ofInt(limitInt);
}
//
//
//
//
//
//
@Value
@Builder
private static class ComputedWorkflowLaunchers
{
@NonNull WorkflowLaunchersList list;
@NonNull WorkflowLaunchersQuery validationKey;
private ComputedWorkflowLaunchers(@NonNull final WorkflowLaunchersList list, @NonNull final WorkflowLaunchersQuery validationKey)
{
this.list = list;
this.validationKey = validationKey;
}
public static ComputedWorkflowLaunchers ofListAndQuery(@NonNull final WorkflowLaunchersList list, @NonNull final WorkflowLaunchersQuery query)
|
{
return new ComputedWorkflowLaunchers(list, toValidationKey(query));
}
private static WorkflowLaunchersQuery toValidationKey(@NonNull final WorkflowLaunchersQuery query)
{
return query.toBuilder()
.maxStaleAccepted(Duration.ZERO)
.build();
}
public boolean matches(@NonNull final WorkflowLaunchersQuery query)
{
if (list.isStaled(query.getMaxStaleAccepted()))
{
return false;
}
final WorkflowLaunchersQuery validationKeyExpected = toValidationKey(query);
return validationKey.equals(validationKeyExpected);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.picking.rest-api\src\main\java\de\metas\picking\workflow\lauchers\PickingWorkflowLaunchersProvider.java
| 1
|
请完成以下Java代码
|
private void setSalesOrPurchaseReference(
final ITableRecordReference r,
final Object model)
{
final String soTrxColName1 = "IsSOTrx";
final String soTrxColName2 = "SOTrx";
if (!InterfaceWrapperHelper.hasModelColumnName(model, soTrxColName1) && !InterfaceWrapperHelper.hasModelColumnName(model, soTrxColName2))
{
return;
}
final Boolean soTrx = CoalesceUtil.coalesceSuppliers(
() -> InterfaceWrapperHelper.getValueOrNull(model, soTrxColName1),
() -> InterfaceWrapperHelper.getValueOrNull(model, soTrxColName2));
if (soTrx == null)
{
return;
}
|
if (soTrx)
{
lastSalesReference = r;
lastSalesReferenceSeen = de.metas.common.util.time.SystemTime.asDate();
}
else
{
lastPurchaseReference = r;
lastPurchaseReferenceSeen = SystemTime.asDate();
}
}
@Override
public String toString()
{
return "SalesPurchaseWatchDog [lastSalesReference=" + lastSalesReference + ", lastPurchaseReference=" + lastPurchaseReference + "]";
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\partitioner\impl\SalesPurchaseWatchDog.java
| 1
|
请完成以下Java代码
|
private boolean isTrustedPackage(String requestedType) {
if (!this.trustedPackages.isEmpty()) {
String packageName = ClassUtils.getPackageName(requestedType).replaceFirst("\\[L", "");
for (String trustedPackage : this.trustedPackages) {
if (PatternMatchUtils.simpleMatch(trustedPackage, packageName)) {
return true;
}
}
return false;
}
return true;
}
@Override
public void fromJavaType(JavaType javaType, Headers headers) {
String classIdFieldName = getClassIdFieldName();
if (headers.lastHeader(classIdFieldName) != null) {
removeHeaders(headers);
}
addHeader(headers, classIdFieldName, javaType.getRawClass());
if (javaType.isContainerType() && !javaType.isArrayType()) {
addHeader(headers, getContentClassIdFieldName(), javaType.getContentType().getRawClass());
}
if (javaType.getKeyType() != null) {
addHeader(headers, getKeyClassIdFieldName(), javaType.getKeyType().getRawClass());
}
}
@Override
public void fromClass(Class<?> clazz, Headers headers) {
fromJavaType(TypeFactory.defaultInstance().constructType(clazz), headers);
}
@Override
|
public @Nullable Class<?> toClass(Headers headers) {
JavaType javaType = toJavaType(headers);
return javaType == null ? null : javaType.getRawClass();
}
@Override
public void removeHeaders(Headers headers) {
try {
headers.remove(getClassIdFieldName());
headers.remove(getContentClassIdFieldName());
headers.remove(getKeyClassIdFieldName());
}
catch (Exception e) { // NOSONAR
// NOSONAR
}
}
}
|
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\mapping\DefaultJackson2JavaTypeMapper.java
| 1
|
请完成以下Java代码
|
public Flux<Map<String, Object>> routes() {
return this.routeLocator.getRoutes().map(this::serialize);
}
Map<String, Object> serialize(Route route) {
HashMap<String, Object> r = new HashMap<>();
r.put("route_id", route.getId());
r.put("uri", route.getUri().toString());
r.put("order", route.getOrder());
r.put("predicate", route.getPredicate().toString());
if (!CollectionUtils.isEmpty(route.getMetadata())) {
r.put("metadata", route.getMetadata());
}
ArrayList<String> filters = new ArrayList<>();
for (int i = 0; i < route.getFilters().size(); i++) {
GatewayFilter gatewayFilter = route.getFilters().get(i);
filters.add(gatewayFilter.toString());
}
|
r.put("filters", filters);
return r;
}
@GetMapping("/routes/{id}")
public Mono<ResponseEntity<Map<String, Object>>> route(@PathVariable String id) {
// @formatter:off
return this.routeLocator.getRoutes()
.filter(route -> route.getId().equals(id))
.singleOrEmpty()
.map(this::serialize)
.map(ResponseEntity::ok)
.switchIfEmpty(Mono.just(ResponseEntity.notFound().build()));
// @formatter:on
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\actuate\GatewayControllerEndpoint.java
| 1
|
请完成以下Java代码
|
public class StorageManager {
public static final String STORAGE_ROOT_FOLDER = "storage";
public static EmbeddedStorageManager initializeStorageWithStringAsRoot(Path directory, String root) {
EmbeddedStorageManager storageManager = EmbeddedStorage.start(directory);
storageManager.setRoot(root);
storageManager.storeRoot();
return storageManager;
}
public static EmbeddedStorageManager initializeStorageWithCustomTypeAsRoot(Path directory, String root) {
EmbeddedStorageManager storageManager = EmbeddedStorage.start(directory);
storageManager.setRoot(new RootInstance(root));
storageManager.storeRoot();
return storageManager;
}
public static EmbeddedStorageManager initializeStorageWithCustomTypeAsRoot(Path directory, String root, List<Book> booksToStore) {
EmbeddedStorageManager storageManager = EmbeddedStorage.start(directory);
RootInstance rootInstance = new RootInstance(root);
storageManager.setRoot(rootInstance);
storageManager.storeRoot();
List<Book> books = rootInstance.getBooks();
books.addAll(booksToStore);
storageManager.store(books);
return storageManager;
}
public static EmbeddedStorageManager loadOrCreateStorageWithCustomTypeAsRoot(Path directory, String root) {
EmbeddedStorageManager storageManager = EmbeddedStorage.start(directory);
if (storageManager.root() == null) {
|
RootInstance rootInstance = new RootInstance(root);
storageManager.setRoot(rootInstance);
storageManager.storeRoot();
}
return storageManager;
}
public static EmbeddedStorageManager lazyLoadOrCreateStorageWithCustomTypeAsRoot(Path directory, String root, List<Book> booksToStore) {
EmbeddedStorageManager storageManager = EmbeddedStorage.start(directory);
if (storageManager.root() == null) {
RootInstanceLazy rootInstance = new RootInstanceLazy(root);
rootInstance.getBooks().addAll(booksToStore);
storageManager.setRoot(rootInstance);
storageManager.storeRoot();
}
return storageManager;
}
}
|
repos\tutorials-master\persistence-modules\core-java-persistence-2\src\main\java\com\baeldung\microstream\StorageManager.java
| 1
|
请完成以下Java代码
|
private static Object convertValueToType(@Nullable final Object valueObj, @NonNull final FTSJoinColumn.ValueType valueType)
{
if (valueObj == null)
{
return null;
}
if (valueType == FTSJoinColumn.ValueType.INTEGER)
{
return NumberUtils.asIntegerOrNull(valueObj);
}
else if (valueType == FTSJoinColumn.ValueType.STRING)
{
return valueObj.toString();
}
else
|
{
throw new AdempiereException("Cannot convert `" + valueObj + "` (" + valueObj.getClass() + ") to " + valueType);
}
}
private static String toJson(@NonNull final SearchHit hit)
{
return Strings.toString(hit, true, true);
}
public FTSConfig getConfigById(@NonNull final FTSConfigId ftsConfigId)
{
return ftsConfigService.getConfigById(ftsConfigId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.elasticsearch\src\main\java\de\metas\fulltextsearch\query\FTSSearchService.java
| 1
|
请完成以下Java代码
|
public int getAD_Table_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Table_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Referenced Document.
@param C_ReferenceNo_Doc_ID Referenced Document */
@Override
public void setC_ReferenceNo_Doc_ID (int C_ReferenceNo_Doc_ID)
{
if (C_ReferenceNo_Doc_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_ReferenceNo_Doc_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_ReferenceNo_Doc_ID, Integer.valueOf(C_ReferenceNo_Doc_ID));
}
/** Get Referenced Document.
@return Referenced Document */
@Override
public int getC_ReferenceNo_Doc_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_ReferenceNo_Doc_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public de.metas.document.refid.model.I_C_ReferenceNo getC_ReferenceNo() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_C_ReferenceNo_ID, de.metas.document.refid.model.I_C_ReferenceNo.class);
}
@Override
public void setC_ReferenceNo(de.metas.document.refid.model.I_C_ReferenceNo C_ReferenceNo)
{
set_ValueFromPO(COLUMNNAME_C_ReferenceNo_ID, de.metas.document.refid.model.I_C_ReferenceNo.class, C_ReferenceNo);
}
/** Set Reference No.
@param C_ReferenceNo_ID Reference No */
@Override
public void setC_ReferenceNo_ID (int C_ReferenceNo_ID)
{
if (C_ReferenceNo_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_ReferenceNo_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_ReferenceNo_ID, Integer.valueOf(C_ReferenceNo_ID));
}
/** Get Reference No.
@return Reference No */
@Override
public int getC_ReferenceNo_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_ReferenceNo_ID);
if (ii == null)
|
return 0;
return ii.intValue();
}
/** Set Datensatz-ID.
@param Record_ID
Direct internal record ID
*/
@Override
public void setRecord_ID (int Record_ID)
{
if (Record_ID < 0)
set_ValueNoCheck (COLUMNNAME_Record_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID));
}
/** Get Datensatz-ID.
@return Direct internal record ID
*/
@Override
public int getRecord_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.document.refid\src\main\java-gen\de\metas\document\refid\model\X_C_ReferenceNo_Doc.java
| 1
|
请完成以下Java代码
|
public void clearDataSource() {
configAttributeMap.clear();
configAttributeMap = null;
}
@Override
public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
if (configAttributeMap == null) this.loadDataSource();
List<ConfigAttribute> configAttributes = new ArrayList<>();
//获取当前访问的路径
String url = ((FilterInvocation) o).getRequestUrl();
String path = URLUtil.getPath(url);
PathMatcher pathMatcher = new AntPathMatcher();
Iterator<String> iterator = configAttributeMap.keySet().iterator();
//获取访问该路径所需资源
while (iterator.hasNext()) {
String pattern = iterator.next();
if (pathMatcher.match(pattern, path)) {
configAttributes.add(configAttributeMap.get(pattern));
}
|
}
// 未设置操作请求权限,返回空集合
return configAttributes;
}
@Override
public Collection<ConfigAttribute> getAllConfigAttributes() {
return null;
}
@Override
public boolean supports(Class<?> aClass) {
return true;
}
}
|
repos\mall-master\mall-security\src\main\java\com\macro\mall\security\component\DynamicSecurityMetadataSource.java
| 1
|
请完成以下Java代码
|
public void setExitDependentPlanItems(List<PlanItem> exitDependentPlanItems) {
this.exitDependentPlanItems = exitDependentPlanItems;
}
public void addExitDependentPlanItem(PlanItem planItem) {
Optional<PlanItem> planItemWithSameId = exitDependentPlanItems.stream().filter(p -> p.getId().equals(planItem.getId())).findFirst();
if (!planItemWithSameId.isPresent()) {
exitDependentPlanItems.add(planItem);
}
}
public List<PlanItem> getAllDependentPlanItems() {
List<PlanItem> allDependentPlanItems = new ArrayList<>(entryDependentPlanItems.size() + exitDependentPlanItems.size());
allDependentPlanItems.addAll(entryDependentPlanItems);
allDependentPlanItems.addAll(exitDependentPlanItems);
return allDependentPlanItems;
}
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder("PlanItem");
|
if (getName() != null) {
stringBuilder.append(" '").append(getName()).append("'");
}
stringBuilder.append(" (id: ");
stringBuilder.append(getId());
if (getPlanItemDefinition() != null) {
stringBuilder.append(", definitionId: ").append(getPlanItemDefinition().getId());
}
stringBuilder.append(")");
return stringBuilder.toString();
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\PlanItem.java
| 1
|
请完成以下Java代码
|
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Association.class, BPMN_ELEMENT_ASSOCIATION)
.namespaceUri(BPMN20_NS)
.extendsType(Artifact.class)
.instanceProvider(new ModelTypeInstanceProvider<Association>() {
public Association newInstance(ModelTypeInstanceContext instanceContext) {
return new AssociationImpl(instanceContext);
}
});
sourceRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_SOURCE_REF)
.required()
.qNameAttributeReference(BaseElement.class)
.build();
targetRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_TARGET_REF)
.required()
.qNameAttributeReference(BaseElement.class)
.build();
associationDirectionAttribute = typeBuilder.enumAttribute(BPMN_ATTRIBUTE_ASSOCIATION_DIRECTION, AssociationDirection.class)
.defaultValue(AssociationDirection.None)
.build();
typeBuilder.build();
}
public AssociationImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
}
public BaseElement getSource() {
return sourceRefAttribute.getReferenceTargetElement(this);
}
public void setSource(BaseElement source) {
sourceRefAttribute.setReferenceTargetElement(this, source);
|
}
public BaseElement getTarget() {
return targetRefAttribute.getReferenceTargetElement(this);
}
public void setTarget(BaseElement target) {
targetRefAttribute.setReferenceTargetElement(this, target);
}
public AssociationDirection getAssociationDirection() {
return associationDirectionAttribute.getValue(this);
}
public void setAssociationDirection(AssociationDirection associationDirection) {
associationDirectionAttribute.setValue(this, associationDirection);
}
public BpmnEdge getDiagramElement() {
return (BpmnEdge) super.getDiagramElement();
}
}
|
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\AssociationImpl.java
| 1
|
请完成以下Java代码
|
private int getC_BPartner_Location_ID_ToUse()
{
if (_bpartnerLocationId > 0)
{
return _bpartnerLocationId;
}
final I_C_BPartner bpartner = _bpartner;
if (bpartner != null)
{
final I_C_BPartner_Location bpLocation = bpartnerDAO.retrieveShipToLocation(getCtx(), bpartner.getC_BPartner_ID(), ITrx.TRXNAME_None);
if (bpLocation != null)
{
return bpLocation.getC_BPartner_Location_ID();
}
}
return -1;
}
@Override
public IReturnsInOutProducer setMovementType(final String movementType)
{
assertConfigurable();
_movementType = movementType;
return this;
}
public IReturnsInOutProducer setManualReturnInOut(final I_M_InOut manualReturnInOut)
{
assertConfigurable();
_manualReturnInOut = manualReturnInOut;
return this;
}
private String getMovementTypeToUse()
{
Check.assumeNotNull(_movementType, "movementType not null");
return _movementType;
}
@Override
public IReturnsInOutProducer setM_Warehouse(final I_M_Warehouse warehouse)
{
assertConfigurable();
_warehouse = warehouse;
return this;
}
private final int getM_Warehouse_ID_ToUse()
{
if (_warehouse != null)
{
return _warehouse.getM_Warehouse_ID();
}
return -1;
}
|
@Override
public IReturnsInOutProducer setMovementDate(final Date movementDate)
{
Check.assumeNotNull(movementDate, "movementDate not null");
_movementDate = movementDate;
return this;
}
protected final Timestamp getMovementDateToUse()
{
if (_movementDate != null)
{
return TimeUtil.asTimestamp(_movementDate);
}
final Properties ctx = getCtx();
final Timestamp movementDate = Env.getDate(ctx); // use Login date (08306)
return movementDate;
}
@Override
public IReturnsInOutProducer setC_Order(final I_C_Order order)
{
assertConfigurable();
_order = order;
return this;
}
protected I_C_Order getC_Order()
{
return _order;
}
@Override
public IReturnsInOutProducer dontComplete()
{
_complete = false;
return this;
}
protected boolean isComplete()
{
return _complete;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inout\returns\AbstractReturnsInOutProducer.java
| 1
|
请完成以下Java代码
|
public class DokumentAbfragen {
@XmlElement(namespace = "")
protected String clientSoftwareKennung;
@XmlElement(namespace = "")
protected DokumentAbfragenType dokumentAbfragenType;
/**
* Gets the value of the clientSoftwareKennung property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getClientSoftwareKennung() {
return clientSoftwareKennung;
}
/**
* Sets the value of the clientSoftwareKennung property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setClientSoftwareKennung(String value) {
this.clientSoftwareKennung = value;
|
}
/**
* Gets the value of the dokumentAbfragenType property.
*
* @return
* possible object is
* {@link DokumentAbfragenType }
*
*/
public DokumentAbfragenType getDokumentAbfragenType() {
return dokumentAbfragenType;
}
/**
* Sets the value of the dokumentAbfragenType property.
*
* @param value
* allowed object is
* {@link DokumentAbfragenType }
*
*/
public void setDokumentAbfragenType(DokumentAbfragenType value) {
this.dokumentAbfragenType = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v2\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v2\DokumentAbfragen.java
| 1
|
请完成以下Java代码
|
public Category name(String name) {
this.name = name;
return this;
}
/**
* Get name
* @return name
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
@JsonProperty(JSON_PROPERTY_NAME)
@JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Category category = (Category) o;
return Objects.equals(this.id, category.id) &&
Objects.equals(this.name, category.name);
|
}
@Override
public int hashCode() {
return Objects.hash(id, name);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Category {\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append(" name: ").append(toIndentedString(name)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
repos\tutorials-master\spring-swagger-codegen-modules\spring-openapi-generator-api-client\src\main\java\com\baeldung\petstore\client\model\Category.java
| 1
|
请完成以下Java代码
|
public static void zip(Path file, Path destination) throws IOException {
try (InputStream input = Files.newInputStream(file);
OutputStream output = Files.newOutputStream(destination);
ZipArchiveOutputStream archive = new ZipArchiveOutputStream(output)) {
archive.setLevel(Deflater.BEST_COMPRESSION);
archive.setMethod(ZipEntry.DEFLATED);
archive.putArchiveEntry(new ZipArchiveEntry(file.getFileName()
.toString()));
IOUtils.copy(input, archive);
archive.closeArchiveEntry();
}
}
public static void extractOne(Path archivePath, String fileName, Path destinationDirectory) throws IOException, ArchiveException {
try (InputStream input = Files.newInputStream(archivePath);
BufferedInputStream buffer = new BufferedInputStream(input);
ArchiveInputStream<?> archive = new ArchiveStreamFactory().createArchiveInputStream(buffer)) {
|
ArchiveEntry entry;
while ((entry = archive.getNextEntry()) != null) {
if (entry.getName()
.equals(fileName)) {
Path outFile = destinationDirectory.resolve(fileName);
Files.createDirectories(outFile.getParent());
try (OutputStream os = Files.newOutputStream(outFile)) {
IOUtils.copy(archive, os);
}
break;
}
}
}
}
}
|
repos\tutorials-master\libraries-apache-commons-2\src\main\java\com\baeldung\commons\compress\CompressUtils.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl());
}
@Order(1)
@Bean
public SecurityFilterChain clientFilterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(auth -> auth
.requestMatchers(new AntPathRequestMatcher("/"))
.permitAll()
.anyRequest()
.authenticated());
http.oauth2Login(Customizer.withDefaults())
.logout(logout -> logout.addLogoutHandler(keycloakLogoutHandler)
.logoutSuccessUrl("/"));
return http.build();
}
|
@Order(2)
@Bean
public SecurityFilterChain resourceServerFilterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(auth -> auth
.requestMatchers(new AntPathRequestMatcher("/customers*", "/users*"))
.hasRole("USER")
.anyRequest()
.authenticated());
http.oauth2ResourceServer((oauth2) -> oauth2
.jwt(Customizer.withDefaults()));
return http.build();
}
@Bean
public AuthenticationManager authenticationManager(HttpSecurity http) throws Exception {
return http.getSharedObject(AuthenticationManagerBuilder.class)
.build();
}
}
|
repos\tutorials-master\spring-boot-modules\spring-boot-keycloak-adapters\src\main\java\com\baeldung\keycloak\SecurityConfig.java
| 2
|
请完成以下Java代码
|
public final String getAccountNo()
{
return orgBankAccount.getAccountNo();
}
public String getIBAN()
{
return orgBankAccount.getIBAN();
}
public ClientSetup setIBAN(final String iban)
{
if (!Check.isEmpty(iban, true))
{
orgBankAccount.setIBAN(iban.trim());
}
return this;
}
public ClientSetup setC_Bank_ID(final int bankId)
{
if (bankId > 0)
{
orgBankAccount.setC_Bank_ID(bankId);
}
return this;
}
public final int getC_Bank_ID()
{
return orgBankAccount.getC_Bank_ID();
}
public ClientSetup setPhone(final String phone)
{
if (!Check.isEmpty(phone, true))
{
// NOTE: we are not setting the Phone, Fax, EMail on C_BPartner_Location because those fields are hidden in BPartner window
orgContact.setPhone(phone.trim());
}
return this;
}
public final String getPhone()
{
return orgContact.getPhone();
}
public ClientSetup setFax(final String fax)
{
if (!Check.isEmpty(fax, true))
{
// NOTE: we are not setting the Phone, Fax, EMail on C_BPartner_Location because those fields are hidden in BPartner window
orgContact.setFax(fax.trim());
}
return this;
|
}
public final String getFax()
{
return orgContact.getFax();
}
public ClientSetup setEMail(final String email)
{
if (!Check.isEmpty(email, true))
{
// NOTE: we are not setting the Phone, Fax, EMail on C_BPartner_Location because those fields are hidden in BPartner window
orgContact.setEMail(email.trim());
}
return this;
}
public final String getEMail()
{
return orgContact.getEMail();
}
public ClientSetup setBPartnerDescription(final String bpartnerDescription)
{
if (Check.isEmpty(bpartnerDescription, true))
{
return this;
}
orgBPartner.setDescription(bpartnerDescription.trim());
return this;
}
public String getBPartnerDescription()
{
return orgBPartner.getDescription();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java\de\metas\fresh\setup\process\ClientSetup.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class OutputService {
private Logger logger = LoggerFactory.getLogger(ParsingService.class);
public enum OutputType {
CSV, TSV, FIXED_WIDTH
};
public boolean writeData(List<Object[]> products, OutputType outputType, String outputPath) {
try (Writer outputWriter = new OutputStreamWriter(new FileOutputStream(new File(outputPath)), "UTF-8")) {
switch (outputType) {
case CSV: {
CsvWriter writer = new CsvWriter(outputWriter, new CsvWriterSettings());
writer.writeRowsAndClose(products);
}
break;
case TSV: {
TsvWriter writer = new TsvWriter(outputWriter, new TsvWriterSettings());
writer.writeRowsAndClose(products);
}
break;
case FIXED_WIDTH: {
FixedWidthFields fieldLengths = new FixedWidthFields(8, 30, 10);
FixedWidthWriterSettings settings = new FixedWidthWriterSettings(fieldLengths);
FixedWidthWriter writer = new FixedWidthWriter(outputWriter, settings);
writer.writeRowsAndClose(products);
}
break;
default:
logger.warn("Invalid OutputType: " + outputType);
return false;
}
return true;
} catch (IOException e) {
logger.error(e.getMessage());
return false;
}
}
|
public boolean writeBeanToFixedWidthFile(List<Product> products, String outputPath) {
try (Writer outputWriter = new OutputStreamWriter(new FileOutputStream(new File(outputPath)), "UTF-8")) {
BeanWriterProcessor<Product> rowProcessor = new BeanWriterProcessor<Product>(Product.class);
FixedWidthFields fieldLengths = new FixedWidthFields(8, 30, 10);
FixedWidthWriterSettings settings = new FixedWidthWriterSettings(fieldLengths);
settings.setHeaders("product_no", "description", "unit_price");
settings.setRowWriterProcessor(rowProcessor);
FixedWidthWriter writer = new FixedWidthWriter(outputWriter, settings);
writer.writeHeaders();
for (Product product : products) {
writer.processRecord(product);
}
writer.close();
return true;
} catch (IOException e) {
logger.error(e.getMessage());
return false;
}
}
}
|
repos\tutorials-master\libraries-data-2\src\main\java\com\baeldung\univocity\OutputService.java
| 2
|
请完成以下Java代码
|
public final class NullHUTrxListener implements IHUTrxListener
{
public static final NullHUTrxListener instance = new NullHUTrxListener();
private NullHUTrxListener()
{
super();
}
@Override
public void trxLineProcessed(final IHUContext huContext, final I_M_HU_Trx_Line trxLine)
{
// nothing
}
@Override
public void huParentChanged(final I_M_HU hu, final I_M_HU_Item parentHUItemOld)
{
// nothing
}
@Override
public void afterTrxProcessed(final IReference<I_M_HU_Trx_Hdr> trxHdrRef, final List<I_M_HU_Trx_Line> trxLines)
{
// nothing
}
@Override
public void afterLoad(final IHUContext huContext, final List<IAllocationResult> loadResults)
|
{
// nothing;
}
@Override
public void onUnloadLoadTransaction(final IHUContext huContext, final IHUTransactionCandidate unloadTrx, final IHUTransactionCandidate loadTrx)
{
// nothing
}
@Override
public void onSplitTransaction(final IHUContext huContext, final IHUTransactionCandidate unloadTrx, final IHUTransactionCandidate loadTrx)
{
// nothing
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\NullHUTrxListener.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Money computeProjectedOverUnderAmt(@NonNull final AllocationAmounts amountsToAllocate)
{
return computeOpenAmtRemainingToAllocate().subtract(amountsToAllocate.getTotalAmt());
}
@NonNull
private Money computeOpenAmtRemainingToAllocate()
{
return openAmtInitial.subtract(amountsAllocated.getTotalAmt());
}
@NonNull
public Money getTotalAllocatedAmount()
{
return amountsAllocated.getTotalAmt();
}
|
public boolean isFullyAllocated()
{
return amountsToAllocate.getTotalAmt().isZero();
}
public boolean isARC()
{
return isCreditMemo() && getSoTrx().isSales();
}
public boolean isAPI()
{
return !isCreditMemo() && getSoTrx().isPurchase();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\payment\paymentallocation\service\PayableDocument.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public Map<String, Integer> getProdIdCountMap() {
return prodIdCountMap;
}
public void setProdIdCountMap(Map<String, Integer> prodIdCountMap) {
this.prodIdCountMap = prodIdCountMap;
}
public Integer getPayModeCode() {
return payModeCode;
}
public void setPayModeCode(Integer payModeCode) {
this.payModeCode = payModeCode;
}
public String getReceiptId() {
return receiptId;
}
public void setReceiptId(String receiptId) {
this.receiptId = receiptId;
}
public String getLocationId() {
return locationId;
}
public void setLocationId(String locationId) {
this.locationId = locationId;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public Map<ProductEntity, Integer> getProdEntityCountMap() {
return prodEntityCountMap;
}
public void setProdEntityCountMap(Map<ProductEntity, Integer> prodEntityCountMap) {
|
this.prodEntityCountMap = prodEntityCountMap;
}
public String getProdIdCountJson() {
return prodIdCountJson;
}
public void setProdIdCountJson(String prodIdCountJson) {
this.prodIdCountJson = prodIdCountJson;
}
@Override
public String toString() {
return "OrderInsertReq{" +
"userId='" + userId + '\'' +
", prodIdCountJson='" + prodIdCountJson + '\'' +
", prodIdCountMap=" + prodIdCountMap +
", prodEntityCountMap=" + prodEntityCountMap +
", payModeCode=" + payModeCode +
", receiptId='" + receiptId + '\'' +
", locationId='" + locationId + '\'' +
", remark='" + remark + '\'' +
'}';
}
}
|
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\req\order\OrderInsertReq.java
| 2
|
请完成以下Java代码
|
private static String extractClassnameOrNull(@NonNull final I_AD_Process adProcess)
{
if (!Check.isEmpty(adProcess.getClassname(), true))
{
return adProcess.getClassname();
}
return null;
}
private static final class ProcessPreconditionsResolutionSupplier implements Supplier<ProcessPreconditionsResolution>
{
private final IProcessPreconditionsContext preconditionsContext;
private final ProcessDescriptor processDescriptor;
@Builder
private ProcessPreconditionsResolutionSupplier(
@NonNull final IProcessPreconditionsContext preconditionsContext,
@NonNull final ProcessDescriptor processDescriptor)
{
this.preconditionsContext = preconditionsContext;
this.processDescriptor = processDescriptor;
}
@Override
public ProcessPreconditionsResolution get()
{
return processDescriptor.checkPreconditionsApplicable(preconditionsContext);
}
}
private static final class ProcessParametersCallout
{
private static void forwardValueToCurrentProcessInstance(final ICalloutField calloutField)
{
final JavaProcess processInstance = JavaProcess.currentInstance();
final String parameterName = calloutField.getColumnName();
final IRangeAwareParams source = createSource(calloutField);
// Ask the instance to load the parameter
processInstance.loadParameterValueNoFail(parameterName, source);
}
private static IRangeAwareParams createSource(final ICalloutField calloutField)
{
final String parameterName = calloutField.getColumnName();
final Object fieldValue = calloutField.getValue();
if (fieldValue instanceof LookupValue)
{
final Object idObj = ((LookupValue)fieldValue).getId();
return ProcessParams.ofValueObject(parameterName, idObj);
}
else if (fieldValue instanceof DateRangeValue)
{
|
final DateRangeValue dateRange = (DateRangeValue)fieldValue;
return ProcessParams.of(
parameterName,
TimeUtil.asDate(dateRange.getFrom()),
TimeUtil.asDate(dateRange.getTo()));
}
else
{
return ProcessParams.ofValueObject(parameterName, fieldValue);
}
}
}
private static final class ProcessParametersDataBindingDescriptorBuilder implements DocumentEntityDataBindingDescriptorBuilder
{
public static final ProcessParametersDataBindingDescriptorBuilder instance = new ProcessParametersDataBindingDescriptorBuilder();
private static final DocumentEntityDataBindingDescriptor dataBinding = () -> ADProcessParametersRepository.instance;
@Override
public DocumentEntityDataBindingDescriptor getOrBuild()
{
return dataBinding;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\adprocess\ADProcessDescriptorsFactory.java
| 1
|
请完成以下Java代码
|
public DocTypeId getInvoiceDocTypeId(
@Nullable final DocBaseAndSubType docBaseAndSubType,
@NonNull final OrgId orgId)
{
if (docBaseAndSubType == null)
{
return null;
}
final DocBaseType docBaseType = docBaseAndSubType.getDocBaseType();
final DocSubType docSubType = docBaseAndSubType.getDocSubType();
final I_AD_Org orgRecord = orgsDAO.getById(orgId);
final DocTypeQuery query = DocTypeQuery
.builder()
.docBaseType(docBaseType)
.docSubType(docSubType)
.adClientId(orgRecord.getAD_Client_ID())
.adOrgId(orgRecord.getAD_Org_ID())
.build();
return docTypeDAO.getDocTypeId(query);
}
@Nullable
public DocTypeId getOrderDocTypeIdOrNull(@Nullable final OrderDocType orderDocType, final OrgId orgId)
{
if (orderDocType == null)
{
return null;
}
final DocBaseType docBaseType = DocBaseType.SalesOrder;
final DocSubType docSubType;
if (OrderDocType.PrepayOrder.equals(orderDocType))
{
docSubType = DocSubType.PrepayOrder;
|
}
else
{
docSubType = DocSubType.StandardOrder;
}
final I_AD_Org orgRecord = orgsDAO.getById(orgId);
final DocTypeQuery query = DocTypeQuery
.builder()
.docBaseType(docBaseType)
.docSubType(docSubType)
.adClientId(orgRecord.getAD_Client_ID())
.adOrgId(orgRecord.getAD_Org_ID())
.build();
return docTypeDAO.getDocTypeId(query);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\utils\DocTypeService.java
| 1
|
请完成以下Java代码
|
public class FetchAndLockRequestDto extends RequestDto {
protected int maxTasks;
protected boolean usePriority;
protected Long asyncResponseTimeout;
protected List<TopicRequestDto> topics;
protected List<SortingDto> sorting;
public FetchAndLockRequestDto(String workerId, int maxTasks, Long asyncResponseTimeout, List<TopicRequestDto> topics) {
this(workerId, maxTasks, asyncResponseTimeout, topics, true);
}
public FetchAndLockRequestDto(String workerId, int maxTasks, Long asyncResponseTimeout, List<TopicRequestDto> topics,
boolean usePriority) {
this(workerId, maxTasks, asyncResponseTimeout, topics, usePriority, OrderingConfig.empty());
}
public FetchAndLockRequestDto(String workerId, int maxTasks, Long asyncResponseTimeout, List<TopicRequestDto> topics,
boolean usePriority, OrderingConfig orderingConfig) {
super(workerId);
this.maxTasks = maxTasks;
this.usePriority = usePriority;
this.asyncResponseTimeout = asyncResponseTimeout;
this.topics = topics;
this.sorting = orderingConfig.toSortingDtos();
}
public int getMaxTasks() {
return maxTasks;
}
public boolean isUsePriority() {
return usePriority;
|
}
public List<TopicRequestDto> getTopics() {
return topics;
}
public Long getAsyncResponseTimeout() {
return asyncResponseTimeout;
}
public List<SortingDto> getSorting() {
return sorting;
}
public void setSorting(List<SortingDto> sorting) {
this.sorting = sorting;
}
}
|
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\topic\impl\dto\FetchAndLockRequestDto.java
| 1
|
请完成以下Java代码
|
public boolean isEmpty()
{
return pattern2replacement.isEmpty();
}
public void addPattern(final String matchPatternStr, final String replacementStr)
{
Check.assumeNotNull(matchPatternStr, "matchPatternStr not null");
final Pattern matchPattern = Pattern.compile(matchPatternStr, Convert.REGEX_FLAGS);
pattern2replacement.put(matchPattern, replacementStr);
}
public void addDataType(final String dataType, final String dataTypeTo)
{
Check.assumeNotNull(dataType, "dataType not null");
Check.assumeNotNull(dataTypeTo, "dataTypeTo not null");
dataTypes.put(dataType.toUpperCase(), dataTypeTo);
final String matchPatternStr = "\\b" + dataType + "\\b";
addPattern(matchPatternStr, dataTypeTo);
|
}
public Set<Map.Entry<Pattern, String>> getPattern2ReplacementEntries()
{
return pattern2replacement.entrySet();
}
public String getDataTypeReplacement(final String dataTypeUC)
{
if (dataTypeUC == null)
{
return dataTypeUC;
}
return dataTypes.get(dataTypeUC);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\dbPort\ConvertMap.java
| 1
|
请完成以下Java代码
|
public org.compiere.model.I_AD_Table getAD_Table() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_AD_Table_ID, org.compiere.model.I_AD_Table.class);
}
@Override
public void setAD_Table(org.compiere.model.I_AD_Table AD_Table)
{
set_ValueFromPO(COLUMNNAME_AD_Table_ID, org.compiere.model.I_AD_Table.class, AD_Table);
}
/** Set DB-Tabelle.
@param AD_Table_ID
Database Table information
*/
@Override
public void setAD_Table_ID (int AD_Table_ID)
{
if (AD_Table_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Table_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Table_ID, Integer.valueOf(AD_Table_ID));
}
/** Get DB-Tabelle.
@return Database Table information
*/
@Override
public int getAD_Table_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Table_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Binärwert.
@param BinaryData
Binary Data
*/
@Override
public void setBinaryData (byte[] BinaryData)
{
set_ValueNoCheck (COLUMNNAME_BinaryData, BinaryData);
}
/** Get Binärwert.
@return Binary Data
*/
@Override
public byte[] getBinaryData ()
{
return (byte[])get_Value(COLUMNNAME_BinaryData);
}
/** Set Migriert am.
@param MigrationDate Migriert am */
@Override
public void setMigrationDate (java.sql.Timestamp MigrationDate)
{
set_Value (COLUMNNAME_MigrationDate, MigrationDate);
}
/** Get Migriert am.
@return Migriert am */
@Override
public java.sql.Timestamp getMigrationDate ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_MigrationDate);
}
/** Set Datensatz-ID.
@param Record_ID
Direct internal record ID
*/
@Override
public void setRecord_ID (int Record_ID)
{
if (Record_ID < 0)
set_ValueNoCheck (COLUMNNAME_Record_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID));
}
/** Get Datensatz-ID.
@return Direct internal record ID
*/
@Override
public int getRecord_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID);
|
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Mitteilung.
@param TextMsg
Text Message
*/
@Override
public void setTextMsg (java.lang.String TextMsg)
{
set_Value (COLUMNNAME_TextMsg, TextMsg);
}
/** Get Mitteilung.
@return Text Message
*/
@Override
public java.lang.String getTextMsg ()
{
return (java.lang.String)get_Value(COLUMNNAME_TextMsg);
}
/** Set Titel.
@param Title
Name this entity is referred to as
*/
@Override
public void setTitle (java.lang.String Title)
{
set_Value (COLUMNNAME_Title, Title);
}
/** Get Titel.
@return Name this entity is referred to as
*/
@Override
public java.lang.String getTitle ()
{
return (java.lang.String)get_Value(COLUMNNAME_Title);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Attachment.java
| 1
|
请完成以下Java代码
|
public int runBinarySearchUsingJavaArrays(int[] sortedArray, Integer key) {
int index = Arrays.binarySearch(sortedArray, key);
return index;
}
public int runBinarySearchUsingJavaCollections(List<Integer> sortedList, Integer key) {
int index = Collections.binarySearch(sortedList, key);
return index;
}
public List<Integer> runBinarySearchOnSortedArraysWithDuplicates(int[] sortedArray, Integer key) {
int startIndex = startIndexSearch(sortedArray, key);
int endIndex = endIndexSearch(sortedArray, key);
return IntStream.rangeClosed(startIndex, endIndex)
.boxed()
.collect(Collectors.toList());
}
private int endIndexSearch(int[] sortedArray, int target) {
int left = 0;
int right = sortedArray.length - 1;
int result = -1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (sortedArray[mid] == target) {
result = mid;
left = mid + 1;
} else if (sortedArray[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
|
}
return result;
}
private int startIndexSearch(int[] sortedArray, int target) {
int left = 0;
int right = sortedArray.length - 1;
int result = -1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (sortedArray[mid] == target) {
result = mid;
right = mid - 1;
} else if (sortedArray[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return result;
}
}
|
repos\tutorials-master\algorithms-modules\algorithms-searching\src\main\java\com\baeldung\algorithms\binarysearch\BinarySearch.java
| 1
|
请完成以下Java代码
|
protected String getVariableLocalTypedName(InjectionPoint ip) {
String variableName = ip.getAnnotated().getAnnotation(ProcessVariableLocalTyped.class).value();
if (variableName.length() == 0) {
variableName = ip.getMember().getName();
}
return variableName;
}
@Produces
@ProcessVariableLocal
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
|
请在Spring Boot框架中完成以下Java代码
|
private Map<InvoiceId, ImmutableList<I_C_InvoicePaySchedule>> retrieveRecordsByInvoiceId(@NonNull final Set<InvoiceId> invoiceIds)
{
if (invoiceIds.isEmpty())
{
return ImmutableMap.of();
}
final Map<InvoiceId, ImmutableList<I_C_InvoicePaySchedule>> recordsByInvoiceId = queryBL.createQueryBuilder(I_C_InvoicePaySchedule.class)
.addInArrayFilter(I_C_InvoicePaySchedule.COLUMNNAME_C_Invoice_ID, invoiceIds)
.orderBy(I_C_InvoicePaySchedule.COLUMNNAME_C_OrderPaySchedule_ID)
.create()
.stream()
.collect(Collectors.groupingBy(
InvoicePayScheduleLoaderAndSaver::extractInvoiceId,
ImmutableList.toImmutableList()
));
final HashMap<InvoiceId, ImmutableList<I_C_InvoicePaySchedule>> result = new HashMap<>();
for (final InvoiceId invoiceId : invoiceIds)
{
final ImmutableList<I_C_InvoicePaySchedule> records = recordsByInvoiceId.get(invoiceId);
result.put(invoiceId, records != null ? records : ImmutableList.of());
}
return result;
}
private void invalidateCache(final InvoiceId invoiceId)
{
recordsByInvoiceId.remove(invoiceId);
}
private static InvoiceId extractInvoiceId(@NonNull final I_C_InvoicePaySchedule record)
{
return InvoiceId.ofRepoId(record.getC_Invoice_ID());
}
private void save0(@NonNull final InvoicePaySchedule invoicePaySchedule)
{
final InvoiceId invoiceId = invoicePaySchedule.getInvoiceId();
final HashMap<InvoicePayScheduleLineId, I_C_InvoicePaySchedule> records = getRecordsByInvoiceId(invoiceId)
.stream()
.collect(GuavaCollectors.toHashMapByKey(record -> InvoicePayScheduleLineId.ofRepoId(record.getC_InvoicePaySchedule_ID())));
for (final InvoicePayScheduleLine line : invoicePaySchedule.getLines())
{
final I_C_InvoicePaySchedule record = records.remove(line.getId());
if (record == null)
{
throw new AdempiereException("No record found by " + line.getId());
}
InvoicePayScheduleConverter.updateRecord(record, line);
InterfaceWrapperHelper.save(record);
}
|
InterfaceWrapperHelper.deleteAll(records.values());
invalidateCache(invoiceId);
}
public void updateByIds(@NonNull final Set<InvoiceId> invoiceIds, @NonNull final Consumer<InvoicePaySchedule> updater)
{
if (invoiceIds.isEmpty()) {return;}
trxManager.runInThreadInheritedTrx(() -> {
warmUpByInvoiceIds(invoiceIds);
invoiceIds.forEach(invoiceId -> updateById0(invoiceId, updater));
});
}
public void updateById(@NonNull final InvoiceId invoiceId, @NonNull final Consumer<InvoicePaySchedule> updater)
{
trxManager.runInThreadInheritedTrx(() -> updateById0(invoiceId, updater));
}
private void updateById0(@NonNull final InvoiceId invoiceId, @NonNull final Consumer<InvoicePaySchedule> updater)
{
final InvoicePaySchedule paySchedules = loadByInvoiceId(invoiceId).orElse(null);
if (paySchedules == null)
{
return;
}
updater.accept(paySchedules);
save0(paySchedules);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\paymentschedule\repository\InvoicePayScheduleLoaderAndSaver.java
| 2
|
请完成以下Java代码
|
public FormFrame startForm(final int AD_Form_ID)
{
// metas: tsa: begin: US831: Open one window per session per user (2010101810000044)
final Properties ctx = Env.getCtx();
final I_AD_Form form = InterfaceWrapperHelper.create(ctx, AD_Form_ID, I_AD_Form.class, ITrx.TRXNAME_None);
if (form == null)
{
ADialog.warn(0, null, "Error", msgBL.parseTranslation(ctx, "@NotFound@ @AD_Form_ID@"));
return null;
}
final WindowManager windowManager = getWindowManager();
// metas: tsa: end: US831: Open one window per session per user (2010101810000044)
if (Ini.isPropertyBool(Ini.P_SINGLE_INSTANCE_PER_WINDOW) || form.isOneInstanceOnly()) // metas: tsa: us831
{
final FormFrame ffExisting = windowManager.findForm(AD_Form_ID);
if (ffExisting != null)
{
AEnv.showWindow(ffExisting); // metas: tsa: use this method because toFront() is not working when window is minimized
|
// ff.toFront(); // metas: tsa: commented original code
return ffExisting;
}
}
final FormFrame ff = new FormFrame();
final boolean ok = ff.openForm(form); // metas: tsa: us831
if (!ok)
{
ff.dispose();
return null;
}
windowManager.add(ff);
// Center the window
ff.showFormWindow();
return ff;
} // startForm
} // AMenu
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\AMenu.java
| 1
|
请完成以下Java代码
|
public static String sendDirectMessage(String recipientName, String msg) throws TwitterException {
Twitter twitter = getTwitterinstance();
DirectMessage message = twitter.sendDirectMessage(recipientName, msg);
return message.getText();
}
public static List<String> searchtweets() throws TwitterException {
Twitter twitter = getTwitterinstance();
Query query = new Query("source:twitter4j baeldung");
QueryResult result = twitter.search(query);
List<Status> statuses = result.getTweets();
return statuses.stream().map(
item -> item.getText()).collect(
Collectors.toList());
}
public static void streamFeed() {
StatusListener listener = new StatusListener(){
@Override
public void onException(Exception e) {
e.printStackTrace();
}
@Override
public void onDeletionNotice(StatusDeletionNotice arg) {
System.out.println("Got a status deletion notice id:" + arg.getStatusId());
}
@Override
public void onScrubGeo(long userId, long upToStatusId) {
System.out.println("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId);
}
@Override
public void onStallWarning(StallWarning warning) {
System.out.println("Got stall warning:" + warning);
}
@Override
|
public void onStatus(Status status) {
System.out.println(status.getUser().getName() + " : " + status.getText());
}
@Override
public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
System.out.println("Got track limitation notice:" + numberOfLimitedStatuses);
}
};
TwitterStream twitterStream = new TwitterStreamFactory().getInstance();
twitterStream.addListener(listener);
twitterStream.sample();
}
}
|
repos\tutorials-master\saas-modules\twitter4j\src\main\java\com\baeldung\Application.java
| 1
|
请完成以下Java代码
|
public String toCursor(Map<String, Object> keys) {
return ((Encoder<Map<String, Object>>) this.encoder).encodeValue(
keys, DefaultDataBufferFactory.sharedInstance, MAP_TYPE,
MimeTypeUtils.APPLICATION_JSON, null).toString(StandardCharsets.UTF_8);
}
@SuppressWarnings("unchecked")
@Override
public Map<String, Object> fromCursor(String cursor) {
DataBuffer buffer = this.bufferFactory.wrap(cursor.getBytes(StandardCharsets.UTF_8));
Map<String, Object> map = ((Decoder<Map<String, Object>>) this.decoder).decode(buffer, MAP_TYPE, null, null);
return (map != null) ? map : Collections.emptyMap();
}
/**
* Customizes the {@link ObjectMapper} to use default typing that supports
* {@link Date}, {@link Calendar}, {@link UUID} and classes in {@code java.time}.
*/
private static final class JacksonObjectMapperCustomizer {
static void customize(CodecConfigurer configurer) {
PolymorphicTypeValidator validator = BasicPolymorphicTypeValidator.builder()
.allowIfBaseType(Map.class)
.allowIfSubType("java.time.")
.allowIfSubType(Calendar.class)
.allowIfSubType(Date.class)
.allowIfSubType(UUID.class)
.build();
JsonMapper mapper = JsonMapper.builder()
.activateDefaultTyping(validator, DefaultTyping.NON_FINAL)
.enable(DateTimeFeature.WRITE_DATES_AS_TIMESTAMPS)
.build();
|
configurer.defaultCodecs().jacksonJsonDecoder(new JacksonJsonDecoder(mapper));
configurer.defaultCodecs().jacksonJsonEncoder(new JacksonJsonEncoder(mapper));
}
}
/**
* Customizes the {@link ObjectMapper} to use default typing that supports
* {@link Date}, {@link Calendar}, {@link UUID} and classes in {@code java.time}.
*/
@SuppressWarnings("removal")
private static final class Jackson2ObjectMapperCustomizer {
static void customize(CodecConfigurer configurer) {
com.fasterxml.jackson.databind.jsontype.PolymorphicTypeValidator validator =
com.fasterxml.jackson.databind.jsontype.BasicPolymorphicTypeValidator.builder()
.allowIfBaseType(Map.class)
.allowIfSubType("java.time.")
.allowIfSubType(Calendar.class)
.allowIfSubType(Date.class)
.allowIfSubType(UUID.class)
.build();
com.fasterxml.jackson.databind.ObjectMapper mapper = Jackson2ObjectMapperBuilder.json().build();
mapper.activateDefaultTyping(validator, com.fasterxml.jackson.databind.ObjectMapper.DefaultTyping.NON_FINAL);
mapper.enable(com.fasterxml.jackson.databind.SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
configurer.defaultCodecs().jacksonJsonDecoder(new Jackson2JsonDecoder(mapper));
configurer.defaultCodecs().jacksonJsonEncoder(new Jackson2JsonEncoder(mapper));
}
}
}
|
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\data\query\JsonKeysetCursorStrategy.java
| 1
|
请完成以下Java代码
|
public Float getGnp() {
return gnp;
}
public void setGnp(Float gnp) {
this.gnp = gnp;
}
public Float getGnpold() {
return gnpold;
}
public void setGnpold(Float gnpold) {
this.gnpold = gnpold;
}
public String getLocalname() {
return localname;
}
public void setLocalname(String localname) {
this.localname = localname == null ? null : localname.trim();
}
public String getGovernmentform() {
return governmentform;
}
public void setGovernmentform(String governmentform) {
this.governmentform = governmentform == null ? null : governmentform.trim();
}
public String getHeadofstate() {
return headofstate;
}
public void setHeadofstate(String headofstate) {
this.headofstate = headofstate == null ? null : headofstate.trim();
}
|
public Integer getCapital() {
return capital;
}
public void setCapital(Integer capital) {
this.capital = capital;
}
public String getCode2() {
return code2;
}
public void setCode2(String code2) {
this.code2 = code2 == null ? null : code2.trim();
}
}
|
repos\spring-boot-quick-master\quick-modules\dao\src\main\java\com\modules\entity\Country.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class ValidateImportRecordsResult
{
@NonNull String importTableName;
@NonNull @Default @With Duration duration = Duration.ZERO;
int countImportRecordsDeleted;
@NonNull OptionalInt countImportRecordsWithValidationErrors;
public String getSummary()
{
final StringBuilder sb = new StringBuilder();
if (countImportRecordsDeleted > 0)
{
if (sb.length() > 0) {sb.append("; ");}
sb.append(countImportRecordsDeleted).append(" record(s) deleted");
}
if (countImportRecordsWithValidationErrors.isPresent() && countImportRecordsWithValidationErrors.getAsInt() > 0)
{
if (sb.length() > 0) {sb.append("; ");}
sb.append(countImportRecordsWithValidationErrors.getAsInt()).append(" validation errors encountered");
}
return sb.toString();
}
|
public boolean hasErrors()
{
return countImportRecordsWithValidationErrors.orElse(-1) > 0;
}
public String getErrorMessage()
{
int errorsCount = countImportRecordsWithValidationErrors.orElse(-1);
if (errorsCount <= 0)
{
throw new IllegalStateException("no errors expected");
}
return errorsCount + " row(s) have validation errors";
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\ValidateImportRecordsResult.java
| 2
|
请完成以下Java代码
|
public void setMemberIp(String memberIp) {
this.memberIp = memberIp;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Integer getShowStatus() {
return showStatus;
}
public void setShowStatus(Integer showStatus) {
this.showStatus = showStatus;
}
public String getProductAttribute() {
return productAttribute;
}
public void setProductAttribute(String productAttribute) {
this.productAttribute = productAttribute;
}
public Integer getCollectCouont() {
return collectCouont;
}
public void setCollectCouont(Integer collectCouont) {
this.collectCouont = collectCouont;
}
public Integer getReadCount() {
return readCount;
}
public void setReadCount(Integer readCount) {
this.readCount = readCount;
}
public String getPics() {
return pics;
}
public void setPics(String pics) {
this.pics = pics;
}
public String getMemberIcon() {
return memberIcon;
}
public void setMemberIcon(String memberIcon) {
this.memberIcon = memberIcon;
}
public Integer getReplayCount() {
return replayCount;
}
public void setReplayCount(Integer replayCount) {
this.replayCount = replayCount;
}
public String getContent() {
|
return content;
}
public void setContent(String content) {
this.content = content;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", productId=").append(productId);
sb.append(", memberNickName=").append(memberNickName);
sb.append(", productName=").append(productName);
sb.append(", star=").append(star);
sb.append(", memberIp=").append(memberIp);
sb.append(", createTime=").append(createTime);
sb.append(", showStatus=").append(showStatus);
sb.append(", productAttribute=").append(productAttribute);
sb.append(", collectCouont=").append(collectCouont);
sb.append(", readCount=").append(readCount);
sb.append(", pics=").append(pics);
sb.append(", memberIcon=").append(memberIcon);
sb.append(", replayCount=").append(replayCount);
sb.append(", content=").append(content);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}
|
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsComment.java
| 1
|
请完成以下Java代码
|
public DocumentId retrieveParentDocumentId(final DocumentEntityDescriptor parentEntityDescriptor, final DocumentQuery childDocumentQuery)
{
throw new UnsupportedOperationException(); // TODO
}
@Override
public Document createNewDocument(final DocumentEntityDescriptor entityDescriptor, @Nullable final Document parentDocument, final IDocumentChangesCollector changesCollector)
{
throw new UnsupportedOperationException();
}
@Override
public void refresh(final @NotNull Document document)
{
final AttributesIncludedTabDataKey key = extractKey(document);
final AttributesIncludedTabData data = attributesIncludedTabService.getData(key);
refreshDocumentFromData(document, data);
}
@Override
public SaveResult save(final @NotNull Document document)
{
final AttributesIncludedTabEntityBinding entityBinding = extractEntityBinding(document);
final AttributesIncludedTabData data = attributesIncludedTabService.updateByKey(
extractKey(document),
entityBinding.getAttributeIds(),
(attributeId, field) -> {
final String fieldName = entityBinding.getFieldNameByAttributeId(attributeId);
final IDocumentFieldView documentField = document.getFieldView(fieldName);
if (!documentField.hasChangesToSave())
{
return field;
}
final AttributesIncludedTabFieldBinding fieldBinding = extractFieldBinding(document, fieldName);
return fieldBinding.updateData(
field != null ? field : newDataField(fieldBinding),
documentField);
});
refreshDocumentFromData(document, data);
// Notify the parent document that one of its children were saved (copied from SqlDocumentsRepository)
document.getParentDocument().onChildSaved(document);
return SaveResult.SAVED;
}
private static AttributesIncludedTabDataField newDataField(final AttributesIncludedTabFieldBinding fieldBinding)
{
|
return AttributesIncludedTabDataField.builder()
.attributeId(fieldBinding.getAttributeId())
.valueType(fieldBinding.getAttributeValueType())
.build();
}
private void refreshDocumentFromData(@NonNull final Document document, @NonNull final AttributesIncludedTabData data)
{
document.refreshFromSupplier(new AttributesIncludedTabDataAsDocumentValuesSupplier(data));
}
@Override
public void delete(final @NotNull Document document)
{
throw new UnsupportedOperationException();
}
@Override
public String retrieveVersion(final DocumentEntityDescriptor entityDescriptor, final int documentIdAsInt) {return AttributesIncludedTabDataAsDocumentValuesSupplier.VERSION_DEFAULT;}
@Override
public int retrieveLastLineNo(final DocumentQuery query)
{
throw new UnsupportedOperationException();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\attributes_included_tab\AttributesIncludedTabDocumentsRepository.java
| 1
|
请完成以下Java代码
|
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
// @formatter:off
return this.authorizationRequestResolver.resolve(exchange)
.switchIfEmpty(chain.filter(exchange).then(Mono.empty()))
.onErrorResume(ClientAuthorizationRequiredException.class,
(ex) -> this.requestCache.saveRequest(exchange).then(
this.authorizationRequestResolver.resolve(exchange, ex.getClientRegistrationId()))
)
.flatMap((clientRegistration) -> sendRedirectForAuthorization(exchange, clientRegistration));
// @formatter:on
}
private Mono<Void> sendRedirectForAuthorization(ServerWebExchange exchange,
OAuth2AuthorizationRequest authorizationRequest) {
return Mono.defer(() -> {
|
Mono<Void> saveAuthorizationRequest = Mono.empty();
if (AuthorizationGrantType.AUTHORIZATION_CODE.equals(authorizationRequest.getGrantType())) {
saveAuthorizationRequest = this.authorizationRequestRepository
.saveAuthorizationRequest(authorizationRequest, exchange);
}
// @formatter:off
URI redirectUri = UriComponentsBuilder.fromUriString(authorizationRequest.getAuthorizationRequestUri())
.build(true)
.toUri();
// @formatter:on
return saveAuthorizationRequest
.then(this.authorizationRedirectStrategy.sendRedirect(exchange, redirectUri));
});
}
}
|
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\web\server\OAuth2AuthorizationRequestRedirectWebFilter.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
private int score;
public Student() {
}
public Student(String name, int score) {
this.name = name;
this.score = score;
}
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 int getScore() {
return score;
|
}
public void setScore(int score) {
this.score = score;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", score=" + score + "]";
}
@Override
public int hashCode() {
return Objects.hash(id, name, score);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
return id == other.id && Objects.equals(name, other.name) && score == other.score;
}
}
|
repos\tutorials-master\persistence-modules\spring-data-jpa-repo-2\src\main\java\com\baeldung\spring\data\persistence\search\Student.java
| 2
|
请完成以下Java代码
|
public class ThingsboardException extends Exception {
private static final long serialVersionUID = 1L;
private ThingsboardErrorCode errorCode;
public ThingsboardException() {
super();
}
public ThingsboardException(ThingsboardErrorCode errorCode) {
this.errorCode = errorCode;
}
public ThingsboardException(String message, ThingsboardErrorCode errorCode) {
super(message);
this.errorCode = errorCode;
}
|
public ThingsboardException(String message, Throwable cause, ThingsboardErrorCode errorCode) {
super(message, cause);
this.errorCode = errorCode;
}
public ThingsboardException(Throwable cause, ThingsboardErrorCode errorCode) {
super(cause);
this.errorCode = errorCode;
}
public ThingsboardErrorCode getErrorCode() {
return errorCode;
}
}
|
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\exception\ThingsboardException.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class SpELWeekDaysHolder {
@Value("#{'${monday}'.toUpperCase()}")
private WeekDays monday;
@Value("#{'${tuesday}'.toUpperCase()}")
private WeekDays tuesday;
@Value("#{'${wednesday}'.toUpperCase()}")
private WeekDays wednesday;
@Value("#{'${thursday}'.toUpperCase()}")
private WeekDays thursday;
@Value("#{'${friday}'.toUpperCase()}")
private WeekDays friday;
@Value("#{'${saturday}'.toUpperCase()}")
private WeekDays saturday;
@Value("#{'${sunday}'.toUpperCase()}")
private WeekDays sunday;
public WeekDays getMonday() {
return monday;
}
public void setMonday(final WeekDays monday) {
this.monday = monday;
}
public WeekDays getTuesday() {
return tuesday;
}
public void setTuesday(final WeekDays tuesday) {
this.tuesday = tuesday;
}
public WeekDays getWednesday() {
return wednesday;
}
|
public void setWednesday(final WeekDays wednesday) {
this.wednesday = wednesday;
}
public WeekDays getThursday() {
return thursday;
}
public void setThursday(final WeekDays thursday) {
this.thursday = thursday;
}
public WeekDays getFriday() {
return friday;
}
public void setFriday(final WeekDays friday) {
this.friday = friday;
}
public WeekDays getSaturday() {
return saturday;
}
public void setSaturday(final WeekDays saturday) {
this.saturday = saturday;
}
public WeekDays getSunday() {
return sunday;
}
public void setSunday(final WeekDays sunday) {
this.sunday = sunday;
}
}
|
repos\tutorials-master\spring-boot-modules\spring-boot-properties-4\src\main\java\com\baeldung\caseinsensitiveenum\week\SpELWeekDaysHolder.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class UaaWebSecurityConfiguration extends WebSecurityConfigurerAdapter {
private final UserDetailsService userDetailsService;
private final AuthenticationManagerBuilder authenticationManagerBuilder;
public UaaWebSecurityConfiguration(UserDetailsService userDetailsService, AuthenticationManagerBuilder authenticationManagerBuilder) {
this.userDetailsService = userDetailsService;
this.authenticationManagerBuilder = authenticationManagerBuilder;
}
@PostConstruct
public void init() throws Exception {
try {
authenticationManagerBuilder
.userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder());
} catch (Exception e) {
throw new BeanInitializationException("Security configuration failed", e);
}
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
|
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring()
.antMatchers(HttpMethod.OPTIONS, "/**")
.antMatchers("/app/**/*.{js,html}")
.antMatchers("/bower_components/**")
.antMatchers("/i18n/**")
.antMatchers("/content/**")
.antMatchers("/swagger-ui/index.html")
.antMatchers("/test/**")
.antMatchers("/h2-console/**");
}
@Bean
public SecurityEvaluationContextExtension securityEvaluationContextExtension() {
return new SecurityEvaluationContextExtension();
}
}
|
repos\tutorials-master\jhipster-modules\jhipster-uaa\uaa\src\main\java\com\baeldung\jhipster\uaa\config\UaaWebSecurityConfiguration.java
| 2
|
请完成以下Java代码
|
public String getScopeType() {
throw new UnsupportedOperationException("Not supported to scope type");
}
@Override
public String getTaskId() {
throw new UnsupportedOperationException("Not supported to get task id");
}
@Override
public String getTextValue() {
return node.path("textValue").stringValue(null);
}
@Override
public void setTextValue(String textValue) {
throw new UnsupportedOperationException("Not supported to set text value");
}
@Override
public String getTextValue2() {
return node.path("textValues").stringValue(null);
}
@Override
public void setTextValue2(String textValue2) {
throw new UnsupportedOperationException("Not supported to set text value2");
}
@Override
public Long getLongValue() {
JsonNode longNode = node.path("longValue");
if (longNode.isNumber()) {
return longNode.longValue();
}
return null;
}
@Override
public void setLongValue(Long longValue) {
throw new UnsupportedOperationException("Not supported to set long value");
}
@Override
public Double getDoubleValue() {
JsonNode doubleNode = node.path("doubleValue");
if (doubleNode.isNumber()) {
return doubleNode.doubleValue();
}
return null;
}
@Override
public void setDoubleValue(Double doubleValue) {
throw new UnsupportedOperationException("Not supported to set double value");
|
}
@Override
public byte[] getBytes() {
throw new UnsupportedOperationException("Not supported to get bytes");
}
@Override
public void setBytes(byte[] bytes) {
throw new UnsupportedOperationException("Not supported to set bytes");
}
@Override
public Object getCachedValue() {
throw new UnsupportedOperationException("Not supported to set get cached value");
}
@Override
public void setCachedValue(Object cachedValue) {
throw new UnsupportedOperationException("Not supported to set cached value");
}
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\delete\BatchDeleteCaseConfig.java
| 1
|
请完成以下Java代码
|
private ImmutableList<ProcessBasicInfo> buildProcessBasicInfoList(
@NonNull final Map<Integer, I_AD_Process> processByIdMap,
@NonNull final ImmutableListMultimap<Integer, I_AD_Process_Para> processParamByProcessIdMap)
{
return processByIdMap.keySet()
.stream()
.map(processId -> {
final List<ProcessParamBasicInfo> params = processParamByProcessIdMap.get(processId)
.stream()
.map(this::buildProcessParamBasicInfo)
.collect(Collectors.toList());
return buildProcessBasicInfo(processByIdMap.get(processId), params);
})
.collect(ImmutableList.toImmutableList());
}
private ProcessParamBasicInfo buildProcessParamBasicInfo(@NonNull final I_AD_Process_Para processPara)
{
final IModelTranslationMap processParamTrlMap;
if (processPara.getAD_Element_ID() <= 0)
{
processParamTrlMap = InterfaceWrapperHelper.getModelTranslationMap(processPara);
}
else
{
final I_AD_Element element = elementDAO.getById(processPara.getAD_Element_ID());
processParamTrlMap = InterfaceWrapperHelper.getModelTranslationMap(element);
}
|
return ProcessParamBasicInfo.builder()
.columnName(processPara.getColumnName())
.type(DisplayType.getDescription(processPara.getAD_Reference_ID()))
.name(processParamTrlMap.getColumnTrl(I_AD_Process_Para.COLUMNNAME_Name, processPara.getName()))
.description(processParamTrlMap.getColumnTrl(I_AD_Process_Para.COLUMNNAME_Description, processPara.getDescription()))
.build();
}
private ProcessBasicInfo buildProcessBasicInfo(@NonNull final I_AD_Process adProcess, @Nullable final List<ProcessParamBasicInfo> paramBasicInfos)
{
final IModelTranslationMap processTrlMap = InterfaceWrapperHelper.getModelTranslationMap(adProcess);
return ProcessBasicInfo.builder()
.processId(AdProcessId.ofRepoId(adProcess.getAD_Process_ID()))
.value(adProcess.getValue())
.name(processTrlMap.getColumnTrl(I_AD_Process.COLUMNNAME_Name, adProcess.getName()))
.description(processTrlMap.getColumnTrl(I_AD_Process.COLUMNNAME_Description, adProcess.getName()))
.type(ProcessType.ofCode(adProcess.getType()))
.parameters(paramBasicInfos)
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\process\impl\ProcessService.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.