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
parent_context
stringclasses
74 values
parent_class_output
stringlengths
20
1.75k
param_context
stringclasses
89 values
initial_context
stringlengths
1
34.7k
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
memory[index] = (byte) value; memory[index + 1] = (byte) (value >>> 8); memory[index + 2] = (byte) (value >>> 16); memory[index + 3] = (byte) (value >>> 24);
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(); }
if (metaContact != null) { for (Contact contact : metaContact.getContacts()) { OtrContactMenu otrContactMenu = new OtrContactMenu(getContainer(), getParentFactory()); otrContactMenu.setCurrentContact(contact); menu.add(otrContactMenu); } } else { menu.removeAll(); }
/** * A MetaContact is an abstraction used for merging multiple Contacts (most often) belonging to different <tt>ProtocolProvider</tt>s. <p> Instances of a MetaContact are read-only objects that cannot be modified directly but only through the corresponding MetaContactListService. </p> * @author Emil Ivov * @author Lubomir Marinov */ public interface MetaContact extends Comparable<MetaContact> { /** * Returns the default protocol specific <tt>Contact</tt> to use when communicating with this <tt>MetaContact</tt>. * @return the default <tt>Contact</tt> to use when communicating withthis <tt>MetaContact</tt> */ public Contact getDefaultContact(); /** * Returns the default protocol specific <tt>Contact</tt> to use with this <tt>MetaContact</tt> for a precise operation (IM, call, ...). * @param operationSet the operation for which the default contact is needed * @return the default contact for the specified operation. */ public Contact getDefaultContact( Class<? extends OperationSet> operationSet); /** * Returns a <tt>java.util.Iterator</tt> with all protocol specific <tt>Contacts</tt> encapsulated by this <tt>MetaContact</tt>. <p> Note to implementors: In order to prevent problems with concurrency, the <tt>Iterator</tt> returned by this method should not be over the actual list of contacts but rather over a copy of that list. <p> * @return a <tt>java.util.Iterator</tt> containing all protocol specific<tt>Contact</tt>s that were registered as subcontacts for this <tt>MetaContact</tt> */ public Iterator<Contact> getContacts(); /** * Returns a contact encapsulated by this meta contact, having the specified contactAddress and coming from the indicated ownerProvider. * @param contactAddress the address of the contact who we're looking for. * @param ownerProvider a reference to the ProtocolProviderService thatthe contact we're looking for belongs to. * @return a reference to a <tt>Contact</tt>, encapsulated by thisMetaContact, carrying the specified address and originating from the specified ownerProvider or null if no such contact exists.. */ public Contact getContact( String contactAddress, ProtocolProviderService ownerProvider); /** * Returns <tt>true</tt> if the given <tt>protocolContact</tt> is contained in this <tt>MetaContact</tt>, otherwise - returns <tt>false</tt>. * @param protocolContact the <tt>Contact</tt> we're looking for * @return <tt>true</tt> if the given <tt>protocolContact</tt> is containedin this <tt>MetaContact</tt>, otherwise - returns <tt>false</tt> */ public boolean containsContact( Contact protocolContact); /** * Returns the number of protocol speciic <tt>Contact</tt>s that this <tt>MetaContact</tt> contains. * @return an int indicating the number of protocol specific contacts mergedin this <tt>MetaContact</tt> */ public int getContactCount(); /** * Returns all protocol specific Contacts, encapsulated by this MetaContact and coming from the indicated ProtocolProviderService. If none of the contacts encapsulated by this MetaContact is originating from the specified provider then an empty iterator is returned. <p> Note to implementors: In order to prevent problems with concurrency, the <tt>Iterator</tt> returned by this method should not be over the actual list of contacts but rather over a copy of that list. <p> * @param provider a reference to the <tt>ProtocolProviderService</tt>whose contacts we'd like to get. * @return an <tt>Iterator</tt> over all contacts encapsulated in this<tt>MetaContact</tt> and originating from the specified provider. */ public Iterator<Contact> getContactsForProvider( ProtocolProviderService provider); /** * Returns all protocol specific Contacts, encapsulated by this MetaContact and supporting the given <tt>opSetClass</tt>. If none of the contacts encapsulated by this MetaContact is supporting the specified <tt>OperationSet</tt> class then an empty list is returned. <p> Note to implementors: In order to prevent problems with concurrency, the <tt>List</tt> returned by this method should not be the actual list of contacts but rather a copy of that list. <p> * @param opSetClass the operation for which the default contact is needed * @return a <tt>List</tt> of all contacts encapsulated in this<tt>MetaContact</tt> and supporting the specified <tt>OperationSet</tt> */ public List<Contact> getContactsForOperationSet( Class<? extends OperationSet> opSetClass); /** * Returns the MetaContactGroup currently containing this meta contact * @return a reference to the MetaContactGroup currently containing thismeta contact. */ public MetaContactGroup getParentMetaContactGroup(); /** * Returns a String identifier (the actual contents is left to implementations) that uniquely represents this <tt>MetaContact</tt> in the containing <tt>MetaContactList</tt> * @return String */ public String getMetaUID(); /** * Returns a characteristic display name that can be used when including this <tt>MetaContact</tt> in user interface. * @return a human readable String that represents this meta contact. */ public String getDisplayName(); /** * Returns the avatar of this contact, that can be used when including this <tt>MetaContact</tt> in user interface. * @return an avatar (e.g. user photo) of this contact. */ public byte[] getAvatar(); /** * Returns the avatar of this contact, that can be used when including this <tt>MetaContact</tt> in user interface. The isLazy parameter would tell the implementation if it could return the locally stored avatar or it should obtain the avatar right from the server. * @param isLazy Indicates if this method should return the locally storedavatar or it should obtain the avatar right from the server. * @return an avatar (e.g. user photo) of this contact. */ public byte[] getAvatar( boolean isLazy); /** * Returns a String representation of this <tt>MetaContact</tt>. * @return a String representation of this <tt>MetaContact</tt>. */ public String toString(); /** * Adds a custom detail to this contact. * @param name name of the detail. * @param value the value of the detail. */ public void addDetail( String name, String value); /** * Remove the given detail. * @param name of the detail to be removed. * @param value value of the detail to be removed. */ public void removeDetail( String name, String value); /** * Remove all details with given name. * @param name of the details to be removed. */ public void removeDetails( String name); /** * Change the detail. * @param name of the detail to be changed. * @param oldValue the old value of the detail. * @param newValue the new value of the detail. */ public void changeDetail( String name, String oldValue, String newValue); /** * Get all details with given name. * @param name the name of the details we are searching. * @return list of string values for the details with the given name. */ public List<String> getDetails( String name); /** * Gets the user data associated with this instance and a specific key. * @param key the key of the user data associated with this instance to beretrieved * @return an <tt>Object</tt> which represents the value associated withthis instance and the specified <tt>key</tt>; <tt>null</tt> if no association with the specified <tt>key</tt> exists in this instance */ public Object getData( Object key); /** * Sets a user-specific association in this instance in the form of a key-value pair. If the specified <tt>key</tt> is already associated in this instance with a value, the existing value is overwritten with the specified <tt>value</tt>. <p> The user-defined association created by this method and stored in this instance is not serialized by this instance and is thus only meant for runtime use. </p> <p> The storage of the user data is implementation-specific and is thus not guaranteed to be optimized for execution time and memory use. </p> * @param key the key to associate in this instance with the specified value * @param value the value to be associated in this instance with thespecified <tt>key</tt> */ public void setData( Object key, Object value); }
/** * 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(); } /** * A MetaContact is an abstraction used for merging multiple Contacts (most often) belonging to different <tt>ProtocolProvider</tt>s. <p> Instances of a MetaContact are read-only objects that cannot be modified directly but only through the corresponding MetaContactListService. </p> * @author Emil Ivov * @author Lubomir Marinov */ public interface MetaContact extends Comparable<MetaContact> { /** * Returns the default protocol specific <tt>Contact</tt> to use when communicating with this <tt>MetaContact</tt>. * @return the default <tt>Contact</tt> to use when communicating withthis <tt>MetaContact</tt> */ public Contact getDefaultContact(); /** * Returns the default protocol specific <tt>Contact</tt> to use with this <tt>MetaContact</tt> for a precise operation (IM, call, ...). * @param operationSet the operation for which the default contact is needed * @return the default contact for the specified operation. */ public Contact getDefaultContact( Class<? extends OperationSet> operationSet); /** * Returns a <tt>java.util.Iterator</tt> with all protocol specific <tt>Contacts</tt> encapsulated by this <tt>MetaContact</tt>. <p> Note to implementors: In order to prevent problems with concurrency, the <tt>Iterator</tt> returned by this method should not be over the actual list of contacts but rather over a copy of that list. <p> * @return a <tt>java.util.Iterator</tt> containing all protocol specific<tt>Contact</tt>s that were registered as subcontacts for this <tt>MetaContact</tt> */ public Iterator<Contact> getContacts(); /** * Returns a contact encapsulated by this meta contact, having the specified contactAddress and coming from the indicated ownerProvider. * @param contactAddress the address of the contact who we're looking for. * @param ownerProvider a reference to the ProtocolProviderService thatthe contact we're looking for belongs to. * @return a reference to a <tt>Contact</tt>, encapsulated by thisMetaContact, carrying the specified address and originating from the specified ownerProvider or null if no such contact exists.. */ public Contact getContact( String contactAddress, ProtocolProviderService ownerProvider); /** * Returns <tt>true</tt> if the given <tt>protocolContact</tt> is contained in this <tt>MetaContact</tt>, otherwise - returns <tt>false</tt>. * @param protocolContact the <tt>Contact</tt> we're looking for * @return <tt>true</tt> if the given <tt>protocolContact</tt> is containedin this <tt>MetaContact</tt>, otherwise - returns <tt>false</tt> */ public boolean containsContact( Contact protocolContact); /** * Returns the number of protocol speciic <tt>Contact</tt>s that this <tt>MetaContact</tt> contains. * @return an int indicating the number of protocol specific contacts mergedin this <tt>MetaContact</tt> */ public int getContactCount(); /** * Returns all protocol specific Contacts, encapsulated by this MetaContact and coming from the indicated ProtocolProviderService. If none of the contacts encapsulated by this MetaContact is originating from the specified provider then an empty iterator is returned. <p> Note to implementors: In order to prevent problems with concurrency, the <tt>Iterator</tt> returned by this method should not be over the actual list of contacts but rather over a copy of that list. <p> * @param provider a reference to the <tt>ProtocolProviderService</tt>whose contacts we'd like to get. * @return an <tt>Iterator</tt> over all contacts encapsulated in this<tt>MetaContact</tt> and originating from the specified provider. */ public Iterator<Contact> getContactsForProvider( ProtocolProviderService provider); /** * Returns all protocol specific Contacts, encapsulated by this MetaContact and supporting the given <tt>opSetClass</tt>. If none of the contacts encapsulated by this MetaContact is supporting the specified <tt>OperationSet</tt> class then an empty list is returned. <p> Note to implementors: In order to prevent problems with concurrency, the <tt>List</tt> returned by this method should not be the actual list of contacts but rather a copy of that list. <p> * @param opSetClass the operation for which the default contact is needed * @return a <tt>List</tt> of all contacts encapsulated in this<tt>MetaContact</tt> and supporting the specified <tt>OperationSet</tt> */ public List<Contact> getContactsForOperationSet( Class<? extends OperationSet> opSetClass); /** * Returns the MetaContactGroup currently containing this meta contact * @return a reference to the MetaContactGroup currently containing thismeta contact. */ public MetaContactGroup getParentMetaContactGroup(); /** * Returns a String identifier (the actual contents is left to implementations) that uniquely represents this <tt>MetaContact</tt> in the containing <tt>MetaContactList</tt> * @return String */ public String getMetaUID(); /** * Returns a characteristic display name that can be used when including this <tt>MetaContact</tt> in user interface. * @return a human readable String that represents this meta contact. */ public String getDisplayName(); /** * Returns the avatar of this contact, that can be used when including this <tt>MetaContact</tt> in user interface. * @return an avatar (e.g. user photo) of this contact. */ public byte[] getAvatar(); /** * Returns the avatar of this contact, that can be used when including this <tt>MetaContact</tt> in user interface. The isLazy parameter would tell the implementation if it could return the locally stored avatar or it should obtain the avatar right from the server. * @param isLazy Indicates if this method should return the locally storedavatar or it should obtain the avatar right from the server. * @return an avatar (e.g. user photo) of this contact. */ public byte[] getAvatar( boolean isLazy); /** * Returns a String representation of this <tt>MetaContact</tt>. * @return a String representation of this <tt>MetaContact</tt>. */ public String toString(); /** * Adds a custom detail to this contact. * @param name name of the detail. * @param value the value of the detail. */ public void addDetail( String name, String value); /** * Remove the given detail. * @param name of the detail to be removed. * @param value value of the detail to be removed. */ public void removeDetail( String name, String value); /** * Remove all details with given name. * @param name of the details to be removed. */ public void removeDetails( String name); /** * Change the detail. * @param name of the detail to be changed. * @param oldValue the old value of the detail. * @param newValue the new value of the detail. */ public void changeDetail( String name, String oldValue, String newValue); /** * Get all details with given name. * @param name the name of the details we are searching. * @return list of string values for the details with the given name. */ public List<String> getDetails( String name); /** * Gets the user data associated with this instance and a specific key. * @param key the key of the user data associated with this instance to beretrieved * @return an <tt>Object</tt> which represents the value associated withthis instance and the specified <tt>key</tt>; <tt>null</tt> if no association with the specified <tt>key</tt> exists in this instance */ public Object getData( Object key); /** * Sets a user-specific association in this instance in the form of a key-value pair. If the specified <tt>key</tt> is already associated in this instance with a value, the existing value is overwritten with the specified <tt>value</tt>. <p> The user-defined association created by this method and stored in this instance is not serialized by this instance and is thus only meant for runtime use. </p> <p> The storage of the user data is implementation-specific and is thus not guaranteed to be optimized for execution time and memory use. </p> * @param key the key to associate in this instance with the specified value * @param value the value to be associated in this instance with thespecified <tt>key</tt> */ public void setData( Object key, Object value); }
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(); }
final String[] deviceParts = deviceStr.split(":"); if (deviceParts.length != 3) { throw new IllegalArgumentException("Invalid device format: " + deviceStr); } final String devicePathInContainer = deviceParts[0]; final String devicePathOnHost = deviceParts[1]; final String deviceCGroupPermissions = deviceParts[2]; if (!validDeviceMode(deviceCGroupPermissions)) { throw new IllegalArgumentException("Invalid device mode: " + deviceCGroupPermissions); } return new Device(deviceCGroupPermissions, devicePathInContainer, devicePathOnHost);
/** * @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
Service service = (Service) value; setText(service.getName()); return this;
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
if (pointcut == null) { pointcut = new AspectJExpressionPointcut(); pointcut.setExpression(expression); } return pointcut;
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); }
WxPayRequest wxPayRequest = (WxPayRequest) request; WxPayAsyncRequest wxPayAsyncRequest = new WxPayAsyncRequest(); wxPayAsyncRequest.setAppid(wxPayConfig.getAppId()); wxPayAsyncRequest.setMchId(wxPayConfig.getMchId()); wxPayAsyncRequest.setNonceStr(wxPayConfig.getNonceStr()); wxPayAsyncRequest.setSign(wxPayConfig.getSign(wxPayAsyncRequest)); wxPayAsyncRequest.setBody(wxPayRequest.getBody()); wxPayAsyncRequest.setOutTradeNo(wxPayRequest.getOrderId()); wxPayAsyncRequest.setTotalFee(wxPayRequest.getTotalFee()); wxPayAsyncRequest.setSpbillCreateIp(wxPayRequest.getSpbillCreateIp()); wxPayAsyncRequest.setTradeType(wxPayRequest.getTradeType()); wxPayAsyncRequest.setNotifyUrl(wxPayRequest.getNotifyUrl()); wxPayAsyncRequest.setLimitPay(wxPayRequest.getLimitPay()); wxPayAsyncRequest.setOpenid(wxPayRequest.getOpenid()); wxPayAsyncRequest.setSceneInfo(wxPayRequest.getSceneInfo()); wxPayAsyncRequest.setDeviceInfo(wxPayRequest.getDeviceInfo()); wxPayAsyncRequest.setAttach(wxPayRequest.getAttach()); wxPayAsyncRequest.setFeeType(wxPayRequest.getFeeType()); wxPayAsyncRequest.setTimeStart(wxPayRequest.getTimeStart()); wxPayAsyncRequest.setTimeExpire(wxPayRequest
/** * 支付时请求参数 */ @Data public class PayRequest { /** * 支付方式. */ private BestPayTypeEnum payTypeEnum; /** * 订单号. */ private String orderId; /** * 订单金额. */ private Double orderAmount; /** * 订单名字. */ private String orderName; /** * 微信openid, 仅微信公众号/小程序支付时需要 */ private String openid; /** * 客户端访问Ip 外部H5支付时必传,需要真实Ip 20191015测试,微信h5支付已不需要真实的ip */ private String spbillCreateIp; /** * 附加内容,发起支付时传入 */ private String attach; /** * 支付后跳转(支付宝PC网站支付) 优先级高于PayConfig.returnUrl */ private String returnUrl; /** * 买家支付宝账号 {@link AliPayTradeCreateRequest.BizContent} */ private String buyerLogonId; /** * 买家的支付宝唯一用户号(2088开头的16位纯数字) {@link AliPayTradeCreateRequest.BizContent} */ private String buyerId; /** * 付款码 */ private String authCode; }
/** * 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); } /** * 支付时请求参数 */ @Data public class PayRequest { /** * 支付方式. */ private BestPayTypeEnum payTypeEnum; /** * 订单号. */ private String orderId; /** * 订单金额. */ private Double orderAmount; /** * 订单名字. */ private String orderName; /** * 微信openid, 仅微信公众号/小程序支付时需要 */ private String openid; /** * 客户端访问Ip 外部H5支付时必传,需要真实Ip 20191015测试,微信h5支付已不需要真实的ip */ private String spbillCreateIp; /** * 附加内容,发起支付时传入 */ private String attach; /** * 支付后跳转(支付宝PC网站支付) 优先级高于PayConfig.returnUrl */ private String returnUrl; /** * 买家支付宝账号 {@link AliPayTradeCreateRequest.BizContent} */ private String buyerLogonId; /** * 买家的支付宝唯一用户号(2088开头的16位纯数字) {@link AliPayTradeCreateRequest.BizContent} */ private String buyerId; /** * 付款码 */ private String authCode; }
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
ASTMethodDeclaration method = (ASTMethodDeclaration) node; List<JVariableSymbol> localVars = method.getLocalVariables(); for (JVariableSymbol local : localVars) { if (isLocalOnlyStoredWithVolatileField(method, local)) { addViolation(data, method, local); } } return data;
/** * A method declaration, in a class or interface declaration. Since 7.0, this also represents annotation methods. Annotation methods have a much more restricted grammar though, in particular: <ul> <li>They can't declare a {@linkplain #getThrowsList() throws clause}<li>They can't declare {@linkplain #getTypeParameters() type parameters}<li>Their {@linkplain #getFormalParameters() formal parameters} must be empty<li>They can't be declared void <li>They must be abstract </ul> They can however declare a {@link #getDefaultClause() default value}. <pre class="grammar"> MethodDeclaration ::= {@link ASTModifierList ModifierList}{@link ASTTypeParameters TypeParameters}? {@link ASTType Type}&lt;IDENTIFIER&gt; {@link ASTFormalParameters FormalParameters}{@link ASTArrayDimensions ArrayDimensions}? {@link ASTThrowsList ThrowsList}? ( {@link ASTBlock Block} | ";" )</pre> */ public final class ASTMethodDeclaration extends AbstractExecutableDeclaration<JMethodSymbol> { private String name; /** * Populated by {@link OverrideResolutionPass}. */ private JMethodSig overriddenMethod=null; ASTMethodDeclaration( int id); @Override protected <P,R>R acceptVisitor( JavaVisitor<? super P,? extends R> visitor, P data); /** * Returns true if this method is overridden. */ public boolean isOverridden(); /** * Returns the signature of the method this method overrides in a supertype. Note that this method may be implementing several methods of super-interfaces at once, in that case, an arbitrary one is returned. <p>If the method has an {@link Override} annotation, but we couldn'tresolve any method that is actually implemented, this will return {@link TypeSystem#UNRESOLVED_METHOD}. */ public JMethodSig getOverriddenMethod(); void setOverriddenMethod( JMethodSig overriddenMethod); @Override public FileLocation getReportLocation(); /** * Returns the simple name of the method. */ @Override public String getName(); void setName( String name); /** * If this method declaration is an explicit record component accessor, returns the corresponding record component. Otherwise returns null. */ public @Nullable ASTRecordComponent getAccessedRecordComponent(); /** * Returns true if the result type of this method is {@code void}. */ public boolean isVoid(); /** * Returns the default clause, if this is an annotation method declaration that features one. Otherwise returns null. */ @Nullable public ASTDefaultValue getDefaultClause(); /** * Returns the result type node of the method. This may be a {@link ASTVoidType}. */ public @NonNull ASTType getResultTypeNode(); /** * Returns the extra array dimensions that may be after the formal parameters. */ @Nullable public ASTArrayDimensions getExtraDimensions(); /** * Returns whether this is a main method declaration. */ public boolean isMainMethod(); /** * With JEP 445 (Java 21 Preview) the main method does not need to be static anymore and does not need to be public or have a formal parameter. */ private boolean isMainMethodUnnamedClass(); }
/** * A method declaration, in a class or interface declaration. Since 7.0, this also represents annotation methods. Annotation methods have a much more restricted grammar though, in particular: <ul> <li>They can't declare a {@linkplain #getThrowsList() throws clause}<li>They can't declare {@linkplain #getTypeParameters() type parameters}<li>Their {@linkplain #getFormalParameters() formal parameters} must be empty<li>They can't be declared void <li>They must be abstract </ul> They can however declare a {@link #getDefaultClause() default value}. <pre class="grammar"> MethodDeclaration ::= {@link ASTModifierList ModifierList}{@link ASTTypeParameters TypeParameters}? {@link ASTType Type}&lt;IDENTIFIER&gt; {@link ASTFormalParameters FormalParameters}{@link ASTArrayDimensions ArrayDimensions}? {@link ASTThrowsList ThrowsList}? ( {@link ASTBlock Block} | ";" )</pre> */ public final class ASTMethodDeclaration extends AbstractExecutableDeclaration<JMethodSymbol> { private String name; /** * Populated by {@link OverrideResolutionPass}. */ private JMethodSig overriddenMethod=null; ASTMethodDeclaration( int id); @Override protected <P,R>R acceptVisitor( JavaVisitor<? super P,? extends R> visitor, P data); /** * Returns true if this method is overridden. */ public boolean isOverridden(); /** * Returns the signature of the method this method overrides in a supertype. Note that this method may be implementing several methods of super-interfaces at once, in that case, an arbitrary one is returned. <p>If the method has an {@link Override} annotation, but we couldn'tresolve any method that is actually implemented, this will return {@link TypeSystem#UNRESOLVED_METHOD}. */ public JMethodSig getOverriddenMethod(); void setOverriddenMethod( JMethodSig overriddenMethod); @Override public FileLocation getReportLocation(); /** * Returns the simple name of the method. */ @Override public String getName(); void setName( String name); /** * If this method declaration is an explicit record component accessor, returns the corresponding record component. Otherwise returns null. */ public @Nullable ASTRecordComponent getAccessedRecordComponent(); /** * Returns true if the result type of this method is {@code void}. */ public boolean isVoid(); /** * Returns the default clause, if this is an annotation method declaration that features one. Otherwise returns null. */ @Nullable public ASTDefaultValue getDefaultClause(); /** * Returns the result type node of the method. This may be a {@link ASTVoidType}. */ public @NonNull ASTType getResultTypeNode(); /** * Returns the extra array dimensions that may be after the formal parameters. */ @Nullable public ASTArrayDimensions getExtraDimensions(); /** * Returns whether this is a main method declaration. */ public boolean isMainMethod(); /** * With JEP 445 (Java 21 Preview) the main method does not need to be static anymore and does not need to be public or have a formal parameter. */ private boolean isMainMethodUnnamedClass(); }
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); }
defaults.put("Button.background", new Color(20, 20, 20)); defaults.put("Button.foreground", Color.WHITE); defaults.put("Button.borderColor", Color.BLACK); defaults.put("Button.borderPainted", true); defaults.put("Button.focusPainted", false); defaults.put("Button.arc", 0); defaults.put("Button.contentAreaFilled", false); defaults.put("Button.focus", false); defaults.put("Button.focusHighlight", false); defaults.put("Button.focusHighlightColor", Color.BLACK); defaults.put("Button.focusHighlightColor", Color.BLACK); defaults.put("Button.focusHighlightColor", Color.BLACK); defaults.put("Button.focusHighlightColor", Color.BLACK); defaults.put("Button.focusHighlightColor", Color.BLACK); defaults.put("Button.focusHighlightColor", Color.BLACK); defaults.put("Button.focusHighlightColor", Color.BLACK); defaults.put("Button.focusHighlightColor", Color.BLACK); defaults.put("Button.focusHighlightColor", Color.BLACK); defaults.put("Button.focusHighlightColor", Color.BLACK); defaults.put("Button.focusHighlightColor", Color.BLACK); defaults.put("Button.focusHighlightColor", Color.BLACK);
/** * @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
LoadBalancerProperties loadBalancerProperties = clientFactory.getProperties(serviceId); LoadBalancerClient loadBalancer = clientFactory.getLazyProvider(serviceId, loadBalancerProperties) .getIfAvailable(); return loadBalancer.choose(lbRequest).doOnNext(response -> supportedLifecycleProcessors.forEach(lifecycle -> lifecycle .onStart(lbRequest, response)));
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
this.apiClient = new Api(this.apiKey,this.apiKeyList,this.apiHost,this.okHttpClient,this.timeout,this.proxy); return this;
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(); }
return "CREATE " + indexType + " INDEX " + indexName + " ON " + getClassName() + "(" + getFieldsToIndex().get(0) + ") " + "USING " + engine + " " + "WITH " + "{ " + "\"collate\":\"" + collate.getName() + "\", " + "\"nullValuesIgnored\":" + nullValuesIgnored + " }";
/** * 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(); }
return new HookLoader(emulator);
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
if(ObjectUtil.isNull(collection)) { return; } // 初始化根节点 root = new WordDataTreeNode(); // 遍历集合 for(String word : collection) { // 如果为空,则跳过 if(ObjectUtil.isNull(word)) { continue; } // 获取字符数组 char[] chars = word.toCharArray(); // 获取长度 int len = chars.length; // 当前节点 WordDataTreeNode nowNode = root; // 遍历字符数组 for(int i = 0; i < len; i++) { // 获取当前字符 char c = chars[i]; // 获取当前节点的子节点 WordDataTreeNode subNode = nowNode.getSubNode(c); // 如果为空,则创建一个新的节点 if(ObjectUtil.isNull(subNode)) { subNode = new WordDataTreeNode(); nowNode.addSubNode(c, subNode); } // 如果为最后一个字符,则设置为结尾 if(i == len - 1) { subNode.setEnd(true); } // 设置当前节点为子节点 nowNode = subNode; } }
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(); }
XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory); String[] configLocations = getConfigLocations(); if (configLocations != null) { for (String location : configLocations) { beanDefinitionReader.loadBeanDefinitions(location); } }
/** * @author derekyi * @date 2020/11/22 */ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory, BeanDefinitionRegistry { private Map<String,BeanDefinition> beanDefinitionMap=new ConcurrentHashMap<>(256); @Override public void registerBeanDefinition( String beanName, BeanDefinition beanDefinition); @Override public BeanDefinition getBeanDefinition( String beanName) throws BeansException; @Override public boolean containsBeanDefinition( String beanName); @Override public <T>Map<String,T> getBeansOfType( Class<T> type) throws BeansException; public <T>T getBean( Class<T> requiredType) throws BeansException; @Override public String[] getBeanDefinitionNames(); @Override public void preInstantiateSingletons() throws BeansException; }
/** * @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(); } /** * @author derekyi * @date 2020/11/22 */ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory, BeanDefinitionRegistry { private Map<String,BeanDefinition> beanDefinitionMap=new ConcurrentHashMap<>(256); @Override public void registerBeanDefinition( String beanName, BeanDefinition beanDefinition); @Override public BeanDefinition getBeanDefinition( String beanName) throws BeansException; @Override public boolean containsBeanDefinition( String beanName); @Override public <T>Map<String,T> getBeansOfType( Class<T> type) throws BeansException; public <T>T getBean( Class<T> requiredType) throws BeansException; @Override public String[] getBeanDefinitionNames(); @Override public void preInstantiateSingletons() throws BeansException; }
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
if (bean instanceof ApplicationContextAware) { ((ApplicationContextAware) bean).setApplicationContext(applicationContext); } return bean;
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
String name = c.getName().getFullyQualifiedName(); JClass jClass = _package.getClass(name); if (jClass == null) { jClass = new JClass(name, _package); _package.addClass(jClass); } if (arrayCount > 0) { for (int i = 0; i < arrayCount; i++) { jClass = new JClass(jClass.getName() + "[]", jClass); } } return jClass;
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
String value = lockValue.get(); if (value == null) { return false; } String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end"; RedisScript<Long> redisScript = new DefaultRedisScript<>(script, Long.class); Long result = redisTemplate.execute(redisScript, Collections.singletonList(key), value); if (result != null && result > 0) { lockValue.remove(); return true; } return false;
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
if (isStarted()) { throw new IllegalStateException("Configuration cannot be changed while the provider is started"); } this.customFieldsNode = customFields; this.customFields = null;
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
return field.getType().isPrimitive() || field.getType().isAssignableTo(BigDecimal.class) || field.getType().isAssignableTo(BigInteger.class) || field.getType().isAssignableTo(Number.class);
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
int updatedLineInd = findLineInd(buffer, updatedLine); if (updatedLineInd == -1) { LOG.error("Can't find updated line in buffer"); return; } int startLineInd = updatedLineInd; if (updatedLineInd > 0) { startLineInd = updatedLineInd - 1; } String text = joinLines(buffer, startLineInd, updatedLineInd); for (HyperlinkFilter filter : myHyperlinkFilter) { filter.process(text, myHyperlinkColor, myHighlightMode); }
/** * Holds styled characters lines */ public class LinesBuffer { private static final Logger LOG=Logger.getLogger(LinesBuffer.class); public static final int DEFAULT_MAX_LINES_COUNT=5000; private int myBufferMaxLinesCount=DEFAULT_MAX_LINES_COUNT; private ArrayList<TerminalLine> myLines=new ArrayList<>(); private final TextProcessing myTextProcessing; public LinesBuffer( TextProcessing textProcessing); public LinesBuffer( int bufferMaxLinesCount, TextProcessing textProcessing); public synchronized String getLines(); public synchronized void addNewLine( TextStyle style, CharBuffer characters); private synchronized void addNewLine( TerminalLine.TextEntry entry); private synchronized void addLine( TerminalLine line); public synchronized int getLineCount(); public synchronized void removeTopLines( int count); public String getLineText( int row); public synchronized void insertLines( int y, int count, int lastLine, TextEntry filler); public synchronized LinesBuffer deleteLines( int y, int count, int lastLine, TextEntry filler); public synchronized void writeString( int x, int y, CharBuffer str, TextStyle style); public synchronized void clearLines( int startRow, int endRow, TextEntry filler); public synchronized void clearAll(); public synchronized void deleteCharacters( int x, int y, int count, TextStyle style); public synchronized void insertBlankCharacters( final int x, final int y, final int count, final int maxLen, TextStyle style); public synchronized void clearArea( int leftX, int topY, int rightX, int bottomY, TextStyle style); public synchronized void processLines( final int yStart, final int yCount, final StyledTextConsumer consumer); public synchronized void processLines( final int firstLine, final int count, final StyledTextConsumer consumer, final int startRow); public synchronized void moveTopLinesTo( int count, final LinesBuffer buffer); public synchronized void addLines( List<TerminalLine> lines); public synchronized TerminalLine getLine( int row); public synchronized void moveBottomLinesTo( int count, final LinesBuffer buffer); private synchronized void addLinesFirst( List<TerminalLine> lines); private synchronized void removeBottomLines( int count); public int removeBottomEmptyLines( int ind, int maxCount); } /** * @author traff */ public class TerminalLine { private TextEntries myTextEntries=new TextEntries(); private boolean myWrapped=false; public TerminalLine(); public TerminalLine( TextEntry entry); public static TerminalLine createEmpty(); private List<TextEntry> newList( Iterable<TextEntry> items); public synchronized String getText(); public char charAt( int x); public boolean isWrapped(); public void setWrapped( boolean wrapped); public synchronized void clear( TextEntry filler); public void writeString( int x, CharBuffer str, TextStyle style); private synchronized void writeCharacters( int x, TextStyle style, CharBuffer characters); private static TextEntries merge( int x, CharBuffer str, TextStyle style, TextEntries entries, int lineLength); private static Pair<char[],TextStyle[]> toBuf( TextEntries entries, int lineLength); private static TextEntries collectFromBuffer( char[] buf, TextStyle[] styles); public synchronized void deleteCharacters( int x); public synchronized void deleteCharacters( int x, TextStyle style); public synchronized void deleteCharacters( int x, int count, TextStyle style); public synchronized void insertBlankCharacters( int x, int count, int maxLen, TextStyle style); public synchronized void clearArea( int leftX, int rightX, TextStyle style); public synchronized TextStyle getStyleAt( int x); public synchronized void process( int y, StyledTextConsumer consumer, int startRow); public synchronized boolean isNul(); public void runWithLock( Runnable r); void forEachEntry( Consumer<TextEntry> action); public List<TextEntry> getEntries(); void appendEntry( TextEntry entry); @Override public String toString(); public static class TextEntry { private final TextStyle myStyle; private final CharBuffer myText; public TextEntry( TextStyle style, CharBuffer text); public TextStyle getStyle(); public CharBuffer getText(); public int getLength(); public boolean isNul(); @Override public String toString(); } private static class TextEntries implements Iterable<TextEntry> { private List<TextEntry> myTextEntries=new ArrayList<>(); private int myLength=0; public void add( TextEntry entry); private List<TextEntry> entries(); public Iterator<TextEntry> iterator(); public int length(); public void clear(); } }
/** * Holds styled characters lines */ public class LinesBuffer { private static final Logger LOG=Logger.getLogger(LinesBuffer.class); public static final int DEFAULT_MAX_LINES_COUNT=5000; private int myBufferMaxLinesCount=DEFAULT_MAX_LINES_COUNT; private ArrayList<TerminalLine> myLines=new ArrayList<>(); private final TextProcessing myTextProcessing; public LinesBuffer( TextProcessing textProcessing); public LinesBuffer( int bufferMaxLinesCount, TextProcessing textProcessing); public synchronized String getLines(); public synchronized void addNewLine( TextStyle style, CharBuffer characters); private synchronized void addNewLine( TerminalLine.TextEntry entry); private synchronized void addLine( TerminalLine line); public synchronized int getLineCount(); public synchronized void removeTopLines( int count); public String getLineText( int row); public synchronized void insertLines( int y, int count, int lastLine, TextEntry filler); public synchronized LinesBuffer deleteLines( int y, int count, int lastLine, TextEntry filler); public synchronized void writeString( int x, int y, CharBuffer str, TextStyle style); public synchronized void clearLines( int startRow, int endRow, TextEntry filler); public synchronized void clearAll(); public synchronized void deleteCharacters( int x, int y, int count, TextStyle style); public synchronized void insertBlankCharacters( final int x, final int y, final int count, final int maxLen, TextStyle style); public synchronized void clearArea( int leftX, int topY, int rightX, int bottomY, TextStyle style); public synchronized void processLines( final int yStart, final int yCount, final StyledTextConsumer consumer); public synchronized void processLines( final int firstLine, final int count, final StyledTextConsumer consumer, final int startRow); public synchronized void moveTopLinesTo( int count, final LinesBuffer buffer); public synchronized void addLines( List<TerminalLine> lines); public synchronized TerminalLine getLine( int row); public synchronized void moveBottomLinesTo( int count, final LinesBuffer buffer); private synchronized void addLinesFirst( List<TerminalLine> lines); private synchronized void removeBottomLines( int count); public int removeBottomEmptyLines( int ind, int maxCount); } /** * @author traff */ public class TerminalLine { private TextEntries myTextEntries=new TextEntries(); private boolean myWrapped=false; public TerminalLine(); public TerminalLine( TextEntry entry); public static TerminalLine createEmpty(); private List<TextEntry> newList( Iterable<TextEntry> items); public synchronized String getText(); public char charAt( int x); public boolean isWrapped(); public void setWrapped( boolean wrapped); public synchronized void clear( TextEntry filler); public void writeString( int x, CharBuffer str, TextStyle style); private synchronized void writeCharacters( int x, TextStyle style, CharBuffer characters); private static TextEntries merge( int x, CharBuffer str, TextStyle style, TextEntries entries, int lineLength); private static Pair<char[],TextStyle[]> toBuf( TextEntries entries, int lineLength); private static TextEntries collectFromBuffer( char[] buf, TextStyle[] styles); public synchronized void deleteCharacters( int x); public synchronized void deleteCharacters( int x, TextStyle style); public synchronized void deleteCharacters( int x, int count, TextStyle style); public synchronized void insertBlankCharacters( int x, int count, int maxLen, TextStyle style); public synchronized void clearArea( int leftX, int rightX, TextStyle style); public synchronized TextStyle getStyleAt( int x); public synchronized void process( int y, StyledTextConsumer consumer, int startRow); public synchronized boolean isNul(); public void runWithLock( Runnable r); void forEachEntry( Consumer<TextEntry> action); public List<TextEntry> getEntries(); void appendEntry( TextEntry entry); @Override public String toString(); public static class TextEntry { private final TextStyle myStyle; private final CharBuffer myText; public TextEntry( TextStyle style, CharBuffer text); public TextStyle getStyle(); public CharBuffer getText(); public int getLength(); public boolean isNul(); @Override public String toString(); } private static class TextEntries implements Iterable<TextEntry> { private List<TextEntry> myTextEntries=new ArrayList<>(); private int myLength=0; public void add( TextEntry entry); private List<TextEntry> entries(); public Iterator<TextEntry> iterator(); public int length(); public void clear(); } }
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
return "ConsumerPartitionVO{" + "groupId='" + groupId + '\'' + ", topic='" + topic + '\'' + ", partitionId=" + partitionId + ", offset=" + offset + ", size=" + size + ", firstOffset=" + firstOffset + '}';
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
return field.getType().isAssignableFrom(String.class);
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
byte[] data = serializer.serialize(obj); if (data.length > compressionThreshold) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); bos.write(1); compressor.compress(new ByteArrayInputStream(data), bos); return bos.toByteArray(); } else { byte[] result = new byte[data.length + 1]; result[0] = 0; System.arraycopy(data, 0, result, 1, data.length); return result; }
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
if (o instanceof String) { Matcher matcher = pattern.matcher((String) o); if (matcher.matches()) { return matcher.replaceAll(mask.toString()); } } return o;
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
// 获取请求头中的 token String token = WebFrameworkUtils.getToken(request); // 获取请求头中的 userType Integer userType = WebFrameworkUtils.getUserType(request); // 模拟登录用户 LoginUser loginUser = mockLoginUser(request, token, userType); if (loginUser == null) { // 正式登录用户 loginUser = buildLoginUserByToken(token, userType); } // 设置登录用户 WebFrameworkUtils.setLoginUser(loginUser); // 继续执行过滤器链 chain.doFilter(request, response);
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); }
return stringBuilder.length() >= 5;
/** * 内部信息上下文 * @author binbin.hou * @since 0.6.0 */ public class InnerSensitiveWordContext { /** * 原始文本 */ private String originalText; /** * 格式化后的字符 */ private Map<Character,Character> formatCharMapping; /** * 校验模式 */ private WordValidModeEnum modeEnum; /** * 原始上下文 */ private IWordContext wordContext; public static InnerSensitiveWordContext newInstance(); public String originalText(); public InnerSensitiveWordContext originalText( String text); public Map<Character,Character> formatCharMapping(); public InnerSensitiveWordContext formatCharMapping( Map<Character,Character> formatCharMapping); public WordValidModeEnum modeEnum(); public InnerSensitiveWordContext modeEnum( WordValidModeEnum modeEnum); public IWordContext wordContext(); public InnerSensitiveWordContext wordContext( IWordContext context); }
/** * 抽象实现策略 * @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); } /** * 内部信息上下文 * @author binbin.hou * @since 0.6.0 */ public class InnerSensitiveWordContext { /** * 原始文本 */ private String originalText; /** * 格式化后的字符 */ private Map<Character,Character> formatCharMapping; /** * 校验模式 */ private WordValidModeEnum modeEnum; /** * 原始上下文 */ private IWordContext wordContext; public static InnerSensitiveWordContext newInstance(); public String originalText(); public InnerSensitiveWordContext originalText( String text); public Map<Character,Character> formatCharMapping(); public InnerSensitiveWordContext formatCharMapping( Map<Character,Character> formatCharMapping); public WordValidModeEnum modeEnum(); public InnerSensitiveWordContext modeEnum( WordValidModeEnum modeEnum); public IWordContext wordContext(); public InnerSensitiveWordContext wordContext( IWordContext context); }
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
if (THREAD_LOCAL.get() == null) { THREAD_LOCAL.set(new LinkedHashMap<>()); } THREAD_LOCAL.get().put(key, val);
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
FileInfo ent = (FileInfo) value; textLabel.setText(ent.getName()); iconLabel.setText(getIconForType(ent)); label.setBackground(isSelected ? App.SKIN.getSelectedBackground() : App.SKIN.getBackground()); label.setForeground(isSelected ? App.SKIN.getSelectedForeground() : foreground); label.setIcon(null); label.setIconTextGap(0); label.setHorizontalAlignment(JLabel.LEFT); label.setHorizontalTextPosition(JLabel.LEFT); label.setVerticalTextPosition(JLabel.CENTER); label.setIcon(iconLabel); label.setText(textLabel.getText()); return label;
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); }
return super.decrypt(key, data);
/** * 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
myEmulatorExecutor.shutdownNow(); myEmulator.close(); myTtyConnector.close();
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
Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(beanDefinition.getBeanClass()); enhancer.setCallback(new NoOp() { @Override public int hashCode() { return super.hashCode(); } }); if (beanDefinition.getConstructorArgumentValues().getArgumentValues().size() > 0) { enhancer.setCallback(new ConstructorArgInterceptor(beanDefinition.getConstructorArgumentValues())); } return enhancer.create();
/** * BeanDefinition实例保存bean的信息,包括class类型、方法构造参数、bean属性、bean的scope等,此处简化只包含class类型和bean属性 * @author derekyi * @date 2020/11/22 */ public class BeanDefinition { public static String SCOPE_SINGLETON="singleton"; public static String SCOPE_PROTOTYPE="prototype"; /** * bean class类 */ private Class beanClass; /** * class 属性值 */ private PropertyValues propertyValues; /** * 通过反射 初始化方法名称 */ private String initMethodName; /** * 销毁方法名称 */ private String destroyMethodName; /** * 作用域 默认单例Bean */ private String scope=SCOPE_SINGLETON; private boolean singleton=true; private boolean prototype=false; private boolean lazyInit=false; public BeanDefinition( Class beanClass); public BeanDefinition( Class beanClass, PropertyValues propertyValues); public void setScope( String scope); public boolean isSingleton(); public boolean isPrototype(); public Class getBeanClass(); public void setBeanClass( Class beanClass); public PropertyValues getPropertyValues(); public void setPropertyValues( PropertyValues propertyValues); public String getInitMethodName(); public void setInitMethodName( String initMethodName); public String getDestroyMethodName(); public void setDestroyMethodName( String destroyMethodName); @Override public boolean equals( Object o); @Override public int hashCode(); public void setLazyInit( boolean b); public boolean isLazyInit(); }
/** * BeanDefinition实例保存bean的信息,包括class类型、方法构造参数、bean属性、bean的scope等,此处简化只包含class类型和bean属性 * @author derekyi * @date 2020/11/22 */ public class BeanDefinition { public static String SCOPE_SINGLETON="singleton"; public static String SCOPE_PROTOTYPE="prototype"; /** * bean class类 */ private Class beanClass; /** * class 属性值 */ private PropertyValues propertyValues; /** * 通过反射 初始化方法名称 */ private String initMethodName; /** * 销毁方法名称 */ private String destroyMethodName; /** * 作用域 默认单例Bean */ private String scope=SCOPE_SINGLETON; private boolean singleton=true; private boolean prototype=false; private boolean lazyInit=false; public BeanDefinition( Class beanClass); public BeanDefinition( Class beanClass, PropertyValues propertyValues); public void setScope( String scope); public boolean isSingleton(); public boolean isPrototype(); public Class getBeanClass(); public void setBeanClass( Class beanClass); public PropertyValues getPropertyValues(); public void setPropertyValues( PropertyValues propertyValues); public String getInitMethodName(); public void setInitMethodName( String initMethodName); public String getDestroyMethodName(); public void setDestroyMethodName( String destroyMethodName); @Override public boolean equals( Object o); @Override public int hashCode(); public void setLazyInit( boolean b); public boolean isLazyInit(); }
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
List<NameValuePair> list = new ArrayList<NameValuePair>(); for (Map.Entry<String, String> entry : map.entrySet()) { list.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } return list;
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 ; }
return (ProtocolProviderFactory) bundleContext.getService( bundleContext.getServiceReference( ProtocolProviderFactory.class.getName()));
/** * 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
ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(orientClassLoader); Iterator<T> iterator = ServiceRegistry.lookupProvider(clazz); Thread.currentThread().setContextClassLoader(oldClassLoader); return iterator;
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
return new ExceptionVisitor() { @Override public boolean onException(Hypervisor hypervisor, int ec, long address) { breakRestorer.restore(hypervisor, ec, address); return true; } };
interface BreakRestorer { void install( Hypervisor hypervisor); }
interface BreakRestorer { void install( Hypervisor hypervisor); }
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; }
if (!shouldExecute()) { return; } try { factory.getWebpack().run(arguments, workingDirectory, outputdir); } catch (FrontendException e) { throw new TaskRunnerException(e); }
public final class FrontendPluginFactory { private static final Platform defaultPlatform=Platform.guess(); private static final String DEFAULT_CACHE_PATH="cache"; private final File workingDirectory; private final File installDirectory; private final CacheResolver cacheResolver; public FrontendPluginFactory( File workingDirectory, File installDirectory); public FrontendPluginFactory( File workingDirectory, File installDirectory, CacheResolver cacheResolver); public BunInstaller getBunInstaller( ProxyConfig proxy); public NodeInstaller getNodeInstaller( ProxyConfig proxy); public NPMInstaller getNPMInstaller( ProxyConfig proxy); public PnpmInstaller getPnpmInstaller( ProxyConfig proxy); public YarnInstaller getYarnInstaller( ProxyConfig proxy); public BowerRunner getBowerRunner( ProxyConfig proxy); public BunRunner getBunRunner( ProxyConfig proxy, String npmRegistryURL); public JspmRunner getJspmRunner(); public NpmRunner getNpmRunner( ProxyConfig proxy, String npmRegistryURL); public PnpmRunner getPnpmRunner( ProxyConfig proxyConfig, String npmRegistryUrl); public NpxRunner getNpxRunner( ProxyConfig proxy, String npmRegistryURL); public YarnRunner getYarnRunner( ProxyConfig proxy, String npmRegistryURL); public GruntRunner getGruntRunner(); public EmberRunner getEmberRunner(); public KarmaRunner getKarmaRunner(); public GulpRunner getGulpRunner(); public WebpackRunner getWebpackRunner(); private NodeExecutorConfig getExecutorConfig(); private InstallConfig getInstallConfig(); private static final CacheResolver getDefaultCacheResolver( File root); }
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; } public final class FrontendPluginFactory { private static final Platform defaultPlatform=Platform.guess(); private static final String DEFAULT_CACHE_PATH="cache"; private final File workingDirectory; private final File installDirectory; private final CacheResolver cacheResolver; public FrontendPluginFactory( File workingDirectory, File installDirectory); public FrontendPluginFactory( File workingDirectory, File installDirectory, CacheResolver cacheResolver); public BunInstaller getBunInstaller( ProxyConfig proxy); public NodeInstaller getNodeInstaller( ProxyConfig proxy); public NPMInstaller getNPMInstaller( ProxyConfig proxy); public PnpmInstaller getPnpmInstaller( ProxyConfig proxy); public YarnInstaller getYarnInstaller( ProxyConfig proxy); public BowerRunner getBowerRunner( ProxyConfig proxy); public BunRunner getBunRunner( ProxyConfig proxy, String npmRegistryURL); public JspmRunner getJspmRunner(); public NpmRunner getNpmRunner( ProxyConfig proxy, String npmRegistryURL); public PnpmRunner getPnpmRunner( ProxyConfig proxyConfig, String npmRegistryUrl); public NpxRunner getNpxRunner( ProxyConfig proxy, String npmRegistryURL); public YarnRunner getYarnRunner( ProxyConfig proxy, String npmRegistryURL); public GruntRunner getGruntRunner(); public EmberRunner getEmberRunner(); public KarmaRunner getKarmaRunner(); public GulpRunner getGulpRunner(); public WebpackRunner getWebpackRunner(); private NodeExecutorConfig getExecutorConfig(); private InstallConfig getInstallConfig(); private static final CacheResolver getDefaultCacheResolver( File root); }

No dataset card yet

New: Create and edit this dataset card directly on the website!

Contribute a Dataset Card
Downloads last month
7
Add dataset card