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);
}
|
End of preview. Expand
in Data Studio
No dataset card yet
- Downloads last month
- -