proj_name
stringclasses
26 values
relative_path
stringlengths
42
165
class_name
stringlengths
3
46
func_name
stringlengths
2
44
masked_class
stringlengths
80
7.9k
func_body
stringlengths
76
5.98k
len_input
int64
30
1.88k
len_output
int64
25
1.43k
total
int64
73
2.03k
initial_context
stringclasses
74 values
subhra74_snowflake
snowflake/muon-jediterm/src/main/java/com/jediterm/terminal/model/hyperlinks/LinkResult.java
LinkResult
getItems
class LinkResult { private final LinkResultItem myItem; private List<LinkResultItem> myItemList; public LinkResult( LinkResultItem item) { myItem = item; myItemList = null; } public LinkResult( List<LinkResultItem> itemList) { myItemList = itemList; myItem = null; } public List<LinkResultItem> getItems() {<FILL_FUNCTION_BODY>} }
if (myItemList == null) { myItemList = new ArrayList<>(Arrays.asList(myItem)); } return myItemList;
123
43
166
ainilili_ratel
ratel/landlords-server/src/main/java/org/nico/ratel/landlords/server/event/ServerEventListener_CODE_ROOM_JOIN.java
ServerEventListener_CODE_ROOM_JOIN
call
class ServerEventListener_CODE_ROOM_JOIN implements ServerEventListener { @Override public void call(ClientSide clientSide, String data) {<FILL_FUNCTION_BODY>} /** * 通知观战者玩家加入房间 * * @param room 房间 * @param clientSide 玩家 */ private void notifyWatcherJoinRoom(Room room, ClientSide clientSide) { for (ClientSide watcher : room.getWatcherList()) { ChannelUtils.pushToClient(watcher.getChannel(), ClientEventCode.CODE_ROOM_JOIN_SUCCESS, clientSide.getNickname()); } } }
Room room = ServerContains.getRoom(Integer.parseInt(data)); if (room == null) { String result = MapHelper.newInstance() .put("roomId", data) .json(); ChannelUtils.pushToClient(clientSide.getChannel(), ClientEventCode.CODE_ROOM_JOIN_FAIL_BY_INEXIST, result); return; } if (room.getClientSideList().size() == 3) { String result = MapHelper.newInstance() .put("roomId", room.getId()) .put("roomOwner", room.getRoomOwner()) .json(); ChannelUtils.pushToClient(clientSide.getChannel(), ClientEventCode.CODE_ROOM_JOIN_FAIL_BY_FULL, result); return; } // join default ready clientSide.setStatus(ClientStatus.READY); clientSide.setRoomId(room.getId()); ConcurrentSkipListMap<Integer, ClientSide> roomClientMap = (ConcurrentSkipListMap<Integer, ClientSide>) room.getClientSideMap(); LinkedList<ClientSide> roomClientList = room.getClientSideList(); if (roomClientList.size() > 0) { ClientSide pre = roomClientList.getLast(); pre.setNext(clientSide); clientSide.setPre(pre); } roomClientList.add(clientSide); roomClientMap.put(clientSide.getId(), clientSide); room.setStatus(RoomStatus.WAIT); String result = MapHelper.newInstance() .put("clientId", clientSide.getId()) .put("clientNickname", clientSide.getNickname()) .put("roomId", room.getId()) .put("roomOwner", room.getRoomOwner()) .put("roomClientCount", room.getClientSideList().size()) .json(); for (ClientSide client : roomClientMap.values()) { ChannelUtils.pushToClient(client.getChannel(), ClientEventCode.CODE_ROOM_JOIN_SUCCESS, result); } if (roomClientMap.size() == 3) { clientSide.setNext(roomClientList.getFirst()); roomClientList.getFirst().setPre(clientSide); ServerEventListener.get(ServerEventCode.CODE_GAME_STARTING).call(clientSide, String.valueOf(room.getId())); return; } notifyWatcherJoinRoom(room, clientSide);
169
656
825
google_truth
truth/core/src/main/java/com/google/common/truth/MultisetSubject.java
MultisetSubject
hasCount
class MultisetSubject extends IterableSubject { private final @Nullable Multiset<?> actual; MultisetSubject(FailureMetadata metadata, @Nullable Multiset<?> multiset) { super(metadata, multiset, /* typeDescriptionOverride= */ "multiset"); this.actual = multiset; } /** Fails if the element does not have the given count. */ public final void hasCount(@Nullable Object element, int expectedCount) {<FILL_FUNCTION_BODY>} }
checkArgument(expectedCount >= 0, "expectedCount(%s) must be >= 0", expectedCount); int actualCount = checkNotNull(actual).count(element); check("count(%s)", element).that(actualCount).isEqualTo(expectedCount);
133
66
199
/** * Propositions for {@link Iterable} subjects.<p><b>Note:</b> <ul> <li>Assertions may iterate through the given {@link Iterable} more than once. If you have anunusual implementation of {@link Iterable} which does not support multiple iterations(sometimes known as a "one-shot iterable"), you must copy your iterable into a collection which does (e.g. {@code ImmutableList.copyOf(iterable)} or, if your iterable may containnull, {@code newArrayList(iterable)}). If you don't, you may see surprising failures. <li>Assertions may also require that the elements in the given {@link Iterable} implement{@link Object#hashCode} correctly.</ul> * @author Kurt Alfred Kluever * @author Pete Gillin */ public class IterableSubject extends Subject { private final @Nullable Iterable<?> actual; /** * Constructor for use by subclasses. If you want to create an instance of this class itself, call {@link Subject#check(String,Object...) check(...)}{@code .that(actual)}. */ protected IterableSubject( FailureMetadata metadata, @Nullable Iterable<?> iterable); /** * Constructor for use by package-private callers. */ IterableSubject( FailureMetadata metadata, @Nullable Iterable<?> iterable, @Nullable String typeDescriptionOverride); @Override protected String actualCustomStringRepresentation(); @Override public void isEqualTo( @Nullable Object expected); /** * Fails if the subject is not empty. */ public final void isEmpty(); /** * Fails if the subject is empty. */ public final void isNotEmpty(); /** * Fails if the subject does not have the given size. */ public final void hasSize( int expectedSize); /** * Checks (with a side-effect failure) that the subject contains the supplied item. */ public final void contains( @Nullable Object element); /** * Checks (with a side-effect failure) that the subject does not contain the supplied item. */ public final void doesNotContain( @Nullable Object element); /** * Checks that the subject does not contain duplicate elements. */ public final void containsNoDuplicates(); /** * Checks that the subject contains at least one of the provided objects or fails. */ public final void containsAnyOf( @Nullable Object first, @Nullable Object second, @Nullable Object @Nullable ... rest); /** * Checks that the subject contains at least one of the objects contained in the provided collection or fails. */ public final void containsAnyIn( @Nullable Iterable<?> expected); /** * Checks that the subject contains at least one of the objects contained in the provided array or fails. */ @SuppressWarnings("AvoidObjectArrays") public final void containsAnyIn( @Nullable Object[] expected); /** * Checks that the actual iterable contains at least all of the expected elements or fails. If an element appears more than once in the expected elements to this call then it must appear at least that number of times in the actual elements. <p>To also test that the contents appear in the given order, make a call to {@code inOrder()}on the object returned by this method. The expected elements must appear in the given order within the actual elements, but they are not required to be consecutive. */ @CanIgnoreReturnValue public final Ordered containsAtLeast( @Nullable Object firstExpected, @Nullable Object secondExpected, @Nullable Object @Nullable ... restOfExpected); /** * Checks that the actual iterable contains at least all of the expected elements or fails. If an element appears more than once in the expected elements then it must appear at least that number of times in the actual elements. <p>To also test that the contents appear in the given order, make a call to {@code inOrder()}on the object returned by this method. The expected elements must appear in the given order within the actual elements, but they are not required to be consecutive. */ @CanIgnoreReturnValue public final Ordered containsAtLeastElementsIn( Iterable<?> expectedIterable); /** * Checks that the actual iterable contains at least all of the expected elements or fails. If an element appears more than once in the expected elements then it must appear at least that number of times in the actual elements. <p>To also test that the contents appear in the given order, make a call to {@code inOrder()}on the object returned by this method. The expected elements must appear in the given order within the actual elements, but they are not required to be consecutive. */ @CanIgnoreReturnValue @SuppressWarnings("AvoidObjectArrays") public final Ordered containsAtLeastElementsIn( @Nullable Object[] expected); private Ordered failAtLeast( Collection<?> expected, Collection<?> missingRawObjects); /** * Removes at most the given number of available elements from the input list and adds them to the given output collection. */ private static void moveElements( List<?> input, Collection<@Nullable Object> output, int maxElements); /** * Checks that a subject contains exactly the provided objects or fails. <p>Multiplicity is respected. For example, an object duplicated exactly 3 times in the parameters asserts that the object must likewise be duplicated exactly 3 times in the subject. <p>To also test that the contents appear in the given order, make a call to {@code inOrder()}on the object returned by this method. <p>To test that the iterable contains the same elements as an array, prefer {@link #containsExactlyElementsIn(Object[])}. It makes clear that the given array is a list of elements, not an element itself. This helps human readers and avoids a compiler warning. */ @CanIgnoreReturnValue public final Ordered containsExactly( @Nullable Object @Nullable ... varargs); /** * Checks that a subject contains exactly the provided objects or fails. <p>Multiplicity is respected. For example, an object duplicated exactly 3 times in the {@code Iterable} parameter asserts that the object must likewise be duplicated exactly 3 times in thesubject. <p>To also test that the contents appear in the given order, make a call to {@code inOrder()}on the object returned by this method. */ @CanIgnoreReturnValue public final Ordered containsExactlyElementsIn( @Nullable Iterable<?> expected); /** * Checks that a subject contains exactly the provided objects or fails. <p>Multiplicity is respected. For example, an object duplicated exactly 3 times in the array parameter asserts that the object must likewise be duplicated exactly 3 times in the subject. <p>To also test that the contents appear in the given order, make a call to {@code inOrder()}on the object returned by this method. */ @CanIgnoreReturnValue @SuppressWarnings({"AvoidObjectArrays","ContainsExactlyElementsInUnnecessaryWrapperAroundArray","ContainsExactlyElementsInWithVarArgsToExactly"}) public final Ordered containsExactlyElementsIn( @Nullable Object @Nullable [] expected); private Ordered containsExactlyElementsIn( @Nullable Iterable<?> required, boolean addElementsInWarning); private Ordered failExactly( Iterable<?> required, boolean addElementsInWarning, Collection<?> missingRawObjects, Collection<?> extraRawObjects); private static ImmutableList<Fact> makeElementFactsForBoth( String firstKey, Collection<?> firstCollection, String secondKey, Collection<?> secondCollection); /** * Returns a list of facts (zero, one, or many, depending on the number of elements and the grouping policy) describing the given missing, unexpected, or near-miss elements. */ private static ImmutableList<Fact> makeElementFacts( String label, DuplicateGroupedAndTyped elements, ElementFactGrouping grouping); private static String keyToGoWithElementsString( String label, DuplicateGroupedAndTyped elements); private static String keyToServeAsHeader( String label, DuplicateGroupedAndTyped elements); private static String numberString( int n, int count); private static ElementFactGrouping pickGrouping( Iterable<Multiset.Entry<?>> first, Iterable<Multiset.Entry<?>> second); private static boolean anyContainsCommaOrNewline( Iterable<Multiset.Entry<?>>... lists); private static boolean hasMultiple( Iterable<Multiset.Entry<?>> entries); private static boolean containsEmptyOrLong( Iterable<Multiset.Entry<?>> entries); /** * Whether to output each missing/unexpected item as its own {@link Fact} or to group all thoseitems together into a single {@code Fact}. */ enum ElementFactGrouping { ALL_IN_ONE_FACT, FACT_PER_ELEMENT} /** * Checks that a actual iterable contains none of the excluded objects or fails. (Duplicates are irrelevant to this test, which fails if any of the actual elements equal any of the excluded.) */ public final void containsNoneOf( @Nullable Object firstExcluded, @Nullable Object secondExcluded, @Nullable Object @Nullable ... restOfExcluded); /** * Checks that the actual iterable contains none of the elements contained in the excluded iterable or fails. (Duplicates are irrelevant to this test, which fails if any of the actual elements equal any of the excluded.) */ public final void containsNoneIn( Iterable<?> excluded); /** * Checks that the actual iterable contains none of the elements contained in the excluded array or fails. (Duplicates are irrelevant to this test, which fails if any of the actual elements equal any of the excluded.) */ @SuppressWarnings("AvoidObjectArrays") public final void containsNoneIn( @Nullable Object[] excluded); /** * Ordered implementation that does nothing because it's already known to be true. */ private static final Ordered IN_ORDER=() -> { } ; /** * Ordered implementation that does nothing because an earlier check already caused a failure. */ private static final Ordered ALREADY_FAILED=() -> { } ; /** * Fails if the iterable is not strictly ordered, according to the natural ordering of its elements. Strictly ordered means that each element in the iterable is <i>strictly</i> greater than the element that preceded it. * @throws ClassCastException if any pair of elements is not mutually Comparable * @throws NullPointerException if any element is null */ public void isInStrictOrder(); /** * Fails if the iterable is not strictly ordered, according to the given comparator. Strictly ordered means that each element in the iterable is <i>strictly</i> greater than the element that preceded it. * @throws ClassCastException if any pair of elements is not mutually Comparable */ @SuppressWarnings({"unchecked"}) public final void isInStrictOrder( Comparator<?> comparator); /** * Fails if the iterable is not ordered, according to the natural ordering of its elements. Ordered means that each element in the iterable is greater than or equal to the element that preceded it. * @throws ClassCastException if any pair of elements is not mutually Comparable * @throws NullPointerException if any element is null */ public void isInOrder(); /** * Fails if the iterable is not ordered, according to the given comparator. Ordered means that each element in the iterable is greater than or equal to the element that preceded it. * @throws ClassCastException if any pair of elements is not mutually Comparable */ @SuppressWarnings({"unchecked"}) public final void isInOrder( Comparator<?> comparator); private interface PairwiseChecker { boolean check( @Nullable Object prev, @Nullable Object next); } private void pairwiseCheck( String expectedFact, PairwiseChecker checker); /** * @deprecated You probably meant to call {@link #containsNoneOf} instead. */ @Override @Deprecated public void isNoneOf( @Nullable Object first, @Nullable Object second, @Nullable Object @Nullable ... rest); /** * @deprecated You probably meant to call {@link #containsNoneIn} instead. */ @Override @Deprecated public void isNotIn( @Nullable Iterable<?> iterable); private Fact fullContents(); /** * Starts a method chain for a check in which the actual elements (i.e. the elements of the {@link Iterable} under test) are compared to expected elements using the given {@link Correspondence}. The actual elements must be of type {@code A}, the expected elements must be of type {@code E}. The check is actually executed by continuing the method chain. For example: <pre> {@code assertThat(actualIterable).comparingElementsUsing(correspondence).contains(expected);}</pre> where {@code actualIterable} is an {@code Iterable<A>} (or, more generally, an {@code Iterable<? extends A>}), {@code correspondence} is a {@code Correspondence<A, E>}, and {@code expected} is an {@code E}. <p>Any of the methods on the returned object may throw {@link ClassCastException} if theyencounter an actual element that is not of type {@code A}. */ public <A extends @Nullable Object,E extends @Nullable Object>UsingCorrespondence<A,E> comparingElementsUsing( Correspondence<? super A,? super E> correspondence); /** * Starts a method chain for a check in which failure messages may use the given {@link DiffFormatter} to describe the difference between an actual elements (i.e. an element of the{@link Iterable} under test) and the element it is expected to be equal to, but isn't. Theactual and expected elements must be of type {@code T}. The check is actually executed by continuing the method chain. You may well want to use {@link UsingCorrespondence#displayingDiffsPairedBy} to specify how the elements should be paired upfor diffing. For example: <pre> {@code assertThat(actualFoos) .formattingDiffsUsing(FooTestHelper::formatDiff) .displayingDiffsPairedBy(Foo::getId) .containsExactly(foo1, foo2, foo3);}</pre> where {@code actualFoos} is an {@code Iterable<Foo>}, {@code FooTestHelper.formatDiff} is astatic method taking two {@code Foo} arguments and returning a {@link String}, {@code Foo.getId} is a no-arg instance method returning some kind of ID, and {@code foo1}, {code foo2}, and {@code foo3} are {@code Foo} instances.<p>Unlike when using {@link #comparingElementsUsing}, the elements are still compared using object equality, so this method does not affect whether a test passes or fails. <p>Any of the methods on the returned object may throw {@link ClassCastException} if theyencounter an actual element that is not of type {@code T}. * @since 1.1 */ public <T>UsingCorrespondence<T,T> formattingDiffsUsing( DiffFormatter<? super T,? super T> formatter); /** * A partially specified check in which the actual elements (normally the elements of the {@link Iterable} under test) are compared to expected elements using a {@link Correspondence}. The expected elements are of type {@code E}. Call methods on this object to actually execute the check. */ public static class UsingCorrespondence<A extends @Nullable Object,E extends @Nullable Object> { private final IterableSubject subject; private final Correspondence<? super A,? super E> correspondence; private final Optional<Pairer> pairer; UsingCorrespondence( IterableSubject subject, Correspondence<? super A,? super E> correspondence); UsingCorrespondence( IterableSubject subject, Correspondence<? super A,? super E> correspondence, Pairer pairer); /** * @throws UnsupportedOperationException always * @deprecated {@link Object#equals(Object)} is not supported on Truth subjects or intermediateclasses. If you are writing a test assertion (actual vs. expected), use methods liks {@link #containsExactlyElementsIn(Iterable)} instead. */ @DoNotCall("UsingCorrespondence.equals() is not supported. Did you mean to call" + " containsExactlyElementsIn(expected) instead of equals(expected)?") @Deprecated @Override public final boolean equals( @Nullable Object o); /** * @throws UnsupportedOperationException always * @deprecated {@link Object#hashCode()} is not supported on Truth types. */ @DoNotCall("UsingCorrespondence.hashCode() is not supported.") @Deprecated @Override public final int hashCode(); /** * @throws UnsupportedOperationException always * @deprecated {@link Object#toString()} is not supported on Truth subjects. */ @Deprecated @DoNotCall("UsingCorrespondence.toString() is not supported.") @Override public final String toString(); /** * Specifies a way to pair up unexpected and missing elements in the message when an assertion fails. For example: <pre> {@code assertThat(actualRecords) .comparingElementsUsing(RECORD_CORRESPONDENCE) .displayingDiffsPairedBy(MyRecord::getId) .containsExactlyElementsIn(expectedRecords);}</pre> <p><b>Important</b>: The {code keyFunction} function must be able to accept both the actual and the unexpected elements, i.e. it must satisfy {@code Function<? super A, ?>} as well as{@code Function<? super E, ?>}. If that constraint is not met then a subsequent method may throw {@link ClassCastException}. Use the two-parameter overload if you need to specify different key functions for the actual and expected elements. <p>On assertions where it makes sense to do so, the elements are paired as follows: they are keyed by {@code keyFunction}, and if an unexpected element and a missing element have the same non-null key then the they are paired up. (Elements with null keys are not paired.) The failure message will show paired elements together, and a diff will be shown if the {@link Correspondence#formatDiff} method returns non-null.<p>The expected elements given in the assertion should be uniquely keyed by {@code keyFunction}. If multiple missing elements have the same key then the pairing will be skipped. <p>Useful key functions will have the property that key equality is less strict than the correspondence, i.e. given {@code actual} and {@code expected} values with keys {@code actualKey} and {@code expectedKey}, if {@code correspondence.compare(actual, expected)} istrue then it is guaranteed that {@code actualKey} is equal to {@code expectedKey}, but there are cases where {@code actualKey} is equal to {@code expectedKey} but {@code correspondence.compare(actual, expected)} is false.<p>If the {@code apply} method on the key function throws an exception then the element willbe treated as if it had a null key and not paired. (The first such exception will be noted in the failure message.) <p>Note that calling this method makes no difference to whether a test passes or fails, it just improves the message if it fails. */ public UsingCorrespondence<A,E> displayingDiffsPairedBy( Function<? super E,?> keyFunction); /** * Specifies a way to pair up unexpected and missing elements in the message when an assertion fails. For example: <pre> {@code assertThat(actualFoos) .comparingElementsUsing(FOO_BAR_CORRESPONDENCE) .displayingDiffsPairedBy(Foo::getId, Bar::getFooId) .containsExactlyElementsIn(expectedBar);}</pre> <p>On assertions where it makes sense to do so, the elements are paired as follows: the unexpected elements are keyed by {@code actualKeyFunction}, the missing elements are keyed by {@code expectedKeyFunction}, and if an unexpected element and a missing element have the same non-null key then the they are paired up. (Elements with null keys are not paired.) The failure message will show paired elements together, and a diff will be shown if the {@link Correspondence#formatDiff} method returns non-null.<p>The expected elements given in the assertion should be uniquely keyed by {@code expectedKeyFunction}. If multiple missing elements have the same key then the pairing will be skipped. <p>Useful key functions will have the property that key equality is less strict than the correspondence, i.e. given {@code actual} and {@code expected} values with keys {@code actualKey} and {@code expectedKey}, if {@code correspondence.compare(actual, expected)} istrue then it is guaranteed that {@code actualKey} is equal to {@code expectedKey}, but there are cases where {@code actualKey} is equal to {@code expectedKey} but {@code correspondence.compare(actual, expected)} is false.<p>If the {@code apply} method on either of the key functions throws an exception then theelement will be treated as if it had a null key and not paired. (The first such exception will be noted in the failure message.) <p>Note that calling this method makes no difference to whether a test passes or fails, it just improves the message if it fails. */ public UsingCorrespondence<A,E> displayingDiffsPairedBy( Function<? super A,?> actualKeyFunction, Function<? super E,?> expectedKeyFunction); /** * Checks that the subject contains at least one element that corresponds to the given expected element. */ public void contains( E expected); /** * Checks that none of the actual elements correspond to the given element. */ public void doesNotContain( E excluded); /** * Checks that subject contains exactly elements that correspond to the expected elements, i.e. that there is a 1:1 mapping between the actual elements and the expected elements where each pair of elements correspond. <p>To also test that the contents appear in the given order, make a call to {@code inOrder()}on the object returned by this method. <p>To test that the iterable contains the elements corresponding to those in an array, prefer {@link #containsExactlyElementsIn(Object[])}. It makes clear that the given array is a list of elements, not an element itself. This helps human readers and avoids a compiler warning. */ @SafeVarargs @CanIgnoreReturnValue public final Ordered containsExactly( @Nullable E @Nullable ... expected); /** * Checks that subject contains exactly elements that correspond to the expected elements, i.e. that there is a 1:1 mapping between the actual elements and the expected elements where each pair of elements correspond. <p>To also test that the contents appear in the given order, make a call to {@code inOrder()}on the object returned by this method. */ @CanIgnoreReturnValue public Ordered containsExactlyElementsIn( @Nullable Iterable<? extends E> expected); /** * Checks that subject contains exactly elements that correspond to the expected elements, i.e. that there is a 1:1 mapping between the actual elements and the expected elements where each pair of elements correspond. <p>To also test that the contents appear in the given order, make a call to {@code inOrder()}on the object returned by this method. */ @CanIgnoreReturnValue @SuppressWarnings("AvoidObjectArrays") public Ordered containsExactlyElementsIn( E @Nullable [] expected); /** * Returns whether the actual and expected iterators have the same number of elements and, when iterated pairwise, every pair of actual and expected values satisfies the correspondence. Returns false if any comparison threw an exception. */ private boolean correspondInOrderExactly( Iterator<? extends A> actual, Iterator<? extends E> expected); /** * Given a list of actual elements and a list of expected elements, finds a many:many mapping between actual and expected elements where a pair of elements maps if it satisfies the correspondence. Returns this mapping as a multimap where the keys are indexes into the actual list and the values are indexes into the expected list. Any exceptions are treated as if the elements did not correspond, and the exception added to the store. */ private ImmutableSetMultimap<Integer,Integer> findCandidateMapping( List<? extends A> actual, List<? extends E> expected, Correspondence.ExceptionStore exceptions); /** * Given a list of actual elements, a list of expected elements, and a many:many mapping between actual and expected elements specified as a multimap of indexes into the actual list to indexes into the expected list, checks that every actual element maps to at least one expected element and vice versa, and fails if this is not the case. Returns whether the assertion failed. */ private boolean failIfCandidateMappingHasMissingOrExtra( List<? extends A> actual, List<? extends E> expected, ImmutableSetMultimap<Integer,Integer> mapping, Correspondence.ExceptionStore exceptions); /** * Given a list of missing elements and a list of extra elements, at least one of which must be non-empty, returns facts describing them. Exceptions from calling {@link Correspondence#formatDiff} are stored in {@code exceptions}. */ private ImmutableList<Fact> describeMissingOrExtra( List<? extends E> missing, List<? extends A> extra, Correspondence.ExceptionStore exceptions); private ImmutableList<Fact> describeMissingOrExtraWithoutPairing( List<? extends E> missing, List<? extends A> extra); private ImmutableList<Fact> describeMissingOrExtraWithPairing( Pairing pairing, Correspondence.ExceptionStore exceptions); private ImmutableList<Fact> formatExtras( String label, E missing, List<? extends A> extras, Correspondence.ExceptionStore exceptions); /** * Returns all the elements of the given list other than those with the given indexes. Assumes that all the given indexes really are valid indexes into the list. */ private <T extends @Nullable Object>List<T> findNotIndexed( List<T> list, Set<Integer> indexes); /** * Given a many:many mapping between actual elements and expected elements, finds a 1:1 mapping which is the subset of that many:many mapping which includes the largest possible number of elements. The input and output mappings are each described as a map or multimap where the keys are indexes into the actual list and the values are indexes into the expected list. If there are multiple possible output mappings tying for the largest possible, this returns an arbitrary one. */ private ImmutableBiMap<Integer,Integer> findMaximalOneToOneMapping( ImmutableMultimap<Integer,Integer> edges); /** * Given a list of actual elements, a list of expected elements, and a 1:1 mapping between actual and expected elements specified as a bimap of indexes into the actual list to indexes into the expected list, checks that every actual element maps to an expected element and vice versa, and fails if this is not the case. Returns whether the assertion failed. */ private boolean failIfOneToOneMappingHasMissingOrExtra( List<? extends A> actual, List<? extends E> expected, BiMap<Integer,Integer> mapping, Correspondence.ExceptionStore exceptions); /** * Checks that the subject contains elements that corresponds to all of the expected elements, i.e. that there is a 1:1 mapping between any subset of the actual elements and the expected elements where each pair of elements correspond. <p>To also test that the contents appear in the given order, make a call to {@code inOrder()}on the object returned by this method. The elements must appear in the given order within the subject, but they are not required to be consecutive. */ @SafeVarargs @CanIgnoreReturnValue public final Ordered containsAtLeast( E first, E second, E @Nullable ... rest); /** * Checks that the subject contains elements that corresponds to all of the expected elements, i.e. that there is a 1:1 mapping between any subset of the actual elements and the expected elements where each pair of elements correspond. <p>To also test that the contents appear in the given order, make a call to {@code inOrder()}on the object returned by this method. The elements must appear in the given order within the subject, but they are not required to be consecutive. */ @CanIgnoreReturnValue public Ordered containsAtLeastElementsIn( Iterable<? extends E> expected); /** * Checks that the subject contains elements that corresponds to all of the expected elements, i.e. that there is a 1:1 mapping between any subset of the actual elements and the expected elements where each pair of elements correspond. <p>To also test that the contents appear in the given order, make a call to {@code inOrder()}on the object returned by this method. The elements must appear in the given order within the subject, but they are not required to be consecutive. */ @CanIgnoreReturnValue @SuppressWarnings("AvoidObjectArrays") public Ordered containsAtLeastElementsIn( E[] expected); /** * Returns whether all the elements of the expected iterator and any subset of the elements of the actual iterator can be paired up in order, such that every pair of actual and expected elements satisfies the correspondence. Returns false if any comparison threw an exception. */ private boolean correspondInOrderAllIn( Iterator<? extends A> actual, Iterator<? extends E> expected); /** * Advances the actual iterator looking for an element which corresponds to the expected element. Returns whether or not it finds one. */ private boolean findCorresponding( Iterator<? extends A> actual, E expectedElement, Correspondence.ExceptionStore exceptions); /** * Given a list of actual elements, a list of expected elements, and a many:many mapping between actual and expected elements specified as a multimap of indexes into an actual list to indexes into the expected list, checks that every expected element maps to at least one actual element, and fails if this is not the case. Actual elements which do not map to any expected elements are ignored. */ private boolean failIfCandidateMappingHasMissing( List<? extends A> actual, List<? extends E> expected, ImmutableSetMultimap<Integer,Integer> mapping, Correspondence.ExceptionStore exceptions); /** * Given a list of missing elements, which must be non-empty, and a list of extra elements, returns a list of facts describing the missing elements, diffing against the extra ones where appropriate. */ private ImmutableList<Fact> describeMissing( List<? extends E> missing, List<? extends A> extra, Correspondence.ExceptionStore exceptions); private ImmutableList<Fact> describeMissingWithoutPairing( List<? extends E> missing); private ImmutableList<Fact> describeMissingWithPairing( Pairing pairing, Correspondence.ExceptionStore exceptions); /** * Given a list of expected elements, and a 1:1 mapping between actual and expected elements specified as a bimap of indexes into an actual list to indexes into the expected list, checks that every expected element maps to an actual element. Actual elements which do not map to any expected elements are ignored. */ private boolean failIfOneToOneMappingHasMissing( List<? extends A> actual, List<? extends E> expected, BiMap<Integer,Integer> mapping, Correspondence.ExceptionStore exceptions); /** * Checks that the subject contains at least one element that corresponds to at least one of the expected elements. */ @SafeVarargs public final void containsAnyOf( E first, E second, E @Nullable ... rest); /** * Checks that the subject contains at least one element that corresponds to at least one of the expected elements. */ public void containsAnyIn( Iterable<? extends E> expected); /** * Checks that the subject contains at least one element that corresponds to at least one of the expected elements. */ @SuppressWarnings("AvoidObjectArrays") public void containsAnyIn( E[] expected); private ImmutableList<Fact> describeAnyMatchesByKey( Pairing pairing, Correspondence.ExceptionStore exceptions); /** * Checks that the subject contains no elements that correspond to any of the given elements. (Duplicates are irrelevant to this test, which fails if any of the subject elements correspond to any of the given elements.) */ @SafeVarargs public final void containsNoneOf( E firstExcluded, E secondExcluded, E @Nullable ... restOfExcluded); /** * Checks that the subject contains no elements that correspond to any of the given elements. (Duplicates are irrelevant to this test, which fails if any of the subject elements correspond to any of the given elements.) */ public void containsNoneIn( Iterable<? extends E> excluded); /** * Checks that the subject contains no elements that correspond to any of the given elements. (Duplicates are irrelevant to this test, which fails if any of the subject elements correspond to any of the given elements.) */ @SuppressWarnings("AvoidObjectArrays") public void containsNoneIn( E[] excluded); @SuppressWarnings("unchecked") private Iterable<A> getCastActual(); /** * A class which knows how to pair the actual and expected elements (see {@link #displayingDiffsPairedBy}). */ private final class Pairer { private final Function<? super A,?> actualKeyFunction; private final Function<? super E,?> expectedKeyFunction; Pairer( Function<? super A,?> actualKeyFunction, Function<? super E,?> expectedKeyFunction); /** * Returns a {@link Pairing} of the given expected and actual values, or {@code null} if theexpected values are not uniquely keyed. */ @Nullable Pairing pair( List<? extends E> expectedValues, List<? extends A> actualValues, Correspondence.ExceptionStore exceptions); List<A> pairOne( E expectedValue, Iterable<? extends A> actualValues, Correspondence.ExceptionStore exceptions); private @Nullable Object actualKey( A actual, Correspondence.ExceptionStore exceptions); private @Nullable Object expectedKey( E expected, Correspondence.ExceptionStore exceptions); } /** * A description of a pairing between expected and actual values. N.B. This is mutable. */ private final class Pairing { /** * Map from keys used in the pairing to the expected value with that key. Iterates in the order the expected values appear in the input. Will never contain null keys. */ private final Map<Object,E> pairedKeysToExpectedValues=new LinkedHashMap<>(); /** * Multimap from keys used in the pairing to the actual values with that key. Keys iterate in the order they first appear in the actual values in the input, and values for each key iterate in the order they appear too. Will never contain null keys. */ private final ListMultimap<Object,A> pairedKeysToActualValues=LinkedListMultimap.create(); /** * List of the expected values not used in the pairing. Iterates in the order they appear in the input. */ private final List<E> unpairedExpectedValues=newArrayList(); /** * List of the actual values not used in the pairing. Iterates in the order they appear in the input. */ private final List<A> unpairedActualValues=newArrayList(); } } }
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-core/src/main/java/com/jarvis/cache/RefreshHandler.java
RefreshHandler
doRefresh
class RefreshHandler { private static final Logger log = LoggerFactory.getLogger(RefreshHandler.class); private static final int REFRESH_MIN_EXPIRE = 120; private static final int ONE_THOUSAND_MS = 1000; /** * 刷新缓存线程池 */ private final ThreadPoolExecutor refreshThreadPool; /** * 正在刷新缓存队列 */ private final ConcurrentHashMap<CacheKeyTO, Byte> refreshing; private final CacheHandler cacheHandler; public RefreshHandler(CacheHandler cacheHandler, AutoLoadConfig config) { this.cacheHandler = cacheHandler; int corePoolSize = config.getRefreshThreadPoolSize();// 线程池的基本大小 int maximumPoolSize = config.getRefreshThreadPoolMaxSize();// 线程池最大大小,线程池允许创建的最大线程数。如果队列满了,并且已创建的线程数小于最大线程数,则线程池会再创建新的线程执行任务。值得注意的是如果使用了无界的任务队列这个参数就没什么效果。 int keepAliveTime = config.getRefreshThreadPoolkeepAliveTime(); TimeUnit unit = TimeUnit.MINUTES; int queueCapacity = config.getRefreshQueueCapacity();// 队列容量 refreshing = new ConcurrentHashMap<CacheKeyTO, Byte>(queueCapacity); LinkedBlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>(queueCapacity); RejectedExecutionHandler rejectedHandler = new RefreshRejectedExecutionHandler(); refreshThreadPool = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, queue, new ThreadFactory() { private final AtomicInteger threadNumber = new AtomicInteger(1); private final String namePrefix = "autoload-cache-RefreshHandler-"; @Override public Thread newThread(Runnable r) { Thread t = new Thread(r, namePrefix + threadNumber.getAndIncrement()); t.setDaemon(true); return t; } }, rejectedHandler); } public void removeTask(CacheKeyTO cacheKey) { refreshing.remove(cacheKey); } public void doRefresh(CacheAopProxyChain pjp, Cache cache, CacheKeyTO cacheKey, CacheWrapper<Object> cacheWrapper) {<FILL_FUNCTION_BODY>} public void shutdown() { refreshThreadPool.shutdownNow(); try { refreshThreadPool.awaitTermination(5, TimeUnit.SECONDS); } catch (InterruptedException e) { e.printStackTrace(); } } class RefreshTask implements Runnable { private final CacheAopProxyChain pjp; private final Cache cache; private final CacheKeyTO cacheKey; private final CacheWrapper<Object> cacheWrapper; private final Object[] arguments; public RefreshTask(CacheAopProxyChain pjp, Cache cache, CacheKeyTO cacheKey, CacheWrapper<Object> cacheWrapper) throws Exception { this.pjp = pjp; this.cache = cache; this.cacheKey = cacheKey; this.cacheWrapper = cacheWrapper; if (cache.argumentsDeepCloneEnable()) { // 进行深度复制(因为是异步执行,防止外部修改参数值) this.arguments = (Object[]) cacheHandler.getCloner().deepCloneMethodArgs(pjp.getMethod(), pjp.getArgs()); } else { this.arguments = pjp.getArgs(); } } @Override public void run() { DataLoader dataLoader; if(cacheHandler.getAutoLoadConfig().isDataLoaderPooled()) { DataLoaderFactory factory = DataLoaderFactory.getInstance(); dataLoader = factory.getDataLoader(); } else { dataLoader = new DataLoader(); } CacheWrapper<Object> newCacheWrapper = null; boolean isFirst = false; try { newCacheWrapper = dataLoader.init(pjp, cacheKey, cache, cacheHandler, arguments).loadData() .getCacheWrapper(); } catch (Throwable ex) { log.error(ex.getMessage(), ex); } finally { // dataLoader 的数据必须在放回对象池之前获取 isFirst = dataLoader.isFirst(); if(cacheHandler.getAutoLoadConfig().isDataLoaderPooled()) { DataLoaderFactory factory = DataLoaderFactory.getInstance(); factory.returnObject(dataLoader); } } if (isFirst) { // 如果数据加载失败,则把旧数据进行续租 if (null == newCacheWrapper && null != cacheWrapper) { int newExpire = cacheWrapper.getExpire() / 2; if (newExpire < 120) { newExpire = 120; } newCacheWrapper = new CacheWrapper<Object>(cacheWrapper.getCacheObject(), newExpire); } try { if (null != newCacheWrapper) { cacheHandler.writeCache(pjp, arguments, cache, cacheKey, newCacheWrapper); } } catch (Throwable e) { log.error(e.getMessage(), e); } } refreshing.remove(cacheKey); } public CacheKeyTO getCacheKey() { return cacheKey; } } class RefreshRejectedExecutionHandler implements RejectedExecutionHandler { @Override public void rejectedExecution(Runnable r, ThreadPoolExecutor e) { if (!e.isShutdown()) { Runnable last = e.getQueue().poll(); if (last instanceof RefreshTask) { RefreshTask lastTask = (RefreshTask) last; refreshing.remove(lastTask.getCacheKey()); } e.execute(r); } } } }
int expire = cacheWrapper.getExpire(); if (expire < REFRESH_MIN_EXPIRE) {// 如果过期时间太小了,就不允许自动加载,避免加载过于频繁,影响系统稳定性 return; } // 计算超时时间 int alarmTime = cache.alarmTime(); long timeout; if (alarmTime > 0 && alarmTime < expire) { timeout = expire - alarmTime; } else { if (expire >= 600) { timeout = expire - REFRESH_MIN_EXPIRE; } else { timeout = expire - 60; } } if ((System.currentTimeMillis() - cacheWrapper.getLastLoadTime()) < (timeout * ONE_THOUSAND_MS)) { return; } Byte tmpByte = refreshing.get(cacheKey); // 如果有正在刷新的请求,则不处理 if (null != tmpByte) { return; } tmpByte = 1; if (null == refreshing.putIfAbsent(cacheKey, tmpByte)) { try { refreshThreadPool.execute(new RefreshTask(pjp, cache, cacheKey, cacheWrapper)); } catch (Exception e) { log.error(e.getMessage(), e); } }
1,526
349
1,875
docker-java_docker-java
docker-java/docker-java-core/src/main/java/com/github/dockerjava/core/exec/PullImageCmdExec.java
PullImageCmdExec
execute0
class PullImageCmdExec extends AbstrAsyncDockerCmdExec<PullImageCmd, PullResponseItem> implements PullImageCmd.Exec { private static final Logger LOGGER = LoggerFactory.getLogger(PullImageCmdExec.class); public PullImageCmdExec(WebTarget baseResource, DockerClientConfig dockerClientConfig) { super(baseResource, dockerClientConfig); } @Override protected Void execute0(PullImageCmd command, ResultCallback<PullResponseItem> resultCallback) {<FILL_FUNCTION_BODY>} }
WebTarget webResource = getBaseResource().path("/images/create").queryParam("tag", command.getTag()) .queryParam("fromImage", command.getRepository()).queryParam("registry", command.getRegistry()); if (command.getPlatform() != null) { webResource = webResource.queryParam("platform", command.getPlatform()); } LOGGER.trace("POST: {}", webResource); resourceWithOptionalAuthConfig(command.getAuthConfig(), webResource.request()) .accept(MediaType.APPLICATION_OCTET_STREAM) .post(null, new TypeReference<PullResponseItem>() { }, resultCallback); return null;
145
176
321
pmd_pmd
pmd/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/NioTextFile.java
NioTextFile
writeContents
class NioTextFile extends BaseCloseable implements TextFile { private final Path path; private final Charset charset; private final LanguageVersion languageVersion; private final FileId fileId; private boolean readOnly; NioTextFile(Path path, @Nullable FileId parentFsPath, Charset charset, LanguageVersion languageVersion, boolean readOnly) { AssertionUtil.requireParamNotNull("path", path); AssertionUtil.requireParamNotNull("charset", charset); AssertionUtil.requireParamNotNull("language version", languageVersion); this.readOnly = readOnly; this.path = path; this.charset = charset; this.languageVersion = languageVersion; this.fileId = FileId.fromPath(path, parentFsPath); } @Override public @NonNull LanguageVersion getLanguageVersion() { return languageVersion; } @Override public FileId getFileId() { return fileId; } @Override public boolean isReadOnly() { return readOnly || !Files.isWritable(path); } @Override public void writeContents(TextFileContent content) throws IOException {<FILL_FUNCTION_BODY>} @Override public TextFileContent readContents() throws IOException { ensureOpen(); if (!Files.isRegularFile(path)) { throw new IOException("Not a regular file: " + path); } return TextFileContent.fromInputStream(Files.newInputStream(path), charset); } @Override protected void doClose() throws IOException { // nothing to do. } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } @SuppressWarnings("PMD.CloseResource") NioTextFile that = (NioTextFile) o; return path.equals(that.path); } @Override public int hashCode() { return path.hashCode(); } @Override public String toString() { return "NioTextFile[charset=" + charset + ", path=" + path + ']'; } }
ensureOpen(); if (isReadOnly()) { throw new ReadOnlyFileException(this); } try (BufferedWriter bw = Files.newBufferedWriter(path, charset)) { if (TextFileContent.NORMALIZED_LINE_TERM.equals(content.getLineTerminator())) { content.getNormalizedText().writeFully(bw); } else { for (Chars line : content.getNormalizedText().lines()) { line.writeFully(bw); bw.write(content.getLineTerminator()); } } }
595
157
752
public abstract class BaseCloseable implements Closeable { protected boolean open=true; protected final void ensureOpen() throws IOException; protected final void ensureOpenIllegalState() throws IllegalStateException; /** * Noop if called several times. Thread-safe. */ @Override public void close() throws IOException; /** * Called at most once. */ protected abstract void doClose() throws IOException ; }
spring-cloud_spring-cloud-gateway
spring-cloud-gateway/spring-cloud-gateway-server/src/main/java/org/springframework/cloud/gateway/config/GatewayReactiveOAuth2AutoConfiguration.java
GatewayReactiveOAuth2AutoConfiguration
gatewayReactiveOAuth2AuthorizedClientManager
class GatewayReactiveOAuth2AutoConfiguration { @Bean @ConditionalOnMissingBean @ConditionalOnBean(ReactiveClientRegistrationRepository.class) public ReactiveOAuth2AuthorizedClientManager gatewayReactiveOAuth2AuthorizedClientManager( ReactiveClientRegistrationRepository clientRegistrationRepository, ServerOAuth2AuthorizedClientRepository authorizedClientRepository) {<FILL_FUNCTION_BODY>} }
ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder .builder().authorizationCode().refreshToken().build(); DefaultReactiveOAuth2AuthorizedClientManager authorizedClientManager = new DefaultReactiveOAuth2AuthorizedClientManager( clientRegistrationRepository, authorizedClientRepository); authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider); return authorizedClientManager;
106
111
217
elunez_eladmin
eladmin/eladmin-system/src/main/java/me/zhengjie/modules/mnt/domain/ServerDeploy.java
ServerDeploy
equals
class ServerDeploy extends BaseEntity implements Serializable { @Id @Column(name = "server_id") @ApiModelProperty(value = "ID", hidden = true) @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @ApiModelProperty(value = "服务器名称") private String name; @ApiModelProperty(value = "IP") private String ip; @ApiModelProperty(value = "端口") private Integer port; @ApiModelProperty(value = "账号") private String account; @ApiModelProperty(value = "密码") private String password; public void copy(ServerDeploy source){ BeanUtil.copyProperties(source,this, CopyOptions.create().setIgnoreNullValue(true)); } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(id, name); } }
if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ServerDeploy that = (ServerDeploy) o; return Objects.equals(id, that.id) && Objects.equals(name, that.name);
265
89
354
/** * 通用字段, is_del 根据需求自行添加 * @author Zheng Jie * @Date 2019年10月24日20:46:32 */ @Getter @Setter @MappedSuperclass @EntityListeners(AuditingEntityListener.class) public class BaseEntity implements Serializable { @CreatedBy @Column(name="create_by",updatable=false) @ApiModelProperty(value="创建人",hidden=true) private String createBy; @LastModifiedBy @Column(name="update_by") @ApiModelProperty(value="更新人",hidden=true) private String updateBy; @CreationTimestamp @Column(name="create_time",updatable=false) @ApiModelProperty(value="创建时间",hidden=true) private Timestamp createTime; @UpdateTimestamp @Column(name="update_time") @ApiModelProperty(value="更新时间",hidden=true) private Timestamp updateTime; public @interface Create {} public @interface Update {} @Override public String toString(); }
elunez_eladmin
eladmin/eladmin-system/src/main/java/me/zhengjie/modules/system/rest/VerifyController.java
VerifyController
resetPass
class VerifyController { private final VerifyService verificationCodeService; private final EmailService emailService; @PostMapping(value = "/resetEmail") @ApiOperation("重置邮箱,发送验证码") public ResponseEntity<Object> resetEmail(@RequestParam String email){ EmailVo emailVo = verificationCodeService.sendEmail(email, CodeEnum.EMAIL_RESET_EMAIL_CODE.getKey()); emailService.send(emailVo,emailService.find()); return new ResponseEntity<>(HttpStatus.OK); } @PostMapping(value = "/email/resetPass") @ApiOperation("重置密码,发送验证码") public ResponseEntity<Object> resetPass(@RequestParam String email){<FILL_FUNCTION_BODY>} @GetMapping(value = "/validated") @ApiOperation("验证码验证") public ResponseEntity<Object> validated(@RequestParam String email, @RequestParam String code, @RequestParam Integer codeBi){ CodeBiEnum biEnum = CodeBiEnum.find(codeBi); switch (Objects.requireNonNull(biEnum)){ case ONE: verificationCodeService.validated(CodeEnum.EMAIL_RESET_EMAIL_CODE.getKey() + email ,code); break; case TWO: verificationCodeService.validated(CodeEnum.EMAIL_RESET_PWD_CODE.getKey() + email ,code); break; default: break; } return new ResponseEntity<>(HttpStatus.OK); } }
EmailVo emailVo = verificationCodeService.sendEmail(email, CodeEnum.EMAIL_RESET_PWD_CODE.getKey()); emailService.send(emailVo,emailService.find()); return new ResponseEntity<>(HttpStatus.OK);
400
68
468
elunez_eladmin
eladmin/eladmin-system/src/main/java/me/zhengjie/config/ConfigurerAdapter.java
ConfigurerAdapter
addResourceHandlers
class ConfigurerAdapter implements WebMvcConfigurer { /** 文件配置 */ private final FileProperties properties; public ConfigurerAdapter(FileProperties properties) { this.properties = properties; } @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials(true); config.addAllowedOriginPattern("*"); config.addAllowedHeader("*"); config.addAllowedMethod("*"); source.registerCorsConfiguration("/**", config); return new CorsFilter(source); } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) {<FILL_FUNCTION_BODY>} @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { // 使用 fastjson 序列化,会导致 @JsonIgnore 失效,可以使用 @JSONField(serialize = false) 替换 FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter(); List<MediaType> supportMediaTypeList = new ArrayList<>(); supportMediaTypeList.add(MediaType.APPLICATION_JSON); FastJsonConfig config = new FastJsonConfig(); config.setDateFormat("yyyy-MM-dd HH:mm:ss"); config.setSerializerFeatures(SerializerFeature.DisableCircularReferenceDetect); converter.setFastJsonConfig(config); converter.setSupportedMediaTypes(supportMediaTypeList); converter.setDefaultCharset(StandardCharsets.UTF_8); converters.add(converter); } }
FileProperties.ElPath path = properties.getPath(); String avatarUtl = "file:" + path.getAvatar().replace("\\","/"); String pathUtl = "file:" + path.getPath().replace("\\","/"); registry.addResourceHandler("/avatar/**").addResourceLocations(avatarUtl).setCachePeriod(0); registry.addResourceHandler("/file/**").addResourceLocations(pathUtl).setCachePeriod(0); registry.addResourceHandler("/**").addResourceLocations("classpath:/META-INF/resources/").setCachePeriod(0);
428
150
578
logfellow_logstash-logback-encoder
logstash-logback-encoder/src/main/java/net/logstash/logback/composite/LogstashVersionJsonProvider.java
LogstashVersionJsonProvider
writeTo
class LogstashVersionJsonProvider<Event extends DeferredProcessingAware> extends AbstractFieldJsonProvider<Event> implements FieldNamesAware<LogstashCommonFieldNames> { public static final String FIELD_VERSION = "@version"; public static final String DEFAULT_VERSION = "1"; private String version; private long versionAsInteger; /** * When false (the default), the version will be written as a string value. * When true, the version will be written as a numeric integer value. */ private boolean writeAsInteger; public LogstashVersionJsonProvider() { setFieldName(FIELD_VERSION); setVersion(DEFAULT_VERSION); } @Override public void writeTo(JsonGenerator generator, Event event) throws IOException {<FILL_FUNCTION_BODY>} @Override public void setFieldNames(LogstashCommonFieldNames fieldNames) { setFieldName(fieldNames.getVersion()); } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; if (writeAsInteger) { this.versionAsInteger = Integer.parseInt(version); } } public boolean isWriteAsInteger() { return writeAsInteger; } public void setWriteAsInteger(boolean writeAsInteger) { this.writeAsInteger = writeAsInteger; if (writeAsInteger) { this.versionAsInteger = Integer.parseInt(version); } } }
if (writeAsInteger) { JsonWritingUtils.writeNumberField(generator, getFieldName(), versionAsInteger); } else { JsonWritingUtils.writeStringField(generator, getFieldName(), version); }
403
60
463
ainilili_ratel
ratel/landlords-client/src/main/java/org/nico/ratel/landlords/client/event/ClientEventListener_CODE_SHOW_OPTIONS_PVP.java
ClientEventListener_CODE_SHOW_OPTIONS_PVP
call
class ClientEventListener_CODE_SHOW_OPTIONS_PVP extends ClientEventListener { @Override public void call(Channel channel, String data) {<FILL_FUNCTION_BODY>} private void parseInvalid(Channel channel, String data) { SimplePrinter.printNotice("Invalid options, please choose again:"); call(channel, data); } private void handleJoinRoom(Channel channel, String data) { handleJoinRoom(channel, data, false); } private void handleJoinRoom(Channel channel, String data, Boolean watchMode) { String notice = String.format("Please enter the room id you want to %s (enter [back|b] return options list)", watchMode ? "spectate" : "join"); SimplePrinter.printNotice(notice); String line = SimpleWriter.write(User.INSTANCE.getNickname(), "roomid"); if (line == null) { parseInvalid(channel, data); return; } if (line.equalsIgnoreCase("BACK") || line.equalsIgnoreCase("b")) { call(channel, data); return; } int option = OptionsUtils.getOptions(line); if (option < 1) { parseInvalid(channel, data); return; } pushToServer(channel, watchMode? ServerEventCode.CODE_GAME_WATCH : ServerEventCode.CODE_ROOM_JOIN, String.valueOf(option)); } }
SimplePrinter.printNotice("PVP: "); SimplePrinter.printNotice("1. Create Room"); SimplePrinter.printNotice("2. Room List"); SimplePrinter.printNotice("3. Join Room"); SimplePrinter.printNotice("4. Spectate Game"); SimplePrinter.printNotice("Please select an option above (enter [back|b] to return to options list)"); String line = SimpleWriter.write(User.INSTANCE.getNickname(), "pvp"); if (line == null) { SimplePrinter.printNotice("Invalid options, please choose again:"); call(channel, data); return; } if (line.equalsIgnoreCase("BACK") || line.equalsIgnoreCase("b")) { get(ClientEventCode.CODE_SHOW_OPTIONS).call(channel, data); return; } int choose = OptionsUtils.getOptions(line); switch (choose) { case 1: pushToServer(channel, ServerEventCode.CODE_ROOM_CREATE, null); break; case 2: pushToServer(channel, ServerEventCode.CODE_GET_ROOMS, null); break; case 3: handleJoinRoom(channel, data); break; case 4: handleJoinRoom(channel, data, true); break; default: SimplePrinter.printNotice("Invalid option, please choose again:"); call(channel, data); }
375
398
773
public abstract class ClientEventListener { public abstract void call( Channel channel, String data); public final static Map<ClientEventCode,ClientEventListener> LISTENER_MAP=new HashMap<>(); private final static String LISTENER_PREFIX="org.nico.ratel.landlords.client.event.ClientEventListener_"; protected static List<Poker> lastPokers=null; protected static String lastSellClientNickname=null; protected static String lastSellClientType=null; protected static void initLastSellInfo(); @SuppressWarnings("unchecked") public static ClientEventListener get( ClientEventCode code); protected ChannelFuture pushToServer( Channel channel, ServerEventCode code, String datas); protected ChannelFuture pushToServer( Channel channel, ServerEventCode code); }
jeecgboot_jeecg-boot
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/aspect/PermissionDataAspect.java
PermissionDataAspect
getJgAuthRequsetPath
class PermissionDataAspect { @Lazy @Autowired private CommonAPI commonApi; private static final String SPOT_DO = ".do"; @Pointcut("@annotation(org.jeecg.common.aspect.annotation.PermissionData)") public void pointCut() { } @Around("pointCut()") public Object arround(ProceedingJoinPoint point) throws Throwable{ HttpServletRequest request = SpringContextUtils.getHttpServletRequest(); MethodSignature signature = (MethodSignature) point.getSignature(); Method method = signature.getMethod(); PermissionData pd = method.getAnnotation(PermissionData.class); String component = pd.pageComponent(); String requestMethod = request.getMethod(); String requestPath = request.getRequestURI().substring(request.getContextPath().length()); requestPath = filterUrl(requestPath); //update-begin-author:taoyan date:20211027 for:JTC-132【online报表权限】online报表带参数的菜单配置数据权限无效 //先判断是否online报表请求 if(requestPath.indexOf(UrlMatchEnum.CGREPORT_DATA.getMatchUrl())>=0 || requestPath.indexOf(UrlMatchEnum.CGREPORT_ONLY_DATA.getMatchUrl())>=0){ // 获取地址栏参数 String urlParamString = request.getParameter(CommonConstant.ONL_REP_URL_PARAM_STR); if(oConvertUtils.isNotEmpty(urlParamString)){ requestPath+="?"+urlParamString; } } //update-end-author:taoyan date:20211027 for:JTC-132【online报表权限】online报表带参数的菜单配置数据权限无效 log.debug("拦截请求 >> {} ; 请求类型 >> {} . ", requestPath, requestMethod); String username = JwtUtil.getUserNameByToken(request); //查询数据权限信息 //TODO 微服务情况下也得支持缓存机制 List<SysPermissionDataRuleModel> dataRules = commonApi.queryPermissionDataRule(component, requestPath, username); if(dataRules!=null && dataRules.size()>0) { //临时存储 JeecgDataAutorUtils.installDataSearchConditon(request, dataRules); //TODO 微服务情况下也得支持缓存机制 SysUserCacheInfo userinfo = commonApi.getCacheUser(username); JeecgDataAutorUtils.installUserInfo(request, userinfo); } return point.proceed(); } private String filterUrl(String requestPath){ String url = ""; if(oConvertUtils.isNotEmpty(requestPath)){ url = requestPath.replace("\\", "/"); url = url.replace("//", "/"); if(url.indexOf(SymbolConstant.DOUBLE_SLASH)>=0){ url = filterUrl(url); } /*if(url.startsWith("/")){ url=url.substring(1); }*/ } return url; } /** * 获取请求地址 * @param request * @return */ @Deprecated private String getJgAuthRequsetPath(HttpServletRequest request) {<FILL_FUNCTION_BODY>} @Deprecated private boolean moHuContain(List<String> list,String key){ for(String str : list){ if(key.contains(str)){ return true; } } return false; } }
String queryString = request.getQueryString(); String requestPath = request.getRequestURI(); if(oConvertUtils.isNotEmpty(queryString)){ requestPath += "?" + queryString; } // 去掉其他参数(保留一个参数) 例如:loginController.do?login if (requestPath.indexOf(SymbolConstant.AND) > -1) { requestPath = requestPath.substring(0, requestPath.indexOf("&")); } if(requestPath.indexOf(QueryRuleEnum.EQ.getValue())!=-1){ if(requestPath.indexOf(SPOT_DO)!=-1){ requestPath = requestPath.substring(0,requestPath.indexOf(".do")+3); }else{ requestPath = requestPath.substring(0,requestPath.indexOf("?")); } } // 去掉项目路径 requestPath = requestPath.substring(request.getContextPath().length() + 1); return filterUrl(requestPath);
935
255
1,190
jeecgboot_jeecg-boot
jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/config/jimureport/JimuReportTokenService.java
JimuReportTokenService
getUserInfo
class JimuReportTokenService implements JmReportTokenServiceI { @Autowired private SysBaseApiImpl sysBaseApi; @Autowired @Lazy private RedisUtil redisUtil; @Override public String getToken(HttpServletRequest request) { return TokenUtils.getTokenByRequest(request); } @Override public String getUsername(String token) { return JwtUtil.getUsername(token); } @Override public String[] getRoles(String token) { String username = JwtUtil.getUsername(token); Set roles = sysBaseApi.getUserRoleSet(username); if(CollectionUtils.isEmpty(roles)){ return null; } return (String[]) roles.toArray(new String[roles.size()]); } @Override public Boolean verifyToken(String token) { return TokenUtils.verifyToken(token, sysBaseApi, redisUtil); } @Override public Map<String, Object> getUserInfo(String token) {<FILL_FUNCTION_BODY>} }
Map<String, Object> map = new HashMap(5); String username = JwtUtil.getUsername(token); //此处通过token只能拿到一个信息 用户账号 后面的就是根据账号获取其他信息 查询数据或是走redis 用户根据自身业务可自定义 SysUserCacheInfo userInfo = null; try { userInfo = sysBaseApi.getCacheUser(username); } catch (Exception e) { log.error("获取用户信息异常:"+ e.getMessage()); return map; } //设置账号名 map.put(SYS_USER_CODE, userInfo.getSysUserCode()); //设置部门编码 map.put(SYS_ORG_CODE, userInfo.getSysOrgCode()); // 将所有信息存放至map 解析sql/api会根据map的键值解析 return map;
291
231
522
jeecgboot_jeecg-boot
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/config/DruidConfig.java
DruidConfig
removeDruidAdFilter
class DruidConfig { /** * 带有广告的common.js全路径,druid-1.1.14 */ private static final String FILE_PATH = "support/http/resources/js/common.js"; /** * 原始脚本,触发构建广告的语句 */ private static final String ORIGIN_JS = "this.buildFooter();"; /** * 替换后的脚本 */ private static final String NEW_JS = "//this.buildFooter();"; /** * 去除Druid监控页面的广告 * * @param properties DruidStatProperties属性集合 * @return {@link FilterRegistrationBean} */ @Bean @ConditionalOnWebApplication @ConditionalOnProperty(name = "spring.datasource.druid.stat-view-servlet.enabled", havingValue = "true") public FilterRegistrationBean<RemoveAdFilter> removeDruidAdFilter( DruidStatProperties properties) throws IOException {<FILL_FUNCTION_BODY>} /** * 删除druid的广告过滤器 * * @author BBF */ private class RemoveAdFilter implements Filter { private final String newJs; public RemoveAdFilter(String newJs) { this.newJs = newJs; } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { chain.doFilter(request, response); // 重置缓冲区,响应头不会被重置 response.resetBuffer(); response.getWriter().write(newJs); } } }
// 获取web监控页面的参数 DruidStatProperties.StatViewServlet config = properties.getStatViewServlet(); // 提取common.js的配置路径 String pattern = config.getUrlPattern() != null ? config.getUrlPattern() : "/druid/*"; String commonJsPattern = pattern.replaceAll("\\*", "js/common.js"); // 获取common.js String text = Utils.readFromResource(FILE_PATH); // 屏蔽 this.buildFooter(); 不构建广告 final String newJs = text.replace(ORIGIN_JS, NEW_JS); FilterRegistrationBean<RemoveAdFilter> registration = new FilterRegistrationBean<>(); registration.setFilter(new RemoveAdFilter(newJs)); registration.addUrlPatterns(commonJsPattern); return registration;
449
215
664
PlayEdu_PlayEdu
PlayEdu/playedu-api/src/main/java/xyz/playedu/api/controller/backend/CourseAttachmentController.java
CourseAttachmentController
store
class CourseAttachmentController { @Autowired private CourseAttachmentService attachmentService; @BackendPermission(slug = BPermissionConstant.COURSE) @PostMapping("/create") @Log(title = "线上课-附件-新建", businessType = BusinessTypeConstant.INSERT) public JsonResponse store( @PathVariable(name = "courseId") Integer courseId, @RequestBody @Validated CourseAttachmentRequest req) throws NotFoundException {<FILL_FUNCTION_BODY>} @BackendPermission(slug = BPermissionConstant.COURSE) @PostMapping("/create-batch") @Transactional @Log(title = "线上课-附件-批量新建", businessType = BusinessTypeConstant.INSERT) public JsonResponse storeMulti( @PathVariable(name = "courseId") Integer courseId, @RequestBody @Validated CourseAttachmentMultiRequest req) { if (req.getAttachments().size() == 0) { return JsonResponse.error("参数为空"); } List<Integer> existsRids = attachmentService.getRidsByCourseId(courseId); List<CourseAttachment> attachments = new ArrayList<>(); Date now = new Date(); for (CourseAttachmentMultiRequest.AttachmentItem item : req.getAttachments()) { if (existsRids.contains(item.getRid())) { return JsonResponse.error("附件《" + item.getTitle() + "》已存在"); } attachments.add( new CourseAttachment() { { setCourseId(courseId); setSort(item.getSort()); setType(item.getType()); setRid(item.getRid()); setTitle(item.getTitle()); setCreatedAt(now); } }); } attachmentService.saveBatch(attachments); return JsonResponse.success(); } @BackendPermission(slug = BPermissionConstant.COURSE) @GetMapping("/{id}") @Log(title = "线上课-附件-编辑", businessType = BusinessTypeConstant.GET) public JsonResponse edit( @PathVariable(name = "courseId") Integer courseId, @PathVariable(name = "id") Integer id) throws NotFoundException { CourseAttachment courseAttachment = attachmentService.findOrFail(id, courseId); return JsonResponse.data(courseAttachment); } @BackendPermission(slug = BPermissionConstant.COURSE) @PutMapping("/{id}") @Log(title = "线上课-附件-编辑", businessType = BusinessTypeConstant.UPDATE) public JsonResponse update( @PathVariable(name = "courseId") Integer courseId, @PathVariable(name = "id") Integer id, @RequestBody @Validated CourseAttachmentRequest req) throws NotFoundException { CourseAttachment courseAttachment = attachmentService.findOrFail(id, courseId); attachmentService.update(courseAttachment, req.getSort(), req.getTitle()); return JsonResponse.success(); } @BackendPermission(slug = BPermissionConstant.COURSE) @DeleteMapping("/{id}") @Log(title = "线上课-附件-删除", businessType = BusinessTypeConstant.DELETE) public JsonResponse destroy( @PathVariable(name = "courseId") Integer courseId, @PathVariable(name = "id") Integer id) throws NotFoundException { CourseAttachment courseAttachment = attachmentService.findOrFail(id, courseId); attachmentService.removeById(courseAttachment.getId()); return JsonResponse.success(); } @PutMapping("/update/sort") @Log(title = "线上课-附件-排序调整", businessType = BusinessTypeConstant.UPDATE) public JsonResponse updateSort( @PathVariable(name = "courseId") Integer courseId, @RequestBody @Validated CourseAttachmentSortRequest req) { attachmentService.updateSort(req.getIds(), courseId); return JsonResponse.success(); } }
// 附件类型校验 String type = req.getType(); if (!BackendConstant.RESOURCE_TYPE_ATTACHMENT.contains(type)) { return JsonResponse.error("附件类型不支持"); } // 课时重复添加校验 List<Integer> existsRids = attachmentService.getRidsByCourseId(courseId); if (existsRids != null) { if (existsRids.contains(req.getRid())) { return JsonResponse.error("附件已存在"); } } CourseAttachment courseAttachment = attachmentService.create( courseId, req.getSort(), req.getTitle(), type, req.getRid()); return JsonResponse.success();
1,048
195
1,243
pmd_pmd
pmd/pmd-core/src/main/java/net/sourceforge/pmd/lang/metrics/MetricsUtil.java
MetricsUtil
computeStatistics
class MetricsUtil { static final String NULL_KEY_MESSAGE = "The metric key must not be null"; static final String NULL_OPTIONS_MESSAGE = "The metric options must not be null"; static final String NULL_NODE_MESSAGE = "The node must not be null"; private MetricsUtil() { // util class } public static boolean supportsAll(Node node, Metric<?, ?>... metrics) { for (Metric<?, ?> metric : metrics) { if (!metric.supports(node)) { return false; } } return true; } /** * Computes statistics for the results of a metric over a sequence of nodes. * * @param key The metric to compute * @param ops List of nodes for which to compute the metric * * @return Statistics for the value of the metric over all the nodes */ public static <O extends Node> DoubleSummaryStatistics computeStatistics(Metric<? super O, ?> key, Iterable<? extends O> ops) { return computeStatistics(key, ops, MetricOptions.emptyOptions()); } /** * Computes statistics for the results of a metric over a sequence of nodes. * * @param key The metric to compute * @param ops List of nodes for which to compute the metric * @param options The options of the metric * * @return Statistics for the value of the metric over all the nodes */ public static <O extends Node> DoubleSummaryStatistics computeStatistics(Metric<? super O, ?> key, Iterable<? extends O> ops, MetricOptions options) {<FILL_FUNCTION_BODY>} /** * Computes a metric identified by its code on a node, with the default options. * * @param key The key identifying the metric to be computed * @param node The node on which to compute the metric * * @return The value of the metric, or {@code Double.NaN} if the value couldn't be computed * * @throws IllegalArgumentException If the metric does not support the given node */ public static <N extends Node, R extends Number> R computeMetric(Metric<? super N, R> key, N node) { return computeMetric(key, node, MetricOptions.emptyOptions()); } /** * Computes a metric identified by its code on a node, possibly * selecting a variant with the {@code options} parameter. * * <p>Note that contrary to the previous behaviour, this method * throws an exception if the metric does not support the node. * * @param key The key identifying the metric to be computed * @param node The node on which to compute the metric * @param options The options of the metric * * @return The value of the metric * * @throws IllegalArgumentException If the metric does not support the given node */ public static <N extends Node, R extends Number> R computeMetric(Metric<? super N, R> key, N node, MetricOptions options) { return computeMetric(key, node, options, false); } /** * Computes a metric identified by its code on a node, possibly * selecting a variant with the {@code options} parameter. * * <p>Note that contrary to the previous behaviour, this method * throws an exception if the metric does not support the node. * * @param key The key identifying the metric to be computed * @param node The node on which to compute the metric * @param options The options of the metric * @param forceRecompute Force recomputation of the result * * @return The value of the metric * * @throws IllegalArgumentException If the metric does not support the given node */ public static <N extends Node, R extends Number> R computeMetric(Metric<? super N, R> key, N node, MetricOptions options, boolean forceRecompute) { Objects.requireNonNull(key, NULL_KEY_MESSAGE); Objects.requireNonNull(options, NULL_OPTIONS_MESSAGE); Objects.requireNonNull(node, NULL_NODE_MESSAGE); if (!key.supports(node)) { throw new IllegalArgumentException(key + " cannot be computed on " + node); } ParameterizedMetricKey<? super N, R> paramKey = ParameterizedMetricKey.getInstance(key, options); R prev = node.getUserMap().get(paramKey); if (!forceRecompute && prev != null) { return prev; } R val = key.computeFor(node, options); node.getUserMap().set(paramKey, val); return val; } }
Objects.requireNonNull(key, NULL_KEY_MESSAGE); Objects.requireNonNull(options, NULL_OPTIONS_MESSAGE); Objects.requireNonNull(ops, NULL_NODE_MESSAGE); return StreamSupport.stream(ops.spliterator(), false) .filter(key::supports) .collect(Collectors.summarizingDouble(op -> computeMetric(key, op, options).doubleValue()));
1,218
118
1,336
mapstruct_mapstruct
mapstruct/processor/src/main/java/org/mapstruct/ap/internal/model/AbstractBaseBuilder.java
AbstractBaseBuilder
createForgedAssignment
class AbstractBaseBuilder<B extends AbstractBaseBuilder<B>> { protected B myself; protected MappingBuilderContext ctx; protected Method method; AbstractBaseBuilder(Class<B> selfType) { myself = selfType.cast( this ); } public B mappingContext(MappingBuilderContext mappingContext) { this.ctx = mappingContext; return myself; } public B method(Method sourceMethod) { this.method = sourceMethod; return myself; } /** * Checks if MapStruct is allowed to generate an automatic sub-mapping between {@code sourceType} and @{code * targetType}. * This will evaluate to {@code true}, when: * <li> * <ul>Automatic sub-mapping methods generation is not disabled</ul> * <ul>MapStruct is allowed to generate an automatic sub-mapping between the {@code sourceType} and {@code * targetType}</ul> * </li> * * @param sourceType candidate source type to generate a sub-mapping from * @param targetType candidate target type to generate a sub-mapping for * * @return {@code true} if MapStruct can try to generate an automatic sub-mapping between the types. */ boolean canGenerateAutoSubMappingBetween(Type sourceType, Type targetType) { return !isDisableSubMappingMethodsGeneration() && ctx.canGenerateAutoSubMappingBetween( sourceType, targetType ); } private boolean isDisableSubMappingMethodsGeneration() { return method.getOptions().getMapper().isDisableSubMappingMethodsGeneration(); } /** * Creates a forged assignment from the provided {@code sourceRHS} and {@code forgedMethod}. If a mapping method * for the {@code forgedMethod} already exists, then this method used for the assignment. * * @param sourceRHS that needs to be used for the assignment * @param forgedMethod the forged method for which we want to create an {@link Assignment} * * @return See above */ Assignment createForgedAssignment(SourceRHS sourceRHS, BuilderType builderType, ForgedMethod forgedMethod) { if ( ctx.getForgedMethodsUnderCreation().containsKey( forgedMethod ) ) { return createAssignment( sourceRHS, ctx.getForgedMethodsUnderCreation().get( forgedMethod ) ); } else { ctx.getForgedMethodsUnderCreation().put( forgedMethod, forgedMethod ); } MappingMethod forgedMappingMethod; if ( MappingMethodUtils.isEnumMapping( forgedMethod ) ) { forgedMappingMethod = new ValueMappingMethod.Builder() .method( forgedMethod ) .valueMappings( forgedMethod.getOptions().getValueMappings() ) .enumMapping( forgedMethod.getOptions().getEnumMappingOptions() ) .mappingContext( ctx ) .build(); } else { forgedMappingMethod = new BeanMappingMethod.Builder() .forgedMethod( forgedMethod ) .returnTypeBuilder( builderType ) .mappingContext( ctx ) .build(); } Assignment forgedAssignment = createForgedAssignment( sourceRHS, forgedMethod, forgedMappingMethod ); ctx.getForgedMethodsUnderCreation().remove( forgedMethod ); return forgedAssignment; } Assignment createForgedAssignment(SourceRHS source, ForgedMethod methodRef, MappingMethod mappingMethod) {<FILL_FUNCTION_BODY>} private Assignment createAssignment(SourceRHS source, ForgedMethod methodRef) { Assignment assignment = MethodReference.forForgedMethod( methodRef, ParameterBinding.fromParameters( methodRef.getParameters() ) ); assignment.setAssignment( source ); return assignment; } /** * Reports that a mapping could not be created. * * @param method the method that should be mapped * @param sourceErrorMessagePart the error message part for the source * @param sourceType the source type of the mapping * @param targetType the type of the target mapping * @param targetPropertyName the name of the target property */ void reportCannotCreateMapping(Method method, String sourceErrorMessagePart, Type sourceType, Type targetType, String targetPropertyName) { ctx.getMessager().printMessage( method.getExecutable(), Message.PROPERTYMAPPING_MAPPING_NOT_FOUND, sourceErrorMessagePart, targetType.describe(), targetPropertyName, targetType.describe(), sourceType.describe() ); } /** * Reports that a mapping could not be created. * * @param method the method that should be mapped * @param posHint hint which @Mapping is the culprit * @param sourceErrorMessagePart the error message part for the source * @param sourceType the source type of the mapping * @param targetType the type of the target mapping * @param targetPropertyName the name of the target property */ void reportCannotCreateMapping(Method method, AnnotationMirror posHint, String sourceErrorMessagePart, Type sourceType, Type targetType, String targetPropertyName) { ctx.getMessager().printMessage( method.getExecutable(), posHint, Message.PROPERTYMAPPING_MAPPING_NOT_FOUND, sourceErrorMessagePart, targetType.describe(), targetPropertyName, targetType.describe(), sourceType.describe() ); } }
if ( mappingMethod == null ) { return null; } if (methodRef.getMappingReferences().isRestrictToDefinedMappings() || !ctx.getMappingsToGenerate().contains( mappingMethod )) { // If the mapping options are restricted only to the defined mappings, then use the mapping method. // See https://github.com/mapstruct/mapstruct/issues/1148 ctx.getMappingsToGenerate().add( mappingMethod ); } else { String existingName = ctx.getExistingMappingMethod( mappingMethod ).getName(); methodRef = new ForgedMethod( existingName, methodRef ); } return createAssignment( source, methodRef );
1,427
180
1,607
DerekYRC_mini-spring
mini-spring/src/main/java/org/springframework/aop/framework/adapter/AfterReturningAdviceInterceptor.java
AfterReturningAdviceInterceptor
invoke
class AfterReturningAdviceInterceptor implements MethodInterceptor, AfterAdvice { private AfterReturningAdvice advice; public AfterReturningAdviceInterceptor() { } public AfterReturningAdviceInterceptor(AfterReturningAdvice advice) { this.advice = advice; } @Override public Object invoke(MethodInvocation mi) throws Throwable {<FILL_FUNCTION_BODY>} }
Object retVal = mi.proceed(); this.advice.afterReturning(retVal, mi.getMethod(), mi.getArguments(), mi.getThis()); return retVal;
110
50
160
Pay-Group_best-pay-sdk
best-pay-sdk/src/main/java/com/lly835/bestpay/utils/StreamUtil.java
StreamUtil
io
class StreamUtil { private static final int DEFAULT_BUFFER_SIZE = 8192; public static void io(InputStream in, OutputStream out) throws IOException { io(in, out, -1); } public static void io(InputStream in, OutputStream out, int bufferSize) throws IOException { if (bufferSize == -1) { bufferSize = DEFAULT_BUFFER_SIZE; } byte[] buffer = new byte[bufferSize]; int amount; while ((amount = in.read(buffer)) >= 0) { out.write(buffer, 0, amount); } } public static void io(Reader in, Writer out) throws IOException { io(in, out, -1); } public static void io(Reader in, Writer out, int bufferSize) throws IOException {<FILL_FUNCTION_BODY>} public static OutputStream synchronizedOutputStream(OutputStream out) { return new SynchronizedOutputStream(out); } public static OutputStream synchronizedOutputStream(OutputStream out, Object lock) { return new SynchronizedOutputStream(out, lock); } public static String readText(InputStream in) throws IOException { return readText(in, null, -1); } public static String readText(InputStream in, String encoding) throws IOException { return readText(in, encoding, -1); } public static String readText(InputStream in, String encoding, int bufferSize) throws IOException { Reader reader = (encoding == null) ? new InputStreamReader(in) : new InputStreamReader(in, encoding); return readText(reader, bufferSize); } public static String readText(Reader reader) throws IOException { return readText(reader, -1); } public static String readText(Reader reader, int bufferSize) throws IOException { StringWriter writer = new StringWriter(); io(reader, writer, bufferSize); return writer.toString(); } private static class SynchronizedOutputStream extends OutputStream { private OutputStream out; private Object lock; SynchronizedOutputStream(OutputStream out) { this(out, out); } SynchronizedOutputStream(OutputStream out, Object lock) { this.out = out; this.lock = lock; } public void write(int datum) throws IOException { synchronized (lock) { out.write(datum); } } public void write(byte[] data) throws IOException { synchronized (lock) { out.write(data); } } public void write(byte[] data, int offset, int length) throws IOException { synchronized (lock) { out.write(data, offset, length); } } public void flush() throws IOException { synchronized (lock) { out.flush(); } } public void close() throws IOException { synchronized (lock) { out.close(); } } } }
if (bufferSize == -1) { bufferSize = DEFAULT_BUFFER_SIZE >> 1; } char[] buffer = new char[bufferSize]; int amount; while ((amount = in.read(buffer)) >= 0) { out.write(buffer, 0, amount); }
769
83
852
jeecgboot_jeecg-boot
jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/system/controller/SysFillRuleController.java
SysFillRuleController
executeByRuleCodeBatch
class SysFillRuleController extends JeecgController<SysFillRule, ISysFillRuleService> { @Autowired private ISysFillRuleService sysFillRuleService; /** * 分页列表查询 * * @param sysFillRule * @param pageNo * @param pageSize * @param req * @return */ @AutoLog(value = "填值规则-分页列表查询") @ApiOperation(value = "填值规则-分页列表查询", notes = "填值规则-分页列表查询") @GetMapping(value = "/list") public Result<?> queryPageList(SysFillRule sysFillRule, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo, @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) { QueryWrapper<SysFillRule> queryWrapper = QueryGenerator.initQueryWrapper(sysFillRule, req.getParameterMap()); Page<SysFillRule> page = new Page<>(pageNo, pageSize); IPage<SysFillRule> pageList = sysFillRuleService.page(page, queryWrapper); return Result.ok(pageList); } /** * 测试 ruleCode * * @param ruleCode * @return */ @GetMapping(value = "/testFillRule") public Result testFillRule(@RequestParam("ruleCode") String ruleCode) { Object result = FillRuleUtil.executeRule(ruleCode, new JSONObject()); return Result.ok(result); } /** * 添加 * * @param sysFillRule * @return */ @AutoLog(value = "填值规则-添加") @ApiOperation(value = "填值规则-添加", notes = "填值规则-添加") @PostMapping(value = "/add") public Result<?> add(@RequestBody SysFillRule sysFillRule) { sysFillRuleService.save(sysFillRule); return Result.ok("添加成功!"); } /** * 编辑 * * @param sysFillRule * @return */ @AutoLog(value = "填值规则-编辑") @ApiOperation(value = "填值规则-编辑", notes = "填值规则-编辑") @RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST}) public Result<?> edit(@RequestBody SysFillRule sysFillRule) { sysFillRuleService.updateById(sysFillRule); return Result.ok("编辑成功!"); } /** * 通过id删除 * * @param id * @return */ @AutoLog(value = "填值规则-通过id删除") @ApiOperation(value = "填值规则-通过id删除", notes = "填值规则-通过id删除") @DeleteMapping(value = "/delete") public Result<?> delete(@RequestParam(name = "id", required = true) String id) { sysFillRuleService.removeById(id); return Result.ok("删除成功!"); } /** * 批量删除 * * @param ids * @return */ @AutoLog(value = "填值规则-批量删除") @ApiOperation(value = "填值规则-批量删除", notes = "填值规则-批量删除") @DeleteMapping(value = "/deleteBatch") public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) { this.sysFillRuleService.removeByIds(Arrays.asList(ids.split(","))); return Result.ok("批量删除成功!"); } /** * 通过id查询 * * @param id * @return */ @AutoLog(value = "填值规则-通过id查询") @ApiOperation(value = "填值规则-通过id查询", notes = "填值规则-通过id查询") @GetMapping(value = "/queryById") public Result<?> queryById(@RequestParam(name = "id", required = true) String id) { SysFillRule sysFillRule = sysFillRuleService.getById(id); return Result.ok(sysFillRule); } /** * 导出excel * * @param request * @param sysFillRule */ @RequestMapping(value = "/exportXls") public ModelAndView exportXls(HttpServletRequest request, SysFillRule sysFillRule) { return super.exportXls(request, sysFillRule, SysFillRule.class, "填值规则"); } /** * 通过excel导入数据 * * @param request * @param response * @return */ @RequestMapping(value = "/importExcel", method = RequestMethod.POST) public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) { return super.importExcel(request, response, SysFillRule.class); } /** * 通过 ruleCode 执行自定义填值规则 * * @param ruleCode 要执行的填值规则编码 * @param formData 表单数据,可根据表单数据的不同生成不同的填值结果 * @return 运行后的结果 */ @PutMapping("/executeRuleByCode/{ruleCode}") public Result executeByRuleCode(@PathVariable("ruleCode") String ruleCode, @RequestBody JSONObject formData) { Object result = FillRuleUtil.executeRule(ruleCode, formData); return Result.ok(result); } /** * 批量通过 ruleCode 执行自定义填值规则 * * @param ruleData 要执行的填值规则JSON数组: * 示例: { "commonFormData": {}, rules: [ { "ruleCode": "xxx", "formData": null } ] } * @return 运行后的结果,返回示例: [{"ruleCode": "order_num_rule", "result": "CN2019111117212984"}] * */ @PutMapping("/executeRuleByCodeBatch") public Result executeByRuleCodeBatch(@RequestBody JSONObject ruleData) {<FILL_FUNCTION_BODY>} }
JSONObject commonFormData = ruleData.getJSONObject("commonFormData"); JSONArray rules = ruleData.getJSONArray("rules"); // 遍历 rules ,批量执行规则 JSONArray results = new JSONArray(rules.size()); for (int i = 0; i < rules.size(); i++) { JSONObject rule = rules.getJSONObject(i); String ruleCode = rule.getString("ruleCode"); JSONObject formData = rule.getJSONObject("formData"); // 如果没有传递 formData,就用common的 if (formData == null) { formData = commonFormData; } // 执行填值规则 Object result = FillRuleUtil.executeRule(ruleCode, formData); JSONObject obj = new JSONObject(rules.size()); obj.put("ruleCode", ruleCode); obj.put("result", result); results.add(obj); } return Result.ok(results);
1,659
246
1,905
subhra74_snowflake
snowflake/muon-app/src/main/java/muon/app/ui/components/session/WinScpImporter.java
WinScpImporter
importSessions
class WinScpImporter { private static final String WinSCPRegKey = "Software\\Martin Prikryl\\WinSCP 2\\Sessions"; public static Map<String, String> getKeyNames() { Map<String, String> map = new HashMap<String, String>(); try { String[] keys = Advapi32Util .registryGetKeys(WinReg.HKEY_CURRENT_USER, WinSCPRegKey); for (String key : keys) { String decodedKey = key.replace("%20", " "); map.put(key, decodedKey); } } catch (Exception e) { e.printStackTrace(); } System.out.println(map); return map; } public static void importSessions(DefaultMutableTreeNode node, List<String> keys) {<FILL_FUNCTION_BODY>} private static DefaultMutableTreeNode find(DefaultMutableTreeNode node, String name) { NamedItem item = (NamedItem) node.getUserObject(); if (item.name.equals(name)) { return node; } for (int i = 0; i < node.getChildCount(); i++) { DefaultMutableTreeNode child = (DefaultMutableTreeNode) node .getChildAt(i); if (child.getAllowsChildren()) { DefaultMutableTreeNode fn = find(child, name); if (fn != null) return fn; } } return null; } }
// String[] keys = // Advapi32Util.registryGetKeys(WinReg.HKEY_CURRENT_USER, // WinSCPRegKey); for (String key : keys) { if (RegUtil.regGetInt(WinReg.HKEY_CURRENT_USER, WinSCPRegKey + "\\" + key, "FSProtocol") == 0) { String host = RegUtil.regGetStr(WinReg.HKEY_CURRENT_USER, WinSCPRegKey + "\\" + key, "HostName"); int port = RegUtil.regGetInt(WinReg.HKEY_CURRENT_USER, WinSCPRegKey + "\\" + key, "PortNumber"); if (port == 0) port = 22; String user = RegUtil.regGetStr(WinReg.HKEY_CURRENT_USER, WinSCPRegKey + "\\" + key, "UserName"); String keyfile = RegUtil.regGetStr(WinReg.HKEY_CURRENT_USER, WinSCPRegKey + "\\" + key, "PublicKeyFile"); String proxyHost = RegUtil.regGetStr(WinReg.HKEY_CURRENT_USER, WinSCPRegKey + "\\" + key, "ProxyHost"); int proxyPort = RegUtil.regGetInt(WinReg.HKEY_CURRENT_USER, WinSCPRegKey + "\\" + key, "ProxyPort"); String proxyUser = RegUtil.regGetStr(WinReg.HKEY_CURRENT_USER, WinSCPRegKey + "\\" + key, "ProxyUsername"); String proxyPass = RegUtil.regGetStr(WinReg.HKEY_CURRENT_USER, WinSCPRegKey + "\\" + key, "ProxyPassword"); int proxyType = RegUtil.regGetInt(WinReg.HKEY_CURRENT_USER, WinSCPRegKey + "\\" + key, "ProxyMethod"); if (proxyType == 1) { proxyType = 2; } else if (proxyType == 2) { proxyType = 3; } else if (proxyType == 3) { proxyType = 1; } else { proxyType = 0; } SessionInfo info = new SessionInfo(); info.setHost(host); info.setPort(port); info.setUser(user); try { if (keyfile != null && keyfile.length() > 0) { info.setPrivateKeyFile( URLDecoder.decode(keyfile, "utf-8")); } } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } info.setProxyHost(proxyHost); info.setProxyPort(proxyPort); info.setProxyUser(proxyUser); info.setProxyPassword(proxyPass); info.setProxyType(proxyType); try { String[] arr = URLDecoder.decode(key, "utf-8").split("/"); info.setName(arr[arr.length - 1]); DefaultMutableTreeNode parent = node; if (arr.length > 1) { for (int i = 0; i < arr.length - 1; i++) { DefaultMutableTreeNode parent2 = find(parent, arr[i]); if (parent2 == null) { SessionFolder folder = new SessionFolder(); folder.setName(arr[i]); parent2 = new DefaultMutableTreeNode(folder); parent2.setAllowsChildren(true); parent.add(parent2); } parent = parent2; } } DefaultMutableTreeNode node1 = new DefaultMutableTreeNode( info); node1.setAllowsChildren(false); parent.add(node1); } catch (Exception e) { e.printStackTrace(); } } }
445
1,144
1,589
jitsi_jitsi
jitsi/modules/impl/protocol-sip/src/main/java/net/java/sip/communicator/impl/protocol/sip/xcap/model/commonpolicy/IdentityType.java
IdentityType
getOneList
class IdentityType { /** * The list of one elements. */ private List<OneType> oneList; /** * The list of many elements. */ private List<ManyType> manyList; /** * The list of any elements. */ private List<Element> any; /** * Gets the value of the oneList property. * * @return the oneList property. */ public List<OneType> getOneList() {<FILL_FUNCTION_BODY>} /** * Gets the value of the manyList property. * * @return the manyList property. */ public List<ManyType> getManyList() { if (manyList == null) { manyList = new ArrayList<ManyType>(); } return this.manyList; } /** * Gets the value of the any property. * * @return the any property. */ public List<Element> getAny() { if (any == null) { any = new ArrayList<Element>(); } return this.any; } }
if (oneList == null) { oneList = new ArrayList<OneType>(); } return this.oneList;
308
38
346
javamelody_javamelody
javamelody/javamelody-offline-viewer/src/main/java/net/bull/javamelody/Viewer.java
Viewer
getLatest
class Viewer { /** * main. * @param args String[] * @throws Exception e */ public static void main(String[] args) throws Exception { final String storageDirectory = Parameter.STORAGE_DIRECTORY.getValue(); if (storageDirectory == null) { throw new IllegalArgumentException( "Please give the javamelody storage directory with -Djavamelody.storage-directory=... containing directories with the data of one or more instances of an application"); } // merge and copy the data of one or more instances into a temporary directory final String tmpApplication = "tmpjavamelody" + new Random().nextInt(); final String mergedDirectory = System.getProperty("java.io.tmpdir"); //Parameters.getStorageDirectory(tmpApplication).getPath(); DataMerge.main(new String[] { storageDirectory, mergedDirectory + '/' + tmpApplication }); addShutdownHook(new File(mergedDirectory + '/' + tmpApplication)); final Map<Parameter, String> parameters = new HashMap<>(); // set the path of the reports: parameters.put(Parameter.MONITORING_PATH, "/"); // set the storage directory and temp application name: Parameter.STORAGE_DIRECTORY.setValue(mergedDirectory); parameters.put(Parameter.APPLICATION_NAME, tmpApplication); // start the embedded http server with javamelody final String port = System.getProperty("javamelody.viewer.port", "8080"); String url = "http://localhost:" + port + '/'; System.out.println("Starting on " + url); EmbeddedServer.start(Integer.parseInt(port), parameters); // open the reports in a browser final String lastDay = new SimpleDateFormat("yyyy-MM-dd") .format(new Date(getLatest(new File(storageDirectory)))); url += "?period=" + lastDay + "%7C" + lastDay + "&pattern=yyyy-MM-dd"; System.out.println("Opening the reports in a browser on " + url); Desktop.getDesktop().browse(URI.create(url)); System.out.println("Done"); } private static long getLatest(File directory) {<FILL_FUNCTION_BODY>} private static void addShutdownHook(final File directoryToCleanup) { Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { System.out.println("Cleaning up..."); try { // stop is needed to remove locks on files such as the javamelody.lock file EmbeddedServer.stop(); } catch (final Exception e) { System.out.println(e.toString()); } if (directoryToCleanup.exists()) { for (final File file : directoryToCleanup.listFiles()) { file.delete(); } directoryToCleanup.delete(); } System.out.println("Good bye"); } }); } }
long latest = 0; for (final File file : directory.listFiles()) { if (file.isDirectory()) { latest = Math.max(latest, getLatest(file)); } else { latest = Math.max(latest, file.lastModified()); } } return latest;
783
85
868
ainilili_ratel
ratel/landlords-client/src/main/java/org/nico/ratel/landlords/client/event/ClientEventListener_CODE_GAME_LANDLORD_ELECT.java
ClientEventListener_CODE_GAME_LANDLORD_ELECT
call
class ClientEventListener_CODE_GAME_LANDLORD_ELECT extends ClientEventListener { @Override public void call(Channel channel, String data) {<FILL_FUNCTION_BODY>} }
Map<String, Object> map = MapHelper.parser(data); int turnClientId = (int) map.get("nextClientId"); int highestScore = (int) map.get("highestScore"); if (map.containsKey("preClientNickname")) { if (highestScore != 0 && map.get("preClientId") == map.get("currentLandlordId")) { SimplePrinter.printNotice(map.get("preClientNickname") + " robs the landlord with " + highestScore + " score" + (highestScore == 1 ? "" : "s") + "!"); } else { SimplePrinter.printNotice(map.get("preClientNickname") + " don't rob the landlord!"); } } if (turnClientId != SimpleClient.id) { SimplePrinter.printNotice("It's " + map.get("nextClientNickname") + "'s turn. Please wait patiently for his/her confirmation !"); } else { String message = "It's your turn. What score do you want to rob the landlord? [0"; for(int i = highestScore + 1; i <= 3; ++i) { message = message + "/" + i; } message = message + "] (enter [exit|e] to exit current room)"; SimplePrinter.printNotice(message); String line = SimpleWriter.write("getScore"); if (!line.equalsIgnoreCase("exit") && !line.equalsIgnoreCase("e")) { try { int currentScore = Integer.parseInt(line); if (currentScore <= highestScore && currentScore != 0 || currentScore > 3) { SimplePrinter.printNotice("Invalid options"); this.call(channel, data); return; } String result; if (currentScore > highestScore) { result = MapHelper.newInstance() .put("highestScore", currentScore) .put("currentLandlordId", SimpleClient.id) .json(); } else if (map.containsKey("currentLandlordId")) { result = MapHelper.newInstance() .put("highestScore", highestScore) .put("currentLandlordId", (int) map.get("currentLandlordId")) .json(); } else { result = MapHelper.newInstance() .put("highestScore", 0) .json(); } this.pushToServer(channel, ServerEventCode.CODE_GAME_LANDLORD_ELECT, result); } catch (Exception e) { SimplePrinter.printNotice("Invalid options"); this.call(channel, data); } } else { this.pushToServer(channel, ServerEventCode.CODE_CLIENT_EXIT); } }
52
724
776
public abstract class ClientEventListener { public abstract void call( Channel channel, String data); public final static Map<ClientEventCode,ClientEventListener> LISTENER_MAP=new HashMap<>(); private final static String LISTENER_PREFIX="org.nico.ratel.landlords.client.event.ClientEventListener_"; protected static List<Poker> lastPokers=null; protected static String lastSellClientNickname=null; protected static String lastSellClientType=null; protected static void initLastSellInfo(); @SuppressWarnings("unchecked") public static ClientEventListener get( ClientEventCode code); protected ChannelFuture pushToServer( Channel channel, ServerEventCode code, String datas); protected ChannelFuture pushToServer( Channel channel, ServerEventCode code); }
jeecgboot_jeecg-boot
jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/system/controller/SysLogController.java
SysLogController
deleteBatch
class SysLogController { @Autowired private ISysLogService sysLogService; /** * 全部清除 */ private static final String ALL_ClEAR = "allclear"; /** * @功能:查询日志记录 * @param syslog * @param pageNo * @param pageSize * @param req * @return */ @RequestMapping(value = "/list", method = RequestMethod.GET) //@RequiresPermissions("system:log:list") public Result<IPage<SysLog>> queryPageList(SysLog syslog,@RequestParam(name="pageNo", defaultValue="1") Integer pageNo, @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,HttpServletRequest req) { Result<IPage<SysLog>> result = new Result<IPage<SysLog>>(); QueryWrapper<SysLog> queryWrapper = QueryGenerator.initQueryWrapper(syslog, req.getParameterMap()); Page<SysLog> page = new Page<SysLog>(pageNo, pageSize); //日志关键词 String keyWord = req.getParameter("keyWord"); if(oConvertUtils.isNotEmpty(keyWord)) { queryWrapper.like("log_content",keyWord); } //TODO 过滤逻辑处理 //TODO begin、end逻辑处理 //TODO 一个强大的功能,前端传一个字段字符串,后台只返回这些字符串对应的字段 //创建时间/创建人的赋值 IPage<SysLog> pageList = sysLogService.page(page, queryWrapper); log.info("查询当前页:"+pageList.getCurrent()); log.info("查询当前页数量:"+pageList.getSize()); log.info("查询结果数量:"+pageList.getRecords().size()); log.info("数据总数:"+pageList.getTotal()); result.setSuccess(true); result.setResult(pageList); return result; } /** * @功能:删除单个日志记录 * @param id * @return */ @RequestMapping(value = "/delete", method = RequestMethod.DELETE) //@RequiresPermissions("system:log:delete") public Result<SysLog> delete(@RequestParam(name="id",required=true) String id) { Result<SysLog> result = new Result<SysLog>(); SysLog sysLog = sysLogService.getById(id); if(sysLog==null) { result.error500("未找到对应实体"); }else { boolean ok = sysLogService.removeById(id); if(ok) { result.success("删除成功!"); } } return result; } /** * @功能:批量,全部清空日志记录 * @param ids * @return */ @RequestMapping(value = "/deleteBatch", method = RequestMethod.DELETE) //@RequiresPermissions("system:log:deleteBatch") public Result<SysRole> deleteBatch(@RequestParam(name="ids",required=true) String ids) {<FILL_FUNCTION_BODY>} }
Result<SysRole> result = new Result<SysRole>(); if(ids==null || "".equals(ids.trim())) { result.error500("参数不识别!"); }else { if(ALL_ClEAR.equals(ids)) { this.sysLogService.removeAll(); result.success("清除成功!"); } this.sysLogService.removeByIds(Arrays.asList(ids.split(","))); result.success("删除成功!"); } return result;
863
144
1,007
logfellow_logstash-logback-encoder
logstash-logback-encoder/src/main/java/net/logstash/logback/stacktrace/StackElementFilter.java
StackElementFilter
byPattern
class StackElementFilter { /** * Tests whether or not the specified {@link StackTraceElement} should be * accepted when computing a stack hash. * * @param element The {@link StackTraceElement} to be tested * @return {@code true} if and only if {@code element} should be accepted */ public abstract boolean accept(StackTraceElement element); /** * Creates a {@link StackElementFilter} that accepts any stack trace elements * * @return the filter */ public static final StackElementFilter any() { return new StackElementFilter() { @Override public boolean accept(StackTraceElement element) { return true; } }; } /** * Creates a {@link StackElementFilter} that accepts all stack trace elements with a non {@code null} * {@code {@link StackTraceElement#getFileName()} filename} and positive {@link StackTraceElement#getLineNumber()} line number} * * @return the filter */ public static final StackElementFilter withSourceInfo() { return new StackElementFilter() { @Override public boolean accept(StackTraceElement element) { return element.getFileName() != null && element.getLineNumber() >= 0; } }; } /** * Creates a {@link StackElementFilter} by exclusion {@link Pattern patterns} * * @param excludes regular expressions matching {@link StackTraceElement} to filter out * @return the filter */ public static final StackElementFilter byPattern(final List<Pattern> excludes) {<FILL_FUNCTION_BODY>} }
return new StackElementFilter() { @Override public boolean accept(StackTraceElement element) { if (!excludes.isEmpty()) { String classNameAndMethod = element.getClassName() + "." + element.getMethodName(); for (Pattern exclusionPattern : excludes) { if (exclusionPattern.matcher(classNameAndMethod).find()) { return false; } } } return true; } };
412
117
529
javamelody_javamelody
javamelody/javamelody-core/src/main/java/net/bull/javamelody/MonitoringInitialContextFactory.java
MonitoringInitialContextFactory
stop
class MonitoringInitialContextFactory implements InitialContextFactory { // on sauvegarde la factory initiale // (org.apache.naming.java.javaURLContextFactory dans Tomcat6 // avec un scheme "java" tel que défini dans NamingManager.getURLContext) private static String initialContextFactory; // et on la remplace par la nôtre static void init() { initialContextFactory = System.getProperty(Context.INITIAL_CONTEXT_FACTORY); System.setProperty(Context.INITIAL_CONTEXT_FACTORY, MonitoringInitialContextFactory.class.getName()); } static void stop() {<FILL_FUNCTION_BODY>} /** {@inheritDoc} */ @Override public Context getInitialContext(Hashtable<?, ?> environment) throws NamingException { // NOPMD try { final Class<?> clazz = Class.forName(initialContextFactory); final InitialContextFactory icf = (InitialContextFactory) clazz.newInstance(); final Context context = icf.getInitialContext(environment); final JdbcWrapper jdbcWrapper = JdbcWrapper.SINGLETON; return jdbcWrapper.createContextProxy(context); } catch (final ClassNotFoundException | IllegalAccessException | InstantiationException e) { throw createNamingException(e); } } private static NoInitialContextException createNamingException(Exception e) { final NoInitialContextException ex = new NoInitialContextException(e.toString()); ex.initCause(e); return ex; } }
if (MonitoringInitialContextFactory.class.getName() .equals(System.getProperty(Context.INITIAL_CONTEXT_FACTORY))) { // on remet l'ancienne valeur System.setProperty(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory); }
436
88
524
jitsi_jitsi
jitsi/modules/impl/protocol-sip/src/main/java/net/java/sip/communicator/impl/protocol/sip/xcap/model/xcaperror/UniquenessFailureType.java
ExistsType
getAltValue
class ExistsType { /** * The list of alt-value elements. */ protected List<String> altValue; /** * The field attribute. */ protected String field; /** * Gets the altValue attribute. * * @return the altValue property. */ public List<String> getAltValue() {<FILL_FUNCTION_BODY>} /** * Gets the field attribute. * * @return the field property. */ public String getField() { return field; } /** * Sets the value of the field property. * * @param field the field to set. */ public void setField(String field) { this.field = field; } }
if (altValue == null) { altValue = new ArrayList<String>(); } return this.altValue;
214
37
251
ainilili_ratel
ratel/landlords-client/src/main/java/org/nico/ratel/landlords/client/event/ClientEventListener_CODE_CLIENT_EXIT.java
ClientEventListener_CODE_CLIENT_EXIT
call
class ClientEventListener_CODE_CLIENT_EXIT extends ClientEventListener { @Override public void call(Channel channel, String data) {<FILL_FUNCTION_BODY>} }
Map<String, Object> map = MapHelper.parser(data); Integer exitClientId = (Integer) map.get("exitClientId"); String role; if (exitClientId == SimpleClient.id) { role = "You"; } else { role = String.valueOf(map.get("exitClientNickname")); } SimplePrinter.printNotice(role + " left the room. Room disbanded!\n"); get(ClientEventCode.CODE_SHOW_OPTIONS).call(channel, data);
46
146
192
public abstract class ClientEventListener { public abstract void call( Channel channel, String data); public final static Map<ClientEventCode,ClientEventListener> LISTENER_MAP=new HashMap<>(); private final static String LISTENER_PREFIX="org.nico.ratel.landlords.client.event.ClientEventListener_"; protected static List<Poker> lastPokers=null; protected static String lastSellClientNickname=null; protected static String lastSellClientType=null; protected static void initLastSellInfo(); @SuppressWarnings("unchecked") public static ClientEventListener get( ClientEventCode code); protected ChannelFuture pushToServer( Channel channel, ServerEventCode code, String datas); protected ChannelFuture pushToServer( Channel channel, ServerEventCode code); }
jitsi_jitsi
jitsi/modules/util/src/main/java/net/java/sip/communicator/util/Html2Text.java
HTMLParserCallback
parse
class HTMLParserCallback extends HTMLEditorKit.ParserCallback { /** * The <tt>StringBuilder</tt> which accumulates the parsed text while it * is being parsed. */ private StringBuilder sb; /** * Parses the text contained in the given reader. * * @param in the reader to parse. * @return the parsed text * @throws IOException thrown if we fail to parse the reader. */ public String parse(Reader in) throws IOException {<FILL_FUNCTION_BODY>} /** * Appends the given text to the string buffer. * * @param text the text of a text node which has been parsed from the * specified HTML * @param pos the zero-based position of the specified <tt>text</tt> in * the specified HTML */ @Override public void handleText(char[] text, int pos) { sb.append(text); } }
sb = new StringBuilder(); String s; try { new ParserDelegator().parse(in, this, /* ignoreCharSet */ true); s = sb.toString(); } finally { /* * Since the Html2Text class keeps this instance in a static * reference, the field sb should be reset to null as soon as * completing its goad in order to avoid keeping the parsed * text in memory after it is no longer needed i.e. to prevent * a memory leak. This method has been converted to return the * parsed string instead of having a separate getter method for * the parsed string for the same purpose. */ sb = null; } return s;
258
187
445
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/routing/util/parsers/OSMRoadClassParser.java
OSMRoadClassParser
handleWayTags
class OSMRoadClassParser implements TagParser { protected final EnumEncodedValue<RoadClass> roadClassEnc; public OSMRoadClassParser(EnumEncodedValue<RoadClass> roadClassEnc) { this.roadClassEnc = roadClassEnc; } @Override public void handleWayTags(int edgeId, EdgeIntAccess edgeIntAccess, ReaderWay readerWay, IntsRef relationFlags) {<FILL_FUNCTION_BODY>} }
String roadClassTag = readerWay.getTag("highway"); if (roadClassTag == null) return; RoadClass roadClass = RoadClass.find(roadClassTag); if (roadClass == OTHER && roadClassTag.endsWith("_link")) roadClass = RoadClass.find(roadClassTag.substring(0, roadClassTag.length() - 5)); if (roadClass != OTHER) roadClassEnc.setEnum(false, edgeId, edgeIntAccess, roadClass);
120
132
252
Pay-Group_best-pay-sdk
best-pay-sdk/src/main/java/com/lly835/bestpay/utils/ServletRequestUtils.java
ServletRequestUtils
getParameterMap
class ServletRequestUtils { public static TreeMap<String, String> getParameterMap(ServletRequest request) {<FILL_FUNCTION_BODY>} }
Objects.requireNonNull(request, "request is null."); TreeMap<String, String> map = new TreeMap<>(); Enumeration enu = request.getParameterNames(); while (enu.hasMoreElements()) { String paraName = (String) enu.nextElement(); map.put(paraName, request.getParameter(paraName)); } return map;
43
101
144
eirslett_frontend-maven-plugin
frontend-maven-plugin/frontend-plugin-core/src/main/java/com/github/eirslett/maven/plugins/frontend/lib/ArchiveExtractor.java
DefaultArchiveExtractor
extract
class DefaultArchiveExtractor implements ArchiveExtractor { private static final Logger LOG = LoggerFactory.getLogger(DefaultArchiveExtractor.class); private void prepDestination(File path, boolean directory) throws IOException { if (directory) { path.mkdirs(); } else { if (!path.getParentFile().exists()) { path.getParentFile().mkdirs(); } if (!path.getParentFile().canWrite()) { throw new AccessDeniedException( String.format("Could not get write permissions for '%s'", path.getParentFile().getAbsolutePath())); } } } @Override public void extract(String archive, String destinationDirectory) throws ArchiveExtractionException {<FILL_FUNCTION_BODY>} /** * Do multiple file system checks that should enable the plugin to work on any file system * whether or not it's case sensitive or not. * * @param destPath * @param destDir * @return */ private boolean startsWithPath(String destPath, String destDir) { if (destPath.startsWith(destDir)) { return true; } else if (destDir.length() > destPath.length()) { return false; } else { if (new File(destPath).exists() && !(new File(destPath.toLowerCase()).exists())) { return false; } return destPath.toLowerCase().startsWith(destDir.toLowerCase()); } } }
final File archiveFile = new File(archive); try (FileInputStream fis = new FileInputStream(archiveFile)) { if ("msi".equals(FileUtils.getExtension(archiveFile.getAbsolutePath()))) { String command = "msiexec /a " + archiveFile.getAbsolutePath() + " /qn TARGETDIR=\"" + destinationDirectory + "\""; Process child = Runtime.getRuntime().exec(command); try { int result = child.waitFor(); if (result != 0) { throw new ArchiveExtractionException( "Could not extract " + archiveFile.getAbsolutePath() + "; return code " + result); } } catch (InterruptedException e) { throw new ArchiveExtractionException( "Unexpected interruption of while waiting for extraction process", e); } } else if ("zip".equals(FileUtils.getExtension(archiveFile.getAbsolutePath()))) { Path destinationPath = Paths.get(destinationDirectory).normalize(); try (ZipFile zipFile = new ZipFile(archiveFile)) { Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); final Path destPath = destinationPath.resolve(entry.getName()).normalize(); if (!destPath.startsWith(destinationPath)) { throw new RuntimeException("Bad zip entry"); } prepDestination(destPath.toFile(), entry.isDirectory()); if (!entry.isDirectory()) { InputStream in = null; OutputStream out = null; try { in = zipFile.getInputStream(entry); out = new BufferedOutputStream(Files.newOutputStream(destPath)); IOUtils.copy(in, out); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } } } } } else { // TarArchiveInputStream can be constructed with a normal FileInputStream if // we ever need to extract regular '.tar' files. TarArchiveInputStream tarIn = null; try { tarIn = new TarArchiveInputStream(new GzipCompressorInputStream(fis)); TarArchiveEntry tarEntry = tarIn.getNextTarEntry(); String canonicalDestinationDirectory = new File(destinationDirectory).getCanonicalPath(); while (tarEntry != null) { // Create a file for this tarEntry final File destPath = new File(destinationDirectory, tarEntry.getName()); prepDestination(destPath, tarEntry.isDirectory()); if (!startsWithPath(destPath.getCanonicalPath(), canonicalDestinationDirectory)) { throw new IOException( "Expanding " + tarEntry.getName() + " would create file outside of " + canonicalDestinationDirectory ); } if (!tarEntry.isDirectory()) { destPath.createNewFile(); boolean isExecutable = (tarEntry.getMode() & 0100) > 0; destPath.setExecutable(isExecutable); OutputStream out = null; try { out = new FileOutputStream(destPath); IOUtils.copy(tarIn, out); } finally { IOUtils.closeQuietly(out); } } tarEntry = tarIn.getNextTarEntry(); } } finally { IOUtils.closeQuietly(tarIn); } } } catch (IOException e) { throw new ArchiveExtractionException("Could not extract archive: '" + archive + "'", e); }
393
925
1,318
eirslett_frontend-maven-plugin
frontend-maven-plugin/frontend-maven-plugin/src/main/java/com/github/eirslett/maven/plugins/frontend/mojo/PnpmMojo.java
PnpmMojo
execute
class PnpmMojo extends AbstractFrontendMojo { private static final String PNPM_REGISTRY_URL = "npmRegistryURL"; /** * pnpm arguments. Default is "install". */ @Parameter(defaultValue = "install", property = "frontend.pnpm.arguments", required = false) private String arguments; @Parameter(property = "frontend.pnpm.pnpmInheritsProxyConfigFromMaven", required = false, defaultValue = "true") private boolean pnpmInheritsProxyConfigFromMaven; /** * Registry override, passed as the registry option during pnpm install if set. */ @Parameter(property = PNPM_REGISTRY_URL, required = false, defaultValue = "") private String pnpmRegistryURL; @Parameter(property = "session", defaultValue = "${session}", readonly = true) private MavenSession session; @Component private BuildContext buildContext; @Component(role = SettingsDecrypter.class) private SettingsDecrypter decrypter; /** * Skips execution of this mojo. */ @Parameter(property = "skip.pnpm", defaultValue = "${skip.pnpm}") private boolean skip; @Override protected boolean skipExecution() { return this.skip; } @Override public synchronized void execute(FrontendPluginFactory factory) throws TaskRunnerException {<FILL_FUNCTION_BODY>} private ProxyConfig getProxyConfig() { if (pnpmInheritsProxyConfigFromMaven) { return MojoUtils.getProxyConfig(session, decrypter); } else { getLog().info("pnpm not inheriting proxy config from Maven"); return new ProxyConfig(Collections.<ProxyConfig.Proxy>emptyList()); } } private String getRegistryUrl() { // check to see if overridden via `-D`, otherwise fallback to pom value return System.getProperty(PNPM_REGISTRY_URL, pnpmRegistryURL); } }
File packageJson = new File(workingDirectory, "package.json"); if (buildContext == null || buildContext.hasDelta(packageJson) || !buildContext.isIncremental()) { ProxyConfig proxyConfig = getProxyConfig(); factory.getPnpmRunner(proxyConfig, getRegistryUrl()).execute(arguments, environmentVariables); } else { getLog().info("Skipping pnpm install as package.json unchanged"); }
540
112
652
public abstract class AbstractFrontendMojo extends AbstractMojo { @Component protected MojoExecution execution; /** * Whether you should skip while running in the test phase (default is false) */ @Parameter(property="skipTests",required=false,defaultValue="false") protected Boolean skipTests; /** * Set this to true to ignore a failure during testing. Its use is NOT RECOMMENDED, but quite convenient on occasion. * @since 1.4 */ @Parameter(property="maven.test.failure.ignore",defaultValue="false") protected boolean testFailureIgnore; /** * The base directory for running all Node commands. (Usually the directory that contains package.json) */ @Parameter(defaultValue="${basedir}",property="workingDirectory",required=false) protected File workingDirectory; /** * The base directory for installing node and npm. */ @Parameter(property="installDirectory",required=false) protected File installDirectory; /** * Additional environment variables to pass to the build. */ @Parameter protected Map<String,String> environmentVariables; @Parameter(defaultValue="${project}",readonly=true) private MavenProject project; @Parameter(defaultValue="${repositorySystemSession}",readonly=true) private RepositorySystemSession repositorySystemSession; /** * Determines if this execution should be skipped. */ private boolean skipTestPhase(); /** * Determines if the current execution is during a testing phase (e.g., "test" or "integration-test"). */ private boolean isTestingPhase(); protected abstract void execute( FrontendPluginFactory factory) throws FrontendException ; /** * Implemented by children to determine if this execution should be skipped. */ protected abstract boolean skipExecution(); @Override public void execute() throws MojoFailureException; }
mapstruct_mapstruct
mapstruct/processor/src/main/java/org/mapstruct/ap/internal/model/source/selector/QualifierSelector.java
QualifierSelector
getMatchingMethods
class QualifierSelector implements MethodSelector { private final TypeUtils typeUtils; private final TypeMirror namedAnnotationTypeMirror; public QualifierSelector(TypeUtils typeUtils, ElementUtils elementUtils ) { this.typeUtils = typeUtils; namedAnnotationTypeMirror = elementUtils.getTypeElement( "org.mapstruct.Named" ).asType(); } @Override public <T extends Method> List<SelectedMethod<T>> getMatchingMethods(List<SelectedMethod<T>> methods, SelectionContext context) {<FILL_FUNCTION_BODY>} private Set<AnnotationMirror> getQualifierAnnotationMirrors( Method candidate ) { // retrieve annotations Set<AnnotationMirror> qualiferAnnotations = new HashSet<>(); // first from the method itself SourceMethod candidateSM = (SourceMethod) candidate; List<? extends AnnotationMirror> methodAnnotations = candidateSM.getExecutable().getAnnotationMirrors(); for ( AnnotationMirror methodAnnotation : methodAnnotations ) { addOnlyWhenQualifier( qualiferAnnotations, methodAnnotation ); } // then from the mapper (if declared) Type mapper = candidate.getDeclaringMapper(); if ( mapper != null ) { List<? extends AnnotationMirror> mapperAnnotations = mapper.getTypeElement().getAnnotationMirrors(); for ( AnnotationMirror mapperAnnotation : mapperAnnotations ) { addOnlyWhenQualifier( qualiferAnnotations, mapperAnnotation ); } } return qualiferAnnotations; } private void addOnlyWhenQualifier( Set<AnnotationMirror> annotationSet, AnnotationMirror candidate ) { // only add the candidate annotation when the candidate itself has the annotation 'Qualifier' if ( QualifierGem.instanceOn( candidate.getAnnotationType().asElement() ) != null ) { annotationSet.add( candidate ); } } }
SelectionCriteria criteria = context.getSelectionCriteria(); int numberOfQualifiersToMatch = 0; // Define some local collections and make sure that they are defined. List<TypeMirror> qualifierTypes = new ArrayList<>(); if ( criteria.getQualifiers() != null ) { qualifierTypes.addAll( criteria.getQualifiers() ); numberOfQualifiersToMatch += criteria.getQualifiers().size(); } List<String> qualfiedByNames = new ArrayList<>(); if ( criteria.getQualifiedByNames() != null ) { qualfiedByNames.addAll( criteria.getQualifiedByNames() ); numberOfQualifiersToMatch += criteria.getQualifiedByNames().size(); } // add the mapstruct @Named annotation as annotation to look for if ( !qualfiedByNames.isEmpty() ) { qualifierTypes.add( namedAnnotationTypeMirror ); } // Check there are qualfiers for this mapping: Mapping#qualifier or Mapping#qualfiedByName if ( qualifierTypes.isEmpty() ) { // When no qualifiers, disqualify all methods marked with a qualifier by removing them from the candidates List<SelectedMethod<T>> nonQualiferAnnotatedMethods = new ArrayList<>( methods.size() ); for ( SelectedMethod<T> candidate : methods ) { if ( candidate.getMethod() instanceof SourceMethod ) { Set<AnnotationMirror> qualifierAnnotations = getQualifierAnnotationMirrors( candidate.getMethod() ); if ( qualifierAnnotations.isEmpty() ) { nonQualiferAnnotatedMethods.add( candidate ); } } else { nonQualiferAnnotatedMethods.add( candidate ); } } return nonQualiferAnnotatedMethods; } else { // Check all methods marked with qualfier (or methods in Mappers marked wiht a qualfier) for matches. List<SelectedMethod<T>> matches = new ArrayList<>( methods.size() ); for ( SelectedMethod<T> candidate : methods ) { if ( !( candidate.getMethod() instanceof SourceMethod ) ) { continue; } // retrieve annotations Set<AnnotationMirror> qualifierAnnotationMirrors = getQualifierAnnotationMirrors( candidate.getMethod() ); // now count if all qualifiers are matched int matchingQualifierCounter = 0; for ( AnnotationMirror qualifierAnnotationMirror : qualifierAnnotationMirrors ) { for ( TypeMirror qualifierType : qualifierTypes ) { // get the type of the annotation positionHint. DeclaredType qualifierAnnotationType = qualifierAnnotationMirror.getAnnotationType(); if ( typeUtils.isSameType( qualifierType, qualifierAnnotationType ) ) { // Match! we have an annotation which has the @Qualifer marker ( could be @Named as well ) if ( typeUtils.isSameType( qualifierAnnotationType, namedAnnotationTypeMirror ) ) { // Match! its an @Named, so do the additional check on name. NamedGem named = NamedGem.instanceOn( qualifierAnnotationMirror ); if ( named.value().hasValue() && qualfiedByNames.contains( named.value().get() ) ) { // Match! its an @Name and the value matches as well. Oh boy. matchingQualifierCounter++; } } else { // Match! its a self declared qualifer annoation (marked with @Qualifier) matchingQualifierCounter++; } break; } } } if ( matchingQualifierCounter == numberOfQualifiersToMatch ) { // Only if all qualifiers are matched with a qualifying annotation, add candidate matches.add( candidate ); } } return matches; }
504
994
1,498
Kong_unirest-java
unirest-java/unirest-modules-mocks/src/main/java/kong/unirest/core/Times.java
AtLeast
matches
class AtLeast extends Times { private final int times; AtLeast(int times) { this.times = times; } @Override public EvaluationResult matches(int number) {<FILL_FUNCTION_BODY>} }
if(number >= times) { return EvaluationResult.success(); } else { return EvaluationResult.fail("Expected at least %s invocations but got %s", times, number); }
68
55
123
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/struct/sysctl/ExternProc64.java
ExternProc64
getFieldOrder
class ExternProc64 extends UnidbgStructure implements DarwinSyscall { public ExternProc64(Pointer p) { super(p); } public long __p_forw; public long __p_back; public long p_vmspace; /* Address space. */ public long p_sigacts; /* Signal actions, state (PROC ONLY). */ public int p_flag; /* P_* flags. */ public byte p_stat; /* S* process status. */ public int p_pid; /* Process identifier. */ public int p_oppid; /* Save parent pid during ptrace. XXX */ public int p_dupfd; /* Sideways return value from fdopen. XXX */ public long user_stack; /* where user stack was allocated */ public long exit_thread; /* XXX Which thread is exiting? */ public int p_debugger; /* allow to debug */ public boolean sigwait; /* indication to suspend */ public int p_estcpu; /* Time averaged value of p_cpticks. */ public int p_cpticks; /* Ticks of cpu time. */ public int p_pctcpu; /* %cpu for this process during p_swtime */ public long p_wchan; /* Sleep address. */ public long p_wmesg; /* Reason for sleep. */ public int p_swtime; /* Time swapped in or out. */ public int p_slptime; /* Time since last blocked. */ public ITimerVal64 p_realtimer; /* Alarm timer. */ public TimeVal64 p_rtime; /* Real time. */ public long p_uticks; /* Statclock hits in user mode. */ public long p_sticks; /* Statclock hits in system mode. */ public long p_iticks; /* Statclock hits processing intr. */ public int p_traceflag; /* Kernel trace points. */ public long p_tracep; /* Trace to vnode. */ public int p_siglist; public long p_textvp; /* Vnode of executable. */ public int p_holdcnt; /* If non-zero, don't swap. */ public int p_sigmask; public int p_sigignore; /* Signals being ignored. */ public int p_sigcatch; /* Signals being caught by user. */ public byte p_priority; /* Process priority. */ public byte p_usrpri; /* User-priority based on p_cpu and p_nice. */ public byte p_nice; /* Process "nice" value. */ public byte[] p_comm = new byte[MAXCOMLEN + 1]; public long p_pgrp; /* Pointer to process group. */ public long p_addr; /* Kernel virtual addr of u-area (PROC ONLY). */ public short p_xstat; /* Exit status for wait; also stop signal. */ public short p_acflag; /* Accounting flags. */ public long p_ru; /* Exit information. XXX */ @Override protected List<String> getFieldOrder() {<FILL_FUNCTION_BODY>} }
return Arrays.asList("__p_forw", "__p_back", "p_vmspace", "p_sigacts", "p_flag", "p_stat", "p_pid", "p_oppid", "p_dupfd", "user_stack", "exit_thread", "p_debugger", "sigwait", "p_estcpu", "p_cpticks", "p_pctcpu", "p_wchan", "p_wmesg", "p_swtime", "p_slptime", "p_realtimer", "p_rtime", "p_uticks", "p_sticks", "p_iticks", "p_traceflag", "p_tracep", "p_siglist", "p_textvp", "p_holdcnt", "p_sigmask", "p_sigignore", "p_sigcatch", "p_priority", "p_usrpri", "p_nice", "p_comm", "p_pgrp", "p_addr", "p_xstat", "p_acflag", "p_ru");
799
274
1,073
public abstract class UnidbgStructure extends Structure implements PointerArg { /** * Placeholder pointer to help avoid auto-allocation of memory where a Structure needs a valid pointer but want to avoid actually reading from it. */ private static final Pointer PLACEHOLDER_MEMORY=new UnidbgPointer(null,null){ @Override public UnidbgPointer share( long offset, long sz); } ; public static int calculateSize( Class<? extends UnidbgStructure> type); private static class ByteArrayPointer extends UnidbgPointer { private final Emulator<?> emulator; private final byte[] data; public ByteArrayPointer( Emulator<?> emulator, byte[] data); @Override public UnidbgPointer share( long offset, long sz); } protected UnidbgStructure( Emulator<?> emulator, byte[] data); protected UnidbgStructure( byte[] data); protected UnidbgStructure( Pointer p); private void checkPointer( Pointer p); @Override protected int getNativeSize( Class<?> nativeType, Object value); @Override protected int getNativeAlignment( Class<?> type, Object value, boolean isFirstElement); private boolean isPlaceholderMemory( Pointer p); public void pack(); public void unpack(); /** * @param debug If true, will include a native memory dump of theStructure's backing memory. * @return String representation of this object. */ public String toString( boolean debug); private String format( Class<?> type); private String toString( int indent, boolean showContents, boolean dumpMemory); /** * Obtain the value currently in the Java field. Does not read from native memory. * @param field field to look up * @return current field value (Java-side only) */ private Object getFieldValue( Field field); private static final Field FIELD_STRUCT_FIELDS; static { try { FIELD_STRUCT_FIELDS=Structure.class.getDeclaredField("structFields"); FIELD_STRUCT_FIELDS.setAccessible(true); } catch ( NoSuchFieldException e) { throw new IllegalStateException(e); } } /** * Return all fields in this structure (ordered). This represents the layout of the structure, and will be shared among Structures of the same class except when the Structure can have a variable size. NOTE: {@link #ensureAllocated()} <em>must</em> be called prior tocalling this method. * @return {@link Map} of field names to field representations. */ @SuppressWarnings("unchecked") private Map<String,StructField> fields(); }
zhkl0228_unidbg
unidbg/unidbg-android/src/main/java/com/github/unidbg/linux/android/dvm/jni/ProxyClassLoader.java
ProxyClassLoader
loadClass
class ProxyClassLoader { private final ClassLoader classLoader; ProxyClassLoader(ClassLoader classLoader) { this.classLoader = classLoader; } private ProxyClassMapper classNameMapper; final void setClassNameMapper(ProxyClassMapper classNameMapper) { this.classNameMapper = classNameMapper; } final Class<?> loadClass(String name) throws ClassNotFoundException {<FILL_FUNCTION_BODY>} }
Class<?> newClass = classNameMapper == null ? null : classNameMapper.map(name); if (newClass != null) { return newClass; } return classLoader.loadClass(name);
119
57
176
joelittlejohn_jsonschema2pojo
jsonschema2pojo/jsonschema2pojo-core/src/main/java/org/jsonschema2pojo/SchemaGenerator.java
SchemaGenerator
mergeObjectNodes
class SchemaGenerator { private final ObjectMapper objectMapper; public SchemaGenerator() { this(null); } public SchemaGenerator(JsonFactory jsonFactory) { this.objectMapper = new ObjectMapper(jsonFactory) .enable(JsonParser.Feature.ALLOW_COMMENTS) .enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS); } public ObjectNode schemaFromExample(URL example) { try { JsonNode content = this.objectMapper.readTree(example); return schemaFromExample(content); } catch (IOException e) { throw new GenerationException("Could not process JSON in source file", e); } } public ObjectNode schemaFromExample(JsonNode example) { if (example.isObject()) { return objectSchema(example); } else if (example.isArray()) { return arraySchema(example); } else { return simpleTypeSchema(example); } } private ObjectNode objectSchema(JsonNode exampleObject) { ObjectNode schema = this.objectMapper.createObjectNode(); schema.put("type", "object"); ObjectNode properties = this.objectMapper.createObjectNode(); for (Iterator<String> iter = exampleObject.fieldNames(); iter.hasNext();) { String property = iter.next(); properties.set(property, schemaFromExample(exampleObject.get(property))); } schema.set("properties", properties); return schema; } private ObjectNode arraySchema(JsonNode exampleArray) { ObjectNode schema = this.objectMapper.createObjectNode(); schema.put("type", "array"); if (exampleArray.size() > 0) { JsonNode exampleItem = exampleArray.get(0).isObject() ? mergeArrayItems(exampleArray) : exampleArray.get(0); schema.set("items", schemaFromExample(exampleItem)); } return schema; } private JsonNode mergeArrayItems(JsonNode exampleArray) { ObjectNode mergedItems = this.objectMapper.createObjectNode(); for (JsonNode item : exampleArray) { if (item.isObject()) { mergeObjectNodes(mergedItems, (ObjectNode) item); } } return mergedItems; } private ObjectNode mergeObjectNodes(ObjectNode targetNode, ObjectNode updateNode) {<FILL_FUNCTION_BODY>} private ObjectNode simpleTypeSchema(JsonNode exampleValue) { try { Object valueAsJavaType = this.objectMapper.treeToValue(exampleValue, Object.class); SerializerProvider serializerProvider = new DefaultSerializerProvider.Impl().createInstance(this.objectMapper.getSerializationConfig(), BeanSerializerFactory.instance); if (valueAsJavaType == null) { SchemaAware valueSerializer = NullSerializer.instance; return (ObjectNode) valueSerializer.getSchema(serializerProvider, null); } else if (valueAsJavaType instanceof Long) { // longs are 'integers' in schema terms SchemaAware valueSerializer = (SchemaAware) serializerProvider.findValueSerializer(Integer.class, null); ObjectNode schema = (ObjectNode) valueSerializer.getSchema(serializerProvider, null); schema.put("minimum", Long.MAX_VALUE); return schema; } else { Class<? extends Object> javaTypeForValue = valueAsJavaType.getClass(); SchemaAware valueSerializer = (SchemaAware) serializerProvider.findValueSerializer(javaTypeForValue, null); return (ObjectNode) valueSerializer.getSchema(serializerProvider, null); } } catch (JsonProcessingException e) { throw new GenerationException("Unable to generate a schema for this json example: " + exampleValue, e); } } }
Iterator<String> fieldNames = updateNode.fieldNames(); while (fieldNames.hasNext()) { String fieldName = fieldNames.next(); JsonNode targetValue = targetNode.get(fieldName); JsonNode updateValue = updateNode.get(fieldName); if (targetValue == null) { // Target node doesn't have this field from update node: just add it targetNode.set(fieldName, updateValue); } else { // Both nodes have the same field: merge the values if (targetValue.isObject() && updateValue.isObject()) { // Both values are objects: recurse targetNode.set(fieldName, mergeObjectNodes((ObjectNode) targetValue, (ObjectNode) updateValue)); } else if (targetValue.isArray() && updateValue.isArray()) { // Both values are arrays: concatenate them to be merged later ((ArrayNode) targetValue).addAll((ArrayNode) updateValue); } else { // Values have different types: use the one from the update node targetNode.set(fieldName, updateValue); } } } return targetNode;
981
291
1,272
obsidiandynamics_kafdrop
kafdrop/src/main/java/kafdrop/config/HealthCheckConfiguration.java
HealthCheck
getHealth
class HealthCheck { private final HealthEndpoint healthEndpoint; public HealthCheck(HealthEndpoint healthEndpoint) { this.healthEndpoint = healthEndpoint; } @ManagedAttribute public Map<String, Object> getHealth() {<FILL_FUNCTION_BODY>} private Map<String, Object> getDetails(Map<String, Object> details) { return details.entrySet().stream() .collect(Collectors.toMap(Map.Entry::getKey, e -> { final var health = (Health) e.getValue(); final var detail = new LinkedHashMap<String, Object>(); final var healthy = Status.UP.equals(health.getStatus()); detail.put("healthy", healthy); detail.put("message", health.getDetails().toString()); return detail; })); } private String getStatus(Health health) { final var status = health.getStatus(); if (Status.UP.equals(status) || Status.DOWN.equals(status)) { return status.toString(); } else { return "ERROR"; } } }
final var health = (Health) healthEndpoint.health(); final var healthMap = new LinkedHashMap<String, Object>(); healthMap.put("status", getStatus(health)); healthMap.put("detail", getDetails(health.getDetails())); return healthMap;
285
71
356
spring-cloud_spring-cloud-gateway
spring-cloud-gateway/spring-cloud-gateway-server-mvc/src/main/java/org/springframework/cloud/gateway/server/mvc/filter/LoadBalancerFilterFunctions.java
LoadBalancerFilterFunctions
lb
class LoadBalancerFilterFunctions { private static final Log log = LogFactory.getLog(LoadBalancerFilterFunctions.class); private LoadBalancerFilterFunctions() { } public static HandlerFilterFunction<ServerResponse, ServerResponse> lb(String serviceId) { return lb(serviceId, LoadBalancerUriTools::reconstructURI); } public static HandlerFilterFunction<ServerResponse, ServerResponse> lb(String serviceId, BiFunction<ServiceInstance, URI, URI> reconstructUriFunction) {<FILL_FUNCTION_BODY>} private static String getHint(LoadBalancerClientFactory clientFactory, 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; } private static MultiValueMap<String, String> buildCookies(MultiValueMap<String, Cookie> cookies) { HttpHeaders newCookies = new HttpHeaders(); if (cookies != null) { cookies.forEach((key, value) -> value .forEach(cookie -> newCookies.put(cookie.getName(), Collections.singletonList(cookie.getValue())))); } return newCookies; } static class DelegatingServiceInstance implements ServiceInstance { final ServiceInstance delegate; private String overrideScheme; DelegatingServiceInstance(ServiceInstance delegate, String overrideScheme) { this.delegate = delegate; this.overrideScheme = overrideScheme; } @Override public String getServiceId() { return delegate.getServiceId(); } @Override public String getHost() { return delegate.getHost(); } @Override public int getPort() { return delegate.getPort(); } @Override public boolean isSecure() { // TODO: move to map if ("https".equals(this.overrideScheme) || "wss".equals(this.overrideScheme)) { return true; } return delegate.isSecure(); } @Override public URI getUri() { return delegate.getUri(); } @Override public Map<String, String> getMetadata() { return delegate.getMetadata(); } @Override public String getScheme() { String scheme = delegate.getScheme(); if (scheme != null) { return scheme; } return this.overrideScheme; } } }
return (request, next) -> { LoadBalancerClientFactory clientFactory = getApplicationContext(request) .getBean(LoadBalancerClientFactory.class); Set<LoadBalancerLifecycle> supportedLifecycleProcessors = LoadBalancerLifecycleValidator .getSupportedLifecycleProcessors(clientFactory.getInstances(serviceId, LoadBalancerLifecycle.class), RequestDataContext.class, ResponseData.class, ServiceInstance.class); RequestData requestData = new RequestData(request.method(), request.uri(), request.headers().asHttpHeaders(), buildCookies(request.cookies()), request.attributes()); DefaultRequest<RequestDataContext> lbRequest = new DefaultRequest<>( new RequestDataContext(requestData, getHint(clientFactory, serviceId))); LoadBalancerClient loadBalancerClient = clientFactory.getInstance(serviceId, LoadBalancerClient.class); if (loadBalancerClient == null) { throw new HttpServerErrorException(HttpStatus.SERVICE_UNAVAILABLE, "No loadbalancer available for " + serviceId); } supportedLifecycleProcessors.forEach(lifecycle -> lifecycle.onStart(lbRequest)); ServiceInstance retrievedInstance = loadBalancerClient.choose(serviceId, lbRequest); if (retrievedInstance == null) { supportedLifecycleProcessors.forEach(lifecycle -> lifecycle .onComplete(new CompletionContext<>(CompletionContext.Status.DISCARD, lbRequest))); throw new HttpServerErrorException(HttpStatus.SERVICE_UNAVAILABLE, "Unable to find instance for " + serviceId); // throw NotFoundException.create(properties.isUse404(), "Unable to find // instance for " + serviceId); } URI uri = request.uri(); // if the `lb:<scheme>` mechanism was used, use `<scheme>` as the default, // if the loadbalancer doesn't provide one. String scheme = retrievedInstance.isSecure() ? "https" : "http"; DelegatingServiceInstance serviceInstance = new DelegatingServiceInstance(retrievedInstance, scheme); URI requestUrl = reconstructUriFunction.apply(serviceInstance, uri); if (log.isTraceEnabled()) { log.trace("LoadBalancerClientFilter url chosen: " + requestUrl); } MvcUtils.setRequestUrl(request, requestUrl); // exchange.getAttributes().put(GATEWAY_LOADBALANCER_RESPONSE_ATTR, response); DefaultResponse defaultResponse = new DefaultResponse(serviceInstance); supportedLifecycleProcessors.forEach(lifecycle -> lifecycle.onStartRequest(lbRequest, defaultResponse)); try { ServerResponse serverResponse = next.handle(request); supportedLifecycleProcessors.forEach( lifecycle -> lifecycle.onComplete(new CompletionContext<>(CompletionContext.Status.SUCCESS, lbRequest, defaultResponse, serverResponse))); return serverResponse; } catch (Exception e) { supportedLifecycleProcessors.forEach(lifecycle -> lifecycle.onComplete( new CompletionContext<>(CompletionContext.Status.FAILED, e, lbRequest, defaultResponse))); throw new RuntimeException(e); } };
707
884
1,591
jeecgboot_jeecg-boot
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/config/mybatis/MybatisInterceptor.java
MybatisInterceptor
getLoginUser
class MybatisInterceptor implements Interceptor { @Override public Object intercept(Invocation invocation) throws Throwable { MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0]; String sqlId = mappedStatement.getId(); log.debug("------sqlId------" + sqlId); SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType(); Object parameter = invocation.getArgs()[1]; log.debug("------sqlCommandType------" + sqlCommandType); if (parameter == null) { return invocation.proceed(); } if (SqlCommandType.INSERT == sqlCommandType) { LoginUser sysUser = this.getLoginUser(); Field[] fields = oConvertUtils.getAllFields(parameter); for (Field field : fields) { log.debug("------field.name------" + field.getName()); try { if ("createBy".equals(field.getName())) { field.setAccessible(true); Object localCreateBy = field.get(parameter); field.setAccessible(false); if (localCreateBy == null || "".equals(localCreateBy)) { if (sysUser != null) { // 登录人账号 field.setAccessible(true); field.set(parameter, sysUser.getUsername()); field.setAccessible(false); } } } // 注入创建时间 if ("createTime".equals(field.getName())) { field.setAccessible(true); Object localCreateDate = field.get(parameter); field.setAccessible(false); if (localCreateDate == null || "".equals(localCreateDate)) { field.setAccessible(true); field.set(parameter, new Date()); field.setAccessible(false); } } //注入部门编码 if ("sysOrgCode".equals(field.getName())) { field.setAccessible(true); Object localSysOrgCode = field.get(parameter); field.setAccessible(false); if (localSysOrgCode == null || "".equals(localSysOrgCode)) { // 获取登录用户信息 if (sysUser != null) { field.setAccessible(true); field.set(parameter, sysUser.getOrgCode()); field.setAccessible(false); } } } //------------------------------------------------------------------------------------------------ //注入租户ID(是否开启系统管理模块的多租户数据隔离【SAAS多租户模式】) if(MybatisPlusSaasConfig.OPEN_SYSTEM_TENANT_CONTROL) { if (TenantConstant.TENANT_ID.equals(field.getName())) { field.setAccessible(true); Object localTenantId = field.get(parameter); field.setAccessible(false); if (localTenantId == null) { field.setAccessible(true); field.set(parameter, oConvertUtils.getInt(TenantContext.getTenant(),0)); field.setAccessible(false); } } } //------------------------------------------------------------------------------------------------ } catch (Exception e) { } } } if (SqlCommandType.UPDATE == sqlCommandType) { LoginUser sysUser = this.getLoginUser(); Field[] fields = null; if (parameter instanceof ParamMap) { ParamMap<?> p = (ParamMap<?>) parameter; //update-begin-author:scott date:20190729 for:批量更新报错issues/IZA3Q-- String et = "et"; if (p.containsKey(et)) { parameter = p.get(et); } else { parameter = p.get("param1"); } //update-end-author:scott date:20190729 for:批量更新报错issues/IZA3Q- //update-begin-author:scott date:20190729 for:更新指定字段时报错 issues/#516- if (parameter == null) { return invocation.proceed(); } //update-end-author:scott date:20190729 for:更新指定字段时报错 issues/#516- fields = oConvertUtils.getAllFields(parameter); } else { fields = oConvertUtils.getAllFields(parameter); } for (Field field : fields) { log.debug("------field.name------" + field.getName()); try { if ("updateBy".equals(field.getName())) { //获取登录用户信息 if (sysUser != null) { // 登录账号 field.setAccessible(true); field.set(parameter, sysUser.getUsername()); field.setAccessible(false); } } if ("updateTime".equals(field.getName())) { field.setAccessible(true); field.set(parameter, new Date()); field.setAccessible(false); } } catch (Exception e) { e.printStackTrace(); } } } return invocation.proceed(); } @Override public Object plugin(Object target) { return Plugin.wrap(target, this); } @Override public void setProperties(Properties properties) { // TODO Auto-generated method stub } //update-begin--Author:scott Date:20191213 for:关于使用Quzrtz 开启线程任务, #465 /** * 获取登录用户 * @return */ private LoginUser getLoginUser() {<FILL_FUNCTION_BODY>} //update-end--Author:scott Date:20191213 for:关于使用Quzrtz 开启线程任务, #465 }
LoginUser sysUser = null; try { sysUser = SecurityUtils.getSubject().getPrincipal() != null ? (LoginUser) SecurityUtils.getSubject().getPrincipal() : null; } catch (Exception e) { //e.printStackTrace(); sysUser = null; } return sysUser;
1,573
90
1,663
docker-java_docker-java
docker-java/docker-java-api/src/main/java/com/github/dockerjava/api/model/TaskStatusContainerStatus.java
TaskStatusContainerStatus
withPid
class TaskStatusContainerStatus extends DockerObject implements Serializable { private static final long serialVersionUID = 1L; @JsonProperty("ContainerID") private String containerID = null; @JsonProperty("PID") private Long pid = null; @JsonProperty("ExitCode") private Long exitCode = null; public String getContainerID() { return containerID; } /** * * @deprecated use {@link #getPidLong()} */ @Deprecated public Integer getPid() { return pid != null ? pid.intValue() : null; } public Long getPidLong() { return pid; } /** * @deprecated use {@link #getExitCodeLong()} */ @Deprecated public Integer getExitCode() { return exitCode != null ? exitCode.intValue() : null; } public Long getExitCodeLong() { return exitCode; } public TaskStatusContainerStatus withContainerID(String containerID) { this.containerID = containerID; return this; } public TaskStatusContainerStatus withPid(Long pid) { this.pid = pid; return this; } /** * * @deprecated use {@link #withPid(Long)} */ @Deprecated public TaskStatusContainerStatus withPid(Integer pid) {<FILL_FUNCTION_BODY>} public TaskStatusContainerStatus withExitCode(Long exitCode) { this.exitCode = exitCode; return this; } /** * * @deprecated use {@link #withExitCode(Long)} */ @Deprecated public TaskStatusContainerStatus withExitCode(Integer exitCode) { this.exitCode = exitCode != null ? exitCode.longValue() : null; return this; } }
this.pid = pid != null ? pid.longValue() : null; return this;
493
27
520
/** * @see DockerObjectAccessor */ public abstract class DockerObject { HashMap<String,Object> rawValues=new HashMap<>(); @JsonAnyGetter public Map<String,Object> getRawValues(); }
YunaiV_ruoyi-vue-pro
ruoyi-vue-pro/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/dict/DictDataServiceImpl.java
DictDataServiceImpl
validateDictDataExists
class DictDataServiceImpl implements DictDataService { /** * 排序 dictType > sort */ private static final Comparator<DictDataDO> COMPARATOR_TYPE_AND_SORT = Comparator .comparing(DictDataDO::getDictType) .thenComparingInt(DictDataDO::getSort); @Resource private DictTypeService dictTypeService; @Resource private DictDataMapper dictDataMapper; @Override public List<DictDataDO> getDictDataList(Integer status, String dictType) { List<DictDataDO> list = dictDataMapper.selectListByStatusAndDictType(status, dictType); list.sort(COMPARATOR_TYPE_AND_SORT); return list; } @Override public PageResult<DictDataDO> getDictDataPage(DictDataPageReqVO pageReqVO) { return dictDataMapper.selectPage(pageReqVO); } @Override public DictDataDO getDictData(Long id) { return dictDataMapper.selectById(id); } @Override public Long createDictData(DictDataSaveReqVO createReqVO) { // 校验字典类型有效 validateDictTypeExists(createReqVO.getDictType()); // 校验字典数据的值的唯一性 validateDictDataValueUnique(null, createReqVO.getDictType(), createReqVO.getValue()); // 插入字典类型 DictDataDO dictData = BeanUtils.toBean(createReqVO, DictDataDO.class); dictDataMapper.insert(dictData); return dictData.getId(); } @Override public void updateDictData(DictDataSaveReqVO updateReqVO) { // 校验自己存在 validateDictDataExists(updateReqVO.getId()); // 校验字典类型有效 validateDictTypeExists(updateReqVO.getDictType()); // 校验字典数据的值的唯一性 validateDictDataValueUnique(updateReqVO.getId(), updateReqVO.getDictType(), updateReqVO.getValue()); // 更新字典类型 DictDataDO updateObj = BeanUtils.toBean(updateReqVO, DictDataDO.class); dictDataMapper.updateById(updateObj); } @Override public void deleteDictData(Long id) { // 校验是否存在 validateDictDataExists(id); // 删除字典数据 dictDataMapper.deleteById(id); } @Override public long getDictDataCountByDictType(String dictType) { return dictDataMapper.selectCountByDictType(dictType); } @VisibleForTesting public void validateDictDataValueUnique(Long id, String dictType, String value) { DictDataDO dictData = dictDataMapper.selectByDictTypeAndValue(dictType, value); if (dictData == null) { return; } // 如果 id 为空,说明不用比较是否为相同 id 的字典数据 if (id == null) { throw exception(DICT_DATA_VALUE_DUPLICATE); } if (!dictData.getId().equals(id)) { throw exception(DICT_DATA_VALUE_DUPLICATE); } } @VisibleForTesting public void validateDictDataExists(Long id) {<FILL_FUNCTION_BODY>} @VisibleForTesting public void validateDictTypeExists(String type) { DictTypeDO dictType = dictTypeService.getDictType(type); if (dictType == null) { throw exception(DICT_TYPE_NOT_EXISTS); } if (!CommonStatusEnum.ENABLE.getStatus().equals(dictType.getStatus())) { throw exception(DICT_TYPE_NOT_ENABLE); } } @Override public void validateDictDataList(String dictType, Collection<String> values) { if (CollUtil.isEmpty(values)) { return; } Map<String, DictDataDO> dictDataMap = CollectionUtils.convertMap( dictDataMapper.selectByDictTypeAndValues(dictType, values), DictDataDO::getValue); // 校验 values.forEach(value -> { DictDataDO dictData = dictDataMap.get(value); if (dictData == null) { throw exception(DICT_DATA_NOT_EXISTS); } if (!CommonStatusEnum.ENABLE.getStatus().equals(dictData.getStatus())) { throw exception(DICT_DATA_NOT_ENABLE, dictData.getLabel()); } }); } @Override public DictDataDO getDictData(String dictType, String value) { return dictDataMapper.selectByDictTypeAndValue(dictType, value); } @Override public DictDataDO parseDictData(String dictType, String label) { return dictDataMapper.selectByDictTypeAndLabel(dictType, label); } @Override public List<DictDataDO> getDictDataListByDictType(String dictType) { List<DictDataDO> list = dictDataMapper.selectList(DictDataDO::getDictType, dictType); list.sort(Comparator.comparing(DictDataDO::getSort)); return list; } }
if (id == null) { return; } DictDataDO dictData = dictDataMapper.selectById(id); if (dictData == null) { throw exception(DICT_DATA_NOT_EXISTS); }
1,435
65
1,500
DerekYRC_mini-spring
mini-spring/src/main/java/org/springframework/context/annotation/ClassPathBeanDefinitionScanner.java
ClassPathBeanDefinitionScanner
doScan
class ClassPathBeanDefinitionScanner extends ClassPathScanningCandidateComponentProvider { public static final String AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME = "org.springframework.context.annotation.internalAutowiredAnnotationProcessor"; private BeanDefinitionRegistry registry; public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry) { this.registry = registry; } public void doScan(String... basePackages) {<FILL_FUNCTION_BODY>} /** * 获取bean的作用域 * * @param beanDefinition * @return */ private String resolveBeanScope(BeanDefinition beanDefinition) { Class<?> beanClass = beanDefinition.getBeanClass(); Scope scope = beanClass.getAnnotation(Scope.class); if (scope != null) { return scope.value(); } return StrUtil.EMPTY; } /** * 生成bean的名称 * * @param beanDefinition * @return */ private String determineBeanName(BeanDefinition beanDefinition) { Class<?> beanClass = beanDefinition.getBeanClass(); Component component = beanClass.getAnnotation(Component.class); String value = component.value(); if (StrUtil.isEmpty(value)) { value = StrUtil.lowerFirst(beanClass.getSimpleName()); } return value; } }
for (String basePackage : basePackages) { Set<BeanDefinition> candidates = findCandidateComponents(basePackage); for (BeanDefinition candidate : candidates) { // 解析bean的作用域 String beanScope = resolveBeanScope(candidate); if (StrUtil.isNotEmpty(beanScope)) { candidate.setScope(beanScope); } //生成bean的名称 String beanName = determineBeanName(candidate); //注册BeanDefinition registry.registerBeanDefinition(beanName, candidate); } } //注册处理@Autowired和@Value注解的BeanPostProcessor registry.registerBeanDefinition(AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME, new BeanDefinition(AutowiredAnnotationBeanPostProcessor.class));
358
209
567
/** * @author derekyi * @date 2020/12/26 */ public class ClassPathScanningCandidateComponentProvider { public Set<BeanDefinition> findCandidateComponents( String basePackage); }
docker-java_docker-java
docker-java/docker-java-core/src/main/java/com/github/dockerjava/core/exec/CopyArchiveToContainerCmdExec.java
CopyArchiveToContainerCmdExec
execute
class CopyArchiveToContainerCmdExec extends AbstrSyncDockerCmdExec<CopyArchiveToContainerCmd, Void> implements CopyArchiveToContainerCmd.Exec { private static final Logger LOGGER = LoggerFactory.getLogger(CopyArchiveFromContainerCmdExec.class); public CopyArchiveToContainerCmdExec(WebTarget baseResource, DockerClientConfig dockerClientConfig) { super(baseResource, dockerClientConfig); } @Override protected Void execute(CopyArchiveToContainerCmd command) {<FILL_FUNCTION_BODY>} }
WebTarget webResource = getBaseResource().path("/containers/{id}/archive").resolveTemplate("id", command.getContainerId()); LOGGER.trace("PUT: " + webResource.toString()); InputStream streamToUpload = command.getTarInputStream(); webResource.queryParam("path", command.getRemotePath()) .queryParam("noOverwriteDirNonDir", command.isNoOverwriteDirNonDir()) .queryParam("copyUIDGID", command.isCopyUIDGID()) .request() .put(streamToUpload, MediaType.APPLICATION_X_TAR); return null;
143
159
302
YunaiV_ruoyi-vue-pro
ruoyi-vue-pro/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/social/SocialUserServiceImpl.java
SocialUserServiceImpl
getSocialUserList
class SocialUserServiceImpl implements SocialUserService { @Resource private SocialUserBindMapper socialUserBindMapper; @Resource private SocialUserMapper socialUserMapper; @Resource private SocialClientService socialClientService; @Override public List<SocialUserDO> getSocialUserList(Long userId, Integer userType) {<FILL_FUNCTION_BODY>} @Override @Transactional(rollbackFor = Exception.class) public String bindSocialUser(SocialUserBindReqDTO reqDTO) { // 获得社交用户 SocialUserDO socialUser = authSocialUser(reqDTO.getSocialType(), reqDTO.getUserType(), reqDTO.getCode(), reqDTO.getState()); Assert.notNull(socialUser, "社交用户不能为空"); // 社交用户可能之前绑定过别的用户,需要进行解绑 socialUserBindMapper.deleteByUserTypeAndSocialUserId(reqDTO.getUserType(), socialUser.getId()); // 用户可能之前已经绑定过该社交类型,需要进行解绑 socialUserBindMapper.deleteByUserTypeAndUserIdAndSocialType(reqDTO.getUserType(), reqDTO.getUserId(), socialUser.getType()); // 绑定当前登录的社交用户 SocialUserBindDO socialUserBind = SocialUserBindDO.builder() .userId(reqDTO.getUserId()).userType(reqDTO.getUserType()) .socialUserId(socialUser.getId()).socialType(socialUser.getType()).build(); socialUserBindMapper.insert(socialUserBind); return socialUser.getOpenid(); } @Override public void unbindSocialUser(Long userId, Integer userType, Integer socialType, String openid) { // 获得 openid 对应的 SocialUserDO 社交用户 SocialUserDO socialUser = socialUserMapper.selectByTypeAndOpenid(socialType, openid); if (socialUser == null) { throw exception(SOCIAL_USER_NOT_FOUND); } // 获得对应的社交绑定关系 socialUserBindMapper.deleteByUserTypeAndUserIdAndSocialType(userType, userId, socialUser.getType()); } @Override public SocialUserRespDTO getSocialUserByUserId(Integer userType, Long userId, Integer socialType) { // 获得绑定用户 SocialUserBindDO socialUserBind = socialUserBindMapper.selectByUserIdAndUserTypeAndSocialType(userId, userType, socialType); if (socialUserBind == null) { return null; } // 获得社交用户 SocialUserDO socialUser = socialUserMapper.selectById(socialUserBind.getSocialUserId()); Assert.notNull(socialUser, "社交用户不能为空"); return new SocialUserRespDTO(socialUser.getOpenid(), socialUser.getNickname(), socialUser.getAvatar(), socialUserBind.getUserId()); } @Override public SocialUserRespDTO getSocialUserByCode(Integer userType, Integer socialType, String code, String state) { // 获得社交用户 SocialUserDO socialUser = authSocialUser(socialType, userType, code, state); Assert.notNull(socialUser, "社交用户不能为空"); // 获得绑定用户 SocialUserBindDO socialUserBind = socialUserBindMapper.selectByUserTypeAndSocialUserId(userType, socialUser.getId()); return new SocialUserRespDTO(socialUser.getOpenid(), socialUser.getNickname(), socialUser.getAvatar(), socialUserBind != null ? socialUserBind.getUserId() : null); } /** * 授权获得对应的社交用户 * 如果授权失败,则会抛出 {@link ServiceException} 异常 * * @param socialType 社交平台的类型 {@link SocialTypeEnum} * @param userType 用户类型 * @param code 授权码 * @param state state * @return 授权用户 */ @NotNull public SocialUserDO authSocialUser(Integer socialType, Integer userType, String code, String state) { // 优先从 DB 中获取,因为 code 有且可以使用一次。 // 在社交登录时,当未绑定 User 时,需要绑定登录,此时需要 code 使用两次 SocialUserDO socialUser = socialUserMapper.selectByTypeAndCodeAnState(socialType, code, state); if (socialUser != null) { return socialUser; } // 请求获取 AuthUser authUser = socialClientService.getAuthUser(socialType, userType, code, state); Assert.notNull(authUser, "三方用户不能为空"); // 保存到 DB 中 socialUser = socialUserMapper.selectByTypeAndOpenid(socialType, authUser.getUuid()); if (socialUser == null) { socialUser = new SocialUserDO(); } socialUser.setType(socialType).setCode(code).setState(state) // 需要保存 code + state 字段,保证后续可查询 .setOpenid(authUser.getUuid()).setToken(authUser.getToken().getAccessToken()).setRawTokenInfo((toJsonString(authUser.getToken()))) .setNickname(authUser.getNickname()).setAvatar(authUser.getAvatar()).setRawUserInfo(toJsonString(authUser.getRawUserInfo())); if (socialUser.getId() == null) { socialUserMapper.insert(socialUser); } else { socialUserMapper.updateById(socialUser); } return socialUser; } // ==================== 社交用户 CRUD ==================== @Override public SocialUserDO getSocialUser(Long id) { return socialUserMapper.selectById(id); } @Override public PageResult<SocialUserDO> getSocialUserPage(SocialUserPageReqVO pageReqVO) { return socialUserMapper.selectPage(pageReqVO); } }
// 获得绑定 List<SocialUserBindDO> socialUserBinds = socialUserBindMapper.selectListByUserIdAndUserType(userId, userType); if (CollUtil.isEmpty(socialUserBinds)) { return Collections.emptyList(); } // 获得社交用户 return socialUserMapper.selectBatchIds(convertSet(socialUserBinds, SocialUserBindDO::getSocialUserId));
1,562
108
1,670
orientechnologies_orientdb
orientdb/distributed/src/main/java/com/orientechnologies/orient/server/distributed/impl/metadata/OSharedContextDistributed.java
OSharedContextDistributed
reload
class OSharedContextDistributed extends OSharedContextEmbedded { public OSharedContextDistributed(OStorage storage, OrientDBDistributed orientDB) { super(storage, orientDB); } protected void init(OStorage storage) { stringCache = new OStringCache( storage .getConfiguration() .getContextConfiguration() .getValueAsInteger(OGlobalConfiguration.DB_STRING_CAHCE_SIZE)); schema = new OSchemaDistributed(this); security = orientDB.getSecuritySystem().newSecurity(storage.getName()); indexManager = new OIndexManagerDistributed(storage); functionLibrary = new OFunctionLibraryImpl(); scheduler = new OSchedulerImpl(orientDB); sequenceLibrary = new OSequenceLibraryImpl(); liveQueryOps = new OLiveQueryHook.OLiveQueryOps(); liveQueryOpsV2 = new OLiveQueryHookV2.OLiveQueryOps(); statementCache = new OStatementCache( storage .getConfiguration() .getContextConfiguration() .getValueAsInteger(OGlobalConfiguration.STATEMENT_CACHE_SIZE)); executionPlanCache = new OExecutionPlanCache( storage .getConfiguration() .getContextConfiguration() .getValueAsInteger(OGlobalConfiguration.STATEMENT_CACHE_SIZE)); this.registerListener(executionPlanCache); queryStats = new OQueryStats(); activeDistributedQueries = new HashMap<>(); ((OAbstractPaginatedStorage) storage) .setStorageConfigurationUpdateListener( update -> { for (OMetadataUpdateListener listener : browseListeners()) { listener.onStorageConfigurationUpdate(storage.getName(), update); } }); this.viewManager = new ViewManager(orientDB, storage.getName()); } public synchronized void load(ODatabaseDocumentInternal database) { OScenarioThreadLocal.executeAsDistributed( () -> { final long timer = PROFILER.startChrono(); try { if (!loaded) { schema.load(database); indexManager.load(database); // The Immutable snapshot should be after index and schema that require and before // everything else that use it schema.forceSnapshot(database); security.load(database); functionLibrary.load(database); scheduler.load(database); sequenceLibrary.load(database); schema.onPostIndexManagement(); viewManager.load(); loaded = true; } } finally { PROFILER.stopChrono( PROFILER.getDatabaseMetric(database.getName(), "metadata.load"), "Loading of database metadata", timer, "db.*.metadata.load"); } return null; }); } @Override public synchronized void close() { stringCache.close(); viewManager.close(); schema.close(); security.close(); indexManager.close(); functionLibrary.close(); scheduler.close(); sequenceLibrary.close(); statementCache.clear(); executionPlanCache.invalidate(); liveQueryOps.close(); liveQueryOpsV2.close(); activeDistributedQueries.values().forEach(x -> x.close()); loaded = false; } public synchronized void reload(ODatabaseDocumentInternal database) {<FILL_FUNCTION_BODY>} public synchronized void create(ODatabaseDocumentInternal database) { OScenarioThreadLocal.executeAsDistributed( () -> { schema.create(database); indexManager.create(database); security.create(database); functionLibrary.create(database); sequenceLibrary.create(database); security.createClassTrigger(database); scheduler.create(database); // CREATE BASE VERTEX AND EDGE CLASSES schema.createClass(database, "V"); schema.createClass(database, "E"); // create geospatial classes try { OIndexFactory factory = OIndexes.getFactory(OClass.INDEX_TYPE.SPATIAL.toString(), "LUCENE"); if (factory != null && factory instanceof ODatabaseLifecycleListener) { ((ODatabaseLifecycleListener) factory).onCreate(database); } } catch (OIndexException x) { // the index does not exist } viewManager.create(); schema.forceSnapshot(database); loaded = true; return null; }); } public ViewManager getViewManager() { return viewManager; } }
OScenarioThreadLocal.executeAsDistributed( () -> { schema.reload(database); indexManager.reload(); // The Immutable snapshot should be after index and schema that require and before // everything else that use it schema.forceSnapshot(database); security.load(database); functionLibrary.load(database); sequenceLibrary.load(database); scheduler.load(database); return null; });
1,178
117
1,295
/** * Created by tglman on 13/06/17. */ public class OSharedContextEmbedded extends OSharedContext { protected Map<String,DistributedQueryContext> activeDistributedQueries; protected ViewManager viewManager; public OSharedContextEmbedded( OStorage storage, OrientDBEmbedded orientDB); protected void init( OStorage storage); public synchronized void load( ODatabaseDocumentInternal database); @Override public synchronized void close(); public synchronized void reload( ODatabaseDocumentInternal database); public synchronized void create( ODatabaseDocumentInternal database); public Map<String,DistributedQueryContext> getActiveDistributedQueries(); public ViewManager getViewManager(); public synchronized void reInit( OAbstractPaginatedStorage storage2, ODatabaseDocumentInternal database); public synchronized ODocument loadConfig( ODatabaseSession session, String name); /** * Store a configuration with a key, without checking eventual update version. * @param session * @param name * @param value */ public synchronized void saveConfig( ODatabaseSession session, String name, ODocument value); public ODocument loadDistributedConfig( ODatabaseSession session); public void saveDistributedConfig( ODatabaseSession session, String name, ODocument value); }
ainilili_ratel
ratel/landlords-server/src/main/java/org/nico/ratel/landlords/server/event/ServerEventListener_CODE_CLIENT_EXIT.java
ServerEventListener_CODE_CLIENT_EXIT
notifyWatcherClientExit
class ServerEventListener_CODE_CLIENT_EXIT implements ServerEventListener { private static final Object locked = new Object(); @Override public void call(ClientSide clientSide, String data) { synchronized (locked){ Room room = ServerContains.getRoom(clientSide.getRoomId()); if (room == null) { return; } String result = MapHelper.newInstance() .put("roomId", room.getId()) .put("exitClientId", clientSide.getId()) .put("exitClientNickname", clientSide.getNickname()) .json(); for (ClientSide client : room.getClientSideList()) { if (client.getRole() == ClientRole.PLAYER) { ChannelUtils.pushToClient(client.getChannel(), ClientEventCode.CODE_CLIENT_EXIT, result); client.init(); } } notifyWatcherClientExit(room, clientSide); ServerContains.removeRoom(room.getId()); } } /** * 通知所有观战者玩家退出游戏 * * @param room 房间 * @param player 退出游戏玩家 */ private void notifyWatcherClientExit(Room room, ClientSide player) {<FILL_FUNCTION_BODY>} }
for (ClientSide watcher : room.getWatcherList()) { ChannelUtils.pushToClient(watcher.getChannel(), ClientEventCode.CODE_CLIENT_EXIT, player.getNickname()); }
338
59
397
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-serializer/autoload-cache-serializer-jdk/src/main/java/com/jarvis/cache/serializer/JdkSerializer.java
JdkSerializer
deserialize
class JdkSerializer implements ISerializer<Object> { @Override public Object deserialize(byte[] bytes, Type returnType) throws Exception {<FILL_FUNCTION_BODY>} @Override public byte[] serialize(Object obj) throws Exception { if (obj == null) { return new byte[0]; } // 将对象写到流里 ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutputStream output = new ObjectOutputStream(outputStream); output.writeObject(obj); output.flush(); return outputStream.toByteArray(); } @Override public Object deepClone(Object obj, final Type type) throws Exception { if (null == obj) { return obj; } Class<?> clazz = obj.getClass(); if (BeanUtil.isPrimitive(obj) || clazz.isEnum() || obj instanceof Class || clazz.isAnnotation() || clazz.isSynthetic()) {// 常见不会被修改的数据类型 return obj; } if (obj instanceof Date) { return ((Date) obj).clone(); } else if (obj instanceof Calendar) { Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(((Calendar) obj).getTime().getTime()); return cal; } return deserialize(serialize(obj), null); } @Override public Object[] deepCloneMethodArgs(Method method, Object[] args) throws Exception { if (null == args || args.length == 0) { return args; } Type[] genericParameterTypes = method.getGenericParameterTypes(); if (args.length != genericParameterTypes.length) { throw new Exception("the length of " + method.getDeclaringClass().getName() + "." + method.getName() + " must " + genericParameterTypes.length); } Object[] res = new Object[args.length]; int len = genericParameterTypes.length; for (int i = 0; i < len; i++) { res[i] = deepClone(args[i], null); } return res; } }
if (null == bytes || bytes.length == 0) { return null; } ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInputStream input = new ObjectInputStream(inputStream); return input.readObject();
546
62
608
YunaiV_ruoyi-vue-pro
ruoyi-vue-pro/yudao-framework/yudao-spring-boot-starter-biz-tenant/src/main/java/cn/iocoder/yudao/framework/tenant/core/service/TenantFrameworkServiceImpl.java
TenantFrameworkServiceImpl
load
class TenantFrameworkServiceImpl implements TenantFrameworkService { private static final ServiceException SERVICE_EXCEPTION_NULL = new ServiceException(); private final TenantApi tenantApi; /** * 针对 {@link #getTenantIds()} 的缓存 */ private final LoadingCache<Object, List<Long>> getTenantIdsCache = CacheUtils.buildAsyncReloadingCache( Duration.ofMinutes(1L), // 过期时间 1 分钟 new CacheLoader<Object, List<Long>>() { @Override public List<Long> load(Object key) { return tenantApi.getTenantIdList(); } }); /** * 针对 {@link #validTenant(Long)} 的缓存 */ private final LoadingCache<Long, ServiceException> validTenantCache = CacheUtils.buildAsyncReloadingCache( Duration.ofMinutes(1L), // 过期时间 1 分钟 new CacheLoader<Long, ServiceException>() { @Override public ServiceException load(Long id) {<FILL_FUNCTION_BODY>} }); @Override @SneakyThrows public List<Long> getTenantIds() { return getTenantIdsCache.get(Boolean.TRUE); } @Override public void validTenant(Long id) { ServiceException serviceException = validTenantCache.getUnchecked(id); if (serviceException != SERVICE_EXCEPTION_NULL) { throw serviceException; } } }
try { tenantApi.validateTenant(id); return SERVICE_EXCEPTION_NULL; } catch (ServiceException ex) { return ex; }
404
48
452
Kong_unirest-java
unirest-java/unirest/src/main/java/kong/unirest/core/java/PartSubscriber.java
PartSubscriber
abortUpstream
class PartSubscriber implements Flow.Subscriber<ByteBuffer> { static final ByteBuffer END_OF_PART = ByteBuffer.allocate(0); private final MultipartSubscription downstream; // for signalling private final Part part; private final ProgressMonitor monitor; private final ConcurrentLinkedQueue<ByteBuffer> buffers; private final Upstream upstream; private final Prefetcher prefetcher; private long total; PartSubscriber(MultipartSubscription downstream, Part part, ProgressMonitor monitor) { this.downstream = downstream; this.part = part; this.monitor = monitor; buffers = new ConcurrentLinkedQueue<>(); upstream = new Upstream(); prefetcher = new Prefetcher(); } @Override public void onSubscribe(Flow.Subscription subscription) { requireNonNull(subscription); if (upstream.setOrCancel(subscription)) { // The only possible concurrent access to prefetcher applies here. // But the operation need not be atomic as other reads/writes // are done serially when ByteBuffers are polled, which is only // possible after this volatile write. prefetcher.initialize(upstream); } } @Override public void onNext(ByteBuffer item) { requireNonNull(item); buffers.offer(item); if(monitor != null) { this.total = total + item.remaining(); monitor.accept(part.getFieldName(), part.getFilename(), Long.valueOf(item.remaining()), total); } downstream.signal(false); } @Override public void onError(Throwable throwable) { requireNonNull(throwable); abortUpstream(false); downstream.signalError(throwable); } @Override public void onComplete() { abortUpstream(false); buffers.offer(END_OF_PART); downstream.signal(true); // force completion signal } void abortUpstream(boolean cancel) {<FILL_FUNCTION_BODY>} ByteBuffer pollNext() { ByteBuffer next = buffers.peek(); if (next != null && next != END_OF_PART) { buffers.poll(); // remove prefetcher.update(upstream); } return next; } public Part getPart() { return part; } }
if (cancel) { upstream.cancel(); } else { upstream.clear(); }
639
32
671
jitsi_jitsi
jitsi/modules/impl/gui/src/main/java/net/java/sip/communicator/impl/gui/main/chatroomslist/joinforms/JoinChatRoomDialog.java
JoinChatRoomDialog
actionPerformed
class JoinChatRoomDialog extends SIPCommDialog implements ActionListener, Skinnable { private SearchChatRoomPanel searchPanel; private JButton joinButton = new JButton( GuiActivator.getResources().getI18NString("service.gui.JOIN")); private JButton cancelButton = new JButton( GuiActivator.getResources().getI18NString("service.gui.CANCEL")); private JLabel iconLabel = new JLabel(new ImageIcon(ImageLoader .getImage(ImageLoader.ADD_CONTACT_CHAT_ICON))); private JPanel buttonsPanel = new TransparentPanel(new FlowLayout(FlowLayout.RIGHT)); private ChatRoomProviderWrapper chatRoomProvider; /** * Creates an instance of <tt>JoinChatRoomDialog</tt>. * * @param provider the <tt>ChatRoomProviderWrapper</tt>, which will be the chat * server for the newly created chat room */ public JoinChatRoomDialog(ChatRoomProviderWrapper provider) { this.chatRoomProvider = provider; this.searchPanel = new SearchChatRoomPanel(chatRoomProvider); this.setTitle( GuiActivator.getResources() .getI18NString("service.gui.JOIN_CHAT_ROOM")); this.getRootPane().setDefaultButton(joinButton); this.joinButton.setName("join"); this.cancelButton.setName("cancel"); this.joinButton.setMnemonic( GuiActivator.getResources().getI18nMnemonic("service.gui.JOIN")); this.cancelButton.setMnemonic( GuiActivator.getResources().getI18nMnemonic("service.gui.CANCEL")); this.iconLabel.setBorder(BorderFactory.createEmptyBorder(5, 0, 5, 10)); this.joinButton.addActionListener(this); this.cancelButton.addActionListener(this); this.buttonsPanel.add(joinButton); this.buttonsPanel.add(cancelButton); this.getContentPane().add(iconLabel, BorderLayout.WEST); this.getContentPane().add(searchPanel, BorderLayout.CENTER); this.getContentPane().add(buttonsPanel, BorderLayout.SOUTH); } /** * Handles the <tt>ActionEvent</tt>. Depending on the user choice creates * the desired chat room in a separate thread. * <br> * Note: No specific properties are set right now! * * @param e the <tt>ActionEvent</tt> that notified us */ public void actionPerformed(ActionEvent e) {<FILL_FUNCTION_BODY>} /** * When escape is pressed clicks the cancel button programatically. * * @param escaped indicates if the window was closed by pressing the Esc * key */ @Override protected void close(boolean escaped) { this.cancelButton.doClick(); } /** * Shows this dialog. And requests the current focus in the chat room name * field. */ public void showDialog() { this.setVisible(true); searchPanel.requestFocusInField(); } /** * Reloads icon label. */ public void loadSkin() { iconLabel.setIcon(new ImageIcon(ImageLoader .getImage(ImageLoader.ADD_CONTACT_CHAT_ICON))); } }
JButton button = (JButton)e.getSource(); String name = button.getName(); if (name.equals("service.gui.JOIN")) { GuiActivator.getMUCService().joinChatRoom( searchPanel.getChatRoomName(), chatRoomProvider); } this.dispose();
938
89
1,027
/** * @author Yana Stamcheva * @author Lubomir Marinov */ public class SIPCommDialog extends JDialog { /** * Serial version UID. */ private static final long serialVersionUID=0L; /** * The <tt>Logger</tt> used by the <tt>SIPCommDialog</tt> class and its instances for logging output. */ private static final org.slf4j.Logger logger=org.slf4j.LoggerFactory.getLogger(SIPCommDialog.class); /** * The action map of this dialog. */ private ActionMap amap; /** * The input map of this dialog. */ private InputMap imap; /** * Indicates if the size and location of this dialog are stored after closing. */ private boolean isSaveSizeAndLocation=true; /** * Creates an instance of <tt>SIPCommDialog</tt>. */ public SIPCommDialog(); /** * Creates an instance of <tt>SIPCommDialog</tt> by specifying the <tt>Dialog</tt>owner of this dialog. * @param owner the owner of this dialog */ public SIPCommDialog( Dialog owner); /** * Creates an instance of <tt>SIPCommDialog</tt> by specifying the <tt>Frame</tt> owner. * @param owner the owner of this dialog */ public SIPCommDialog( Frame owner); /** * Creates an instance of <tt>SIPCommDialog</tt> by specifying the <tt>Frame</tt> owner. * @param owner the owner of this dialog */ public SIPCommDialog( Window owner); /** * Creates an instance of <tt>SIPCommDialog</tt> by specifying explicitly if the size and location properties are saved. By default size and location are stored. * @param isSaveSizeAndLocation indicates whether to save the size andlocation of this dialog */ public SIPCommDialog( boolean isSaveSizeAndLocation); /** * Creates an instance of <tt>SIPCommDialog</tt> by specifying the owner of this dialog and indicating whether to save the size and location properties. * @param owner the owner of this dialog * @param isSaveSizeAndLocation indicates whether to save the size andlocation of this dialog */ public SIPCommDialog( Dialog owner, boolean isSaveSizeAndLocation); /** * Creates an instance of <tt>SIPCommDialog</tt> by specifying the owner of this dialog and indicating whether to save the size and location properties. * @param owner the owner of this dialog * @param isSaveSizeAndLocation indicates whether to save the size andlocation of this dialog */ public SIPCommDialog( Frame owner, boolean isSaveSizeAndLocation); /** * Creates an instance of <tt>SIPCommDialog</tt> by specifying the owner of this dialog and indicating whether to save the size and location properties. * @param owner the owner of this dialog * @param isSaveSizeAndLocation indicates whether to save the size andlocation of this dialog */ public SIPCommDialog( Window owner, boolean isSaveSizeAndLocation); /** * Initializes this dialog. */ private void init(); private void initInputMap(); /** * The action invoked when user presses Escape key. */ private class CloseAction extends UIAction { /** * Serial version UID. */ private static final long serialVersionUID=0L; public void actionPerformed( ActionEvent e); } /** * Adds a key - action pair for this frame. * @param keyStroke the key combination * @param action the action which will be executed when user presses thegiven key combination */ protected void addKeyBinding( KeyStroke keyStroke, Action action); /** * Before closing the application window saves the current size and position through the <tt>ConfigurationService</tt>. */ public class DialogWindowAdapter extends WindowAdapter { /** * Invoked when this window is in the process of being closed. * @param e the <tt>WindowEvent</tt> that notified us */ @Override public void windowClosing( WindowEvent e); } /** * Saves the size and the location of this dialog through the <tt>ConfigurationService</tt>. */ private void saveSizeAndLocation(); /** * Sets window size and position. */ private void setSizeAndLocation(); /** * Positions this window in the center of the screen. */ private void setCenterLocation(); /** * Checks whether the current component will exceeds the screen size and if it do will set a default size */ private void ensureOnScreenLocationAndSize(); /** * Overwrites the setVisible method in order to set the size and the position of this window before showing it. * @param isVisible indicates if the dialog should be visible */ @Override public void setVisible( boolean isVisible); /** * Overwrites the dispose method in order to save the size and the position of this window before closing it. */ @Override public void dispose(); /** * All functions implemented in this method will be invoked when user presses the Escape key. * @param escaped <tt>true</tt> if this frame has been closed by pressingthe Esc key; otherwise, <tt>false</tt> */ protected void close( boolean escaped); }
pmd_pmd
pmd/pmd-core/src/main/java/net/sourceforge/pmd/properties/internal/PropertyParsingUtil.java
PropertyParsingUtil
checkConstraintsThrow
class PropertyParsingUtil { public static final ValueSyntax<String> STRING = ValueSyntax.withDefaultToString(String::trim); public static final ValueSyntax<Character> CHARACTER = ValueSyntax.partialFunction( c -> Character.toString(c), s -> s.charAt(0), PropertyConstraint.fromPredicate( s -> s.length() == 1, "Should be exactly one character in length" )); public static final ValueSyntax<Pattern> REGEX = ValueSyntax.withDefaultToString(Pattern::compile); public static final ValueSyntax<Integer> INTEGER = ValueSyntax.withDefaultToString(preTrim(Integer::valueOf)); public static final ValueSyntax<Long> LONG = ValueSyntax.withDefaultToString(preTrim(Long::valueOf)); public static final ValueSyntax<Boolean> BOOLEAN = ValueSyntax.withDefaultToString(preTrim(Boolean::valueOf)); public static final ValueSyntax<Double> DOUBLE = ValueSyntax.withDefaultToString(preTrim(Double::valueOf)); public static final PropertySerializer<List<Integer>> INTEGER_LIST = numberList(INTEGER); public static final PropertySerializer<List<Double>> DOUBLE_LIST = numberList(DOUBLE); public static final PropertySerializer<List<Long>> LONG_LIST = numberList(LONG); public static final PropertySerializer<List<Character>> CHAR_LIST = otherList(CHARACTER); public static final PropertySerializer<List<String>> STRING_LIST = otherList(STRING); private PropertyParsingUtil() { } private static <T extends Number> PropertySerializer<List<T>> numberList(ValueSyntax<T> valueSyntax) { return delimitedString(valueSyntax, Collectors.toList()); } private static <T> PropertySerializer<List<T>> otherList(ValueSyntax<T> valueSyntax) { return delimitedString(valueSyntax, Collectors.toList() /* prefer old syntax for now */); } private static <T> Function<String, ? extends T> preTrim(Function<? super String, ? extends T> parser) { return parser.compose(String::trim); } public static <T> PropertySerializer<Optional<T>> toOptional(PropertySerializer<T> itemSyntax, String missingValue) { return ValueSyntax.create( opt -> opt.map(itemSyntax::toString).orElse(missingValue), str -> { if (str.equals(missingValue)) { return Optional.empty(); } return Optional.of(itemSyntax.fromString(str)); } ); } /** * Checks the result of the constraints defined by this mapper on * the given element. Returns all failures as a list of strings. */ public static <T> void checkConstraintsThrow(T t, List<? extends PropertyConstraint<? super T>> constraints) {<FILL_FUNCTION_BODY>} public static <T> PropertySerializer<T> withAllConstraints(PropertySerializer<T> mapper, List<PropertyConstraint<? super T>> constraints) { PropertySerializer<T> result = mapper; for (PropertyConstraint<? super T> constraint : constraints) { result = result.withConstraint(constraint); } return result; } /** * Builds an XML syntax that understands delimited {@code <value>} syntax. * * @param <T> Type of items * @param <C> Type of collection to handle * @param itemSyntax Serializer for the items, must support string mapping * @param collector Collector to create the collection from strings * * @throws IllegalArgumentException If the item syntax doesn't support string mapping */ public static <T, C extends Iterable<T>> PropertySerializer<C> delimitedString(PropertySerializer<T> itemSyntax, Collector<? super T, ?, ? extends C> collector) { String delim = "" + PropertyFactory.DEFAULT_DELIMITER; return ValueSyntax.create( coll -> IteratorUtil.toStream(coll.iterator()).map(itemSyntax::toString).collect(Collectors.joining(delim)), string -> parseListWithEscapes(string, PropertyFactory.DEFAULT_DELIMITER, itemSyntax::fromString).stream().collect(collector) ); } private static final char ESCAPE_CHAR = '\\'; /** * Parse a list delimited with the given delimiter, converting individual * values to type {@code <U>} with the given extractor. Any character is * escaped with a backslash. This is useful to escape the delimiter, and * to escape the backslash. For example: * <pre>{@code * * "a,c" -> [ "a", "c" ] * "a\,c" -> [ "a,c" ] * "a\c" -> [ "ac" ] * "a\\c" -> [ "a\c" ] * "a\" -> [ "a\" ] (a backslash at the end of the string is just a backslash) * * }</pre> */ public static <U> List<U> parseListWithEscapes(String str, char delimiter, Function<? super String, ? extends U> extractor) { if (str.isEmpty()) { return Collections.emptyList(); } List<U> result = new ArrayList<>(); StringBuilder currentToken = new StringBuilder(); boolean inEscapeMode = false; for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); if (inEscapeMode) { inEscapeMode = false; currentToken.append(c); } else if (c == delimiter) { result.add(extractor.apply(currentToken.toString())); currentToken = new StringBuilder(); } else if (c == ESCAPE_CHAR && i < str.length() - 1) { // this is ordered this way so that if the delimiter is // itself a backslash, no escapes are processed. inEscapeMode = true; } else { currentToken.append(c); } } if (currentToken.length() > 0) { result.add(extractor.apply(currentToken.toString())); } return result; } public static <T> ValueSyntax<T> enumerationParser(final Map<String, T> mappings, Function<? super T, String> reverseFun) { if (mappings.containsValue(null)) { throw new IllegalArgumentException("Map may not contain entries with null values"); } return ValueSyntax.partialFunction( reverseFun, mappings::get, PropertyConstraint.fromPredicate( mappings::containsKey, "Should be " + XmlUtil.formatPossibleNames(XmlUtil.toConstants(mappings.keySet())) ) ); } }
ConstraintViolatedException exception = null; for (PropertyConstraint<? super T> constraint : constraints) { try { constraint.validate(t); } catch (ConstraintViolatedException e) { if (exception == null) { exception = e; } else { exception.addSuppressed(e); } } } if (exception != null) { throw exception; }
1,786
114
1,900
logfellow_logstash-logback-encoder
logstash-logback-encoder/src/main/java/net/logstash/logback/composite/AbstractJsonProvider.java
AbstractJsonProvider
assertIsStarted
class AbstractJsonProvider<Event extends DeferredProcessingAware> extends ContextAwareBase implements JsonProvider<Event> { private volatile boolean started; @Override public void start() { started = true; } @Override public void stop() { started = false; } @Override public boolean isStarted() { return started; } @Override public void prepareForDeferredProcessing(Event event) { } /** * Assert the component is started and throw {@link IllegalStateException} if not * * @throws IllegalStateException if component is not started */ protected void assertIsStarted() {<FILL_FUNCTION_BODY>} }
if (!isStarted()) { throw new IllegalStateException(this.getClass().getSimpleName() + " is not started"); }
194
38
232
docker-java_docker-java
docker-java/docker-java-core/src/main/java/com/github/dockerjava/core/exec/CopyFileFromContainerCmdExec.java
CopyFileFromContainerCmdExec
execute
class CopyFileFromContainerCmdExec extends AbstrSyncDockerCmdExec<CopyFileFromContainerCmd, InputStream> implements CopyFileFromContainerCmd.Exec { private static final Logger LOGGER = LoggerFactory.getLogger(CopyFileFromContainerCmdExec.class); public CopyFileFromContainerCmdExec(WebTarget baseResource, DockerClientConfig dockerClientConfig) { super(baseResource, dockerClientConfig); } @Override protected InputStream execute(CopyFileFromContainerCmd command) {<FILL_FUNCTION_BODY>} }
WebTarget webResource = getBaseResource().path("/containers/{id}/copy").resolveTemplate("id", command.getContainerId()); LOGGER.trace("POST: " + webResource.toString()); return webResource.request().accept(MediaType.APPLICATION_OCTET_STREAM) .post(command);
138
86
224
docker-java_docker-java
docker-java/docker-java-core/src/main/java/com/github/dockerjava/core/exec/JoinSwarmCmdExec.java
JoinSwarmCmdExec
execute
class JoinSwarmCmdExec extends AbstrSyncDockerCmdExec<JoinSwarmCmd, Void> implements JoinSwarmCmd.Exec { private static final Logger LOGGER = LoggerFactory.getLogger(InitializeSwarmCmdExec.class); public JoinSwarmCmdExec(WebTarget baseResource, DockerClientConfig dockerClientConfig) { super(baseResource, dockerClientConfig); } @Override protected Void execute(JoinSwarmCmd command) {<FILL_FUNCTION_BODY>} }
WebTarget webResource = getBaseResource().path("/swarm/join"); LOGGER.trace("POST: {} ", webResource); try { webResource.request().accept(MediaType.APPLICATION_JSON).post(command).close(); } catch (IOException e) { throw new RuntimeException(e); } return null;
132
89
221
eirslett_frontend-maven-plugin
frontend-maven-plugin/frontend-plugin-core/src/main/java/com/github/eirslett/maven/plugins/frontend/lib/BunInstaller.java
BunInstaller
bunIsAlreadyInstalled
class BunInstaller { public static final String INSTALL_PATH = "/bun"; public static final String DEFAULT_BUN_DOWNLOAD_ROOT = "https://github.com/oven-sh/bun/releases/download/"; private static final Object LOCK = new Object(); private String bunVersion, userName, password; private final Logger logger; private final InstallConfig config; private final ArchiveExtractor archiveExtractor; private final FileDownloader fileDownloader; BunInstaller(InstallConfig config, ArchiveExtractor archiveExtractor, FileDownloader fileDownloader) { this.logger = LoggerFactory.getLogger(getClass()); this.config = config; this.archiveExtractor = archiveExtractor; this.fileDownloader = fileDownloader; } public BunInstaller setBunVersion(String bunVersion) { this.bunVersion = bunVersion; return this; } public BunInstaller setUserName(String userName) { this.userName = userName; return this; } public BunInstaller setPassword(String password) { this.password = password; return this; } public void install() throws InstallationException { // use static lock object for a synchronized block synchronized (LOCK) { if (!bunIsAlreadyInstalled()) { if (!this.bunVersion.startsWith("v")) { this.logger.warn("Bun version does not start with naming convention 'v'."); } if (this.config.getPlatform().isWindows()) { throw new InstallationException("Unable to install bun on windows!"); } else { installBunDefault(); } } } } private boolean bunIsAlreadyInstalled() {<FILL_FUNCTION_BODY>} private void installBunDefault() throws InstallationException { try { logger.info("Installing Bun version {}", bunVersion); String downloadUrl = createDownloadUrl(); CacheDescriptor cacheDescriptor = new CacheDescriptor("bun", this.bunVersion, "zip"); File archive = this.config.getCacheResolver().resolve(cacheDescriptor); downloadFileIfMissing(downloadUrl, archive, this.userName, this.password); File installDirectory = getInstallDirectory(); // We need to delete the existing bun directory first so we clean out any old files, and // so we can rename the package directory below. try { if (installDirectory.isDirectory()) { FileUtils.deleteDirectory(installDirectory); } } catch (IOException e) { logger.warn("Failed to delete existing Bun installation."); } try { extractFile(archive, installDirectory); } catch (ArchiveExtractionException e) { if (e.getCause() instanceof EOFException) { this.logger.error("The archive file {} is corrupted and will be deleted. " + "Please try the build again.", archive.getPath()); archive.delete(); } throw e; } // Search for the bun binary File bunBinary = new File(getInstallDirectory(), File.separator + createBunTargetArchitecturePath() + File.separator + "bun"); if (!bunBinary.exists()) { throw new FileNotFoundException( "Could not find the downloaded bun binary in " + bunBinary); } else { File destinationDirectory = getInstallDirectory(); File destination = new File(destinationDirectory, "bun"); this.logger.info("Copying bun binary from {} to {}", bunBinary, destination); if (destination.exists() && !destination.delete()) { throw new InstallationException("Could not install Bun: Was not allowed to delete " + destination); } try { Files.move(bunBinary.toPath(), destination.toPath(), StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { throw new InstallationException("Could not install Bun: Was not allowed to rename " + bunBinary + " to " + destination); } if (!destination.setExecutable(true, false)) { throw new InstallationException( "Could not install Bun: Was not allowed to make " + destination + " executable."); } this.logger.info("Installed bun locally."); } } catch (IOException e) { throw new InstallationException("Could not install bun", e); } catch (DownloadException e) { throw new InstallationException("Could not download bun", e); } catch (ArchiveExtractionException e) { throw new InstallationException("Could not extract the bun archive", e); } } private String createDownloadUrl() { String downloadUrl = String.format("%sbun-%s", DEFAULT_BUN_DOWNLOAD_ROOT, bunVersion); String extension = "zip"; String fileending = String.format("%s.%s", createBunTargetArchitecturePath(), extension); downloadUrl += fileending; return downloadUrl; } private String createBunTargetArchitecturePath() { OS os = OS.guess(); Architecture architecture = Architecture.guess(); String destOs = os.equals(OS.Linux) ? "linux" : os.equals(OS.Mac) ? "darwin" : null; String destArc = architecture.equals(Architecture.x64) ? "x64" : architecture.equals( Architecture.arm64) ? "aarch64" : null; return String.format("%s-%s-%s", INSTALL_PATH, destOs, destArc); } private File getInstallDirectory() { File installDirectory = new File(this.config.getInstallDirectory(), "/"); if (!installDirectory.exists()) { this.logger.info("Creating install directory {}", installDirectory); installDirectory.mkdirs(); } return installDirectory; } private void extractFile(File archive, File destinationDirectory) throws ArchiveExtractionException { this.logger.info("Unpacking {} into {}", archive, destinationDirectory); this.archiveExtractor.extract(archive.getPath(), destinationDirectory.getPath()); } private void downloadFileIfMissing(String downloadUrl, File destination, String userName, String password) throws DownloadException { if (!destination.exists()) { downloadFile(downloadUrl, destination, userName, password); } } private void downloadFile(String downloadUrl, File destination, String userName, String password) throws DownloadException { this.logger.info("Downloading {} to {}", downloadUrl, destination); this.fileDownloader.download(downloadUrl, destination.getPath(), userName, password); } }
try { BunExecutorConfig executorConfig = new InstallBunExecutorConfig(config); File bunFile = executorConfig.getBunPath(); if (bunFile.exists()) { final String version = new BunExecutor(executorConfig, Arrays.asList("--version"), null).executeAndGetResult(logger); if (version.equals(this.bunVersion.replaceFirst("^v", ""))) { this.logger.info("Bun {} is already installed.", version); return true; } else { this.logger.info("Bun {} was installed, but we need version {}", version, this.bunVersion); return false; } } else { return false; } } catch (ProcessExecutionException e) { this.logger.warn("Unable to determine current bun version: {}", e.getMessage()); return false; }
1,741
233
1,974
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/routing/util/parsers/CarAverageSpeedParser.java
CarAverageSpeedParser
getSpeed
class CarAverageSpeedParser extends AbstractAverageSpeedParser implements TagParser { protected final Map<String, Integer> trackTypeSpeedMap = new HashMap<>(); protected final Set<String> badSurfaceSpeedMap = new HashSet<>(); // This value determines the maximal possible on roads with bad surfaces private final int badSurfaceSpeed; /** * A map which associates string to speed. Get some impression: * http://www.itoworld.com/map/124#fullscreen * http://wiki.openstreetmap.org/wiki/OSM_tags_for_routing/Maxspeed */ protected final Map<String, Integer> defaultSpeedMap = new HashMap<>(); public CarAverageSpeedParser(EncodedValueLookup lookup) { this(lookup.getDecimalEncodedValue(VehicleSpeed.key("car")), lookup.getDecimalEncodedValue(FerrySpeed.KEY)); } public CarAverageSpeedParser(DecimalEncodedValue speedEnc, DecimalEncodedValue ferrySpeed) { super(speedEnc, ferrySpeed); badSurfaceSpeedMap.add("cobblestone"); badSurfaceSpeedMap.add("unhewn_cobblestone"); badSurfaceSpeedMap.add("sett"); badSurfaceSpeedMap.add("grass_paver"); badSurfaceSpeedMap.add("gravel"); badSurfaceSpeedMap.add("fine_gravel"); badSurfaceSpeedMap.add("pebblestone"); badSurfaceSpeedMap.add("sand"); badSurfaceSpeedMap.add("paving_stones"); badSurfaceSpeedMap.add("dirt"); badSurfaceSpeedMap.add("earth"); badSurfaceSpeedMap.add("ground"); badSurfaceSpeedMap.add("wood"); badSurfaceSpeedMap.add("grass"); badSurfaceSpeedMap.add("unpaved"); badSurfaceSpeedMap.add("compacted"); // autobahn defaultSpeedMap.put("motorway", 100); defaultSpeedMap.put("motorway_link", 70); // bundesstraße defaultSpeedMap.put("trunk", 70); defaultSpeedMap.put("trunk_link", 65); // linking bigger town defaultSpeedMap.put("primary", 65); defaultSpeedMap.put("primary_link", 60); // linking towns + villages defaultSpeedMap.put("secondary", 60); defaultSpeedMap.put("secondary_link", 50); // streets without middle line separation defaultSpeedMap.put("tertiary", 50); defaultSpeedMap.put("tertiary_link", 40); defaultSpeedMap.put("unclassified", 30); defaultSpeedMap.put("residential", 30); // spielstraße defaultSpeedMap.put("living_street", 5); defaultSpeedMap.put("service", 20); // unknown road defaultSpeedMap.put("road", 20); // forestry stuff defaultSpeedMap.put("track", 15); trackTypeSpeedMap.put("grade1", 20); // paved trackTypeSpeedMap.put("grade2", 15); // now unpaved - gravel mixed with ... trackTypeSpeedMap.put("grade3", 10); // ... hard and soft materials trackTypeSpeedMap.put(null, defaultSpeedMap.get("track")); // limit speed on bad surfaces to 30 km/h badSurfaceSpeed = 30; } protected double getSpeed(ReaderWay way) {<FILL_FUNCTION_BODY>} @Override public void handleWayTags(int edgeId, EdgeIntAccess edgeIntAccess, ReaderWay way) { if (FerrySpeedCalculator.isFerry(way)) { double ferrySpeed = FerrySpeedCalculator.minmax(ferrySpeedEnc.getDecimal(false, edgeId, edgeIntAccess), avgSpeedEnc); setSpeed(false, edgeId, edgeIntAccess, ferrySpeed); if (avgSpeedEnc.isStoreTwoDirections()) setSpeed(true, edgeId, edgeIntAccess, ferrySpeed); return; } // get assumed speed from highway type double speed = getSpeed(way); speed = applyBadSurfaceSpeed(way, speed); setSpeed(false, edgeId, edgeIntAccess, applyMaxSpeed(way, speed, false)); setSpeed(true, edgeId, edgeIntAccess, applyMaxSpeed(way, speed, true)); } /** * @param way needed to retrieve tags * @param speed speed guessed e.g. from the road type or other tags * @return The assumed speed. */ protected double applyMaxSpeed(ReaderWay way, double speed, boolean bwd) { double maxSpeed = getMaxSpeed(way, bwd); return Math.min(140, isValidSpeed(maxSpeed) ? Math.max(1, maxSpeed * 0.9) : speed); } /** * @param way needed to retrieve tags * @param speed speed guessed e.g. from the road type or other tags * @return The assumed speed */ protected double applyBadSurfaceSpeed(ReaderWay way, double speed) { // limit speed if bad surface if (badSurfaceSpeed > 0 && isValidSpeed(speed) && speed > badSurfaceSpeed) { String surface = way.getTag("surface", ""); int colonIndex = surface.indexOf(":"); if (colonIndex != -1) surface = surface.substring(0, colonIndex); if (badSurfaceSpeedMap.contains(surface)) speed = badSurfaceSpeed; } return speed; } }
String highwayValue = way.getTag("highway", ""); Integer speed = defaultSpeedMap.get(highwayValue); // even inaccessible edges get a speed assigned if (speed == null) speed = 10; if (highwayValue.equals("track")) { String tt = way.getTag("tracktype"); if (!Helper.isEmpty(tt)) { Integer tInt = trackTypeSpeedMap.get(tt); if (tInt != null) speed = tInt; } } return speed;
1,480
143
1,623
public abstract class AbstractAverageSpeedParser implements TagParser { protected final DecimalEncodedValue avgSpeedEnc; protected final DecimalEncodedValue ferrySpeedEnc; protected AbstractAverageSpeedParser( DecimalEncodedValue speedEnc, DecimalEncodedValue ferrySpeedEnc); /** * @return {@link Double#NaN} if no maxspeed found */ public static double getMaxSpeed( ReaderWay way, boolean bwd); /** * @return <i>true</i> if the given speed is not {@link Double#NaN} */ protected static boolean isValidSpeed( double speed); public final DecimalEncodedValue getAverageSpeedEnc(); protected void setSpeed( boolean reverse, int edgeId, EdgeIntAccess edgeIntAccess, double speed); public final String getName(); @Override public void handleWayTags( int edgeId, EdgeIntAccess edgeIntAccess, ReaderWay way, IntsRef relationFlags); public abstract void handleWayTags( int edgeId, EdgeIntAccess edgeIntAccess, ReaderWay way); @Override public String toString(); }
PlayEdu_PlayEdu
PlayEdu/playedu-api/src/main/java/xyz/playedu/api/controller/backend/DashboardController.java
DashboardController
index
class DashboardController { @Autowired private AdminUserService adminUserService; @Autowired private CategoryService categoryService; @Autowired private UserService userService; @Autowired private CourseService courseService; @Autowired private DepartmentService departmentService; @Autowired private ResourceService resourceService; @Autowired private UserLearnDurationStatsService userLearnDurationStatsService; @GetMapping("/index") @Log(title = "主面板", businessType = BusinessTypeConstant.GET) public JsonResponse index() {<FILL_FUNCTION_BODY>} }
HashMap<String, Object> data = new HashMap<>(); data.put("version", SystemConstant.VERSION); data.put("user_total", userService.total()); // 总学员数量 data.put("user_today", userService.todayCount()); // 今日注册学员数量 data.put("user_yesterday", userService.yesterdayCount()); // 昨日注册学员数量 data.put("course_total", courseService.total()); // 线上课数量 data.put("department_total", departmentService.total()); data.put("resource_category_total", categoryService.total()); data.put("admin_user_total", adminUserService.total()); data.put( "resource_video_total", resourceService.total(BackendConstant.RESOURCE_TYPE_VIDEO)); data.put( "resource_image_total", resourceService.total(BackendConstant.RESOURCE_TYPE_IMAGE)); data.put("user_learn_today", userLearnDurationStatsService.todayTotal()); data.put("user_learn_yesterday", userLearnDurationStatsService.yesterdayTotal()); List<UserLearnDurationStats> userLearnTop10 = userLearnDurationStatsService.top10(); Map<Integer, User> top10Users = userService .chunks( userLearnTop10.stream() .map(UserLearnDurationStats::getUserId) .toList(), new ArrayList<>() { { add("id"); add("name"); add("avatar"); add("email"); } }) .stream() .collect(Collectors.toMap(User::getId, e -> e)); data.put("user_learn_top10", userLearnTop10); data.put("user_learn_top10_users", top10Users); return JsonResponse.data(data);
158
491
649
zhkl0228_unidbg
unidbg/unidbg-api/src/main/java/com/github/unidbg/debugger/gdb/SetThreadCommand.java
SetThreadCommand
processCommand
class SetThreadCommand implements GdbStubCommand { private static final Log log = LogFactory.getLog(SetThreadCommand.class); @Override public boolean processCommand(Emulator<?> emulator, GdbStub stub, String command) {<FILL_FUNCTION_BODY>} }
char type = command.charAt(1); int thread = Integer.parseInt(command.substring(2), 16); if (log.isDebugEnabled()) { log.debug("Set thread type=" + type + ", thread=" + thread); } switch (type) { case 'c': case 'g': stub.makePacketAndSend("OK"); break; default: stub.makePacketAndSend("E22"); break; } return true;
78
136
214
Kong_unirest-java
unirest-java/unirest/src/main/java/kong/unirest/core/BaseResponse.java
BaseResponse
getErrorBody
class BaseResponse<T> implements HttpResponse<T> { private final Headers headers; private final String statusText; private final int statusCode; private final HttpRequestSummary reqSummary; private Optional<UnirestParsingException> parsingerror = Optional.empty(); private final Config config; private Cookies cookies; protected BaseResponse(RawResponse response) { this.headers = response.getHeaders(); // Unirest decompresses the content, so this should be removed as it is // no longer encoded this.headers.remove("Content-Encoding", "gzip"); this.statusCode = response.getStatus(); this.statusText = response.getStatusText(); this.config = response.getConfig(); this.reqSummary = response.getRequestSummary(); } protected BaseResponse(BaseResponse other) { this.headers = other.headers; this.statusCode = other.statusCode; this.statusText = other.statusText; this.config = other.config; this.reqSummary = other.reqSummary; } @Override public int getStatus() { return statusCode; } @Override public String getStatusText() { return statusText; } @Override public Headers getHeaders() { return headers; } @Override public abstract T getBody(); @Override public Optional<UnirestParsingException> getParsingError() { return parsingerror; } @Override public <V> V mapBody(Function<T, V> func) { return func.apply(getBody()); } @Override public <V> HttpResponse<V> map(Function<T, V> func) { return new BasicResponse(this, mapBody(func)); } protected void setParsingException(String originalBody, RuntimeException e) { parsingerror = Optional.of(new UnirestParsingException(originalBody, e)); } @Override public boolean isSuccess() { return getStatus() >= 200 && getStatus() < 300 && !getParsingError().isPresent(); } @Override public HttpResponse<T> ifSuccess(Consumer<HttpResponse<T>> consumer) { if (isSuccess()) { consumer.accept(this); } return this; } @Override public HttpResponse<T> ifFailure(Consumer<HttpResponse<T>> consumer) { if (!isSuccess()) { consumer.accept(this); } return this; } @Override public <E> E mapError(Class<? extends E> errorClass) { if (!isSuccess()) { String errorBody = getErrorBody(); if(String.class.equals(errorClass)){ return (E) errorBody; } try { return config.getObjectMapper().readValue(errorBody, errorClass); } catch (RuntimeException e) { setParsingException(errorBody, e); } } return null; } private String getErrorBody() {<FILL_FUNCTION_BODY>} @Override public <E> HttpResponse<T> ifFailure(Class<? extends E> errorClass, Consumer<HttpResponse<E>> consumer) { if (!isSuccess()) { E error = mapError(errorClass); BasicResponse br = new BasicResponse(this, error); getParsingError().ifPresent(p -> br.setParsingException(p.getOriginalBody(), p)); consumer.accept(br); } return this; } @Override public Cookies getCookies() { if (cookies == null) { cookies = new Cookies(headers.get("set-cookie")); } return cookies; } @Override public HttpRequestSummary getRequestSummary() { return reqSummary; } protected abstract String getRawBody(); }
if (getParsingError().isPresent()) { return getParsingError().get().getOriginalBody(); } else if (getRawBody() != null) { return getRawBody(); } T body = getBody(); if (body == null) { return null; } try { if(body instanceof byte[]){ return new String((byte[])body, StandardCharsets.UTF_8); } return config.getObjectMapper().writeValue(body); } catch (Exception e) { return String.valueOf(body); }
1,027
153
1,180
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/routing/ev/TurnCost.java
TurnCost
create
class TurnCost { public static String key(String prefix) { return getKey(prefix, "turn_cost"); } /** * This creates an EncodedValue specifically for the turn costs */ public static DecimalEncodedValue create(String name, int maxTurnCosts) {<FILL_FUNCTION_BODY>} }
int turnBits = BitUtil.countBitValue(maxTurnCosts); return new DecimalEncodedValueImpl(key(name), turnBits, 0, 1, false, false, true);
88
52
140
ainilili_ratel
ratel/landlords-client/src/main/java/org/nico/ratel/landlords/client/event/ClientEventListener_CODE_GAME_POKER_PLAY.java
ClientEventListener_CODE_GAME_POKER_PLAY
call
class ClientEventListener_CODE_GAME_POKER_PLAY extends ClientEventListener { @Override public void call(Channel channel, String data) {<FILL_FUNCTION_BODY>} }
Map<String, Object> map = MapHelper.parser(data); SimplePrinter.printNotice("It's your turn to play, your cards are as follows: "); List<Poker> pokers = Noson.convert(map.get("pokers"), new NoType<List<Poker>>() { }); SimplePrinter.printPokers(pokers); SimplePrinter.printNotice("Last cards are"); SimplePrinter.printNotice(map.containsKey("lastPokers")?map.get("lastPokers").toString():""); SimplePrinter.printNotice("Please enter the combination you came up with (enter [exit|e] to exit current room, enter [pass|p] to jump current round, enter [view|v] to show all valid combinations.)"); String line = SimpleWriter.write(User.INSTANCE.getNickname(), "combination"); if (line == null) { SimplePrinter.printNotice("Invalid enter"); call(channel, data); } else { if (line.equalsIgnoreCase("pass") || line.equalsIgnoreCase("p")) { pushToServer(channel, ServerEventCode.CODE_GAME_POKER_PLAY_PASS); } else if (line.equalsIgnoreCase("exit") || line.equalsIgnoreCase("e")) { pushToServer(channel, ServerEventCode.CODE_CLIENT_EXIT); } else if (line.equalsIgnoreCase("view") || line.equalsIgnoreCase("v")) { if (!map.containsKey("lastSellPokers") || !map.containsKey("lastSellClientId")) { SimplePrinter.printNotice("Current server version unsupport this feature, need more than v1.2.4."); call(channel, data); return; } Object lastSellPokersObj = map.get("lastSellPokers"); if (lastSellPokersObj == null || Integer.valueOf(SimpleClient.id).equals(map.get("lastSellClientId"))) { SimplePrinter.printNotice("Up to you !"); call(channel, data); return; } else { List<Poker> lastSellPokers = Noson.convert(lastSellPokersObj, new NoType<List<Poker>>() {}); List<PokerSell> sells = PokerHelper.validSells(PokerHelper.checkPokerType(lastSellPokers), pokers); if (sells.size() == 0) { SimplePrinter.printNotice("It is a pity that, there is no winning combination..."); call(channel, data); return; } for (int i = 0; i < sells.size(); i++) { SimplePrinter.printNotice(i + 1 + ". " + PokerHelper.textOnlyNoType(sells.get(i).getSellPokers())); } while (true) { SimplePrinter.printNotice("You can enter index to choose anyone.(enter [back|b] to go back.)"); line = SimpleWriter.write(User.INSTANCE.getNickname(), "choose"); if (line.equalsIgnoreCase("back") || line.equalsIgnoreCase("b")) { call(channel, data); return; } else { try { int choose = Integer.valueOf(line); if (choose < 1 || choose > sells.size()) { SimplePrinter.printNotice("The input number must be in the range of 1 to " + sells.size() + "."); } else { List<Poker> choosePokers = sells.get(choose - 1).getSellPokers(); List<Character> options = new ArrayList<>(); for (Poker poker : choosePokers) { options.add(poker.getLevel().getAlias()[0]); } pushToServer(channel, ServerEventCode.CODE_GAME_POKER_PLAY, Noson.reversal(options.toArray(new Character[]{}))); break; } } catch (NumberFormatException e) { SimplePrinter.printNotice("Please input a number."); } } } } // PokerHelper.validSells(lastPokerSell, pokers); } else { String[] strs = line.split(" "); List<Character> options = new ArrayList<>(); boolean access = true; for (int index = 0; index < strs.length; index++) { String str = strs[index]; for (char c : str.toCharArray()) { if (c == ' ' || c == '\t') { } else { if (!PokerLevel.aliasContains(c)) { access = false; break; } else { options.add(c); } } } } if (access) { pushToServer(channel, ServerEventCode.CODE_GAME_POKER_PLAY, Noson.reversal(options.toArray(new Character[]{}))); } else { SimplePrinter.printNotice("Invalid enter"); if (lastPokers != null) { SimplePrinter.printNotice(lastSellClientNickname + "[" + lastSellClientType + "] played:"); SimplePrinter.printPokers(lastPokers); } call(channel, data); } } }
51
1,419
1,470
public abstract class ClientEventListener { public abstract void call( Channel channel, String data); public final static Map<ClientEventCode,ClientEventListener> LISTENER_MAP=new HashMap<>(); private final static String LISTENER_PREFIX="org.nico.ratel.landlords.client.event.ClientEventListener_"; protected static List<Poker> lastPokers=null; protected static String lastSellClientNickname=null; protected static String lastSellClientType=null; protected static void initLastSellInfo(); @SuppressWarnings("unchecked") public static ClientEventListener get( ClientEventCode code); protected ChannelFuture pushToServer( Channel channel, ServerEventCode code, String datas); protected ChannelFuture pushToServer( Channel channel, ServerEventCode code); }
PlexPt_chatgpt-java
chatgpt-java/src/main/java/com/plexpt/chatgpt/ConsoleChatGPT.java
ConsoleChatGPT
main
class ConsoleChatGPT { public static Proxy proxy = Proxy.NO_PROXY; public static void main(String[] args) {<FILL_FUNCTION_BODY>} private static BigDecimal getBalance(String key) { ChatGPT chatGPT = ChatGPT.builder() .apiKey(key) .proxy(proxy) .build() .init(); return chatGPT.balance(); } private static void check(String key) { if (key == null || key.isEmpty()) { throw new RuntimeException("请输入正确的KEY"); } } @SneakyThrows public static String getInput(String prompt) { System.out.print(prompt); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); List<String> lines = new ArrayList<>(); String line; try { while ((line = reader.readLine()) != null && !line.isEmpty()) { lines.add(line); } } catch (IOException e) { e.printStackTrace(); } return lines.stream().collect(Collectors.joining("\n")); } }
System.out.println("ChatGPT - Java command-line interface"); System.out.println("Press enter twice to submit your question."); System.out.println(); System.out.println("按两次回车以提交您的问题!!!"); System.out.println("按两次回车以提交您的问题!!!"); System.out.println("按两次回车以提交您的问题!!!"); System.out.println(); System.out.println("Please enter APIKEY, press Enter twice to submit:"); String key = getInput("请输入APIKEY,按两次回车以提交:\n"); check(key); // 询问用户是否使用代理 国内需要代理 System.out.println("是否使用代理?(y/n): "); System.out.println("use proxy?(y/n): "); String useProxy = getInput("按两次回车以提交:\n"); if (useProxy.equalsIgnoreCase("y")) { // 输入代理地址 System.out.println("请输入代理类型(http/socks): "); String type = getInput("按两次回车以提交:\n"); // 输入代理地址 System.out.println("请输入代理IP: "); String proxyHost = getInput("按两次回车以提交:\n"); // 输入代理端口 System.out.println("请输入代理端口: "); String portStr = getInput("按两次回车以提交:\n"); Integer proxyPort = Integer.parseInt(portStr); if (type.equals("http")) { proxy = Proxys.http(proxyHost, proxyPort); } else { proxy = Proxys.socks5(proxyHost, proxyPort); } } // System.out.println("Inquiry balance..."); // System.out.println("查询余额中..."); // BigDecimal balance = getBalance(key); // System.out.println("API KEY balance: " + balance.toPlainString()); // // if (!NumberUtil.isGreater(balance, BigDecimal.ZERO)) { // System.out.println("API KEY 余额不足: "); // return; // } while (true) { String prompt = getInput("\nYou:\n"); ChatGPTStream chatGPT = ChatGPTStream.builder() .apiKey(key) .proxy(proxy) .build() .init(); System.out.println("AI: "); //卡住 CountDownLatch countDownLatch = new CountDownLatch(1); Message message = Message.of(prompt); ConsoleStreamListener listener = new ConsoleStreamListener() { @Override public void onError(Throwable throwable, String response) { throwable.printStackTrace(); countDownLatch.countDown(); } }; listener.setOnComplate(msg -> { countDownLatch.countDown(); }); chatGPT.streamChatCompletion(Arrays.asList(message), listener); try { countDownLatch.await(); } catch (InterruptedException e) { e.printStackTrace(); } }
311
838
1,149
jitsi_jitsi
jitsi/modules/plugin/msofficecomm/src/main/java/net/java/sip/communicator/plugin/msofficecomm/MessengerContact.java
MessengerContact
getStatus
class MessengerContact { /** * The <tt>Logger</tt> used by the <tt>MessengerContact</tt> class and its * instances for logging output. */ private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(MessengerContact.class); /** * The sign-in name associated with the native <tt>IMessengerContact</tt> * implementation represented by this instance. */ public final String signinName; /** * Initializes a new <tt>MessengerContact</tt> instance which is to * represent the Java counterpart of a native <tt>IMessengerContact</tt> * implementation associated with a specific sign-in name. * * @param signinName the sign-in name associated with the native * <tt>IMessengerContact</tt> implementation which is to be represented by * the new instance */ public MessengerContact(String signinName) { this.signinName = signinName; } /** * Gets the phone number information of the contact associated with this * instance. * * @param a member of the <tt>MPHONE_TYPE</tt> enumerated type which * specifies the type of the phone number information to be retrieved * @return the phone number information of the contact associated with this * instance */ public String getPhoneNumber(int type) { try { return Messenger.getPhoneNumber(this, type); } catch (Throwable t) { /* * The native counterpart will swallow any exception. Even if it * didn't, it would still not use a Logger instance to describe the * exception. So describe it on the Java side and rethrow it. */ if (t instanceof ThreadDeath) throw (ThreadDeath) t; else if (t instanceof OutOfMemoryError) throw (OutOfMemoryError) t; else { logger.error( "Failed to retrieve the phone number information of an" + " IMessengerContact with sign-in name: " + signinName, t); throw new RuntimeException(t); } } } /** * Gets the connection/presence status of the contact associated with this * instance in the form of a <tt>MISTATUS</tt> value. * * @return a <tt>MISTATUS</tt> value which specifies the connection/presence * status of the contact associated with this instance */ public int getStatus() {<FILL_FUNCTION_BODY>} /** * Gets the indicator which determines whether this * <tt>MessengerContact</tt> is the same user as the current client user. * * @return <tt>true</tt> if this <tt>MessengerContact</tt> is the same user * as the current client user; otherwise, <tt>false</tt> */ public boolean isSelf() { return Messenger.isSelf(this); } }
try { return Messenger.getStatus(this); } catch (Throwable t) { /* * The native counterpart will swallow any exception. Even if it * didn't, it would still not use a Logger instance to describe the * exception. So describe it on the Java side and rethrow it. */ if (t instanceof ThreadDeath) throw (ThreadDeath) t; else if (t instanceof OutOfMemoryError) throw (OutOfMemoryError) t; else { logger.error( "Failed to determine the status of an IMessengerContact" + " with sign-in name: " + signinName, t); throw new RuntimeException(t); } }
805
199
1,004
jitsi_jitsi
jitsi/modules/plugin/otr/src/main/java/net/java/sip/communicator/plugin/otr/OtrConfigurator.java
OtrConfigurator
getXmlFriendlyString
class OtrConfigurator { /** * Gets an XML tag friendly {@link String} from a {@link String}. * * @param s a {@link String} * @return an XML friendly {@link String} */ private String getXmlFriendlyString(String s) {<FILL_FUNCTION_BODY>} /** * Puts a given property ID under the OTR namespace and makes sure it is XML * tag friendly. * * @param id the property ID. * @return the namespaced ID. */ private String getID(String id) { return "net.java.sip.communicator.plugin.otr." + getXmlFriendlyString(id); } /** * Returns the value of the property with the specified name or null if no * such property exists ({@link ConfigurationService#getProperty(String)} * proxy). * * @param id of the property that is being queried. * @return the <tt>byte[]</tt> value of the property with the specified * name. */ public byte[] getPropertyBytes(String id) { String value = OtrActivator.configService.getString(getID(id)); return value == null ? null : Base64.getDecoder().decode(value.getBytes()); } /** * Gets the value of a specific property as a boolean ( * {@link ConfigurationService#getBoolean(String, boolean)} proxy). * * @param id of the property that is being queried. * @param defaultValue the value to be returned if the specified property * name is not associated with a value. * @return the <tt>Boolean</tt> value of the property with the specified * name. */ public boolean getPropertyBoolean(String id, boolean defaultValue) { return OtrActivator.configService.getBoolean(getID(id), defaultValue); } /** * Sets the property with the specified name to the specified value ( * {@link ConfigurationService#setProperty(String, Object)} proxy). The * value is Base64 encoded. * * @param id the name of the property to change. * @param value the new value of the specified property. */ public void setProperty(String id, byte[] value) { String valueToStore = Base64.getEncoder().encodeToString(value); OtrActivator.configService.setProperty(getID(id), valueToStore); } /** * Sets the property with the specified name to the specified value ( * {@link ConfigurationService#setProperty(String, Object)} proxy). * * @param id the name of the property to change. * @param value the new value of the specified property. */ public void setProperty(String id, Object value) { OtrActivator.configService.setProperty(getID(id), value); } /** * Removes the property with the specified name ( * {@link ConfigurationService#removeProperty(String)} proxy). * * @param id the name of the property to change. */ public void removeProperty(String id) { OtrActivator.configService.removeProperty(getID(id)); } /** * Gets the value of a specific property as a signed decimal integer. * * @param id the name of the property to change. * @param defaultValue the value to be returned if the specified property * name is not associated with a value. * @return the <tt>int</tt> value of the property */ public int getPropertyInt(String id, int defaultValue) { return OtrActivator.configService.getInt(getID(id), defaultValue); } /** * Appends <tt>value</tt> to the old value of the property with the * specified name. The two values will be comma separated. * * @param id the name of the property to append to * @param value the value to append */ public void appendProperty(String id, Object value) { Object oldValue = OtrActivator.configService.getProperty(getID(id)); String newValue = oldValue == null ? value.toString() : oldValue + "," + value; setProperty(id, newValue); } public List<String> getAppendedProperties(String id) { String listProperties = (String) OtrActivator.configService.getProperty(getID(id)); if (listProperties == null) return new ArrayList<String>(); return Arrays.asList(listProperties.split(",")); } }
if (s == null || s.length() < 1) return s; // XML Tags are not allowed to start with digits, // insert a dummy "p" char. if (Character.isDigit(s.charAt(0))) s = "p" + s; char[] cId = new char[s.length()]; for (int i = 0; i < cId.length; i++) { char c = s.charAt(i); cId[i] = Character.isLetterOrDigit(c) ? c : '_'; } return new String(cId);
1,211
167
1,378
javamelody_javamelody
javamelody/javamelody-core/src/main/java/net/bull/javamelody/internal/web/pdf/PdfThreadInformationsReport.java
PdfThreadInformationsReport
toPdf
class PdfThreadInformationsReport extends PdfAbstractTableReport { private final List<ThreadInformations> threadInformationsList; private final DecimalFormat integerFormat = I18N.createIntegerFormat(); private final boolean stackTraceEnabled; private final boolean cpuTimeEnabled; private final Font cellFont = PdfFonts.TABLE_CELL.getFont(); private final PdfDocumentFactory pdfDocumentFactory; PdfThreadInformationsReport(List<ThreadInformations> threadInformationsList, boolean stackTraceEnabled, PdfDocumentFactory pdfDocumentFactory, Document document) { super(document); assert threadInformationsList != null; assert pdfDocumentFactory != null; this.threadInformationsList = threadInformationsList; this.pdfDocumentFactory = pdfDocumentFactory; this.stackTraceEnabled = stackTraceEnabled; this.cpuTimeEnabled = !threadInformationsList.isEmpty() && threadInformationsList.get(0).getCpuTimeMillis() != -1; } @Override void toPdf() throws DocumentException, IOException {<FILL_FUNCTION_BODY>} void writeIntro(JavaInformations javaInformations) throws DocumentException { final Font boldFont = PdfFonts.BOLD.getFont(); final Font normalFont = PdfFonts.NORMAL.getFont(); addToDocument(new Phrase( getFormattedString("Threads_sur", javaInformations.getHost()) + ": ", boldFont)); addToDocument(new Phrase(getFormattedString("thread_count", javaInformations.getThreadCount(), javaInformations.getPeakThreadCount(), javaInformations.getTotalStartedThreadCount()), normalFont)); } void writeDeadlocks() throws DocumentException { final List<ThreadInformations> deadlockedThreads = new ArrayList<>(); for (final ThreadInformations thread : threadInformationsList) { if (thread.isDeadlocked()) { deadlockedThreads.add(thread); } } if (!deadlockedThreads.isEmpty()) { final StringBuilder sb = new StringBuilder(); sb.append('\n'); sb.append(getString("Threads_deadlocks")); String separator = " "; for (final ThreadInformations thread : deadlockedThreads) { sb.append(separator); sb.append(thread.getName()); separator = ", "; } sb.append('\n'); addToDocument(new Phrase(sb.toString(), PdfFonts.SEVERE_CELL.getFont())); } } private void writeHeader() throws DocumentException { final List<String> headers = createHeaders(); final int[] relativeWidths = new int[headers.size()]; Arrays.fill(relativeWidths, 0, headers.size(), 1); relativeWidths[0] = 3; // thread relativeWidths[3] = 2; // état if (stackTraceEnabled) { relativeWidths[4] = 6; // méthode exécutée } initTable(headers, relativeWidths); } private List<String> createHeaders() { final List<String> headers = new ArrayList<>(); headers.add(getString("Thread")); headers.add(getString("Demon")); headers.add(getString("Priorite")); headers.add(getString("Etat")); if (stackTraceEnabled) { headers.add(getString("Methode_executee")); } if (cpuTimeEnabled) { headers.add(getString("Temps_cpu")); headers.add(getString("Temps_user")); } return headers; } private void writeThreadInformations(ThreadInformations threadInformations) throws DocumentException, IOException { final PdfPCell defaultCell = getDefaultCell(); defaultCell.setHorizontalAlignment(Element.ALIGN_LEFT); addCell(threadInformations.getName()); defaultCell.setHorizontalAlignment(Element.ALIGN_CENTER); if (threadInformations.isDaemon()) { addCell(getString("oui")); } else { addCell(getString("non")); } defaultCell.setHorizontalAlignment(Element.ALIGN_RIGHT); addCell(integerFormat.format(threadInformations.getPriority())); defaultCell.setHorizontalAlignment(Element.ALIGN_LEFT); final PdfPCell cell = new PdfPCell(); final Paragraph paragraph = new Paragraph( getDefaultCell().getLeading() + cellFont.getSize()); paragraph.add(new Chunk( getImage( "bullets/" + HtmlThreadInformationsReport.getStateIcon(threadInformations)), 0, -1)); paragraph.add(new Phrase(String.valueOf(threadInformations.getState()), cellFont)); cell.addElement(paragraph); addCell(cell); if (stackTraceEnabled) { addCell(threadInformations.getExecutedMethod()); } if (cpuTimeEnabled) { defaultCell.setHorizontalAlignment(Element.ALIGN_RIGHT); addCell(integerFormat.format(threadInformations.getCpuTimeMillis())); addCell(integerFormat.format(threadInformations.getUserTimeMillis())); } } private Image getImage(String resourceFileName) throws DocumentException, IOException { return pdfDocumentFactory.getSmallImage(resourceFileName); } }
writeHeader(); for (final ThreadInformations threadInformations : threadInformationsList) { nextRow(); writeThreadInformations(threadInformations); } addTableToDocument(); final Paragraph tempsThreads = new Paragraph(getString("Temps_threads") + '\n', cellFont); tempsThreads.setAlignment(Element.ALIGN_RIGHT); addToDocument(tempsThreads); // rq stack-trace: on n'inclue pas dans le pdf les stack-traces des threads // car c'est très verbeux et cela remplirait des pages pour pas grand chose // d'autant que si le pdf est généré de nuit pour être envoyé par mail // alors ces stack-traces n'ont pas beaucoup d'intérêt // if (stackTrace != null && !stackTrace.isEmpty()) { // // même si stackTraceEnabled, ce thread n'a pas forcément de stack-trace // writeln(threadInformations.getName()); // for (final StackTraceElement stackTraceElement : stackTrace) { // writeln(stackTraceElement.toString()); // } // }
1,573
358
1,931
/** * Parent abstrait des classes de rapport pdf avec un tableau. * @author Emeric Vernat */ abstract class PdfAbstractTableReport extends PdfAbstractReport { private final Font cellFont=PdfFonts.TABLE_CELL.getFont(); private PdfPTable table; private boolean oddRow; PdfAbstractTableReport( Document document); void initTable( List<String> headers, int[] relativeWidths) throws DocumentException; void nextRow(); PdfPCell getDefaultCell(); void addCell( String string); void addCell( Phrase phrase); void addCell( Image image); void addCell( PdfPCell cell); /** * Adds the <CODE>table</CODE> to the <CODE>Document</CODE>. * @return <CODE>true</CODE> if the element was added, <CODE>false</CODE> if not * @throws DocumentException when a document isn't open yet, or has been closed */ boolean addTableToDocument() throws DocumentException; }
jeecgboot_jeecg-boot
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/config/sign/util/BodyReaderHttpServletRequestWrapper.java
BodyReaderHttpServletRequestWrapper
getBodyString
class BodyReaderHttpServletRequestWrapper extends HttpServletRequestWrapper { private final byte[] body; public BodyReaderHttpServletRequestWrapper(HttpServletRequest request) { super(request); String sessionStream = getBodyString(request); body = sessionStream.getBytes(Charset.forName("UTF-8")); } /** * 获取请求Body * * @param request * @return */ public String getBodyString(final ServletRequest request) {<FILL_FUNCTION_BODY>} /** * Description: 复制输入流</br> * * @param inputStream * @return</br> */ public InputStream cloneInputStream(ServletInputStream inputStream) { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len; try { while ((len = inputStream.read(buffer)) > -1) { byteArrayOutputStream.write(buffer, 0, len); } byteArrayOutputStream.flush(); } catch (IOException e) { e.printStackTrace(); } return new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); } @Override public BufferedReader getReader() { return new BufferedReader(new InputStreamReader(getInputStream())); } @Override public ServletInputStream getInputStream() { final ByteArrayInputStream bais = new ByteArrayInputStream(body); return new ServletInputStream() { @Override public int read() { return bais.read(); } @Override public boolean isFinished() { return false; } @Override public boolean isReady() { return false; } @Override public void setReadListener(ReadListener readListener) { } }; } }
StringBuilder sb = new StringBuilder(); try (InputStream inputStream = cloneInputStream(request.getInputStream()); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")))) { String line; while ((line = reader.readLine()) != null) { sb.append(line); } } catch (IOException e) { e.printStackTrace(); } return sb.toString();
488
121
609
logfellow_logstash-logback-encoder
logstash-logback-encoder/src/main/java/net/logstash/logback/decorate/smile/SmileJsonFactoryDecorator.java
SmileJsonFactoryDecorator
decorate
class SmileJsonFactoryDecorator implements JsonFactoryDecorator { @Override public JsonFactory decorate(JsonFactory factory) {<FILL_FUNCTION_BODY>} }
SmileFactory smileFactory = new SmileFactory(); ObjectMapper mapper = new ObjectMapper(smileFactory); smileFactory.setCodec(mapper); return smileFactory;
48
49
97
joelittlejohn_jsonschema2pojo
jsonschema2pojo/jsonschema2pojo-core/src/main/java/org/jsonschema2pojo/rules/PrimitiveTypes.java
PrimitiveTypes
isPrimitive
class PrimitiveTypes { private PrimitiveTypes() { } /** * Check if a name string refers to a given type. * * @param name * the name of a Java type * @param owner * the current code model for type generation * @return <code>true</code> when the given name refers to a primitive Java * type (e.g. "int"), otherwise <code>false</code> */ public static boolean isPrimitive(String name, JCodeModel owner) {<FILL_FUNCTION_BODY>} /** * Create a primitive type reference (for code generation) using the given * primitive type name. * * @param name * the name of a primitive Java type * @param owner * the current code model for type generation * @return a type reference created by the given owner */ public static JPrimitiveType primitiveType(String name, JCodeModel owner) { try { return (JPrimitiveType) owner.parseType(name); } catch (ClassNotFoundException e) { throw new GenerationException( "Given name does not refer to a primitive type, this type can't be found: " + name, e); } } }
try { return JType.parse(owner, name) != owner.VOID; } catch (IllegalArgumentException e) { return false; }
328
45
373
Kong_unirest-java
unirest-java/unirest/src/main/java/kong/unirest/core/JsonPatchItem.java
JsonPatchItem
toString
class JsonPatchItem { private final JsonPatchOperation op; private final String path; private final Object value; public JsonPatchItem(JsonPatchOperation op, String path, Object value){ this.op = op; this.path = path; this.value = value; } public JsonPatchItem(JsonPatchOperation op, String path) { this(op, path, null); } public JsonPatchItem(JSONObject row) { this.op = JsonPatchOperation.valueOf(row.getString("op")); this.path = row.getString("path"); if(row.has(op.getOperationtype())) { this.value = row.get(op.getOperationtype()); } else { this.value = null; } } @Override public boolean equals(Object o) { if (this == o) {return true;} if (o == null || getClass() != o.getClass()) {return false;} JsonPatchItem that = (JsonPatchItem) o; return op == that.op && Objects.equals(path, that.path) && Objects.equals(toString(), that.toString()); } @Override public int hashCode() { return Objects.hash(op, path, value); } @Override public String toString() {<FILL_FUNCTION_BODY>} public JsonPatchOperation getOp() { return op; } public String getPath() { return path; } public Object getValue() { return value; } }
JSONObject json = new JSONObject() .put("op", op) .put("path", path); if(Objects.nonNull(value)){ json.put(op.getOperationtype(), value); } return json.toString();
422
68
490
mapstruct_mapstruct
mapstruct/processor/src/main/java/org/mapstruct/ap/internal/model/common/ParameterBinding.java
ParameterBinding
fromTypeAndName
class ParameterBinding { private final Type type; private final String variableName; private final boolean targetType; private final boolean mappingTarget; private final boolean mappingContext; private final boolean sourcePropertyName; private final boolean targetPropertyName; private final SourceRHS sourceRHS; private ParameterBinding(Type parameterType, String variableName, boolean mappingTarget, boolean targetType, boolean mappingContext, boolean sourcePropertyName, boolean targetPropertyName, SourceRHS sourceRHS) { this.type = parameterType; this.variableName = variableName; this.targetType = targetType; this.mappingTarget = mappingTarget; this.mappingContext = mappingContext; this.sourcePropertyName = sourcePropertyName; this.targetPropertyName = targetPropertyName; this.sourceRHS = sourceRHS; } /** * @return the name of the variable (or parameter) that is being used as argument for the parameter being bound. */ public String getVariableName() { return variableName; } /** * @return {@code true}, if the parameter being bound is a {@code @TargetType} parameter. */ public boolean isTargetType() { return targetType; } /** * @return {@code true}, if the parameter being bound is a {@code @MappingTarget} parameter. */ public boolean isMappingTarget() { return mappingTarget; } /** * @return {@code true}, if the parameter being bound is a {@code @MappingContext} parameter. */ public boolean isMappingContext() { return mappingContext; } /** * @return {@code true}, if the parameter being bound is a {@code @SourcePropertyName} parameter. */ public boolean isSourcePropertyName() { return sourcePropertyName; } /** * @return {@code true}, if the parameter being bound is a {@code @TargetPropertyName} parameter. */ public boolean isTargetPropertyName() { return targetPropertyName; } /** * @return the type of the parameter that is bound */ public Type getType() { return type; } /** * @return the sourceRHS that this parameter is bound to */ public SourceRHS getSourceRHS() { return sourceRHS; } public Set<Type> getImportTypes() { if ( targetType ) { return type.getImportTypes(); } if ( sourceRHS != null ) { return sourceRHS.getImportTypes(); } return Collections.emptySet(); } /** * @param parameter parameter * @return a parameter binding reflecting the given parameter as being used as argument for a method call */ public static ParameterBinding fromParameter(Parameter parameter) { return new ParameterBinding( parameter.getType(), parameter.getName(), parameter.isMappingTarget(), parameter.isTargetType(), parameter.isMappingContext(), parameter.isSourcePropertyName(), parameter.isTargetPropertyName(), null ); } public static List<ParameterBinding> fromParameters(List<Parameter> parameters) { List<ParameterBinding> result = new ArrayList<>( parameters.size() ); for ( Parameter param : parameters ) { result.add( fromParameter( param ) ); } return result; } public static ParameterBinding fromTypeAndName(Type parameterType, String parameterName) {<FILL_FUNCTION_BODY>} /** * @param classTypeOf the type representing {@code Class<X>} for the target type {@code X} * @return a parameter binding representing a target type parameter */ public static ParameterBinding forTargetTypeBinding(Type classTypeOf) { return new ParameterBinding( classTypeOf, null, false, true, false, false, false, null ); } /** * @return a parameter binding representing a target property name parameter */ public static ParameterBinding forTargetPropertyNameBinding(Type classTypeOf) { return new ParameterBinding( classTypeOf, null, false, false, false, false, true, null ); } /** * @return a parameter binding representing a source property name parameter */ public static ParameterBinding forSourcePropertyNameBinding(Type classTypeOf) { return new ParameterBinding( classTypeOf, null, false, false, false, true, false, null ); } /** * @param resultType type of the mapping target * @return a parameter binding representing a mapping target parameter */ public static ParameterBinding forMappingTargetBinding(Type resultType) { return new ParameterBinding( resultType, null, true, false, false, false, false, null ); } /** * @param sourceType type of the parameter * @return a parameter binding representing a mapping source type */ public static ParameterBinding forSourceTypeBinding(Type sourceType) { return new ParameterBinding( sourceType, null, false, false, false, false, false, null ); } public static ParameterBinding fromSourceRHS(SourceRHS sourceRHS) { return new ParameterBinding( sourceRHS.getSourceType(), null, false, false, false, false, false, sourceRHS ); } }
return new ParameterBinding( parameterType, parameterName, false, false, false, false, false, null );
1,338
47
1,385
docker-java_docker-java
docker-java/docker-java-core/src/main/java/com/github/dockerjava/core/exec/EventsCmdExec.java
EventsCmdExec
execute0
class EventsCmdExec extends AbstrAsyncDockerCmdExec<EventsCmd, Event> implements EventsCmd.Exec { private static final Logger LOGGER = LoggerFactory.getLogger(EventsCmdExec.class); public EventsCmdExec(WebTarget baseResource, DockerClientConfig dockerClientConfig) { super(baseResource, dockerClientConfig); } @Override protected Void execute0(EventsCmd command, ResultCallback<Event> resultCallback) {<FILL_FUNCTION_BODY>} }
WebTarget webTarget = getBaseResource().path("/events").queryParam("since", command.getSince()) .queryParam("until", command.getUntil()); if (command.getFilters() != null && !command.getFilters().isEmpty()) { webTarget = webTarget .queryParam("filters", FiltersEncoder.jsonEncode(command.getFilters())); } LOGGER.trace("GET: {}", webTarget); webTarget.request().get(new TypeReference<Event>() { }, resultCallback); return null;
125
146
271
YunaiV_ruoyi-vue-pro
ruoyi-vue-pro/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/controller/admin/file/FileController.java
FileController
getFileContent
class FileController { @Resource private FileService fileService; @PostMapping("/upload") @Operation(summary = "上传文件", description = "模式一:后端上传文件") public CommonResult<String> uploadFile(FileUploadReqVO uploadReqVO) throws Exception { MultipartFile file = uploadReqVO.getFile(); String path = uploadReqVO.getPath(); return success(fileService.createFile(file.getOriginalFilename(), path, IoUtil.readBytes(file.getInputStream()))); } @GetMapping("/presigned-url") @Operation(summary = "获取文件预签名地址", description = "模式二:前端上传文件:用于前端直接上传七牛、阿里云 OSS 等文件存储器") public CommonResult<FilePresignedUrlRespVO> getFilePresignedUrl(@RequestParam("path") String path) throws Exception { return success(fileService.getFilePresignedUrl(path)); } @PostMapping("/create") @Operation(summary = "创建文件", description = "模式二:前端上传文件:配合 presigned-url 接口,记录上传了上传的文件") public CommonResult<Long> createFile(@Valid @RequestBody FileCreateReqVO createReqVO) { return success(fileService.createFile(createReqVO)); } @DeleteMapping("/delete") @Operation(summary = "删除文件") @Parameter(name = "id", description = "编号", required = true) @PreAuthorize("@ss.hasPermission('infra:file:delete')") public CommonResult<Boolean> deleteFile(@RequestParam("id") Long id) throws Exception { fileService.deleteFile(id); return success(true); } @GetMapping("/{configId}/get/**") @PermitAll @Operation(summary = "下载文件") @Parameter(name = "configId", description = "配置编号", required = true) public void getFileContent(HttpServletRequest request, HttpServletResponse response, @PathVariable("configId") Long configId) throws Exception {<FILL_FUNCTION_BODY>} @GetMapping("/page") @Operation(summary = "获得文件分页") @PreAuthorize("@ss.hasPermission('infra:file:query')") public CommonResult<PageResult<FileRespVO>> getFilePage(@Valid FilePageReqVO pageVO) { PageResult<FileDO> pageResult = fileService.getFilePage(pageVO); return success(BeanUtils.toBean(pageResult, FileRespVO.class)); } }
// 获取请求的路径 String path = StrUtil.subAfter(request.getRequestURI(), "/get/", false); if (StrUtil.isEmpty(path)) { throw new IllegalArgumentException("结尾的 path 路径必须传递"); } // 解码,解决中文路径的问题 https://gitee.com/zhijiantianya/ruoyi-vue-pro/pulls/807/ path = URLUtil.decode(path); // 读取内容 byte[] content = fileService.getFileContent(configId, path); if (content == null) { log.warn("[getFileContent][configId({}) path({}) 文件不存在]", configId, path); response.setStatus(HttpStatus.NOT_FOUND.value()); return; } ServletUtils.writeAttachment(response, path, content);
672
227
899
YunaiV_ruoyi-vue-pro
ruoyi-vue-pro/yudao-framework/yudao-spring-boot-starter-websocket/src/main/java/cn/iocoder/yudao/framework/websocket/core/security/LoginUserHandshakeInterceptor.java
LoginUserHandshakeInterceptor
beforeHandshake
class LoginUserHandshakeInterceptor implements HandshakeInterceptor { @Override public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) {<FILL_FUNCTION_BODY>} @Override public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) { // do nothing } }
LoginUser loginUser = SecurityFrameworkUtils.getLoginUser(); if (loginUser != null) { WebSocketFrameworkUtils.setLoginUser(loginUser, attributes); } return true;
120
53
173
elunez_eladmin
eladmin/eladmin-system/src/main/java/me/zhengjie/modules/system/service/impl/DictServiceImpl.java
DictServiceImpl
delete
class DictServiceImpl implements DictService { private final DictRepository dictRepository; private final DictMapper dictMapper; private final RedisUtils redisUtils; @Override public PageResult<DictDto> queryAll(DictQueryCriteria dict, Pageable pageable){ Page<Dict> page = dictRepository.findAll((root, query, cb) -> QueryHelp.getPredicate(root, dict, cb), pageable); return PageUtil.toPage(page.map(dictMapper::toDto)); } @Override public List<DictDto> queryAll(DictQueryCriteria dict) { List<Dict> list = dictRepository.findAll((root, query, cb) -> QueryHelp.getPredicate(root, dict, cb)); return dictMapper.toDto(list); } @Override @Transactional(rollbackFor = Exception.class) public void create(Dict resources) { dictRepository.save(resources); } @Override @Transactional(rollbackFor = Exception.class) public void update(Dict resources) { // 清理缓存 delCaches(resources); Dict dict = dictRepository.findById(resources.getId()).orElseGet(Dict::new); ValidationUtil.isNull( dict.getId(),"Dict","id",resources.getId()); dict.setName(resources.getName()); dict.setDescription(resources.getDescription()); dictRepository.save(dict); } @Override @Transactional(rollbackFor = Exception.class) public void delete(Set<Long> ids) {<FILL_FUNCTION_BODY>} @Override public void download(List<DictDto> dictDtos, HttpServletResponse response) throws IOException { List<Map<String, Object>> list = new ArrayList<>(); for (DictDto dictDTO : dictDtos) { if(CollectionUtil.isNotEmpty(dictDTO.getDictDetails())){ for (DictDetailDto dictDetail : dictDTO.getDictDetails()) { Map<String,Object> map = new LinkedHashMap<>(); map.put("字典名称", dictDTO.getName()); map.put("字典描述", dictDTO.getDescription()); map.put("字典标签", dictDetail.getLabel()); map.put("字典值", dictDetail.getValue()); map.put("创建日期", dictDetail.getCreateTime()); list.add(map); } } else { Map<String,Object> map = new LinkedHashMap<>(); map.put("字典名称", dictDTO.getName()); map.put("字典描述", dictDTO.getDescription()); map.put("字典标签", null); map.put("字典值", null); map.put("创建日期", dictDTO.getCreateTime()); list.add(map); } } FileUtil.downloadExcel(list, response); } public void delCaches(Dict dict){ redisUtils.del(CacheKey.DICT_NAME + dict.getName()); } }
// 清理缓存 List<Dict> dicts = dictRepository.findByIdIn(ids); for (Dict dict : dicts) { delCaches(dict); } dictRepository.deleteByIdIn(ids);
815
63
878
Pay-Group_best-pay-sdk
best-pay-sdk/src/main/java/com/lly835/bestpay/service/impl/alipay/AlipayQRCodeServiceImpl.java
AlipayQRCodeServiceImpl
pay
class AlipayQRCodeServiceImpl extends AliPayServiceImpl { private final Retrofit retrofit = new Retrofit.Builder() .baseUrl(AliPayConstants.ALIPAY_GATEWAY_OPEN) .addConverterFactory(GsonConverterFactory.create( //下划线驼峰互转 new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create() )) .client(new OkHttpClient.Builder() .addInterceptor((new HttpLoggingInterceptor() .setLevel(HttpLoggingInterceptor.Level.BODY))) .build() ) .build(); private final Retrofit devRetrofit = new Retrofit.Builder() .baseUrl(AliPayConstants.ALIPAY_GATEWAY_OPEN_DEV) .addConverterFactory(GsonConverterFactory.create( //下划线驼峰互转 new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create() )) .client(new OkHttpClient.Builder() .addInterceptor((new HttpLoggingInterceptor() .setLevel(HttpLoggingInterceptor.Level.BODY))) .build() ) .build(); @Override public PayResponse pay(PayRequest request) {<FILL_FUNCTION_BODY>} }
AliPayTradeCreateRequest aliPayOrderQueryRequest = new AliPayTradeCreateRequest(); aliPayOrderQueryRequest.setMethod(AliPayConstants.ALIPAY_TRADE_QRCODE_PAY); aliPayOrderQueryRequest.setAppId(aliPayConfig.getAppId()); aliPayOrderQueryRequest.setTimestamp(LocalDateTime.now().format(formatter)); aliPayOrderQueryRequest.setNotifyUrl(aliPayConfig.getNotifyUrl()); AliPayTradeCreateRequest.BizContent bizContent = new AliPayTradeCreateRequest.BizContent(); bizContent.setOutTradeNo(request.getOrderId()); bizContent.setTotalAmount(request.getOrderAmount()); bizContent.setSubject(request.getOrderName()); aliPayOrderQueryRequest.setBizContent(JsonUtil.toJsonWithUnderscores(bizContent).replaceAll("\\s*", "")); aliPayOrderQueryRequest.setSign(AliPaySignature.sign(MapUtil.object2MapWithUnderline(aliPayOrderQueryRequest), aliPayConfig.getPrivateKey())); Call<AliPayOrderCreateResponse> call; if (aliPayConfig.isSandbox()) { call = devRetrofit.create(AliPayApi.class).tradeCreate((MapUtil.object2MapWithUnderline(aliPayOrderQueryRequest))); } else { call = retrofit.create(AliPayApi.class).tradeCreate((MapUtil.object2MapWithUnderline(aliPayOrderQueryRequest))); } Response<AliPayOrderCreateResponse> retrofitResponse = null; try { retrofitResponse = call.execute(); } catch (IOException e) { e.printStackTrace(); } assert retrofitResponse != null; if (!retrofitResponse.isSuccessful()) { throw new RuntimeException("【支付宝创建订单】网络异常. alipay.trade.precreate"); } assert retrofitResponse.body() != null; AliPayOrderCreateResponse.AlipayTradeCreateResponse response = retrofitResponse.body().getAlipayTradePrecreateResponse(); if (!response.getCode().equals(AliPayConstants.RESPONSE_CODE_SUCCESS)) { throw new RuntimeException("【支付宝创建订单】alipay.trade.precreate. code=" + response.getCode() + ", returnMsg=" + response.getMsg() + String.format("|%s|%s", response.getSubCode(), response.getSubMsg())); } PayResponse payResponse = new PayResponse(); payResponse.setOutTradeNo(response.getTradeNo()); payResponse.setOrderId(response.getOutTradeNo()); payResponse.setCodeUrl(response.getQrCode()); return payResponse;
376
700
1,076
/** * Created by this on 2019/9/8 15:50 */ @Slf4j public class AliPayServiceImpl extends BestPayServiceImpl { protected final static DateTimeFormatter formatter=DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); protected AliPayConfig aliPayConfig; @Override public void setAliPayConfig( AliPayConfig aliPayConfig); private Retrofit retrofit=new Retrofit.Builder().baseUrl(AliPayConstants.ALIPAY_GATEWAY_OPEN).addConverterFactory(GsonConverterFactory.create(new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create())).client(new OkHttpClient.Builder().addInterceptor((new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))).build()).build(); private Retrofit devRetrofit=new Retrofit.Builder().baseUrl(AliPayConstants.ALIPAY_GATEWAY_OPEN_DEV).addConverterFactory(GsonConverterFactory.create(new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create())).client(new OkHttpClient.Builder().addInterceptor((new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))).build()).build(); @Override public PayResponse pay( PayRequest request); @Override public boolean verify( Map<String,String> toBeVerifiedParamMap, SignType signType, String sign); /** * 异步通知 * @param notifyData * @return */ @Override public PayResponse asyncNotify( String notifyData); @Override public RefundResponse refund( RefundRequest request); @Override public OrderQueryResponse query( OrderQueryRequest request); @Override public String downloadBill( DownloadBillRequest request); private PayResponse buildPayResponse( AliPayAsyncResponse response); @Override public CloseResponse close( CloseRequest request); @Override public PayBankResponse payBank( PayBankRequest request); }
javamelody_javamelody
javamelody/javamelody-core/src/main/java/net/bull/javamelody/SpringElasticsearchOperationsBeanPostProcessor.java
SpringElasticsearchOperationsBeanPostProcessor
postProcessAfterInitialization
class SpringElasticsearchOperationsBeanPostProcessor implements BeanPostProcessor, PriorityOrdered { private static final boolean ELASTICSEARCH_OPERATIONS_AVAILABLE = isElasticsearchOperationsAvailable(); private static final Counter SERVICES_COUNTER = MonitoringProxy.getServicesCounter(); private static final boolean COUNTER_HIDDEN = Parameters .isCounterHidden(SERVICES_COUNTER.getName()); private static final boolean DISABLED = Parameter.DISABLED.getValueAsBoolean(); // l'interface PriorityOrdered place la priorité assez haute dans le contexte Spring // quelle que soit la valeur de order private int order = LOWEST_PRECEDENCE; /** {@inheritDoc} */ @Override public int getOrder() { return order; } /** * Définit la priorité dans le contexte Spring. * @param order int */ public void setOrder(int order) { this.order = order; } /** {@inheritDoc} */ @Override public Object postProcessBeforeInitialization(Object bean, String beanName) { return bean; } /** {@inheritDoc} */ @Override public Object postProcessAfterInitialization(Object bean, String beanName) {<FILL_FUNCTION_BODY>} static Object doInvoke(final Object object, final Method method, final Object[] args, final String requestName) throws Throwable { boolean systemError = false; try { SERVICES_COUNTER.bindContextIncludingCpu(requestName); return method.invoke(object, args); } catch (final Error e) { // on catche Error pour avoir les erreurs systèmes // mais pas Exception qui sont fonctionnelles en général systemError = true; throw e; } finally { // on enregistre la requête dans les statistiques SERVICES_COUNTER.addRequestForCurrentContext(systemError); } } private static boolean isElasticsearchOperationsAvailable() { try { Class.forName("org.springframework.data.elasticsearch.core.ElasticsearchOperations"); return true; } catch (final ClassNotFoundException e) { return false; } } }
if (ELASTICSEARCH_OPERATIONS_AVAILABLE && bean instanceof ElasticsearchOperations) { final ElasticsearchOperations elasticsearchOperations = (ElasticsearchOperations) bean; if (DISABLED) { return elasticsearchOperations; } SERVICES_COUNTER.setDisplayed(!COUNTER_HIDDEN); SERVICES_COUNTER.setUsed(true); final InvocationHandler invocationHandler = new InvocationHandler() { /** {@inheritDoc} */ @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { final StringBuilder requestName = new StringBuilder(); requestName.append("elasticsearch.").append(method.getName()).append('('); if (args != null) { boolean first = true; for (final Object arg : args) { if (first) { first = false; } else { requestName.append(", "); } if (arg == null) { requestName.append("null"); } else if (arg instanceof Class) { requestName.append(((Class<?>) arg).getSimpleName()); } else { requestName.append(arg.getClass().getSimpleName()); } } } requestName.append(')'); return doInvoke(elasticsearchOperations, method, args, requestName.toString()); } }; final ElasticsearchOperations ops = JdbcWrapper.createProxy(elasticsearchOperations, invocationHandler); LOG.debug("elasticsearch operations monitoring initialized"); return ops; } return bean;
599
442
1,041
logfellow_logstash-logback-encoder
logstash-logback-encoder/src/main/java/net/logstash/logback/composite/loggingevent/StackTraceJsonProvider.java
StackTraceJsonProvider
writeTo
class StackTraceJsonProvider extends AbstractFieldJsonProvider<ILoggingEvent> implements FieldNamesAware<LogstashFieldNames> { public static final String FIELD_STACK_TRACE = "stack_trace"; /** * Used to format throwables as Strings. * * Uses an {@link ExtendedThrowableProxyConverter} from logstash by default. * * Consider using a * {@link net.logstash.logback.stacktrace.ShortenedThrowableConverter ShortenedThrowableConverter} * for more customization options. */ private ThrowableHandlingConverter throwableConverter = new ExtendedThrowableProxyConverter(); public StackTraceJsonProvider() { setFieldName(FIELD_STACK_TRACE); } @Override public void start() { this.throwableConverter.start(); super.start(); } @Override public void stop() { this.throwableConverter.stop(); super.stop(); } @Override public void writeTo(JsonGenerator generator, ILoggingEvent event) throws IOException {<FILL_FUNCTION_BODY>} @Override public void setFieldNames(LogstashFieldNames fieldNames) { setFieldName(fieldNames.getStackTrace()); } public ThrowableHandlingConverter getThrowableConverter() { return throwableConverter; } public void setThrowableConverter(ThrowableHandlingConverter throwableConverter) { this.throwableConverter = throwableConverter; } }
IThrowableProxy throwableProxy = event.getThrowableProxy(); if (throwableProxy != null) { JsonWritingUtils.writeStringField(generator, getFieldName(), throwableConverter.convert(event)); }
388
60
448
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/reader/dem/CGIARProvider.java
CGIARProvider
readFile
class CGIARProvider extends AbstractTiffElevationProvider { private final double invPrecision = 1 / precision; public CGIARProvider() { this(""); } public CGIARProvider(String cacheDir) { // Alternative URLs for the CGIAR data can be found in #346 super("https://srtm.csi.cgiar.org/wp-content/uploads/files/srtm_5x5/TIFF/", cacheDir.isEmpty() ? "/tmp/cgiar" : cacheDir, "GraphHopper CGIARReader", 6000, 6000, 5, 5); } public static void main(String[] args) { CGIARProvider provider = new CGIARProvider(); System.out.println(provider.getEle(46, -20)); // 337.0 System.out.println(provider.getEle(49.949784, 11.57517)); // 466.0 System.out.println(provider.getEle(49.968668, 11.575127)); // 455.0 System.out.println(provider.getEle(49.968682, 11.574842)); // 3134 System.out.println(provider.getEle(-22.532854, -65.110474)); // 120 System.out.println(provider.getEle(38.065392, -87.099609)); // 1615 System.out.println(provider.getEle(40, -105.2277023)); System.out.println(provider.getEle(39.99999999, -105.2277023)); System.out.println(provider.getEle(39.9999999, -105.2277023)); // 1616 System.out.println(provider.getEle(39.999999, -105.2277023)); // 0 System.out.println(provider.getEle(29.840644, -42.890625)); // 841 System.out.println(provider.getEle(48.469123, 9.576393)); } @Override Raster readFile(File file, String tifName) {<FILL_FUNCTION_BODY>} int down(double val) { // 'rounding' to closest 5 int intVal = (int) (val / LAT_DEGREE) * LAT_DEGREE; if (!(val >= 0 || intVal - val < invPrecision)) intVal = intVal - LAT_DEGREE; return intVal; } @Override boolean isOutsideSupportedArea(double lat, double lon) { return lat >= 60 || lat <= -56; } protected String getFileName(double lat, double lon) { lon = 1 + (180 + lon) / LAT_DEGREE; int lonInt = (int) lon; lat = 1 + (60 - lat) / LAT_DEGREE; int latInt = (int) lat; if (Math.abs(latInt - lat) < invPrecision / LAT_DEGREE) latInt--; // replace String.format as it seems to be slow // String.format("srtm_%02d_%02d", lonInt, latInt); String str = "srtm_"; str += lonInt < 10 ? "0" : ""; str += lonInt; str += latInt < 10 ? "_0" : "_"; str += latInt; return str; } @Override int getMinLatForTile(double lat) { return down(lat); } @Override int getMinLonForTile(double lon) { return down(lon); } @Override String getDownloadURL(double lat, double lon) { return baseUrl + "/" + getFileName(lat, lon) + ".zip"; } @Override String getFileNameOfLocalFile(double lat, double lon) { return getDownloadURL(lat, lon); } @Override public String toString() { return "cgiar"; } }
SeekableStream ss = null; try { InputStream is = new FileInputStream(file); ZipInputStream zis = new ZipInputStream(is); // find tif file in zip ZipEntry entry = zis.getNextEntry(); while (entry != null && !entry.getName().equals(tifName)) { entry = zis.getNextEntry(); } ss = SeekableStream.wrapInputStream(zis, true); TIFFImageDecoder imageDecoder = new TIFFImageDecoder(ss, new TIFFDecodeParam()); return imageDecoder.decodeAsRaster(); } catch (Exception e) { throw new RuntimeException("Can't decode " + tifName, e); } finally { if (ss != null) Helper.close(ss); }
1,223
217
1,440
/** * Provides basic methods that are usually used in an ElevationProvider that reads tiff files. * @author Robin Boldt */ public abstract class AbstractTiffElevationProvider extends TileBasedElevationProvider { private final Map<String,HeightTile> cacheData=new HashMap<>(); final double precision=1e7; private final int WIDTH; private final int HEIGHT; final int LAT_DEGREE; final int LON_DEGREE; public AbstractTiffElevationProvider( String baseUrl, String cacheDir, String downloaderName, int width, int height, int latDegree, int lonDegree); @Override public void release(); /** * Return true if the coordinates are outside of the supported area */ abstract boolean isOutsideSupportedArea( double lat, double lon); /** * The smallest lat that is still in the HeightTile */ abstract int getMinLatForTile( double lat); /** * The smallest lon that is still in the HeightTile */ abstract int getMinLonForTile( double lon); /** * Specify the name of the file after downloading */ abstract String getFileNameOfLocalFile( double lat, double lon); /** * Return the local file name without file ending, has to be lower case, because DataAccess only supports lower case names. */ abstract String getFileName( double lat, double lon); /** * Returns the complete URL to download the file */ abstract String getDownloadURL( double lat, double lon); @Override public double getEle( double lat, double lon); abstract Raster readFile( File file, String tifName); /** * Download a file at the provided url and save it as the given downloadFile if the downloadFile does not exist. */ private void downloadToFile( File downloadFile, String url) throws IOException; private void fillDataAccessWithElevationData( Raster raster, DataAccess heights, int dataAccessWidth); }
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-common/src/main/java/com/jarvis/cache/to/CacheKeyTO.java
CacheKeyTO
getCacheKey
class CacheKeyTO implements Serializable { private static final long serialVersionUID = 7229320497442357252L; private final String namespace; private final String key;// 缓存Key private final String hfield;// 设置哈希表中的字段,如果设置此项,则用哈希表进行存储 public CacheKeyTO(String namespace, String key, String hfield) { this.namespace = namespace; this.key = key; this.hfield = hfield; } public String getCacheKey() {<FILL_FUNCTION_BODY>} public String getLockKey() { StringBuilder key = new StringBuilder(getCacheKey()); if (null != hfield && hfield.length() > 0) { key.append(":").append(hfield); } key.append(":lock"); return key.toString(); } public String getNamespace() { return namespace; } public String getHfield() { return hfield; } public String getKey() { return key; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CacheKeyTO that = (CacheKeyTO) o; return Objects.equals(namespace, that.namespace) && Objects.equals(key, that.key) && Objects.equals(hfield, that.hfield); } @Override public int hashCode() { return Objects.hash(namespace, key, hfield); } @Override public String toString() { return "CacheKeyTO{" + "namespace='" + namespace + '\'' + ", key='" + key + '\'' + ", hfield='" + hfield + '\'' + '}'; } }
if (null != this.namespace && this.namespace.length() > 0) { return new StringBuilder(this.namespace).append(":").append(this.key).toString(); } return this.key;
506
57
563
obsidiandynamics_kafdrop
kafdrop/src/main/java/kafdrop/config/CorsConfiguration.java
CorsConfiguration
corsFilter
class CorsConfiguration { @Value("${cors.allowOrigins:*}") private String corsAllowOrigins; @Value("${cors.allowMethods:GET,POST,PUT,DELETE}") private String corsAllowMethods; @Value("${cors.maxAge:3600}") private String corsMaxAge; @Value("${cors.allowCredentials:true}") private String corsAllowCredentials; @Value("${cors.allowHeaders:Origin,Accept,X-Requested-With,Content-Type,Access-Control-Request-Method," + "Access-Control-Request-Headers,Authorization}") private String corsAllowHeaders; @Bean @Order(Ordered.HIGHEST_PRECEDENCE) public Filter corsFilter() {<FILL_FUNCTION_BODY>} }
return new Filter() { @Override public void init(FilterConfig filterConfig) { // nothing to init } @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { final var response = (HttpServletResponse) res; final var request = (HttpServletRequest) req; response.setHeader("Access-Control-Allow-Origin", corsAllowOrigins); response.setHeader("Access-Control-Allow-Methods", corsAllowMethods); response.setHeader("Access-Control-Max-Age", corsMaxAge); response.setHeader("Access-Control-Allow-Credentials", corsAllowCredentials); response.setHeader("Access-Control-Allow-Headers", corsAllowHeaders); if (request.getMethod().equals(HttpMethod.OPTIONS.name())) { response.setStatus(HttpStatus.NO_CONTENT.value()); } else { chain.doFilter(req, res); } } @Override public void destroy() { // nothing to destroy } };
232
285
517
obsidiandynamics_kafdrop
kafdrop/src/main/java/kafdrop/model/ConsumerVO.java
ConsumerVO
equals
class ConsumerVO implements Comparable<ConsumerVO> { private final String groupId; private final Map<String, ConsumerTopicVO> topics = new TreeMap<>(); public ConsumerVO(String groupId) { Validate.notEmpty("groupId is required"); this.groupId = groupId; } public String getGroupId() { return groupId; } public void addTopic(ConsumerTopicVO topic) { topics.put(topic.getTopic(), topic); } public ConsumerTopicVO getTopic(String topic) { return topics.get(topic); } public Collection<ConsumerTopicVO> getTopics() { return topics.values(); } @Override public int compareTo(ConsumerVO that) { return this.groupId.compareTo(that.groupId); } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hashCode(groupId); } }
if (this == o) { return true; } else if (o instanceof ConsumerVO) { final var that = (ConsumerVO) o; return Objects.equals(groupId, that.groupId); } else { return false; }
277
69
346
docker-java_docker-java
docker-java/docker-java-core/src/main/java/com/github/dockerjava/core/exec/TopContainerCmdExec.java
TopContainerCmdExec
execute
class TopContainerCmdExec extends AbstrSyncDockerCmdExec<TopContainerCmd, TopContainerResponse> implements TopContainerCmd.Exec { private static final Logger LOGGER = LoggerFactory.getLogger(TopContainerCmdExec.class); public TopContainerCmdExec(WebTarget baseResource, DockerClientConfig dockerClientConfig) { super(baseResource, dockerClientConfig); } @Override protected TopContainerResponse execute(TopContainerCmd command) {<FILL_FUNCTION_BODY>} }
WebTarget webResource = getBaseResource().path("/containers/{id}/top").resolveTemplate("id", command.getContainerId()); if (!StringUtils.isEmpty(command.getPsArgs())) { webResource = webResource.queryParam("ps_args", command.getPsArgs()); } LOGGER.trace("GET: {}", webResource); return webResource.request().accept(MediaType.APPLICATION_JSON).get(new TypeReference<TopContainerResponse>() { });
128
126
254
jeecgboot_jeecg-boot
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/DySmsHelper.java
DySmsHelper
sendSms
class DySmsHelper { private final static Logger logger=LoggerFactory.getLogger(DySmsHelper.class); /**产品名称:云通信短信API产品,开发者无需替换*/ static final String PRODUCT = "Dysmsapi"; /**产品域名,开发者无需替换*/ static final String DOMAIN = "dysmsapi.aliyuncs.com"; /**TODO 此处需要替换成开发者自己的AK(在阿里云访问控制台寻找)*/ static String accessKeyId; static String accessKeySecret; public static void setAccessKeyId(String accessKeyId) { DySmsHelper.accessKeyId = accessKeyId; } public static void setAccessKeySecret(String accessKeySecret) { DySmsHelper.accessKeySecret = accessKeySecret; } public static String getAccessKeyId() { return accessKeyId; } public static String getAccessKeySecret() { return accessKeySecret; } public static boolean sendSms(String phone, JSONObject templateParamJson, DySmsEnum dySmsEnum) throws ClientException {<FILL_FUNCTION_BODY>} private static void validateParam(JSONObject templateParamJson,DySmsEnum dySmsEnum) { String keys = dySmsEnum.getKeys(); String [] keyArr = keys.split(","); for(String item :keyArr) { if(!templateParamJson.containsKey(item)) { throw new RuntimeException("模板缺少参数:"+item); } } } // public static void main(String[] args) throws ClientException, InterruptedException { // JSONObject obj = new JSONObject(); // obj.put("code", "1234"); // sendSms("13800138000", obj, DySmsEnum.FORGET_PASSWORD_TEMPLATE_CODE); // } }
//可自助调整超时时间 System.setProperty("sun.net.client.defaultConnectTimeout", "10000"); System.setProperty("sun.net.client.defaultReadTimeout", "10000"); //update-begin-author:taoyan date:20200811 for:配置类数据获取 StaticConfig staticConfig = SpringContextUtils.getBean(StaticConfig.class); //logger.info("阿里大鱼短信秘钥 accessKeyId:" + staticConfig.getAccessKeyId()); //logger.info("阿里大鱼短信秘钥 accessKeySecret:"+ staticConfig.getAccessKeySecret()); setAccessKeyId(staticConfig.getAccessKeyId()); setAccessKeySecret(staticConfig.getAccessKeySecret()); //update-end-author:taoyan date:20200811 for:配置类数据获取 //初始化acsClient,暂不支持region化 IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret); DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", PRODUCT, DOMAIN); IAcsClient acsClient = new DefaultAcsClient(profile); //验证json参数 validateParam(templateParamJson,dySmsEnum); //组装请求对象-具体描述见控制台-文档部分内容 SendSmsRequest request = new SendSmsRequest(); //必填:待发送手机号 request.setPhoneNumbers(phone); //必填:短信签名-可在短信控制台中找到 request.setSignName(dySmsEnum.getSignName()); //必填:短信模板-可在短信控制台中找到 request.setTemplateCode(dySmsEnum.getTemplateCode()); //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为 request.setTemplateParam(templateParamJson.toJSONString()); //选填-上行短信扩展码(无特殊需求用户请忽略此字段) //request.setSmsUpExtendCode("90997"); //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者 //request.setOutId("yourOutId"); boolean result = false; //hint 此处可能会抛出异常,注意catch SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request); logger.info("短信接口返回的数据----------------"); logger.info("{Code:" + sendSmsResponse.getCode()+",Message:" + sendSmsResponse.getMessage()+",RequestId:"+ sendSmsResponse.getRequestId()+",BizId:"+sendSmsResponse.getBizId()+"}"); String ok = "OK"; if (ok.equals(sendSmsResponse.getCode())) { result = true; } return result;
524
793
1,317
spring-cloud_spring-cloud-gateway
spring-cloud-gateway/spring-cloud-gateway-server-mvc/src/main/java/org/springframework/cloud/gateway/server/mvc/invoke/InvocationContext.java
InvocationContext
resolveArgument
class InvocationContext { private final Map<String, Object> arguments; private final List<OperationArgumentResolver> argumentResolvers; /** * Creates a new context for an operation being invoked by the given * {@code securityContext} with the given available {@code arguments}. * @param arguments the arguments available to the operation. Never {@code null} * @param argumentResolvers resolvers for additional arguments should be available to * the operation. */ public InvocationContext(Map<String, Object> arguments, OperationArgumentResolver... argumentResolvers) { Assert.notNull(arguments, "Arguments must not be null"); this.arguments = arguments; this.argumentResolvers = new ArrayList<>(); if (argumentResolvers != null) { this.argumentResolvers.addAll(Arrays.asList(argumentResolvers)); } } /** * Return the invocation arguments. * @return the arguments */ public Map<String, Object> getArguments() { return this.arguments; } /** * Resolves an argument with the given {@code argumentType}. * @param <T> type of the argument * @param argumentType type of the argument * @return resolved argument of the required type or {@code null} * @since 2.5.0 * @see #canResolve(Class) */ public <T> T resolveArgument(Class<T> argumentType) {<FILL_FUNCTION_BODY>} /** * Returns whether the context is capable of resolving an argument of the given * {@code type}. Note that, even when {@code true} is returned, * {@link #resolveArgument argument resolution} will return {@code null} if no * argument of the required type is available. * @param type argument type * @return {@code true} if resolution of arguments of the given type is possible, * otherwise {@code false}. * @since 2.5.0 * @see #resolveArgument(Class) */ public boolean canResolve(Class<?> type) { for (OperationArgumentResolver argumentResolver : this.argumentResolvers) { if (argumentResolver.canResolve(type)) { return true; } } return false; } }
for (OperationArgumentResolver argumentResolver : this.argumentResolvers) { if (argumentResolver.canResolve(argumentType)) { T result = argumentResolver.resolve(argumentType); if (result != null) { return result; } } } return null;
562
78
640
Pay-Group_best-pay-sdk
best-pay-sdk/src/main/java/com/lly835/bestpay/utils/StringUtil.java
StringUtil
isEmpty
class StringUtil { public static boolean areNotEmpty(String... values) { boolean result = true; if (values != null && values.length != 0) { String[] var2 = values; int var3 = values.length; for(int var4 = 0; var4 < var3; ++var4) { String value = var2[var4]; result &= !isEmpty(value); } } else { result = false; } return result; } public static boolean isEmpty(String value) {<FILL_FUNCTION_BODY>} }
int strLen; if (value != null && (strLen = value.length()) != 0) { for(int i = 0; i < strLen; ++i) { if (!Character.isWhitespace(value.charAt(i))) { return false; } } return true; } else { return true; }
160
98
258
zhkl0228_unidbg
unidbg/unidbg-android/src/main/java/net/fornwall/jelf/PtLoadData.java
PtLoadData
writeTo
class PtLoadData { private final ByteBuffer buffer; private final long dataSize; PtLoadData(ByteBuffer buffer, long dataSize) { this.buffer = buffer; this.dataSize = dataSize; } public long getDataSize() { return dataSize; } public void writeTo(final Pointer ptr) {<FILL_FUNCTION_BODY>} }
Pointer pointer = ptr; byte[] buf = new byte[Math.min(0x1000, buffer.remaining())]; while (buffer.hasRemaining()) { int write = Math.min(buf.length, buffer.remaining()); buffer.get(buf, 0, write); pointer.write(0, buf, 0, write); pointer = pointer.share(write); }
111
108
219
spring-cloud_spring-cloud-gateway
spring-cloud-gateway/spring-cloud-gateway-server/src/main/java/org/springframework/cloud/gateway/discovery/DiscoveryLocatorProperties.java
DiscoveryLocatorProperties
toString
class DiscoveryLocatorProperties { /** Flag that enables DiscoveryClient gateway integration. */ private boolean enabled = false; /** * The prefix for the routeId, defaults to discoveryClient.getClass().getSimpleName() * + "_". Service Id will be appended to create the routeId. */ private String routeIdPrefix; /** * SpEL expression that will evaluate whether to include a service in gateway * integration or not, defaults to: true. */ private String includeExpression = "true"; /** * SpEL expression that create the uri for each route, defaults to: 'lb://'+serviceId. */ private String urlExpression = "'lb://'+serviceId"; /** * Option to lower case serviceId in predicates and filters, defaults to false. Useful * with eureka when it automatically uppercases serviceId. so MYSERIVCE, would match * /myservice/** */ private boolean lowerCaseServiceId = false; private List<PredicateDefinition> predicates = new ArrayList<>(); private List<FilterDefinition> filters = new ArrayList<>(); public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public String getRouteIdPrefix() { return routeIdPrefix; } public void setRouteIdPrefix(String routeIdPrefix) { this.routeIdPrefix = routeIdPrefix; } public String getIncludeExpression() { return includeExpression; } public void setIncludeExpression(String includeExpression) { this.includeExpression = includeExpression; } public String getUrlExpression() { return urlExpression; } public void setUrlExpression(String urlExpression) { this.urlExpression = urlExpression; } public boolean isLowerCaseServiceId() { return lowerCaseServiceId; } public void setLowerCaseServiceId(boolean lowerCaseServiceId) { this.lowerCaseServiceId = lowerCaseServiceId; } public List<PredicateDefinition> getPredicates() { return predicates; } public void setPredicates(List<PredicateDefinition> predicates) { this.predicates = predicates; } public List<FilterDefinition> getFilters() { return filters; } public void setFilters(List<FilterDefinition> filters) { this.filters = filters; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return new ToStringCreator(this).append("enabled", enabled).append("routeIdPrefix", routeIdPrefix) .append("includeExpression", includeExpression).append("urlExpression", urlExpression) .append("lowerCaseServiceId", lowerCaseServiceId).append("predicates", predicates) .append("filters", filters).toString();
624
86
710
eirslett_frontend-maven-plugin
frontend-maven-plugin/frontend-maven-plugin/src/main/java/com/github/eirslett/maven/plugins/frontend/mojo/EmberMojo.java
EmberMojo
shouldExecute
class EmberMojo extends AbstractFrontendMojo { /** * Grunt arguments. Default is empty (runs just the "grunt" command). */ @Parameter(property = "frontend.ember.arguments") private String arguments; /** * Files that should be checked for changes, in addition to the srcdir files. * {@link #workingDirectory}. */ @Parameter(property = "triggerfiles") private List<File> triggerfiles; /** * The directory containing front end files that will be processed by grunt. * If this is set then files in the directory will be checked for * modifications before running grunt. */ @Parameter(property = "srcdir") private File srcdir; /** * The directory where front end files will be output by grunt. 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.ember", defaultValue = "${skip.ember}") private boolean skip; @Component private BuildContext buildContext; @Override protected boolean skipExecution() { return this.skip; } @Override public synchronized void execute(FrontendPluginFactory factory) throws TaskRunnerException { if (shouldExecute()) { factory.getEmberRunner().execute(arguments, environmentVariables); if (outputdir != null) { getLog().info("Refreshing files after ember: " + outputdir); buildContext.refresh(outputdir); } } else { getLog().info("Skipping ember as no modified files in " + srcdir); } } private boolean shouldExecute() {<FILL_FUNCTION_BODY>} }
if (triggerfiles == null || triggerfiles.isEmpty()) { triggerfiles = Arrays.asList(new File(workingDirectory, "Gruntfile.js")); } return MojoUtils.shouldExecute(buildContext, triggerfiles, srcdir);
495
68
563
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; }
orientechnologies_orientdb
orientdb/core/src/main/java/com/orientechnologies/orient/core/storage/OPhysicalPosition.java
OPhysicalPosition
equals
class OPhysicalPosition implements OSerializableStream, Externalizable { private static final int binarySize = OBinaryProtocol.SIZE_LONG + OBinaryProtocol.SIZE_BYTE + OBinaryProtocol.SIZE_INT + OBinaryProtocol.SIZE_INT; public long clusterPosition; public byte recordType; public int recordVersion = 0; public int recordSize; public OPhysicalPosition() {} public OPhysicalPosition(final long iClusterPosition) { clusterPosition = iClusterPosition; } public OPhysicalPosition(final byte iRecordType) { recordType = iRecordType; } public OPhysicalPosition(final long iClusterPosition, final int iVersion) { clusterPosition = iClusterPosition; recordVersion = iVersion; } private void copyTo(final OPhysicalPosition iDest) { iDest.clusterPosition = clusterPosition; iDest.recordType = recordType; iDest.recordVersion = recordVersion; iDest.recordSize = recordSize; } public void copyFrom(final OPhysicalPosition iSource) { iSource.copyTo(this); } @Override public String toString() { return "rid(?:" + clusterPosition + ") record(type:" + recordType + " size:" + recordSize + " v:" + recordVersion + ")"; } @Override public OSerializableStream fromStream(final byte[] iStream) throws OSerializationException { int pos = 0; clusterPosition = OBinaryProtocol.bytes2long(iStream); pos += OBinaryProtocol.SIZE_LONG; recordType = iStream[pos]; pos += OBinaryProtocol.SIZE_BYTE; recordSize = OBinaryProtocol.bytes2int(iStream, pos); pos += OBinaryProtocol.SIZE_INT; recordVersion = OBinaryProtocol.bytes2int(iStream, pos); return this; } @Override public byte[] toStream() throws OSerializationException { final byte[] buffer = new byte[binarySize]; int pos = 0; OBinaryProtocol.long2bytes(clusterPosition, buffer, pos); pos += OBinaryProtocol.SIZE_LONG; buffer[pos] = recordType; pos += OBinaryProtocol.SIZE_BYTE; OBinaryProtocol.int2bytes(recordSize, buffer, pos); pos += OBinaryProtocol.SIZE_INT; OBinaryProtocol.int2bytes(recordVersion, buffer, pos); return buffer; } @Override public boolean equals(Object obj) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { int result = (int) (31 * clusterPosition); result = 31 * result + (int) recordType; result = 31 * result + recordVersion; result = 31 * result + recordSize; return result; } @Override public void writeExternal(final ObjectOutput out) throws IOException { out.writeLong(clusterPosition); out.writeByte(recordType); out.writeInt(recordSize); out.writeInt(recordVersion); } @Override public void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException { clusterPosition = in.readLong(); recordType = in.readByte(); recordSize = in.readInt(); recordVersion = in.readInt(); } }
if (obj == null || !(obj instanceof OPhysicalPosition)) return false; final OPhysicalPosition other = (OPhysicalPosition) obj; return clusterPosition == other.clusterPosition && recordType == other.recordType && recordVersion == other.recordVersion && recordSize == other.recordSize;
898
83
981
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-serializer/autoload-cache-serializer-kryo/src/main/java/com/jarvis/cache/serializer/kryo/DefaultKryoContext.java
DefaultKryoContext
serialize
class DefaultKryoContext implements KryoContext { private static final int DEFAULT_BUFFER_SIZE = 1024 * 100; private KryoPool pool; private List<KryoClassRegistration> registrations; public static KryoContext newKryoContextFactory(KryoClassRegistration registration) { KryoContext kryoContext = new DefaultKryoContext(); kryoContext.addKryoClassRegistration(registration); return kryoContext; } private DefaultKryoContext() { registrations = new ArrayList<>(); //KryoFactory的create方法会延后调用 pool = new KryoPool.Builder(() -> { Kryo kryo = new Kryo(); registrations.forEach(reg -> reg.register(kryo)); return kryo; }).softReferences().build(); } @Override public byte[] serialize(Object obj) { return serialize(obj, DEFAULT_BUFFER_SIZE); } @Override public byte[] serialize(Object obj, int bufferSize) {<FILL_FUNCTION_BODY>} @Override public Object deserialize(byte[] serialized) { Kryo kryo = pool.borrow(); try (Input input = new Input(new ByteArrayInputStream(serialized))) { Object o = kryo.readClassAndObject(input); return o; } finally { pool.release(kryo); } } @Override public void addKryoClassRegistration(KryoClassRegistration registration) { if (null != registration) { registrations.add(registration); } } }
Kryo kryo = pool.borrow(); try (Output output = new Output(new ByteArrayOutputStream(), bufferSize)) { kryo.writeClassAndObject(output, obj); return output.toBytes(); } finally { pool.release(kryo); }
451
77
528
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-serializer/autoload-cache-serializer-hessian/src/main/java/com/jarvis/cache/serializer/hession/WeakReferenceSerializer.java
WeakReferenceSerializer
writeObject
class WeakReferenceSerializer extends AbstractSerializer implements ObjectSerializer { @Override public Serializer getObjectSerializer() { return this; } @Override public void writeObject(Object obj, AbstractHessianOutput out) throws IOException {<FILL_FUNCTION_BODY>} }
if (out.addRef(obj)) { return; } @SuppressWarnings("unchecked") WeakReference<Object> data = (WeakReference<Object>) obj; int refV = out.writeObjectBegin(WeakReference.class.getName()); if (refV == -1) { out.writeInt(1); out.writeString("ref"); out.writeObjectBegin(WeakReference.class.getName()); } if (data != null) { Object ref = data.get(); if (null != ref) { out.writeObject(ref); } else { out.writeNull(); } } else { out.writeNull(); }
75
192
267
zhkl0228_unidbg
unidbg/unidbg-android/src/main/java/com/github/unidbg/linux/android/dvm/api/Bitmap.java
Bitmap
lockPixels
class Bitmap extends DvmObject<BufferedImage> { public Bitmap(VM vm, BufferedImage image) { super(vm.resolveClass("android/graphics/Bitmap"), image); } public Pointer lockPixels(Emulator<?> emulator, BufferedImage image, ByteBuffer buffer) {<FILL_FUNCTION_BODY>} public void unlockPixels() { freeMemoryBlock(null); } }
Pointer pointer = allocateMemoryBlock(emulator, image.getWidth() * image.getHeight() * 4); pointer.write(0, buffer.array(), 0, buffer.capacity()); return pointer;
117
57
174
jitsi_jitsi
jitsi/modules/plugin/desktoputil/src/main/java/net/java/sip/communicator/plugin/desktoputil/plaf/SIPCommTabbedPaneEnhancedUI.java
ScrollableTabButton
tabRemoveHighlight
class ScrollableTabButton extends SIPCommTabbedPaneUI.ScrollableTabButton { /** * Serial version UID. */ private static final long serialVersionUID = 0L; public ScrollableTabButton(int direction) { super(direction); setRolloverEnabled(true); } @Override public Dimension getPreferredSize() { return new Dimension(16, calculateMaxTabHeight(0)); } @Override public void paint(Graphics g) { Color origColor; boolean isPressed, isRollOver, isEnabled; int w, h, size; w = getWidth(); h = getHeight(); origColor = g.getColor(); isPressed = getModel().isPressed(); isRollOver = getModel().isRollover(); isEnabled = isEnabled(); g.setColor(getBackground()); g.fillRect(0, 0, w, h); g.setColor(shadow); // Using the background color set above if (direction == WEST) { g.drawLine(0, 0, 0, h - 1); // left g.drawLine(w - 1, 0, w - 1, 0); // right } else g.drawLine(w - 2, h - 1, w - 2, 0); // right g.drawLine(0, 0, w - 2, 0); // top if (isRollOver) { // do highlights or shadows Color color1; Color color2; if (isPressed) { color2 = Color.WHITE; color1 = shadow; } else { color1 = Color.WHITE; color2 = shadow; } g.setColor(color1); if (direction == WEST) { g.drawLine(1, 1, 1, h - 1); // left g.drawLine(1, 1, w - 2, 1); // top g.setColor(color2); g.drawLine(w - 1, h - 1, w - 1, 1); // right } else { g.drawLine(0, 1, 0, h - 1); g.drawLine(0, 1, w - 3, 1); // top g.setColor(color2); g.drawLine(w - 3, h - 1, w - 3, 1); // right } } // g.drawLine(0, h - 1, w - 1, h - 1); //bottom // If there's no room to draw arrow, bail if (h < 5 || w < 5) { g.setColor(origColor); return; } if (isPressed) { g.translate(1, 1); } // Draw the arrow size = Math.min((h - 4) / 3, (w - 4) / 3); size = Math.max(size, 2); boolean highlight = false; if(!highlightedTabs.isEmpty() && ((direction == WEST && tabScroller.scrollBackwardButton.isEnabled()) || (direction == EAST && tabScroller.scrollForwardButton.isEnabled()))) { Rectangle viewRect = tabScroller.viewport.getViewRect(); if(direction == WEST) { int leadingTabIndex = getClosestTab(viewRect.x, viewRect.y); for(int i = 0; i < leadingTabIndex; i++) { if(highlightedTabs.contains(i) && !isScrollTabVisible(i)) { highlight = true; break; } } } else { int leadingTabIndex = getClosestTab(viewRect.x + viewRect.y, viewRect.y); for(int i = leadingTabIndex; i < tabPane.getTabCount(); i++) { if(highlightedTabs.contains(i) && !isScrollTabVisible(i)) { highlight = true; break; } } } if(highlight) { Image img = DesktopUtilActivator.getImage( direction == WEST ? "service.gui.icons.TAB_UNREAD_BACKWARD_ICON" : "service.gui.icons.TAB_UNREAD_FORWARD_ICON"); int wi = img.getWidth(null); g.drawImage(img, (w - wi)/2, (h - size) / 2 - 2/* 2 borders 1px width*/, null); } } if(!highlight) paintTriangle(g, (w - size) / 2, (h - size) / 2, size, direction, isEnabled); // Reset the Graphics back to it's original settings if (isPressed) { g.translate(-1, -1); } g.setColor(origColor); } } /** * Checks whether the <tt>tabIndex</tt> is visible in the scrollable * tabs list. * * @param tabIndex the tab index to check. * @return whether <tt>tabIndex</tt> is visible in the list of scrollable * tabs. */ private boolean isScrollTabVisible(int tabIndex) { Rectangle tabRect = rects[tabIndex]; Rectangle viewRect = tabScroller.viewport.getViewRect(); if ((tabRect.x + tabRect.width - BUTTONSIZE < viewRect.x) || (tabRect.x + BUTTONSIZE > viewRect.x + viewRect.width)) { return false; } else { return true; } } @Override protected SIPCommTabbedPaneUI.ScrollableTabButton createScrollableTabButton( int direction) { return new ScrollableTabButton(direction); } @Override protected int calculateTabWidth(int tabPlacement, int tabIndex, FontMetrics metrics) { int width = super.calculateTabWidth(tabPlacement, tabIndex, metrics); if (isOneActionButtonEnabled()) { if(width > PREFERRED_WIDTH) width = PREFERRED_WIDTH; } return width + WIDTHDELTA; } public void tabAddHightlight(int tabIndex) { this.highlightedTabs.add(tabIndex); } public void tabRemoveHighlight(int tabIndex) {<FILL_FUNCTION_BODY>
Iterator<Integer> highlightedIter = highlightedTabs.iterator(); while (highlightedIter.hasNext()) { if (highlightedIter.next().intValue() == tabIndex) { highlightedIter.remove(); break; } }
1,779
71
1,850
orientechnologies_orientdb
orientdb/core/src/main/java/com/orientechnologies/orient/core/sql/parser/OValueExpression.java
OValueExpression
equals
class OValueExpression extends OExpression { public OValueExpression(Object val) { super(-1); this.value = val; } public Object execute(OIdentifiable iCurrentRecord, OCommandContext ctx) { return value; } public Object execute(OResult iCurrentRecord, OCommandContext ctx) { return value; } public boolean isBaseIdentifier() { return false; } public boolean isEarlyCalculated() { return true; } public OIdentifier getDefaultAlias() { return new OIdentifier(String.valueOf(value)); } public void toString(Map<Object, Object> params, StringBuilder builder) { builder.append(String.valueOf(value)); } public boolean supportsBasicCalculation() { return true; } public boolean isIndexedFunctionCal() { return false; } public boolean canExecuteIndexedFunctionWithoutIndex( OFromClause target, OCommandContext context, OBinaryCompareOperator operator, Object right) { return false; } public boolean allowsIndexedFunctionExecutionOnTarget( OFromClause target, OCommandContext context, OBinaryCompareOperator operator, Object right) { return false; } public boolean executeIndexedFunctionAfterIndexSearch( OFromClause target, OCommandContext context, OBinaryCompareOperator operator, Object right) { return false; } public boolean isExpand() { return false; } public OValueExpression getExpandContent() { return null; } public boolean needsAliases(Set<String> aliases) { return false; } public boolean isAggregate() { return false; } public OValueExpression splitForAggregation(AggregateProjectionSplit aggregateSplit) { return this; } public AggregationContext getAggregationContext(OCommandContext ctx) { throw new OCommandExecutionException("Cannot aggregate on " + toString()); } public OValueExpression copy() { OValueExpression result = new OValueExpression(-1); result.value = value; return result; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return 1; } public void extractSubQueries(SubQueryCollector collector) {} public void extractSubQueries(OIdentifier letAlias, SubQueryCollector collector) {} public boolean refersToParent() { return false; } List<String> getMatchPatternInvolvedAliases() { return null; } public void applyRemove(OResultInternal result, OCommandContext ctx) { throw new OCommandExecutionException("Cannot apply REMOVE " + toString()); } public boolean isCount() { return false; } public OResult serialize() { throw new UnsupportedOperationException( "Cannot serialize value expression (not supported yet)"); } public void deserialize(OResult fromResult) { throw new UnsupportedOperationException( "Cannot deserialize value expression (not supported yet)"); } public boolean isDefinedFor(OResult currentRecord) { return true; } public boolean isDefinedFor(OElement currentRecord) { return true; } public OCollate getCollate(OResult currentRecord, OCommandContext ctx) { return null; } public boolean isCacheable() { return true; } }
if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; OValueExpression that = (OValueExpression) o; return that.value == this.value;
931
61
992
public class OExpression extends SimpleNode { protected Boolean singleQuotes; protected Boolean doubleQuotes; protected boolean isNull=false; protected ORid rid; protected OMathExpression mathExpression; protected OArrayConcatExpression arrayConcatExpression; protected OJson json; protected Boolean booleanValue; public OExpression( int id); public OExpression( OrientSql p, int id); public OExpression( OIdentifier identifier); public OExpression( OIdentifier identifier, OModifier modifier); public OExpression( ORecordAttribute attr, OModifier modifier); public Object execute( OIdentifiable iCurrentRecord, OCommandContext ctx); public Object execute( OResult iCurrentRecord, OCommandContext ctx); public boolean isBaseIdentifier(); public Optional<OPath> getPath(); public boolean isEarlyCalculated( OCommandContext ctx); public OIdentifier getDefaultAlias(); public void toString( Map<Object,Object> params, StringBuilder builder); @Override public void toGenericStatement( StringBuilder builder); public static String encode( String s); public boolean supportsBasicCalculation(); public boolean isIndexedFunctionCal(); public static String encodeSingle( String s); public long estimateIndexedFunction( OFromClause target, OCommandContext context, OBinaryCompareOperator operator, Object right); public Iterable<OIdentifiable> executeIndexedFunction( OFromClause target, OCommandContext context, OBinaryCompareOperator operator, Object right); /** * tests if current expression is an indexed function AND that function can also be executed without using the index * @param target the query target * @param context the execution context * @param operator * @param right * @return true if current expression is an indexed funciton AND that function can also beexecuted without using the index, false otherwise */ public boolean canExecuteIndexedFunctionWithoutIndex( OFromClause target, OCommandContext context, OBinaryCompareOperator operator, Object right); /** * tests if current expression is an indexed function AND that function can be used on this target * @param target the query target * @param context the execution context * @param operator * @param right * @return true if current expression involves an indexed function AND that function can be usedon this target, false otherwise */ public boolean allowsIndexedFunctionExecutionOnTarget( OFromClause target, OCommandContext context, OBinaryCompareOperator operator, Object right); /** * tests if current expression is an indexed function AND the function has also to be executed after the index search. In some cases, the index search is accurate, so this condition can be excluded from further evaluation. In other cases the result from the index is a superset of the expected result, so the function has to be executed anyway for further filtering * @param target the query target * @param context the execution context * @return true if current expression involves an indexed function AND the function has also to beexecuted after the index search. */ public boolean executeIndexedFunctionAfterIndexSearch( OFromClause target, OCommandContext context, OBinaryCompareOperator operator, Object right); public boolean isExpand(); public OExpression getExpandContent(); public boolean needsAliases( Set<String> aliases); public boolean isAggregate(); public OExpression splitForAggregation( AggregateProjectionSplit aggregateSplit, OCommandContext ctx); public AggregationContext getAggregationContext( OCommandContext ctx); public OExpression copy(); @Override public boolean equals( Object o); @Override public int hashCode(); public void setMathExpression( OMathExpression mathExpression); public void extractSubQueries( SubQueryCollector collector); public void extractSubQueries( OIdentifier letAlias, SubQueryCollector collector); public boolean refersToParent(); public ORid getRid(); public void setRid( ORid rid); public OMathExpression getMathExpression(); /** * if the condition involved the current pattern (MATCH statement, eg. $matched.something = foo), returns the name of involved pattern aliases ("something" in this case) * @return a list of pattern aliases involved in this condition. Null it does not involve thepattern */ List<String> getMatchPatternInvolvedAliases(); public void applyRemove( OResultInternal result, OCommandContext ctx); public boolean isCount(); public OArrayConcatExpression getArrayConcatExpression(); public void setArrayConcatExpression( OArrayConcatExpression arrayConcatExpression); public OResult serialize(); public void deserialize( OResult fromResult); public boolean isDefinedFor( OResult currentRecord); public boolean isDefinedFor( OElement currentRecord); public OCollate getCollate( OResult currentRecord, OCommandContext ctx); public boolean isCacheable(); public boolean isIndexChain( OCommandContext ctx, OClass clazz); public boolean isFunctionAny(); public boolean isFunctionAll(); }
docker-java_docker-java
docker-java/docker-java-core/src/main/java/com/github/dockerjava/core/exec/InspectExecCmdExec.java
InspectExecCmdExec
execute
class InspectExecCmdExec extends AbstrSyncDockerCmdExec<InspectExecCmd, InspectExecResponse> implements InspectExecCmd.Exec { private static final Logger LOGGER = LoggerFactory.getLogger(InspectExecCmdExec.class); public InspectExecCmdExec(WebTarget baseResource, DockerClientConfig dockerClientConfig) { super(baseResource, dockerClientConfig); } @Override protected InspectExecResponse execute(InspectExecCmd command) {<FILL_FUNCTION_BODY>} }
WebTarget webResource = getBaseResource().path("/exec/{id}/json").resolveTemplate("id", command.getExecId()); LOGGER.debug("GET: {}", webResource); return webResource.request().accept(MediaType.APPLICATION_JSON).get(new TypeReference<InspectExecResponse>() { });
134
84
218
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-serializer/autoload-cache-serializer-protobuf/src/main/java/com/jarvis/cache/serializer/protobuf/WriteByteBuf.java
WriteByteBuf
writeBytes
class WriteByteBuf extends OutputStream { private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; private byte[] buf; private int count; public WriteByteBuf() { this(32); } @Override public void write(int b) throws IOException { writeByte((byte) b); } public WriteByteBuf(int arrayLength) { buf = new byte[arrayLength]; } public void writeByte(byte value) { int length = 1; ensureCapacity(length + count); HeapByteBufUtil.setByte(buf, count, value); count += length; } public void writeInt(int value) { int length = 4; ensureCapacity(length + count); HeapByteBufUtil.setInt(buf, count, value); count += length; } public void writeLong(long value) { int length = 8; ensureCapacity(length + count); HeapByteBufUtil.setLong(buf, count, value); count += length; } public void writeBytes(byte[] bytes) {<FILL_FUNCTION_BODY>} public byte[] toByteArray() { byte[] newArray = new byte[count]; System.arraycopy(buf, 0, newArray, 0, count); return newArray; } private void ensureCapacity(int minCapacity) { // overflow-conscious code if (minCapacity - buf.length > 0) grow(minCapacity); } private void grow(int minCapacity) { // overflow-conscious code int oldCapacity = buf.length; int newCapacity = oldCapacity << 1; if (newCapacity - minCapacity < 0) newCapacity = minCapacity; if (newCapacity - MAX_ARRAY_SIZE > 0) newCapacity = hugeCapacity(minCapacity); buf = Arrays.copyOf(buf, newCapacity); } private static int hugeCapacity(int minCapacity) { if (minCapacity < 0) // overflow throw new OutOfMemoryError(); return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE; } }
int length = bytes.length; ensureCapacity(bytes.length + count); System.arraycopy(bytes, 0, buf, count, length); count += bytes.length;
607
50
657