proj_name
stringclasses
26 values
relative_path
stringlengths
42
165
class_name
stringlengths
3
46
func_name
stringlengths
2
44
masked_class
stringlengths
80
7.9k
func_body
stringlengths
76
5.98k
len_input
int64
30
1.88k
len_output
int64
25
1.43k
total
int64
73
2.03k
initial_context
stringclasses
74 values
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-serializer/autoload-cache-serializer-protobuf/src/main/java/com/jarvis/cache/serializer/protobuf/HeapByteBufUtil.java
HeapByteBufUtil
setIntLE
class HeapByteBufUtil { static byte getByte(byte[] memory, int index) { return memory[index]; } static short getShort(byte[] memory, int index) { return (short) (memory[index] << 8 | memory[index + 1] & 0xFF); } static short getShortLE(byte[] memory, int index) { return (short) (memory[index] & 0xff | memory[index + 1] << 8); } static int getUnsignedMedium(byte[] memory, int index) { return (memory[index] & 0xff) << 16 | (memory[index + 1] & 0xff) << 8 | memory[index + 2] & 0xff; } static int getUnsignedMediumLE(byte[] memory, int index) { return memory[index] & 0xff | (memory[index + 1] & 0xff) << 8 | (memory[index + 2] & 0xff) << 16; } static int getInt(byte[] memory, int index) { return (memory[index] & 0xff) << 24 | (memory[index + 1] & 0xff) << 16 | (memory[index + 2] & 0xff) << 8 | memory[index + 3] & 0xff; } static int getIntLE(byte[] memory, int index) { return memory[index] & 0xff | (memory[index + 1] & 0xff) << 8 | (memory[index + 2] & 0xff) << 16 | (memory[index + 3] & 0xff) << 24; } static long getLong(byte[] memory, int index) { return ((long) memory[index] & 0xff) << 56 | ((long) memory[index + 1] & 0xff) << 48 | ((long) memory[index + 2] & 0xff) << 40 | ((long) memory[index + 3] & 0xff) << 32 | ((long) memory[index + 4] & 0xff) << 24 | ((long) memory[index + 5] & 0xff) << 16 | ((long) memory[index + 6] & 0xff) << 8 | (long) memory[index + 7] & 0xff; } static long getLongLE(byte[] memory, int index) { return (long) memory[index] & 0xff | ((long) memory[index + 1] & 0xff) << 8 | ((long) memory[index + 2] & 0xff) << 16 | ((long) memory[index + 3] & 0xff) << 24 | ((long) memory[index + 4] & 0xff) << 32 | ((long) memory[index + 5] & 0xff) << 40 | ((long) memory[index + 6] & 0xff) << 48 | ((long) memory[index + 7] & 0xff) << 56; } static void setByte(byte[] memory, int index, int value) { memory[index] = (byte) value; } static void setShort(byte[] memory, int index, int value) { memory[index] = (byte) (value >>> 8); memory[index + 1] = (byte) value; } static void setShortLE(byte[] memory, int index, int value) { memory[index] = (byte) value; memory[index + 1] = (byte) (value >>> 8); } static void setMedium(byte[] memory, int index, int value) { memory[index] = (byte) (value >>> 16); memory[index + 1] = (byte) (value >>> 8); memory[index + 2] = (byte) value; } static void setMediumLE(byte[] memory, int index, int value) { memory[index] = (byte) value; memory[index + 1] = (byte) (value >>> 8); memory[index + 2] = (byte) (value >>> 16); } static void setInt(byte[] memory, int index, int value) { memory[index] = (byte) (value >>> 24); memory[index + 1] = (byte) (value >>> 16); memory[index + 2] = (byte) (value >>> 8); memory[index + 3] = (byte) value; } static void setIntLE(byte[] memory, int index, int value) {<FILL_FUNCTION_BODY>} static void setLong(byte[] memory, int index, long value) { memory[index] = (byte) (value >>> 56); memory[index + 1] = (byte) (value >>> 48); memory[index + 2] = (byte) (value >>> 40); memory[index + 3] = (byte) (value >>> 32); memory[index + 4] = (byte) (value >>> 24); memory[index + 5] = (byte) (value >>> 16); memory[index + 6] = (byte) (value >>> 8); memory[index + 7] = (byte) value; } static void setLongLE(byte[] memory, int index, long value) { memory[index] = (byte) value; memory[index + 1] = (byte) (value >>> 8); memory[index + 2] = (byte) (value >>> 16); memory[index + 3] = (byte) (value >>> 24); memory[index + 4] = (byte) (value >>> 32); memory[index + 5] = (byte) (value >>> 40); memory[index + 6] = (byte) (value >>> 48); memory[index + 7] = (byte) (value >>> 56); } private HeapByteBufUtil() { } }
memory[index] = (byte) value; memory[index + 1] = (byte) (value >>> 8); memory[index + 2] = (byte) (value >>> 16); memory[index + 3] = (byte) (value >>> 24);
1,590
74
1,664
jitsi_jitsi
jitsi/modules/plugin/otr/src/main/java/net/java/sip/communicator/plugin/otr/OtrMetaContactMenu.java
OtrMetaContactMenu
createOtrContactMenus
class OtrMetaContactMenu extends AbstractPluginComponent implements ActionListener, PopupMenuListener { /** * The last known <tt>MetaContact</tt> to be currently selected and to be * depicted by this instance and the <tt>OtrContactMenu</tt>s it contains. */ private MetaContact currentContact; /** * The indicator which determines whether the <tt>JMenu</tt> of this * <tt>OtrMetaContactMenu</tt> is displayed in the Mac OS X screen menu bar * and thus should work around the known problem of PopupMenuListener not * being invoked. */ private final boolean inMacOSXScreenMenuBar; /** * The <tt>JMenu</tt> which is the component of this plug-in. */ private JMenu menu; /** * The "What's this?" <tt>JMenuItem</tt> which launches help on the subject * of off-the-record messaging. */ private JMenuItem whatsThis; public OtrMetaContactMenu(Container container, PluginComponentFactory parentFactory) { super(container, parentFactory); inMacOSXScreenMenuBar = Container.CONTAINER_CHAT_MENU_BAR.equals(container) && OSUtils.IS_MAC; } /* * Implements ActionListener#actionPerformed(ActionEvent). Handles the * invocation of the whatsThis menu item i.e. launches help on the subject * of off-the-record messaging. */ public void actionPerformed(ActionEvent e) { OtrActivator.scOtrEngine.launchHelp(); } /** * Creates an {@link OtrContactMenu} for each {@link Contact} contained in * the <tt>metaContact</tt>. * * @param metaContact The {@link MetaContact} this * {@link OtrMetaContactMenu} refers to. */ private void createOtrContactMenus(MetaContact metaContact) {<FILL_FUNCTION_BODY>} /* * Implements PluginComponent#getComponent(). Returns the JMenu which is the * component of this plug-in creating it first if it doesn't exist. */ public Component getComponent() { return getMenu(); } /** * Gets the <tt>JMenu</tt> which is the component of this plug-in. If it * still doesn't exist, it's created. * * @return the <tt>JMenu</tt> which is the component of this plug-in */ private JMenu getMenu() { if (menu == null) { menu = new SIPCommMenu(); menu.setText(getName()); if (Container.CONTAINER_CONTACT_RIGHT_BUTTON_MENU .equals(getContainer())) { Icon icon = OtrActivator.resourceService .getImage("plugin.otr.MENU_ITEM_ICON_16x16"); if (icon != null) menu.setIcon(icon); } if (!inMacOSXScreenMenuBar) menu.getPopupMenu().addPopupMenuListener(this); } return menu; } /* * Implements PluginComponent#getName(). */ public String getName() { return OtrActivator.resourceService .getI18NString("plugin.otr.menu.TITLE"); } /* * Implements PopupMenuListener#popupMenuCanceled(PopupMenuEvent). */ public void popupMenuCanceled(PopupMenuEvent e) { createOtrContactMenus(null); } /* * Implements PopupMenuListener#popupMenuWillBecomeInvisible( * PopupMenuEvent). */ public void popupMenuWillBecomeInvisible(PopupMenuEvent e) { popupMenuCanceled(e); } /* * Implements PopupMenuListener#popupMenuWillBecomeVisible(PopupMenuEvent). */ public void popupMenuWillBecomeVisible(PopupMenuEvent e) { createOtrContactMenus(currentContact); JMenu menu = getMenu(); menu.addSeparator(); whatsThis = new JMenuItem(); whatsThis.setIcon( OtrActivator.resourceService.getImage( "plugin.otr.HELP_ICON_15x15")); whatsThis.setText( OtrActivator.resourceService.getI18NString( "plugin.otr.menu.WHATS_THIS")); whatsThis.addActionListener(this); menu.add(whatsThis); } /* * Implements PluginComponent#setCurrentContact(MetaContact). */ @Override public void setCurrentContact(MetaContact metaContact) { if (this.currentContact != metaContact) { this.currentContact = metaContact; if (inMacOSXScreenMenuBar) popupMenuWillBecomeVisible(null); else if ((menu != null) && menu.isPopupMenuVisible()) createOtrContactMenus(currentContact); } } }
JMenu menu = getMenu(); // Remove any existing OtrContactMenu items. menu.removeAll(); // Create the new OtrContactMenu items. if (metaContact != null) { Iterator<Contact> contacts = metaContact.getContacts(); if (metaContact.getContactCount() == 1) { Contact contact = contacts.next(); Collection<ContactResource> resources = contact.getResources(); if (contact.supportResources() && resources != null && resources.size() > 0) { for (ContactResource resource : resources) { new OtrContactMenu( OtrContactManager.getOtrContact(contact, resource), inMacOSXScreenMenuBar, menu, true); } } else new OtrContactMenu( OtrContactManager.getOtrContact(contact, null), inMacOSXScreenMenuBar, menu, false); } else while (contacts.hasNext()) { Contact contact = contacts.next(); Collection<ContactResource> resources = contact.getResources(); if (contact.supportResources() && resources != null && resources.size() > 0) { for (ContactResource resource : resources) { new OtrContactMenu( OtrContactManager.getOtrContact( contact, resource), inMacOSXScreenMenuBar, menu, true); } } else new OtrContactMenu( OtrContactManager.getOtrContact(contact, null), inMacOSXScreenMenuBar, menu, true); } }
1,403
437
1,840
/** * Provides an abstract base implementation of <code>PluginComponent</code> in order to take care of the implementation boilerplate and let implementers focus on the specifics of their plug-in. * @author Lyubomir Marinov */ public abstract class AbstractPluginComponent implements PluginComponent { /** * The parent factory. */ private final PluginComponentFactory parentFactory; /** * The container in which the component of this plug-in is to be added. */ private final Container container; /** * Initializes a new <code>AbstractPluginComponent</code> which is to be added to a specific <code>Container</code>. * @param container the container in which the component of the new plug-inis to be added * @param parentFactory the parent <tt>PluginComponentFactory</tt> that iscreating this plugin component. */ protected AbstractPluginComponent( Container container, PluginComponentFactory parentFactory); public String getConstraints(); public Container getContainer(); /** * Implements {@link PluginComponent#getPositionIndex()}. Returns <tt>-1</tt> which indicates that the position of this <tt>AbstractPluginComponent</tt> within its <tt>Container</tt> is of no importance. * @return <tt>-1</tt> which indicates that the position of this<tt>AbstractPluginComponent</tt> within its <tt>Container</tt> is of no importance * @see PluginComponent#getPositionIndex() */ public int getPositionIndex(); public boolean isNativeComponent(); public void setCurrentContact( Contact contact); public void setCurrentContact( Contact contact, String resourceName); public void setCurrentContact( MetaContact metaContact); public void setCurrentContactGroup( MetaContactGroup metaGroup); public void setCurrentAccountID( AccountID accountID); /** * Returns the factory that has created the component. * @return the parent factory. */ public PluginComponentFactory getParentFactory(); }
docker-java_docker-java
docker-java/docker-java-api/src/main/java/com/github/dockerjava/api/model/Device.java
Device
parse
class Device extends DockerObject implements Serializable { private static final long serialVersionUID = 1L; @JsonProperty("CgroupPermissions") private String cGroupPermissions = ""; @JsonProperty("PathOnHost") private String pathOnHost = null; @JsonProperty("PathInContainer") private String pathInContainer = null; public Device() { } public Device(String cGroupPermissions, String pathInContainer, String pathOnHost) { requireNonNull(cGroupPermissions, "cGroupPermissions is null"); requireNonNull(pathInContainer, "pathInContainer is null"); requireNonNull(pathOnHost, "pathOnHost is null"); this.cGroupPermissions = cGroupPermissions; this.pathInContainer = pathInContainer; this.pathOnHost = pathOnHost; } public String getcGroupPermissions() { return cGroupPermissions; } public String getPathInContainer() { return pathInContainer; } public String getPathOnHost() { return pathOnHost; } /** * @link https://github.com/docker/docker/blob/6b4a46f28266031ce1a1315f17fb69113a06efe1/runconfig/opts/parse_test.go#L468 */ @Nonnull public static Device parse(@Nonnull String deviceStr) {<FILL_FUNCTION_BODY>} /** * ValidDeviceMode checks if the mode for device is valid or not. * Valid mode is a composition of r (read), w (write), and m (mknod). * * @link https://github.com/docker/docker/blob/6b4a46f28266031ce1a1315f17fb69113a06efe1/runconfig/opts/parse.go#L796 */ private static boolean validDeviceMode(String deviceMode) { Map<String, Boolean> validModes = new HashMap<>(3); validModes.put("r", true); validModes.put("w", true); validModes.put("m", true); if (deviceMode == null || deviceMode.length() == 0) { return false; } for (char ch : deviceMode.toCharArray()) { final String mode = String.valueOf(ch); if (!Boolean.TRUE.equals(validModes.get(mode))) { return false; // wrong mode } validModes.put(mode, false); } return true; } }
String src = ""; String dst = ""; String permissions = "rwm"; final String[] arr = deviceStr.trim().split(":"); // java String.split() returns wrong length, use tokenizer instead switch (new StringTokenizer(deviceStr, ":").countTokens()) { case 3: { // Mismatches docker code logic. While there is no validations after parsing, checking heregit if (validDeviceMode(arr[2])) { permissions = arr[2]; } else { throw new IllegalArgumentException("Invalid device specification: " + deviceStr); } } case 2: { if (validDeviceMode(arr[1])) { permissions = arr[1]; } else { dst = arr[1]; } } case 1: { src = arr[0]; break; } default: { throw new IllegalArgumentException("Invalid device specification: " + deviceStr); } } if (dst == null || dst.length() == 0) { dst = src; } return new Device(permissions, dst, src);
686
297
983
/** * @see DockerObjectAccessor */ public abstract class DockerObject { HashMap<String,Object> rawValues=new HashMap<>(); @JsonAnyGetter public Map<String,Object> getRawValues(); }
subhra74_snowflake
snowflake/muon-app/src/main/java/muon/app/ui/components/session/utilpage/services/ServiceTableCellRenderer.java
ServiceTableCellRenderer
getTableCellRendererComponent
class ServiceTableCellRenderer extends JLabel implements TableCellRenderer { public ServiceTableCellRenderer() { setText("HHH"); setBorder(new EmptyBorder(5, 5, 5, 5)); setOpaque(true); } @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {<FILL_FUNCTION_BODY>} }
setText(value == null ? "" : value.toString()); setBackground(isSelected ? table.getSelectionBackground() : table.getBackground()); setForeground(isSelected ? table.getSelectionForeground() : table.getForeground()); return this;
124
71
195
DerekYRC_mini-spring
mini-spring/src/main/java/org/springframework/aop/aspectj/AspectJExpressionPointcutAdvisor.java
AspectJExpressionPointcutAdvisor
getPointcut
class AspectJExpressionPointcutAdvisor implements PointcutAdvisor { private AspectJExpressionPointcut pointcut; private Advice advice; private String expression; public void setExpression(String expression) { this.expression = expression; } @Override public Pointcut getPointcut() {<FILL_FUNCTION_BODY>} @Override public Advice getAdvice() { return advice; } public void setAdvice(Advice advice) { this.advice = advice; } }
if (pointcut == null) { pointcut = new AspectJExpressionPointcut(expression); } return pointcut;
135
38
173
Pay-Group_best-pay-sdk
best-pay-sdk/src/main/java/com/lly835/bestpay/service/impl/wx/WxPayMicroServiceImpl.java
WxPayMicroServiceImpl
pay
class WxPayMicroServiceImpl extends WxPayServiceImpl { /** * 微信付款码支付 * 提交支付请求后微信会同步返回支付结果。 * 当返回结果为“系统错误 {@link WxPayConstants#SYSTEMERROR}”时,商户系统等待5秒后调用【查询订单API {@link WxPayServiceImpl#query(OrderQueryRequest)}】,查询支付实际交易结果; * 当返回结果为“正在支付 {@link WxPayConstants#USERPAYING}”时,商户系统可设置间隔时间(建议10秒)重新查询支付结果,直到支付成功或超时(建议30秒); * * @param request * @return */ @Override public PayResponse pay(PayRequest request) {<FILL_FUNCTION_BODY>} }
WxPayUnifiedorderRequest wxRequest = new WxPayUnifiedorderRequest(); wxRequest.setOutTradeNo(request.getOrderId()); wxRequest.setTotalFee(MoneyUtil.Yuan2Fen(request.getOrderAmount())); wxRequest.setBody(request.getOrderName()); wxRequest.setOpenid(request.getOpenid()); wxRequest.setAuthCode(request.getAuthCode()); wxRequest.setAppid(wxPayConfig.getAppId()); wxRequest.setMchId(wxPayConfig.getMchId()); wxRequest.setNonceStr(RandomUtil.getRandomStr()); wxRequest.setSpbillCreateIp(StringUtils.isEmpty(request.getSpbillCreateIp()) ? "8.8.8.8" : request.getSpbillCreateIp()); wxRequest.setAttach(request.getAttach()); wxRequest.setSign(WxPaySignature.sign(MapUtil.buildMap(wxRequest), wxPayConfig.getMchKey())); //对付款码支付无用的字段 wxRequest.setNotifyUrl(""); wxRequest.setTradeType(""); RequestBody body = RequestBody.create(MediaType.parse("application/xml; charset=utf-8"), XmlUtil.toString(wxRequest)); WxPayApi api = null; if (wxPayConfig.isSandbox()) { api = devRetrofit.create(WxPayApi.class); } else { api = retrofit.create(WxPayApi.class); } Call<WxPaySyncResponse> call = api.micropay(body); Response<WxPaySyncResponse> retrofitResponse = null; try { retrofitResponse = call.execute(); } catch (IOException e) { e.printStackTrace(); } assert retrofitResponse != null; if (!retrofitResponse.isSuccessful()) { throw new RuntimeException("【微信付款码支付】发起支付, 网络异常"); } return buildPayResponse(retrofitResponse.body());
218
535
753
/** * Created by 廖师兄 2017-07-02 13:40 */ @Slf4j public class WxPayServiceImpl extends BestPayServiceImpl { protected WxPayConfig wxPayConfig; protected final Retrofit retrofit=new Retrofit.Builder().baseUrl(WxPayConstants.WXPAY_GATEWAY).addConverterFactory(SimpleXmlConverterFactory.create()).client(new OkHttpClient.Builder().addInterceptor((new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))).build()).build(); protected final Retrofit devRetrofit=new Retrofit.Builder().baseUrl(WxPayConstants.WXPAY_GATEWAY_SANDBOX).addConverterFactory(SimpleXmlConverterFactory.create()).client(new OkHttpClient.Builder().addInterceptor((new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))).build()).build(); @Override public void setWxPayConfig( WxPayConfig wxPayConfig); @Override public PayResponse pay( PayRequest request); @Override public boolean verify( Map map, SignType signType, String sign); @Override public PayResponse syncNotify( HttpServletRequest request); /** * 异步通知 * @param notifyData * @return */ @Override public PayResponse asyncNotify( String notifyData); /** * 微信退款 * @param request * @return */ @Override public RefundResponse refund( RefundRequest request); /** * 查询订单 * @param request * @return */ @Override public OrderQueryResponse query( OrderQueryRequest request); private RefundResponse buildRefundResponse( WxRefundResponse response); private PayResponse buildPayResponse( WxPayAsyncResponse response); /** * 返回给h5的参数 * @param response * @return */ protected PayResponse buildPayResponse( WxPaySyncResponse response); /** * 返回给企业付款到银行卡的参数 * @param response * @return */ private PayBankResponse buildPayBankResponse( WxPaySyncResponse response); /** * @param request * @return */ @Override public String downloadBill( DownloadBillRequest request); /** * 根据微信规则生成扫码二维码的URL * @return */ @Override public String getQrCodeUrl( String productId); @Override public PayBankResponse payBank( PayBankRequest request); }
pmd_pmd
pmd/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/multithreading/DoubleCheckedLockingRule.java
DoubleCheckedLockingRule
visit
class DoubleCheckedLockingRule extends AbstractJavaRule { @Override protected @NonNull RuleTargetSelector buildTargetSelector() { return RuleTargetSelector.forTypes(ASTMethodDeclaration.class); } @Override public Object visit(ASTMethodDeclaration node, Object data) {<FILL_FUNCTION_BODY>} private boolean isLocalOnlyStoredWithVolatileField(ASTMethodDeclaration method, JVariableSymbol local) { ASTExpression initializer; if (local instanceof JLocalVariableSymbol) { ASTVariableId id = local.tryGetNode(); if (id == null) { return false; } initializer = id.getInitializer(); } else { // the return variable name doesn't seem to be a local variable return false; } return (initializer == null || isVolatileFieldReference(initializer)) && method.descendants(ASTAssignmentExpression.class) .filter(it -> JavaAstUtils.isReferenceToVar(it.getLeftOperand(), local)) .all(it -> isVolatileFieldReference(it.getRightOperand())); } private boolean isVolatileFieldReference(@Nullable ASTExpression initializer) { if (initializer instanceof ASTNamedReferenceExpr) { JVariableSymbol fieldSym = ((ASTNamedReferenceExpr) initializer).getReferencedSym(); return fieldSym instanceof JFieldSymbol && Modifier.isVolatile(((JFieldSymbol) fieldSym).getModifiers()); } else { return false; } } }
if (node.isVoid() || node.getResultTypeNode() instanceof ASTPrimitiveType || node.getBody() == null) { return data; } List<ASTReturnStatement> rsl = node.descendants(ASTReturnStatement.class).toList(); if (rsl.size() != 1) { return data; } ASTReturnStatement rs = rsl.get(0); ASTExpression returnExpr = rs.getExpr(); if (!(returnExpr instanceof ASTNamedReferenceExpr)) { return data; } JVariableSymbol returnVariable = ((ASTNamedReferenceExpr) returnExpr).getReferencedSym(); // With Java5 and volatile keyword, DCL is no longer an issue if (returnVariable instanceof JFieldSymbol && Modifier.isVolatile(((JFieldSymbol) returnVariable).getModifiers())) { return data; } // if the return variable is local and only written with the volatile // field, then it's ok, too if (isLocalOnlyStoredWithVolatileField(node, returnVariable)) { return data; } List<ASTIfStatement> isl = node.descendants(ASTIfStatement.class).toList(); if (isl.size() == 2) { ASTIfStatement outerIf = isl.get(0); if (JavaRuleUtil.isNullCheck(outerIf.getCondition(), returnVariable)) { // find synchronized List<ASTSynchronizedStatement> ssl = outerIf.descendants(ASTSynchronizedStatement.class).toList(); if (ssl.size() == 1 && ssl.get(0).ancestors().any(it -> it == outerIf)) { ASTIfStatement is2 = isl.get(1); if (JavaRuleUtil.isNullCheck(is2.getCondition(), returnVariable)) { List<ASTAssignmentExpression> assignments = is2.descendants(ASTAssignmentExpression.class).toList(); if (assignments.size() == 1 && JavaAstUtils.isReferenceToVar(assignments.get(0).getLeftOperand(), returnVariable)) { asCtx(data).addViolation(node); } } } } } return data;
389
574
963
subhra74_snowflake
snowflake/muon-app/src/main/java/muon/app/ui/laf/AppSkinDark.java
AppSkinDark
initDefaultsDark
class AppSkinDark extends AppSkin { /** * */ public AppSkinDark() { initDefaultsDark(); } private void initDefaultsDark() {<FILL_FUNCTION_BODY>} }
Color selectionColor = new Color(3, 155, 229); Color controlColor = new Color(40, 44, 52); Color textColor = new Color(230, 230, 230); Color selectedTextColor = new Color(230, 230, 230); Color infoTextColor = new Color(180, 180, 180); Color borderColor = new Color(24, 26, 31); Color treeTextColor = new Color(75 + 20, 83 + 20, 98 + 20); Color scrollbarColor = new Color(75, 83, 98); Color scrollbarRolloverColor = new Color(75 + 20, 83 + 20, 98 + 20); Color textFieldColor = new Color(40 + 10, 44 + 10, 52 + 10); Color buttonGradient1 = new Color(57, 62, 74); Color buttonGradient2 = new Color(55 - 10, 61 - 10, 72 - 10); Color buttonGradient3 = new Color(57 + 20, 62 + 20, 74 + 20); Color buttonGradient4 = new Color(57 + 10, 62 + 10, 74 + 10); Color buttonGradient5 = new Color(57 - 20, 62 - 20, 74 - 20); Color buttonGradient6 = new Color(57 - 10, 62 - 10, 74 - 10); this.defaults.put("nimbusBase", controlColor); this.defaults.put("nimbusSelection", selectionColor); this.defaults.put("textBackground", selectionColor); this.defaults.put("textHighlight", selectionColor); this.defaults.put("desktop", selectionColor); this.defaults.put("nimbusFocus", selectionColor); this.defaults.put("ArrowButton.foreground", textColor); this.defaults.put("nimbusSelectionBackground", selectionColor); this.defaults.put("nimbusSelectedText", selectedTextColor); this.defaults.put("control", controlColor); this.defaults.put("nimbusBorder", borderColor); this.defaults.put("Table.alternateRowColor", controlColor); this.defaults.put("nimbusLightBackground", textFieldColor); this.defaults.put("tabSelectionBackground", scrollbarColor); this.defaults.put("Table.background", buttonGradient6); this.defaults.put("Table[Enabled+Selected].textForeground", selectedTextColor); // this.defaults.put("scrollbar", buttonGradient4); // this.defaults.put("scrollbar-hot", buttonGradient3); this.defaults.put("text", textColor); this.defaults.put("menuText", textColor); this.defaults.put("controlText", textColor); this.defaults.put("textForeground", textColor); this.defaults.put("infoText", infoTextColor); this.defaults.put("List.foreground", textColor); this.defaults.put("List.background", controlColor); this.defaults.put("List[Disabled].textForeground", selectedTextColor); this.defaults.put("List[Selected].textBackground", selectionColor); this.defaults.put("Label.foreground", textColor); this.defaults.put("Tree.background", textFieldColor); this.defaults.put("Tree.textForeground", treeTextColor); this.defaults.put("scrollbar", scrollbarColor); this.defaults.put("scrollbar-hot", scrollbarRolloverColor); this.defaults.put("button.normalGradient1", buttonGradient1); this.defaults.put("button.normalGradient2", buttonGradient2); this.defaults.put("button.hotGradient1", buttonGradient3); this.defaults.put("button.hotGradient2", buttonGradient4); this.defaults.put("button.pressedGradient1", buttonGradient5); this.defaults.put("button.pressedGradient2", buttonGradient6); this.defaults.put("TextField.background", textFieldColor); this.defaults.put("FormattedTextField.background", textFieldColor); this.defaults.put("PasswordField.background", textFieldColor); createSkinnedButton(this.defaults); createTextFieldSkin(this.defaults); createSpinnerSkin(this.defaults); createComboBoxSkin(this.defaults); createTreeSkin(this.defaults); createTableHeaderSkin(this.defaults); createPopupMenuSkin(this.defaults); createCheckboxSkin(this.defaults); createRadioButtonSkin(this.defaults); createTooltipSkin(this.defaults); createSkinnedToggleButton(this.defaults); createProgressBarSkin(this.defaults); this.defaults.put("ScrollBarUI", CustomScrollBarUI.class.getName());
77
1,434
1,511
/** * @author subhro */ public abstract class AppSkin { protected UIDefaults defaults; protected NimbusLookAndFeel laf; /** */ public AppSkin(); private void initDefaults(); /** * @return the laf */ public NimbusLookAndFeel getLaf(); protected Font loadFonts(); protected Font loadFontAwesomeFonts(); public Color getDefaultBackground(); public Color getDefaultForeground(); public Color getDefaultSelectionForeground(); public Color getDefaultSelectionBackground(); public Color getDefaultBorderColor(); public Font getIconFont(); public Font getDefaultFont(); public Color getInfoTextForeground(); public Color getAddressBarSelectionBackground(); public Color getAddressBarRolloverBackground(); public UIDefaults getSplitPaneSkin(); public void createSkinnedButton( UIDefaults btnSkin); public void createTextFieldSkin( UIDefaults uiDefaults); public void createSpinnerSkin( UIDefaults uiDefaults); public void createComboBoxSkin( UIDefaults uiDefaults); public void createTreeSkin( UIDefaults uiDefaults); public UIDefaults createToolbarSkin(); public UIDefaults createTabButtonSkin(); public void createTableHeaderSkin( UIDefaults uiDefaults); public void createPopupMenuSkin( UIDefaults uiDefaults); public Color getTableBackgroundColor(); public Color getSelectedTabColor(); public Color getTextFieldBackground(); public void createCheckboxSkin( UIDefaults uiDefaults); public void createRadioButtonSkin( UIDefaults uiDefaults); public void createTooltipSkin( UIDefaults uiDefaults); public void createSkinnedToggleButton( UIDefaults btnSkin); public void createProgressBarSkin( UIDefaults uiDefaults); }
spring-cloud_spring-cloud-gateway
spring-cloud-gateway/spring-cloud-gateway-server/src/main/java/org/springframework/cloud/gateway/filter/ReactiveLoadBalancerClientFilter.java
ReactiveLoadBalancerClientFilter
choose
class ReactiveLoadBalancerClientFilter implements GlobalFilter, Ordered { private static final Log log = LogFactory.getLog(ReactiveLoadBalancerClientFilter.class); /** * Order of filter. */ public static final int LOAD_BALANCER_CLIENT_FILTER_ORDER = 10150; private final LoadBalancerClientFactory clientFactory; private final GatewayLoadBalancerProperties properties; /** * @deprecated in favour of * {@link ReactiveLoadBalancerClientFilter#ReactiveLoadBalancerClientFilter(LoadBalancerClientFactory, GatewayLoadBalancerProperties)} */ @Deprecated public ReactiveLoadBalancerClientFilter(LoadBalancerClientFactory clientFactory, GatewayLoadBalancerProperties properties, LoadBalancerProperties loadBalancerProperties) { this.clientFactory = clientFactory; this.properties = properties; } public ReactiveLoadBalancerClientFilter(LoadBalancerClientFactory clientFactory, GatewayLoadBalancerProperties properties) { this.clientFactory = clientFactory; this.properties = properties; } @Override public int getOrder() { return LOAD_BALANCER_CLIENT_FILTER_ORDER; } @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { URI url = exchange.getAttribute(GATEWAY_REQUEST_URL_ATTR); String schemePrefix = exchange.getAttribute(GATEWAY_SCHEME_PREFIX_ATTR); if (url == null || (!"lb".equals(url.getScheme()) && !"lb".equals(schemePrefix))) { return chain.filter(exchange); } // preserve the original url addOriginalRequestUrl(exchange, url); if (log.isTraceEnabled()) { log.trace(ReactiveLoadBalancerClientFilter.class.getSimpleName() + " url before: " + url); } URI requestUri = exchange.getAttribute(GATEWAY_REQUEST_URL_ATTR); String serviceId = requestUri.getHost(); Set<LoadBalancerLifecycle> supportedLifecycleProcessors = LoadBalancerLifecycleValidator .getSupportedLifecycleProcessors(clientFactory.getInstances(serviceId, LoadBalancerLifecycle.class), RequestDataContext.class, ResponseData.class, ServiceInstance.class); DefaultRequest<RequestDataContext> lbRequest = new DefaultRequest<>(new RequestDataContext( new RequestData(exchange.getRequest(), exchange.getAttributes()), getHint(serviceId))); return choose(lbRequest, serviceId, supportedLifecycleProcessors).doOnNext(response -> { if (!response.hasServer()) { supportedLifecycleProcessors.forEach(lifecycle -> lifecycle .onComplete(new CompletionContext<>(CompletionContext.Status.DISCARD, lbRequest, response))); throw NotFoundException.create(properties.isUse404(), "Unable to find instance for " + url.getHost()); } ServiceInstance retrievedInstance = response.getServer(); URI uri = exchange.getRequest().getURI(); // if the `lb:<scheme>` mechanism was used, use `<scheme>` as the default, // if the loadbalancer doesn't provide one. String overrideScheme = retrievedInstance.isSecure() ? "https" : "http"; if (schemePrefix != null) { overrideScheme = url.getScheme(); } DelegatingServiceInstance serviceInstance = new DelegatingServiceInstance(retrievedInstance, overrideScheme); URI requestUrl = reconstructURI(serviceInstance, uri); if (log.isTraceEnabled()) { log.trace("LoadBalancerClientFilter url chosen: " + requestUrl); } exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, requestUrl); exchange.getAttributes().put(GATEWAY_LOADBALANCER_RESPONSE_ATTR, response); supportedLifecycleProcessors.forEach(lifecycle -> lifecycle.onStartRequest(lbRequest, response)); }).then(chain.filter(exchange)) .doOnError(throwable -> supportedLifecycleProcessors.forEach(lifecycle -> lifecycle .onComplete(new CompletionContext<ResponseData, ServiceInstance, RequestDataContext>( CompletionContext.Status.FAILED, throwable, lbRequest, exchange.getAttribute(GATEWAY_LOADBALANCER_RESPONSE_ATTR))))) .doOnSuccess(aVoid -> supportedLifecycleProcessors.forEach(lifecycle -> lifecycle .onComplete(new CompletionContext<ResponseData, ServiceInstance, RequestDataContext>( CompletionContext.Status.SUCCESS, lbRequest, exchange.getAttribute(GATEWAY_LOADBALANCER_RESPONSE_ATTR), new ResponseData(exchange.getResponse(), new RequestData(exchange.getRequest(), exchange.getAttributes())))))); } protected URI reconstructURI(ServiceInstance serviceInstance, URI original) { return LoadBalancerUriTools.reconstructURI(serviceInstance, original); } private Mono<Response<ServiceInstance>> choose(Request<RequestDataContext> lbRequest, String serviceId, Set<LoadBalancerLifecycle> supportedLifecycleProcessors) {<FILL_FUNCTION_BODY>} private String getHint(String serviceId) { LoadBalancerProperties loadBalancerProperties = clientFactory.getProperties(serviceId); Map<String, String> hints = loadBalancerProperties.getHint(); String defaultHint = hints.getOrDefault("default", "default"); String hintPropertyValue = hints.get(serviceId); return hintPropertyValue != null ? hintPropertyValue : defaultHint; } }
ReactorLoadBalancer<ServiceInstance> loadBalancer = this.clientFactory.getInstance(serviceId, ReactorServiceInstanceLoadBalancer.class); if (loadBalancer == null) { throw new NotFoundException("No loadbalancer available for " + serviceId); } supportedLifecycleProcessors.forEach(lifecycle -> lifecycle.onStart(lbRequest)); return loadBalancer.choose(lbRequest);
1,522
117
1,639
PlexPt_chatgpt-java
chatgpt-java/src/main/java/com/plexpt/chatgpt/Images.java
Images
init
class Images { /** * keys */ private String apiKey; private List<String> apiKeyList; /** * 自定义api host使用builder的方式构造client */ @Builder.Default private String apiHost = Api.DEFAULT_API_HOST; private Api apiClient; private OkHttpClient okHttpClient; /** * 超时 默认300 */ @Builder.Default private long timeout = 300; /** * okhttp 代理 */ @Builder.Default private Proxy proxy = Proxy.NO_PROXY; /** * 初始化 */ public Images init() {<FILL_FUNCTION_BODY>} public ImagesRensponse generations(Generations generations){ Single<ImagesRensponse> imagesRensponse = this.apiClient.imageGenerations(generations); return imagesRensponse.blockingGet(); } public ImagesRensponse edits(File image,File mask,Edits edits){ RequestBody i = RequestBody.create(MediaType.parse("multipart/form-data;charset=UTF-8"), image); MultipartBody.Part iPart = MultipartBody.Part.createFormData("image", image.getName(), i); RequestBody m = RequestBody.create(MediaType.parse("multipart/form-data;charset=UTF-8"), mask); MultipartBody.Part mPart = MultipartBody.Part.createFormData("mask", mask.getName(), m); Single<ImagesRensponse> imagesRensponse = this.apiClient.imageEdits(iPart,mPart,edits); return imagesRensponse.blockingGet(); } public ImagesRensponse variations(File image,Variations variations){ RequestBody i = RequestBody.create(MediaType.parse("multipart/form-data;charset=UTF-8"), image); MultipartBody.Part iPart = MultipartBody.Part.createFormData("image", image.getName(), i); Single<ImagesRensponse> imagesRensponse = this.apiClient.imageVariations(iPart,variations); return imagesRensponse.blockingGet(); } }
OkHttpClient.Builder client = new OkHttpClient.Builder(); client.addInterceptor(chain -> { Request original = chain.request(); String key = apiKey; if (apiKeyList != null && !apiKeyList.isEmpty()) { key = RandomUtil.randomEle(apiKeyList); } Request request = original.newBuilder() .header(Header.AUTHORIZATION.getValue(), "Bearer " + key) .header(Header.CONTENT_TYPE.getValue(), ContentType.JSON.getValue()) .method(original.method(), original.body()) .build(); return chain.proceed(request); }).addInterceptor(chain -> { Request original = chain.request(); Response response = chain.proceed(original); if (!response.isSuccessful()) { String errorMsg = response.body().string(); log.error("请求异常:{}", errorMsg); BaseResponse baseResponse = JSON.parseObject(errorMsg, BaseResponse.class); if (Objects.nonNull(baseResponse.getError())) { log.error(baseResponse.getError().getMessage()); throw new ChatException(baseResponse.getError().getMessage()); } throw new ChatException("error"); } return response; }); client.connectTimeout(timeout, TimeUnit.SECONDS); client.writeTimeout(timeout, TimeUnit.SECONDS); client.readTimeout(timeout, TimeUnit.SECONDS); if (Objects.nonNull(proxy)) { client.proxy(proxy); } OkHttpClient httpClient = client.build(); this.okHttpClient = httpClient; this.apiClient = new Retrofit.Builder() .baseUrl(this.apiHost) .client(okHttpClient) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(JacksonConverterFactory.create()) .build() .create(Api.class); return this;
571
512
1,083
orientechnologies_orientdb
orientdb/core/src/main/java/com/orientechnologies/orient/core/index/ORuntimeKeyIndexDefinition.java
ORuntimeKeyIndexDefinition
toCreateIndexDDL
class ORuntimeKeyIndexDefinition<T> extends OAbstractIndexDefinition { private static final long serialVersionUID = -8855918974071833818L; private transient OBinarySerializer<T> serializer; @SuppressWarnings("unchecked") public ORuntimeKeyIndexDefinition(final byte iId) { super(); serializer = (OBinarySerializer<T>) OBinarySerializerFactory.getInstance().getObjectSerializer(iId); if (serializer == null) throw new OConfigurationException( "Runtime index definition cannot find binary serializer with id=" + iId + ". Assure to plug custom serializer into the server."); } public ORuntimeKeyIndexDefinition() {} public List<String> getFields() { return Collections.emptyList(); } public List<String> getFieldsToIndex() { return Collections.emptyList(); } public String getClassName() { return null; } public Comparable<?> createValue(final List<?> params) { return (Comparable<?>) params.get(0); } public Comparable<?> createValue(final Object... params) { return createValue(Arrays.asList(params)); } public int getParamCount() { return 1; } public OType[] getTypes() { return new OType[0]; } @Override public ODocument toStream() { serializeToStream(); return document; } @Override protected void serializeToStream() { super.serializeToStream(); document.field("keySerializerId", serializer.getId()); document.field("collate", collate.getName()); document.field("nullValuesIgnored", isNullValuesIgnored()); } public void fromStream(ODocument document) { this.document = document; serializeFromStream(); } @Override protected void serializeFromStream() { super.serializeFromStream(); final byte keySerializerId = ((Number) document.field("keySerializerId")).byteValue(); //noinspection unchecked serializer = (OBinarySerializer<T>) OBinarySerializerFactory.getInstance().getObjectSerializer(keySerializerId); if (serializer == null) throw new OConfigurationException( "Runtime index definition cannot find binary serializer with id=" + keySerializerId + ". Assure to plug custom serializer into the server."); setNullValuesIgnored(!Boolean.FALSE.equals(document.<Boolean>field("nullValuesIgnored"))); } public Object getDocumentValueToIndex(final ODocument iDocument) { throw new OIndexException("This method is not supported in given index definition."); } @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final ORuntimeKeyIndexDefinition<?> that = (ORuntimeKeyIndexDefinition<?>) o; return serializer.equals(that.serializer); } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + serializer.getId(); return result; } @Override public String toString() { return "ORuntimeKeyIndexDefinition{" + "serializer=" + serializer.getId() + '}'; } /** {@inheritDoc} */ public String toCreateIndexDDL(final String indexName, final String indexType, String engine) {<FILL_FUNCTION_BODY>} public OBinarySerializer<T> getSerializer() { return serializer; } @Override public boolean isAutomatic() { return getClassName() != null; } }
return "create index `" + indexName + "` " + indexType + ' ' + "runtime " + serializer.getId();
996
34
1,030
/** * Abstract index definiton implementation. * @author Luca Garulli (l.garulli--(at)--orientdb.com) */ public abstract class OAbstractIndexDefinition implements OIndexDefinition { protected OCollate collate=new ODefaultCollate(); private boolean nullValuesIgnored=true; protected ODocument document; protected OAbstractIndexDefinition(); public OCollate getCollate(); public void setCollate( final OCollate collate); public void setCollate( String iCollate); @Override public boolean equals( Object o); @Override public int hashCode(); @Override public boolean isNullValuesIgnored(); @Override public void setNullValuesIgnored( boolean value); protected void serializeToStream(); protected void serializeFromStream(); }
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/hook/HookLoader.java
HookLoader
load
class HookLoader extends BaseHook { private static final Log log = LogFactory.getLog(HookLoader.class); public static HookLoader load(Emulator<?> emulator) {<FILL_FUNCTION_BODY>} private final Symbol _hook_objc_msgSend; private final Symbol _hook_dispatch_async; private HookLoader(Emulator<?> emulator) { super(emulator, "libhook"); _hook_objc_msgSend = module.findSymbolByName("_hook_objc_msgSend", false); if (_hook_objc_msgSend == null) { throw new IllegalStateException("find _hook_objc_msgSend failed"); } _hook_dispatch_async = module.findSymbolByName("_hook_dispatch_async", false); if (_hook_dispatch_async == null) { throw new IllegalStateException("find _hook_dispatch_async failed"); } } private boolean objcMsgSendHooked; public synchronized void hookObjcMsgSend(final MsgSendCallback callback) { if (objcMsgSendHooked) { throw new IllegalStateException("objc_msgSend already hooked."); } SvcMemory svcMemory = emulator.getSvcMemory(); Pointer pointer = callback == null ? null : svcMemory.registerSvc(emulator.is64Bit() ? new Arm64Svc() { @Override public long handle(Emulator<?> emulator) { return objc_msgSend_callback(emulator, callback); } } : new ArmSvc() { @Override public long handle(Emulator<?> emulator) { return objc_msgSend_callback(emulator, callback); } }); _hook_objc_msgSend.call(emulator, pointer); objcMsgSendHooked = true; } private boolean dispatchAsyncHooked; public synchronized void hookDispatchAsync(final DispatchAsyncCallback callback) { if (dispatchAsyncHooked) { throw new IllegalStateException("dispatch_async already hooked."); } if (emulator.is32Bit()) { throw new UnsupportedOperationException(); } SvcMemory svcMemory = emulator.getSvcMemory(); Pointer pointer = callback == null ? null : svcMemory.registerSvc(new Arm64Svc() { @Override public long handle(Emulator<?> emulator) { return dispatch_callback(emulator, callback); } }); _hook_dispatch_async.call(emulator, pointer); dispatchAsyncHooked = true; } private long dispatch_callback(Emulator<?> emulator, DispatchAsyncCallback callback) { RegisterContext context = emulator.getContext(); Pointer dq = context.getPointerArg(0); Pointer block = context.getPointerArg(1); Pointer fun = block.getPointer(0x10); boolean is_barrier_async = context.getIntArg(2) != 0; boolean dispatch = callback.canDispatch(emulator, dq, fun, is_barrier_async); if (!dispatch && (log.isDebugEnabled() || LogFactory.getLog(AbstractEmulator.class).isDebugEnabled())) { System.err.println("Skip dispatch_async dq=" + dq + ", fun=" + fun); } return dispatch ? 1 : 0; } private long objc_msgSend_callback(Emulator<?> emulator, MsgSendCallback callback) { RegisterContext context = emulator.getContext(); boolean systemClass = context.getIntArg(0) != 0; Pointer classNamePointer = context.getPointerArg(1); String cmd = context.getPointerArg(2).getString(0); Pointer lr = context.getPointerArg(3); callback.onMsgSend(emulator, systemClass, classNamePointer == null ? null : classNamePointer.getString(0), cmd, lr); return 0; } }
Substrate.getInstance(emulator); // load substrate first FishHook.getInstance(emulator); // load fishhook HookLoader loader = emulator.get(HookLoader.class.getName()); if (loader == null) { loader = new HookLoader(emulator); emulator.set(HookLoader.class.getName(), loader); } return loader;
1,034
98
1,132
public abstract class BaseHook implements IHook { protected final Emulator<?> emulator; protected final Module module; public BaseHook( Emulator<?> emulator, String libName); protected Pointer createReplacePointer( final ReplaceCallback callback, final Pointer backup, boolean enablePostCall); protected LibraryFile resolveLibrary( String libName); @Override public Module getModule(); }
houbb_sensitive-word
sensitive-word/src/main/java/com/github/houbb/sensitive/word/support/data/WordDataTree.java
WordDataTree
initWordData
class WordDataTree implements IWordData { /** * 根节点 */ private WordDataTreeNode root; @Override public synchronized void initWordData(Collection<String> collection) {<FILL_FUNCTION_BODY>} @Override public WordContainsTypeEnum contains(StringBuilder stringBuilder, InnerSensitiveWordContext innerContext) { WordDataTreeNode nowNode = root; int len = stringBuilder.length(); for(int i = 0; i < len; i++) { // 获取当前的 map 信息 nowNode = getNowMap(nowNode, i, stringBuilder, innerContext); // 如果不为空,则判断是否为结尾。 if (ObjectUtil.isNull(nowNode)) { return WordContainsTypeEnum.NOT_FOUND; } } if(nowNode.end()) { return WordContainsTypeEnum.CONTAINS_END; } return WordContainsTypeEnum.CONTAINS_PREFIX; } /** * 获取当前的 Map * @param nowNode 当前节点 * @param index 下标 * @param stringBuilder 文本缓存 * @param sensitiveContext 上下文 * @return 实际的当前 map * @since 0.0.7 */ private WordDataTreeNode getNowMap(WordDataTreeNode nowNode, final int index, final StringBuilder stringBuilder, final InnerSensitiveWordContext sensitiveContext) { final IWordContext context = sensitiveContext.wordContext(); // 这里的 char 已经是统一格式化之后的,所以可以不用再次格式化。 char mappingChar = stringBuilder.charAt(index); // 这里做一次重复词的处理 WordDataTreeNode currentMap = nowNode.getSubNode(mappingChar); // 启用忽略重复&当前下标不是第一个 if(context.ignoreRepeat() && index > 0) { char preMappingChar = stringBuilder.charAt(index-1); // 直接赋值为上一个 map if(preMappingChar == mappingChar) { currentMap = nowNode; } } return currentMap; } }
WordDataTreeNode newRoot = new WordDataTreeNode(); for(String word : collection) { if(StringUtil.isEmpty(word)) { continue; } WordDataTreeNode tempNode = newRoot; char[] chars = word.toCharArray(); for (char c : chars) { // 获取子节点 WordDataTreeNode subNode = tempNode.getSubNode(c); if (subNode == null) { subNode = new WordDataTreeNode(); // 加入新的子节点 tempNode.addSubNode(c, subNode); } // 临时节点指向子节点,进入下一次循环 tempNode = subNode; } // 设置结束标识(循环结束,设置一次即可) tempNode.end(true); } // 初始化完成才做替换 this.root = newRoot;
577
240
817
DerekYRC_mini-spring
mini-spring/src/main/java/org/springframework/context/support/AbstractXmlApplicationContext.java
AbstractXmlApplicationContext
loadBeanDefinitions
class AbstractXmlApplicationContext extends AbstractRefreshableApplicationContext { protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) {<FILL_FUNCTION_BODY>} protected abstract String[] getConfigLocations(); }
XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory, this); String[] configLocations = getConfigLocations(); if (configLocations != null) { beanDefinitionReader.loadBeanDefinitions(configLocations); }
60
71
131
/** * @author derekyi * @date 2020/11/28 */ public abstract class AbstractRefreshableApplicationContext extends AbstractApplicationContext { private DefaultListableBeanFactory beanFactory; /** * 创建beanFactory并加载BeanDefinition * @throws BeansException */ protected final void refreshBeanFactory() throws BeansException; /** * 创建bean工厂 * @return */ protected DefaultListableBeanFactory createBeanFactory(); /** * 加载BeanDefinition * @param beanFactory * @throws BeansException */ protected abstract void loadBeanDefinitions( DefaultListableBeanFactory beanFactory) throws BeansException ; public DefaultListableBeanFactory getBeanFactory(); }
DerekYRC_mini-spring
mini-spring/src/main/java/org/springframework/context/support/ApplicationContextAwareProcessor.java
ApplicationContextAwareProcessor
postProcessBeforeInitialization
class ApplicationContextAwareProcessor implements BeanPostProcessor { private final ApplicationContext applicationContext; public ApplicationContextAwareProcessor(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {<FILL_FUNCTION_BODY>} @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { return bean; } }
if (bean instanceof ApplicationContextAware) { ((ApplicationContextAware) bean).setApplicationContext(applicationContext); } return bean;
120
41
161
joelittlejohn_jsonschema2pojo
jsonschema2pojo/jsonschema2pojo-core/src/main/java/org/jsonschema2pojo/util/TypeUtil.java
TypeUtil
buildClass
class TypeUtil { public static JClass resolveType(JClassContainer _package, String typeDefinition) { try { FieldDeclaration fieldDeclaration = (FieldDeclaration) JavaParser.parseBodyDeclaration(typeDefinition + " foo;"); ClassOrInterfaceType c = (ClassOrInterfaceType) ((ReferenceType) fieldDeclaration.getType()).getType(); return buildClass(_package, c, 0); } catch (ParseException e) { throw new GenerationException("Couldn't parse type: " + typeDefinition, e); } } private static JClass buildClass(JClassContainer _package, ClassOrInterfaceType c, int arrayCount) {<FILL_FUNCTION_BODY>} }
final String packagePrefix = (c.getScope() != null) ? c.getScope().toString() + "." : ""; JClass _class = _package.owner().ref(packagePrefix + c.getName()); for (int i = 0; i < arrayCount; i++) { _class = _class.array(); } List<Type> typeArgs = c.getTypeArgs(); if (typeArgs != null && typeArgs.size() > 0) { JClass[] genericArgumentClasses = new JClass[typeArgs.size()]; for (int i = 0; i < typeArgs.size(); i++) { final Type type = typeArgs.get(i); final JClass resolvedClass; if (type instanceof WildcardType) { final WildcardType wildcardType = (WildcardType) type; if (wildcardType.getSuper() != null) { throw new IllegalArgumentException("\"? super \" declaration is not yet supported"); } else if (wildcardType.getExtends() != null) { resolvedClass = buildClass(_package, (ClassOrInterfaceType) wildcardType.getExtends().getType(), 0).wildcard(); } else { resolvedClass = _package.owner().ref(Object.class).wildcard(); } } else { final ReferenceType referenceType = (ReferenceType) type; resolvedClass = buildClass(_package, (ClassOrInterfaceType) referenceType.getType(), referenceType.getArrayCount()); } genericArgumentClasses[i] = resolvedClass; } _class = _class.narrow(genericArgumentClasses); } return _class;
177
418
595
PlayEdu_PlayEdu
PlayEdu/playedu-common/src/main/java/xyz/playedu/common/util/RedisDistributedLock.java
RedisDistributedLock
releaseLock
class RedisDistributedLock { private final StringRedisTemplate redisTemplate; private final ThreadLocal<String> lockValue = new ThreadLocal<>(); public RedisDistributedLock(StringRedisTemplate redisTemplate) { this.redisTemplate = redisTemplate; } public boolean tryLock(String key, long expire, TimeUnit timeUnit) { String value = UUID.randomUUID().toString(); Boolean success = redisTemplate.opsForValue().setIfAbsent(key, value, expire, timeUnit); if (Boolean.TRUE.equals(success)) { lockValue.set(value); return true; } return false; } public boolean releaseLock(String key) {<FILL_FUNCTION_BODY>} }
String value = lockValue.get(); if (value == null) { return false; } DefaultRedisScript<Boolean> script = new DefaultRedisScript<>( "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del'," + " KEYS[1]) else return 0 end", Boolean.class); Boolean success = redisTemplate.execute(script, Collections.singletonList(key), value); if (Boolean.TRUE.equals(success)) { lockValue.remove(); return true; } return false;
197
161
358
logfellow_logstash-logback-encoder
logstash-logback-encoder/src/main/java/net/logstash/logback/composite/GlobalCustomFieldsJsonProvider.java
GlobalCustomFieldsJsonProvider
setCustomFieldsNode
class GlobalCustomFieldsJsonProvider<Event extends DeferredProcessingAware> extends AbstractJsonProvider<Event> implements JsonFactoryAware { /** * The un-parsed custom fields string to use to initialize customFields * when the formatter is started. */ private String customFields; /** * When non-null, the fields in this JsonNode will be embedded in the logstash json. */ private ObjectNode customFieldsNode; /** * The factory used to convert the JSON string into a valid {@link ObjectNode} when custom * fields are set as text instead of a pre-parsed Jackson ObjectNode. */ private JsonFactory jsonFactory; @Override public void writeTo(JsonGenerator generator, Event event) throws IOException { writeFieldsOfNode(generator, customFieldsNode); } /** * Writes the fields of the given node into the generator. */ private void writeFieldsOfNode(JsonGenerator generator, JsonNode node) throws IOException { if (node != null) { for (Iterator<Entry<String, JsonNode>> fields = node.fields(); fields.hasNext();) { Entry<String, JsonNode> field = fields.next(); generator.writeFieldName(field.getKey()); generator.writeTree(field.getValue()); } } } /** * Start the provider. * * <p>The provider is started even when it fails to parse the {@link #customFields} JSON string. * An ERROR status is emitted instead and no exception is thrown. */ @Override public void start() { initializeCustomFields(); super.start(); } private void initializeCustomFields() { if (customFieldsNode != null || customFields == null) { return; } if (jsonFactory == null) { throw new IllegalStateException("JsonFactory has not been set"); } try { this.customFieldsNode = JsonReadingUtils.readFullyAsObjectNode(this.jsonFactory, this.customFields); } catch (IOException e) { addError("[customFields] is not a valid JSON object", e); } } /** * Set the custom fields as a JSON string. * The string will be parsed when the provider is {@link #start()}. * * @param customFields the custom fields as JSON string. */ public void setCustomFields(String customFields) { if (isStarted()) { throw new IllegalStateException("Configuration cannot be changed while the provider is started"); } this.customFields = customFields; this.customFieldsNode = null; } public String getCustomFields() { return customFields; } public ObjectNode getCustomFieldsNode() { return this.customFieldsNode; } /** * Set the custom JSON fields. * Must be a valid JsonNode that maps to a JSON object structure, i.e. an {@link ObjectNode}. * * @param customFields a {@link JsonNode} whose properties must be added as custom fields. * @deprecated use {@link #setCustomFieldsNode(ObjectNode)} instead. * @throws IllegalArgumentException if the argument is not a {@link ObjectNode}. */ @Deprecated public void setCustomFieldsNode(JsonNode customFields) { if (customFields != null && !(customFields instanceof ObjectNode)) { throw new IllegalArgumentException("Must be an ObjectNode"); } setCustomFieldsNode((ObjectNode) customFields); } /** * Use the fields of the given {@link ObjectNode} (may be empty). * * @param customFields the JSON object whose fields as added as custom fields */ public void setCustomFieldsNode(ObjectNode customFields) {<FILL_FUNCTION_BODY>} @Override public void setJsonFactory(JsonFactory jsonFactory) { this.jsonFactory = Objects.requireNonNull(jsonFactory); } }
if (isStarted()) { throw new IllegalStateException("Configuration cannot be changed while the provider is started"); } this.customFieldsNode = customFields; this.customFields = null;
1,017
55
1,072
joelittlejohn_jsonschema2pojo
jsonschema2pojo/jsonschema2pojo-core/src/main/java/org/jsonschema2pojo/rules/MinimumMaximumRule.java
MinimumMaximumRule
isApplicableType
class MinimumMaximumRule implements Rule<JFieldVar, JFieldVar> { private final RuleFactory ruleFactory; protected MinimumMaximumRule(RuleFactory ruleFactory) { this.ruleFactory = ruleFactory; } @Override public JFieldVar apply(String nodeName, JsonNode node, JsonNode parent, JFieldVar field, Schema currentSchema) { if (ruleFactory.getGenerationConfig().isIncludeJsr303Annotations() && isApplicableType(field)) { if (node.has("minimum")) { final Class<? extends Annotation> decimalMinClass = ruleFactory.getGenerationConfig().isUseJakartaValidation() ? DecimalMin.class : javax.validation.constraints.DecimalMin.class; JAnnotationUse annotation = field.annotate(decimalMinClass); annotation.param("value", node.get("minimum").asText()); } if (node.has("maximum")) { final Class<? extends Annotation> decimalMaxClass = ruleFactory.getGenerationConfig().isUseJakartaValidation() ? DecimalMax.class : javax.validation.constraints.DecimalMax.class; JAnnotationUse annotation = field.annotate(decimalMaxClass); annotation.param("value", node.get("maximum").asText()); } } return field; } private boolean isApplicableType(JFieldVar field) {<FILL_FUNCTION_BODY>} }
try { Class<?> fieldClass = Class.forName(field.type().boxify().fullName()); // Support Strings and most number types except Double and Float, per docs on DecimalMax/Min annotations return String.class.isAssignableFrom(fieldClass) || (Number.class.isAssignableFrom(fieldClass) && !Float.class.isAssignableFrom(fieldClass) && !Double.class.isAssignableFrom(fieldClass)); } catch (ClassNotFoundException ignore) { return false; }
387
142
529
subhra74_snowflake
snowflake/muon-jediterm/src/main/java/com/jediterm/terminal/model/hyperlinks/TextProcessing.java
TextProcessing
doProcessHyperlinks
class TextProcessing { private static final Logger LOG = Logger.getLogger(TextProcessing.class); private final List<HyperlinkFilter> myHyperlinkFilter; private TextStyle myHyperlinkColor; private HyperlinkStyle.HighlightMode myHighlightMode; private TerminalTextBuffer myTerminalTextBuffer; public TextProcessing( TextStyle hyperlinkColor, HyperlinkStyle.HighlightMode highlightMode) { myHyperlinkColor = hyperlinkColor; myHighlightMode = highlightMode; myHyperlinkFilter = new ArrayList<>(); } public void setTerminalTextBuffer( TerminalTextBuffer terminalTextBuffer) { myTerminalTextBuffer = terminalTextBuffer; } public void processHyperlinks( LinesBuffer buffer, TerminalLine updatedLine) { if (myHyperlinkFilter.isEmpty()) return; doProcessHyperlinks(buffer, updatedLine); } private void doProcessHyperlinks( LinesBuffer buffer, TerminalLine updatedLine) {<FILL_FUNCTION_BODY>} private int findHistoryLineInd( LinesBuffer historyBuffer, TerminalLine line) { int lastLineInd = Math.max(0, historyBuffer.getLineCount() - 200); // check only last lines in history buffer for (int i = historyBuffer.getLineCount() - 1; i >= lastLineInd; i--) { if (historyBuffer.getLine(i) == line) { return i; } } return -1; } private static int findLineInd( LinesBuffer buffer, TerminalLine line) { for (int i = 0; i < buffer.getLineCount(); i++) { TerminalLine l = buffer.getLine(i); if (l == line) { return i; } } return -1; } private String joinLines( LinesBuffer buffer, int startLineInd, int updatedLineInd) { StringBuilder result = new StringBuilder(); for (int i = startLineInd; i <= updatedLineInd; i++) { String text = buffer.getLine(i).getText(); if (i < updatedLineInd && text.length() < myTerminalTextBuffer.getWidth()) { text = text + new CharBuffer(CharUtils.NUL_CHAR, myTerminalTextBuffer.getWidth() - text.length()); } result.append(text); } return result.toString(); } public void addHyperlinkFilter( HyperlinkFilter filter) { myHyperlinkFilter.add(filter); } }
myTerminalTextBuffer.lock(); try { int updatedLineInd = findLineInd(buffer, updatedLine); if (updatedLineInd == -1) { // When lines arrive fast enough, the line might be pushed to the history buffer already. updatedLineInd = findHistoryLineInd(myTerminalTextBuffer.getHistoryBuffer(), updatedLine); if (updatedLineInd == -1) { LOG.debug("Cannot find line for links processing"); return; } buffer = myTerminalTextBuffer.getHistoryBuffer(); } int startLineInd = updatedLineInd; while (startLineInd > 0 && buffer.getLine(startLineInd - 1).isWrapped()) { startLineInd--; } String lineStr = joinLines(buffer, startLineInd, updatedLineInd); for (HyperlinkFilter filter : myHyperlinkFilter) { LinkResult result = filter.apply(lineStr); if (result != null) { for (LinkResultItem item : result.getItems()) { TextStyle style = new HyperlinkStyle(myHyperlinkColor.getForeground(), myHyperlinkColor.getBackground(), item.getLinkInfo(), myHighlightMode, null); if (item.getStartOffset() < 0 || item.getEndOffset() > lineStr.length()) continue; int prevLinesLength = 0; for (int lineInd = startLineInd; lineInd <= updatedLineInd; lineInd++) { int startLineOffset = Math.max(prevLinesLength, item.getStartOffset()); int endLineOffset = Math.min(prevLinesLength + myTerminalTextBuffer.getWidth(), item.getEndOffset()); if (startLineOffset < endLineOffset) { buffer.getLine(lineInd).writeString(startLineOffset - prevLinesLength, new CharBuffer(lineStr.substring(startLineOffset, endLineOffset)), style); } prevLinesLength += myTerminalTextBuffer.getWidth(); } } } } } finally { myTerminalTextBuffer.unlock(); }
663
528
1,191
obsidiandynamics_kafdrop
kafdrop/src/main/java/kafdrop/model/ConsumerPartitionVO.java
ConsumerPartitionVO
toString
class ConsumerPartitionVO { private final String groupId; private final String topic; private final int partitionId; private long offset; private long size; private long firstOffset; public ConsumerPartitionVO(String groupId, String topic, int partitionId) { this.groupId = groupId; this.topic = topic; this.partitionId = partitionId; } public String getTopic() { return topic; } public int getPartitionId() { return partitionId; } public long getSize() { return size; } public void setSize(long size) { this.size = size; } public long getFirstOffset() { return firstOffset; } public void setFirstOffset(long firstOffset) { this.firstOffset = firstOffset; } public long getLag() { if (size < 0 || firstOffset < 0) { return 0; } else if (offset < firstOffset) { return size - firstOffset; } else { return size - offset; } } public long getOffset() { return offset; } public void setOffset(long offset) { this.offset = offset; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return ConsumerPartitionVO.class.getSimpleName() + " [groupId=" + groupId + ", topic=" + topic + ", partitionId=" + partitionId + ", offset=" + offset + ", size=" + size + ", firstOffset=" + firstOffset + "]";
358
73
431
joelittlejohn_jsonschema2pojo
jsonschema2pojo/jsonschema2pojo-core/src/main/java/org/jsonschema2pojo/rules/PatternRule.java
PatternRule
isApplicableType
class PatternRule implements Rule<JFieldVar, JFieldVar> { private RuleFactory ruleFactory; public PatternRule(RuleFactory ruleFactory) { this.ruleFactory = ruleFactory; } @Override public JFieldVar apply(String nodeName, JsonNode node, JsonNode parent, JFieldVar field, Schema currentSchema) { if (ruleFactory.getGenerationConfig().isIncludeJsr303Annotations() && isApplicableType(field)) { final Class<? extends Annotation> patternClass = ruleFactory.getGenerationConfig().isUseJakartaValidation() ? Pattern.class : javax.validation.constraints.Pattern.class; JAnnotationUse annotation = field.annotate(patternClass); annotation.param("regexp", node.asText()); } return field; } private boolean isApplicableType(JFieldVar field) {<FILL_FUNCTION_BODY>} }
try { Class<?> fieldClass = Class.forName(field.type().boxify().fullName()); return String.class.isAssignableFrom(fieldClass); } catch (ClassNotFoundException ignore) { return false; }
249
66
315
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-serializer/autoload-cache-serializer-api/src/main/java/com/jarvis/cache/serializer/CompressorSerializer.java
CompressorSerializer
serialize
class CompressorSerializer implements ISerializer<Object> { private static final int DEFAULT_COMPRESSION_THRESHOLD = 16384; private int compressionThreshold = DEFAULT_COMPRESSION_THRESHOLD; private final ISerializer<Object> serializer; private final ICompressor compressor; public CompressorSerializer(ISerializer<Object> serializer) { this.serializer = serializer; this.compressor = new CommonsCompressor(CompressorStreamFactory.GZIP); } public CompressorSerializer(ISerializer<Object> serializer, int compressionThreshold) { this.serializer = serializer; this.compressionThreshold = compressionThreshold; this.compressor = new CommonsCompressor(CompressorStreamFactory.GZIP); } public CompressorSerializer(ISerializer<Object> serializer, int compressionThreshold, String compressType) { this.serializer = serializer; this.compressionThreshold = compressionThreshold; this.compressor = new CommonsCompressor(compressType); } public CompressorSerializer(ISerializer<Object> serializer, int compressionThreshold, ICompressor compressor) { this.serializer = serializer; this.compressionThreshold = compressionThreshold; this.compressor = compressor; } @Override public byte[] serialize(final Object obj) throws Exception {<FILL_FUNCTION_BODY>} @Override public Object deserialize(final byte[] bytes, final Type returnType) throws Exception { if (null == bytes || bytes.length == 0) { return null; } byte flag = bytes[0]; byte[] data; if (flag == 0) { data = new byte[bytes.length - 1]; System.arraycopy(bytes, 1, data, 0, data.length); } else { data = compressor.decompress(new ByteArrayInputStream(bytes, 1, bytes.length - 1)); } return serializer.deserialize(data, returnType); } @Override public Object deepClone(Object obj, final Type type) throws Exception { return serializer.deepClone(obj, type); } @Override public Object[] deepCloneMethodArgs(Method method, Object[] args) throws Exception { return serializer.deepCloneMethodArgs(method, args); } }
if (null == obj) { return null; } byte[] data = serializer.serialize(obj); byte flag = 0; if (data.length > compressionThreshold) { data = compressor.compress(new ByteArrayInputStream(data)); flag = 1; } byte[] out = new byte[data.length + 1]; out[0] = flag; System.arraycopy(data, 0, out, 1, data.length); return out;
633
130
763
logfellow_logstash-logback-encoder
logstash-logback-encoder/src/main/java/net/logstash/logback/mask/RegexValueMasker.java
RegexValueMasker
mask
class RegexValueMasker implements ValueMasker { private final Pattern pattern; private final Object mask; /** * @param regex the regex used to identify values to mask * @param mask the value to write for values that match the regex (can contain back references to capture groups in the regex) */ public RegexValueMasker(String regex, Object mask) { this(Pattern.compile(regex), mask); } /** * @param pattern the pattern used to identify values to mask * @param mask the value to write for values that match the regex (can contain back references to capture groups in the regex) */ public RegexValueMasker(Pattern pattern, Object mask) { this.pattern = Objects.requireNonNull(pattern, "pattern must not be null"); this.mask = Objects.requireNonNull(mask, "mask must not be null"); } @Override public Object mask(JsonStreamContext context, Object o) {<FILL_FUNCTION_BODY>} }
if (o instanceof CharSequence) { Matcher matcher = pattern.matcher((CharSequence) o); if (mask instanceof String) { String replaced = matcher.replaceAll((String) mask); if (replaced != o) { return replaced; } } else if (matcher.matches()) { return mask; } } return null;
254
102
356
YunaiV_ruoyi-vue-pro
ruoyi-vue-pro/yudao-framework/yudao-spring-boot-starter-security/src/main/java/cn/iocoder/yudao/framework/security/core/filter/TokenAuthenticationFilter.java
TokenAuthenticationFilter
doFilterInternal
class TokenAuthenticationFilter extends OncePerRequestFilter { private final SecurityProperties securityProperties; private final GlobalExceptionHandler globalExceptionHandler; private final OAuth2TokenApi oauth2TokenApi; @Override @SuppressWarnings("NullableProblems") protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {<FILL_FUNCTION_BODY>} private LoginUser buildLoginUserByToken(String token, Integer userType) { try { OAuth2AccessTokenCheckRespDTO accessToken = oauth2TokenApi.checkAccessToken(token); if (accessToken == null) { return null; } // 用户类型不匹配,无权限 // 注意:只有 /admin-api/* 和 /app-api/* 有 userType,才需要比对用户类型 // 类似 WebSocket 的 /ws/* 连接地址,是不需要比对用户类型的 if (userType != null && ObjectUtil.notEqual(accessToken.getUserType(), userType)) { throw new AccessDeniedException("错误的用户类型"); } // 构建登录用户 return new LoginUser().setId(accessToken.getUserId()).setUserType(accessToken.getUserType()) .setInfo(accessToken.getUserInfo()) // 额外的用户信息 .setTenantId(accessToken.getTenantId()).setScopes(accessToken.getScopes()); } catch (ServiceException serviceException) { // 校验 Token 不通过时,考虑到一些接口是无需登录的,所以直接返回 null 即可 return null; } } /** * 模拟登录用户,方便日常开发调试 * * 注意,在线上环境下,一定要关闭该功能!!! * * @param request 请求 * @param token 模拟的 token,格式为 {@link SecurityProperties#getMockSecret()} + 用户编号 * @param userType 用户类型 * @return 模拟的 LoginUser */ private LoginUser mockLoginUser(HttpServletRequest request, String token, Integer userType) { if (!securityProperties.getMockEnable()) { return null; } // 必须以 mockSecret 开头 if (!token.startsWith(securityProperties.getMockSecret())) { return null; } // 构建模拟用户 Long userId = Long.valueOf(token.substring(securityProperties.getMockSecret().length())); return new LoginUser().setId(userId).setUserType(userType) .setTenantId(WebFrameworkUtils.getTenantId(request)); } }
String token = SecurityFrameworkUtils.obtainAuthorization(request, securityProperties.getTokenHeader(), securityProperties.getTokenParameter()); if (StrUtil.isNotEmpty(token)) { Integer userType = WebFrameworkUtils.getLoginUserType(request); try { // 1.1 基于 token 构建登录用户 LoginUser loginUser = buildLoginUserByToken(token, userType); // 1.2 模拟 Login 功能,方便日常开发调试 if (loginUser == null) { loginUser = mockLoginUser(request, token, userType); } // 2. 设置当前用户 if (loginUser != null) { SecurityFrameworkUtils.setLoginUser(loginUser, request); } } catch (Throwable ex) { CommonResult<?> result = globalExceptionHandler.allExceptionHandler(request, ex); ServletUtils.writeJSON(response, result); return; } } // 继续过滤链 chain.doFilter(request, response);
692
265
957
houbb_sensitive-word
sensitive-word/src/main/java/com/github/houbb/sensitive/word/support/check/WordCheckEmail.java
WordCheckEmail
isStringCondition
class WordCheckEmail extends AbstractConditionWordCheck { /** * @since 0.3.0 */ private static final IWordCheck INSTANCE = new WordCheckEmail(); public static IWordCheck getInstance() { return INSTANCE; } @Override protected Class<? extends IWordCheck> getSensitiveCheckClass() { return WordCheckEmail.class; } @Override protected String getType() { return WordTypeEnum.EMAIL.getCode(); } @Override protected boolean isCharCondition(char mappingChar, int index, InnerSensitiveWordContext checkContext) { return CharUtil.isEmilChar(mappingChar); } @Override protected boolean isStringCondition(int index, StringBuilder stringBuilder, InnerSensitiveWordContext checkContext) {<FILL_FUNCTION_BODY>} }
int bufferLen = stringBuilder.length(); //x@a.cn if(bufferLen < 6) { return false; } if(bufferLen > WordConst.MAX_EMAIL_LEN) { return false; } String string = stringBuilder.toString(); return RegexUtil.isEmail(string);
226
92
318
/** * 抽象实现策略 * @author binbin.hou * @since 0.3.2 */ @ThreadSafe public abstract class AbstractConditionWordCheck extends AbstractWordCheck { /** * 当前字符串是否符合规范 * @param mappingChar 当前字符 * @param index 下标 * @param checkContext 校验文本 * @return 结果 * @since 0.3.2 */ protected abstract boolean isCharCondition( char mappingChar, int index, InnerSensitiveWordContext checkContext); /** * 这里指定一个阈值条件 * @param index 当前下标 * @param stringBuilder 缓存 * @param checkContext 上下文 * @return 是否满足条件 * @since 0.3.2 */ protected abstract boolean isStringCondition( int index, final StringBuilder stringBuilder, InnerSensitiveWordContext checkContext); @Override protected int getActualLength( int beginIndex, InnerSensitiveWordContext checkContext); }
PlayEdu_PlayEdu
PlayEdu/playedu-common/src/main/java/xyz/playedu/common/context/FCtx.java
FCtx
put
class FCtx { private static final ThreadLocal<LinkedHashMap<String, Object>> THREAD_LOCAL = new ThreadLocal<>(); private static final String KEY_USER_ID = "user_id"; private static final String KEY_USER = "user"; private static final String KEY_JWT_JTI = "jwt_jti"; public FCtx() {} private static void put(String key, Object val) {<FILL_FUNCTION_BODY>} private static Object get(String key) { return THREAD_LOCAL.get().getOrDefault(key, null); } public static void remove() { THREAD_LOCAL.remove(); } public static void setId(Integer id) { put(KEY_USER_ID, id); } public static Integer getId() { return (Integer) get(KEY_USER_ID); } public static void setUser(User user) { put(KEY_USER, user); } public static User getUser() { return (User) get(KEY_USER); } public static void setJWtJti(String jti) { put(KEY_JWT_JTI, jti); } public static String getJwtJti() { return (String) get(KEY_JWT_JTI); } }
LinkedHashMap<String, Object> hashMap = THREAD_LOCAL.get(); if (hashMap == null) { hashMap = new LinkedHashMap<>(); } hashMap.put(key, val); THREAD_LOCAL.set(hashMap);
357
72
429
subhra74_snowflake
snowflake/muon-app/src/main/java/muon/app/ui/components/session/files/view/TableCellLabelRenderer.java
TableCellLabelRenderer
getTableCellRendererComponent
class TableCellLabelRenderer implements TableCellRenderer { private JPanel panel; private JLabel textLabel; private JLabel iconLabel; private JLabel label; private int height; private Color foreground; public TableCellLabelRenderer() { foreground = App.SKIN.getInfoTextForeground(); panel = new JPanel(new BorderLayout(10, 5)); panel.setBorder(new EmptyBorder(5, 10, 5, 5)); textLabel = new JLabel(); textLabel.setForeground(foreground); textLabel.setText("AAA"); textLabel.setFont(new Font(Font.DIALOG, Font.PLAIN, 14)); iconLabel = new JLabel(); iconLabel.setFont(App.SKIN.getIconFont().deriveFont(Font.PLAIN, 20.f)); iconLabel.setText("\uf016"); iconLabel.setForeground(foreground); // iconLabel.setForeground(new Color(92, 167, 25)); Dimension d1 = iconLabel.getPreferredSize(); iconLabel.setText("\uf07b"); Dimension d2 = iconLabel.getPreferredSize(); height = Math.max(d1.height, d2.height) + 10; iconLabel.setHorizontalAlignment(JLabel.CENTER); panel.add(textLabel); panel.add(iconLabel, BorderLayout.WEST); panel.doLayout(); System.out.println(panel.getPreferredSize()); label = new JLabel(); label.setForeground(foreground); label.setBorder(new EmptyBorder(5, 5, 5, 5)); label.setFont(new Font(Font.DIALOG, Font.PLAIN, 14)); label.setOpaque(true); } public int getHeight() { return height; } @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {<FILL_FUNCTION_BODY>} public String getIconForType(FileInfo ent) { return FileIconUtil.getIconForType(ent); } }
FolderViewTableModel folderViewModel = (FolderViewTableModel) table.getModel(); int r = table.convertRowIndexToModel(row); int c = table.convertColumnIndexToModel(column); FileInfo ent = folderViewModel.getItemAt(r); panel.setBackground(isSelected ? table.getSelectionBackground() : table.getBackground()); textLabel.setForeground(isSelected ? table.getSelectionForeground() : foreground); iconLabel.setForeground(isSelected ? table.getSelectionForeground() : foreground); iconLabel.setText(getIconForType(ent)); textLabel.setText(ent.getName()); label.setBackground(isSelected ? table.getSelectionBackground() : table.getBackground()); label.setForeground(isSelected ? table.getSelectionForeground() : foreground); switch (c) { case 0: label.setText(""); break; case 1: label.setText(FormatUtils.formatDate(ent.getLastModified())); break; case 2: if (ent.getType() == FileType.Directory || ent.getType() == FileType.DirLink) { label.setText(""); } else { label.setText(FormatUtils.humanReadableByteCount(ent.getSize(), true)); } break; case 3: label.setText(ent.getType() + ""); break; case 4: label.setText(ent.getPermissionString()); break; case 5: label.setText(ent.getUser()); break; default: break; } if (c == 0) { return panel; } else { return label; }
660
517
1,177
Pay-Group_best-pay-sdk
best-pay-sdk/src/main/java/com/lly835/bestpay/service/impl/WxEncryptAndDecryptServiceImpl.java
WxEncryptAndDecryptServiceImpl
decrypt
class WxEncryptAndDecryptServiceImpl extends AbstractEncryptAndDecryptServiceImpl { /** * 密钥算法 */ private static final String ALGORITHM = "AES"; /** * 加解密算法/工作模式/填充方式 */ private static final String ALGORITHM_MODE_PADDING = "AES/ECB/PKCS5Padding"; /** * 加密 * * @param key * @param data * @return */ @Override public Object encrypt(String key, String data) { return super.encrypt(key, data); } /** * 解密 * https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_16#menu1 * * @param key * @param data * @return */ @Override public Object decrypt(String key, String data) {<FILL_FUNCTION_BODY>} }
Security.addProvider(new BouncyCastleProvider()); SecretKeySpec aesKey = new SecretKeySpec(DigestUtils.md5Hex(key).toLowerCase().getBytes(), ALGORITHM); Cipher cipher = null; try { cipher = Cipher.getInstance(ALGORITHM_MODE_PADDING); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } try { cipher.init(Cipher.DECRYPT_MODE, aesKey); } catch (InvalidKeyException e) { e.printStackTrace(); } try { return new String(cipher.doFinal(Base64.getDecoder().decode(data))); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } return null;
272
261
533
/** * Created by 廖师兄 2018-05-30 16:21 */ abstract class AbstractEncryptAndDecryptServiceImpl implements EncryptAndDecryptService { /** * 加密 * @param key * @param data * @return */ @Override public Object encrypt( String key, String data); /** * 解密 * @param key * @param data * @return */ @Override public Object decrypt( String key, String data); }
subhra74_snowflake
snowflake/muon-jediterm/src/main/java/com/jediterm/terminal/TerminalStarter.java
TerminalStarter
close
class TerminalStarter implements TerminalOutputStream { private static final Logger LOG = Logger.getLogger(TerminalStarter.class); private final Emulator myEmulator; private final Terminal myTerminal; private final TerminalDataStream myDataStream; private final TtyConnector myTtyConnector; private final ExecutorService myEmulatorExecutor = Executors.newSingleThreadExecutor(); public TerminalStarter(final Terminal terminal, final TtyConnector ttyConnector, TerminalDataStream dataStream) { myTtyConnector = ttyConnector; //can be implemented - just recreate channel and that's it myDataStream = dataStream; myTerminal = terminal; myTerminal.setTerminalOutput(this); myEmulator = createEmulator(myDataStream, terminal); } protected JediEmulator createEmulator(TerminalDataStream dataStream, Terminal terminal) { return new JediEmulator(dataStream, terminal); } private void execute(Runnable runnable) { if (!myEmulatorExecutor.isShutdown()) { myEmulatorExecutor.execute(runnable); } } public void start() { try { while (!Thread.currentThread().isInterrupted() && myEmulator.hasNext()) { myEmulator.next(); } } catch (final InterruptedIOException e) { LOG.info("Terminal exiting"); } catch (final Exception e) { if (!myTtyConnector.isConnected()) { myTerminal.disconnected(); return; } LOG.error("Caught exception in terminal thread", e); } } public byte[] getCode(final int key, final int modifiers) { return myTerminal.getCodeForKey(key, modifiers); } public void postResize(final Dimension dimension, final RequestOrigin origin) { execute(() -> resizeTerminal(myTerminal, myTtyConnector, dimension, origin)); } /** * Resizes terminal and tty connector, should be called on a pooled thread. */ public static void resizeTerminal( Terminal terminal, TtyConnector ttyConnector, Dimension terminalDimension, RequestOrigin origin) { Dimension pixelSize; //noinspection SynchronizationOnLocalVariableOrMethodParameter synchronized (terminal) { pixelSize = terminal.resize(terminalDimension, origin); } ttyConnector.resize(terminalDimension, pixelSize); } @Override public void sendBytes(final byte[] bytes) { execute(() -> { try { myTtyConnector.write(bytes); } catch (IOException e) { throw new RuntimeException(e); } }); } @Override public void sendString(final String string) { execute(() -> { try { myTtyConnector.write(string); } catch (IOException e) { throw new RuntimeException(e); } }); } public void close() {<FILL_FUNCTION_BODY>} }
execute(() -> { try { myTtyConnector.close(); } catch (Exception e) { LOG.error("Error closing terminal", e); } finally { myEmulatorExecutor.shutdown(); } });
807
70
877
DerekYRC_mini-spring
mini-spring/src/main/java/org/springframework/beans/factory/support/CglibSubclassingInstantiationStrategy.java
CglibSubclassingInstantiationStrategy
instantiate
class CglibSubclassingInstantiationStrategy implements InstantiationStrategy { /** * 使用CGLIB动态生成子类 * * @param beanDefinition * @return * @throws BeansException */ @Override public Object instantiate(BeanDefinition beanDefinition) throws BeansException {<FILL_FUNCTION_BODY>} }
Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(beanDefinition.getBeanClass()); enhancer.setCallback((MethodInterceptor) (obj, method, argsTemp, proxy) -> proxy.invokeSuper(obj,argsTemp)); return enhancer.create();
93
80
173
Pay-Group_best-pay-sdk
best-pay-sdk/src/main/java/com/lly835/bestpay/utils/NameValuePairUtil.java
NameValuePairUtil
convert
class NameValuePairUtil { /** * 将Map转换为List<{@link NameValuePair}>. * * @param map * @return */ public static List<NameValuePair> convert(Map<String, String> map) {<FILL_FUNCTION_BODY>} }
List<NameValuePair> nameValuePairs = new ArrayList<>(); map.forEach((key, value) -> { nameValuePairs.add(new BasicNameValuePair(key, value)); }); return nameValuePairs;
85
64
149
jitsi_jitsi
jitsi/modules/plugin/ircaccregwizz/src/main/java/net/java/sip/communicator/plugin/ircaccregwizz/IrcAccRegWizzActivator.java
IrcAccRegWizzActivator
getIrcProtocolProviderFactory
class IrcAccRegWizzActivator extends DependentActivator { /** * OSGi bundle context. */ static BundleContext bundleContext; public IrcAccRegWizzActivator() { super( ResourceManagementService.class, UIService.class ); } /** * Start the IRC account registration wizard. */ public void startWithServices(BundleContext bundleContext) { logger.info("Loading irc account wizard."); UIService uiService = getService(UIService.class); Resources.resourcesService = getService(ResourceManagementService.class); WizardContainer wizardContainer = uiService.getAccountRegWizardContainer(); IrcAccountRegistrationWizard ircWizard = new IrcAccountRegistrationWizard(wizardContainer); Hashtable<String, String> containerFilter = new Hashtable<>(); containerFilter .put(ProtocolProviderFactory.PROTOCOL, ProtocolNames.IRC); bundleContext.registerService( AccountRegistrationWizard.class.getName(), ircWizard, containerFilter); logger.info("IRC account registration wizard [STARTED]."); } /** * Returns the <tt>ProtocolProviderFactory</tt> for the IRC protocol. * * @return the <tt>ProtocolProviderFactory</tt> for the IRC protocol */ public static ProtocolProviderFactory getIrcProtocolProviderFactory() {<FILL_FUNCTION_BODY>} }
ServiceReference<?>[] serRefs = null; String osgiFilter = "(" + ProtocolProviderFactory.PROTOCOL + "=IRC)"; try { serRefs = bundleContext.getServiceReferences( ProtocolProviderFactory.class.getName(), osgiFilter); } catch (InvalidSyntaxException ex) { logger.error("Invalid OSGi filter", ex); } return (ProtocolProviderFactory) bundleContext.getService(serRefs[0]);
397
134
531
/** * Bundle activator that will start the bundle when the requested dependent services are available. */ public abstract class DependentActivator implements BundleActivator, ServiceTrackerCustomizer<Object,Object> { private static final Map<BundleActivator,Set<Class<?>>> openTrackers=Collections.synchronizedMap(new HashMap<>()); private final Logger logger=LoggerFactory.getLogger(getClass()); private final Map<Class<?>,ServiceTracker<?,?>> dependentServices=new HashMap<>(); private final Set<Object> runningServices=new HashSet<>(); private BundleContext bundleContext; protected DependentActivator( Iterable<Class<?>> dependentServices); protected DependentActivator( Class<?>... dependentServices); /** * Starts the bundle. * @param bundleContext the currently valid <tt>BundleContext</tt>. */ @Override public final void start( BundleContext bundleContext); @Override public void stop( BundleContext context) throws Exception; @Override public Object addingService( ServiceReference<Object> reference); @SuppressWarnings("unchecked") protected <T>T getService( Class<T> serviceClass); @Override public void modifiedService( ServiceReference<Object> reference, Object service); @Override public void removedService( ServiceReference<Object> reference, Object service); protected abstract void startWithServices( BundleContext bundleContext) throws Exception ; }
orientechnologies_orientdb
orientdb/core/src/main/java/com/orientechnologies/common/util/OClassLoaderHelper.java
OClassLoaderHelper
lookupProviderWithOrientClassLoader
class OClassLoaderHelper { /** * Switch to the OrientDb classloader before lookups on ServiceRegistry for implementation of the * given Class. Useful under OSGI and generally under applications where jars are loaded by * another class loader * * @param clazz the class to lookup foor * @return an Iterator on the class implementation */ public static synchronized <T extends Object> Iterator<T> lookupProviderWithOrientClassLoader( Class<T> clazz) { return lookupProviderWithOrientClassLoader(clazz, OClassLoaderHelper.class.getClassLoader()); } public static synchronized <T extends Object> Iterator<T> lookupProviderWithOrientClassLoader( Class<T> clazz, ClassLoader orientClassLoader) {<FILL_FUNCTION_BODY>} }
final ClassLoader origClassLoader = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(orientClassLoader); try { return ServiceLoader.load(clazz).iterator(); } catch (Exception e) { OLogManager.instance().warn(null, "Cannot lookup in service registry", e); throw OException.wrapException( new OConfigurationException("Cannot lookup in service registry"), e); } finally { Thread.currentThread().setContextClassLoader(origClassLoader); }
206
134
340
zhkl0228_unidbg
unidbg/backend/hypervisor/src/main/java/com/github/unidbg/arm/backend/hypervisor/ExceptionVisitor.java
ExceptionVisitor
breakRestorerVisitor
class ExceptionVisitor { public abstract boolean onException(Hypervisor hypervisor, int ec, long address); static ExceptionVisitor breakRestorerVisitor(final BreakRestorer breakRestorer) {<FILL_FUNCTION_BODY>} }
return new ExceptionVisitor() { @Override public boolean onException(Hypervisor hypervisor, int ec, long address) { breakRestorer.install(hypervisor); return false; } };
66
61
127
eirslett_frontend-maven-plugin
frontend-maven-plugin/frontend-maven-plugin/src/main/java/com/github/eirslett/maven/plugins/frontend/mojo/WebpackMojo.java
WebpackMojo
execute
class WebpackMojo extends AbstractFrontendMojo { /** * Webpack arguments. Default is empty (runs just the "webpack" command). */ @Parameter(property = "frontend.webpack.arguments") private String arguments; /** * Files that should be checked for changes, in addition to the srcdir files. * Defaults to webpack.config.js in the {@link #workingDirectory}. */ @Parameter(property = "triggerfiles") private List<File> triggerfiles; /** * The directory containing front end files that will be processed by webpack. * If this is set then files in the directory will be checked for * modifications before running webpack. */ @Parameter(property = "srcdir") private File srcdir; /** * The directory where front end files will be output by webpack. If this is * set then they will be refreshed so they correctly show as modified in * Eclipse. */ @Parameter(property = "outputdir") private File outputdir; /** * Skips execution of this mojo. */ @Parameter(property = "skip.webpack", defaultValue = "${skip.webpack}") private boolean skip; @Component private BuildContext buildContext; @Override protected boolean skipExecution() { return this.skip; } @Override public synchronized void execute(FrontendPluginFactory factory) throws TaskRunnerException {<FILL_FUNCTION_BODY>} private boolean shouldExecute() { if (triggerfiles == null || triggerfiles.isEmpty()) { triggerfiles = Arrays.asList(new File(workingDirectory, "webpack.config.js")); } return MojoUtils.shouldExecute(buildContext, triggerfiles, srcdir); } }
if (shouldExecute()) { factory.getWebpackRunner().execute(arguments, environmentVariables); if (outputdir != null) { getLog().info("Refreshing files after webpack: " + outputdir); buildContext.refresh(outputdir); } } else { getLog().info("Skipping webpack as no modified files in " + srcdir); }
467
105
572
public abstract class AbstractFrontendMojo extends AbstractMojo { @Component protected MojoExecution execution; /** * Whether you should skip while running in the test phase (default is false) */ @Parameter(property="skipTests",required=false,defaultValue="false") protected Boolean skipTests; /** * Set this to true to ignore a failure during testing. Its use is NOT RECOMMENDED, but quite convenient on occasion. * @since 1.4 */ @Parameter(property="maven.test.failure.ignore",defaultValue="false") protected boolean testFailureIgnore; /** * The base directory for running all Node commands. (Usually the directory that contains package.json) */ @Parameter(defaultValue="${basedir}",property="workingDirectory",required=false) protected File workingDirectory; /** * The base directory for installing node and npm. */ @Parameter(property="installDirectory",required=false) protected File installDirectory; /** * Additional environment variables to pass to the build. */ @Parameter protected Map<String,String> environmentVariables; @Parameter(defaultValue="${project}",readonly=true) private MavenProject project; @Parameter(defaultValue="${repositorySystemSession}",readonly=true) private RepositorySystemSession repositorySystemSession; /** * Determines if this execution should be skipped. */ private boolean skipTestPhase(); /** * Determines if the current execution is during a testing phase (e.g., "test" or "integration-test"). */ private boolean isTestingPhase(); protected abstract void execute( FrontendPluginFactory factory) throws FrontendException ; /** * Implemented by children to determine if this execution should be skipped. */ protected abstract boolean skipExecution(); @Override public void execute() throws MojoFailureException; }
mapstruct_mapstruct
mapstruct/processor/src/main/java/org/mapstruct/ap/internal/model/source/selector/TargetTypeSelector.java
TargetTypeSelector
getMatchingMethods
class TargetTypeSelector implements MethodSelector { private final TypeUtils typeUtils; public TargetTypeSelector( TypeUtils typeUtils ) { this.typeUtils = typeUtils; } @Override public <T extends Method> List<SelectedMethod<T>> getMatchingMethods(List<SelectedMethod<T>> methods, SelectionContext context) {<FILL_FUNCTION_BODY>} }
SelectionCriteria criteria = context.getSelectionCriteria(); TypeMirror qualifyingTypeMirror = criteria.getQualifyingResultType(); if ( qualifyingTypeMirror != null && !criteria.isLifecycleCallbackRequired() ) { List<SelectedMethod<T>> candidatesWithQualifyingTargetType = new ArrayList<>( methods.size() ); for ( SelectedMethod<T> method : methods ) { TypeMirror resultTypeMirror = method.getMethod().getResultType().getTypeElement().asType(); if ( typeUtils.isSameType( qualifyingTypeMirror, resultTypeMirror ) ) { candidatesWithQualifyingTargetType.add( method ); } } return candidatesWithQualifyingTargetType; } else { return methods; }
103
215
318
logfellow_logstash-logback-encoder
logstash-logback-encoder/src/main/java/net/logstash/logback/composite/loggingevent/MessageJsonProvider.java
MessageJsonProvider
writeTo
class MessageJsonProvider extends AbstractFieldJsonProvider<ILoggingEvent> implements FieldNamesAware<LogstashFieldNames> { public static final String FIELD_MESSAGE = "message"; private Pattern messageSplitPattern = null; public MessageJsonProvider() { setFieldName(FIELD_MESSAGE); } @Override public void writeTo(JsonGenerator generator, ILoggingEvent event) throws IOException {<FILL_FUNCTION_BODY>} @Override public void setFieldNames(LogstashFieldNames fieldNames) { setFieldName(fieldNames.getMessage()); } /** * Write the message as a JSON array by splitting the message text using the specified regex. * * @return The regex used to split the message text */ public String getMessageSplitRegex() { return messageSplitPattern != null ? messageSplitPattern.pattern() : null; } /** * Write the message as a JSON array by splitting the message text using the specified regex. * * <p>The allowed values are: * <ul> * <li>Null/Empty : Disable message splitting. This is also the default behavior.</li> * <li>Any valid regex : Use the specified regex.</li> * <li>{@code SYSTEM} : Use the system-default line separator.</li> * <li>{@code UNIX} : Use {@code \n}.</li> * <li>{@code WINDOWS} : Use {@code \r\n}.</li> * </ul> * * For example, if this parameter is set to the regex {@code #+}, then the logging statement: * * <pre> * log.info("First line##Second line###Third line") * </pre> * * will produce: * <pre> * { * ... * "message": [ * "First line", * "Second line", * "Third line" * ], * ... * } * </pre> * * @param messageSplitRegex The regex used to split the message text */ public void setMessageSplitRegex(String messageSplitRegex) { String parsedMessageSplitRegex = SeparatorParser.parseSeparator(messageSplitRegex); this.messageSplitPattern = parsedMessageSplitRegex != null ? Pattern.compile(parsedMessageSplitRegex) : null; } }
if (messageSplitPattern != null) { String[] multiLineMessage = messageSplitPattern.split(event.getFormattedMessage()); JsonWritingUtils.writeStringArrayField(generator, getFieldName(), multiLineMessage); } else { JsonWritingUtils.writeStringField(generator, getFieldName(), event.getFormattedMessage()); }
646
90
736
obsidiandynamics_kafdrop
kafdrop/src/main/java/kafdrop/config/MessageFormatConfiguration.java
MessageFormatProperties
init
class MessageFormatProperties { private MessageFormat format; private MessageFormat keyFormat; @PostConstruct public void init() {<FILL_FUNCTION_BODY>} public MessageFormat getFormat() { return format; } public void setFormat(MessageFormat format) { this.format = format; } public MessageFormat getKeyFormat() { return keyFormat; } public void setKeyFormat(MessageFormat keyFormat) { this.keyFormat = keyFormat; } }
// Set a default message format if not configured. if (format == null) { format = MessageFormat.DEFAULT; } if (keyFormat == null) { keyFormat = format; //fallback }
139
59
198
elunez_eladmin
eladmin/eladmin-system/src/main/java/me/zhengjie/modules/system/service/impl/MonitorServiceImpl.java
MonitorServiceImpl
getCpuInfo
class MonitorServiceImpl implements MonitorService { private final DecimalFormat df = new DecimalFormat("0.00"); @Override public Map<String,Object> getServers(){ Map<String, Object> resultMap = new LinkedHashMap<>(8); try { SystemInfo si = new SystemInfo(); OperatingSystem os = si.getOperatingSystem(); HardwareAbstractionLayer hal = si.getHardware(); // 系统信息 resultMap.put("sys", getSystemInfo(os)); // cpu 信息 resultMap.put("cpu", getCpuInfo(hal.getProcessor())); // 内存信息 resultMap.put("memory", getMemoryInfo(hal.getMemory())); // 交换区信息 resultMap.put("swap", getSwapInfo(hal.getMemory())); // 磁盘 resultMap.put("disk", getDiskInfo(os)); resultMap.put("time", DateUtil.format(new Date(), "HH:mm:ss")); } catch (Exception e) { e.printStackTrace(); } return resultMap; } /** * 获取磁盘信息 * @return / */ private Map<String,Object> getDiskInfo(OperatingSystem os) { Map<String,Object> diskInfo = new LinkedHashMap<>(); FileSystem fileSystem = os.getFileSystem(); List<OSFileStore> fsArray = fileSystem.getFileStores(); String osName = System.getProperty("os.name"); long available = 0, total = 0; for (OSFileStore fs : fsArray){ // windows 需要将所有磁盘分区累加,linux 和 mac 直接累加会出现磁盘重复的问题,待修复 if(osName.toLowerCase().startsWith(ElConstant.WIN)) { available += fs.getUsableSpace(); total += fs.getTotalSpace(); } else { available = fs.getUsableSpace(); total = fs.getTotalSpace(); break; } } long used = total - available; diskInfo.put("total", total > 0 ? FileUtil.getSize(total) : "?"); diskInfo.put("available", FileUtil.getSize(available)); diskInfo.put("used", FileUtil.getSize(used)); if(total != 0){ diskInfo.put("usageRate", df.format(used/(double)total * 100)); } else { diskInfo.put("usageRate", 0); } return diskInfo; } /** * 获取交换区信息 * @param memory / * @return / */ private Map<String,Object> getSwapInfo(GlobalMemory memory) { Map<String,Object> swapInfo = new LinkedHashMap<>(); VirtualMemory virtualMemory = memory.getVirtualMemory(); long total = virtualMemory.getSwapTotal(); long used = virtualMemory.getSwapUsed(); swapInfo.put("total", FormatUtil.formatBytes(total)); swapInfo.put("used", FormatUtil.formatBytes(used)); swapInfo.put("available", FormatUtil.formatBytes(total - used)); if(used == 0){ swapInfo.put("usageRate", 0); } else { swapInfo.put("usageRate", df.format(used/(double)total * 100)); } return swapInfo; } /** * 获取内存信息 * @param memory / * @return / */ private Map<String,Object> getMemoryInfo(GlobalMemory memory) { Map<String,Object> memoryInfo = new LinkedHashMap<>(); memoryInfo.put("total", FormatUtil.formatBytes(memory.getTotal())); memoryInfo.put("available", FormatUtil.formatBytes(memory.getAvailable())); memoryInfo.put("used", FormatUtil.formatBytes(memory.getTotal() - memory.getAvailable())); memoryInfo.put("usageRate", df.format((memory.getTotal() - memory.getAvailable())/(double)memory.getTotal() * 100)); return memoryInfo; } /** * 获取Cpu相关信息 * @param processor / * @return / */ private Map<String,Object> getCpuInfo(CentralProcessor processor) {<FILL_FUNCTION_BODY>} /** * 获取系统相关信息,系统、运行天数、系统IP * @param os / * @return / */ private Map<String,Object> getSystemInfo(OperatingSystem os){ Map<String,Object> systemInfo = new LinkedHashMap<>(); // jvm 运行时间 long time = ManagementFactory.getRuntimeMXBean().getStartTime(); Date date = new Date(time); // 计算项目运行时间 String formatBetween = DateUtil.formatBetween(date, new Date(), Level.HOUR); // 系统信息 systemInfo.put("os", os.toString()); systemInfo.put("day", formatBetween); systemInfo.put("ip", StringUtils.getLocalIp()); return systemInfo; } }
Map<String,Object> cpuInfo = new LinkedHashMap<>(); cpuInfo.put("name", processor.getProcessorIdentifier().getName()); cpuInfo.put("package", processor.getPhysicalPackageCount() + "个物理CPU"); cpuInfo.put("core", processor.getPhysicalProcessorCount() + "个物理核心"); cpuInfo.put("coreNumber", processor.getPhysicalProcessorCount()); cpuInfo.put("logic", processor.getLogicalProcessorCount() + "个逻辑CPU"); // CPU信息 long[] prevTicks = processor.getSystemCpuLoadTicks(); // 默认等待300毫秒... long time = 300; Util.sleep(time); long[] ticks = processor.getSystemCpuLoadTicks(); while (Arrays.toString(prevTicks).equals(Arrays.toString(ticks)) && time < 1000){ time += 25; Util.sleep(25); ticks = processor.getSystemCpuLoadTicks(); } long user = ticks[CentralProcessor.TickType.USER.getIndex()] - prevTicks[CentralProcessor.TickType.USER.getIndex()]; long nice = ticks[CentralProcessor.TickType.NICE.getIndex()] - prevTicks[CentralProcessor.TickType.NICE.getIndex()]; long sys = ticks[CentralProcessor.TickType.SYSTEM.getIndex()] - prevTicks[CentralProcessor.TickType.SYSTEM.getIndex()]; long idle = ticks[CentralProcessor.TickType.IDLE.getIndex()] - prevTicks[CentralProcessor.TickType.IDLE.getIndex()]; long iowait = ticks[CentralProcessor.TickType.IOWAIT.getIndex()] - prevTicks[CentralProcessor.TickType.IOWAIT.getIndex()]; long irq = ticks[CentralProcessor.TickType.IRQ.getIndex()] - prevTicks[CentralProcessor.TickType.IRQ.getIndex()]; long softirq = ticks[CentralProcessor.TickType.SOFTIRQ.getIndex()] - prevTicks[CentralProcessor.TickType.SOFTIRQ.getIndex()]; long steal = ticks[CentralProcessor.TickType.STEAL.getIndex()] - prevTicks[CentralProcessor.TickType.STEAL.getIndex()]; long totalCpu = user + nice + sys + idle + iowait + irq + softirq + steal; cpuInfo.put("used", df.format(100d * user / totalCpu + 100d * sys / totalCpu)); cpuInfo.put("idle", df.format(100d * idle / totalCpu)); return cpuInfo;
1,312
719
2,031
PlexPt_chatgpt-java
chatgpt-java/src/main/java/com/plexpt/chatgpt/util/SseHelper.java
SseHelper
complete
class SseHelper { public void complete(SseEmitter sseEmitter) {<FILL_FUNCTION_BODY>} public void send(SseEmitter sseEmitter, Object data) { try { sseEmitter.send(data); } catch (Exception e) { } } }
try { sseEmitter.complete(); } catch (Exception e) { }
95
31
126
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/storage/index/Snap.java
Snap
getSnappedPoint
class Snap { public static final int INVALID_NODE = -1; private final GHPoint queryPoint; private double queryDistance = Double.MAX_VALUE; private int wayIndex = -1; private int closestNode = INVALID_NODE; private EdgeIteratorState closestEdge; private GHPoint3D snappedPoint; private Position snappedPosition; public Snap(double queryLat, double queryLon) { queryPoint = new GHPoint(queryLat, queryLon); } /** * Returns the closest matching node. This is either a tower node of the base graph * or a virtual node (see also {@link QueryGraph#create(BaseGraph, List)}). * * @return {@link #INVALID_NODE} if nothing found, this should be avoided via a call of 'isValid' */ public int getClosestNode() { return closestNode; } public void setClosestNode(int node) { closestNode = node; } /** * @return the distance of the query to the snapped coordinates. In meter */ public double getQueryDistance() { return queryDistance; } public void setQueryDistance(double dist) { queryDistance = dist; } public int getWayIndex() { return wayIndex; } public void setWayIndex(int wayIndex) { this.wayIndex = wayIndex; } /** * @return 0 if on edge. 1 if on pillar node and 2 if on tower node. */ public Position getSnappedPosition() { return snappedPosition; } public void setSnappedPosition(Position pos) { this.snappedPosition = pos; } /** * @return true if a closest node was found */ public boolean isValid() { return closestNode >= 0; } public EdgeIteratorState getClosestEdge() { return closestEdge; } public void setClosestEdge(EdgeIteratorState edge) { closestEdge = edge; } public GHPoint getQueryPoint() { return queryPoint; } /** * Calculates the position of the query point 'snapped' to a close road segment or node. Call * calcSnappedPoint before, if not, an IllegalStateException is thrown. */ public GHPoint3D getSnappedPoint() {<FILL_FUNCTION_BODY>} public void setSnappedPoint(GHPoint3D point) { this.snappedPoint = point; } /** * Calculates the closest point on the edge from the query point. If too close to a tower or pillar node this method * might change the snappedPosition and wayIndex. */ public void calcSnappedPoint(DistanceCalc distCalc) { if (closestEdge == null) throw new IllegalStateException("No closest edge?"); if (snappedPoint != null) throw new IllegalStateException("Calculate snapped point only once"); PointList fullPL = getClosestEdge().fetchWayGeometry(FetchMode.ALL); double tmpLat = fullPL.getLat(wayIndex); double tmpLon = fullPL.getLon(wayIndex); double tmpEle = fullPL.getEle(wayIndex); if (snappedPosition != Position.EDGE) { snappedPoint = new GHPoint3D(tmpLat, tmpLon, tmpEle); return; } double queryLat = getQueryPoint().lat, queryLon = getQueryPoint().lon; double adjLat = fullPL.getLat(wayIndex + 1), adjLon = fullPL.getLon(wayIndex + 1); if (distCalc.validEdgeDistance(queryLat, queryLon, tmpLat, tmpLon, adjLat, adjLon)) { GHPoint crossingPoint = distCalc.calcCrossingPointToEdge(queryLat, queryLon, tmpLat, tmpLon, adjLat, adjLon); double adjEle = fullPL.getEle(wayIndex + 1); // We want to prevent extra virtual nodes and very short virtual edges in case the snap/crossing point is // very close to a tower node. Since we delayed the calculation of the crossing point until here, we need // to correct the Snap.Position in these cases. Note that it is possible that the query point is very far // from the tower node, but the crossing point is still very close to it. if (considerEqual(crossingPoint.lat, crossingPoint.lon, tmpLat, tmpLon)) { snappedPosition = wayIndex == 0 ? Position.TOWER : Position.PILLAR; snappedPoint = new GHPoint3D(tmpLat, tmpLon, tmpEle); } else if (considerEqual(crossingPoint.lat, crossingPoint.lon, adjLat, adjLon)) { wayIndex++; snappedPosition = wayIndex == fullPL.size() - 1 ? Position.TOWER : Position.PILLAR; snappedPoint = new GHPoint3D(adjLat, adjLon, adjEle); } else { snappedPoint = new GHPoint3D(crossingPoint.lat, crossingPoint.lon, (tmpEle + adjEle) / 2); } } else { // outside of edge segment [wayIndex, wayIndex+1] should not happen for EDGE assert false : "incorrect pos: " + snappedPosition + " for " + snappedPoint + ", " + fullPL + ", " + wayIndex; } } public static boolean considerEqual(double lat, double lon, double lat2, double lon2) { return Math.abs(lat - lat2) < 1e-6 && Math.abs(lon - lon2) < 1e-6; } @Override public String toString() { if (closestEdge != null) return snappedPosition + ", " + closestNode + " " + closestEdge.getEdge() + ":" + closestEdge.getBaseNode() + "-" + closestEdge.getAdjNode() + " snap: [" + Helper.round6(snappedPoint.getLat()) + ", " + Helper.round6(snappedPoint.getLon()) + "]," + " query: [" + Helper.round6(queryPoint.getLat()) + "," + Helper.round6(queryPoint.getLon()) + "]"; return closestNode + ", " + queryPoint + ", " + wayIndex; } /** * Whether the query point is projected onto a tower node, pillar node or somewhere within * the closest edge. * <p> * Due to precision differences it is hard to define when something is exactly 90° or "on-node" * like TOWER or PILLAR or if it is more "on-edge" (EDGE). The default mechanism is to prefer * "on-edge" even if it could be 90°. To prefer "on-node" you could use e.g. GHPoint.equals with * a default precision of 1e-6. * <p> * * @see DistanceCalc#validEdgeDistance */ public enum Position { EDGE, TOWER, PILLAR } }
if (snappedPoint == null) throw new IllegalStateException("Calculate snapped point before!"); return snappedPoint;
1,844
36
1,880
google_truth
truth/extensions/proto/src/main/java/com/google/common/truth/extensions/proto/DiffResult.java
SingularField
printContents
class SingularField extends RecursableDiffEntity.WithResultCode implements ProtoPrintable { /** The type information for this field. May be absent if result code is {@code IGNORED}. */ abstract Optional<SubScopeId> subScopeId(); /** The display name for this field. May include an array-index specifier. */ abstract String fieldName(); /** The field under test. */ abstract Optional<Object> actual(); /** The expected value of said field. */ abstract Optional<Object> expected(); /** * The detailed breakdown of the comparison, only present if both objects are set on this * instance and they are messages. * * <p>This does not necessarily mean the messages were set on the input protos. */ abstract Optional<DiffResult> breakdown(); /** * The detailed breakdown of the comparison, only present if both objects are set and they are * {@link UnknownFieldSet}s. * * <p>This will only ever be set inside a parent {@link UnknownFieldSetDiff}. The top {@link * UnknownFieldSetDiff} is set on the {@link DiffResult}, not here. */ abstract Optional<UnknownFieldSetDiff> unknownsBreakdown(); /** Returns {@code actual().get()}, or {@code expected().get()}, whichever is available. */ @Memoized Object actualOrExpected() { return actual().or(expected()).get(); } @Memoized @Override Iterable<? extends RecursableDiffEntity> childEntities() { return ImmutableList.copyOf( Iterables.concat(breakdown().asSet(), unknownsBreakdown().asSet())); } @Override final void printContents(boolean includeMatches, String fieldPrefix, StringBuilder sb) {<FILL_FUNCTION_BODY>} @Override final boolean isContentEmpty() { return false; } static SingularField ignored(String fieldName) { return newBuilder() .setFieldName(fieldName) .setResult(Result.IGNORED) // Ignored fields don't need a customized proto printer. .setProtoPrinter(TextFormat.printer()) .build(); } static Builder newBuilder() { return new AutoValue_DiffResult_SingularField.Builder(); } /** Builder for {@link SingularField}. */ @AutoValue.Builder abstract static class Builder { abstract Builder setResult(Result result); abstract Builder setSubScopeId(SubScopeId subScopeId); abstract Builder setFieldName(String fieldName); abstract Builder setActual(Object actual); abstract Builder setExpected(Object expected); abstract Builder setBreakdown(DiffResult breakdown); abstract Builder setUnknownsBreakdown(UnknownFieldSetDiff unknownsBreakdown); abstract Builder setProtoPrinter(TextFormat.Printer value); abstract SingularField build(); } }
if (!includeMatches && isMatched()) { return; } fieldPrefix = newFieldPrefix(fieldPrefix, fieldName()); switch (result()) { case ADDED: sb.append("added: ").append(fieldPrefix).append(": "); if (actual().get() instanceof Message) { sb.append("\n"); printMessage((Message) actual().get(), sb); } else { printFieldValue(subScopeId().get(), actual().get(), sb); sb.append("\n"); } return; case IGNORED: sb.append("ignored: ").append(fieldPrefix).append("\n"); return; case MATCHED: sb.append("matched: ").append(fieldPrefix); if (actualOrExpected() instanceof Message) { sb.append("\n"); printChildContents(includeMatches, fieldPrefix, sb); } else { sb.append(": "); printFieldValue(subScopeId().get(), actualOrExpected(), sb); sb.append("\n"); } return; case MODIFIED: sb.append("modified: ").append(fieldPrefix); if (actualOrExpected() instanceof Message) { sb.append("\n"); printChildContents(includeMatches, fieldPrefix, sb); } else { sb.append(": "); printFieldValue(subScopeId().get(), expected().get(), sb); sb.append(" -> "); printFieldValue(subScopeId().get(), actual().get(), sb); sb.append("\n"); } return; case REMOVED: sb.append("deleted: ").append(fieldPrefix).append(": "); if (expected().get() instanceof Message) { sb.append("\n"); printMessage((Message) expected().get(), sb); } else { printFieldValue(subScopeId().get(), expected().get(), sb); sb.append("\n"); } return; default: throw new AssertionError("Impossible: " + result()); }
739
531
1,270
mapstruct_mapstruct
mapstruct/processor/src/main/java/org/mapstruct/ap/internal/model/IterableCreation.java
IterableCreation
getImportTypes
class IterableCreation extends ModelElement { private final Type resultType; private final Parameter sourceParameter; private final MethodReference factoryMethod; private final boolean canUseSize; private final boolean loadFactorAdjustment; private IterableCreation(Type resultType, Parameter sourceParameter, MethodReference factoryMethod) { this.resultType = resultType; this.sourceParameter = sourceParameter; this.factoryMethod = factoryMethod; this.canUseSize = ( sourceParameter.getType().isCollectionOrMapType() || sourceParameter.getType().isArrayType() ) && resultType.getImplementation() != null && resultType.getImplementation().hasInitialCapacityConstructor(); this.loadFactorAdjustment = this.canUseSize && resultType.getImplementation().isLoadFactorAdjustment(); } public static IterableCreation create(NormalTypeMappingMethod mappingMethod, Parameter sourceParameter) { return new IterableCreation( mappingMethod.getResultType(), sourceParameter, mappingMethod.getFactoryMethod() ); } public Type getResultType() { return resultType; } public Parameter getSourceParameter() { return sourceParameter; } public MethodReference getFactoryMethod() { return this.factoryMethod; } public boolean isCanUseSize() { return canUseSize; } public boolean isLoadFactorAdjustment() { return loadFactorAdjustment; } @Override public Set<Type> getImportTypes() {<FILL_FUNCTION_BODY>} public Type getEnumSetElementType() { return first( getResultType().determineTypeArguments( Iterable.class ) ); } public boolean isEnumSet() { return "java.util.EnumSet".equals( resultType.getFullyQualifiedName() ); } }
Set<Type> types = new HashSet<>(); if ( factoryMethod == null && resultType.getImplementationType() != null ) { types.addAll( resultType.getImplementationType().getImportTypes() ); } if ( isEnumSet() ) { types.add( getEnumSetElementType() ); // The result type itself is an EnumSet types.add( resultType ); } return types;
477
114
591
/** * Base class of all model elements. Implements the {@link Writable} contract to write model elements into source codefiles. * @author Gunnar Morling */ public abstract class ModelElement extends FreeMarkerWritable { /** * Returns a set containing those {@link Type}s referenced by this model element for which an import statement needs to be declared. * @return A set with type referenced by this model element. Must not be {@code null}. */ public abstract Set<Type> getImportTypes(); }
Kong_unirest-java
unirest-java/unirest-modules-jackson/src/main/java/kong/unirest/modules/jackson/JacksonElement.java
JacksonElement
getAsInt
class JacksonElement<T extends JsonNode> implements JsonEngine.Element { protected T element; JacksonElement(T element){ this.element = element; } static JsonEngine.Element wrap(JsonNode node) { if(node == null || node.isNull()){ return new JacksonPrimitive(NullNode.getInstance()); } else if(node.isArray()){ return new JacksonArray((ArrayNode) node); } else if(node.isObject()){ return new JacksonObject((ObjectNode)node); } else if (node.isValueNode()){ return new JacksonPrimitive((ValueNode)node); } return new JacksonPrimitive(NullNode.getInstance()); } @Override public JsonEngine.Object getAsJsonObject() { if(element.isObject()) { return new JacksonObject((ObjectNode) element); } throw new IllegalStateException("Not an object"); } @Override public boolean isJsonNull() { return element instanceof NullNode; } @Override public JsonEngine.Primitive getAsJsonPrimitive() { return new JacksonPrimitive((ValueNode) element); } @Override public JsonEngine.Array getAsJsonArray() { if(!element.isArray()){ throw new IllegalStateException("Not an Array"); } return new JacksonArray((ArrayNode)element); } @Override public float getAsFloat() { if(!element.isFloat()){ throw new NumberFormatException("not a float"); } return element.floatValue(); } @Override public double getAsDouble() { if(!element.isNumber()){ throw new NumberFormatException("not a double"); } return element.asDouble(); } @Override public String getAsString() { return element.asText(); } @Override public long getAsLong() { if(!element.isLong() && !element.isIntegralNumber()){ throw new NumberFormatException("not a long"); } return element.asLong(); } @Override public int getAsInt() {<FILL_FUNCTION_BODY>} @Override public boolean getAsBoolean() { return element.asBoolean(); } @Override public BigInteger getAsBigInteger() { if(!element.isIntegralNumber()) { throw new NumberFormatException("Not a integer"); } return element.bigIntegerValue(); } @Override public BigDecimal getAsBigDecimal() { if(!element.isNumber()){ throw new NumberFormatException("Not a decimal"); } return element.decimalValue(); } @Override public JsonEngine.Primitive getAsPrimitive() { if(element.isValueNode()){ return new JacksonPrimitive((ValueNode) element); } throw new JSONException("Not a value type"); } @Override public boolean isJsonArray() { return element.isArray(); } @Override public boolean isJsonPrimitive() { return element.isValueNode(); } @Override public boolean isJsonObject() { return element.isObject(); } @Override public <T> T getEngineElement() { return (T)element; } @Override public boolean equals(Object o) { if (this == o) {return true;} if (o == null || getClass() != o.getClass()) {return false;} JacksonElement<?> that = (JacksonElement<?>) o; return Objects.equals(element, that.element); } @Override public int hashCode() { return Objects.hash(element); } }
if(!element.isIntegralNumber()) { throw new NumberFormatException("Not a number"); } return element.asInt();
978
38
1,016
PlayEdu_PlayEdu
PlayEdu/playedu-common/src/main/java/xyz/playedu/common/service/impl/AdminPermissionServiceImpl.java
AdminPermissionServiceImpl
allSlugs
class AdminPermissionServiceImpl extends ServiceImpl<AdminPermissionMapper, AdminPermission> implements AdminPermissionService { @Override public HashMap<String, Integer> allSlugs() {<FILL_FUNCTION_BODY>} @Override public List<AdminPermission> listOrderBySortAsc() { return list(query().getWrapper().orderByAsc("group_name", "sort")); } @Override public HashMap<String, Boolean> getSlugsByIds(List<Integer> ids) { List<AdminPermission> adminPermissions = list(query().getWrapper().in("id", ids)); HashMap<String, Boolean> map = new HashMap<>(); for (AdminPermission adminPermission : adminPermissions) { map.put(adminPermission.getSlug(), true); } return map; } @Override public List<Integer> allIds() { List<AdminPermission> permissions = list(query().getWrapper().eq("1", "1").select("id")); List<Integer> ids = new ArrayList<>(); for (AdminPermission permission : permissions) { ids.add(permission.getId()); } return ids; } @Override public List<AdminPermission> chunks(List<Integer> ids) { return list(query().getWrapper().in("id", ids)); } }
List<AdminPermission> data = list(); HashMap<String, Integer> map = new HashMap<>(); for (AdminPermission permission : data) { map.put(permission.getSlug(), permission.getId()); } return map;
351
65
416
javamelody_javamelody
javamelody/javamelody-core/src/main/java/net/bull/javamelody/MonitoringTargetInterceptor.java
MonitoringTargetInterceptor
getRequestName
class MonitoringTargetInterceptor extends MonitoringInterceptor { private static final long serialVersionUID = 1L; @Override protected String getRequestName(InvocationContext context) {<FILL_FUNCTION_BODY>} }
final Method method = context.getMethod(); final Object target = context.getTarget(); return target.getClass().getSimpleName() + '.' + method.getName();
64
51
115
/** * Intercepteur pour EJB 3 (Java EE 5+). Il est destiné à un compteur pour les statistiques d'exécutions de méthodes sur les "façades métiers" ( @ {@link Stateless}, @ {@link Stateful} ou @{@link MessageDriven} ).Il peut être paramétré dans le fichier ejb-jar.xml pour certains ejb ou pour tous les ejb, ou alors par l'annotation @ {@link jakarta.interceptor.Interceptors} dans les sources java des implémentations d'ejb. * @author Emeric Vernat */ public class MonitoringInterceptor implements Serializable { private static final long serialVersionUID=1L; private static final Counter EJB_COUNTER=MonitoringProxy.getEjbCounter(); private static final boolean COUNTER_HIDDEN=Parameters.isCounterHidden(EJB_COUNTER.getName()); private static final boolean DISABLED=Parameter.DISABLED.getValueAsBoolean(); /** * Constructeur. */ public MonitoringInterceptor(); /** * Intercepte une exécution de méthode sur un ejb. * @param context InvocationContext * @return Object * @throws Exception e */ @AroundInvoke public Object intercept( InvocationContext context) throws Exception; /** * Determine request name for an invocation context. * @param context the invocation context (not null) * @return the request name for this invocation */ protected String getRequestName( InvocationContext context); }
DerekYRC_mini-spring
mini-spring/src/main/java/org/springframework/context/support/ConversionServiceFactoryBean.java
ConversionServiceFactoryBean
registerConverters
class ConversionServiceFactoryBean implements FactoryBean<ConversionService>, InitializingBean { private Set<?> converters; private GenericConversionService conversionService; @Override public void afterPropertiesSet() throws Exception { conversionService = new DefaultConversionService(); registerConverters(converters, conversionService); } private void registerConverters(Set<?> converters, ConverterRegistry registry) {<FILL_FUNCTION_BODY>} @Override public ConversionService getObject() throws Exception { return conversionService; } @Override public boolean isSingleton() { return true; } public void setConverters(Set<?> converters) { this.converters = converters; } }
if (converters != null) { for (Object converter : converters) { if (converter instanceof GenericConverter) { registry.addConverter((GenericConverter) converter); } else if (converter instanceof Converter<?, ?>) { registry.addConverter((Converter<?, ?>) converter); } else if (converter instanceof ConverterFactory<?, ?>) { registry.addConverterFactory((ConverterFactory<?, ?>) converter); } else { throw new IllegalArgumentException("Each converter object must implement one of the " + "Converter, ConverterFactory, or GenericConverter interfaces"); } } }
193
170
363
orientechnologies_orientdb
orientdb/core/src/main/java/com/orientechnologies/orient/core/index/OIndexes.java
OIndexes
createIndexEngine
class OIndexes { private static Set<OIndexFactory> FACTORIES = null; private static final Set<OIndexFactory> DYNAMIC_FACTORIES = Collections.synchronizedSet(new HashSet<>()); private static ClassLoader orientClassLoader = OIndexes.class.getClassLoader(); private OIndexes() {} /** * Cache a set of all factories. we do not use the service loader directly since it is not * concurrent. * * @return Set<OIndexFactory> */ private static synchronized Set<OIndexFactory> getFactories() { if (FACTORIES == null) { final Iterator<OIndexFactory> ite = lookupProviderWithOrientClassLoader(OIndexFactory.class, orientClassLoader); final Set<OIndexFactory> factories = new HashSet<>(); while (ite.hasNext()) { factories.add(ite.next()); } factories.addAll(DYNAMIC_FACTORIES); FACTORIES = Collections.unmodifiableSet(factories); } return FACTORIES; } /** @return Iterator of all index factories */ public static Iterator<OIndexFactory> getAllFactories() { return getFactories().iterator(); } /** * Iterates on all factories and append all index types. * * @return Set of all index types. */ private static Set<String> getIndexTypes() { final Set<String> types = new HashSet<>(); final Iterator<OIndexFactory> ite = getAllFactories(); while (ite.hasNext()) { types.addAll(ite.next().getTypes()); } return types; } /** * Iterates on all factories and append all index engines. * * @return Set of all index engines. */ public static Set<String> getIndexEngines() { final Set<String> engines = new HashSet<>(); final Iterator<OIndexFactory> ite = getAllFactories(); while (ite.hasNext()) { engines.addAll(ite.next().getAlgorithms()); } return engines; } public static OIndexFactory getFactory(String indexType, String algorithm) { if (algorithm == null) { algorithm = chooseDefaultIndexAlgorithm(indexType); } if (algorithm != null) { algorithm = algorithm.toUpperCase(Locale.ENGLISH); final Iterator<OIndexFactory> ite = getAllFactories(); while (ite.hasNext()) { final OIndexFactory factory = ite.next(); if (factory.getTypes().contains(indexType) && factory.getAlgorithms().contains(algorithm)) { return factory; } } } throw new OIndexException( "Index with type " + indexType + " and algorithm " + algorithm + " does not exist."); } /** * @param storage TODO * @param indexType index type * @return OIndexInternal * @throws OConfigurationException if index creation failed * @throws OIndexException if index type does not exist */ public static OIndexInternal createIndex(OStorage storage, OIndexMetadata metadata) throws OConfigurationException, OIndexException { String indexType = metadata.getType(); String algorithm = metadata.getAlgorithm(); return findFactoryByAlgorithmAndType(algorithm, indexType).createIndex(storage, metadata); } private static OIndexFactory findFactoryByAlgorithmAndType(String algorithm, String indexType) { for (OIndexFactory factory : getFactories()) { if (indexType == null || indexType.isEmpty() || (factory.getTypes().contains(indexType)) && factory.getAlgorithms().contains(algorithm)) { return factory; } } throw new OIndexException( "Index type " + indexType + " with engine " + algorithm + " is not supported. Types are " + OCollections.toString(getIndexTypes())); } public static OBaseIndexEngine createIndexEngine( final OStorage storage, final IndexEngineData metadata) {<FILL_FUNCTION_BODY>} public static String chooseDefaultIndexAlgorithm(String type) { String algorithm = null; if (OClass.INDEX_TYPE.DICTIONARY.name().equalsIgnoreCase(type) || OClass.INDEX_TYPE.FULLTEXT.name().equalsIgnoreCase(type) || OClass.INDEX_TYPE.NOTUNIQUE.name().equalsIgnoreCase(type) || OClass.INDEX_TYPE.UNIQUE.name().equalsIgnoreCase(type)) { algorithm = ODefaultIndexFactory.CELL_BTREE_ALGORITHM; } else if (OClass.INDEX_TYPE.DICTIONARY_HASH_INDEX.name().equalsIgnoreCase(type) || OClass.INDEX_TYPE.NOTUNIQUE_HASH_INDEX.name().equalsIgnoreCase(type) || OClass.INDEX_TYPE.UNIQUE_HASH_INDEX.name().equalsIgnoreCase(type)) { algorithm = OHashIndexFactory.HASH_INDEX_ALGORITHM; } return algorithm; } /** * Scans for factory plug-ins on the application class path. This method is needed because the * application class path can theoretically change, or additional plug-ins may become available. * Rather than re-scanning the classpath on every invocation of the API, the class path is scanned * automatically only on the first invocation. Clients can call this method to prompt a re-scan. * Thus this method need only be invoked by sophisticated applications which dynamically make new * plug-ins available at runtime. */ private static synchronized void scanForPlugins() { // clear cache, will cause a rescan on next getFactories call FACTORIES = null; } /** Register at runtime custom factories */ public static void registerFactory(OIndexFactory factory) { DYNAMIC_FACTORIES.add(factory); scanForPlugins(); } /** Unregister custom factories */ public static void unregisterFactory(OIndexFactory factory) { DYNAMIC_FACTORIES.remove(factory); scanForPlugins(); } }
final OIndexFactory factory = findFactoryByAlgorithmAndType(metadata.getAlgorithm(), metadata.getIndexType()); return factory.createIndexEngine(storage, metadata);
1,621
48
1,669
YunaiV_ruoyi-vue-pro
ruoyi-vue-pro/yudao-framework/yudao-spring-boot-starter-biz-tenant/src/main/java/cn/iocoder/yudao/framework/tenant/core/mq/rabbitmq/TenantRabbitMQInitializer.java
TenantRabbitMQInitializer
postProcessAfterInitialization
class TenantRabbitMQInitializer implements BeanPostProcessor { @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {<FILL_FUNCTION_BODY>} }
if (bean instanceof RabbitTemplate) { RabbitTemplate rabbitTemplate = (RabbitTemplate) bean; rabbitTemplate.addBeforePublishPostProcessors(new TenantRabbitMQMessagePostProcessor()); } return bean;
59
65
124
jitsi_jitsi
jitsi/modules/impl/protocol-sip/src/main/java/net/java/sip/communicator/impl/protocol/sip/SipApplicationData.java
SipApplicationData
getApplicationData
class SipApplicationData { /** * Key service. */ public static final String KEY_SERVICE = "service"; /** * Key subscriptions. */ public static final String KEY_SUBSCRIPTIONS = "subscriptions"; /** * Key user request. */ public static final String KEY_USER_REQUEST = "userRequest"; /** * Logger for this class. */ private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(SipApplicationData.class); /** * Internal representation of the store. */ private final Map<String, Object> storage_ = new HashMap<String, Object>(); /** * Stores a <tt>value</tt> associated to the a <tt>key</tt> string in the * <tt>container</tt>. Currently <tt>SIPMessage</tt>, <tt>Transaction</tt> * and <tt>Dialog</tt> are supported as container. * * @param container the <tt>Object</tt> to attach the * <tt>key</tt>/<tt>value</tt> pair to. * @param key the key string to retrieve the value later with get() * @param value the value to store */ public static void setApplicationData( Object container, String key, Object value) { if (container == null) { logger.warn("container is null"); return; } if (key == null) { logger.warn("key is null"); return; } SipApplicationData appData = getSipApplicationData(container); if (appData == null) { appData = new SipApplicationData(); if (container instanceof SIPMessage) ((SIPMessage) container).setApplicationData(appData); else if (container instanceof Transaction) ((Transaction) container).setApplicationData(appData); else if (container instanceof Dialog) ((Dialog) container).setApplicationData(appData); else logger.error("container should be of type " + "SIPMessage, Transaction or Dialog"); } appData.put(key, value); } /** * Retrieves a value associated to the a <tt>key</tt> string in the * <tt>container</tt>. Currently <tt>SIPMessage</tt>, <tt>Transaction</tt> * and <tt>Dialog</tt> are supported as container. * * @param container the <tt>Object</tt> to retrieve a value from. * @param key the key string to identify the value to retrieve * @return the returned value or null if it is not found */ public static Object getApplicationData(Object container, String key) {<FILL_FUNCTION_BODY>} /** * Stores a <tt>value</tt> associated to the a <tt>key</tt> string in the * <tt>SipApplicationData</tt>. * * @param key the key string to retrieve the value later with get() * @param value the value to store */ private void put(String key, Object value) { this.storage_.put(key, value); } /** * Retrieves a value stored in <tt>SipApplicationData</tt>. * * @param key the key string to identify the value to retrieve * @return the returned value or null if it is not found */ private Object get(String key) { return this.storage_.get(key); } /** * Tries to use the setApplicationData() method on the provided container * and returns the SipApplicationData stored there, or null if there is none * or if another type of instance is found. * * @param container the <tt>Object</tt> to retrieve a * <tt>SipApplicationData</tt> from. * @return the <tt>SipApplicationData</tt> rerieved, or null. */ private static SipApplicationData getSipApplicationData(Object container) { Object appData; if (container instanceof SIPMessage) appData = ((SIPMessage) container).getApplicationData(); else if (container instanceof Transaction) appData = ((Transaction) container).getApplicationData(); else if (container instanceof Dialog) appData = ((Dialog) container).getApplicationData(); else { logger.error("container should be of type " + "SIPMessage, Transaction or Dialog"); appData = null; } if (appData == null) return null; if (appData instanceof SipApplicationData) return (SipApplicationData) appData; logger.error("application data should be of type " + "SipApplicationData"); return null; } }
if (container == null) { logger.debug("container is null"); return null; } if (key == null) { logger.warn("key is null"); return null; } SipApplicationData appData = getSipApplicationData(container); if (appData == null) return null; return appData.get(key);
1,271
103
1,374
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/routing/ev/MaxLength.java
MaxLength
create
class MaxLength { public static final String KEY = "max_length"; /** * Currently enables to store 0.1 to max=0.1*2⁷m and infinity. If a value is * between the maximum and infinity it is assumed to use the maximum value. */ public static DecimalEncodedValue create() {<FILL_FUNCTION_BODY>} }
return new DecimalEncodedValueImpl(KEY, 7, 0, 0.1, false, false, true);
97
32
129
subhra74_snowflake
snowflake/muon-app/src/main/java/muon/app/ui/components/session/utilpage/portview/SocketTableModel.java
SocketTableModel
getValueAt
class SocketTableModel extends AbstractTableModel { private String columns[] = {"Process", "PID", "Host", "Port"}; private List<SocketEntry> list = new ArrayList<>(); public void addEntry(SocketEntry e) { list.add(e); fireTableDataChanged(); } public void addEntries(List<SocketEntry> entries) { if (entries != null) { list.addAll(entries); fireTableDataChanged(); } } @Override public Class<?> getColumnClass(int columnIndex) { return Object.class; } @Override public int getRowCount() { return list.size(); } @Override public int getColumnCount() { return columns.length; } @Override public String getColumnName(int column) { return columns[column]; } @Override public Object getValueAt(int rowIndex, int columnIndex) {<FILL_FUNCTION_BODY>} public void clear() { list.clear(); } }
SocketEntry e = list.get(rowIndex); switch (columnIndex) { case 0: return e.getApp(); case 1: return e.getPid(); case 2: return e.getHost(); case 3: return e.getPort(); default: return ""; }
329
107
436
graphhopper_graphhopper
graphhopper/web-bundle/src/main/java/com/graphhopper/http/TypeGPXFilter.java
TypeGPXFilter
filter
class TypeGPXFilter implements ContainerRequestFilter { @Override public void filter(ContainerRequestContext rc) {<FILL_FUNCTION_BODY>} }
String maybeType = rc.getUriInfo().getQueryParameters().getFirst("type"); if (maybeType != null && maybeType.equals("gpx")) { rc.getHeaders().putSingle(HttpHeaders.ACCEPT, "application/gpx+xml"); }
45
72
117
eirslett_frontend-maven-plugin
frontend-maven-plugin/frontend-maven-plugin/src/main/java/com/github/eirslett/maven/plugins/frontend/mojo/InstallNodeAndPnpmMojo.java
InstallNodeAndPnpmMojo
execute
class InstallNodeAndPnpmMojo extends AbstractFrontendMojo { /** * Where to download Node.js binary from. Defaults to https://nodejs.org/dist/ */ @Parameter(property = "nodeDownloadRoot", required = false) private String nodeDownloadRoot; /** * Where to download pnpm binary from. Defaults to https://registry.npmjs.org/pnpm/-/ */ @Parameter(property = "pnpmDownloadRoot", required = false, defaultValue = PnpmInstaller.DEFAULT_PNPM_DOWNLOAD_ROOT) private String pnpmDownloadRoot; /** * Where to download Node.js and pnpm binaries from. * * @deprecated use {@link #nodeDownloadRoot} and {@link #pnpmDownloadRoot} instead, this configuration will be used only when no {@link #nodeDownloadRoot} or {@link #pnpmDownloadRoot} is specified. */ @Parameter(property = "downloadRoot", required = false, defaultValue = "") @Deprecated private String downloadRoot; /** * The version of Node.js to install. IMPORTANT! Most Node.js version names start with 'v', for example 'v0.10.18' */ @Parameter(property="nodeVersion", required = true) private String nodeVersion; /** * The version of pnpm to install. Note that the version string can optionally be prefixed with * 'v' (i.e., both 'v1.2.3' and '1.2.3' are valid). */ @Parameter(property = "pnpmVersion", required = true) private String pnpmVersion; /** * Server Id for download username and password */ @Parameter(property = "serverId", defaultValue = "") private String serverId; @Parameter(property = "session", defaultValue = "${session}", readonly = true) private MavenSession session; /** * Skips execution of this mojo. */ @Parameter(property = "skip.installnodepnpm", defaultValue = "${skip.installnodepnpm}") private boolean skip; @Component(role = SettingsDecrypter.class) private SettingsDecrypter decrypter; @Override protected boolean skipExecution() { return this.skip; } @Override public void execute(FrontendPluginFactory factory) throws InstallationException {<FILL_FUNCTION_BODY>} private String getNodeDownloadRoot() { if (downloadRoot != null && !"".equals(downloadRoot) && nodeDownloadRoot == null) { return downloadRoot; } return nodeDownloadRoot; } private String getPnpmDownloadRoot() { if (downloadRoot != null && !"".equals(downloadRoot) && PnpmInstaller.DEFAULT_PNPM_DOWNLOAD_ROOT.equals(pnpmDownloadRoot)) { return downloadRoot; } return pnpmDownloadRoot; } }
ProxyConfig proxyConfig = MojoUtils.getProxyConfig(session, decrypter); // Use different names to avoid confusion with fields `nodeDownloadRoot` and // `pnpmDownloadRoot`. // // TODO: Remove the `downloadRoot` config (with breaking change) to simplify download root // resolution. String resolvedNodeDownloadRoot = getNodeDownloadRoot(); String resolvedPnpmDownloadRoot = getPnpmDownloadRoot(); Server server = MojoUtils.decryptServer(serverId, session, decrypter); if (null != server) { factory.getNodeInstaller(proxyConfig) .setNodeVersion(nodeVersion) .setNodeDownloadRoot(resolvedNodeDownloadRoot) .setUserName(server.getUsername()) .setPassword(server.getPassword()) .install(); factory.getPnpmInstaller(proxyConfig) .setPnpmVersion(pnpmVersion) .setPnpmDownloadRoot(resolvedPnpmDownloadRoot) .setUserName(server.getUsername()) .setPassword(server.getPassword()) .install(); } else { factory.getNodeInstaller(proxyConfig) .setNodeVersion(nodeVersion) .setNodeDownloadRoot(resolvedNodeDownloadRoot) .install(); factory.getPnpmInstaller(proxyConfig) .setPnpmVersion(this.pnpmVersion) .setPnpmDownloadRoot(resolvedPnpmDownloadRoot) .install(); }
762
371
1,133
public abstract class AbstractFrontendMojo extends AbstractMojo { @Component protected MojoExecution execution; /** * Whether you should skip while running in the test phase (default is false) */ @Parameter(property="skipTests",required=false,defaultValue="false") protected Boolean skipTests; /** * Set this to true to ignore a failure during testing. Its use is NOT RECOMMENDED, but quite convenient on occasion. * @since 1.4 */ @Parameter(property="maven.test.failure.ignore",defaultValue="false") protected boolean testFailureIgnore; /** * The base directory for running all Node commands. (Usually the directory that contains package.json) */ @Parameter(defaultValue="${basedir}",property="workingDirectory",required=false) protected File workingDirectory; /** * The base directory for installing node and npm. */ @Parameter(property="installDirectory",required=false) protected File installDirectory; /** * Additional environment variables to pass to the build. */ @Parameter protected Map<String,String> environmentVariables; @Parameter(defaultValue="${project}",readonly=true) private MavenProject project; @Parameter(defaultValue="${repositorySystemSession}",readonly=true) private RepositorySystemSession repositorySystemSession; /** * Determines if this execution should be skipped. */ private boolean skipTestPhase(); /** * Determines if the current execution is during a testing phase (e.g., "test" or "integration-test"). */ private boolean isTestingPhase(); protected abstract void execute( FrontendPluginFactory factory) throws FrontendException ; /** * Implemented by children to determine if this execution should be skipped. */ protected abstract boolean skipExecution(); @Override public void execute() throws MojoFailureException; }
houbb_sensitive-word
sensitive-word/src/main/java/com/github/houbb/sensitive/word/support/allow/WordAllows.java
WordAllows
init
class WordAllows { private WordAllows(){} /** * 责任链 * @param wordAllow 允许 * @param others 其他 * @return 结果 * @since 0.0.13 */ public static IWordAllow chains(final IWordAllow wordAllow, final IWordAllow... others) { return new WordAllowInit() { @Override protected void init(Pipeline<IWordAllow> pipeline) {<FILL_FUNCTION_BODY>} }; } /** * 系统实现 * @return 结果 * @since 0.0.13 */ public static IWordAllow defaults() { return WordAllowSystem.getInstance(); } }
pipeline.addLast(wordAllow); if(ArrayUtil.isNotEmpty(others)) { for(IWordAllow other : others) { pipeline.addLast(other); } }
194
55
249
Pay-Group_best-pay-sdk
best-pay-sdk/src/main/java/com/lly835/bestpay/service/impl/BestPayServiceImpl.java
BestPayServiceImpl
payBank
class BestPayServiceImpl implements BestPayService { /** * TODO 重构 * 暂时先再引入一个config */ private WxPayConfig wxPayConfig; private AliPayConfig aliPayConfig; public void setWxPayConfig(WxPayConfig wxPayConfig) { this.wxPayConfig = wxPayConfig; } public void setAliPayConfig(AliPayConfig aliPayConfig) { this.aliPayConfig = aliPayConfig; } @Override public PayResponse pay(PayRequest request) { Objects.requireNonNull(request, "request params must not be null"); //微信支付 if (BestPayPlatformEnum.WX == request.getPayTypeEnum().getPlatform()) { WxPayServiceImpl wxPayService = new WxPayServiceImpl(); wxPayService.setWxPayConfig(this.wxPayConfig); return wxPayService.pay(request); } // 支付宝支付 else if (BestPayPlatformEnum.ALIPAY == request.getPayTypeEnum().getPlatform()) { AliPayServiceImpl aliPayService = new AliPayServiceImpl(); aliPayService.setAliPayConfig(aliPayConfig); return aliPayService.pay(request); } throw new RuntimeException("错误的支付方式"); } /** * 同步返回 * * @param request * @return */ @Override public PayResponse syncNotify(HttpServletRequest request) { return null; } @Override public boolean verify(Map<String, String> toBeVerifiedParamMap, SignType signType, String sign) { return false; } /** * 异步回调 * * @return */ @Override public PayResponse asyncNotify(String notifyData) { //<xml>开头的是微信通知 if (notifyData.startsWith("<xml>")) { WxPayServiceImpl wxPayService = new WxPayServiceImpl(); wxPayService.setWxPayConfig(this.wxPayConfig); return wxPayService.asyncNotify(notifyData); } else { AliPayServiceImpl aliPayService = new AliPayServiceImpl(); aliPayService.setAliPayConfig(aliPayConfig); return aliPayService.asyncNotify(notifyData); } } @Override public RefundResponse refund(RefundRequest request) { if (request.getPayPlatformEnum() == BestPayPlatformEnum.WX) { WxPayServiceImpl wxPayService = new WxPayServiceImpl(); wxPayService.setWxPayConfig(this.wxPayConfig); return wxPayService.refund(request); } else if (request.getPayPlatformEnum() == BestPayPlatformEnum.ALIPAY) { AliPayServiceImpl aliPayService = new AliPayServiceImpl(); aliPayService.setAliPayConfig(this.aliPayConfig); return aliPayService.refund(request); } throw new RuntimeException("错误的支付平台"); } /** * 查询订单 * * @param request * @return */ @Override public OrderQueryResponse query(OrderQueryRequest request) { if (request.getPlatformEnum() == BestPayPlatformEnum.WX) { WxPayServiceImpl wxPayService = new WxPayServiceImpl(); wxPayService.setWxPayConfig(this.wxPayConfig); return wxPayService.query(request); } else if (request.getPlatformEnum() == BestPayPlatformEnum.ALIPAY) { AliPayServiceImpl aliPayService = new AliPayServiceImpl(); aliPayService.setAliPayConfig(this.aliPayConfig); return aliPayService.query(request); } throw new RuntimeException("错误的支付平台"); } @Override public String downloadBill(DownloadBillRequest request) { WxPayServiceImpl wxPayService = new WxPayServiceImpl(); wxPayService.setWxPayConfig(this.wxPayConfig); return wxPayService.downloadBill(request); } @Override public String getQrCodeUrl(String productId) { WxPayServiceImpl wxPayService = new WxPayServiceImpl(); wxPayService.setWxPayConfig(this.wxPayConfig); return wxPayService.getQrCodeUrl(productId); } @Override public CloseResponse close(CloseRequest request) { if (request.getPayTypeEnum().getPlatform() == BestPayPlatformEnum.ALIPAY) { AliPayServiceImpl aliPayService = new AliPayServiceImpl(); aliPayService.setAliPayConfig(this.aliPayConfig); return aliPayService.close(request); } throw new RuntimeException("尚未支持该种支付方式"); } @Override public PayBankResponse payBank(PayBankRequest request) {<FILL_FUNCTION_BODY>} }
if (request.getPayTypeEnum().getPlatform() == BestPayPlatformEnum.WX) { WxPayServiceImpl wxPayService = new WxPayServiceImpl(); wxPayService.setWxPayConfig(this.wxPayConfig); return wxPayService.payBank(request); } else if (request.getPayTypeEnum().getPlatform() == BestPayPlatformEnum.ALIPAY) { AliPayServiceImpl aliPayService = new AliPayServiceImpl(); aliPayService.setAliPayConfig(this.aliPayConfig); return aliPayService.payBank(request); } throw new RuntimeException("尚未支持该种支付方式");
1,273
167
1,440
Kong_unirest-java
unirest-java/unirest/src/main/java/kong/unirest/core/Headers.java
Headers
equals
class Headers { private static final long serialVersionUID = 71310341388734766L; private List<Header> headers = new ArrayList<>(); public Headers() { } public Headers(Collection<Entry> entries) { entries.forEach(e -> add(e.name, e.value)); } /** * Add a header element * @param name the name of the header * @param value the value for the header */ public void add(String name, String value) { add(name, () -> value); } /** * Add a header element with a supplier which will be evaluated on request * @param name the name of the header * @param value the value for the header */ public void add(String name, Supplier<String> value) { if (Objects.nonNull(name)) { headers.add(new Entry(name, value)); } } /** * Replace a header value. If there are multiple instances it will overwrite all of them * @param name the name of the header * @param value the value for the header */ public void replace(String name, String value) { remove(name); add(name, value); } private void remove(String name) { headers.removeIf(h -> isName(h, name)); } /** * Get the number of header keys. * @return the size of the header keys */ public int size() { return headers.stream().map(Header::getName).collect(toSet()).size(); } /** * Get all the values for a header name * @param name name of the header element * @return a list of values */ public List<String> get(String name) { return headers.stream() .filter(h -> isName(h, name)) .map(Header::getValue) .collect(toList()); } /** * Add a bunch of headers at once * @param header a header */ public void putAll(Headers header) { this.headers.addAll(header.headers); } /** * Check if a header is present * @param name a header * @return if the headers contain this name. */ public boolean containsKey(String name) { return this.headers.stream().anyMatch(h -> isName(h, name)); } /** * Clear the headers! */ public void clear() { this.headers.clear(); } /** * Get the first header value for a name * @param key the name of the header * @return the first value */ public String getFirst(String key) { return headers .stream() .filter(h -> isName(h, key)) .findFirst() .map(Header::getValue) .orElse(""); } /** * Get all of the headers * @return all the headers, in order */ public List<Header> all() { return new ArrayList<>(this.headers); } private boolean isName(Header h, String name) { return Util.nullToEmpty(name).equalsIgnoreCase(h.getName()); } void remove(String key, String value) { List<Header> header = headers.stream(). filter(h -> key.equalsIgnoreCase(h.getName()) && value.equalsIgnoreCase(h.getValue())) .collect(toList()); headers.removeAll(header); } /** * @return list all headers like this: <pre>Content-Length: 42 * Cache-Control: no-cache * ...</pre> */ @Override public String toString() { final StringJoiner sb = new StringJoiner(System.lineSeparator()); headers.forEach(header -> sb.add(header.toString())); return sb.toString(); } public void cookie(Cookie cookie) { headers.add(new Entry("cookie", cookie.toString())); } public void cookie(Collection<Cookie> cookies) { cookies.forEach(this::cookie); } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(headers); } public void setBasicAuth(String username, String password) { this.replace("Authorization", Util.toBasicAuthValue(username, password)); } public void accepts(String value) { add(HeaderNames.ACCEPT, value); } public void add(Map<String, String> headerMap) { if (headerMap != null) { for (Map.Entry<String, String> entry : headerMap.entrySet()) { add(entry.getKey(), entry.getValue()); } } } /** * Replace all headers from a given map. * @param headerMap the map of headers */ public void replace(Map<String, String> headerMap) { if (headerMap != null) { headerMap.forEach(this::replace); } } static class Entry implements Header { private final String name; private final Supplier<String> value; public Entry(String name, String value) { this.name = name; this.value = () -> value; } public Entry(String name, Supplier<String> value) { this.name = name; this.value = value == null ? () -> null : value; } @Override public String getName() { return name; } @Override public String getValue() { String s = value.get(); if(s == null){ return ""; } return s; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Entry entry = (Entry) o; return Objects.equals(name, entry.name) && Objects.equals(value.get(), entry.value.get()); } @Override public int hashCode() { return Objects.hash(name, value.get()); } @Override public String toString() { return String.format("%s: %s",getName(), getValue()); } } }
if (this == o) { return true;} if (o == null || getClass() != o.getClass()) { return false; } Headers headers1 = (Headers) o; return Objects.equals(headers, headers1.headers);
1,694
65
1,759
ainilili_ratel
ratel/landlords-client/src/main/java/org/nico/ratel/landlords/client/event/ClientEventListener_CODE_GAME_OVER.java
ClientEventListener_CODE_GAME_OVER
call
class ClientEventListener_CODE_GAME_OVER extends ClientEventListener { @Override public void call(Channel channel, String data) {<FILL_FUNCTION_BODY>} }
Map<String, Object> map = MapHelper.parser(data); SimplePrinter.printNotice("\nPlayer " + map.get("winnerNickname") + "[" + map.get("winnerType") + "]" + " won the game"); if (map.containsKey("scores")){ List<Map<String, Object>> scores = Noson.convert(map.get("scores"), new NoType<List<Map<String, Object>>>() {}); for (Map<String, Object> score : scores) { if (! Objects.equals(score.get("clientId"), SimpleClient.id)) { SimplePrinter.printNotice(score.get("nickName").toString() + "'s rest poker is:"); SimplePrinter.printPokers(Noson.convert(score.get("pokers"), new NoType<List<Poker>>() {})); } } SimplePrinter.printNotice("\n"); // print score for (Map<String, Object> score : scores) { String scoreInc = score.get("scoreInc").toString(); String scoreTotal = score.get("score").toString(); if (SimpleClient.id != (int) score.get("clientId")) { SimplePrinter.printNotice(score.get("nickName").toString() + "'s score is " + scoreInc + ", total score is " + scoreTotal); } else { SimplePrinter.printNotice("your score is " + scoreInc + ", total score is " + scoreTotal); } } ClientEventListener_CODE_GAME_READY.gameReady(channel); }
46
416
462
public abstract class ClientEventListener { public abstract void call( Channel channel, String data); public final static Map<ClientEventCode,ClientEventListener> LISTENER_MAP=new HashMap<>(); private final static String LISTENER_PREFIX="org.nico.ratel.landlords.client.event.ClientEventListener_"; protected static List<Poker> lastPokers=null; protected static String lastSellClientNickname=null; protected static String lastSellClientType=null; protected static void initLastSellInfo(); @SuppressWarnings("unchecked") public static ClientEventListener get( ClientEventCode code); protected ChannelFuture pushToServer( Channel channel, ServerEventCode code, String datas); protected ChannelFuture pushToServer( Channel channel, ServerEventCode code); }
joelittlejohn_jsonschema2pojo
jsonschema2pojo/jsonschema2pojo-cli/src/main/java/org/jsonschema2pojo/cli/CommandLineLogger.java
CommandLineLogger
printLogLevels
class CommandLineLogger extends AbstractRuleLogger { public static final String DEFAULT_LOG_LEVEL = LogLevel.INFO.value(); private final int logLevel; public CommandLineLogger(String logLevel) { this.logLevel = LogLevel.fromValue(logLevel).levelInt(); } @Override public boolean isDebugEnabled() { return logLevel >= LogLevel.DEBUG.levelInt(); } @Override public boolean isErrorEnabled() { return logLevel >= LogLevel.ERROR.levelInt(); } @Override public boolean isInfoEnabled() { return logLevel >= LogLevel.INFO.levelInt(); } @Override public boolean isTraceEnabled() { return logLevel >= LogLevel.TRACE.levelInt(); } @Override public boolean isWarnEnabled() { return logLevel >= LogLevel.WARN.levelInt(); } public void printLogLevels() {<FILL_FUNCTION_BODY>} @Override protected void doDebug(String msg) { System.out.println(msg); } @Override protected void doError(String msg, Throwable e) { System.err.println(msg); if(e != null) { e.printStackTrace(System.err); } } @Override protected void doInfo(String msg) { System.out.print(msg); } @Override protected void doTrace(String msg) { System.out.print(msg); } @Override protected void doWarn(String msg, Throwable e) { System.err.println(msg); if(e != null) { e.printStackTrace(System.err); } } public enum LogLevel { OFF("off", -2), ERROR("error", -1), WARN("warn", 0), INFO("info", 1), DEBUG("debug", 2), TRACE("trace", 3); private final static Map<String, LogLevel> LEVEL_NAMES = new LinkedHashMap<>(); private final String levelName; private final int levelInt; LogLevel(String value, int levelInt) { this.levelName = value; this.levelInt = levelInt; } @JsonCreator public static LogLevel fromValue(String value) { LogLevel constant = LEVEL_NAMES.get(value); if (constant == null) { throw new IllegalArgumentException(value); } else { return constant; } } public static Set<String> getLevelNames() { return LEVEL_NAMES.keySet(); } public int levelInt() { return levelInt; } @Override public String toString() { return this.levelName; } @JsonValue public String value() { return this.levelName; } static { for (LogLevel c : values()) { LEVEL_NAMES.put(c.levelName, c); } } } public static class LogLevelValidator implements IParameterValidator2 { @Override public void validate(String name, String value, ParameterDescription pd) throws ParameterException { Collection<String> availableLogLevels = LogLevel.getLevelNames(); if (!availableLogLevels.contains(value)) { String availableLevelJoined = availableLogLevels.stream().collect(Collectors.joining(", ", "[", "]")); throw new ParameterException("The parameter " + name + " must be one of " + availableLevelJoined); } } @Override public void validate(String name, String value) throws ParameterException { validate(name, value, null); } } }
Set<String> levelNames = LogLevel.getLevelNames(); String levelNamesJoined = levelNames.stream().collect(Collectors.joining(", ")); System.out.println("Available Log Levels: " + levelNamesJoined);
990
63
1,053
public abstract class AbstractRuleLogger implements RuleLogger { @Override public void debug( String msg); @Override public void error( String msg); @Override public void error( String msg, Throwable e); @Override public void info( String msg); @Override public void trace( String msg); @Override public void warn( String msg); @Override public void warn( String msg, Throwable e); abstract protected void doDebug( String msg); abstract protected void doError( String msg, Throwable e); abstract protected void doInfo( String msg); abstract protected void doTrace( String msg); abstract protected void doWarn( String msg, Throwable e); }
zhkl0228_unidbg
unidbg/unidbg-api/src/main/java/com/github/unidbg/memory/MemoryBlockImpl.java
MemoryBlockImpl
alloc
class MemoryBlockImpl implements MemoryBlock { public static MemoryBlock alloc(Memory memory, int length) {<FILL_FUNCTION_BODY>} public static MemoryBlock allocExecutable(Memory memory, int length) { UnidbgPointer pointer = memory.mmap(length, UnicornConst.UC_PROT_READ | UnicornConst.UC_PROT_EXEC); return new MemoryBlockImpl(memory, pointer); } private final Memory memory; private final UnidbgPointer pointer; private MemoryBlockImpl(Memory memory, UnidbgPointer pointer) { this.memory = memory; this.pointer = pointer; } @Override public UnidbgPointer getPointer() { return pointer; } @Override public boolean isSame(Pointer pointer) { return this.pointer.equals(pointer); } @Override public void free() { memory.munmap(pointer.peer, (int) pointer.getSize()); } }
UnidbgPointer pointer = memory.mmap(length, UnicornConst.UC_PROT_READ | UnicornConst.UC_PROT_WRITE); return new MemoryBlockImpl(memory, pointer);
258
55
313
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-lock/autoload-cache-lock-jedis/src/main/java/com/jarvis/cache/lock/ShardedJedisLock.java
ShardedJedisLock
setnx
class ShardedJedisLock extends AbstractRedisLock { private ShardedJedisPool shardedJedisPool; public ShardedJedisLock(ShardedJedisPool shardedJedisPool) { this.shardedJedisPool = shardedJedisPool; } private void returnResource(ShardedJedis shardedJedis) { shardedJedis.close(); } @Override protected boolean setnx(String key, String val, int expire) {<FILL_FUNCTION_BODY>} @Override protected void del(String key) { ShardedJedis shardedJedis = null; try { shardedJedis = shardedJedisPool.getResource(); Jedis jedis = shardedJedis.getShard(key); jedis.del(key); } finally { returnResource(shardedJedis); } } }
ShardedJedis shardedJedis = null; try { shardedJedis = shardedJedisPool.getResource(); Jedis jedis = shardedJedis.getShard(key); return OK.equalsIgnoreCase(jedis.set(key, val, SetParams.setParams().nx().ex(expire))); } finally { returnResource(shardedJedis); }
254
113
367
/** * 基于Redis实现分布式锁 */ public abstract class AbstractRedisLock implements ILock { private static final Logger logger=LoggerFactory.getLogger(AbstractRedisLock.class); private static final ThreadLocal<Map<String,RedisLockInfo>> LOCK_START_TIME=new ThreadLocal<Map<String,RedisLockInfo>>(){ @Override protected Map<String,RedisLockInfo> initialValue(); } ; protected static final String OK="OK"; protected static final String NX="NX"; protected static final String EX="EX"; /** * SETNX * @param key key * @param val vale * @param expire 过期时间 * @return 是否设置成功 */ protected abstract boolean setnx( String key, String val, int expire); /** * DEL * @param key key */ protected abstract void del( String key); @Override public boolean tryLock( String key, int lockExpire); @Override public void unlock( String key); }
joelittlejohn_jsonschema2pojo
jsonschema2pojo/jsonschema2pojo-core/src/main/java/org/jsonschema2pojo/Schema.java
Schema
getGrandParent
class Schema { private final URI id; private final JsonNode content; private final Schema parent; private JType javaType; public Schema(URI id, JsonNode content, Schema parent) { this.id = id; this.content = content; this.parent = parent != null ? parent : this; } public JType getJavaType() { return javaType; } public void setJavaType(JType javaType) { this.javaType = javaType; } public void setJavaTypeIfEmpty(JType javaType) { if (this.getJavaType() == null) { this.setJavaType(javaType); } } public URI getId() { return id; } public JsonNode getContent() { return content; } public Schema getParent() { return parent; } public Schema getGrandParent() {<FILL_FUNCTION_BODY>} public boolean isGenerated() { return javaType != null; } }
if (parent == this) { return this; } else { return this.parent.getGrandParent(); }
287
37
324
javamelody_javamelody
javamelody/javamelody-core/src/main/java/net/bull/javamelody/Log4JAppender.java
Log4JAppender
append
class Log4JAppender extends AppenderSkeleton { private static final String MESSAGE_PATTERN = "%-5p [%c] %m%n"; private static final Level THRESHOLD = Level.WARN; private static final Log4JAppender SINGLETON = new Log4JAppender(); /** * Constructeur. */ public Log4JAppender() { super(); setLayout(new PatternLayout(MESSAGE_PATTERN)); setThreshold(THRESHOLD); setName(getClass().getName()); } static Log4JAppender getSingleton() { return SINGLETON; } void register() { Logger.getRootLogger().addAppender(this); } void deregister() { Logger.getRootLogger().removeAppender(this); } /** * {@inheritDoc} */ @Override protected void append(LoggingEvent event) {<FILL_FUNCTION_BODY>} /** * {@inheritDoc} */ @Override public void close() { // rien à faire } /** * {@inheritDoc} */ @Override public boolean requiresLayout() { return false; } }
final Throwable throwable; if (event.getThrowableInformation() == null) { throwable = null; } else { throwable = event.getThrowableInformation().getThrowable(); } LoggingHandler.addErrorLogToCounter(getLayout().format(event), throwable);
372
92
464
obsidiandynamics_kafdrop
kafdrop/src/main/java/kafdrop/model/ConsumerTopicVO.java
ConsumerTopicVO
getLag
class ConsumerTopicVO { private final String topic; private final Map<Integer, ConsumerPartitionVO> offsets = new TreeMap<>(); public ConsumerTopicVO(String topic) { this.topic = topic; } public String getTopic() { return topic; } public void addOffset(ConsumerPartitionVO offset) { offsets.put(offset.getPartitionId(), offset); } public long getLag() {<FILL_FUNCTION_BODY>} public Collection<ConsumerPartitionVO> getPartitions() { return offsets.values(); } }
return offsets.values().stream() .map(ConsumerPartitionVO::getLag) .filter(lag -> lag >= 0) .reduce(0L, Long::sum);
161
51
212
YunaiV_ruoyi-vue-pro
ruoyi-vue-pro/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/framework/sms/core/client/impl/AbstractSmsClient.java
AbstractSmsClient
refresh
class AbstractSmsClient implements SmsClient { /** * 短信渠道配置 */ protected volatile SmsChannelProperties properties; public AbstractSmsClient(SmsChannelProperties properties) { this.properties = properties; } /** * 初始化 */ public final void init() { doInit(); log.debug("[init][配置({}) 初始化完成]", properties); } /** * 自定义初始化 */ protected abstract void doInit(); public final void refresh(SmsChannelProperties properties) {<FILL_FUNCTION_BODY>} @Override public Long getId() { return properties.getId(); } }
// 判断是否更新 if (properties.equals(this.properties)) { return; } log.info("[refresh][配置({})发生变化,重新初始化]", properties); this.properties = properties; // 初始化 this.init();
192
75
267
Pay-Group_best-pay-sdk
best-pay-sdk/src/main/java/com/lly835/bestpay/utils/WebUtil.java
WebUtil
buildForm
class WebUtil { public static String buildForm(String baseUrl,Map<String, String> parameters) {<FILL_FUNCTION_BODY>} private static String buildHiddenFields(Map<String, String> parameters) { if (parameters != null && !parameters.isEmpty()) { StringBuffer sb = new StringBuffer(); Set<String> keys = parameters.keySet(); Iterator var3 = keys.iterator(); while(var3.hasNext()) { String key = (String)var3.next(); String value = (String)parameters.get(key); if (key != null && value != null) { sb.append(buildHiddenField(key, value)); } } String result = sb.toString(); return result; } else { return ""; } } private static String buildHiddenField(String key, String value) { StringBuffer sb = new StringBuffer(); sb.append("<input type=\"hidden\" name=\""); sb.append(key); sb.append("\" value=\""); String a = value.replace("\"", "&quot;"); sb.append(a).append("\">\n"); return sb.toString(); } public static String buildQuery(Map<String, String> params, String charset) throws IOException { if (params != null && !params.isEmpty()) { StringBuilder query = new StringBuilder(); Set<Map.Entry<String, String>> entries = params.entrySet(); boolean hasParam = false; Iterator var5 = entries.iterator(); while(var5.hasNext()) { Map.Entry<String, String> entry = (Map.Entry)var5.next(); String name = entry.getKey(); String value = entry.getValue(); if (StringUtil.areNotEmpty(new String[]{name, value})) { if (hasParam) { query.append("&"); } else { hasParam = true; } query.append(name).append("=").append(URLEncoder.encode(value, charset)); } } return query.toString(); } else { return null; } } public static String getRequestUrl(Map<String,String> parameters,Boolean isSandbox) { StringBuffer urlSb; if(isSandbox) urlSb = new StringBuffer(AliPayConstants.ALIPAY_GATEWAY_OPEN_DEV); else urlSb = new StringBuffer(AliPayConstants.ALIPAY_GATEWAY_OPEN); urlSb.append("/gateway.do"); try { String charset = null != parameters.get("charset") ? parameters.get("charset") : "utf-8"; String sysMustQuery = WebUtil.buildQuery(parameters, charset); urlSb.append("?"); urlSb.append(sysMustQuery); } catch (IOException e) { e.printStackTrace(); } return urlSb.toString(); } }
StringBuffer sb = new StringBuffer(); sb.append("<form id='bestPayForm' name=\"punchout_form\" method=\"post\" action=\""); sb.append(baseUrl); sb.append("\">\n"); sb.append(buildHiddenFields(parameters)); sb.append("<input type=\"submit\" value=\"立即支付\" style=\"display:none\" >\n"); sb.append("</form>\n"); sb.append("<script>document.getElementById('bestPayForm').submit();</script>"); String form = sb.toString(); return form;
782
160
942
orientechnologies_orientdb
orientdb/core/src/main/java/com/orientechnologies/orient/core/storage/cache/chm/LRUList.java
LRUList
moveToTheTail
class LRUList implements Iterable<OCacheEntry> { private int size; private OCacheEntry head; private OCacheEntry tail; void remove(final OCacheEntry entry) { final OCacheEntry next = entry.getNext(); final OCacheEntry prev = entry.getPrev(); if (!(next != null || prev != null || entry == head)) { return; } assert prev == null || prev.getNext() == entry; assert next == null || next.getPrev() == entry; if (next != null) { next.setPrev(prev); } if (prev != null) { prev.setNext(next); } if (head == entry) { assert entry.getPrev() == null; head = next; } if (tail == entry) { assert entry.getNext() == null; tail = prev; } entry.setNext(null); entry.setPrev(null); entry.setContainer(null); size--; } boolean contains(final OCacheEntry entry) { return entry.getContainer() == this; } void moveToTheTail(final OCacheEntry entry) {<FILL_FUNCTION_BODY>} int size() { return size; } OCacheEntry poll() { if (head == null) { return null; } final OCacheEntry entry = head; final OCacheEntry next = head.getNext(); assert next == null || next.getPrev() == head; head = next; if (next != null) { next.setPrev(null); } assert head == null || head.getPrev() == null; if (head == null) { tail = null; } entry.setNext(null); assert entry.getPrev() == null; size--; entry.setContainer(null); return entry; } OCacheEntry peek() { return head; } public Iterator<OCacheEntry> iterator() { return new Iterator<OCacheEntry>() { private OCacheEntry next = tail; @Override public boolean hasNext() { return next != null; } @Override public OCacheEntry next() { if (!hasNext()) { throw new NoSuchElementException(); } final OCacheEntry result = next; next = next.getPrev(); return result; } }; } }
if (tail == entry) { assert entry.getNext() == null; return; } final OCacheEntry next = entry.getNext(); final OCacheEntry prev = entry.getPrev(); final boolean newEntry = entry.getContainer() == null; assert entry.getContainer() == null || entry.getContainer() == this; assert prev == null || prev.getNext() == entry; assert next == null || next.getPrev() == entry; if (prev != null) { prev.setNext(next); } if (next != null) { next.setPrev(prev); } if (head == entry) { assert entry.getPrev() == null; head = next; } entry.setPrev(tail); entry.setNext(null); if (tail != null) { assert tail.getNext() == null; tail.setNext(entry); tail = entry; } else { tail = head = entry; } if (newEntry) { entry.setContainer(this); size++; } else { assert entry.getContainer() == this; }
675
313
988
YunaiV_ruoyi-vue-pro
ruoyi-vue-pro/yudao-framework/yudao-common/src/main/java/cn/iocoder/yudao/framework/common/validation/InEnumValidator.java
InEnumValidator
isValid
class InEnumValidator implements ConstraintValidator<InEnum, Integer> { private List<Integer> values; @Override public void initialize(InEnum annotation) { IntArrayValuable[] values = annotation.value().getEnumConstants(); if (values.length == 0) { this.values = Collections.emptyList(); } else { this.values = Arrays.stream(values[0].array()).boxed().collect(Collectors.toList()); } } @Override public boolean isValid(Integer value, ConstraintValidatorContext context) {<FILL_FUNCTION_BODY>} }
// 为空时,默认不校验,即认为通过 if (value == null) { return true; } // 校验通过 if (values.contains(value)) { return true; } // 校验不通过,自定义提示语句(因为,注解上的 value 是枚举类,无法获得枚举类的实际值) context.disableDefaultConstraintViolation(); // 禁用默认的 message 的值 context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate() .replaceAll("\\{value}", values.toString())).addConstraintViolation(); // 重新添加错误提示语句 return false;
159
180
339
houbb_sensitive-word
sensitive-word/src/main/java/com/github/houbb/sensitive/word/support/check/AbstractWordCheck.java
AbstractWordCheck
sensitiveCheck
class AbstractWordCheck implements IWordCheck { /** * 获取校验类 * @return 类 * @since 0.3.2 */ protected abstract Class<? extends IWordCheck> getSensitiveCheckClass(); /** * 获取确切的长度 * @param beginIndex 开始 * @param checkContext 上下文 * @return 长度 * @since 0.4.0 */ protected abstract int getActualLength(int beginIndex, final InnerSensitiveWordContext checkContext); /** * 获取类别 * @return 类别 * @since 0.14.0 */ protected abstract String getType(); @Override public WordCheckResult sensitiveCheck(int beginIndex, final InnerSensitiveWordContext checkContext) {<FILL_FUNCTION_BODY>} }
Class<? extends IWordCheck> clazz = getSensitiveCheckClass(); final String txt = checkContext.originalText(); if(StringUtil.isEmpty(txt)) { return WordCheckResult.newInstance() .index(0) .type(getType()) .checkClass(clazz); } int actualLength = getActualLength(beginIndex, checkContext); return WordCheckResult.newInstance() .index(actualLength) .type(getType()) .checkClass(clazz);
227
136
363
PlexPt_chatgpt-java
chatgpt-java/src/main/java/com/plexpt/chatgpt/ChatGPT.java
ChatGPT
init
class ChatGPT { /** * keys */ private String apiKey; private List<String> apiKeyList; /** * 自定义api host使用builder的方式构造client */ @Builder.Default private String apiHost = Api.DEFAULT_API_HOST; private Api apiClient; private OkHttpClient okHttpClient; /** * 超时 默认300 */ @Builder.Default private long timeout = 300; /** * okhttp 代理 */ @Builder.Default private Proxy proxy = Proxy.NO_PROXY; /** * 初始化:与服务端建立连接,成功后可直接与服务端进行对话 */ public ChatGPT init() {<FILL_FUNCTION_BODY>} /** * 最新版的GPT-3.5 chat completion 更加贴近官方网站的问答模型 * * @param chatCompletion 问答参数,即咨询的内容 * @return 服务端的问答响应 */ public ChatCompletionResponse chatCompletion(ChatCompletion chatCompletion) { Single<ChatCompletionResponse> chatCompletionResponse = this.apiClient.chatCompletion(chatCompletion); return chatCompletionResponse.blockingGet(); } /** * 支持多个问答参数来与服务端进行对话 * * @param messages 问答参数,即咨询的内容 * @return 服务端的问答响应 */ public ChatCompletionResponse chatCompletion(List<Message> messages) { ChatCompletion chatCompletion = ChatCompletion.builder().messages(messages).build(); return this.chatCompletion(chatCompletion); } /** * 与服务端进行对话 * @param message 问答参数,即咨询的内容 * @return 服务端的问答响应 */ public String chat(String message) { ChatCompletion chatCompletion = ChatCompletion.builder() .messages(Arrays.asList(Message.of(message))) .build(); ChatCompletionResponse response = this.chatCompletion(chatCompletion); return response.getChoices().get(0).getMessage().getContent(); } /** * 余额查询 * * @return 余额总金额及明细 */ public CreditGrantsResponse creditGrants() { Single<CreditGrantsResponse> creditGrants = this.apiClient.creditGrants(); return creditGrants.blockingGet(); } /** * 余额查询 * * @return 余额总金额 */ public BigDecimal balance() { Single<SubscriptionData> subscription = apiClient.subscription(); SubscriptionData subscriptionData = subscription.blockingGet(); BigDecimal total = subscriptionData.getHardLimitUsd(); DateTime start = DateUtil.offsetDay(new Date(), -90); DateTime end = DateUtil.offsetDay(new Date(), 1); Single<UseageResponse> usage = apiClient.usage(formatDate(start), formatDate(end)); UseageResponse useageResponse = usage.blockingGet(); BigDecimal used = useageResponse.getTotalUsage().divide(BigDecimal.valueOf(100)); return total.subtract(used); } /** * 新建连接进行余额查询 * * @return 余额总金额 */ public static BigDecimal balance(String key) { ChatGPT chatGPT = ChatGPT.builder() .apiKey(key) .build() .init(); return chatGPT.balance(); } }
OkHttpClient.Builder client = new OkHttpClient.Builder(); client.addInterceptor(chain -> { Request original = chain.request(); String key = apiKey; if (apiKeyList != null && !apiKeyList.isEmpty()) { key = RandomUtil.randomEle(apiKeyList); } Request request = original.newBuilder() .header(Header.AUTHORIZATION.getValue(), "Bearer " + key) .header(Header.CONTENT_TYPE.getValue(), ContentType.JSON.getValue()) .method(original.method(), original.body()) .build(); return chain.proceed(request); }).addInterceptor(chain -> { Request original = chain.request(); Response response = chain.proceed(original); if (!response.isSuccessful()) { String errorMsg = response.body().string(); log.error("请求异常:{}", errorMsg); BaseResponse baseResponse = JSON.parseObject(errorMsg, BaseResponse.class); if (Objects.nonNull(baseResponse.getError())) { log.error(baseResponse.getError().getMessage()); throw new ChatException(baseResponse.getError().getMessage()); } throw new ChatException("ChatGPT init error!"); } return response; }); client.connectTimeout(timeout, TimeUnit.SECONDS); client.writeTimeout(timeout, TimeUnit.SECONDS); client.readTimeout(timeout, TimeUnit.SECONDS); if (Objects.nonNull(proxy)) { client.proxy(proxy); } OkHttpClient httpClient = client.build(); this.okHttpClient = httpClient; this.apiClient = new Retrofit.Builder() .baseUrl(this.apiHost) .client(okHttpClient) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(JacksonConverterFactory.create()) .build() .create(Api.class); return this;
965
517
1,482
zhkl0228_unidbg
unidbg/unidbg-android/src/main/java/com/github/unidbg/linux/file/DnsProxyDaemon.java
DnsProxyDaemon
getaddrinfo
class DnsProxyDaemon implements LocalSocketIO.SocketHandler { private static final Log log = LogFactory.getLog(DnsProxyDaemon.class); private static final int DnsProxyQueryResult = 222; private static final int DnsProxyOperationFailed = 401; private final ByteArrayOutputStream baos = new ByteArrayOutputStream(1024); private final int sdk; DnsProxyDaemon(int sdk) { this.sdk = sdk; } @Override public int fstat(StatStructure stat) { stat.st_size = 0; stat.st_blksize = 0; stat.pack(); return 0; } @Override public byte[] handle(byte[] request) throws IOException { baos.write(request); byte[] data = baos.toByteArray(); int endIndex = -1; for (int i = 0; i < data.length; i++) { if (data[i] == 0) { endIndex = i; break; } } if (endIndex == -1) { return null; } baos.reset(); String command = new String(data, 0, endIndex); if (command.startsWith("getaddrinfo")) { return getaddrinfo(command); } else if (command.startsWith("gethostbyaddr")) { return gethostbyaddr(command); } throw new AbstractMethodError(command); } private byte[] gethostbyaddr(String command) { ByteBuffer buffer = ByteBuffer.allocate(1024); String[] tokens = command.split("\\s"); String addr = tokens[1]; try { InetAddress address = InetAddress.getByName(addr); String host = address.getCanonicalHostName(); if (host != null && host.equals(addr)) { host = null; } if (host == null) { throw new UnknownHostException(); } else { buffer.put((DnsProxyQueryResult + "\0").getBytes()); byte[] bytes = host.getBytes(StandardCharsets.UTF_8); buffer.putInt(bytes.length + 1); buffer.put(bytes); buffer.put((byte) 0); // NULL-terminated string buffer.putInt(0); // null to indicate we're done aliases buffer.putInt(SocketIO.AF_INET); // addrtype buffer.putInt(4); // unknown length buffer.putInt(0); // null to indicate we're done addr_list } } catch (UnknownHostException e) { buffer.put((DnsProxyOperationFailed + "\0").getBytes()); buffer.putInt(0); } buffer.flip(); byte[] response = new byte[buffer.remaining()]; buffer.get(response); if (log.isDebugEnabled()) { Inspector.inspect(response, "gethostbyaddr"); } return response; } private byte[] getaddrinfo(String command) {<FILL_FUNCTION_BODY>} private void putAddress(ByteBuffer buffer, InetAddress address, int ai_flags, int ai_socktype, short port) { if (sdk == 19) { buffer.order(ByteOrder.BIG_ENDIAN); buffer.putInt(32); // sizeof(struct addrinfo) buffer.order(ByteOrder.LITTLE_ENDIAN); buffer.putInt(ai_flags); buffer.putInt(SocketIO.AF_INET); buffer.putInt(ai_socktype); buffer.putInt(SocketIO.IPPROTO_TCP); buffer.putInt(16); // ai_addrlen buffer.putInt(0); // ai_canonname buffer.putInt(0); // ai_addr buffer.putInt(0); // ai_next buffer.order(ByteOrder.BIG_ENDIAN); buffer.putInt(16); // ai_addrlen buffer.order(ByteOrder.LITTLE_ENDIAN); buffer.putShort((short) SocketIO.AF_INET); // sin_family buffer.putShort(Short.reverseBytes(port)); // sin_port buffer.put(Arrays.copyOf(address.getAddress(), 4)); buffer.put(new byte[8]); // __pad buffer.order(ByteOrder.BIG_ENDIAN); buffer.putInt(0); // ai_canonname } else if (sdk == 23) { buffer.order(ByteOrder.BIG_ENDIAN); buffer.putInt(1); // sizeof(struct addrinfo) buffer.putInt(ai_flags); buffer.putInt(SocketIO.AF_INET); buffer.putInt(ai_socktype); buffer.putInt(SocketIO.IPPROTO_TCP); buffer.putInt(16); // ai_addrlen buffer.order(ByteOrder.LITTLE_ENDIAN); buffer.putShort((short) SocketIO.AF_INET); // sin_family buffer.putShort(Short.reverseBytes(port)); // sin_port buffer.put(Arrays.copyOf(address.getAddress(), 4)); buffer.put(new byte[8]); // __pad buffer.order(ByteOrder.BIG_ENDIAN); buffer.putInt(0); // ai_canonname } else { throw new IllegalStateException("sdk=" + sdk); } } }
String[] tokens = command.split("\\s"); String hostname = tokens[1]; String servername = tokens[2]; short port = 0; if (!"^".equals(servername)) { try { port = Short.parseShort(servername); } catch (NumberFormatException ignored) { } } int ai_flags = Integer.parseInt(tokens[3]); int ai_family = Integer.parseInt(tokens[4]); int ai_socktype = Integer.parseInt(tokens[5]); int ai_protocol = Integer.parseInt(tokens[6]); ByteBuffer buffer = ByteBuffer.allocate(1024); try { InetAddress[] addresses = InetAddress.getAllByName(hostname); if (log.isDebugEnabled()) { log.debug("getaddrinfo hostname=" + hostname + ", servername=" + servername + ", addresses=" + Arrays.toString(addresses) + ", ai_flags=" + ai_flags + ", ai_family=" + ai_family + ", ai_socktype=" + ai_socktype + ", ai_protocol=" + ai_protocol); } buffer.put((DnsProxyQueryResult + "\0").getBytes()); for (InetAddress address : addresses) { putAddress(buffer, address, ai_flags, ai_socktype, port); } buffer.order(ByteOrder.BIG_ENDIAN); buffer.putInt(0); // NULL-terminated } catch (UnknownHostException e) { final int EAI_NODATA = 7; buffer.put((DnsProxyOperationFailed + "\0").getBytes()); buffer.putInt(4); buffer.order(ByteOrder.LITTLE_ENDIAN); buffer.putInt(EAI_NODATA); } buffer.flip(); byte[] response = new byte[buffer.remaining()]; buffer.get(response); if (log.isDebugEnabled()) { Inspector.inspect(response, "getaddrinfo"); } return response;
1,443
552
1,995
spring-cloud_spring-cloud-gateway
spring-cloud-gateway/spring-cloud-gateway-server/src/main/java/org/springframework/cloud/gateway/filter/FilterDefinition.java
FilterDefinition
toString
class FilterDefinition { @NotNull private String name; private Map<String, String> args = new LinkedHashMap<>(); public FilterDefinition() { } public FilterDefinition(String text) { int eqIdx = text.indexOf('='); if (eqIdx <= 0) { setName(text); return; } setName(text.substring(0, eqIdx)); String[] args = tokenizeToStringArray(text.substring(eqIdx + 1), ","); for (int i = 0; i < args.length; i++) { this.args.put(NameUtils.generateName(i), args[i]); } } public String getName() { return name; } public void setName(String name) { this.name = name; } public Map<String, String> getArgs() { return args; } public void setArgs(Map<String, String> args) { this.args = args; } public void addArg(String key, String value) { this.args.put(key, value); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } FilterDefinition that = (FilterDefinition) o; return Objects.equals(name, that.name) && Objects.equals(args, that.args); } @Override public int hashCode() { return Objects.hash(name, args); } @Override public String toString() {<FILL_FUNCTION_BODY>} }
final StringBuilder sb = new StringBuilder("FilterDefinition{"); sb.append("name='").append(name).append('\''); sb.append(", args=").append(args); sb.append('}'); return sb.toString();
436
69
505
spring-cloud_spring-cloud-gateway
spring-cloud-gateway/spring-cloud-gateway-server/src/main/java/org/springframework/cloud/gateway/support/StringToZonedDateTimeConverter.java
StringToZonedDateTimeConverter
convert
class StringToZonedDateTimeConverter implements Converter<String, ZonedDateTime> { @Override public ZonedDateTime convert(String source) {<FILL_FUNCTION_BODY>} }
ZonedDateTime dateTime; try { long epoch = Long.parseLong(source); dateTime = Instant.ofEpochMilli(epoch).atOffset(ZoneOffset.ofTotalSeconds(0)).toZonedDateTime(); } catch (NumberFormatException e) { // try ZonedDateTime instead dateTime = ZonedDateTime.parse(source); } return dateTime;
49
113
162
YunaiV_ruoyi-vue-pro
ruoyi-vue-pro/yudao-framework/yudao-common/src/main/java/cn/iocoder/yudao/framework/common/util/object/PageUtils.java
PageUtils
buildSortingField
class PageUtils { private static final Object[] ORDER_TYPES = new String[]{SortingField.ORDER_ASC, SortingField.ORDER_DESC}; public static int getStart(PageParam pageParam) { return (pageParam.getPageNo() - 1) * pageParam.getPageSize(); } /** * 构建排序字段(默认倒序) * * @param func 排序字段的 Lambda 表达式 * @param <T> 排序字段所属的类型 * @return 排序字段 */ public static <T> SortingField buildSortingField(Func1<T, ?> func) { return buildSortingField(func, SortingField.ORDER_DESC); } /** * 构建排序字段 * * @param func 排序字段的 Lambda 表达式 * @param order 排序类型 {@link SortingField#ORDER_ASC} {@link SortingField#ORDER_DESC} * @param <T> 排序字段所属的类型 * @return 排序字段 */ public static <T> SortingField buildSortingField(Func1<T, ?> func, String order) {<FILL_FUNCTION_BODY>} /** * 构建默认的排序字段 * 如果排序字段为空,则设置排序字段;否则忽略 * * @param sortablePageParam 排序分页查询参数 * @param func 排序字段的 Lambda 表达式 * @param <T> 排序字段所属的类型 */ public static <T> void buildDefaultSortingField(SortablePageParam sortablePageParam, Func1<T, ?> func) { if (sortablePageParam != null && CollUtil.isEmpty(sortablePageParam.getSortingFields())) { sortablePageParam.setSortingFields(singletonList(buildSortingField(func))); } } }
Assert.isTrue(ArrayUtil.contains(ORDER_TYPES, order), String.format("字段的排序类型只能是 %s/%s", ORDER_TYPES)); String fieldName = LambdaUtil.getFieldName(func); return new SortingField(fieldName, order);
527
77
604
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-manager/autoload-cache-manager-jedis/src/main/java/com/jarvis/cache/redis/JedisClusterPipeline.java
JedisClusterPipeline
innerSync
class JedisClusterPipeline extends PipelineBase implements Closeable { private final JedisClusterInfoCache clusterInfoCache; /** * 根据顺序存储每个命令对应的Client */ private final Queue<Client> clients; /** * 用于缓存连接 */ private final Map<JedisPool, Jedis> jedisMap; public JedisClusterPipeline(JedisClusterInfoCache clusterInfoCache) { this.clusterInfoCache = clusterInfoCache; this.clients = new LinkedList<>(); this.jedisMap = new HashMap<>(3); } /** * 同步读取所有数据. 与syncAndReturnAll()相比,sync()只是没有对数据做反序列化 */ protected void sync() { innerSync(null); } /** * 同步读取所有数据 并按命令顺序返回一个列表 * * @return 按照命令的顺序返回所有的数据 */ protected List<Object> syncAndReturnAll() { List<Object> responseList = new ArrayList<>(clients.size()); innerSync(responseList); return responseList; } private void innerSync(List<Object> formatted) {<FILL_FUNCTION_BODY>} @Override public void close() { clean(); clients.clear(); for (Jedis jedis : jedisMap.values()) { flushCachedData(jedis); jedis.close(); } jedisMap.clear(); } private void flushCachedData(Jedis jedis) { try { //FIXME 这个count怎么取值? 执行命令的个数?? jedis.getClient().getMany(jedisMap.size()); //jedis.getClient().getAll(); } catch (RuntimeException ex) { // 其中一个client出问题,后面出问题的几率较大 } } @Override protected Client getClient(String key) { byte[] bKey = SafeEncoder.encode(key); return getClient(bKey); } @Override protected Client getClient(byte[] key) { Client client = getClient(JedisClusterCRC16.getSlot(key)); clients.add(client); return client; } private Client getClient(int slot) { JedisPool pool = clusterInfoCache.getSlotPool(slot); // 根据pool从缓存中获取Jedis Jedis jedis = jedisMap.get(pool); if (null == jedis) { jedis = pool.getResource(); jedisMap.put(pool, jedis); } return jedis.getClient(); } public JedisClusterInfoCache getClusterInfoCache() { return clusterInfoCache; } public Queue<Client> getClients() { return clients; } public Map<JedisPool, Jedis> getJedisMap() { return jedisMap; } }
try { Response<?> response; Object data; for (Client client : clients) { response = generateResponse(client.getOne()); if (null != formatted) { data = response.get(); formatted.add(data); } } } catch (JedisRedirectionException jre) { throw jre; } finally { close(); }
824
107
931
obsidiandynamics_kafdrop
kafdrop/src/main/java/kafdrop/Kafdrop.java
Kafdrop
deploymentCustomizer
class Kafdrop { private static final Logger LOG = LoggerFactory.getLogger(Kafdrop.class); public static void main(String[] args) { createApplicationBuilder() .run(args); } public static SpringApplicationBuilder createApplicationBuilder() { return new SpringApplicationBuilder(Kafdrop.class) .bannerMode(Mode.OFF) .listeners(new EnvironmentSetupListener(), new LoggingConfigurationListener()); } @Bean public WebServerFactoryCustomizer<UndertowServletWebServerFactory> deploymentCustomizer() {<FILL_FUNCTION_BODY>} @Bean public WebMvcConfigurer webConfig() { return new WebMvcConfigurer() { @Override public void configureContentNegotiation(ContentNegotiationConfigurer configurer) { configurer.favorPathExtension(false); } }; } private static final class LoggingConfigurationListener implements ApplicationListener<ApplicationEnvironmentPreparedEvent>, Ordered { private static final String PROP_LOGGING_FILE = "logging.file"; private static final String PROP_LOGGER = "LOGGER"; private static final String PROP_SPRING_BOOT_LOG_LEVEL = "logging.level.org.springframework.boot"; @Override public int getOrder() { // LoggingApplicationListener runs at HIGHEST_PRECEDENCE + 11. This needs to run before that. return Ordered.HIGHEST_PRECEDENCE; } @Override public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) { final var environment = event.getEnvironment(); final var loggingFile = environment.getProperty(PROP_LOGGING_FILE); if (loggingFile != null) { System.setProperty(PROP_LOGGER, "FILE"); try { System.setProperty("logging.dir", new File(loggingFile).getParent()); } catch (Exception ex) { LOG.error("Unable to set up logging.dir from logging.file {}", loggingFile, ex); } } if (environment.containsProperty("debug") && !"false".equalsIgnoreCase(environment.getProperty("debug", String.class))) { System.setProperty(PROP_SPRING_BOOT_LOG_LEVEL, "DEBUG"); } } } private static final class EnvironmentSetupListener implements ApplicationListener<ApplicationEnvironmentPreparedEvent>, Ordered { private static final String SM_CONFIG_DIR = "sm.config.dir"; private static final String CONFIG_SUFFIX = "-config.ini"; @Override public int getOrder() { return Ordered.HIGHEST_PRECEDENCE + 10; } @Override public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) { final var environment = event.getEnvironment(); LOG.info("Initializing JAAS config"); final String env = environment.getProperty("kafka.env"); LOG.info("Env: {}", env); String path; if (environment.containsProperty(SM_CONFIG_DIR)) { Stream.of("kafdrop", "global") .map(name -> readProperties(environment, name)) .filter(Objects::nonNull) .forEach(iniPropSource -> environment.getPropertySources() .addBefore("applicationConfigurationProperties", iniPropSource)); } } private static IniFilePropertySource readProperties(Environment environment, String name) { final var file = new File(environment.getProperty(SM_CONFIG_DIR), name + CONFIG_SUFFIX); if (file.exists() && file.canRead()) { try (var in = new FileInputStream(file); var reader = new InputStreamReader(in, StandardCharsets.UTF_8)) { return new IniFilePropertySource(name, new IniFileReader().read(reader), environment.getActiveProfiles()); } catch (IOException ex) { LOG.error("Unable to read configuration file {}: {}", file, ex); } } return null; } } }
return factory -> { final UndertowDeploymentInfoCustomizer customizer = deploymentInfo -> { var inf = new WebSocketDeploymentInfo(); inf.setBuffers(new DefaultByteBufferPool(false, 64)); deploymentInfo.addServletContextAttribute(WebSocketDeploymentInfo.ATTRIBUTE_NAME, inf); // see https://stackoverflow.com/a/54129696 deploymentInfo.addInitialHandlerChainWrapper(new HandlerWrapper() { @Override public HttpHandler wrap(HttpHandler handler) { HttpString[] disallowedHttpMethods = { HttpString.tryFromString("TRACE"), HttpString.tryFromString("TRACK") }; return new DisallowedMethodsHandler(handler, disallowedHttpMethods); } }); }; factory.addDeploymentInfoCustomizers(customizer); };
1,049
219
1,268
pmd_pmd
pmd/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTCatchParameter.java
ASTCatchParameter
getAllExceptionTypes
class ASTCatchParameter extends AbstractJavaNode implements InternalInterfaces.VariableIdOwner, ModifierOwner { ASTCatchParameter(int id) { super(id); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } /** * Returns true if this is a multi-catch parameter, * that is, it catches several unrelated exception types * at the same time. For example: * * <pre>catch (IllegalStateException | IllegalArgumentException e) {}</pre> */ public boolean isMulticatch() { return getTypeNode() instanceof ASTUnionType; } @Override @NonNull public ASTVariableId getVarId() { return (ASTVariableId) getLastChild(); } /** Returns the name of this parameter. */ public String getName() { return getVarId().getName(); } /** * Returns the type node of this catch parameter. May be a * {@link ASTUnionType UnionType}. */ public ASTType getTypeNode() { return (ASTType) getChild(1); } /** * Returns a stream of all declared exception types (expanding a union * type if present). * * <p>Note that this is the only reliable way to inspect multi-catch clauses, * as the type mirror of a {@link ASTUnionType} is not itself a {@link JIntersectionType}, * but the {@link TypeSystem#lub(Collection) LUB} of the components. * Since exception types cannot be interfaces, the LUB always erases * to a single class supertype (eg {@link RuntimeException}). */ public NodeStream<ASTClassType> getAllExceptionTypes() {<FILL_FUNCTION_BODY>} public boolean isFinal() { return hasModifiers(JModifier.FINAL); } }
ASTType typeNode = getTypeNode(); if (typeNode instanceof ASTUnionType) { return typeNode.children(ASTClassType.class); } else { return NodeStream.of((ASTClassType) typeNode); }
526
66
592
jeecgboot_jeecg-boot
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/security/JdbcSecurityUtil.java
JdbcSecurityUtil
validate
class JdbcSecurityUtil { /** * 连接驱动漏洞 最新版本修复后,可删除相应的key * postgre:authenticationPluginClassName, sslhostnameverifier, socketFactory, sslfactory, sslpasswordcallback * https://github.com/pgjdbc/pgjdbc/security/advisories/GHSA-v7wg-cpwc-24m4 * */ public static final String[] notAllowedProps = new String[]{"authenticationPluginClassName", "sslhostnameverifier", "socketFactory", "sslfactory", "sslpasswordcallback"}; /** * 校验sql是否有特定的key * @param jdbcUrl * @return */ public static void validate(String jdbcUrl){<FILL_FUNCTION_BODY>} }
if(oConvertUtils.isEmpty(jdbcUrl)){ return; } String urlConcatChar = "?"; if(jdbcUrl.indexOf(urlConcatChar)<0){ return; } String argString = jdbcUrl.substring(jdbcUrl.indexOf(urlConcatChar)+1); String[] keyAndValues = argString.split("&"); for(String temp: keyAndValues){ String key = temp.split("=")[0]; for(String prop: notAllowedProps){ if(prop.equalsIgnoreCase(key)){ throw new JeecgBootException("连接地址有安全风险,【"+key+"】"); } } }
212
184
396
Kong_unirest-java
unirest-java/unirest/src/main/java/kong/unirest/core/ObjectResponse.java
ObjectResponse
getBody
class ObjectResponse<T> extends BaseResponse<T> { private final T body; private final ObjectMapper om; private String rawBody; ObjectResponse(ObjectMapper om, RawResponse response, Class<? extends T> to) { super(response); this.om = om; this.body = readBody(response) .map(s -> getBody(s, e -> om.readValue(e, to))) .orElse(null); } ObjectResponse(ObjectMapper om, RawResponse response, GenericType<? extends T> to){ super(response); this.om = om; this.body = readBody(response) .map(s -> getBody(s, e -> om.readValue(e, to))) .orElse(null); } private Optional<String> readBody(RawResponse response) { if(!response.hasContent()){ return Optional.empty(); } String s = response.getContentAsString(); if(response.getStatus() >= 400){ rawBody = s; } return Optional.of(s); } private T getBody(String b, Function<String, T> func){<FILL_FUNCTION_BODY>} @Override public T getBody() { return body; } @Override protected String getRawBody() { return rawBody; } }
try { return func.apply(b); } catch (RuntimeException e) { setParsingException(b, e); return null; }
375
46
421
Pay-Group_best-pay-sdk
best-pay-sdk/src/main/java/com/lly835/bestpay/utils/JsonUtil.java
JsonUtil
toObject
class JsonUtil { private static final ObjectMapper mapper = new ObjectMapper(); private static GsonBuilder gsonBuilder = new GsonBuilder(); /** * Convert target object to json string. * * @param obj target object. * @return converted json string. */ public static String toJson(Object obj) { gsonBuilder.setPrettyPrinting(); return gsonBuilder.create().toJson(obj); } public static String toJsonWithUnderscores(Object obj) { gsonBuilder.setPrettyPrinting(); gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES); return gsonBuilder.create().toJson(obj); } /** * Convert json string to target object. * * @param json json string. * @param valueType target object class type. * @param <T> target class type. * @return converted target object. */ public static <T> T toObject(String json, Class<T> valueType) {<FILL_FUNCTION_BODY>} }
Objects.requireNonNull(json, "json is null."); Objects.requireNonNull(valueType, "value type is null."); try { return mapper.readValue(json, valueType); } catch (IOException e) { throw new IllegalStateException("fail to convert [" + json + "] to [" + valueType + "].", e); }
295
96
391
Kong_unirest-java
unirest-java/unirest-modules-jackson/src/main/java/kong/unirest/modules/jackson/JacksonArray.java
JacksonArray
add
class JacksonArray extends JacksonElement<ArrayNode> implements JsonEngine.Array { JacksonArray(ArrayNode element) { super(element); } @Override public int size() { return element.size(); } @Override public JsonEngine.Element get(int index) { validateIndex(index); return wrap(element.get(index)); } private void validateIndex(int index) { if(element.size() < index +1){ throw new IndexOutOfBoundsException(); } } @Override public JsonEngine.Element remove(int index) { return wrap(element.remove(index)); } @Override public JsonEngine.Element put(int index, Number number) { if(number instanceof Integer){ element.insert(index, (Integer) number); } else if (number instanceof Double){ element.insert(index, (Double)number); } else if (number instanceof BigInteger) { element.insert(index, (BigInteger) number); } else if (number instanceof Float){ element.insert(index, (Float)number); } else if(number instanceof BigDecimal) { element.insert(index, (BigDecimal) number); } return this; } @Override public JsonEngine.Element put(int index, String value) { element.insert(index, value); return this; } @Override public JsonEngine.Element put(int index, Boolean value) { element.insert(index, value); return this; } @Override public void add(JsonEngine.Element obj) { if(obj == null){ element.add(NullNode.getInstance()); return; } element.add((JsonNode) obj.getEngineElement()); } @Override public void set(int index, JsonEngine.Element o) { if(o == null){ element.set(index, NullNode.getInstance()); } else { element.set(index, (JsonNode)o.getEngineElement()); } } @Override public void add(Number number) {<FILL_FUNCTION_BODY>} @Override public void add(String str) { element.add(str); } @Override public void add(Boolean bool) { element.add(bool); } @Override public String join(String token) { return StreamSupport.stream(element.spliterator(), false) .map(String::valueOf) .collect(Collectors.joining(token)); } }
if(number instanceof Integer){ element.add((Integer) number); } else if (number instanceof Double){ element.add((Double)number); } else if (number instanceof Long){ element.add((Long)number); } else if (number instanceof BigInteger) { element.add((BigInteger) number); } else if (number instanceof Float){ element.add((Float)number); } else if(number instanceof BigDecimal) { element.add((BigDecimal) number); }
673
133
806
Kong_unirest-java
unirest-java/unirest/src/main/java/kong/unirest/core/FileResponse.java
FileResponse
getContent
class FileResponse extends BaseResponse<File> { private File body; public FileResponse(RawResponse r, String path, ProgressMonitor downloadMonitor, CopyOption... copyOptions) { super(r); try { Path target = Paths.get(path); InputStream content = getContent(r, downloadMonitor, target); Files.copy(content, target, copyOptions); body = target.toFile(); } catch (Exception e) { throw new UnrecoverableException(e); } } private InputStream getContent(RawResponse r, ProgressMonitor downloadMonitor, Path target) {<FILL_FUNCTION_BODY>} @Override public File getBody() { return body; } @Override protected String getRawBody() { return null; } }
if(downloadMonitor == null){ return r.getContent(); } return new MonitoringInputStream(r.getContent(), downloadMonitor, target, r);
209
43
252
spring-cloud_spring-cloud-gateway
spring-cloud-gateway/spring-cloud-gateway-server/src/main/java/org/springframework/cloud/gateway/support/tagsprovider/GatewayHttpTagsProvider.java
GatewayHttpTagsProvider
apply
class GatewayHttpTagsProvider implements GatewayTagsProvider { @Override public Tags apply(ServerWebExchange exchange) {<FILL_FUNCTION_BODY>} }
String outcome = "CUSTOM"; String status = "CUSTOM"; String httpStatusCodeStr = "NA"; String httpMethod = exchange.getRequest().getMethod().name(); // a non standard HTTPS status could be used. Let's be defensive here // it needs to be checked for first, otherwise the delegate response // who's status DIDN'T change, will be used if (exchange.getResponse() instanceof AbstractServerHttpResponse) { Integer statusInt = ((AbstractServerHttpResponse) exchange.getResponse()).getRawStatusCode(); if (statusInt != null) { status = String.valueOf(statusInt); httpStatusCodeStr = status; HttpStatus resolved = HttpStatus.resolve(statusInt); if (resolved != null) { // this is not a CUSTOM status, so use series here. outcome = resolved.series().name(); status = resolved.name(); } } } else { HttpStatusCode statusCode = exchange.getResponse().getStatusCode(); if (statusCode != null) { httpStatusCodeStr = String.valueOf(statusCode.value()); if (statusCode instanceof HttpStatus) { HttpStatus httpStatus = (HttpStatus) statusCode; outcome = httpStatus.series().name(); status = httpStatus.name(); } } } return Tags.of("outcome", outcome, "status", status, "httpStatusCode", httpStatusCodeStr, "httpMethod", httpMethod);
45
398
443
jeecgboot_jeecg-boot
jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/message/handle/impl/SystemSendMsgHandle.java
SystemSendMsgHandle
doSend
class SystemSendMsgHandle implements ISendMsgHandle { public static final String FROM_USER="system"; @Resource private SysAnnouncementMapper sysAnnouncementMapper; @Resource private SysUserMapper userMapper; @Resource private SysAnnouncementSendMapper sysAnnouncementSendMapper; @Resource private WebSocket webSocket; /** * 该方法会发送3种消息:系统消息、企业微信 钉钉 * @param esReceiver 发送人 * @param esTitle 标题 * @param esContent 内容 */ @Override public void sendMsg(String esReceiver, String esTitle, String esContent) { if(oConvertUtils.isEmpty(esReceiver)){ throw new JeecgBootException("被发送人不能为空"); } ISysBaseAPI sysBaseApi = SpringContextUtils.getBean(ISysBaseAPI.class); MessageDTO messageDTO = new MessageDTO(FROM_USER,esReceiver,esTitle,esContent); sysBaseApi.sendSysAnnouncement(messageDTO); } /** * 仅发送系统消息 * @param messageDTO */ @Override public void sendMessage(MessageDTO messageDTO) { //原方法不支持 sysBaseApi.sendSysAnnouncement(messageDTO); 有企业微信消息逻辑, String title = messageDTO.getTitle(); String content = messageDTO.getContent(); String fromUser = messageDTO.getFromUser(); Map<String,Object> data = messageDTO.getData(); String[] arr = messageDTO.getToUser().split(","); for(String username: arr){ doSend(title, content, fromUser, username, data); } } private void doSend(String title, String msgContent, String fromUser, String toUser, Map<String, Object> data){<FILL_FUNCTION_BODY>} }
SysAnnouncement announcement = new SysAnnouncement(); if(data!=null){ //摘要信息 Object msgAbstract = data.get(CommonConstant.NOTICE_MSG_SUMMARY); if(msgAbstract!=null){ announcement.setMsgAbstract(msgAbstract.toString()); } // 任务节点ID Object taskId = data.get(CommonConstant.NOTICE_MSG_BUS_ID); if(taskId!=null){ announcement.setBusId(taskId.toString()); announcement.setBusType(Vue3MessageHrefEnum.BPM_TASK.getBusType()); } // 流程内消息节点 发消息会传一个busType Object busType = data.get(CommonConstant.NOTICE_MSG_BUS_TYPE); if(busType!=null){ announcement.setBusType(busType.toString()); } } announcement.setTitile(title); announcement.setMsgContent(msgContent); announcement.setSender(fromUser); announcement.setPriority(CommonConstant.PRIORITY_M); announcement.setMsgType(CommonConstant.MSG_TYPE_UESR); announcement.setSendStatus(CommonConstant.HAS_SEND); announcement.setSendTime(new Date()); //系统消息 announcement.setMsgCategory("2"); announcement.setDelFlag(String.valueOf(CommonConstant.DEL_FLAG_0)); sysAnnouncementMapper.insert(announcement); // 2.插入用户通告阅读标记表记录 String userId = toUser; String[] userIds = userId.split(","); String anntId = announcement.getId(); for(int i=0;i<userIds.length;i++) { if(oConvertUtils.isNotEmpty(userIds[i])) { SysUser sysUser = userMapper.getUserByName(userIds[i]); if(sysUser==null) { continue; } SysAnnouncementSend announcementSend = new SysAnnouncementSend(); announcementSend.setAnntId(anntId); announcementSend.setUserId(sysUser.getId()); announcementSend.setReadFlag(CommonConstant.NO_READ_FLAG); sysAnnouncementSendMapper.insert(announcementSend); JSONObject obj = new JSONObject(); obj.put(WebsocketConst.MSG_CMD, WebsocketConst.CMD_USER); obj.put(WebsocketConst.MSG_USER_ID, sysUser.getId()); obj.put(WebsocketConst.MSG_ID, announcement.getId()); obj.put(WebsocketConst.MSG_TXT, announcement.getTitile()); webSocket.sendMessage(sysUser.getId(), obj.toJSONString()); } }
513
723
1,236
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/reader/ReaderNode.java
ReaderNode
toString
class ReaderNode extends ReaderElement { private final double lat; private final double lon; public ReaderNode(long id, double lat, double lon) { super(id, Type.NODE); this.lat = lat; this.lon = lon; } public ReaderNode(long id, double lat, double lon, Map<String, Object> tags) { super(id, Type.NODE, tags); this.lat = lat; this.lon = lon; } public double getLat() { return lat; } public double getLon() { return lon; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
StringBuilder txt = new StringBuilder(); txt.append("Node: "); txt.append(getId()); txt.append(" lat="); txt.append(getLat()); txt.append(" lon="); txt.append(getLon()); if (hasTags()) { txt.append("\n"); txt.append(tagsToString()); } return txt.toString();
186
102
288
/** * Base class for all network objects <p> * @author Nop * @author Peter */ public abstract class ReaderElement { public enum Type { NODE, WAY, RELATION, FILEHEADER} private final long id; private final Type type; private final Map<String,Object> properties; protected ReaderElement( long id, Type type); protected ReaderElement( long id, Type type, Map<String,Object> properties); public long getId(); protected String tagsToString(); public Map<String,Object> getTags(); public void setTags( Map<String,Object> newTags); public boolean hasTags(); public String getTag( String name); @SuppressWarnings("unchecked") public <T>T getTag( String key, T defaultValue); public void setTag( String name, Object value); /** * Check that the object has a given tag with a given value. */ public boolean hasTag( String key, Object value); /** * Check that a given tag has one of the specified values. If no values are given, just checks for presence of the tag */ public boolean hasTag( String key, String... values); /** * Check that a given tag has one of the specified values. */ public final boolean hasTag( String key, Collection<String> values); /** * Check a number of tags in the given order for any of the given values. */ public boolean hasTag( List<String> keyList, Collection<String> values); /** * Check a number of tags in the given order if their value is equal to the specified value. */ public boolean hasTag( List<String> keyList, Object value); /** * Returns the first existing value of the specified list of keys where the order is important. * @return an empty string if nothing found */ public String getFirstValue( List<String> searchedTags); /** * @return -1 if not found */ public int getFirstIndex( List<String> searchedTags); public void removeTag( String name); public void clearTags(); public Type getType(); @Override public String toString(); }
elunez_eladmin
eladmin/eladmin-logging/src/main/java/me/zhengjie/aspect/LogAspect.java
LogAspect
logAfterThrowing
class LogAspect { private final SysLogService sysLogService; ThreadLocal<Long> currentTime = new ThreadLocal<>(); public LogAspect(SysLogService sysLogService) { this.sysLogService = sysLogService; } /** * 配置切入点 */ @Pointcut("@annotation(me.zhengjie.annotation.Log)") public void logPointcut() { // 该方法无方法体,主要为了让同类中其他方法使用此切入点 } /** * 配置环绕通知,使用在方法logPointcut()上注册的切入点 * * @param joinPoint join point for advice */ @Around("logPointcut()") public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable { Object result; currentTime.set(System.currentTimeMillis()); result = joinPoint.proceed(); SysLog sysLog = new SysLog("INFO",System.currentTimeMillis() - currentTime.get()); currentTime.remove(); HttpServletRequest request = RequestHolder.getHttpServletRequest(); sysLogService.save(getUsername(), StringUtils.getBrowser(request), StringUtils.getIp(request),joinPoint, sysLog); return result; } /** * 配置异常通知 * * @param joinPoint join point for advice * @param e exception */ @AfterThrowing(pointcut = "logPointcut()", throwing = "e") public void logAfterThrowing(JoinPoint joinPoint, Throwable e) {<FILL_FUNCTION_BODY>} public String getUsername() { try { return SecurityUtils.getCurrentUsername(); }catch (Exception e){ return ""; } } }
SysLog sysLog = new SysLog("ERROR",System.currentTimeMillis() - currentTime.get()); currentTime.remove(); sysLog.setExceptionDetail(ThrowableUtil.getStackTrace(e).getBytes()); HttpServletRequest request = RequestHolder.getHttpServletRequest(); sysLogService.save(getUsername(), StringUtils.getBrowser(request), StringUtils.getIp(request), (ProceedingJoinPoint)joinPoint, sysLog);
469
117
586
obsidiandynamics_kafdrop
kafdrop/src/main/java/kafdrop/config/InterceptorConfiguration.java
ProfileHandlerInterceptor
postHandle
class ProfileHandlerInterceptor implements AsyncHandlerInterceptor { @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {<FILL_FUNCTION_BODY>} }
final var activeProfiles = environment.getActiveProfiles(); if (modelAndView != null && activeProfiles != null && activeProfiles.length > 0) { modelAndView.addObject("profile", String.join(",", activeProfiles)); }
64
69
133
spring-cloud_spring-cloud-gateway
spring-cloud-gateway/spring-cloud-gateway-server/src/main/java/org/springframework/cloud/gateway/filter/factory/RequestSizeGatewayFilterFactory.java
RequestSizeGatewayFilterFactory
getReadableByteCount
class RequestSizeGatewayFilterFactory extends AbstractGatewayFilterFactory<RequestSizeGatewayFilterFactory.RequestSizeConfig> { private static String PREFIX = "kMGTPE"; private static String ERROR = "Request size is larger than permissible limit." + " Request size is %s where permissible limit is %s"; public RequestSizeGatewayFilterFactory() { super(RequestSizeGatewayFilterFactory.RequestSizeConfig.class); } private static String getErrorMessage(Long currentRequestSize, Long maxSize) { return String.format(ERROR, getReadableByteCount(currentRequestSize), getReadableByteCount(maxSize)); } private static String getReadableByteCount(long bytes) {<FILL_FUNCTION_BODY>} @Override public GatewayFilter apply(RequestSizeGatewayFilterFactory.RequestSizeConfig requestSizeConfig) { requestSizeConfig.validate(); return new GatewayFilter() { @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { ServerHttpRequest request = exchange.getRequest(); String contentLength = request.getHeaders().getFirst("content-length"); if (!ObjectUtils.isEmpty(contentLength)) { Long currentRequestSize = Long.valueOf(contentLength); if (currentRequestSize > requestSizeConfig.getMaxSize().toBytes()) { exchange.getResponse().setStatusCode(HttpStatus.PAYLOAD_TOO_LARGE); if (!exchange.getResponse().isCommitted()) { exchange.getResponse().getHeaders().add("errorMessage", getErrorMessage(currentRequestSize, requestSizeConfig.getMaxSize().toBytes())); } return exchange.getResponse().setComplete(); } } return chain.filter(exchange); } @Override public String toString() { return filterToStringCreator(RequestSizeGatewayFilterFactory.this) .append("max", requestSizeConfig.getMaxSize()).toString(); } }; } public static class RequestSizeConfig { // TODO: use boot data size type private DataSize maxSize = DataSize.ofBytes(5000000L); public DataSize getMaxSize() { return maxSize; } public RequestSizeGatewayFilterFactory.RequestSizeConfig setMaxSize(DataSize maxSize) { this.maxSize = maxSize; return this; } // TODO: use validator annotation public void validate() { Assert.notNull(this.maxSize, "maxSize may not be null"); Assert.isTrue(this.maxSize.toBytes() > 0, "maxSize must be greater than 0"); } } }
int unit = 1000; if (bytes < unit) { return bytes + " B"; } int exp = (int) (Math.log(bytes) / Math.log(unit)); String pre = Character.toString(PREFIX.charAt(exp - 1)); return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre);
697
101
798
docker-java_docker-java
docker-java/docker-java-core/src/main/java/com/github/dockerjava/core/exec/StartContainerCmdExec.java
StartContainerCmdExec
execute
class StartContainerCmdExec extends AbstrSyncDockerCmdExec<StartContainerCmd, Void> implements StartContainerCmd.Exec { private static final Logger LOGGER = LoggerFactory.getLogger(StartContainerCmdExec.class); public StartContainerCmdExec(WebTarget baseResource, DockerClientConfig dockerClientConfig) { super(baseResource, dockerClientConfig); } @Override protected Void execute(StartContainerCmd command) {<FILL_FUNCTION_BODY>} }
WebTarget webResource = getBaseResource().path("/containers/{id}/start").resolveTemplate("id", command.getContainerId()); LOGGER.trace("POST: {}", webResource); try { webResource.request() .accept(MediaType.APPLICATION_JSON) .post(null) .close(); } catch (IOException e) { throw new RuntimeException(e); } return null;
126
115
241
javamelody_javamelody
javamelody/javamelody-core/src/main/java/net/bull/javamelody/internal/publish/MetricsPublisher.java
MetricsPublisher
getMetricsPublishers
class MetricsPublisher { public static List<MetricsPublisher> getMetricsPublishers( List<JavaInformations> javaInformationsList) {<FILL_FUNCTION_BODY>} private static List<MetricsPublisher> getMetricsPublishers(String contextPath, String hosts) { final List<MetricsPublisher> metricsPublishers = new ArrayList<>(); final Graphite graphite = Graphite.getInstance(contextPath, hosts); final Statsd statsd = Statsd.getInstance(contextPath, hosts); final CloudWatch cloudWatch = CloudWatch.getInstance(contextPath, hosts); final InfluxDB influxDb = InfluxDB.getInstance(contextPath, hosts); final Datadog datadog = Datadog.getInstance(contextPath, hosts); if (graphite != null) { metricsPublishers.add(graphite); } if (statsd != null) { metricsPublishers.add(statsd); } if (cloudWatch != null) { metricsPublishers.add(cloudWatch); } if (influxDb != null) { metricsPublishers.add(influxDb); } if (datadog != null) { metricsPublishers.add(datadog); } if (metricsPublishers.isEmpty()) { return Collections.emptyList(); } return metricsPublishers; } public abstract void addValue(String metric, double value) throws IOException; public abstract void send() throws IOException; public abstract void stop(); }
assert javaInformationsList != null && !javaInformationsList.isEmpty(); final StringBuilder sb = new StringBuilder(); for (final JavaInformations javaInformations : javaInformationsList) { if (sb.length() != 0) { sb.append('_'); } sb.append(javaInformations.getHost().replaceFirst("@.*", "")); } String contextPath = Parameter.APPLICATION_NAME.getValue(); if (contextPath == null) { contextPath = javaInformationsList.get(0).getContextPath(); } if (contextPath == null) { // for NodesCollector in Jenkins, contextPath is null contextPath = "NA"; } else if (contextPath.isEmpty()) { // for CloudWatch, InfluxDB, Datadog, a tag/dimension is not supposed to be empty contextPath = "/"; } final String hosts = sb.toString(); return getMetricsPublishers(contextPath, hosts);
404
267
671
YunaiV_ruoyi-vue-pro
ruoyi-vue-pro/yudao-framework/yudao-common/src/main/java/cn/iocoder/yudao/framework/common/util/object/BeanUtils.java
BeanUtils
toBean
class BeanUtils { public static <T> T toBean(Object source, Class<T> targetClass) { return BeanUtil.toBean(source, targetClass); } public static <T> T toBean(Object source, Class<T> targetClass, Consumer<T> peek) { T target = toBean(source, targetClass); if (target != null) { peek.accept(target); } return target; } public static <S, T> List<T> toBean(List<S> source, Class<T> targetType) {<FILL_FUNCTION_BODY>} public static <S, T> List<T> toBean(List<S> source, Class<T> targetType, Consumer<T> peek) { List<T> list = toBean(source, targetType); if (list != null) { list.forEach(peek); } return list; } public static <S, T> PageResult<T> toBean(PageResult<S> source, Class<T> targetType) { return toBean(source, targetType, null); } public static <S, T> PageResult<T> toBean(PageResult<S> source, Class<T> targetType, Consumer<T> peek) { if (source == null) { return null; } List<T> list = toBean(source.getList(), targetType); if (peek != null) { list.forEach(peek); } return new PageResult<>(list, source.getTotal()); } }
if (source == null) { return null; } return CollectionUtils.convertList(source, s -> toBean(s, targetType));
419
42
461
elunez_eladmin
eladmin/eladmin-system/src/main/java/me/zhengjie/modules/system/service/impl/DictDetailServiceImpl.java
DictDetailServiceImpl
update
class DictDetailServiceImpl implements DictDetailService { private final DictRepository dictRepository; private final DictDetailRepository dictDetailRepository; private final DictDetailMapper dictDetailMapper; private final RedisUtils redisUtils; @Override public PageResult<DictDetailDto> queryAll(DictDetailQueryCriteria criteria, Pageable pageable) { Page<DictDetail> page = dictDetailRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable); return PageUtil.toPage(page.map(dictDetailMapper::toDto)); } @Override @Transactional(rollbackFor = Exception.class) public void create(DictDetail resources) { dictDetailRepository.save(resources); // 清理缓存 delCaches(resources); } @Override @Transactional(rollbackFor = Exception.class) public void update(DictDetail resources) {<FILL_FUNCTION_BODY>} @Override @Cacheable(key = "'name:' + #p0") public List<DictDetailDto> getDictByName(String name) { return dictDetailMapper.toDto(dictDetailRepository.findByDictName(name)); } @Override @Transactional(rollbackFor = Exception.class) public void delete(Long id) { DictDetail dictDetail = dictDetailRepository.findById(id).orElseGet(DictDetail::new); // 清理缓存 delCaches(dictDetail); dictDetailRepository.deleteById(id); } public void delCaches(DictDetail dictDetail){ Dict dict = dictRepository.findById(dictDetail.getDict().getId()).orElseGet(Dict::new); redisUtils.del(CacheKey.DICT_NAME + dict.getName()); } }
DictDetail dictDetail = dictDetailRepository.findById(resources.getId()).orElseGet(DictDetail::new); ValidationUtil.isNull( dictDetail.getId(),"DictDetail","id",resources.getId()); resources.setId(dictDetail.getId()); dictDetailRepository.save(resources); // 清理缓存 delCaches(resources);
491
95
586
PlayEdu_PlayEdu
PlayEdu/playedu-common/src/main/java/xyz/playedu/common/service/impl/LdapUserServiceImpl.java
LdapUserServiceImpl
store
class LdapUserServiceImpl extends ServiceImpl<LdapUserMapper, LdapUser> implements LdapUserService { @Override public LdapUser findByUUID(String id) { return getOne(query().getWrapper().eq("uuid", id)); } @Override public LdapUser store(LdapTransformUser ldapTransformUser) {<FILL_FUNCTION_BODY>} @Override public void updateUserId(Integer id, Integer userId) { LdapUser user = new LdapUser(); user.setId(id); user.setUserId(userId); updateById(user); } @Override public void updateCN(Integer id, String cn) { LdapUser user = new LdapUser(); user.setId(id); user.setCn(cn == null ? "" : cn); updateById(user); } @Override public void updateOU(Integer id, String newOU) { LdapUser user = new LdapUser(); user.setId(id); user.setOu(newOU == null ? "" : newOU); updateById(user); } @Override public void updateEmail(Integer id, String email) { LdapUser user = new LdapUser(); user.setId(id); user.setEmail(email == null ? "" : email); updateById(user); } @Override public void updateUid(Integer id, String uid) { LdapUser user = new LdapUser(); user.setId(id); user.setUid(uid); updateById(user); } }
LdapUser user = new LdapUser(); user.setUuid(ldapTransformUser.getId()); user.setCn(ldapTransformUser.getCn()); user.setDn(ldapTransformUser.getDn()); user.setUid(ldapTransformUser.getUid()); // ou user.setOu(String.join(",", ldapTransformUser.getOu())); // 邮箱可能不存在 if (StringUtil.isNotEmpty(ldapTransformUser.getEmail())) { user.setEmail(ldapTransformUser.getEmail()); } user.setCreatedAt(new Date()); user.setUpdatedAt(new Date()); save(user); return user;
449
193
642
logfellow_logstash-logback-encoder
logstash-logback-encoder/src/main/java/net/logstash/logback/appender/listener/FailureSummaryLoggingAppenderListener.java
FailureSummaryLoggingAppenderListener
handleFailureSummary
class FailureSummaryLoggingAppenderListener<Event extends DeferredProcessingAware> extends FailureSummaryAppenderListener<Event> { private volatile Logger logger = LoggerFactory.getLogger(FailureSummaryLoggingAppenderListener.class); /** * Logs a message with the details from the given {@link FailureSummaryAppenderListener.FailureSummary} * with the given callback type. * * @param failureSummary contains summary details of all the consecutive failures * @param callbackType the type of failure (append/send/connect) */ @Override protected void handleFailureSummary(FailureSummary failureSummary, CallbackType callbackType) {<FILL_FUNCTION_BODY>} public String getLoggerName() { return logger.getName(); } /** * Sets the slf4j logger name to which to log. * Defaults to the fully qualified name of {@link FailureSummaryLoggingAppenderListener}. * * @param loggerName the name of the logger to which to log. */ public void setLoggerName(String loggerName) { logger = LoggerFactory.getLogger(Objects.requireNonNull(loggerName)); } }
if (logger.isWarnEnabled()) { if (failureSummary.getFirstFailure() != failureSummary.getMostRecentFailure()) { failureSummary.getMostRecentFailure().addSuppressed(failureSummary.getFirstFailure()); } logger.warn("{} {} failures since {} for {}.", StructuredArguments.value("failEventCount", failureSummary.getConsecutiveFailures()), StructuredArguments.value("failType", callbackType.name().toLowerCase()), StructuredArguments.value("failStartTime", DateTimeFormatter.ISO_OFFSET_DATE_TIME.withZone(TimeZone.getDefault().toZoneId()).format(Instant.ofEpochMilli(failureSummary.getFirstFailureTime()))), StructuredArguments.value("failDuration", Duration.ofMillis(System.currentTimeMillis() - failureSummary.getFirstFailureTime()).toString()), failureSummary.getMostRecentFailure()); }
297
227
524
PlexPt_chatgpt-java
chatgpt-java/src/main/java/com/plexpt/chatgpt/listener/AbstractStreamListener.java
AbstractStreamListener
onEvent
class AbstractStreamListener extends EventSourceListener { protected String lastMessage = ""; /** * Called when all new message are received. * * @param message the new message */ @Setter @Getter protected Consumer<String> onComplate = s -> { }; /** * Called when a new message is received. * 收到消息 单个字 * * @param message the new message */ public abstract void onMsg(String message); /** * Called when an error occurs. * 出错时调用 * * @param throwable the throwable that caused the error * @param response the response associated with the error, if any */ public abstract void onError(Throwable throwable, String response); @Override public void onOpen(EventSource eventSource, Response response) { // do nothing } @Override public void onClosed(EventSource eventSource) { // do nothing } @Override public void onEvent(EventSource eventSource, String id, String type, String data) {<FILL_FUNCTION_BODY>} @SneakyThrows @Override public void onFailure(EventSource eventSource, Throwable throwable, Response response) { try { log.error("Stream connection error: {}", throwable); String responseText = ""; if (Objects.nonNull(response)) { responseText = response.body().string(); } log.error("response:{}", responseText); String forbiddenText = "Your access was terminated due to violation of our policies"; if (StrUtil.contains(responseText, forbiddenText)) { log.error("Chat session has been terminated due to policy violation"); log.error("检测到号被封了"); } String overloadedText = "That model is currently overloaded with other requests."; if (StrUtil.contains(responseText, overloadedText)) { log.error("检测到官方超载了,赶紧优化你的代码,做重试吧"); } this.onError(throwable, responseText); } catch (Exception e) { log.warn("onFailure error:{}", e); // do nothing } finally { eventSource.cancel(); } } }
if (data.equals("[DONE]")) { onComplate.accept(lastMessage); return; } ChatCompletionResponse response = JSON.parseObject(data, ChatCompletionResponse.class); // 读取Json List<ChatChoice> choices = response.getChoices(); if (choices == null || choices.isEmpty()) { return; } Message delta = choices.get(0).getDelta(); String text = delta.getContent(); if (text != null) { lastMessage += text; onMsg(text); }
612
158
770
eirslett_frontend-maven-plugin
frontend-maven-plugin/frontend-plugin-core/src/main/java/com/github/eirslett/maven/plugins/frontend/lib/NodeTaskExecutor.java
NodeTaskExecutor
maskPassword
class NodeTaskExecutor { private static final String DS = "//"; private static final String AT = "@"; private final Logger logger; private final String taskName; private String taskLocation; private final ArgumentsParser argumentsParser; private final NodeExecutorConfig config; private final Map<String, String> proxy; public NodeTaskExecutor(NodeExecutorConfig config, String taskLocation) { this(config, taskLocation, Collections.<String>emptyList()); } public NodeTaskExecutor(NodeExecutorConfig config, String taskName, String taskLocation) { this(config, taskName, taskLocation, Collections.<String>emptyList()); } public NodeTaskExecutor(NodeExecutorConfig config, String taskLocation, List<String> additionalArguments) { this(config, getTaskNameFromLocation(taskLocation), taskLocation, additionalArguments); } public NodeTaskExecutor(NodeExecutorConfig config, String taskName, String taskLocation, List<String> additionalArguments) { this(config, taskName, taskLocation, additionalArguments, Collections.<String, String>emptyMap()); } public NodeTaskExecutor(NodeExecutorConfig config, String taskName, String taskLocation, List<String> additionalArguments, Map<String, String> proxy) { this.logger = LoggerFactory.getLogger(getClass()); this.config = config; this.taskName = taskName; this.taskLocation = taskLocation; this.argumentsParser = new ArgumentsParser(additionalArguments); this.proxy = proxy; } private static String getTaskNameFromLocation(String taskLocation) { return taskLocation.replaceAll("^.*/([^/]+)(?:\\.js)?$","$1"); } public final void execute(String args, Map<String, String> environment) throws TaskRunnerException { final String absoluteTaskLocation = getAbsoluteTaskLocation(); final List<String> arguments = getArguments(args); logger.info("Running " + taskToString(taskName, arguments) + " in " + config.getWorkingDirectory()); try { Map<String, String> internalEnvironment = new HashMap<>(); if (environment != null && !environment.isEmpty()) { internalEnvironment.putAll(environment); } if (!proxy.isEmpty()) { internalEnvironment.putAll(proxy); } final int result = new NodeExecutor(config, prepend(absoluteTaskLocation, arguments), internalEnvironment ).executeAndRedirectOutput(logger); if (result != 0) { throw new TaskRunnerException(taskToString(taskName, arguments) + " failed. (error code " + result + ")"); } } catch (ProcessExecutionException e) { throw new TaskRunnerException(taskToString(taskName, arguments) + " failed.", e); } } private String getAbsoluteTaskLocation() { String location = normalize(taskLocation); if (Utils.isRelative(taskLocation)) { File taskFile = new File(config.getWorkingDirectory(), location); if (!taskFile.exists()) { taskFile = new File(config.getInstallDirectory(), location); } location = taskFile.getAbsolutePath(); } return location; } private List<String> getArguments(String args) { return argumentsParser.parse(args); } private static String taskToString(String taskName, List<String> arguments) { List<String> clonedArguments = new ArrayList<String>(arguments); for (int i = 0; i < clonedArguments.size(); i++) { final String s = clonedArguments.get(i); final boolean maskMavenProxyPassword = s.contains("proxy="); if (maskMavenProxyPassword) { final String bestEffortMaskedPassword = maskPassword(s); clonedArguments.set(i, bestEffortMaskedPassword); } } return "'" + taskName + " " + implode(" ", clonedArguments) + "'"; } private static String maskPassword(String proxyString) {<FILL_FUNCTION_BODY>} public void setTaskLocation(String taskLocation) { this.taskLocation = taskLocation; } }
String retVal = proxyString; if (proxyString != null && !"".equals(proxyString.trim())) { boolean hasSchemeDefined = proxyString.contains("http:") || proxyString.contains("https:"); boolean hasProtocolDefined = proxyString.contains(DS); boolean hasAtCharacterDefined = proxyString.contains(AT); if (hasSchemeDefined && hasProtocolDefined && hasAtCharacterDefined) { final int firstDoubleSlashIndex = proxyString.indexOf(DS); final int lastAtCharIndex = proxyString.lastIndexOf(AT); boolean hasPossibleURIUserInfo = firstDoubleSlashIndex < lastAtCharIndex; if (hasPossibleURIUserInfo) { final String userInfo = proxyString.substring(firstDoubleSlashIndex + DS.length(), lastAtCharIndex); final String[] userParts = userInfo.split(":"); if (userParts.length > 0) { final int startOfUserNameIndex = firstDoubleSlashIndex + DS.length(); final int firstColonInUsernameOrEndOfUserNameIndex = startOfUserNameIndex + userParts[0].length(); final String leftPart = proxyString.substring(0, firstColonInUsernameOrEndOfUserNameIndex); final String rightPart = proxyString.substring(lastAtCharIndex); retVal = leftPart + ":***" + rightPart; } } } } return retVal;
1,058
368
1,426
PlexPt_chatgpt-java
chatgpt-java/src/main/java/com/plexpt/chatgpt/util/ChatContextHolder.java
ChatContextHolder
add
class ChatContextHolder { private static Map<String, List<Message>> context = new HashMap<>(); /** * 获取对话历史 * * @param id * @return */ public static List<Message> get(String id) { List<Message> messages = context.get(id); if (messages == null) { messages = new ArrayList<>(); context.put(id, messages); } return messages; } /** * 添加对话 * * @param id * @return */ public static void add(String id, String msg) { Message message = Message.builder().content(msg).build(); add(id, message); } /** * 添加对话 * * @param id * @return */ public static void add(String id, Message message) {<FILL_FUNCTION_BODY>} /** * 清除对话 * @param id */ public static void remove(String id) { context.remove(id); } }
List<Message> messages = context.get(id); if (messages == null) { messages = new ArrayList<>(); context.put(id, messages); } messages.add(message);
293
55
348
jeecgboot_jeecg-boot
jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/message/controller/SysMessageController.java
SysMessageController
queryPageList
class SysMessageController extends JeecgController<SysMessage, ISysMessageService> { @Autowired private ISysMessageService sysMessageService; /** * 分页列表查询 * * @param sysMessage * @param pageNo * @param pageSize * @param req * @return */ @GetMapping(value = "/list") public Result<?> queryPageList(SysMessage sysMessage, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo, @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {<FILL_FUNCTION_BODY>} /** * 添加 * * @param sysMessage * @return */ @PostMapping(value = "/add") public Result<?> add(@RequestBody SysMessage sysMessage) { sysMessageService.save(sysMessage); return Result.ok("添加成功!"); } /** * 编辑 * * @param sysMessage * @return */ @PutMapping(value = "/edit") public Result<?> edit(@RequestBody SysMessage sysMessage) { sysMessageService.updateById(sysMessage); return Result.ok("修改成功!"); } /** * 通过id删除 * * @param id * @return */ @DeleteMapping(value = "/delete") public Result<?> delete(@RequestParam(name = "id", required = true) String id) { sysMessageService.removeById(id); return Result.ok("删除成功!"); } /** * 批量删除 * * @param ids * @return */ @DeleteMapping(value = "/deleteBatch") public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) { this.sysMessageService.removeByIds(Arrays.asList(ids.split(","))); return Result.ok("批量删除成功!"); } /** * 通过id查询 * * @param id * @return */ @GetMapping(value = "/queryById") public Result<?> queryById(@RequestParam(name = "id", required = true) String id) { SysMessage sysMessage = sysMessageService.getById(id); return Result.ok(sysMessage); } /** * 导出excel * * @param request */ @GetMapping(value = "/exportXls") public ModelAndView exportXls(HttpServletRequest request, SysMessage sysMessage) { return super.exportXls(request,sysMessage,SysMessage.class, "推送消息模板"); } /** * excel导入 * * @param request * @param response * @return */ @PostMapping(value = "/importExcel") public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) { return super.importExcel(request, response, SysMessage.class); } }
QueryWrapper<SysMessage> queryWrapper = QueryGenerator.initQueryWrapper(sysMessage, req.getParameterMap()); Page<SysMessage> page = new Page<SysMessage>(pageNo, pageSize); IPage<SysMessage> pageList = sysMessageService.page(page, queryWrapper); return Result.ok(pageList);
804
91
895
Kong_unirest-java
unirest-java/unirest-modules-mocks/src/main/java/kong/unirest/core/EqualsBodyMatcher.java
EqualsBodyMatcher
matches
class EqualsBodyMatcher implements BodyMatcher { private final String expected; public EqualsBodyMatcher(String body) { this.expected = body; } @Override public MatchStatus matches(List<String> body) throws AssertionError {<FILL_FUNCTION_BODY>} }
return new MatchStatus(body.size() == 1 && Objects.equals(expected, body.get(0)), expected);
82
32
114