proj_name
stringclasses 230
values | relative_path
stringlengths 33
262
| class_name
stringlengths 1
68
| func_name
stringlengths 1
60
| masked_class
stringlengths 66
10.4k
| func_body
stringlengths 0
7.99k
| len_input
int64 27
2.03k
| len_output
int64 1
1.87k
| total
int64 32
2.05k
| index
int64 3
70.5k
|
---|---|---|---|---|---|---|---|---|---|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/change/core/DropForeignKeyConstraintChange.java
|
DropForeignKeyConstraintChange
|
getBaseTableName
|
class DropForeignKeyConstraintChange extends AbstractChange {
private String baseTableCatalogName;
private String baseTableSchemaName;
private String baseTableName;
private String constraintName;
@DatabaseChangeProperty(mustEqualExisting ="foreignKey.table.catalog", since = "3.0",
description = "Name of the database catalog of the base table")
public String getBaseTableCatalogName() {
return baseTableCatalogName;
}
public void setBaseTableCatalogName(String baseTableCatalogName) {
this.baseTableCatalogName = baseTableCatalogName;
}
@DatabaseChangeProperty(mustEqualExisting ="foreignKey.table.schema",
description = "Name of the database schema of the base table")
public String getBaseTableSchemaName() {
return baseTableSchemaName;
}
public void setBaseTableSchemaName(String baseTableSchemaName) {
this.baseTableSchemaName = baseTableSchemaName;
}
@DatabaseChangeProperty(mustEqualExisting = "foreignKey.table",
description = "Name of the table containing the column constrained by the foreign key")
public String getBaseTableName() {<FILL_FUNCTION_BODY>}
public void setBaseTableName(String baseTableName) {
this.baseTableName = baseTableName;
}
@DatabaseChangeProperty(mustEqualExisting = "foreignKey", description = "Name of the foreign key constraint to drop",
exampleValue = "fk_address_person")
public String getConstraintName() {
return constraintName;
}
public void setConstraintName(String constraintName) {
this.constraintName = constraintName;
}
@Override
public SqlStatement[] generateStatements(Database database) {
return new SqlStatement[]{
new DropForeignKeyConstraintStatement(
getBaseTableCatalogName(),
getBaseTableSchemaName(),
getBaseTableName(),
getConstraintName()),
};
}
@Override
public ChangeStatus checkStatus(Database database) {
try {
return new ChangeStatus().assertComplete(!SnapshotGeneratorFactory.getInstance().has(new ForeignKey(getConstraintName(), getBaseTableCatalogName(), getBaseTableSchemaName(), getBaseTableCatalogName()), database), "Foreign key exists");
} catch (Exception e) {
return new ChangeStatus().unknown(e);
}
}
@Override
public String getConfirmationMessage() {
return "Foreign key " + getConstraintName() + " dropped";
}
@Override
public String getSerializedObjectNamespace() {
return STANDARD_CHANGELOG_NAMESPACE;
}
}
|
return baseTableName;
| 676 | 10 | 686 | 30,640 |
apache_maven
|
maven/maven-core/src/main/java/org/apache/maven/project/collector/MultiModuleCollectionStrategy.java
|
MultiModuleCollectionStrategy
|
isModuleOutsideRequestScopeDependingOnPluginModule
|
class MultiModuleCollectionStrategy implements ProjectCollectionStrategy {
private static final Logger LOGGER = LoggerFactory.getLogger(MultiModuleCollectionStrategy.class);
private final ModelLocator modelLocator;
private final ProjectsSelector projectsSelector;
@Inject
public MultiModuleCollectionStrategy(ModelLocator modelLocator, ProjectsSelector projectsSelector) {
this.modelLocator = modelLocator;
this.projectsSelector = projectsSelector;
}
@Override
public List<MavenProject> collectProjects(MavenExecutionRequest request) throws ProjectBuildingException {
File moduleProjectPomFile = getMultiModuleProjectPomFile(request);
List<File> files = Collections.singletonList(moduleProjectPomFile.getAbsoluteFile());
try {
List<MavenProject> projects = projectsSelector.selectProjects(files, request);
boolean isRequestedProjectCollected = isRequestedProjectCollected(request, projects);
if (isRequestedProjectCollected) {
return projects;
} else {
LOGGER.debug(
"Multi module project collection failed:{}"
+ "Detected a POM file next to a .mvn directory in a parent directory ({}). "
+ "Maven assumed that POM file to be the parent of the requested project ({}), but it turned "
+ "out that it was not. Another project collection strategy will be executed as result.",
System.lineSeparator(),
moduleProjectPomFile.getAbsolutePath(),
request.getPom().getAbsolutePath());
return Collections.emptyList();
}
} catch (ProjectBuildingException e) {
boolean fallThrough = isModuleOutsideRequestScopeDependingOnPluginModule(request, e);
if (fallThrough) {
LOGGER.debug(
"Multi module project collection failed:{}"
+ "Detected that one of the modules of this multi-module project uses another module as "
+ "plugin extension which still needed to be built. This is not possible within the same "
+ "reactor build. Another project collection strategy will be executed as result.",
System.lineSeparator());
return Collections.emptyList();
}
throw e;
}
}
private File getMultiModuleProjectPomFile(MavenExecutionRequest request) {
File multiModuleProjectDirectory = request.getMultiModuleProjectDirectory();
if (request.getPom().getParentFile().equals(multiModuleProjectDirectory)) {
return request.getPom();
} else {
File multiModuleProjectPom = modelLocator.locateExistingPom(multiModuleProjectDirectory);
if (multiModuleProjectPom == null) {
LOGGER.info(
"Maven detected that the requested POM file is part of a multi-module project, "
+ "but could not find a pom.xml file in the multi-module root directory '{}'.",
multiModuleProjectDirectory);
LOGGER.info(
"The reactor is limited to all projects under: {}",
request.getPom().getParent());
return request.getPom();
}
return multiModuleProjectPom;
}
}
/**
* multiModuleProjectDirectory in MavenExecutionRequest is not always the parent of the request pom.
* We should always check whether the request pom project is collected.
* The integration tests for MNG-6223 are examples for this scenario.
*
* @return true if the collected projects contain the requested project (for example with -f)
*/
private boolean isRequestedProjectCollected(MavenExecutionRequest request, List<MavenProject> projects) {
return projects.stream().map(MavenProject::getFile).anyMatch(request.getPom()::equals);
}
/**
* This method finds out whether collecting projects failed because of the following scenario:
* - A multi-module project containing a module which is a plugin and another module which depends on it.
* - Just the plugin is being built with the -f <pom> flag.
* - Because of inter-module dependency collection, all projects in the multi-module project are collected.
* - The plugin is not yet installed in a repository.
*
* Therefore the build fails because the plugin is not found and plugins cannot be built in the same session.
*
* The integration test for <a href="https://issues.apache.org/jira/browse/MNG-5572">MNG-5572</a> is an
* example of this scenario.
*
* @return true if the module which fails to collect the inter-module plugin is not part of the build.
*/
private boolean isModuleOutsideRequestScopeDependingOnPluginModule(
MavenExecutionRequest request, ProjectBuildingException exception) {<FILL_FUNCTION_BODY>}
}
|
return exception.getResults().stream()
.map(ProjectBuildingResult::getProject)
.filter(Objects::nonNull)
.filter(project -> request.getPom().equals(project.getFile()))
.findFirst()
.map(requestPomProject -> {
List<MavenProject> modules = requestPomProject.getCollectedProjects() != null
? requestPomProject.getCollectedProjects()
: Collections.emptyList();
List<MavenProject> projectsInRequestScope = new ArrayList<>(modules);
projectsInRequestScope.add(requestPomProject);
Predicate<ProjectBuildingResult> projectsOutsideOfRequestScope =
pr -> !projectsInRequestScope.contains(pr.getProject());
Predicate<Exception> pluginArtifactNotFoundException = exc -> exc instanceof PluginManagerException
&& exc.getCause() instanceof PluginResolutionException
&& exc.getCause().getCause() instanceof ArtifactResolutionException
&& exc.getCause().getCause().getCause() instanceof ArtifactNotFoundException;
Predicate<Plugin> isPluginPartOfRequestScope = plugin -> projectsInRequestScope.stream()
.anyMatch(project -> project.getGroupId().equals(plugin.getGroupId())
&& project.getArtifactId().equals(plugin.getArtifactId())
&& project.getVersion().equals(plugin.getVersion()));
return exception.getResults().stream()
.filter(projectsOutsideOfRequestScope)
.flatMap(projectBuildingResult -> projectBuildingResult.getProblems().stream())
.map(ModelProblem::getException)
.filter(pluginArtifactNotFoundException)
.map(exc -> ((PluginResolutionException) exc.getCause()).getPlugin())
.anyMatch(isPluginPartOfRequestScope);
})
.orElse(false);
| 1,182 | 468 | 1,650 | 11,320 |
geekidea_spring-boot-plus
|
spring-boot-plus/src/main/java/io/geekidea/boot/framework/xss/XssFilter.java
|
XssFilter
|
doFilter
|
class XssFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
log.info("XssFilter init");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {<FILL_FUNCTION_BODY>}
@Override
public void destroy() {
log.info("XssFilter destroy");
}
}
|
HttpServletRequest request = (HttpServletRequest) servletRequest;
XssHttpServletRequestWrapper xssHttpServletRequestWrapper = new XssHttpServletRequestWrapper(request);
filterChain.doFilter(xssHttpServletRequestWrapper, servletResponse);
| 119 | 63 | 182 | 19,695 |
javaparser_javaparser
|
javaparser/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typesolvers/ClassLoaderTypeSolver.java
|
ClassLoaderTypeSolver
|
tryToSolveType
|
class ClassLoaderTypeSolver implements TypeSolver {
private TypeSolver parent;
private ClassLoader classLoader;
public ClassLoaderTypeSolver(ClassLoader classLoader) {
this.classLoader = classLoader;
}
@Override
public TypeSolver getParent() {
return parent;
}
@Override
public void setParent(TypeSolver parent) {
Objects.requireNonNull(parent);
if (this.parent != null) {
throw new IllegalStateException("This TypeSolver already has a parent.");
}
if (parent == this) {
throw new IllegalStateException("The parent of this TypeSolver cannot be itself.");
}
this.parent = parent;
}
protected boolean filterName(String name) {
return true;
}
@Override
public SymbolReference<ResolvedReferenceTypeDeclaration> tryToSolveType(String name) {<FILL_FUNCTION_BODY>}
}
|
if (filterName(name)) {
try {
// Some implementations could return null when the class was loaded through the bootstrap classloader
// see https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#getClassLoader--
if (classLoader == null) {
throw new RuntimeException(
"The ClassLoaderTypeSolver has been probably loaded through the bootstrap class loader. This usage is not supported by the JavaSymbolSolver");
}
Class<?> clazz = classLoader.loadClass(name);
return SymbolReference.solved(ReflectionFactory.typeDeclarationFor(clazz, getRoot()));
} catch (NoClassDefFoundError e) {
// We can safely ignore this one because it is triggered when there are package names which are almost the
// same as class name, with the exclusion of the case.
// For example:
// java.lang.NoClassDefFoundError: com/github/javaparser/printer/ConcreteSyntaxModel
// (wrong name: com/github/javaparser/printer/concretesyntaxmodel)
// note that this exception seems to be thrown only on certain platform (mac yes, linux no)
return SymbolReference.unsolved();
} catch (ClassNotFoundException e) {
// it could be an inner class
int lastDot = name.lastIndexOf('.');
if (lastDot == -1) {
return SymbolReference.unsolved();
}
String parentName = name.substring(0, lastDot);
String childName = name.substring(lastDot + 1);
SymbolReference<ResolvedReferenceTypeDeclaration> parent = tryToSolveType(parentName);
if (parent.isSolved()) {
Optional<ResolvedReferenceTypeDeclaration> innerClass = parent.getCorrespondingDeclaration()
.internalTypes()
.stream().filter(it -> it.getName().equals(childName)).findFirst();
return innerClass.map(SymbolReference::solved)
.orElseGet(() -> SymbolReference.unsolved());
}
return SymbolReference.unsolved();
}
} else {
return SymbolReference.unsolved();
}
| 246 | 545 | 791 | 24,655 |
jwtk_jjwt
|
jjwt/impl/src/main/java/io/jsonwebtoken/impl/io/TeeOutputStream.java
|
TeeOutputStream
|
write
|
class TeeOutputStream extends FilteredOutputStream {
private final OutputStream other;
public TeeOutputStream(OutputStream one, OutputStream two) {
super(one);
this.other = Assert.notNull(two, "Second OutputStream cannot be null.");
}
@Override
public void close() throws IOException {
try {
super.close();
} finally {
this.other.close();
}
}
@Override
public void flush() throws IOException {
super.flush();
this.other.flush();
}
@Override
public void write(byte[] bts) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public void write(byte[] bts, int st, int end) throws IOException {
super.write(bts, st, end);
this.other.write(bts, st, end);
}
@Override
public void write(int idx) throws IOException {
super.write(idx);
this.other.write(idx);
}
}
|
super.write(bts);
this.other.write(bts);
| 266 | 23 | 289 | 59,352 |
soot-oss_soot
|
soot/src/main/java/soot/dexpler/typing/Validate.java
|
Validate
|
validateArrays
|
class Validate {
public static void validateArrays(Body b) {<FILL_FUNCTION_BODY>}
public static SootMethodRef makeMethodRef(String cName, String mName, String rType, List<String> pTypes,
boolean isStatic) {
SootClass sc = SootResolver.v().makeClassRef(cName);
Type returnType = null;
if (rType == "") {
returnType = VoidType.v();
} else {
returnType = RefType.v(rType);
}
List<Type> parameterTypes = new ArrayList<Type>();
for (String p : pTypes) {
parameterTypes.add(RefType.v(p));
}
return Scene.v().makeMethodRef(sc, mName, parameterTypes, returnType, isStatic);
}
}
|
Set<DefinitionStmt> definitions = new HashSet<DefinitionStmt>();
Set<Unit> unitWithArrayRef = new HashSet<Unit>();
for (Unit u : b.getUnits()) {
if (u instanceof DefinitionStmt) {
DefinitionStmt s = (DefinitionStmt) u;
definitions.add(s);
}
List<ValueBox> uses = u.getUseBoxes();
for (ValueBox vb : uses) {
Value v = vb.getValue();
if (v instanceof ArrayRef) {
unitWithArrayRef.add(u);
}
}
}
final LocalDefs localDefs = G.v().soot_toolkits_scalar_LocalDefsFactory().newLocalDefs(b, true);
Set<Unit> toReplace = new HashSet<Unit>();
for (Unit u : unitWithArrayRef) {
boolean ok = false;
List<ValueBox> uses = u.getUseBoxes();
for (ValueBox vb : uses) {
Value v = vb.getValue();
if (v instanceof ArrayRef) {
ArrayRef ar = (ArrayRef) v;
Local base = (Local) ar.getBase();
List<Unit> defs = localDefs.getDefsOfAt(base, u);
// add aliases
Set<Unit> alreadyHandled = new HashSet<Unit>();
while (true) {
boolean isMore = false;
for (Unit d : defs) {
if (alreadyHandled.contains(d)) {
continue;
}
if (d instanceof AssignStmt) {
AssignStmt ass = (AssignStmt) d;
Value r = ass.getRightOp();
if (r instanceof Local) {
defs.addAll(localDefs.getDefsOfAt((Local) r, d));
alreadyHandled.add(d);
isMore = true;
break;
} else if (r instanceof ArrayRef) {
ArrayRef arrayRef = (ArrayRef) r;
Local l = (Local) arrayRef.getBase();
defs.addAll(localDefs.getDefsOfAt(l, d));
alreadyHandled.add(d);
isMore = true;
break;
}
}
}
if (!isMore) {
break;
}
}
// System.out.println("def size "+ defs.size());
for (Unit def : defs) {
// System.out.println("def u "+ def);
Value r = null;
if (def instanceof IdentityStmt) {
IdentityStmt idstmt = (IdentityStmt) def;
r = idstmt.getRightOp();
} else if (def instanceof AssignStmt) {
AssignStmt assStmt = (AssignStmt) def;
r = assStmt.getRightOp();
} else {
throw new RuntimeException("error: definition statement not an IdentityStmt nor an AssignStmt! " + def);
}
Type t = null;
if (r instanceof InvokeExpr) {
InvokeExpr ie = (InvokeExpr) r;
t = ie.getType();
// System.out.println("ie type: "+ t +" "+ t.getClass());
if (t instanceof ArrayType) {
ok = true;
}
} else if (r instanceof FieldRef) {
FieldRef ref = (FieldRef) r;
t = ref.getType();
// System.out.println("fr type: "+ t +" "+ t.getClass());
if (t instanceof ArrayType) {
ok = true;
}
} else if (r instanceof IdentityRef) {
IdentityRef ir = (IdentityRef) r;
t = ir.getType();
if (t instanceof ArrayType) {
ok = true;
}
} else if (r instanceof CastExpr) {
CastExpr c = (CastExpr) r;
t = c.getType();
if (t instanceof ArrayType) {
ok = true;
}
} else if (r instanceof ArrayRef) {
// we also check that this arrayref is correctly defined
} else if (r instanceof NewArrayExpr) {
ok = true;
} else if (r instanceof Local) {
} else if (r instanceof Constant) {
} else {
throw new RuntimeException("error: unknown right hand side of definition stmt " + def);
}
if (ok) {
break;
}
}
if (ok) {
break;
}
}
}
if (!ok) {
toReplace.add(u);
}
}
int i = 0;
for (Unit u : toReplace) {
System.out.println("warning: incorrect array def, replacing unit " + u);
// new object
RefType throwableType = RefType.v("java.lang.Throwable");
Local ttt = Jimple.v().newLocal("ttt_" + ++i, throwableType);
b.getLocals().add(ttt);
Value r = Jimple.v().newNewExpr(throwableType);
Unit initLocalUnit = Jimple.v().newAssignStmt(ttt, r);
// call <init> method with a string parameter for message
List<String> pTypes = new ArrayList<String>();
pTypes.add("java.lang.String");
boolean isStatic = false;
SootMethodRef mRef = Validate.makeMethodRef("java.lang.Throwable", "<init>", "", pTypes, isStatic);
List<Value> parameters = new ArrayList<Value>();
parameters.add(StringConstant.v("Soot updated this instruction"));
InvokeExpr ie = Jimple.v().newSpecialInvokeExpr(ttt, mRef, parameters);
Unit initMethod = Jimple.v().newInvokeStmt(ie);
// throw exception
Unit newUnit = Jimple.v().newThrowStmt(ttt);
// change instruction in body
b.getUnits().swapWith(u, newUnit);
b.getUnits().insertBefore(initMethod, newUnit);
b.getUnits().insertBefore(initLocalUnit, initMethod);
// Exception a = throw new Exception();
}
DeadAssignmentEliminator.v().transform(b);
UnusedLocalEliminator.v().transform(b);
NopEliminator.v().transform(b);
UnreachableCodeEliminator.v().transform(b);
| 214 | 1,670 | 1,884 | 41,962 |
sqshq_piggymetrics
|
piggymetrics/statistics-service/src/main/java/com/piggymetrics/statistics/domain/timeseries/DataPointId.java
|
DataPointId
|
toString
|
class DataPointId implements Serializable {
private static final long serialVersionUID = 1L;
private String account;
private Date date;
public DataPointId(String account, Date date) {
this.account = account;
this.date = date;
}
public String getAccount() {
return account;
}
public Date getDate() {
return date;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "DataPointId{" +
"account='" + account + '\'' +
", date=" + date +
'}';
| 121 | 39 | 160 | 3,851 |
INRIA_spoon
|
spoon/src/main/java/spoon/support/util/RtHelper.java
|
RtHelper
|
getModifiers
|
class RtHelper {
private RtHelper() {
}
/**
* Gets all the runtime fields for a given class (including the
* superclasses and superinterfaces).
*/
public static Field[] getAllFields(Class<?> c) {
List<Field> fields = new ArrayList<>();
addAllFields(c, fields);
Field[] result = new Field[fields.size()];
return fields.toArray(result);
}
private static void addAllFields(Class<?> c, List<Field> fields) {
if (c != null && c != Object.class) {
Collections.addAll(fields, c.getDeclaredFields());
addAllFields(c.getSuperclass(), fields);
for (Class<?> iface : c.getInterfaces()) {
addAllFields(iface, fields);
}
}
}
/**
* Gets all the field references for a given class (including the
* superclasses').
*/
public static Collection<CtFieldReference<?>> getAllFields(Class<?> c, Factory factory) {
Collection<CtFieldReference<?>> l = new ArrayList<>();
for (Field f : getAllFields(c)) {
l.add(factory.Field().createReference(f));
}
return l;
}
/**
* Gets all the runtime methods for a given class or interface (including
* the superclasses' or interfaces').
*/
public static Method[] getAllMethods(Class<?> c) {
List<Method> methods = new ArrayList<>();
if (c.isInterface()) {
getAllIMethods(c, methods);
} else {
while (c != null && c != Object.class) {
Collections.addAll(methods, c.getDeclaredMethods());
c = c.getSuperclass();
}
}
Method[] result = new Method[methods.size()];
return methods.toArray(result);
}
private static void getAllIMethods(Class<?> c, List<Method> methods) {
Collections.addAll(methods, c.getDeclaredMethods());
for (Class<?> i : c.getInterfaces()) {
getAllIMethods(i, methods);
}
}
/**
* Actually invokes from a compile-time invocation (by using runtime
* reflection).
*/
@SuppressWarnings("unchecked")
public static <T> T invoke(CtInvocation<T> i)
throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
Object target = i.getTarget() == null ? null : ((CtLiteral<?>) i.getTarget()).getValue();
List<Object> args = new ArrayList<>();
for (CtExpression<?> e : i.getArguments()) {
args.add(((CtLiteral<?>) e).getValue());
}
Class<?> c = i.getExecutable().getDeclaringType().getActualClass();
ArrayList<Class<?>> argTypes = new ArrayList<>();
for (CtTypeReference<?> type : i.getExecutable().getActualTypeArguments()) {
argTypes.add(type.getActualClass());
}
return (T) c.getMethod(i.getExecutable().getSimpleName(), argTypes.toArray(new Class[0]))
.invoke(target, args.toArray());
}
/**
* Return the set of modifiers defined by the modifiers integer
* (java.lang.reflect).
*/
public static Set<ModifierKind> getModifiers(int mod) {<FILL_FUNCTION_BODY>}
/**
* return all executables of this class
*/
public static Collection<CtExecutableReference<?>> getAllExecutables(Class<?> clazz, Factory factory) {
Collection<CtExecutableReference<?>> l = new ArrayList<>();
for (Method m : clazz.getDeclaredMethods()) {
l.add(factory.Method().createReference(m));
}
for (Constructor<?> c : clazz.getDeclaredConstructors()) {
l.add(factory.Constructor().createReference(c));
}
return l;
}
/**
* Looks for first public method of clazz (or any super class or super interface),
* whose name is equal to methodName and number of parameters is numParams
* @param clazz
* @param methodName
* @param numParams
* @return the found method or null
*/
public static @Nullable Method getMethod(Class<?> clazz, String methodName, int numParams) {
Method[] methods = clazz.getMethods();
for (Method method : methods) {
if (!method.isSynthetic() && method.getName().equals(methodName)) {
Class<?>[] params = method.getParameterTypes();
if (params.length == numParams) {
return method;
}
}
}
return null;
}
}
|
Set<ModifierKind> set = new HashSet<>();
if (Modifier.isAbstract(mod)) {
set.add(ModifierKind.ABSTRACT);
}
if (Modifier.isFinal(mod)) {
set.add(ModifierKind.FINAL);
}
if (Modifier.isNative(mod)) {
set.add(ModifierKind.NATIVE);
}
if (Modifier.isPrivate(mod)) {
set.add(ModifierKind.PRIVATE);
}
if (Modifier.isProtected(mod)) {
set.add(ModifierKind.PROTECTED);
}
if (Modifier.isPublic(mod)) {
set.add(ModifierKind.PUBLIC);
}
if (Modifier.isStatic(mod)) {
set.add(ModifierKind.STATIC);
}
if (Modifier.isStrict(mod)) {
set.add(ModifierKind.STRICTFP);
}
if (Modifier.isSynchronized(mod)) {
set.add(ModifierKind.SYNCHRONIZED);
}
if (Modifier.isTransient(mod)) {
set.add(ModifierKind.TRANSIENT);
}
if (Modifier.isVolatile(mod)) {
set.add(ModifierKind.VOLATILE);
}
return set;
| 1,265 | 379 | 1,644 | 58,138 |
jwtk_jjwt
|
jjwt/impl/src/main/java/io/jsonwebtoken/impl/security/FieldElementConverter.java
|
FieldElementConverter
|
applyTo
|
class FieldElementConverter implements Converter<BigInteger, byte[]> {
static final FieldElementConverter INSTANCE = new FieldElementConverter();
static final Converter<BigInteger, Object> B64URL_CONVERTER = Converters.forEncoded(BigInteger.class,
Converters.compound(INSTANCE, Codec.BASE64URL));
private static int bytelen(ECCurve curve) {
return Bytes.length(curve.toParameterSpec().getCurve().getField().getFieldSize());
}
private static final int P256_BYTE_LEN = bytelen(ECCurve.P256);
private static final int P384_BYTE_LEN = bytelen(ECCurve.P384);
private static final int P521_BYTE_LEN = bytelen(ECCurve.P521);
@Override
public byte[] applyTo(BigInteger bigInteger) {<FILL_FUNCTION_BODY>}
@Override
public BigInteger applyFrom(byte[] bytes) {
return Converters.BIGINT_UBYTES.applyFrom(bytes);
}
}
|
byte[] bytes = Converters.BIGINT_UBYTES.applyTo(bigInteger);
int len = bytes.length;
if (len == P256_BYTE_LEN || len == P384_BYTE_LEN || len == P521_BYTE_LEN) return bytes;
if (len < P256_BYTE_LEN) {
bytes = Bytes.prepad(bytes, P256_BYTE_LEN);
} else if (len < P384_BYTE_LEN) {
bytes = Bytes.prepad(bytes, P384_BYTE_LEN);
} else { // > P-384, so must be P-521:
bytes = Bytes.prepad(bytes, P521_BYTE_LEN);
}
return bytes;
| 306 | 220 | 526 | 59,456 |
killme2008_aviatorscript
|
aviatorscript/src/main/java/com/googlecode/aviator/runtime/function/seq/AbstractSeqMinMaxFunction.java
|
AbstractSeqMinMaxFunction
|
compare
|
class AbstractSeqMinMaxFunction extends AbstractFunction {
private static final long serialVersionUID = 1236238221132010289L;
static enum Op {
Min, Max
}
@SuppressWarnings("rawtypes")
@Override
public AviatorObject call(final Map<String, Object> env, final AviatorObject arg1) {
Object first = arg1.getValue(env);
if (first == null) {
return AviatorNil.NIL;
}
Sequence seq = RuntimeUtils.seq(first, env);
boolean wasFirst = true;
Object result = null;
for (Object obj : seq) {
result = compareObjects(result, obj, wasFirst);
if (wasFirst) {
wasFirst = false;
}
if (getOp() == Op.Min && result == null) {
break;
}
}
return AviatorRuntimeJavaType.valueOf(result);
}
protected abstract Op getOp();
private Object compareObjects(Object result, final Object obj, final boolean wasFirst) {
if (obj == null) {
switch (getOp()) {
case Min:
return obj;
case Max:
return result;
}
}
if (!(obj instanceof Comparable)) {
throw new CompareNotSupportedException(
"Element in sequence doesn't implement java.lang.Comparable.");
}
if (wasFirst || compare(result, obj)) {
result = obj;
}
return result;
}
@SuppressWarnings({"unchecked", "rawtypes"})
private boolean compare(final Object result, final Object obj) {<FILL_FUNCTION_BODY>}
}
|
try {
int c = ((Comparable) obj).compareTo(result);
switch (getOp()) {
case Min:
return c < 0;
case Max:
return c > 0;
}
return false;
} catch (ClassCastException e) {
throw new CompareNotSupportedException(
"Could not compare `" + obj + "` with `" + result + "`", e);
}
| 462 | 112 | 574 | 27,379 |
igniterealtime_Openfire
|
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/muc/ConflictException.java
|
ConflictException
|
printStackTrace
|
class ConflictException extends Exception {
private static final long serialVersionUID = 1L;
private Throwable nestedThrowable = null;
public ConflictException() {
super();
}
public ConflictException(String msg) {
super(msg);
}
public ConflictException(Throwable nestedThrowable) {
this.nestedThrowable = nestedThrowable;
}
public ConflictException(String msg, Throwable nestedThrowable) {
super(msg);
this.nestedThrowable = nestedThrowable;
}
@Override
public void printStackTrace() {
super.printStackTrace();
if (nestedThrowable != null) {
nestedThrowable.printStackTrace();
}
}
@Override
public void printStackTrace(PrintStream ps) {
super.printStackTrace(ps);
if (nestedThrowable != null) {
nestedThrowable.printStackTrace(ps);
}
}
@Override
public void printStackTrace(PrintWriter pw) {<FILL_FUNCTION_BODY>}
}
|
super.printStackTrace(pw);
if (nestedThrowable != null) {
nestedThrowable.printStackTrace(pw);
}
| 287 | 43 | 330 | 23,247 |
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-proxy-plugin/src/main/java/org/hotswap/agent/plugin/proxy/RedefinitionScheduler.java
|
RedefinitionScheduler
|
schedule
|
class RedefinitionScheduler implements Runnable {
private MultistepProxyTransformer transformer;
@Init
private static Instrumentation instrumentation;
public RedefinitionScheduler(MultistepProxyTransformer transformer) {
this.transformer = transformer;
}
@Override
public void run() {
try {
instrumentation.redefineClasses(new ClassDefinition(transformer.getClassBeingRedefined(), transformer
.getClassfileBuffer()));
} catch (Throwable t) {
transformer.removeClassState();
throw new RuntimeException(t);
}
}
public static void schedule(MultistepProxyTransformer multistepProxyTransformer) {<FILL_FUNCTION_BODY>}
}
|
new Thread(new RedefinitionScheduler(multistepProxyTransformer)).start();
| 187 | 24 | 211 | 22,463 |
macrozheng_mall-swarm
|
mall-swarm/mall-mbg/src/main/java/com/macro/mall/model/PmsProductAttribute.java
|
PmsProductAttribute
|
setInputList
|
class PmsProductAttribute implements Serializable {
private Long id;
private Long productAttributeCategoryId;
private String name;
@ApiModelProperty(value = "属性选择类型:0->唯一;1->单选;2->多选")
private Integer selectType;
@ApiModelProperty(value = "属性录入方式:0->手工录入;1->从列表中选取")
private Integer inputType;
@ApiModelProperty(value = "可选值列表,以逗号隔开")
private String inputList;
@ApiModelProperty(value = "排序字段:最高的可以单独上传图片")
private Integer sort;
@ApiModelProperty(value = "分类筛选样式:1->普通;1->颜色")
private Integer filterType;
@ApiModelProperty(value = "检索类型;0->不需要进行检索;1->关键字检索;2->范围检索")
private Integer searchType;
@ApiModelProperty(value = "相同属性产品是否关联;0->不关联;1->关联")
private Integer relatedStatus;
@ApiModelProperty(value = "是否支持手动新增;0->不支持;1->支持")
private Integer handAddStatus;
@ApiModelProperty(value = "属性的类型;0->规格;1->参数")
private Integer type;
private static final long serialVersionUID = 1L;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getProductAttributeCategoryId() {
return productAttributeCategoryId;
}
public void setProductAttributeCategoryId(Long productAttributeCategoryId) {
this.productAttributeCategoryId = productAttributeCategoryId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getSelectType() {
return selectType;
}
public void setSelectType(Integer selectType) {
this.selectType = selectType;
}
public Integer getInputType() {
return inputType;
}
public void setInputType(Integer inputType) {
this.inputType = inputType;
}
public String getInputList() {
return inputList;
}
public void setInputList(String inputList) {<FILL_FUNCTION_BODY>}
public Integer getSort() {
return sort;
}
public void setSort(Integer sort) {
this.sort = sort;
}
public Integer getFilterType() {
return filterType;
}
public void setFilterType(Integer filterType) {
this.filterType = filterType;
}
public Integer getSearchType() {
return searchType;
}
public void setSearchType(Integer searchType) {
this.searchType = searchType;
}
public Integer getRelatedStatus() {
return relatedStatus;
}
public void setRelatedStatus(Integer relatedStatus) {
this.relatedStatus = relatedStatus;
}
public Integer getHandAddStatus() {
return handAddStatus;
}
public void setHandAddStatus(Integer handAddStatus) {
this.handAddStatus = handAddStatus;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", productAttributeCategoryId=").append(productAttributeCategoryId);
sb.append(", name=").append(name);
sb.append(", selectType=").append(selectType);
sb.append(", inputType=").append(inputType);
sb.append(", inputList=").append(inputList);
sb.append(", sort=").append(sort);
sb.append(", filterType=").append(filterType);
sb.append(", searchType=").append(searchType);
sb.append(", relatedStatus=").append(relatedStatus);
sb.append(", handAddStatus=").append(handAddStatus);
sb.append(", type=").append(type);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}
|
this.inputList = inputList;
| 1,214 | 13 | 1,227 | 2,871 |
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/dynamic/output/CommandOutputResolverSupport.java
|
CommandOutputResolverSupport
|
isAssignableFrom
|
class CommandOutputResolverSupport {
/**
* Overridable hook to check whether {@code selector} can be assigned from the provider type {@code provider}.
* <p>
* This method descends the component type hierarchy and considers primitive/wrapper type conversion.
*
* @param selector must not be {@code null}.
* @param provider must not be {@code null}.
* @return {@code true} if selector can be assigned from its provider type.
*/
protected boolean isAssignableFrom(OutputSelector selector, OutputType provider) {<FILL_FUNCTION_BODY>}
}
|
ResolvableType selectorType = selector.getOutputType();
ResolvableType resolvableType = provider.withCodec(selector.getRedisCodec());
return selectorType.isAssignableFrom(resolvableType);
| 146 | 60 | 206 | 39,342 |
Red5_red5-server
|
red5-server/io/src/main/java/org/red5/compatibility/flex/messaging/messages/AcknowledgeMessageExt.java
|
AcknowledgeMessageExt
|
setMessage
|
class AcknowledgeMessageExt extends AcknowledgeMessage implements IExternalizable {
private static final long serialVersionUID = -8764729006642310394L;
private AcknowledgeMessage message;
public AcknowledgeMessageExt() {
}
public AcknowledgeMessageExt(AcknowledgeMessage message) {
this.setMessage(message);
}
public void setMessage(AcknowledgeMessage message) {<FILL_FUNCTION_BODY>}
public AcknowledgeMessage getMessage() {
return message;
}
@Override
public void writeExternal(IDataOutput output) {
if (this.message != null) {
this.message.writeExternal(output);
} else {
super.writeExternal(output);
}
}
}
|
this.message = message;
| 214 | 11 | 225 | 62,188 |
infinilabs_analysis-ik
|
analysis-ik/elasticsearch/src/main/java/com/infinilabs/ik/elasticsearch/ConfigurationSub.java
|
ConfigurationSub
|
getConfDir
|
class ConfigurationSub extends Configuration {
private Environment environment;
public ConfigurationSub(Environment env,Settings settings) {
this.environment = env;
this.useSmart = settings.get("use_smart", "false").equals("true");
this.enableLowercase = settings.get("enable_lowercase", "true").equals("true");
this.enableRemoteDict = settings.get("enable_remote_dict", "true").equals("true");
Dictionary.initial(this);
}
@Override
public Path getConfDir() {<FILL_FUNCTION_BODY>}
public Path getConfigInPluginDir() {
return PathUtils
.get(new File(AnalysisIkPlugin.class.getProtectionDomain().getCodeSource().getLocation().getPath())
.getParent(), "config")
.toAbsolutePath();
}
public boolean isUseSmart() {
return useSmart;
}
public Configuration setUseSmart(boolean useSmart) {
this.useSmart = useSmart;
return this;
}
public boolean isEnableRemoteDict() {
return enableRemoteDict;
}
public boolean isEnableLowercase() {
return enableLowercase;
}
public Path getPath(String first, String... more) {
return PathUtils.get(first, more);
}
public void check(){
SpecialPermission.check();
}
}
|
return this.environment.configFile().resolve(AnalysisIkPlugin.PLUGIN_NAME);
| 402 | 28 | 430 | 57,761 |
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/change/NormalizingStreamV8.java
|
NormalizingStreamV8
|
read
|
class NormalizingStreamV8 extends InputStream {
private ByteArrayInputStream headerStream;
private PushbackInputStream stream;
private byte[] quickBuffer = new byte[100];
private List<Byte> resizingBuffer = new ArrayList<>();
private int lastChar = 'X';
private boolean seenNonSpace;
@Deprecated
public NormalizingStreamV8(String endDelimiter, Boolean splitStatements, Boolean stripComments, InputStream stream) {
this.stream = new PushbackInputStream(stream, 2048);
try {
this.headerStream = new ByteArrayInputStream((endDelimiter+":"+splitStatements+":"+stripComments+":").getBytes(GlobalConfiguration.OUTPUT_FILE_ENCODING.getCurrentValue()));
} catch (UnsupportedEncodingException e) {
throw new UnexpectedLiquibaseException(e);
}
}
@Override
public int read() throws IOException {<FILL_FUNCTION_BODY>}
@Override
public int available() throws IOException {
return stream.available();
}
@Override
public boolean markSupported() {
return stream.markSupported();
}
@Override
public synchronized void mark(int readLimit) {
stream.mark(readLimit);
}
@Override
public synchronized void reset() throws IOException {
stream.reset();
}
private boolean isOnlyWhitespaceRemaining() throws IOException {
try {
int quickBufferUsed = 0;
while (true) {
byte read = (byte) stream.read();
if (quickBufferUsed >= quickBuffer.length) {
resizingBuffer.add(read);
} else {
quickBuffer[quickBufferUsed++] = read;
}
if (read == -1) {
return true;
}
if (!isWhiteSpace(read)) {
if (!resizingBuffer.isEmpty()) {
byte[] buf = new byte[resizingBuffer.size()];
for (int i=0; i< resizingBuffer.size(); i++) {
buf[i] = resizingBuffer.get(i);
}
stream.unread(buf);
}
stream.unread(quickBuffer, 0, quickBufferUsed);
return false;
}
}
} finally {
resizingBuffer.clear();
}
}
private boolean isWhiteSpace(int read) {
return (read == ' ') || (read == '\n') || (read == '\r') || (read == '\t');
}
@Override
public void close() throws IOException {
stream.close();
}
}
|
if (headerStream != null) {
int returnChar = headerStream.read();
if (returnChar != -1) {
return returnChar;
}
headerStream = null;
}
int returnChar = stream.read();
if (isWhiteSpace(returnChar)) {
returnChar = ' ';
}
while ((returnChar == ' ') && (!seenNonSpace || (lastChar == ' '))) {
returnChar = stream.read();
if (isWhiteSpace(returnChar)) {
returnChar = ' ';
}
}
seenNonSpace = true;
lastChar = returnChar;
if ((lastChar == ' ') && isOnlyWhitespaceRemaining()) {
return -1;
}
return returnChar;
| 670 | 206 | 876 | 30,620 |
gz-yami_mall4cloud
|
mall4cloud/mall4cloud-search/src/main/java/com/mall4j/cloud/search/bo/SpuBO.java
|
SpuBO
|
setMarketPriceFee
|
class SpuBO {
/**
* spu id
*/
private Long spuId;
/**
* 品牌ID
*/
private Long brandId;
/**
* 分类ID
*/
private Long categoryId;
/**
* 店铺id
*/
private Long shopId;
/**
* spu名称
*/
private String name;
/**
* 卖点
*/
private String sellingPoint;
/**
* 主图
*/
private String mainImgUrl;
/**
* 商品图片 多个图片逗号分隔
*/
private String imgUrls;
/**
* 商品视频
*/
private String video;
/**
* 售价,整数方式保存
*/
private Long priceFee;
/**
* 市场价,整数方式保存
*/
private Long marketPriceFee;
/**
* 状态 1:enable, 0:disable, -1:deleted
*/
private Integer status;
private Integer hasSkuImg;
/**
* 序号
*/
private Integer seq;
public Long getSpuId() {
return spuId;
}
public void setSpuId(Long spuId) {
this.spuId = spuId;
}
public Long getBrandId() {
return brandId;
}
public void setBrandId(Long brandId) {
this.brandId = brandId;
}
public Long getCategoryId() {
return categoryId;
}
public void setCategoryId(Long categoryId) {
this.categoryId = categoryId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSellingPoint() {
return sellingPoint;
}
public void setSellingPoint(String sellingPoint) {
this.sellingPoint = sellingPoint;
}
public String getImgUrls() {
return imgUrls;
}
public void setImgUrls(String imgUrls) {
this.imgUrls = imgUrls;
}
public String getVideo() {
return video;
}
public void setVideo(String video) {
this.video = video;
}
public Long getPriceFee() {
return priceFee;
}
public void setPriceFee(Long priceFee) {
this.priceFee = priceFee;
}
public Long getMarketPriceFee() {
return marketPriceFee;
}
public void setMarketPriceFee(Long marketPriceFee) {<FILL_FUNCTION_BODY>}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getMainImgUrl() {
return mainImgUrl;
}
public void setMainImgUrl(String mainImgUrl) {
this.mainImgUrl = mainImgUrl;
}
public Integer getHasSkuImg() {
return hasSkuImg;
}
public void setHasSkuImg(Integer hasSkuImg) {
this.hasSkuImg = hasSkuImg;
}
public Long getShopId() {
return shopId;
}
public void setShopId(Long shopId) {
this.shopId = shopId;
}
public Integer getSeq() {
return seq;
}
public void setSeq(Integer seq) {
this.seq = seq;
}
@Override
public String toString() {
return "SpuBO{" +
"spuId=" + spuId +
", brandId=" + brandId +
", categoryId=" + categoryId +
", shopId=" + shopId +
", name='" + name + '\'' +
", sellingPoint='" + sellingPoint + '\'' +
", mainImgUrl='" + mainImgUrl + '\'' +
", imgUrls='" + imgUrls + '\'' +
", video='" + video + '\'' +
", priceFee=" + priceFee +
", marketPriceFee=" + marketPriceFee +
", status=" + status +
", hasSkuImg=" + hasSkuImg +
", seq=" + seq +
'}';
}
}
|
this.marketPriceFee = marketPriceFee;
| 1,219 | 17 | 1,236 | 21,822 |
WuKongOpenSource_Wukong_HRM
|
Wukong_HRM/hrm/hrm-web/src/main/java/com/kakarote/hrm/entity/VO/FixSalaryRecordDetailVO.java
|
FixSalaryRecordDetailVO
|
toString
|
class FixSalaryRecordDetailVO extends SalaryRecordHeadVO {
private Long id;
@ApiModelProperty(value = "状态 0 未生效 1 已生效 2 已取消")
private Integer status;
@ApiModelProperty("备注")
private String remarks;
@ApiModelProperty(value = "调薪原因 0 入职定薪 1 入职核定 2 转正 3 晋升 4 调动 5 年中调薪 6 年度调薪 7 特别调薪 8 其他")
private Integer changeReason;
@ApiModelProperty("试用期工资")
private List<ChangeSalaryOptionVO> proSalary;
@ApiModelProperty("转正后工资")
private List<ChangeSalaryOptionVO> salary;
@ApiModelProperty("试用期总计")
private String proSum;
@ApiModelProperty("转正后总计")
private String sum;
@ApiModelProperty("是否可以更新")
private Boolean isUpdate;
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "FixSalaryRecordDetailVO{" +
"id=" + id +
", status=" + status +
", remarks='" + remarks + '\'' +
", changeReason=" + changeReason +
", proSalary=" + proSalary +
", salary=" + salary +
", proSum='" + proSum + '\'' +
", sum='" + sum + '\'' +
", isUpdate=" + isUpdate +
'}';
| 290 | 120 | 410 | 64,485 |
speedment_speedment
|
speedment/runtime-parent/runtime-typemapper/src/main/java/com/speedment/runtime/typemapper/integer/PrimitiveIntegerZeroOneToBooleanMapper.java
|
PrimitiveIntegerZeroOneToBooleanMapper
|
toDatabaseType
|
class PrimitiveIntegerZeroOneToBooleanMapper
implements TypeMapper<Integer, Boolean> {
@Override
public String getLabel() {
return "Integer (0|1) to boolean (primitive)";
}
@Override
public Type getJavaType(Column column) {
return boolean.class;
}
@Override
public Boolean toJavaType(Column column, Class<?> entityType, Integer value) {
return value == null ? null : value != 0;
}
@Override
public Integer toDatabaseType(Boolean value) {<FILL_FUNCTION_BODY>}
@Override
public Ordering getOrdering() {
return Ordering.RETAIN;
}
}
|
if (value == null) {
return null;
} else {
return value ? 1 : 0;
}
| 185 | 36 | 221 | 42,862 |
apache_shenyu
|
shenyu/shenyu-plugin/shenyu-plugin-logging/shenyu-plugin-logging-desensitize-api/src/main/java/org/apache/shenyu/plugin/logging/desensitize/api/utils/DataDesensitizeUtils.java
|
DataDesensitizeUtils
|
desensitizeList
|
class DataDesensitizeUtils {
/**
* desensitize for single key word.
*
* @param keyWord key word
* @param source source data
* @param keyWordMatch keyWordMatch
* @param desensitizeAlg desensitizeAlg
* @return desensitized data
*/
public static String desensitizeForSingleWord(final String keyWord, final String source,
final KeyWordMatch keyWordMatch, final String desensitizeAlg) {
return DataDesensitizeUtils.desensitizeSingleKeyword(true, keyWord, source, keyWordMatch, desensitizeAlg);
}
/**
* desensitize for body.
*
* @param source source data.
* @param keyWordMatch keyWordMatch
* @param desensitizeAlg desensitizeAlg
* @return desensitized data.
*/
public static String desensitizeForBody(final String source, final KeyWordMatch keyWordMatch, final String desensitizeAlg) {
return DataDesensitizeUtils.desensitizeBody(true, source, keyWordMatch, desensitizeAlg);
}
/**
* desensitize single keyword.
*
* @param desensitized desensitized flag
* @param keyWord keyword
* @param source source data
* @param keyWordMatch keyWordMatch
* @param desensitizedAlg desensitized algorithm
* @return desensitized data
*/
public static String desensitizeSingleKeyword(final boolean desensitized, final String keyWord, final String source,
final KeyWordMatch keyWordMatch, final String desensitizedAlg) {
if (StringUtils.hasLength(source) && desensitized && keyWordMatch.matches(keyWord)) {
return DataDesensitizeFactory.selectDesensitize(source, desensitizedAlg);
} else {
return source;
}
}
/**
* mask for body.
*
* @param desensitized desensitized flag
* @param source source data
* @param keyWordMatch keyword match strategy
* @param dataDesensitizeAlg desensitize algorithm
* @return desensitized data
*/
public static String desensitizeBody(final boolean desensitized, final String source,
final KeyWordMatch keyWordMatch, final String dataDesensitizeAlg) {
if (StringUtils.hasLength(source) && desensitized) {
Map<String, String> bodyMap = JsonUtils.jsonToMap(source, String.class);
bodyMap.forEach((key, value) -> {
if (keyWordMatch.matches(key)) {
bodyMap.put(key, DataDesensitizeFactory.selectDesensitize(value, dataDesensitizeAlg));
}
});
return JsonUtils.toJson(bodyMap);
} else {
return source;
}
}
/**
* desensitize for list data.
*
* @param desensitized desensitized
* @param keyword keyword
* @param source source data
* @param keyWordMatch keyword match strategy
* @param dataDesensitizeAlg desensitize algorithm
*/
public static void desensitizeList(final boolean desensitized, final String keyword, final List<String> source,
final KeyWordMatch keyWordMatch, final String dataDesensitizeAlg) {<FILL_FUNCTION_BODY>}
}
|
if (desensitized && keyWordMatch.matches(keyword)) {
for (int i = 0; i < source.size(); i++) {
String ret = DataDesensitizeFactory.selectDesensitize(source.get(i), dataDesensitizeAlg);
source.set(i, ret);
}
}
| 893 | 88 | 981 | 68,566 |
javaparser_javaparser
|
javaparser/javaparser-core/src/main/java/com/github/javaparser/ast/PackageDeclaration.java
|
PackageDeclaration
|
replace
|
class PackageDeclaration extends Node implements NodeWithAnnotations<PackageDeclaration>, NodeWithName<PackageDeclaration> {
private NodeList<AnnotationExpr> annotations = new NodeList<>();
private Name name;
public PackageDeclaration() {
this(null, new NodeList<>(), new Name());
}
public PackageDeclaration(Name name) {
this(null, new NodeList<>(), name);
}
@AllFieldsConstructor
public PackageDeclaration(NodeList<AnnotationExpr> annotations, Name name) {
this(null, annotations, name);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public PackageDeclaration(TokenRange tokenRange, NodeList<AnnotationExpr> annotations, Name name) {
super(tokenRange);
setAnnotations(annotations);
setName(name);
customInitialization();
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
return v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <A> void accept(final VoidVisitor<A> v, final A arg) {
v.visit(this, arg);
}
/**
* Retrieves the list of annotations declared before the package
* declaration. Return {@code null} if there are no annotations.
*
* @return list of annotations or {@code null}
*/
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public NodeList<AnnotationExpr> getAnnotations() {
return annotations;
}
/**
* Return the name expression of the package.
*
* @return the name of the package
*/
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Name getName() {
return name;
}
/**
* @param annotations the annotations to set
*/
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public PackageDeclaration setAnnotations(final NodeList<AnnotationExpr> annotations) {
assertNotNull(annotations);
if (annotations == this.annotations) {
return this;
}
notifyPropertyChange(ObservableProperty.ANNOTATIONS, this.annotations, annotations);
if (this.annotations != null)
this.annotations.setParentNode(null);
this.annotations = annotations;
setAsParentNodeOf(annotations);
return this;
}
/**
* Sets the name of this package declaration.
*
* @param name the name to set
*/
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public PackageDeclaration setName(final Name name) {
assertNotNull(name);
if (name == this.name) {
return this;
}
notifyPropertyChange(ObservableProperty.NAME, this.name, name);
if (this.name != null)
this.name.setParentNode(null);
this.name = name;
setAsParentNodeOf(name);
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.RemoveMethodGenerator")
public boolean remove(Node node) {
if (node == null) {
return false;
}
for (int i = 0; i < annotations.size(); i++) {
if (annotations.get(i) == node) {
annotations.remove(i);
return true;
}
}
return super.remove(node);
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public PackageDeclaration clone() {
return (PackageDeclaration) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public PackageDeclarationMetaModel getMetaModel() {
return JavaParserMetaModel.packageDeclarationMetaModel;
}
@Override
@Generated("com.github.javaparser.generator.core.node.ReplaceMethodGenerator")
public boolean replace(Node node, Node replacementNode) {<FILL_FUNCTION_BODY>}
}
|
if (node == null) {
return false;
}
for (int i = 0; i < annotations.size(); i++) {
if (annotations.get(i) == node) {
annotations.set(i, (AnnotationExpr) replacementNode);
return true;
}
}
if (node == name) {
setName((Name) replacementNode);
return true;
}
return super.replace(node, replacementNode);
| 1,164 | 121 | 1,285 | 24,269 |
apache_pdfbox
|
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/graphics/shading/AxialShadingPaint.java
|
AxialShadingPaint
|
createContext
|
class AxialShadingPaint extends ShadingPaint<PDShadingType2>
{
private static final Logger LOG = LogManager.getLogger(AxialShadingPaint.class);
/**
* Constructor.
*
* @param shadingType2 the shading resources
* @param matrix the pattern matrix concatenated with that of the parent content stream
*/
AxialShadingPaint(PDShadingType2 shadingType2, Matrix matrix)
{
super(shadingType2, matrix);
}
@Override
public int getTransparency()
{
return 0;
}
@Override
public PaintContext createContext(ColorModel cm, Rectangle deviceBounds, Rectangle2D userBounds,
AffineTransform xform, RenderingHints hints)
{<FILL_FUNCTION_BODY>}
}
|
try
{
return new AxialShadingContext(shading, cm, xform, matrix, deviceBounds);
}
catch (IOException e)
{
LOG.error("An error occurred while painting", e);
return new Color(0, 0, 0, 0).createContext(cm, deviceBounds, userBounds, xform, hints);
}
| 249 | 106 | 355 | 12,190 |
apache_dolphinscheduler
|
dolphinscheduler/dolphinscheduler-data-quality/src/main/java/org/apache/dolphinscheduler/data/quality/flow/batch/transformer/SqlTransformer.java
|
SqlTransformer
|
validateConfig
|
class SqlTransformer implements BatchTransformer {
private final Config config;
public SqlTransformer(Config config) {
this.config = config;
}
@Override
public Config getConfig() {
return config;
}
@Override
public ValidateResult validateConfig() {<FILL_FUNCTION_BODY>}
@Override
public void prepare(SparkRuntimeEnvironment prepareEnv) {
// Do nothing
}
@Override
public Dataset<Row> transform(Dataset<Row> data, SparkRuntimeEnvironment env) {
return env.sparkSession().sql(config.getString(SQL));
}
}
|
return validate(Collections.singletonList(SQL));
| 168 | 16 | 184 | 66,687 |
apache_incubator-seata
|
incubator-seata/seata-spring-boot-starter/src/main/java/org/apache/seata/spring/boot/autoconfigure/SeataAutoConfiguration.java
|
SeataAutoConfiguration
|
globalTransactionScanner
|
class SeataAutoConfiguration {
private static final Logger LOGGER = LoggerFactory.getLogger(SeataAutoConfiguration.class);
@Bean(BEAN_NAME_FAILURE_HANDLER)
@ConditionalOnMissingBean(FailureHandler.class)
public FailureHandler failureHandler() {
return new DefaultFailureHandlerImpl();
}
@Bean
@DependsOn({BEAN_NAME_SPRING_APPLICATION_CONTEXT_PROVIDER, BEAN_NAME_FAILURE_HANDLER})
@ConditionalOnMissingBean(GlobalTransactionScanner.class)
public static GlobalTransactionScanner globalTransactionScanner(SeataProperties seataProperties, FailureHandler failureHandler,
ConfigurableListableBeanFactory beanFactory,
@Autowired(required = false) List<ScannerChecker> scannerCheckers) {<FILL_FUNCTION_BODY>}
}
|
if (LOGGER.isInfoEnabled()) {
LOGGER.info("Automatically configure Seata");
}
// set bean factory
GlobalTransactionScanner.setBeanFactory(beanFactory);
// add checkers
// '/META-INF/services/org.apache.seata.spring.annotation.ScannerChecker'
GlobalTransactionScanner.addScannerCheckers(EnhancedServiceLoader.loadAll(ScannerChecker.class));
// spring beans
GlobalTransactionScanner.addScannerCheckers(scannerCheckers);
// add scannable packages
GlobalTransactionScanner.addScannablePackages(seataProperties.getScanPackages());
// add excludeBeanNames
GlobalTransactionScanner.addScannerExcludeBeanNames(seataProperties.getExcludesForScanning());
//set accessKey and secretKey
GlobalTransactionScanner.setAccessKey(seataProperties.getAccessKey());
GlobalTransactionScanner.setSecretKey(seataProperties.getSecretKey());
// create global transaction scanner
return new GlobalTransactionScanner(seataProperties.getApplicationId(), seataProperties.getTxServiceGroup(), failureHandler);
| 226 | 289 | 515 | 51,924 |
crate_crate
|
crate/plugins/es-analysis-common/src/main/java/org/elasticsearch/analysis/common/GreekAnalyzerProvider.java
|
GreekAnalyzerProvider
|
get
|
class GreekAnalyzerProvider extends AbstractIndexAnalyzerProvider<GreekAnalyzer> {
private final GreekAnalyzer analyzer;
GreekAnalyzerProvider(IndexSettings indexSettings, Environment env, String name, Settings settings) {
super(indexSettings, name, settings);
analyzer = new GreekAnalyzer(Analysis.parseStopWords(env, settings, GreekAnalyzer.getDefaultStopSet()));
}
@Override
public GreekAnalyzer get() {<FILL_FUNCTION_BODY>}
}
|
return this.analyzer;
| 125 | 11 | 136 | 16,103 |
iluwatar_java-design-patterns
|
java-design-patterns/role-object/src/main/java/com/iluwatar/roleobject/ApplicationRoleObject.java
|
ApplicationRoleObject
|
main
|
class ApplicationRoleObject {
/**
* Main entry point.
*
* @param args program arguments
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
var customer = Customer.newCustomer(Borrower, Investor);
LOGGER.info(" the new customer created : {}", customer);
var hasBorrowerRole = customer.hasRole(Borrower);
LOGGER.info(" customer has a borrowed role - {}", hasBorrowerRole);
var hasInvestorRole = customer.hasRole(Investor);
LOGGER.info(" customer has an investor role - {}", hasInvestorRole);
customer.getRole(Investor, InvestorRole.class)
.ifPresent(inv -> {
inv.setAmountToInvest(1000);
inv.setName("Billy");
});
customer.getRole(Borrower, BorrowerRole.class)
.ifPresent(inv -> inv.setName("Johny"));
customer.getRole(Investor, InvestorRole.class)
.map(InvestorRole::invest)
.ifPresent(LOGGER::info);
customer.getRole(Borrower, BorrowerRole.class)
.map(BorrowerRole::borrow)
.ifPresent(LOGGER::info);
| 57 | 293 | 350 | 793 |
questdb_questdb
|
questdb/core/src/main/java/io/questdb/griffin/engine/functions/catalogue/PrefixedTxIDCurrentFunctionFactory.java
|
PrefixedTxIDCurrentFunctionFactory
|
getSignature
|
class PrefixedTxIDCurrentFunctionFactory extends TxIDCurrentFunctionFactory {
@Override
public String getSignature() {<FILL_FUNCTION_BODY>}
}
|
return "pg_catalog.txid_current()";
| 43 | 18 | 61 | 61,080 |
apache_dubbo
|
dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DecodeableRpcResult.java
|
DecodeableRpcResult
|
decode
|
class DecodeableRpcResult extends AppResponse implements Codec, Decodeable {
private static final ErrorTypeAwareLogger log = LoggerFactory.getErrorTypeAwareLogger(DecodeableRpcResult.class);
private final Channel channel;
private final byte serializationType;
private final InputStream inputStream;
private final Response response;
private final Invocation invocation;
private volatile boolean hasDecoded;
public DecodeableRpcResult(Channel channel, Response response, InputStream is, Invocation invocation, byte id) {
Assert.notNull(channel, "channel == null");
Assert.notNull(response, "response == null");
Assert.notNull(is, "inputStream == null");
this.channel = channel;
this.response = response;
this.inputStream = is;
this.invocation = invocation;
this.serializationType = id;
}
@Override
public void encode(Channel channel, OutputStream output, Object message) throws IOException {
throw new UnsupportedOperationException();
}
@Override
public Object decode(Channel channel, InputStream input) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public void decode() throws Exception {
if (!hasDecoded && channel != null && inputStream != null) {
try {
if (invocation != null) {
Configuration systemConfiguration = null;
try {
systemConfiguration = ConfigurationUtils.getSystemConfiguration(
channel.getUrl().getScopeModel());
} catch (Exception e) {
// Because the Environment may be destroyed during the offline process, the configuration cannot
// be obtained.
// Exceptions are ignored here, and normal decoding is guaranteed.
}
if (systemConfiguration == null
|| systemConfiguration.getBoolean(SERIALIZATION_SECURITY_CHECK_KEY, true)) {
Object serializationTypeObj = invocation.get(SERIALIZATION_ID_KEY);
if (serializationTypeObj != null) {
if ((byte) serializationTypeObj != serializationType) {
throw new IOException("Unexpected serialization id:" + serializationType
+ " received from network, please check if the peer send the right id.");
}
}
}
}
decode(channel, inputStream);
} catch (Throwable e) {
if (log.isWarnEnabled()) {
log.warn(PROTOCOL_FAILED_DECODE, "", "", "Decode rpc result failed: " + e.getMessage(), e);
}
response.setStatus(Response.CLIENT_ERROR);
response.setErrorMessage(StringUtils.toString(e));
} finally {
hasDecoded = true;
}
}
}
private void handleValue(ObjectInput in) throws IOException {
try {
Type[] returnTypes = RpcUtils.getReturnTypes(invocation);
Object value;
if (ArrayUtils.isEmpty(returnTypes)) {
// happens when generic invoke or void return
value = in.readObject();
} else if (returnTypes.length == 1) {
value = in.readObject((Class<?>) returnTypes[0]);
} else {
value = in.readObject((Class<?>) returnTypes[0], returnTypes[1]);
}
setValue(value);
} catch (ClassNotFoundException e) {
rethrow(e);
}
}
private void handleException(ObjectInput in) throws IOException {
try {
setException(in.readThrowable());
} catch (ClassNotFoundException e) {
rethrow(e);
}
}
private void handleAttachment(ObjectInput in) throws IOException {
try {
addObjectAttachments(in.readAttachments());
} catch (ClassNotFoundException e) {
rethrow(e);
}
}
private void rethrow(Exception e) throws IOException {
throw new IOException(StringUtils.toString("Read response data failed.", e));
}
}
|
if (log.isDebugEnabled()) {
Thread thread = Thread.currentThread();
log.debug("Decoding in thread -- [" + thread.getName() + "#" + thread.getId() + "]");
}
int contentLength = input.available();
setAttribute(Constants.CONTENT_LENGTH_KEY, contentLength);
// switch TCCL
if (invocation != null && invocation.getServiceModel() != null) {
Thread.currentThread()
.setContextClassLoader(invocation.getServiceModel().getClassLoader());
}
ObjectInput in = CodecSupport.getSerialization(serializationType).deserialize(channel.getUrl(), input);
byte flag = in.readByte();
switch (flag) {
case DubboCodec.RESPONSE_NULL_VALUE:
break;
case DubboCodec.RESPONSE_VALUE:
handleValue(in);
break;
case DubboCodec.RESPONSE_WITH_EXCEPTION:
handleException(in);
break;
case DubboCodec.RESPONSE_NULL_VALUE_WITH_ATTACHMENTS:
handleAttachment(in);
break;
case DubboCodec.RESPONSE_VALUE_WITH_ATTACHMENTS:
handleValue(in);
handleAttachment(in);
break;
case DubboCodec.RESPONSE_WITH_EXCEPTION_WITH_ATTACHMENTS:
handleException(in);
handleAttachment(in);
break;
default:
throw new IOException("Unknown result flag, expect '0' '1' '2' '3' '4' '5', but received: " + flag);
}
if (in instanceof Cleanable) {
((Cleanable) in).cleanup();
}
return this;
| 1,010 | 465 | 1,475 | 67,170 |
apache_shenyu
|
shenyu/shenyu-loadbalancer/src/main/java/org/apache/shenyu/loadbalancer/spi/P2cLoadBalancer.java
|
P2cLoadBalancer
|
doSelect
|
class P2cLoadBalancer extends AbstractLoadBalancer {
/**
* maximum tolerance of idle time.
*/
private static final int FORCE_GAP = 3 * 1000;
/**
* penalty value.
*/
private static final int PENALTY = 250 * 1000;
/**
* pick times.
*/
private static final int PICK_TIMES = 3;
private final Random random = new Random();
/**
* pick of 2 choices to select upstream.
*
* @param upstreamList the upstream list
* @param ip the ip
* @return selected upstream
*/
@Override
protected Upstream doSelect(final List<Upstream> upstreamList, final String ip) {<FILL_FUNCTION_BODY>}
/**
* select two nodes randomly.
*
* @param upstreamList the upstream list
* @return two upstream
*/
private Upstream[] pickTwoUpstreams(final List<Upstream> upstreamList) {
Upstream[] upstreams = new Upstream[2];
for (int i = 0; i < PICK_TIMES; i++) {
int a = random.nextInt(upstreamList.size());
int b = random.nextInt(upstreamList.size() - 1);
// prevent random nodes from being the same.
if (b >= a) {
b += 1;
}
upstreams[0] = upstreamList.get(a);
upstreams[1] = upstreamList.get(b);
if (upstreams[0].isHealthy() && upstreams[1].isHealthy()) {
break;
}
}
return upstreams;
}
/**
* calculate load.
*
* @param upstream the upstream
* @return load
*/
public long load(final Upstream upstream) {
long lag = (long) (Math.sqrt((double) upstream.getLag()) + 1);
long load = lag * upstream.getInflight().get();
if (load == 0) {
load = PENALTY;
}
return load;
}
}
|
long start = System.currentTimeMillis();
Upstream[] upstreams = pickTwoUpstreams(upstreamList);
Upstream picked;
Upstream unpicked;
if (load(upstreams[0]) > load(upstreams[1])) {
picked = upstreams[1];
unpicked = upstreams[0];
} else {
picked = upstreams[0];
unpicked = upstreams[1];
}
// If the failed node is not selected once in the forceGap period, it is forced to be selected once.
long pick = unpicked.getLastPicked();
if ((start - pick) > FORCE_GAP) {
unpicked.setLastPicked(start);
picked = unpicked;
}
if (picked != unpicked) {
picked.setLastPicked(start);
}
picked.getInflight().incrementAndGet();
return picked;
| 574 | 248 | 822 | 68,249 |
confluentinc_ksql
|
ksql/ksqldb-engine/src/main/java/io/confluent/ksql/schema/registry/KsqlSchemaRegistryClientFactory.java
|
KsqlSchemaRegistryClientFactory
|
get
|
class KsqlSchemaRegistryClientFactory {
private final SSLContext sslContext;
private final Supplier<RestService> serviceSupplier;
private final Map<String, Object> schemaRegistryClientConfigs;
private final SchemaRegistryClientFactory schemaRegistryClientFactory;
private final Map<String, String> httpHeaders;
private final String schemaRegistryUrl;
interface SchemaRegistryClientFactory {
CachedSchemaRegistryClient create(RestService service,
int identityMapCapacity,
List<SchemaProvider> providers,
Map<String, Object> clientConfigs,
Map<String, String> httpHeaders);
}
public KsqlSchemaRegistryClientFactory(
final KsqlConfig config,
final Map<String, String> schemaRegistryHttpHeaders
) {
this(config, newSslContext(config), schemaRegistryHttpHeaders);
}
public KsqlSchemaRegistryClientFactory(
final KsqlConfig config,
final SSLContext sslContext,
final Map<String, String> schemaRegistryHttpHeaders
) {
this(config,
() -> new RestService(config.getString(KsqlConfig.SCHEMA_REGISTRY_URL_PROPERTY)),
sslContext,
CachedSchemaRegistryClient::new,
schemaRegistryHttpHeaders
);
// Force config exception now:
config.getString(KsqlConfig.SCHEMA_REGISTRY_URL_PROPERTY);
}
@VisibleForTesting
KsqlSchemaRegistryClientFactory(final KsqlConfig config,
final Supplier<RestService> serviceSupplier,
final SSLContext sslContext,
final SchemaRegistryClientFactory schemaRegistryClientFactory,
final Map<String, String> httpHeaders) {
this.sslContext = sslContext;
this.serviceSupplier = serviceSupplier;
this.schemaRegistryClientConfigs = config.originalsWithPrefix(
KsqlConfig.KSQL_SCHEMA_REGISTRY_PREFIX);
this.schemaRegistryClientFactory = schemaRegistryClientFactory;
this.httpHeaders = httpHeaders;
this.schemaRegistryUrl = config.getString(KsqlConfig.SCHEMA_REGISTRY_URL_PROPERTY).trim();
}
/**
* Creates an SslContext configured to be used with the KsqlSchemaRegistryClient.
*/
public static SSLContext newSslContext(final KsqlConfig config) {
if (config.getBoolean(ConfluentConfigs.ENABLE_FIPS_CONFIG)) {
SecurityUtils.addConfiguredSecurityProviders(config.originals());
}
final DefaultSslEngineFactory sslFactory = new DefaultSslEngineFactory();
configureSslEngineFactory(config, sslFactory);
return sslFactory.sslContext();
}
@VisibleForTesting
static void configureSslEngineFactory(
final KsqlConfig config,
final SslEngineFactory sslFactory
) {
sslFactory
.configure(config.valuesWithPrefixOverride(KsqlConfig.KSQL_SCHEMA_REGISTRY_PREFIX));
}
public SchemaRegistryClient get() {<FILL_FUNCTION_BODY>}
}
|
if (schemaRegistryUrl.equals("")) {
return new DefaultSchemaRegistryClient();
}
final RestService restService = serviceSupplier.get();
// This call sets a default sslSocketFactory.
final SchemaRegistryClient client = schemaRegistryClientFactory.create(
restService,
1000,
ImmutableList.of(
new AvroSchemaProvider(), new ProtobufSchemaProvider(), new JsonSchemaProvider()),
schemaRegistryClientConfigs,
httpHeaders
);
// If we have an sslContext, we use it to set the sslSocketFactory on the restService client.
// We need to do it in this order so that the override here is not reset by the constructor
// above.
if (sslContext != null) {
restService.setSslSocketFactory(sslContext.getSocketFactory());
}
return client;
| 788 | 221 | 1,009 | 14,904 |
orientechnologies_orientdb
|
orientdb/core/src/main/java/com/orientechnologies/orient/core/storage/cache/chm/LRUList.java
|
LRUList
|
next
|
class LRUList implements Iterable<OCacheEntry> {
private int size;
private OCacheEntry head;
private OCacheEntry tail;
void remove(final OCacheEntry entry) {
final OCacheEntry next = entry.getNext();
final OCacheEntry prev = entry.getPrev();
if (!(next != null || prev != null || entry == head)) {
return;
}
assert prev == null || prev.getNext() == entry;
assert next == null || next.getPrev() == entry;
if (next != null) {
next.setPrev(prev);
}
if (prev != null) {
prev.setNext(next);
}
if (head == entry) {
assert entry.getPrev() == null;
head = next;
}
if (tail == entry) {
assert entry.getNext() == null;
tail = prev;
}
entry.setNext(null);
entry.setPrev(null);
entry.setContainer(null);
size--;
}
boolean contains(final OCacheEntry entry) {
return entry.getContainer() == this;
}
void moveToTheTail(final OCacheEntry entry) {
if (tail == entry) {
assert entry.getNext() == null;
return;
}
final OCacheEntry next = entry.getNext();
final OCacheEntry prev = entry.getPrev();
final boolean newEntry = entry.getContainer() == null;
assert entry.getContainer() == null || entry.getContainer() == this;
assert prev == null || prev.getNext() == entry;
assert next == null || next.getPrev() == entry;
if (prev != null) {
prev.setNext(next);
}
if (next != null) {
next.setPrev(prev);
}
if (head == entry) {
assert entry.getPrev() == null;
head = next;
}
entry.setPrev(tail);
entry.setNext(null);
if (tail != null) {
assert tail.getNext() == null;
tail.setNext(entry);
tail = entry;
} else {
tail = head = entry;
}
if (newEntry) {
entry.setContainer(this);
size++;
} else {
assert entry.getContainer() == this;
}
}
int size() {
return size;
}
OCacheEntry poll() {
if (head == null) {
return null;
}
final OCacheEntry entry = head;
final OCacheEntry next = head.getNext();
assert next == null || next.getPrev() == head;
head = next;
if (next != null) {
next.setPrev(null);
}
assert head == null || head.getPrev() == null;
if (head == null) {
tail = null;
}
entry.setNext(null);
assert entry.getPrev() == null;
size--;
entry.setContainer(null);
return entry;
}
OCacheEntry peek() {
return head;
}
public Iterator<OCacheEntry> iterator() {
return new Iterator<OCacheEntry>() {
private OCacheEntry next = tail;
@Override
public boolean hasNext() {
return next != null;
}
@Override
public OCacheEntry next() {<FILL_FUNCTION_BODY>}
};
}
}
|
if (!hasNext()) {
throw new NoSuchElementException();
}
final OCacheEntry result = next;
next = next.getPrev();
return result;
| 940 | 48 | 988 | 35,511 |
spring-cloud_spring-cloud-gateway
|
spring-cloud-gateway/spring-cloud-gateway-integration-tests/grpc/src/main/java/org/springframework/cloud/gateway/tests/grpc/GRPCApplication.java
|
GRPCServer
|
start
|
class GRPCServer implements ApplicationRunner {
private static final Logger log = LoggerFactory.getLogger(GRPCServer.class);
private final Environment environment;
private Server server;
GRPCServer(Environment environment) {
this.environment = environment;
}
@Override
public void run(ApplicationArguments args) throws Exception {
final GRPCServer server = new GRPCServer(environment);
server.start();
}
private void start() throws IOException {<FILL_FUNCTION_BODY>}
private ServerCredentials createServerCredentials() throws IOException {
File certChain = new ClassPathResource("public.cert").getFile();
File privateKey = new ClassPathResource("private.key").getFile();
return TlsServerCredentials.create(certChain, privateKey);
}
private void stop() throws InterruptedException {
if (server != null) {
server.shutdown().awaitTermination(30, TimeUnit.SECONDS);
}
log.info("gRPC server stopped");
}
static class HelloService extends HelloServiceGrpc.HelloServiceImplBase {
@Override
public void hello(HelloRequest request, StreamObserver<HelloResponse> responseObserver) {
if ("failWithRuntimeException!".equals(request.getFirstName())) {
StatusRuntimeException exception = Status.FAILED_PRECONDITION.withDescription("Invalid firstName")
.asRuntimeException();
responseObserver.onError(exception);
responseObserver.onCompleted();
return;
}
String greeting = String.format("Hello, %s %s", request.getFirstName(), request.getLastName());
log.info("Sending response: " + greeting);
HelloResponse response = HelloResponse.newBuilder().setGreeting(greeting).build();
responseObserver.onNext(response);
responseObserver.onCompleted();
}
}
}
|
Integer serverPort = environment.getProperty("local.server.port", Integer.class);
int grpcPort = serverPort + 1;
ServerCredentials creds = createServerCredentials();
server = Grpc.newServerBuilderForPort(grpcPort, creds).addService(new HelloService()).build().start();
log.info("Starting gRPC server in port " + grpcPort);
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
try {
GRPCServer.this.stop();
}
catch (InterruptedException e) {
e.printStackTrace(System.err);
}
}));
| 504 | 176 | 680 | 43,205 |
apache_maven
|
maven/maven-core/src/main/java/org/apache/maven/lifecycle/internal/builder/multithreaded/MultiThreadedBuilder.java
|
MultiThreadedBuilder
|
multiThreadedProjectTaskSegmentBuild
|
class MultiThreadedBuilder implements Builder {
private final Logger logger = LoggerFactory.getLogger(getClass());
private final LifecycleModuleBuilder lifecycleModuleBuilder;
@Inject
public MultiThreadedBuilder(LifecycleModuleBuilder lifecycleModuleBuilder) {
this.lifecycleModuleBuilder = lifecycleModuleBuilder;
}
@Override
public void build(
MavenSession session,
ReactorContext reactorContext,
ProjectBuildList projectBuilds,
List<TaskSegment> taskSegments,
ReactorBuildStatus reactorBuildStatus)
throws ExecutionException, InterruptedException {
int nThreads = Math.min(
session.getRequest().getDegreeOfConcurrency(),
session.getProjects().size());
boolean parallel = nThreads > 1;
// Propagate the parallel flag to the root session and all of the cloned sessions in each project segment
session.setParallel(parallel);
for (ProjectSegment segment : projectBuilds) {
segment.getSession().setParallel(parallel);
}
ExecutorService executor = Executors.newFixedThreadPool(nThreads, new BuildThreadFactory());
CompletionService<ProjectSegment> service = new ExecutorCompletionService<>(executor);
// Currently disabled
ThreadOutputMuxer muxer = null; // new ThreadOutputMuxer( analyzer.getProjectBuilds(), System.out );
for (TaskSegment taskSegment : taskSegments) {
ProjectBuildList segmentProjectBuilds = projectBuilds.getByTaskSegment(taskSegment);
Map<MavenProject, ProjectSegment> projectBuildMap = projectBuilds.selectSegment(taskSegment);
try {
ConcurrencyDependencyGraph analyzer =
new ConcurrencyDependencyGraph(segmentProjectBuilds, session.getProjectDependencyGraph());
multiThreadedProjectTaskSegmentBuild(
analyzer, reactorContext, session, service, taskSegment, projectBuildMap, muxer);
if (reactorContext.getReactorBuildStatus().isHalted()) {
break;
}
} catch (Exception e) {
session.getResult().addException(e);
break;
}
}
executor.shutdown();
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
}
private void multiThreadedProjectTaskSegmentBuild(
ConcurrencyDependencyGraph analyzer,
ReactorContext reactorContext,
MavenSession rootSession,
CompletionService<ProjectSegment> service,
TaskSegment taskSegment,
Map<MavenProject, ProjectSegment> projectBuildList,
ThreadOutputMuxer muxer) {<FILL_FUNCTION_BODY>}
private Callable<ProjectSegment> createBuildCallable(
final MavenSession rootSession,
final ProjectSegment projectBuild,
final ReactorContext reactorContext,
final TaskSegment taskSegment,
final ThreadOutputMuxer muxer,
final Set<String> duplicateArtifactIds) {
return () -> {
final Thread currentThread = Thread.currentThread();
final String originalThreadName = currentThread.getName();
final MavenProject project = projectBuild.getProject();
final String threadNameSuffix = duplicateArtifactIds.contains(project.getArtifactId())
? project.getGroupId() + ":" + project.getArtifactId()
: project.getArtifactId();
currentThread.setName("mvn-builder-" + threadNameSuffix);
try {
// muxer.associateThreadWithProjectSegment( projectBuild );
lifecycleModuleBuilder.buildProject(
projectBuild.getSession(), rootSession, reactorContext, project, taskSegment);
// muxer.setThisModuleComplete( projectBuild );
return projectBuild;
} finally {
currentThread.setName(originalThreadName);
}
};
}
}
|
// gather artifactIds which are not unique so that the respective thread names can be extended with the groupId
Set<String> duplicateArtifactIds = projectBuildList.keySet().stream()
.map(MavenProject::getArtifactId)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet()
.stream()
.filter(p -> p.getValue() > 1)
.map(Map.Entry::getKey)
.collect(Collectors.toSet());
// schedule independent projects
for (MavenProject mavenProject : analyzer.getRootSchedulableBuilds()) {
ProjectSegment projectSegment = projectBuildList.get(mavenProject);
logger.debug("Scheduling: {}", projectSegment.getProject());
Callable<ProjectSegment> cb = createBuildCallable(
rootSession, projectSegment, reactorContext, taskSegment, muxer, duplicateArtifactIds);
service.submit(cb);
}
// for each finished project
for (int i = 0; i < analyzer.getNumberOfBuilds(); i++) {
try {
ProjectSegment projectBuild = service.take().get();
if (reactorContext.getReactorBuildStatus().isHalted()) {
break;
}
// MNG-6170: Only schedule other modules from reactor if we have more modules to build than one.
if (analyzer.getNumberOfBuilds() > 1) {
final List<MavenProject> newItemsThatCanBeBuilt =
analyzer.markAsFinished(projectBuild.getProject());
for (MavenProject mavenProject : newItemsThatCanBeBuilt) {
ProjectSegment scheduledDependent = projectBuildList.get(mavenProject);
logger.debug("Scheduling: {}", scheduledDependent);
Callable<ProjectSegment> cb = createBuildCallable(
rootSession,
scheduledDependent,
reactorContext,
taskSegment,
muxer,
duplicateArtifactIds);
service.submit(cb);
}
}
} catch (InterruptedException e) {
rootSession.getResult().addException(e);
break;
} catch (ExecutionException e) {
// TODO MNG-5766 changes likely made this redundant
rootSession.getResult().addException(e);
break;
}
}
| 976 | 593 | 1,569 | 11,224 |
hs-web_hsweb-framework
|
hsweb-framework/hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/web/AuthorizationController.java
|
AuthorizationController
|
doLogin
|
class AuthorizationController {
@Autowired
private ApplicationEventPublisher eventPublisher;
@Autowired
private ReactiveAuthenticationManager authenticationManager;
@GetMapping("/me")
@Authorize
@Operation(summary = "当前登录用户权限信息")
public Mono<Authentication> me() {
return Authentication.currentReactive()
.switchIfEmpty(Mono.error(UnAuthorizedException::new));
}
@PostMapping(value = "/login", consumes = MediaType.APPLICATION_JSON_VALUE)
@Authorize(ignore = true)
@AccessLogger(ignoreParameter = {"parameter"})
@Operation(summary = "登录", description = "必要参数:username,password.根据配置不同,其他参数也不同,如:验证码等.")
public Mono<Map<String, Object>> authorizeByJson(@Parameter(example = "{\"username\":\"admin\",\"password\":\"admin\"}")
@RequestBody Mono<Map<String, Object>> parameter) {
return doLogin(parameter);
}
/**
* <img src="https://raw.githubusercontent.com/hs-web/hsweb-framework/4.0.x/hsweb-authorization/hsweb-authorization-basic/img/autz-flow.png">
*/
@SneakyThrows
private Mono<Map<String, Object>> doLogin(Mono<Map<String, Object>> parameter) {<FILL_FUNCTION_BODY>}
private Mono<Authentication> doAuthorize(AuthorizationBeforeEvent event) {
Mono<Authentication> authenticationMono;
if (event.isAuthorized()) {
if (event.getAuthentication() != null) {
authenticationMono = Mono.just(event.getAuthentication());
} else {
authenticationMono = ReactiveAuthenticationHolder
.get(event.getUserId())
.switchIfEmpty(Mono.error(() -> new AuthenticationException(AuthenticationException.USER_DISABLED)));
}
} else {
authenticationMono = authenticationManager
.authenticate(Mono.just(new PlainTextUsernamePasswordAuthenticationRequest(event.getUsername(), event.getPassword())))
.switchIfEmpty(Mono.error(() -> new AuthenticationException(AuthenticationException.ILLEGAL_PASSWORD)));
}
return authenticationMono;
}
}
|
return parameter.flatMap(parameters -> {
String username_ = String.valueOf(parameters.getOrDefault("username", ""));
String password_ = String.valueOf(parameters.getOrDefault("password", ""));
Assert.hasLength(username_, "validation.username_must_not_be_empty");
Assert.hasLength(password_, "validation.password_must_not_be_empty");
Function<String, Object> parameterGetter = parameters::get;
return Mono
.defer(() -> {
AuthorizationDecodeEvent decodeEvent = new AuthorizationDecodeEvent(username_, password_, parameterGetter);
return decodeEvent
.publish(eventPublisher)
.then(Mono.defer(() -> {
String username = decodeEvent.getUsername();
String password = decodeEvent.getPassword();
AuthorizationBeforeEvent beforeEvent = new AuthorizationBeforeEvent(username, password, parameterGetter);
return beforeEvent
.publish(eventPublisher)
.then(Mono.defer(() -> doAuthorize(beforeEvent)
.flatMap(auth -> {
//触发授权成功事件
AuthorizationSuccessEvent event = new AuthorizationSuccessEvent(auth, parameterGetter);
event.getResult().put("userId", auth.getUser().getId());
return event
.publish(eventPublisher)
.then(Mono.fromCallable(event::getResult));
})));
}));
})
.onErrorResume(err -> {
AuthorizationFailedEvent failedEvent = new AuthorizationFailedEvent(username_, password_, parameterGetter);
failedEvent.setException(err);
return failedEvent
.publish(eventPublisher)
.then(Mono.error(failedEvent::getException));
});
});
| 603 | 463 | 1,066 | 22,734 |
dropwizard_dropwizard
|
dropwizard/docs/source/examples/views/src/main/java/io/dropwizard/documentation/ViewsApp.java
|
ViewsApp
|
run
|
class ViewsApp extends Application<ViewsConfiguration> {
@Override
public void initialize(Bootstrap<ViewsConfiguration> bootstrap) {
// Default configuration
// views: ViewsApp#initialize->ViewBundle
bootstrap.addBundle(new ViewBundle<>());
// views: ViewsApp#initialize->ViewBundle
// Custom configuration
// views: ViewsApp#initialize->ViewBundle->custom
bootstrap.addBundle(new ViewBundle<ViewsConfiguration>() {
@Override
public Map<String, Map<String, String>> getViewConfiguration(ViewsConfiguration config) {
return config.getViewRendererConfiguration();
}
});
// views: ViewsApp#initialize->ViewBundle->custom
}
@Override
public void run(ViewsConfiguration configuration, Environment environment) throws Exception {<FILL_FUNCTION_BODY>}
}
|
// views: ViewsApp#run->ExtendedExceptionMapper->ViewRenderException
environment.jersey().register(new ExtendedExceptionMapper<WebApplicationException>() {
@Override
public Response toResponse(WebApplicationException exception) {
// Return a response here, for example HTTP 500 (Internal Server Error)
return Response.serverError().build();
}
@Override
public boolean isMappable(WebApplicationException e) {
return ExceptionUtils.indexOfThrowable(e, ViewRenderException.class) != -1;
}
});
// views: ViewsApp#run->ExtendedExceptionMapper->ViewRenderException
// views: ViewsApp#run->ExtendedExceptionMapper->MustacheNotFoundException
environment.jersey().register(new ExtendedExceptionMapper<WebApplicationException>() {
@Override
public Response toResponse(WebApplicationException exception) {
return Response.status(Response.Status.NOT_FOUND).build();
}
@Override
public boolean isMappable(WebApplicationException e) {
return ExceptionUtils.getRootCause(e).getClass() == MustacheNotFoundException.class;
}
});
// views: ViewsApp#run->ExtendedExceptionMapper->MustacheNotFoundException
// views: ViewsApp#run->ErrorEntityWriter->ErrorMessage
environment.jersey().register(new ErrorEntityWriter<ErrorMessage, View>(MediaType.TEXT_HTML_TYPE, View.class) {
@Override
protected View getRepresentation(ErrorMessage errorMessage) {
return new ErrorView(errorMessage);
}
});
// views: ViewsApp#run->ErrorEntityWriter->ErrorMessage
// views: ViewsApp#run->ErrorEntityWriter->ValidationErrorMessage
environment.jersey().register(new ErrorEntityWriter<ValidationErrorMessage, View>(MediaType.TEXT_HTML_TYPE, View.class) {
@Override
protected View getRepresentation(ValidationErrorMessage message) {
return new ValidationErrorView(message);
}
});
// views: ViewsApp#run->ErrorEntityWriter->ValidationErrorMessage
| 224 | 542 | 766 | 69,991 |
dianping_cat
|
cat/cat-home/src/main/java/com/dianping/cat/report/page/top/ProblemReportVisitor.java
|
ProblemReportVisitor
|
visitMachine
|
class ProblemReportVisitor extends BaseVisitor {
private DomainInfo m_info;
private String m_ipAddress;
private String m_type;
private String m_date;
private Integer m_minute;
public ProblemReportVisitor(String ipAddress, DomainInfo info, String type) {
m_info = info;
m_type = type;
m_ipAddress = ipAddress;
}
@Override
public void visitProblemReport(ProblemReport problemReport) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:");
m_date = sdf.format(problemReport.getStartTime());
super.visitProblemReport(problemReport);
}
@Override
public void visitMachine(Machine machine) {<FILL_FUNCTION_BODY>}
@Override
public void visitEntity(Entity entity) {
if (m_type.equals(entity.getType())) {
super.visitEntity(entity);
}
}
@Override
public void visitSegment(Segment segment) {
m_minute = segment.getId();
int count = segment.getCount();
String key = "";
if (m_minute >= 10) {
key = m_date + m_minute;
} else {
key = m_date + '0' + m_minute;
}
Metric metric = m_info.getMetric(key);
metric.addException(count);
}
}
|
String id = machine.getIp();
if (Constants.ALL.equals(m_ipAddress) || id.equals(m_ipAddress)) {
super.visitMachine(machine);
}
| 377 | 55 | 432 | 69,832 |
jeequan_jeepay
|
jeepay/jeepay-payment/src/main/java/com/jeequan/jeepay/pay/channel/xxpay/payway/WxJsapi.java
|
WxJsapi
|
pay
|
class WxJsapi extends XxpayPaymentService {
@Override
public String preCheck(UnifiedOrderRQ rq, PayOrder payOrder) {
WxJsapiOrderRQ bizRQ = (WxJsapiOrderRQ) rq;
if(StringUtils.isEmpty(bizRQ.getOpenid())){
throw new BizException("[openId]不可为空");
}
return null;
}
@Override
public AbstractRS pay(UnifiedOrderRQ rq, PayOrder payOrder, MchAppConfigContext mchAppConfigContext) throws Exception{<FILL_FUNCTION_BODY>}
}
|
WxJsapiOrderRQ bizRQ = (WxJsapiOrderRQ) rq;
XxpayNormalMchParams params = (XxpayNormalMchParams)configContextQueryService.queryNormalMchParams(mchAppConfigContext.getMchNo(), mchAppConfigContext.getAppId(), getIfCode());
// 构造支付请求参数
Map<String,Object> paramMap = new TreeMap();
paramMap.put("mchId", params.getMchId());
paramMap.put("productId", "8004"); // 微信公众号支付
paramMap.put("mchOrderNo", payOrder.getPayOrderId());
paramMap.put("amount", payOrder.getAmount() + "");
paramMap.put("currency", "cny");
paramMap.put("clientIp", payOrder.getClientIp());
paramMap.put("device", "web");
paramMap.put("returnUrl", getReturnUrl());
paramMap.put("notifyUrl", getNotifyUrl(payOrder.getPayOrderId()));
paramMap.put("subject", payOrder.getSubject());
paramMap.put("body", payOrder.getBody());
paramMap.put("channelUserId", bizRQ.getOpenid());
// 构造函数响应数据
WxJsapiOrderRS res = ApiResBuilder.buildSuccess(WxJsapiOrderRS.class);
ChannelRetMsg channelRetMsg = new ChannelRetMsg();
res.setChannelRetMsg(channelRetMsg);
// 发起支付
JSONObject resObj = doPay(payOrder, params, paramMap, channelRetMsg);
if(resObj == null) {
return res;
}
res.setPayInfo(resObj.getString("payParams"));
return res;
| 170 | 457 | 627 | 25,089 |
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/dynamic/ReactiveExecutableCommandLookupStrategy.java
|
ReactiveCommandFactoryResolver
|
resolveRedisCommandFactory
|
class ReactiveCommandFactoryResolver implements CommandFactoryResolver {
final AnnotationCommandSegmentFactory commandSegmentFactory = new AnnotationCommandSegmentFactory();
final AnnotationRedisCodecResolver codecResolver;
ReactiveCommandFactoryResolver() {
codecResolver = new AnnotationRedisCodecResolver(redisCodecs);
}
public ReactiveCommandSegmentCommandFactory resolveRedisCommandFactory(CommandMethod commandMethod,
RedisCommandsMetadata redisCommandsMetadata) {<FILL_FUNCTION_BODY>}
}
|
RedisCodec<?, ?> codec = codecResolver.resolve(commandMethod);
if (codec == null) {
throw new CommandCreationException(commandMethod, "Cannot resolve RedisCodec");
}
CommandSegments commandSegments = commandSegmentFactory.createCommandSegments(commandMethod);
commandMethodVerifier.validate(commandSegments, commandMethod);
CodecAwareOutputFactoryResolver outputFactoryResolver = new CodecAwareOutputFactoryResolver(
ReactiveExecutableCommandLookupStrategy.this.outputFactoryResolver, codec);
return new ReactiveCommandSegmentCommandFactory(commandSegments, commandMethod, codec, outputFactoryResolver);
| 131 | 167 | 298 | 39,329 |
wildfirechat_im-server
|
im-server/common/src/main/java/cn/wildfirechat/messagecontentbuilder/MessageContentBuilder.java
|
MessageContentBuilder
|
mentionedType
|
class MessageContentBuilder {
private int mentionedType;
private List<String> mentionedTargets;
private String extra;
public MessageContentBuilder mentionedType(int mentionedType) {<FILL_FUNCTION_BODY>}
public MessageContentBuilder mentionedTargets(List<String> mentionedTargets) {
this.mentionedTargets = mentionedTargets;
return this;
}
public MessageContentBuilder extra(String extra) {
this.extra = extra;
return this;
}
protected MessagePayload encodeBase() {
MessagePayload payload = new MessagePayload();
payload.setMentionedType(mentionedType);
payload.setMentionedTarget(mentionedTargets);
payload.setExtra(extra);
return payload;
}
abstract public MessagePayload build();
}
|
this.mentionedType = mentionedType;
return this;
| 202 | 18 | 220 | 4,158 |
PlayEdu_PlayEdu
|
PlayEdu/playedu-common/src/main/java/xyz/playedu/common/domain/LdapUser.java
|
LdapUser
|
setUserId
|
class LdapUser implements Serializable {
/** */
@TableId(type = IdType.AUTO)
private Integer id;
/** 唯一特征值 */
private String uuid;
/** 用户ID */
private Integer userId;
/** cn */
private String cn;
/** dn */
private String dn;
/** ou */
private String ou;
/** uid */
private String uid;
/** 邮箱 */
private String email;
/** */
private Date createdAt;
/** */
private Date updatedAt;
@TableField(exist = false)
private static final long serialVersionUID = 1L;
/** */
public Integer getId() {
return id;
}
/** */
public void setId(Integer id) {
this.id = id;
}
/** 唯一特征值 */
public String getUuid() {
return uuid;
}
/** 唯一特征值 */
public void setUuid(String uuid) {
this.uuid = uuid;
}
/** 用户ID */
public Integer getUserId() {
return userId;
}
/** 用户ID */
public void setUserId(Integer userId) {<FILL_FUNCTION_BODY>}
/** cn */
public String getCn() {
return cn;
}
/** cn */
public void setCn(String cn) {
this.cn = cn;
}
/** dn */
public String getDn() {
return dn;
}
/** dn */
public void setDn(String dn) {
this.dn = dn;
}
/** ou */
public String getOu() {
return ou;
}
/** ou */
public void setOu(String ou) {
this.ou = ou;
}
/** uid */
public String getUid() {
return uid;
}
/** uid */
public void setUid(String uid) {
this.uid = uid;
}
/** 邮箱 */
public String getEmail() {
return email;
}
/** 邮箱 */
public void setEmail(String email) {
this.email = email;
}
/** */
public Date getCreatedAt() {
return createdAt;
}
/** */
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
/** */
public Date getUpdatedAt() {
return updatedAt;
}
/** */
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
@Override
public boolean equals(Object that) {
if (this == that) {
return true;
}
if (that == null) {
return false;
}
if (getClass() != that.getClass()) {
return false;
}
LdapUser other = (LdapUser) that;
return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId()))
&& (this.getUuid() == null
? other.getUuid() == null
: this.getUuid().equals(other.getUuid()))
&& (this.getUserId() == null
? other.getUserId() == null
: this.getUserId().equals(other.getUserId()))
&& (this.getCn() == null
? other.getCn() == null
: this.getCn().equals(other.getCn()))
&& (this.getDn() == null
? other.getDn() == null
: this.getDn().equals(other.getDn()))
&& (this.getOu() == null
? other.getOu() == null
: this.getOu().equals(other.getOu()))
&& (this.getUid() == null
? other.getUid() == null
: this.getUid().equals(other.getUid()))
&& (this.getEmail() == null
? other.getEmail() == null
: this.getEmail().equals(other.getEmail()))
&& (this.getCreatedAt() == null
? other.getCreatedAt() == null
: this.getCreatedAt().equals(other.getCreatedAt()))
&& (this.getUpdatedAt() == null
? other.getUpdatedAt() == null
: this.getUpdatedAt().equals(other.getUpdatedAt()));
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((getId() == null) ? 0 : getId().hashCode());
result = prime * result + ((getUuid() == null) ? 0 : getUuid().hashCode());
result = prime * result + ((getUserId() == null) ? 0 : getUserId().hashCode());
result = prime * result + ((getCn() == null) ? 0 : getCn().hashCode());
result = prime * result + ((getDn() == null) ? 0 : getDn().hashCode());
result = prime * result + ((getOu() == null) ? 0 : getOu().hashCode());
result = prime * result + ((getUid() == null) ? 0 : getUid().hashCode());
result = prime * result + ((getEmail() == null) ? 0 : getEmail().hashCode());
result = prime * result + ((getCreatedAt() == null) ? 0 : getCreatedAt().hashCode());
result = prime * result + ((getUpdatedAt() == null) ? 0 : getUpdatedAt().hashCode());
return result;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", uuid=").append(uuid);
sb.append(", userId=").append(userId);
sb.append(", cn=").append(cn);
sb.append(", dn=").append(dn);
sb.append(", ou=").append(ou);
sb.append(", uid=").append(uid);
sb.append(", email=").append(email);
sb.append(", createdAt=").append(createdAt);
sb.append(", updatedAt=").append(updatedAt);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}
|
this.userId = userId;
| 1,758 | 13 | 1,771 | 37,548 |
docker-java_docker-java
|
docker-java/docker-java-core/src/main/java/com/github/dockerjava/core/exec/RemoveConfigCmdExec.java
|
RemoveConfigCmdExec
|
execute
|
class RemoveConfigCmdExec extends AbstrSyncDockerCmdExec<RemoveConfigCmd, Void> implements RemoveConfigCmd.Exec {
private static final Logger LOGGER = LoggerFactory.getLogger(RemoveConfigCmdExec.class);
public RemoveConfigCmdExec(WebTarget baseResource, DockerClientConfig dockerClientConfig) {
super(baseResource, dockerClientConfig);
}
@Override
protected Void execute(RemoveConfigCmd command) {<FILL_FUNCTION_BODY>}
}
|
WebTarget webTarget = getBaseResource().path("/configs/" + command.getConfigId());
LOGGER.trace("DELETE: {}", webTarget);
webTarget.request().accept(MediaType.APPLICATION_JSON).delete();
return null;
| 124 | 68 | 192 | 17,404 |
jitsi_jitsi
|
jitsi/modules/impl/gui/src/main/java/net/java/sip/communicator/impl/gui/main/UINotification.java
|
UINotification
|
getUnreadObjects
|
class UINotification
{
/**
* The parent notification group.
*/
private final UINotificationGroup parentGroup;
/**
* The name associated with this notification.
*/
private final String notificationName;
/**
* The display name associated with this notification.
*/
private final String notificationDisplayName;
/**
* The time in milliseconds when the notification was received.
*/
private final long notificationTime;
/**
* Number of unread objects like calls or messages.
*/
private int unreadObjects = 0;
/**
* Creates an instance of <tt>UINotification</tt> by specifying the
* notification name and time.
*
* notification belongs
* @param displayName the name associated to this notification
* @param time the time in milliseconds when the notification was received
* @param parentGroup the group of notifications, to which this notification
* belongs
*/
public UINotification( String displayName,
long time,
UINotificationGroup parentGroup)
{
this(displayName, time, parentGroup, 1);
}
/**
* Creates an instance of <tt>UINotification</tt> by specifying the
* notification name and time.
*
* notification belongs
* @param displayName the name associated to this notification
* @param time the time in milliseconds when the notification was received
* @param parentGroup the group of notifications, to which this notification
* belongs
* @param unreadObjects number of unread objects for this notification.
*/
public UINotification( String displayName,
long time,
UINotificationGroup parentGroup,
int unreadObjects)
{
this(displayName, displayName, time, parentGroup, 1);
}
/**
* Creates an instance of <tt>UINotification</tt> by specifying the
* notification name and time.
*
* notification belongs
* @param name the notification name
* @param displayName the name associated to this notification
* @param time the time in milliseconds when the notification was received
* @param parentGroup the group of notifications, to which this notification
* belongs
* @param unreadObjects number of unread objects for this notification.
*/
public UINotification( String name,
String displayName,
long time,
UINotificationGroup parentGroup,
int unreadObjects)
{
this.notificationName = name;
this.notificationDisplayName = displayName;
this.notificationTime = time;
this.parentGroup = parentGroup;
this.unreadObjects = unreadObjects;
}
/**
* Returns the name associated with this notification.
*
* @return the name associated with this notification
*/
public String getDisplayName()
{
return notificationDisplayName;
}
/**
* Returns the time in milliseconds the notification was received.
*
* @return the time in milliseconds the notification was received
*/
public long getTime()
{
return notificationTime;
}
/**
* Returns the parent notification group.
*
* @return the parent notification group
*/
public UINotificationGroup getGroup()
{
return parentGroup;
}
/**
* Returns the number of unread objects for this notification.
* @return
*/
public int getUnreadObjects()
{<FILL_FUNCTION_BODY>}
@Override
public boolean equals(Object o)
{
if(this == o)
return true;
if(o == null || getClass() != o.getClass())
return false;
UINotification that = (UINotification) o;
if(notificationName != null ?
!notificationName.equals(that.notificationName)
: that.notificationName != null)
return false;
if(parentGroup != null ?
!parentGroup.equals(that.parentGroup)
: that.parentGroup != null)
return false;
return true;
}
@Override
public int hashCode()
{
return Objects.hash(notificationName, parentGroup);
}
}
|
return unreadObjects;
| 1,095 | 10 | 1,105 | 26,465 |
TheAlgorithms_Java
|
Java/src/main/java/com/thealgorithms/maths/PerfectSquare.java
|
PerfectSquare
|
isPerfectSquare
|
class PerfectSquare {
private PerfectSquare() {
}
/**
* Check if a number is perfect square number
*
* @param number the number to be checked
* @return <tt>true</tt> if {@code number} is perfect square, otherwise
* <tt>false</tt>
*/
public static boolean isPerfectSquare(final int number) {<FILL_FUNCTION_BODY>}
}
|
final int sqrt = (int) Math.sqrt(number);
return sqrt * sqrt == number;
| 113 | 30 | 143 | 63,500 |
javamelody_javamelody
|
javamelody/javamelody-core/src/main/java/net/bull/javamelody/internal/common/InputOutput.java
|
InputOutput
|
pumpToString
|
class InputOutput {
private InputOutput() {
super();
}
public static void pump(InputStream input, OutputStream output) throws IOException {
final byte[] bytes = new byte[4 * 1024];
int length = input.read(bytes);
while (length != -1) {
output.write(bytes, 0, length);
length = input.read(bytes);
}
}
public static byte[] pumpToByteArray(InputStream input) throws IOException {
final ByteArrayOutputStream out = new ByteArrayOutputStream();
pump(input, out);
return out.toByteArray();
}
public static String pumpToString(InputStream input, Charset charset) throws IOException {<FILL_FUNCTION_BODY>}
public static void pumpToFile(InputStream input, File file) throws IOException {
try (OutputStream output = new FileOutputStream(file)) {
pump(input, output);
}
}
public static void pumpFromFile(File file, OutputStream output) throws IOException {
try (FileInputStream in = new FileInputStream(file)) {
pump(in, output);
}
}
public static void zipFile(File source, File target) throws IOException {
final FileOutputStream fos = new FileOutputStream(target);
try (ZipOutputStream zos = new ZipOutputStream(fos)) {
final ZipEntry ze = new ZipEntry(source.getName());
zos.putNextEntry(ze);
pumpFromFile(source, zos);
zos.closeEntry();
}
}
public static boolean deleteFile(File file) {
return file.delete();
}
public static void copyFile(File source, File target) throws IOException {
try (FileInputStream in = new FileInputStream(source);
FileOutputStream out = new FileOutputStream(target)) {
pump(in, out);
}
}
}
|
final ByteArrayOutputStream out = new ByteArrayOutputStream();
pump(input, out);
return out.toString(charset.name());
| 474 | 38 | 512 | 24,055 |
qiurunze123_miaosha
|
miaosha/miaosha-admin/miaosha-admin-web/src/main/java/com/geekq/web/interceptor/AddGlobalUtilInterceptor.java
|
AddGlobalUtilInterceptor
|
postHandle
|
class AddGlobalUtilInterceptor extends HandlerInterceptorAdapter {
@Autowired
private SystemDictionaryUtil systemDicUtil;
@Override
public void postHandle(HttpServletRequest request,
HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {<FILL_FUNCTION_BODY>}
}
|
if (modelAndView != null) {
modelAndView.addObject("_DicUtil", systemDicUtil);
}
super.postHandle(request, response, handler, modelAndView);
| 88 | 54 | 142 | 60,806 |
noear_solon
|
solon/solon-projects/solon-security/solon.vault/src/main/java/org/noear/solon/vault/VaultUtils.java
|
VaultUtils
|
decrypt
|
class VaultUtils {
public static final String TAG_PREFIX = "ENC(";
public static final String TAG_SUFFIX = ")";
static VaultCoder guardCoder = new AesVaultCoder();
static {
//尝试从容器中获取
Solon.context().getBeanAsync(VaultCoder.class, bean -> {
guardCoder = bean;
});
}
/**
* 是否已加密
*/
public static boolean isEncrypted(String str) {
if (str == null) {
return false;
} else {
return str.startsWith(TAG_PREFIX) && str.endsWith(TAG_SUFFIX);
}
}
/**
* 加密
*/
public static String encrypt(String str) {
if (Utils.isEmpty(str)) {
return str;
}
try {
String tmp = guardCoder.encrypt(str);
return TAG_PREFIX + tmp + TAG_SUFFIX;
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
/**
* 解密
*/
public static String decrypt(String str) {<FILL_FUNCTION_BODY>}
/**
* 警惕处理
* */
public static String guard(String str) {
if (VaultUtils.isEncrypted(str)) {
return VaultUtils.decrypt(str);
} else {
return str;
}
}
/**
* 警惕处理
* */
public static Properties guard(Properties props) {
props.forEach((k, v) -> {
if (v instanceof String) {
String val = (String) v;
if (VaultUtils.isEncrypted(val)) {
String val2 = VaultUtils.decrypt(val);
props.put(k, val2);
}
}
});
return props;
}
}
|
if (Utils.isEmpty(str)) {
return str;
}
try {
str = str.substring(TAG_PREFIX.length(), str.length() - TAG_SUFFIX.length());
return guardCoder.decrypt(str);
} catch (Throwable e) {
throw new RuntimeException(e);
}
| 521 | 91 | 612 | 33,597 |
pmd_pmd
|
pmd/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/design/NPathComplexityRule.java
|
NPathComplexityRule
|
visitMethod
|
class NPathComplexityRule extends AbstractJavaRulechainRule {
private static final PropertyDescriptor<Integer> REPORT_LEVEL_DESCRIPTOR
= PropertyFactory.intProperty("reportLevel").desc("N-Path Complexity reporting threshold")
.require(positive()).defaultValue(200).build();
public NPathComplexityRule() {
super(ASTExecutableDeclaration.class);
definePropertyDescriptor(REPORT_LEVEL_DESCRIPTOR);
}
@Override
public Object visitJavaNode(JavaNode node, Object data) {
return visitMethod((ASTExecutableDeclaration) node, (RuleContext) data);
}
private Object visitMethod(ASTExecutableDeclaration node, RuleContext data) {<FILL_FUNCTION_BODY>}
}
|
int reportLevel = getProperty(REPORT_LEVEL_DESCRIPTOR);
if (!JavaMetrics.NPATH.supports(node)) {
return data;
}
BigInteger npath = MetricsUtil.computeMetric(JavaMetrics.NPATH, node);
if (npath.compareTo(BigInteger.valueOf(reportLevel)) >= 0) {
asCtx(data).addViolation(node, new String[] {node instanceof ASTMethodDeclaration ? "method" : "constructor",
PrettyPrintingUtil.displaySignature(node),
String.valueOf(npath),
String.valueOf(reportLevel)});
}
return data;
| 193 | 172 | 365 | 38,461 |
YunaiV_ruoyi-vue-pro
|
ruoyi-vue-pro/yudao-framework/yudao-spring-boot-starter-mq/src/main/java/cn/iocoder/yudao/framework/mq/redis/core/pubsub/AbstractRedisChannelMessageListener.java
|
AbstractRedisChannelMessageListener
|
onMessage
|
class AbstractRedisChannelMessageListener<T extends AbstractRedisChannelMessage> implements MessageListener {
/**
* 消息类型
*/
private final Class<T> messageType;
/**
* Redis Channel
*/
private final String channel;
/**
* RedisMQTemplate
*/
@Setter
private RedisMQTemplate redisMQTemplate;
@SneakyThrows
protected AbstractRedisChannelMessageListener() {
this.messageType = getMessageClass();
this.channel = messageType.getDeclaredConstructor().newInstance().getChannel();
}
/**
* 获得 Sub 订阅的 Redis Channel 通道
*
* @return channel
*/
public final String getChannel() {
return channel;
}
@Override
public final void onMessage(Message message, byte[] bytes) {<FILL_FUNCTION_BODY>}
/**
* 处理消息
*
* @param message 消息
*/
public abstract void onMessage(T message);
/**
* 通过解析类上的泛型,获得消息类型
*
* @return 消息类型
*/
@SuppressWarnings("unchecked")
private Class<T> getMessageClass() {
Type type = TypeUtil.getTypeArgument(getClass(), 0);
if (type == null) {
throw new IllegalStateException(String.format("类型(%s) 需要设置消息类型", getClass().getName()));
}
return (Class<T>) type;
}
private void consumeMessageBefore(AbstractRedisMessage message) {
assert redisMQTemplate != null;
List<RedisMessageInterceptor> interceptors = redisMQTemplate.getInterceptors();
// 正序
interceptors.forEach(interceptor -> interceptor.consumeMessageBefore(message));
}
private void consumeMessageAfter(AbstractRedisMessage message) {
assert redisMQTemplate != null;
List<RedisMessageInterceptor> interceptors = redisMQTemplate.getInterceptors();
// 倒序
for (int i = interceptors.size() - 1; i >= 0; i--) {
interceptors.get(i).consumeMessageAfter(message);
}
}
}
|
T messageObj = JsonUtils.parseObject(message.getBody(), messageType);
try {
consumeMessageBefore(messageObj);
// 消费消息
this.onMessage(messageObj);
} finally {
consumeMessageAfter(messageObj);
}
| 594 | 69 | 663 | 4,375 |
igniterealtime_Openfire
|
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/security/SecurityAuditManager.java
|
SecurityAuditManagerContainer
|
getSecurityAuditProvider
|
class SecurityAuditManagerContainer {
private static SecurityAuditManager instance = new SecurityAuditManager();
}
/**
* Returns the currently-installed SecurityAuditProvider. <b>Warning:</b> in virtually all
* cases the security audit provider should not be used directly. Instead, the appropriate
* methods in SecurityAuditManager should be called. Direct access to the security audit
* provider is only provided for special-case logic.
*
* @return the current SecurityAuditProvider.
*/
public static SecurityAuditProvider getSecurityAuditProvider() {<FILL_FUNCTION_BODY>
|
return SecurityAuditManagerContainer.instance.provider;
| 158 | 17 | 175 | 23,396 |
apache_pdfbox
|
pdfbox/xmpbox/src/main/java/org/apache/xmpbox/type/ArrayProperty.java
|
ArrayProperty
|
getElementsAsString
|
class ArrayProperty extends AbstractComplexProperty
{
private final Cardinality arrayType;
private final String namespace;
private final String prefix;
/**
* Constructor of a complex property
*
* @param metadata
* The metadata to attach to this property
* @param namespace
* The namespace URI to associate to this property
* @param prefix
* The prefix to set for this property
* @param propertyName
* The local Name of this property
* @param type
* type of complexProperty (Bag, Seq, Alt)
*/
public ArrayProperty(XMPMetadata metadata, String namespace, String prefix, String propertyName, Cardinality type)
{
super(metadata, propertyName);
this.arrayType = type;
this.namespace = namespace;
this.prefix = prefix;
}
public Cardinality getArrayType()
{
return arrayType;
}
public List<String> getElementsAsString()
{<FILL_FUNCTION_BODY>}
/**
* Get the namespace URI of this entity
*
* @return the namespace URI
*/
@Override
public final String getNamespace()
{
return namespace;
}
/**
* Get the prefix of this entity
*
* @return the prefix specified
*/
@Override
public String getPrefix()
{
return prefix;
}
}
|
List<AbstractField> allProperties = getContainer().getAllProperties();
List<String> retval = new ArrayList<>(allProperties.size());
allProperties.forEach(tmp -> retval.add(((AbstractSimpleProperty) tmp).getStringValue()));
return Collections.unmodifiableList(retval);
| 372 | 77 | 449 | 12,428 |
pmd_pmd
|
pmd/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTDoStatement.java
|
ASTDoStatement
|
acceptVisitor
|
class ASTDoStatement extends AbstractStatement implements ASTLoopStatement {
ASTDoStatement(int id) {
super(id);
}
/**
* Returns the node that represents the guard of this loop.
* This may be any expression of type boolean.
*/
@Override
public ASTExpression getCondition() {
return (ASTExpression) getChild(1);
}
/**
* Returns the statement that will be run while the guard
* evaluates to true.
*/
@Override
public ASTStatement getBody() {
return (ASTStatement) getChild(0);
}
@Override
public <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) {<FILL_FUNCTION_BODY>}
}
|
return visitor.visit(this, data);
| 208 | 15 | 223 | 37,966 |
weibocom_motan
|
motan/motan-extension/protocol-extension/motan-protocol-restful/src/main/java/com/weibo/api/motan/protocol/restful/support/servlet/RestfulServletContainerListener.java
|
RestfulServletContainerListener
|
contextInitialized
|
class RestfulServletContainerListener extends ResteasyBootstrap implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {<FILL_FUNCTION_BODY>}
@Override
public void contextDestroyed(ServletContextEvent sce) {
super.contextDestroyed(sce);
}
}
|
ServletContext servletContext = sce.getServletContext();
servletContext.setInitParameter("resteasy.injector.factory", RestfulInjectorFactory.class.getName());
servletContext.setInitParameter(ResteasyContextParameters.RESTEASY_PROVIDERS,
RpcExceptionMapper.class.getName());
super.contextInitialized(sce);
ServletRestServer.setResteasyDeployment(deployment);
| 90 | 118 | 208 | 47,042 |
perwendel_spark
|
spark/src/main/java/spark/embeddedserver/NotSupportedException.java
|
NotSupportedException
|
raise
|
class NotSupportedException extends RuntimeException {
private static final long serialVersionUID = 1L;
/**
* Raises a NotSupportedException for the provided class name and feature name.
*
* @param clazz the class name
* @param feature the feature name
*/
public static void raise(String clazz, String feature) {<FILL_FUNCTION_BODY>}
private NotSupportedException(String clazz, String feature) {
super("'" + clazz + "' doesn't support '" + feature + "'");
}
}
|
throw new NotSupportedException(clazz, feature);
| 144 | 17 | 161 | 60,703 |
crate_crate
|
crate/server/src/main/java/io/crate/execution/engine/distribution/merge/BatchPagingIterator.java
|
BatchPagingIterator
|
raiseIfClosedOrKilled
|
class BatchPagingIterator<Key> implements BatchIterator<Row> {
private final PagingIterator<Key, Row> pagingIterator;
private final Function<Key, KillableCompletionStage<? extends Iterable<? extends KeyIterable<Key, Row>>>> fetchMore;
private final BooleanSupplier isUpstreamExhausted;
private final Consumer<? super Throwable> closeCallback;
private Throwable killed;
private KillableCompletionStage<? extends Iterable<? extends KeyIterable<Key, Row>>> currentlyLoading;
private Iterator<Row> it;
private boolean closed = false;
private Row current;
public BatchPagingIterator(PagingIterator<Key, Row> pagingIterator,
Function<Key, KillableCompletionStage<? extends Iterable<? extends KeyIterable<Key, Row>>>> fetchMore,
BooleanSupplier isUpstreamExhausted,
Consumer<? super Throwable> closeCallback) {
this.pagingIterator = pagingIterator;
this.it = pagingIterator;
this.fetchMore = fetchMore;
this.isUpstreamExhausted = isUpstreamExhausted;
this.closeCallback = closeCallback;
}
@Override
public Row currentElement() {
return current;
}
@Override
public void moveToStart() {
raiseIfClosedOrKilled();
this.it = pagingIterator.repeat().iterator();
current = null;
}
@Override
public boolean moveNext() {
raiseIfClosedOrKilled();
if (it.hasNext()) {
current = it.next();
return true;
}
current = null;
return false;
}
@Override
public void close() {
if (!closed) {
closed = true;
pagingIterator.finish(); // release resource, specially possible ram accounted bytes
closeCallback.accept(killed);
}
}
@Override
public CompletionStage<?> loadNextBatch() throws Exception {
if (closed) {
throw new IllegalStateException("BatchIterator already closed");
}
if (allLoaded()) {
throw new IllegalStateException("All data already loaded");
}
Throwable err;
KillableCompletionStage<? extends Iterable<? extends KeyIterable<Key, Row>>> future;
synchronized (this) {
err = this.killed;
if (err == null) {
currentlyLoading = future = fetchMore.apply(pagingIterator.exhaustedIterable());
} else {
future = KillableCompletionStage.failed(err);
}
}
if (err == null) {
return future.whenComplete(this::onNextPage);
}
return future;
}
private void onNextPage(Iterable<? extends KeyIterable<Key, Row>> rows, Throwable ex) {
if (ex == null) {
pagingIterator.merge(rows);
if (isUpstreamExhausted.getAsBoolean()) {
pagingIterator.finish();
}
} else {
killed = ex;
throw Exceptions.toRuntimeException(ex);
}
}
@Override
public boolean allLoaded() {
return isUpstreamExhausted.getAsBoolean();
}
@Override
public boolean hasLazyResultSet() {
return true;
}
private void raiseIfClosedOrKilled() {<FILL_FUNCTION_BODY>}
@Override
public void kill(@NotNull Throwable throwable) {
KillableCompletionStage<? extends Iterable<? extends KeyIterable<Key, Row>>> loading;
synchronized (this) {
killed = throwable;
loading = this.currentlyLoading;
}
close();
if (loading != null) {
loading.kill(throwable);
}
}
}
|
Throwable err;
synchronized (this) {
err = killed;
}
if (err != null) {
Exceptions.rethrowUnchecked(err);
}
if (closed) {
throw new IllegalStateException("Iterator is closed");
}
| 1,004 | 75 | 1,079 | 15,733 |
mapstruct_mapstruct
|
mapstruct/processor/src/main/java/org/mapstruct/ap/internal/model/source/IterableMappingOptions.java
|
IterableMappingOptions
|
isConsistent
|
class IterableMappingOptions extends DelegatingOptions {
private final SelectionParameters selectionParameters;
private final FormattingParameters formattingParameters;
private final IterableMappingGem iterableMapping;
public static IterableMappingOptions fromGem(IterableMappingGem iterableMapping,
MapperOptions mapperOptions, ExecutableElement method,
FormattingMessager messager, TypeUtils typeUtils) {
if ( iterableMapping == null || !isConsistent( iterableMapping, method, messager ) ) {
IterableMappingOptions options = new IterableMappingOptions( null, null, null, mapperOptions );
return options;
}
SelectionParameters selection = new SelectionParameters(
iterableMapping.qualifiedBy().get(),
iterableMapping.qualifiedByName().get(),
iterableMapping.elementTargetType().getValue(),
typeUtils
);
FormattingParameters formatting = new FormattingParameters(
iterableMapping.dateFormat().get(),
iterableMapping.numberFormat().get(),
iterableMapping.mirror(),
iterableMapping.dateFormat().getAnnotationValue(),
method
);
IterableMappingOptions options =
new IterableMappingOptions( formatting, selection, iterableMapping, mapperOptions );
return options;
}
private static boolean isConsistent(IterableMappingGem gem, ExecutableElement method,
FormattingMessager messager) {<FILL_FUNCTION_BODY>}
private IterableMappingOptions(FormattingParameters formattingParameters, SelectionParameters selectionParameters,
IterableMappingGem iterableMapping,
DelegatingOptions next) {
super( next );
this.formattingParameters = formattingParameters;
this.selectionParameters = selectionParameters;
this.iterableMapping = iterableMapping;
}
public SelectionParameters getSelectionParameters() {
return selectionParameters;
}
public FormattingParameters getFormattingParameters() {
return formattingParameters;
}
public AnnotationMirror getMirror() {
return Optional.ofNullable( iterableMapping ).map( IterableMappingGem::mirror ).orElse( null );
}
@Override
public NullValueMappingStrategyGem getNullValueMappingStrategy() {
return Optional.ofNullable( iterableMapping ).map( IterableMappingGem::nullValueMappingStrategy )
.filter( GemValue::hasValue )
.map( GemValue::getValue )
.map( NullValueMappingStrategyGem::valueOf )
.orElse( next().getNullValueIterableMappingStrategy() );
}
public MappingControl getElementMappingControl(ElementUtils elementUtils) {
return Optional.ofNullable( iterableMapping ).map( IterableMappingGem::elementMappingControl )
.filter( GemValue::hasValue )
.map( GemValue::getValue )
.map( mc -> MappingControl.fromTypeMirror( mc, elementUtils ) )
.orElse( next().getMappingControl( elementUtils ) );
}
@Override
public boolean hasAnnotation() {
return iterableMapping != null;
}
}
|
if ( !gem.dateFormat().hasValue()
&& !gem.numberFormat().hasValue()
&& !gem.qualifiedBy().hasValue()
&& !gem.qualifiedByName().hasValue()
&& !gem.elementTargetType().hasValue()
&& !gem.nullValueMappingStrategy().hasValue() ) {
messager.printMessage( method, Message.ITERABLEMAPPING_NO_ELEMENTS );
return false;
}
return true;
| 785 | 128 | 913 | 32,049 |
dropwizard_dropwizard
|
dropwizard/dropwizard-example/src/main/java/com/example/helloworld/HelloWorldApplication.java
|
HelloWorldApplication
|
initialize
|
class HelloWorldApplication extends Application<HelloWorldConfiguration> {
public static void main(String[] args) throws Exception {
new HelloWorldApplication().run(args);
}
private final HibernateBundle<HelloWorldConfiguration> hibernateBundle =
new HibernateBundle<HelloWorldConfiguration>(Person.class) {
@Override
public DataSourceFactory getDataSourceFactory(HelloWorldConfiguration configuration) {
return configuration.getDataSourceFactory();
}
};
@Override
public String getName() {
return "hello-world";
}
@Override
public void initialize(Bootstrap<HelloWorldConfiguration> bootstrap) {<FILL_FUNCTION_BODY>}
@Override
public void run(HelloWorldConfiguration configuration, Environment environment) {
final PersonDAO dao = new PersonDAO(hibernateBundle.getSessionFactory());
final Template template = configuration.buildTemplate();
environment.healthChecks().register("template", new TemplateHealthCheck(template));
environment.admin().addTask(new EchoTask());
environment.jersey().register(DateRequiredFeature.class);
environment.jersey().register(new AuthDynamicFeature(new BasicCredentialAuthFilter.Builder<User>()
.setAuthenticator(new ExampleAuthenticator())
.setAuthorizer(new ExampleAuthorizer())
.setRealm("SUPER SECRET STUFF")
.buildAuthFilter()));
environment.jersey().register(new AuthValueFactoryProvider.Binder<>(User.class));
environment.jersey().register(RolesAllowedDynamicFeature.class);
environment.jersey().register(new HelloWorldResource(template));
environment.jersey().register(new ViewResource());
environment.jersey().register(new ProtectedResource());
environment.jersey().register(new PeopleResource(dao));
environment.jersey().register(new PersonResource(dao));
environment.jersey().register(new FilteredResource());
}
}
|
// Enable variable substitution with environment variables
bootstrap.setConfigurationSourceProvider(
new SubstitutingSourceProvider(
bootstrap.getConfigurationSourceProvider(),
new EnvironmentVariableSubstitutor(false)
)
);
bootstrap.addCommand(new RenderCommand());
bootstrap.addBundle(new AssetsBundle());
bootstrap.addBundle(new MigrationsBundle<HelloWorldConfiguration>() {
@Override
public DataSourceFactory getDataSourceFactory(HelloWorldConfiguration configuration) {
return configuration.getDataSourceFactory();
}
});
bootstrap.addBundle(hibernateBundle);
bootstrap.addBundle(new ViewBundle<HelloWorldConfiguration>() {
@Override
public Map<String, Map<String, String>> getViewConfiguration(HelloWorldConfiguration configuration) {
return configuration.getViewRendererConfiguration();
}
});
| 500 | 217 | 717 | 70,082 |
subhra74_snowflake
|
snowflake/muon-app/src/main/java/muon/app/ui/components/session/PortForwardingPanel.java
|
PFTableModel
|
addOrEditEntry
|
class PFTableModel extends AbstractTableModel {
private String[] columns = { "Type", "Host", "Source Port", "Target Port", "Bind Host" };
private List<PortForwardingRule> list = new ArrayList<>();
@Override
public int getRowCount() {
return list.size();
}
@Override
public int getColumnCount() {
return columns.length;
}
@Override
public String getColumnName(int column) {
return columns[column];
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
PortForwardingRule pf = list.get(rowIndex);
switch (columnIndex) {
case 0:
return pf.getType();
case 1:
return pf.getHost();
case 2:
return pf.getSourcePort();
case 3:
return pf.getTargetPort();
case 4:
return pf.getBindHost();
}
return "";
}
private void setRules(List<PortForwardingRule> rules) {
list.clear();
if (rules != null) {
for (PortForwardingRule r : rules) {
list.add(r);
}
}
fireTableDataChanged();
}
private List<PortForwardingRule> getRules() {
return list;
}
private void addRule(PortForwardingRule r) {
this.list.add(r);
fireTableDataChanged();
}
private void refreshTable() {
fireTableDataChanged();
}
private void remove(int index) {
list.remove(index);
fireTableDataChanged();
}
private PortForwardingRule get(int index) {
return list.get(index);
}
}
private PortForwardingRule addOrEditEntry(PortForwardingRule r) {<FILL_FUNCTION_BODY>
|
JComboBox<String> cmbPFType = new JComboBox<String>(new String[] { "Local", "Remote" });
JTextField txtHost = new SkinnedTextField(30);
JSpinner spSourcePort = new JSpinner(new SpinnerNumberModel(0, 0, SessionInfoPanel.DEFAULT_MAX_PORT, 1));
JSpinner spTargetPort = new JSpinner(new SpinnerNumberModel(0, 0, SessionInfoPanel.DEFAULT_MAX_PORT, 1));
JTextField txtBindAddress = new SkinnedTextField(30);
txtBindAddress.setText("127.0.0.1");
if (r != null) {
txtHost.setText(r.getHost());
spSourcePort.setValue((Integer) r.getSourcePort());
spTargetPort.setValue((Integer) r.getTargetPort());
txtBindAddress.setText(r.getBindHost());
cmbPFType.setSelectedIndex(r.getType() == PortForwardingType.Local ? 0 : 1);
}
while (JOptionPane.showOptionDialog(this,
new Object[] { "Port forwarding type", cmbPFType, "Host", txtHost, "Source Port", spSourcePort,
"Target Port", spTargetPort, "Bind Address", txtBindAddress },
"Port forwarding rule", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, null,
null) == JOptionPane.OK_OPTION) {
String host = txtHost.getText();
int port1 = (Integer) spSourcePort.getValue();
int port2 = (Integer) spTargetPort.getValue();
String bindAddress = txtBindAddress.getText();
if (host.length() < 1 || bindAddress.length() < 1 || port1 <= 0 || port2 <= 0) {
JOptionPane.showMessageDialog(this, "Invalid input: all fields mandatory");
continue;
}
if (r == null) {
r = new PortForwardingRule();
}
r.setType(cmbPFType.getSelectedIndex() == 0 ? PortForwardingType.Local : PortForwardingType.Remote);
r.setHost(host);
r.setBindHost(bindAddress);
r.setSourcePort(port1);
r.setTargetPort(port2);
return r;
}
return null;
| 590 | 686 | 1,276 | 45,062 |
jitsi_jitsi
|
jitsi/modules/service/desktop/src/main/java/net/java/sip/communicator/impl/osdependent/systemtray/appindicator/AppIndicatorTrayIcon.java
|
PopupMenuPeer
|
componentRemoved
|
class PopupMenuPeer implements ContainerListener
{
public PopupMenuPeer(PopupMenuPeer parent, Component em)
{
menuItem = em;
// if this menu item is a submenu, add ourselves as listener to
// add or remove the native counterpart
if (em instanceof JMenu)
{
((JMenu)em).getPopupMenu().addContainerListener(this);
((JMenu)em).addContainerListener(this);
}
}
@Override
protected void finalize() throws Throwable
{
super.finalize();
if (isDefaultMenuItem)
{
gobject.g_object_unref(gtkMenuItem);
}
}
public List<PopupMenuPeer> children = new ArrayList<>();
public Pointer gtkMenuItem;
public Pointer gtkMenu;
public Pointer gtkImage;
public Memory gtkImageBuffer;
public Pointer gtkPixbuf;
public Component menuItem;
public MenuItemSignalHandler signalHandler;
public long gtkSignalHandler;
public boolean isDefaultMenuItem;
@Override
public void componentAdded(ContainerEvent e)
{
AppIndicatorTrayIcon.this.printMenu(popup.getComponents(), 1);
gtk.gdk_threads_enter();
try
{
createGtkMenuItems(this, new Component[]{e.getChild()});
gtk.gtk_widget_show_all(popupPeer.gtkMenu);
}
finally
{
gtk.gdk_threads_leave();
}
}
@Override
public void componentRemoved(ContainerEvent e)
{<FILL_FUNCTION_BODY>}
}
|
AppIndicatorTrayIcon.this.printMenu(popup.getComponents(), 1);
for (PopupMenuPeer c : children)
{
if (c.menuItem == e.getChild())
{
gtk.gdk_threads_enter();
try
{
cleanMenu(c);
}
finally
{
gtk.gdk_threads_leave();
}
children.remove(c);
break;
}
}
| 452 | 131 | 583 | 26,072 |
apache_shenyu
|
shenyu/shenyu-plugin/shenyu-plugin-proxy/shenyu-plugin-rpc/shenyu-plugin-grpc/src/main/java/org/apache/shenyu/plugin/grpc/loadbalance/picker/AbstractReadyPicker.java
|
AbstractReadyPicker
|
isEquivalentTo
|
class AbstractReadyPicker extends AbstractPicker implements Picker {
private final boolean hasIdleNode;
private final List<SubChannelCopy> list;
AbstractReadyPicker(final List<LoadBalancer.Subchannel> list) {
this.list = list.stream().map(SubChannelCopy::new).collect(Collectors.toList());
this.hasIdleNode = hasIdleNode();
}
private boolean hasIdleNode() {
return this.list.stream().anyMatch(r -> r.getState().getState() == ConnectivityState.IDLE
|| r.getState().getState() == ConnectivityState.CONNECTING);
}
@Override
public LoadBalancer.PickResult pickSubchannel(final LoadBalancer.PickSubchannelArgs args) {
final List<SubChannelCopy> list = getSubchannels();
if (CollectionUtils.isEmpty(list)) {
return getErrorPickResult();
}
SubChannelCopy channel = pick(list);
return Objects.isNull(channel) ? getErrorPickResult() : LoadBalancer.PickResult.withSubchannel(channel.getChannel());
}
/**
* Choose subChannel.
*
* @param list subChannel list
* @return result subChannel
*/
protected abstract SubChannelCopy pick(List<SubChannelCopy> list);
@Override
public List<SubChannelCopy> getSubchannels() {
return list.stream().filter(r -> r.getState().getState() == ConnectivityState.READY
&& Boolean.parseBoolean(r.getStatus())).collect(Collectors.toList());
}
private LoadBalancer.PickResult getErrorPickResult() {
if (hasIdleNode) {
return LoadBalancer.PickResult.withNoResult();
} else {
return LoadBalancer.PickResult.withError(
Status.UNAVAILABLE.withCause(new NoSuchElementException()).withDescription("can not find the subChannel")
);
}
}
@Override
public boolean isEquivalentTo(final AbstractPicker picker) {<FILL_FUNCTION_BODY>}
@Override
public String getSubchannelsInfo() {
final List<String> infos = this.list.stream().map(r -> "Subchannel"
+ "{ weight=" + r.getWeight()
+ ", readyState=\"" + r.getState().toString() + "\""
+ ", address=\"" + r.getChannel().getAddresses() + "\""
+ "}")
.collect(Collectors.toList());
return "[ " + String.join(",", infos) + " ]";
}
}
|
if (!(picker instanceof AbstractReadyPicker)) {
return false;
}
AbstractReadyPicker other = (AbstractReadyPicker) picker;
// the lists cannot contain duplicate subchannels
return other == this || (list.size() == other.list.size()
&& new HashSet<>(list).containsAll(other.list));
| 684 | 88 | 772 | 68,372 |
Nepxion_Discovery
|
Discovery/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/RestUtil.java
|
RestUtil
|
processParameter
|
class RestUtil {
public static HttpHeaders processHeader(HttpHeaders httpHeaders, Map<String, String> headerMap) {
if (MapUtils.isNotEmpty(headerMap)) {
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
httpHeaders.add(key, value);
}
}
return httpHeaders;
}
public static String processParameter(String url, Map<String, String> parameterMap) {<FILL_FUNCTION_BODY>}
public static HttpHeaders processCookie(HttpHeaders httpHeaders, Map<String, String> cookieMap) {
if (MapUtils.isNotEmpty(cookieMap)) {
List<String> cookieList = new ArrayList<String>();
for (Map.Entry<String, String> entry : cookieMap.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
cookieList.add(key + DiscoveryConstant.EQUALS + value);
}
httpHeaders.put(DiscoveryConstant.COOKIE_TYPE, cookieList);
}
return httpHeaders;
}
public static <T> T fromJson(RestTemplate restTemplate, String result, TypeReference<T> typeReference) {
try {
return JsonUtil.fromJson(result, typeReference);
} catch (Exception e) {
String error = getError(restTemplate);
if (StringUtils.isNotEmpty(error)) {
throw new IllegalArgumentException(error);
}
throw e;
}
}
public static String getError(RestTemplate restTemplate) {
ResponseErrorHandler responseErrorHandler = restTemplate.getErrorHandler();
if (responseErrorHandler instanceof DiscoveryResponseErrorHandler) {
DiscoveryResponseErrorHandler discoveryResponseErrorHandler = (DiscoveryResponseErrorHandler) responseErrorHandler;
return discoveryResponseErrorHandler.getError();
}
return null;
}
}
|
if (MapUtils.isNotEmpty(parameterMap)) {
StringBuilder parameterStringBuilder = new StringBuilder();
int index = 0;
for (Map.Entry<String, String> entry : parameterMap.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
parameterStringBuilder.append(key + DiscoveryConstant.EQUALS + value);
if (index < parameterMap.size() - 1) {
parameterStringBuilder.append("&");
}
index++;
}
String parameter = parameterStringBuilder.toString();
parameter = StringUtils.isNotEmpty(parameter) ? "?" + parameter : "";
url += parameter;
}
return url;
| 500 | 186 | 686 | 32,509 |
dropwizard_dropwizard
|
dropwizard/dropwizard-health/src/main/java/io/dropwizard/health/HealthCheckConfigValidator.java
|
HealthCheckConfigValidator
|
validateConfiguration
|
class HealthCheckConfigValidator implements Managed {
private static final Logger LOGGER = LoggerFactory.getLogger(HealthCheckConfigValidator.class);
private final List<HealthCheckConfiguration> configs;
private final HealthCheckRegistry registry;
public HealthCheckConfigValidator(List<HealthCheckConfiguration> configs, HealthCheckRegistry registry) {
this.configs = configs;
this.registry = registry;
}
@Override
public void start() throws Exception {
validateConfiguration(configs, registry.getNames());
}
private void validateConfiguration(final List<HealthCheckConfiguration> healthCheckConfigs,
final Set<String> registeredHealthCheckNames) {<FILL_FUNCTION_BODY>}
}
|
final Set<String> configuredHealthCheckNames = healthCheckConfigs.stream()
.map(HealthCheckConfiguration::getName)
.collect(Collectors.toSet());
// find health checks that are registered but do not have a configured schedule
final List<String> notConfiguredHealthCheckNames = registeredHealthCheckNames.stream()
.filter(healthCheckName -> !configuredHealthCheckNames.contains(healthCheckName))
.sorted()
.collect(Collectors.toList());
if (!notConfiguredHealthCheckNames.isEmpty()) {
final String healthCheckList = notConfiguredHealthCheckNames.stream()
.map(name -> " * " + name)
.collect(Collectors.joining("\n"));
LOGGER.info("The following health check(s) were registered, but are not configured with a schedule:\n{}",
healthCheckList);
}
// find health checks that are configured with a schedule but are not actually registered
final List<String> notRegisteredHealthCheckNames = configuredHealthCheckNames.stream()
.filter(healthCheckName -> !registeredHealthCheckNames.contains(healthCheckName))
.sorted()
.collect(Collectors.toList());
if (!notRegisteredHealthCheckNames.isEmpty()) {
final String healthCheckList = notRegisteredHealthCheckNames.stream()
.map(name -> " * " + name)
.collect(Collectors.joining("\n"));
LOGGER.error("The following health check(s) are configured with a schedule, but were not registered:\n{}",
healthCheckList);
throw new IllegalStateException("The following configured health checks were not registered: "
+ notRegisteredHealthCheckNames);
}
| 180 | 426 | 606 | 70,107 |
alibaba_easyexcel
|
easyexcel/easyexcel-core/src/main/java/com/alibaba/excel/util/BooleanUtils.java
|
BooleanUtils
|
isNotFalse
|
class BooleanUtils {
private static final String TRUE_NUMBER = "1";
private BooleanUtils() {}
/**
* String to boolean
*
* @param str
* @return
*/
public static Boolean valueOf(String str) {
if (TRUE_NUMBER.equals(str)) {
return Boolean.TRUE;
} else {
return Boolean.FALSE;
}
}
// boolean Boolean methods
//-----------------------------------------------------------------------
/**
* <p>Checks if a {@code Boolean} value is {@code true},
* handling {@code null} by returning {@code false}.</p>
*
* <pre>
* BooleanUtils.isTrue(Boolean.TRUE) = true
* BooleanUtils.isTrue(Boolean.FALSE) = false
* BooleanUtils.isTrue(null) = false
* </pre>
*
* @param bool the boolean to check, null returns {@code false}
* @return {@code true} only if the input is non-null and true
* @since 2.1
*/
public static boolean isTrue(final Boolean bool) {
return Boolean.TRUE.equals(bool);
}
/**
* <p>Checks if a {@code Boolean} value is <i>not</i> {@code true},
* handling {@code null} by returning {@code true}.</p>
*
* <pre>
* BooleanUtils.isNotTrue(Boolean.TRUE) = false
* BooleanUtils.isNotTrue(Boolean.FALSE) = true
* BooleanUtils.isNotTrue(null) = true
* </pre>
*
* @param bool the boolean to check, null returns {@code true}
* @return {@code true} if the input is null or false
* @since 2.3
*/
public static boolean isNotTrue(final Boolean bool) {
return !isTrue(bool);
}
/**
* <p>Checks if a {@code Boolean} value is {@code false},
* handling {@code null} by returning {@code false}.</p>
*
* <pre>
* BooleanUtils.isFalse(Boolean.TRUE) = false
* BooleanUtils.isFalse(Boolean.FALSE) = true
* BooleanUtils.isFalse(null) = false
* </pre>
*
* @param bool the boolean to check, null returns {@code false}
* @return {@code true} only if the input is non-null and false
* @since 2.1
*/
public static boolean isFalse(final Boolean bool) {
return Boolean.FALSE.equals(bool);
}
/**
* <p>Checks if a {@code Boolean} value is <i>not</i> {@code false},
* handling {@code null} by returning {@code true}.</p>
*
* <pre>
* BooleanUtils.isNotFalse(Boolean.TRUE) = true
* BooleanUtils.isNotFalse(Boolean.FALSE) = false
* BooleanUtils.isNotFalse(null) = true
* </pre>
*
* @param bool the boolean to check, null returns {@code true}
* @return {@code true} if the input is null or true
* @since 2.3
*/
public static boolean isNotFalse(final Boolean bool) {<FILL_FUNCTION_BODY>}
}
|
return !isFalse(bool);
| 871 | 12 | 883 | 50,888 |
pmd_pmd
|
pmd/pmd-gherkin/src/main/java/net/sourceforge/pmd/lang/gherkin/cpd/GherkinCpdLexer.java
|
GherkinCpdLexer
|
getLexerForSource
|
class GherkinCpdLexer extends AntlrCpdLexer {
@Override
protected Lexer getLexerForSource(CharStream charStream) {<FILL_FUNCTION_BODY>}
}
|
return new GherkinLexer(charStream);
| 57 | 17 | 74 | 38,230 |
zhkl0228_unidbg
|
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/NeedLibrary.java
|
NeedLibrary
|
toString
|
class NeedLibrary {
final String path;
final boolean upward;
final boolean weak;
NeedLibrary(String path, boolean upward, boolean weak) {
this.path = path;
this.upward = upward;
this.weak = weak;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return (upward ? '?' : '*') + path;
| 94 | 19 | 113 | 48,466 |
sofastack_sofa-bolt
|
sofa-bolt/src/main/java/com/alipay/remoting/rpc/HeartbeatHandler.java
|
HeartbeatHandler
|
userEventTriggered
|
class HeartbeatHandler extends ChannelDuplexHandler {
/**
*
* @see io.netty.channel.ChannelInboundHandlerAdapter#userEventTriggered(io.netty.channel.ChannelHandlerContext, java.lang.Object)
*/
@Override
public void userEventTriggered(final ChannelHandlerContext ctx, Object evt) throws Exception {<FILL_FUNCTION_BODY>}
}
|
if (evt instanceof IdleStateEvent) {
ProtocolCode protocolCode = ctx.channel().attr(Connection.PROTOCOL).get();
Protocol protocol = ProtocolManager.getProtocol(protocolCode);
protocol.getHeartbeatTrigger().heartbeatTriggered(ctx);
} else {
super.userEventTriggered(ctx, evt);
}
| 105 | 96 | 201 | 40,919 |
YunaiV_ruoyi-vue-pro
|
ruoyi-vue-pro/yudao-framework/yudao-spring-boot-starter-biz-tenant/src/main/java/cn/iocoder/yudao/framework/tenant/core/redis/TenantRedisCacheManager.java
|
TenantRedisCacheManager
|
getCache
|
class TenantRedisCacheManager extends TimeoutRedisCacheManager {
public TenantRedisCacheManager(RedisCacheWriter cacheWriter,
RedisCacheConfiguration defaultCacheConfiguration) {
super(cacheWriter, defaultCacheConfiguration);
}
@Override
public Cache getCache(String name) {<FILL_FUNCTION_BODY>}
}
|
// 如果开启多租户,则 name 拼接租户后缀
if (!TenantContextHolder.isIgnore()
&& TenantContextHolder.getTenantId() != null) {
name = name + ":" + TenantContextHolder.getTenantId();
}
// 继续基于父方法
return super.getCache(name);
| 90 | 94 | 184 | 4,345 |
apache_incubator-seata
|
incubator-seata/rm-datasource/src/main/java/org/apache/seata/rm/datasource/sql/struct/cache/MariadbTableMetaCache.java
|
MariadbTableMetaCache
|
fetchSchema
|
class MariadbTableMetaCache extends MysqlTableMetaCache {
@Override
protected TableMeta fetchSchema(Connection connection, String tableName) throws SQLException {<FILL_FUNCTION_BODY>}
}
|
String sql = "SELECT * FROM " + ColumnUtils.addEscape(tableName, JdbcConstants.MARIADB) + " LIMIT 1";
try (Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(sql)) {
return resultSetMetaToSchema(rs.getMetaData(), connection.getMetaData());
} catch (SQLException sqlEx) {
throw sqlEx;
} catch (Exception e) {
throw new SQLException(String.format("Failed to fetch schema of %s", tableName), e);
}
| 55 | 142 | 197 | 52,011 |
google_jimfs
|
jimfs/jimfs/src/main/java/com/google/common/jimfs/PathType.java
|
PathType
|
appendToRegex
|
class PathType {
/**
* Returns a Unix-style path type. "/" is both the root and the only separator. Any path starting
* with "/" is considered absolute. The nul character ('\0') is disallowed in paths.
*/
public static PathType unix() {
return UnixPathType.INSTANCE;
}
/**
* Returns a Windows-style path type. The canonical separator character is "\". "/" is also
* treated as a separator when parsing paths.
*
* <p>As much as possible, this implementation follows the information provided in <a
* href="http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx">this
* article</a>. Paths with drive-letter roots (e.g. "C:\") and paths with UNC roots (e.g.
* "\\host\share\") are supported.
*
* <p>Two Windows path features are not currently supported as they are too Windows-specific:
*
* <ul>
* <li>Relative paths containing a drive-letter root, for example "C:" or "C:foo\bar". Such
* paths have a root component and optionally have names, but are <i>relative</i> paths,
* relative to the working directory of the drive identified by the root.
* <li>Absolute paths with no root, for example "\foo\bar". Such paths are absolute paths on the
* current drive.
* </ul>
*/
public static PathType windows() {
return WindowsPathType.INSTANCE;
}
private final boolean allowsMultipleRoots;
private final String separator;
private final String otherSeparators;
private final Joiner joiner;
private final Splitter splitter;
protected PathType(boolean allowsMultipleRoots, char separator, char... otherSeparators) {
this.separator = String.valueOf(separator);
this.allowsMultipleRoots = allowsMultipleRoots;
this.otherSeparators = String.valueOf(otherSeparators);
this.joiner = Joiner.on(separator);
this.splitter = createSplitter(separator, otherSeparators);
}
private static final char[] regexReservedChars = "^$.?+*\\[]{}()".toCharArray();
static {
Arrays.sort(regexReservedChars);
}
private static boolean isRegexReserved(char c) {
return Arrays.binarySearch(regexReservedChars, c) >= 0;
}
private static Splitter createSplitter(char separator, char... otherSeparators) {
if (otherSeparators.length == 0) {
return Splitter.on(separator).omitEmptyStrings();
}
// TODO(cgdecker): When CharMatcher is out of @Beta, us Splitter.on(CharMatcher)
StringBuilder patternBuilder = new StringBuilder();
patternBuilder.append("[");
appendToRegex(separator, patternBuilder);
for (char other : otherSeparators) {
appendToRegex(other, patternBuilder);
}
patternBuilder.append("]");
return Splitter.onPattern(patternBuilder.toString()).omitEmptyStrings();
}
private static void appendToRegex(char separator, StringBuilder patternBuilder) {<FILL_FUNCTION_BODY>}
/** Returns whether or not this type of path allows multiple root directories. */
public final boolean allowsMultipleRoots() {
return allowsMultipleRoots;
}
/**
* Returns the canonical separator for this path type. The returned string always has a length of
* one.
*/
public final String getSeparator() {
return separator;
}
/**
* Returns the other separators that are recognized when parsing a path. If no other separators
* are recognized, the empty string is returned.
*/
public final String getOtherSeparators() {
return otherSeparators;
}
/** Returns the path joiner for this path type. */
public final Joiner joiner() {
return joiner;
}
/** Returns the path splitter for this path type. */
public final Splitter splitter() {
return splitter;
}
/** Returns an empty path. */
protected final ParseResult emptyPath() {
return new ParseResult(null, ImmutableList.of(""));
}
/**
* Parses the given strings as a path.
*
* @throws InvalidPathException if the path isn't valid for this path type
*/
public abstract ParseResult parsePath(String path);
@Override
public String toString() {
return getClass().getSimpleName();
}
/** Returns the string form of the given path. */
public abstract String toString(@Nullable String root, Iterable<String> names);
/**
* Returns the string form of the given path for use in the path part of a URI. The root element
* is not nullable as the path must be absolute. The elements of the returned path <i>do not</i>
* need to be escaped. The {@code directory} boolean indicates whether the file the URI is for is
* known to be a directory.
*/
protected abstract String toUriPath(String root, Iterable<String> names, boolean directory);
/**
* Parses a path from the given URI path.
*
* @throws InvalidPathException if the given path isn't valid for this path type
*/
protected abstract ParseResult parseUriPath(String uriPath);
/**
* Creates a URI for the path with the given root and names in the file system with the given URI.
*/
public final URI toUri(
URI fileSystemUri, String root, Iterable<String> names, boolean directory) {
String path = toUriPath(root, names, directory);
try {
// it should not suck this much to create a new URI that's the same except with a path set =(
// need to do it this way for automatic path escaping
return new URI(
fileSystemUri.getScheme(),
fileSystemUri.getUserInfo(),
fileSystemUri.getHost(),
fileSystemUri.getPort(),
path,
null,
null);
} catch (URISyntaxException e) {
throw new AssertionError(e);
}
}
/** Parses a path from the given URI. */
public final ParseResult fromUri(URI uri) {
return parseUriPath(uri.getPath());
}
/** Simple result of parsing a path. */
public static final class ParseResult {
private final @Nullable String root;
private final Iterable<String> names;
public ParseResult(@Nullable String root, Iterable<String> names) {
this.root = root;
this.names = checkNotNull(names);
}
/** Returns whether or not this result is an absolute path. */
public boolean isAbsolute() {
return root != null;
}
/** Returns whether or not this result represents a root path. */
public boolean isRoot() {
return root != null && Iterables.isEmpty(names);
}
/** Returns the parsed root element, or null if there was no root. */
public @Nullable String root() {
return root;
}
/** Returns the parsed name elements. */
public Iterable<String> names() {
return names;
}
}
}
|
if (isRegexReserved(separator)) {
patternBuilder.append("\\");
}
patternBuilder.append(separator);
| 1,919 | 39 | 1,958 | 20,796 |
fabric8io_kubernetes-client
|
kubernetes-client/kubernetes-examples/src/main/java/io/fabric8/kubernetes/examples/kubectl/equivalents/DownloadFileFromPod.java
|
DownloadFileFromPod
|
main
|
class DownloadFileFromPod {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
try (KubernetesClient client = new KubernetesClientBuilder().build()) {
// Path Where to copy file to local storage
Path downloadToPath = new File("/home/rohaan/Downloads/test-1.0.0-runner.jar").toPath();
// Using Kubernetes Client to copy file from pod
client.pods()
.inNamespace("default") // <- Namespace of pod
.withName("my-pod") // <- Name of pod
.file("/tmp/test-1.0.0-runner.jar") // <- Path of file inside pod
.copy(downloadToPath); // <- Local path where to copy downloaded file
}
| 33 | 168 | 201 | 18,974 |
apache_incubator-seata
|
incubator-seata/saga/seata-saga-processctrl/src/main/java/org/apache/seata/saga/proctrl/eventing/impl/AsyncEventBus.java
|
AsyncEventBus
|
offer
|
class AsyncEventBus extends AbstractEventBus<ProcessContext> {
private static final Logger LOGGER = LoggerFactory.getLogger(AsyncEventBus.class);
private ThreadPoolExecutor threadPoolExecutor;
@Override
public boolean offer(ProcessContext context) throws FrameworkException {<FILL_FUNCTION_BODY>}
public void setThreadPoolExecutor(ThreadPoolExecutor threadPoolExecutor) {
this.threadPoolExecutor = threadPoolExecutor;
}
}
|
List<EventConsumer> eventConsumers = getEventConsumers(context.getClass());
if (CollectionUtils.isEmpty(eventConsumers)) {
if (LOGGER.isWarnEnabled()) {
LOGGER.warn("cannot find event handler by class: " + context.getClass());
}
return false;
}
for (EventConsumer eventConsumer : eventConsumers) {
threadPoolExecutor.execute(() -> eventConsumer.process(context));
}
return true;
| 117 | 127 | 244 | 52,488 |
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/pagemem/wal/record/delta/MergeRecord.java
|
MergeRecord
|
type
|
class MergeRecord<L> extends PageDeltaRecord {
/** */
@GridToStringExclude
private long prntId;
/** */
@GridToStringExclude
private long rightId;
/** */
private int prntIdx;
/** */
private boolean emptyBranch;
/**
* @param grpId Cache group ID.
* @param pageId Page ID.
* @param prntId Parent ID.
* @param prntIdx Index in parent page.
* @param rightId Right ID.
* @param emptyBranch We are merging empty branch.
*/
public MergeRecord(int grpId, long pageId, long prntId, int prntIdx, long rightId, boolean emptyBranch) {
super(grpId, pageId);
this.prntId = prntId;
this.rightId = rightId;
this.prntIdx = prntIdx;
this.emptyBranch = emptyBranch;
throw new IgniteException("Merge record should not be used directly (see GG-11640). " +
"Clear the database directory and restart the node.");
}
/** {@inheritDoc} */
@Override public void applyDelta(PageMemory pageMem, long pageAddr) throws IgniteCheckedException {
throw new IgniteCheckedException("Merge record should not be logged.");
}
/** {@inheritDoc} */
@Override public RecordType type() {<FILL_FUNCTION_BODY>}
/** */
public long parentId() {
return prntId;
}
/** */
public int parentIndex() {
return prntIdx;
}
/** */
public long rightId() {
return rightId;
}
/** */
public boolean isEmptyBranch() {
return emptyBranch;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(MergeRecord.class, this, "prntId", U.hexLong(prntId), "rightId", U.hexLong(rightId),
"super", super.toString());
}
}
|
return RecordType.BTREE_PAGE_MERGE;
| 554 | 19 | 573 | 7,817 |
apache_maven
|
maven/maven-model-builder/src/main/java/org/apache/maven/model/building/FilterModelBuildingRequest.java
|
FilterModelBuildingRequest
|
setRootDirectory
|
class FilterModelBuildingRequest implements ModelBuildingRequest {
protected ModelBuildingRequest request;
FilterModelBuildingRequest(ModelBuildingRequest request) {
this.request = request;
}
@Deprecated
@Override
public File getPomFile() {
return request.getPomFile();
}
@Override
public Path getPomPath() {
return request.getPomPath();
}
@Deprecated
@Override
public ModelBuildingRequest setPomFile(File pomFile) {
request.setPomFile(pomFile);
return this;
}
@Override
public FilterModelBuildingRequest setPomPath(Path pomPath) {
request.setPomPath(pomPath);
return this;
}
@Override
public ModelSource getModelSource() {
return request.getModelSource();
}
@Override
public FilterModelBuildingRequest setModelSource(ModelSource modelSource) {
request.setModelSource(modelSource);
return this;
}
@Override
public int getValidationLevel() {
return request.getValidationLevel();
}
@Override
public FilterModelBuildingRequest setValidationLevel(int validationLevel) {
request.setValidationLevel(validationLevel);
return this;
}
@Override
public boolean isProcessPlugins() {
return request.isProcessPlugins();
}
@Override
public FilterModelBuildingRequest setProcessPlugins(boolean processPlugins) {
request.setProcessPlugins(processPlugins);
return this;
}
@Override
public boolean isTwoPhaseBuilding() {
return request.isTwoPhaseBuilding();
}
@Override
public FilterModelBuildingRequest setTwoPhaseBuilding(boolean twoPhaseBuilding) {
request.setTwoPhaseBuilding(twoPhaseBuilding);
return this;
}
@Override
public boolean isLocationTracking() {
return request.isLocationTracking();
}
@Override
public FilterModelBuildingRequest setLocationTracking(boolean locationTracking) {
request.setLocationTracking(locationTracking);
return this;
}
@Override
public List<Profile> getProfiles() {
return request.getProfiles();
}
@Override
public FilterModelBuildingRequest setProfiles(List<Profile> profiles) {
request.setProfiles(profiles);
return this;
}
@Override
public List<String> getActiveProfileIds() {
return request.getActiveProfileIds();
}
@Override
public FilterModelBuildingRequest setActiveProfileIds(List<String> activeProfileIds) {
request.setActiveProfileIds(activeProfileIds);
return this;
}
@Override
public List<String> getInactiveProfileIds() {
return request.getInactiveProfileIds();
}
@Override
public FilterModelBuildingRequest setInactiveProfileIds(List<String> inactiveProfileIds) {
request.setInactiveProfileIds(inactiveProfileIds);
return this;
}
@Override
public Properties getSystemProperties() {
return request.getSystemProperties();
}
@Override
public FilterModelBuildingRequest setSystemProperties(Properties systemProperties) {
request.setSystemProperties(systemProperties);
return this;
}
@Override
public Properties getUserProperties() {
return request.getUserProperties();
}
@Override
public FilterModelBuildingRequest setUserProperties(Properties userProperties) {
request.setUserProperties(userProperties);
return this;
}
@Override
public Date getBuildStartTime() {
return request.getBuildStartTime();
}
@Override
public ModelBuildingRequest setBuildStartTime(Date buildStartTime) {
request.setBuildStartTime(buildStartTime);
return this;
}
@Override
public ModelResolver getModelResolver() {
return request.getModelResolver();
}
@Override
public FilterModelBuildingRequest setModelResolver(ModelResolver modelResolver) {
request.setModelResolver(modelResolver);
return this;
}
@Override
public ModelBuildingListener getModelBuildingListener() {
return request.getModelBuildingListener();
}
@Override
public ModelBuildingRequest setModelBuildingListener(ModelBuildingListener modelBuildingListener) {
request.setModelBuildingListener(modelBuildingListener);
return this;
}
@Override
public ModelCache getModelCache() {
return request.getModelCache();
}
@Override
public FilterModelBuildingRequest setModelCache(ModelCache modelCache) {
request.setModelCache(modelCache);
return this;
}
@Override
public Model getFileModel() {
return request.getFileModel();
}
@Override
public ModelBuildingRequest setFileModel(Model fileModel) {
request.setFileModel(fileModel);
return this;
}
@Override
public Model getRawModel() {
return request.getRawModel();
}
@Override
public ModelBuildingRequest setRawModel(Model rawModel) {
request.setRawModel(rawModel);
return this;
}
@Override
public WorkspaceModelResolver getWorkspaceModelResolver() {
return request.getWorkspaceModelResolver();
}
@Override
public ModelBuildingRequest setWorkspaceModelResolver(WorkspaceModelResolver workspaceResolver) {
request.setWorkspaceModelResolver(workspaceResolver);
return this;
}
@Override
public TransformerContextBuilder getTransformerContextBuilder() {
return request.getTransformerContextBuilder();
}
@Override
public ModelBuildingRequest setTransformerContextBuilder(TransformerContextBuilder contextBuilder) {
request.setTransformerContextBuilder(contextBuilder);
return this;
}
@Override
public Path getRootDirectory() {
return request.getRootDirectory();
}
@Override
public ModelBuildingRequest setRootDirectory(Path rootDirectory) {<FILL_FUNCTION_BODY>}
}
|
request.setRootDirectory(rootDirectory);
return this;
| 1,571 | 19 | 1,590 | 11,393 |
shopizer-ecommerce_shopizer
|
shopizer/sm-shop-model/src/main/java/com/salesmanager/shop/model/catalog/product/attribute/ReadableProductProperty.java
|
ReadableProductProperty
|
setPropertyValue
|
class ReadableProductProperty extends ProductPropertyOption {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* Property use option objects
*/
private ReadableProductOption property = null;
private ReadableProductPropertyValue propertyValue = null;
public ReadableProductOption getProperty() {
return property;
}
public void setProperty(ReadableProductOption property) {
this.property = property;
}
public ReadableProductPropertyValue getPropertyValue() {
return propertyValue;
}
public void setPropertyValue(ReadableProductPropertyValue propertyValue) {<FILL_FUNCTION_BODY>}
}
|
this.propertyValue = propertyValue;
| 163 | 13 | 176 | 40,412 |
jOOQ_jOOQ
|
jOOQ/jOOQ/src/main/java/org/jooq/impl/RowGt.java
|
RowGt
|
equals
|
class RowGt<T extends Row>
extends
AbstractCondition
implements
QOM.RowGt<T>
{
final T arg1;
final T arg2;
RowGt(
T arg1,
T arg2
) {
this.arg1 = (T) ((AbstractRow) arg1).convertTo(arg2);
this.arg2 = (T) ((AbstractRow) arg2).convertTo(arg1);
}
// -------------------------------------------------------------------------
// XXX: QueryPart API
// -------------------------------------------------------------------------
@Override
public final void accept(Context<?> ctx) {
RowEq.acceptCompareCondition(ctx, this, arg1, org.jooq.Comparator.GREATER, arg2);
}
// -------------------------------------------------------------------------
// XXX: Query Object Model
// -------------------------------------------------------------------------
@Override
public final T $arg1() {
return arg1;
}
@Override
public final T $arg2() {
return arg2;
}
@Override
public final QOM.RowGt<T> $arg1(T newValue) {
return $constructor().apply(newValue, $arg2());
}
@Override
public final QOM.RowGt<T> $arg2(T newValue) {
return $constructor().apply($arg1(), newValue);
}
@Override
public final Function2<? super T, ? super T, ? extends QOM.RowGt<T>> $constructor() {
return (a1, a2) -> new RowGt<>(a1, a2);
}
// -------------------------------------------------------------------------
// XXX: The Object API
// -------------------------------------------------------------------------
@Override
public boolean equals(Object that) {<FILL_FUNCTION_BODY>}
}
|
if (that instanceof QOM.RowGt<?> o) {
return
StringUtils.equals($arg1(), o.$arg1()) &&
StringUtils.equals($arg2(), o.$arg2())
;
}
else
return super.equals(that);
| 482 | 77 | 559 | 58,461 |
apache_rocketmq
|
rocketmq/remoting/src/main/java/org/apache/rocketmq/remoting/protocol/body/ConsumeStatus.java
|
ConsumeStatus
|
setPullTPS
|
class ConsumeStatus {
private double pullRT;
private double pullTPS;
private double consumeRT;
private double consumeOKTPS;
private double consumeFailedTPS;
private long consumeFailedMsgs;
public double getPullRT() {
return pullRT;
}
public void setPullRT(double pullRT) {
this.pullRT = pullRT;
}
public double getPullTPS() {
return pullTPS;
}
public void setPullTPS(double pullTPS) {<FILL_FUNCTION_BODY>}
public double getConsumeRT() {
return consumeRT;
}
public void setConsumeRT(double consumeRT) {
this.consumeRT = consumeRT;
}
public double getConsumeOKTPS() {
return consumeOKTPS;
}
public void setConsumeOKTPS(double consumeOKTPS) {
this.consumeOKTPS = consumeOKTPS;
}
public double getConsumeFailedTPS() {
return consumeFailedTPS;
}
public void setConsumeFailedTPS(double consumeFailedTPS) {
this.consumeFailedTPS = consumeFailedTPS;
}
public long getConsumeFailedMsgs() {
return consumeFailedMsgs;
}
public void setConsumeFailedMsgs(long consumeFailedMsgs) {
this.consumeFailedMsgs = consumeFailedMsgs;
}
}
|
this.pullTPS = pullTPS;
| 389 | 15 | 404 | 53,716 |
wildfirechat_im-server
|
im-server/broker/src/main/java/io/moquette/imhandler/ModifyMyInfoHandler.java
|
ModifyMyInfoHandler
|
action
|
class ModifyMyInfoHandler extends IMHandler<WFCMessage.ModifyMyInfoRequest> {
@Override
public ErrorCode action(ByteBuf ackPayload, String clientID, String fromUser, ProtoConstants.RequestSourceType requestSourceType, WFCMessage.ModifyMyInfoRequest request, Qos1PublishHandler.IMCallback callback) {<FILL_FUNCTION_BODY>}
}
|
try {
return m_messagesStore.modifyUserInfo(fromUser, request);
} catch (Exception e) {
e.printStackTrace();
Utility.printExecption(LOG, e);
return ErrorCode.ERROR_CODE_SERVER_ERROR;
}
| 96 | 71 | 167 | 4,028 |
jOOQ_jOOQ
|
jOOQ/jOOQ/src/main/java/org/jooq/impl/IDiv.java
|
IDiv
|
equals
|
class IDiv<T>
extends
AbstractTransformable<T>
implements
QOM.Div<T>
{
final Field<T> arg1;
final Field<T> arg2;
IDiv(
Field<T> arg1,
Field<T> arg2
) {
super(
N_DIV,
allNotNull((DataType) dataType(arg1), arg1, arg2)
);
this.arg1 = nullSafeNotNull(arg1, (DataType) OTHER);
this.arg2 = nullSafeNotNull(arg2, (DataType) OTHER);
}
// -------------------------------------------------------------------------
// XXX: QueryPart API
// -------------------------------------------------------------------------
@Override
public final void accept0(Context<?> ctx) {
ctx.visit(new Div($arg1(), $arg2()));
}
@Override
public final Field<?> transform(TransformUnneededArithmeticExpressions transform) {
return Expression.transform(this, arg1, ExpressionOperator.DIVIDE, arg2, true, transform);
}
// -------------------------------------------------------------------------
// XXX: Query Object Model
// -------------------------------------------------------------------------
@Override
public final Field<T> $arg1() {
return arg1;
}
@Override
public final Field<T> $arg2() {
return arg2;
}
@Override
public final QOM.Div<T> $arg1(Field<T> newValue) {
return $constructor().apply(newValue, $arg2());
}
@Override
public final QOM.Div<T> $arg2(Field<T> newValue) {
return $constructor().apply($arg1(), newValue);
}
@Override
public final Function2<? super Field<T>, ? super Field<T>, ? extends QOM.Div<T>> $constructor() {
return (a1, a2) -> new IDiv<>(a1, a2);
}
// -------------------------------------------------------------------------
// XXX: The Object API
// -------------------------------------------------------------------------
@Override
public boolean equals(Object that) {<FILL_FUNCTION_BODY>}
}
|
if (that instanceof QOM.Div<?> o) {
return
StringUtils.equals($arg1(), o.$arg1()) &&
StringUtils.equals($arg2(), o.$arg2())
;
}
else
return super.equals(that);
| 560 | 75 | 635 | 58,462 |
orientechnologies_orientdb
|
orientdb/core/src/main/java/com/orientechnologies/orient/core/sql/functions/coll/OSQLFunctionSet.java
|
OSQLFunctionSet
|
execute
|
class OSQLFunctionSet extends OSQLFunctionMultiValueAbstract<Set<Object>> {
public static final String NAME = "set";
public OSQLFunctionSet() {
super(NAME, 1, -1);
}
public Object execute(
Object iThis,
final OIdentifiable iCurrentRecord,
Object iCurrentResult,
final Object[] iParams,
OCommandContext iContext) {<FILL_FUNCTION_BODY>}
public String getSyntax() {
return "set(<value>*)";
}
public boolean aggregateResults(final Object[] configuredParameters) {
return configuredParameters.length == 1;
}
@Override
public Set<Object> getResult() {
final Set<Object> res = context;
context = null;
return prepareResult(res);
}
@SuppressWarnings("unchecked")
@Override
public Object mergeDistributedResult(List<Object> resultsToMerge) {
if (returnDistributedResult()) {
final Collection<Object> result = new HashSet<Object>();
for (Object iParameter : resultsToMerge) {
final Map<String, Object> container =
(Map<String, Object>) ((Collection<?>) iParameter).iterator().next();
result.addAll((Collection<?>) container.get("context"));
}
return result;
}
if (!resultsToMerge.isEmpty()) return resultsToMerge.get(0);
return null;
}
protected Set<Object> prepareResult(Set<Object> res) {
if (returnDistributedResult()) {
final Map<String, Object> doc = new HashMap<String, Object>();
doc.put("node", getDistributedStorageId());
doc.put("context", context);
return Collections.<Object>singleton(doc);
} else {
return res;
}
}
}
|
if (iParams.length > 1)
// IN LINE MODE
context = new HashSet<Object>();
for (Object value : iParams) {
if (value != null) {
if (iParams.length == 1 && context == null)
// AGGREGATION MODE (STATEFULL)
context = new HashSet<Object>();
if (value instanceof ODocument) context.add(value);
else OMultiValue.add(context, value);
}
}
return prepareResult(context);
| 483 | 138 | 621 | 36,189 |
pmd_pmd
|
pmd/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/internal/asm/FieldStub.java
|
FieldStub
|
toString
|
class FieldStub extends MemberStubBase implements JFieldSymbol, TypeAnnotationReceiver {
private final LazyTypeSig type;
private final @Nullable Object constValue;
FieldStub(ClassStub classStub,
String name,
int accessFlags,
String descriptor,
String signature,
@Nullable Object constValue) {
super(classStub, name, accessFlags);
this.type = new LazyTypeSig(classStub, descriptor, signature);
this.constValue = constValue;
}
@Override
public void acceptTypeAnnotation(int typeRef, @Nullable TypePath path, SymAnnot annot) {
assert new TypeReference(typeRef).getSort() == TypeReference.FIELD : typeRef;
this.type.addTypeAnnotation(path, annot);
}
@Override
public @Nullable Object getConstValue() {
return constValue;
}
@Override
public boolean isEnumConstant() {
return (getModifiers() & Opcodes.ACC_ENUM) != 0;
}
@Override
public JTypeMirror getTypeMirror(Substitution subst) {
return type.get(subst);
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return SymbolEquality.FIELD.hash(this);
}
@Override
public boolean equals(Object obj) {
return SymbolEquality.FIELD.equals(this, obj);
}
}
|
return SymbolToStrings.ASM.toString(this);
| 393 | 18 | 411 | 37,994 |
erupts_erupt
|
erupt/erupt-extra/erupt-flow/src/main/java/xyz/erupt/flow/service/impl/ProcessExecutionServiceImpl.java
|
ProcessExecutionServiceImpl
|
newExecution
|
class ProcessExecutionServiceImpl extends ServiceImpl<OaProcessExecutionMapper, OaProcessExecution>
implements ProcessExecutionService {
private Map<Class<ExecutableNodeListener>, List<ExecutableNodeListener>> listenerMap = new HashMap<>();
@Autowired
private ProcessInstanceService processInstanceService;
@Autowired
private ProcessActivityService processActivityService;
@Autowired
private ProcessDefinitionService processDefinitionService;
@Override
@Transactional(rollbackFor = Exception.class)
public OaProcessExecution newExecutionForInstance(OaProcessInstance inst) {
OaProcessDefinition def = processDefinitionService.getById(inst.getProcessDefId());
return this.newExecution(def.getId(), inst.getId(), def.getProcessNode(), null);
}
@Override
@Transactional(rollbackFor = Exception.class)
public OaProcessExecution newExecution(String defId, Long instanceId, OaProcessNode startNode, OaProcessExecution parent) {<FILL_FUNCTION_BODY>}
/**
* 线程前进
* @param executionId
*/
@Override
@Transactional(rollbackFor = Exception.class)
public void step(Long executionId, OaProcessNode currentNode) {
//判断是否满足继续的条件
int count = this.countRunningChildren(executionId);
if(count>0) {
//如果还有运行中的子线程,禁止前进
return;
}
OaProcessExecution execution = this.getById(executionId);
if(!OaProcessExecution.STATUS_RUNNING.equals(execution.getStatus())) {
throw new EruptApiErrorTip("当前线程状态"+execution.getStatus()+"不可完成");
}
//获取下一个节点
OaProcessNode nextNode = null;
if(execution.getProcess()!=null) {
nextNode = currentNode.getChildren();
}
if(nextNode==null || nextNode.getId()==null) {//没有下一步,当前线程结束了
this.finish(execution);//调用结束
}else {//当前线程没结束,生成下一批活动
OaProcessInstance inst = processInstanceService.getById(execution.getProcessInstId());
JSONObject jsonObject = JSON.parseObject(inst.getFormItems());
processActivityService.newActivities(execution, jsonObject, nextNode, OaProcessExecution.STATUS_RUNNING);
}
}
private int countRunningChildren(Long parentId) {
QueryWrapper<OaProcessExecution> queryWrapper = new QueryWrapper<>();
queryWrapper.lambda().eq(OaProcessExecution::getParentId, parentId);
//运行中和等待中的任务都算
queryWrapper.lambda().in(OaProcessExecution::getStatus
, OaProcessExecution.STATUS_RUNNING, OaProcessExecution.STATUS_WAITING);
return this.count(queryWrapper);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void removeByProcessInstId(Long procInstId) {
QueryWrapper<OaProcessExecution> queryWrapper = new QueryWrapper<>();
queryWrapper.lambda().eq(OaProcessExecution::getProcessInstId, procInstId);
this.remove(queryWrapper);
}
//完成一个线程
@Override
@Transactional(rollbackFor = Exception.class)
public void finish(OaProcessExecution execution) {
//线程结束
Date now = new Date();
execution.setProcess("{}");
execution.setStatus(OaProcessExecution.STATUS_ENDED);
execution.setEnded(now);
execution.setUpdated(new Date());
this.updateById(execution);
//触发结束后置监听
this.listenerMap.get(AfterFinishExecutionListener.class).forEach(l -> l.execute(execution));
}
@Override
@Transactional(rollbackFor = Exception.class)
public void freshProcess(Long id, String json) {
OaProcessExecution build = OaProcessExecution.builder()
.process(json)
.updated(new Date())
.build();
build.setId(id);
this.updateById(build);
}
@Override
public void stopByInstId(Long instId, String reason) {
Date now = new Date();
List<OaProcessExecution> executions = this.listByInstId(instId, true);
if(CollectionUtils.isEmpty(executions)) {
return;
}
executions.forEach(e -> {
OaProcessExecution build = OaProcessExecution.builder()
.process("{}")
.status(OaProcessExecution.STATUS_ENDED)
.reason(reason)
.ended(now)
.updated(now)
.id(e.getId())
.build();
this.updateById(build);
});
}
private List<OaProcessExecution> listByInstId(Long instId, boolean active) {
LambdaQueryWrapper<OaProcessExecution> wrapper = new LambdaQueryWrapper<OaProcessExecution>()
.eq(OaProcessExecution::getProcessInstId, instId);
if(active) {
wrapper.in(OaProcessExecution::getStatus, OaProcessExecution.STATUS_RUNNING, OaProcessExecution.STATUS_WAITING);
}else {
wrapper.in(OaProcessExecution::getStatus, OaProcessExecution.STATUS_ENDED);
}
return this.list(wrapper);
}
/**
* 继续线程
* @param executionId
*/
@Override
@Transactional(rollbackFor = Exception.class)
public void active(Long executionId) {
//否则判断是否满足继续的条件
int count = this.countRunningChildren(executionId);
if(count>0) {
//当前线程还有子线程未合并,不能继续
return;
}
//否则激活
OaProcessExecution updateBean = OaProcessExecution.builder()
.status(OaProcessExecution.STATUS_RUNNING)
.build();
updateBean.setId(executionId);
this.updateById(updateBean);
//激活线程下的所有活动和任务
processActivityService.activeByExecutionId(executionId);
}
}
|
//创建线程
OaProcessExecution execution = OaProcessExecution.builder()
.processInstId(instanceId)
.processDefId(defId)
.startNodeId(startNode.getId())
.startNodeName(startNode.getName())
.process(JSON.toJSONString(startNode))
.status(OaProcessExecution.STATUS_RUNNING)//直接就是运行状态
.created(new Date())
.build();
if(parent==null) {
execution.setId(instanceId);//主线程id与流程实例相同
execution.setParentId(null);
}else{
execution.setId(null);
execution.setParentId(parent.getId());
}
super.save(execution);
//创建后置监听
this.listenerMap.get(AfterCreateExecutionListener.class).forEach(l -> l.execute(execution));
return execution;
| 1,591 | 235 | 1,826 | 18,357 |
alibaba_easyexcel
|
easyexcel/easyexcel-core/src/main/java/com/alibaba/excel/write/style/column/LongestMatchColumnWidthStyleStrategy.java
|
LongestMatchColumnWidthStyleStrategy
|
dataLength
|
class LongestMatchColumnWidthStyleStrategy extends AbstractColumnWidthStyleStrategy {
private static final int MAX_COLUMN_WIDTH = 255;
private final Map<Integer, Map<Integer, Integer>> cache = MapUtils.newHashMapWithExpectedSize(8);
@Override
protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List<WriteCellData<?>> cellDataList, Cell cell,
Head head,
Integer relativeRowIndex, Boolean isHead) {
boolean needSetWidth = isHead || !CollectionUtils.isEmpty(cellDataList);
if (!needSetWidth) {
return;
}
Map<Integer, Integer> maxColumnWidthMap = cache.computeIfAbsent(writeSheetHolder.getSheetNo(), key -> new HashMap<>(16));
Integer columnWidth = dataLength(cellDataList, cell, isHead);
if (columnWidth < 0) {
return;
}
if (columnWidth > MAX_COLUMN_WIDTH) {
columnWidth = MAX_COLUMN_WIDTH;
}
Integer maxColumnWidth = maxColumnWidthMap.get(cell.getColumnIndex());
if (maxColumnWidth == null || columnWidth > maxColumnWidth) {
maxColumnWidthMap.put(cell.getColumnIndex(), columnWidth);
writeSheetHolder.getSheet().setColumnWidth(cell.getColumnIndex(), columnWidth * 256);
}
}
private Integer dataLength(List<WriteCellData<?>> cellDataList, Cell cell, Boolean isHead) {<FILL_FUNCTION_BODY>}
}
|
if (isHead) {
return cell.getStringCellValue().getBytes().length;
}
WriteCellData<?> cellData = cellDataList.get(0);
CellDataTypeEnum type = cellData.getType();
if (type == null) {
return -1;
}
switch (type) {
case STRING:
return cellData.getStringValue().getBytes().length;
case BOOLEAN:
return cellData.getBooleanValue().toString().getBytes().length;
case NUMBER:
return cellData.getNumberValue().toString().getBytes().length;
default:
return -1;
}
| 398 | 168 | 566 | 50,951 |
noear_solon
|
solon/solon-projects/solon-data/solon.cache.spymemcached/src/main/java/org/noear/solon/cache/spymemcached/integration/XPluginImp.java
|
XPluginImp
|
start
|
class XPluginImp implements Plugin {
@Override
public void start(AppContext context) {<FILL_FUNCTION_BODY>}
}
|
CacheLib.cacheFactoryAdd("memcached", new MemCacheFactoryImpl());
| 39 | 22 | 61 | 33,339 |
spring-io_initializr
|
initializr/initializr-docs/src/main/java/io/spring/initializr/doc/generator/project/ProjectGeneratorSetupExample.java
|
ProjectGeneratorSetupExample
|
createProjectGenerator
|
class ProjectGeneratorSetupExample {
// tag::code[]
public ProjectGenerator createProjectGenerator(ApplicationContext appContext) {<FILL_FUNCTION_BODY>}
// end::code[]
}
|
return new ProjectGenerator((context) -> {
context.setParent(appContext);
context.registerBean(SampleContributor.class, SampleContributor::new);
});
| 49 | 51 | 100 | 43,930 |
questdb_questdb
|
questdb/core/src/main/java/io/questdb/griffin/engine/functions/cast/CastSymbolToStrFunctionFactory.java
|
Func
|
isReadThreadSafe
|
class Func extends AbstractCastToStrFunction {
public Func(Function arg) {
super(arg);
}
@Override
public CharSequence getStrA(Record rec) {
return arg.getSymbol(rec);
}
@Override
public void getStr(Record rec, Utf16Sink utf16Sink) {
utf16Sink.put(arg.getSymbol(rec));
}
@Override
public CharSequence getStrB(Record rec) {
return arg.getSymbolB(rec);
}
@Override
public boolean isReadThreadSafe() {<FILL_FUNCTION_BODY>}
}
|
return arg.isReadThreadSafe();
| 171 | 13 | 184 | 60,966 |
pf4j_pf4j
|
pf4j/pf4j/src/main/java/org/pf4j/SingletonExtensionFactory.java
|
SingletonExtensionFactory
|
create
|
class SingletonExtensionFactory extends DefaultExtensionFactory {
private final List<String> extensionClassNames;
private final Map<ClassLoader, Map<String, Object>> cache;
public SingletonExtensionFactory(PluginManager pluginManager, String... extensionClassNames) {
this.extensionClassNames = Arrays.asList(extensionClassNames);
cache = new HashMap<>();
pluginManager.addPluginStateListener(event -> {
if (event.getPluginState() != PluginState.STARTED) {
cache.remove(event.getPlugin().getPluginClassLoader());
}
});
}
@Override
@SuppressWarnings("unchecked")
public <T> T create(Class<T> extensionClass) {<FILL_FUNCTION_BODY>}
}
|
String extensionClassName = extensionClass.getName();
ClassLoader extensionClassLoader = extensionClass.getClassLoader();
if (!cache.containsKey(extensionClassLoader)) {
cache.put(extensionClassLoader, new HashMap<>());
}
Map<String, Object> classLoaderBucket = cache.get(extensionClassLoader);
if (classLoaderBucket.containsKey(extensionClassName)) {
return (T) classLoaderBucket.get(extensionClassName);
}
T extension = super.create(extensionClass);
if (extensionClassNames.isEmpty() || extensionClassNames.contains(extensionClassName)) {
classLoaderBucket.put(extensionClassName, extension);
}
return extension;
| 200 | 182 | 382 | 37,270 |
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/analysis/plain/PlainAnalyzerFactory.java
|
PlainAnalyzerFactory
|
description
|
class PlainAnalyzerFactory extends FileAnalyzerFactory {
private static final String NAME = "Plain Text";
private static final int MIN_CHARS_WHILE_REMAINING = 20;
// Up to 4 octets per UTF-8 character
private static final int TRY_UTF8_BYTES = MIN_CHARS_WHILE_REMAINING * 4;
/**
* The reentrant {@link Matcher} implementation for plain-text files.
*/
public static final Matcher MATCHER = new Matcher() {
@Override
public String description() {<FILL_FUNCTION_BODY>}
@Override
public AnalyzerFactory isMagic(byte[] content, InputStream in) throws IOException {
int lengthBOM = IOUtils.skipForBOM(content);
if (lengthBOM > 0) {
return DEFAULT_INSTANCE;
}
if (readSomePlainCharactersUTF8noBOMwithoutError(in)) {
return DEFAULT_INSTANCE;
}
return null;
}
@Override
public AnalyzerFactory forFactory() {
return DEFAULT_INSTANCE;
}
};
/**
* Gets the singleton, factory instance that associates
* {@link PlainAnalyzer} with files whose initial bytes are the UTF-8,
* UTF-16BE, or UTF-16LE Byte Order Mark; or whose initial bytes are all
* UTF-8-encoded graphic characters or whitespace.
*/
public static final PlainAnalyzerFactory DEFAULT_INSTANCE = new PlainAnalyzerFactory();
private PlainAnalyzerFactory() {
super(null, null, null, null, MATCHER, "text/plain", AbstractAnalyzer.Genre.PLAIN, NAME, true);
}
@Override
protected AbstractAnalyzer newAnalyzer() {
return new PlainAnalyzer(this);
}
private static boolean readSomePlainCharactersUTF8noBOMwithoutError(InputStream in)
throws IOException {
boolean isEOF = false;
byte[] bytes = new byte[TRY_UTF8_BYTES];
in.mark(TRY_UTF8_BYTES);
int len = in.read(bytes);
in.reset();
if (len < 1) {
return false;
}
if (len != TRY_UTF8_BYTES) {
bytes = Arrays.copyOf(bytes, len);
isEOF = true;
}
/*
* Decode one character at a time until either a decoding error occurs
* (failure) or the minimum number of required, valid characters is
* reached (success).
*
* "Decode bytes to chars one at a time"
* answered by https://stackoverflow.com/users/1831293/evgeniy-dorofeev
* https://stackoverflow.com/questions/17227331/decode-bytes-to-chars-one-at-a-time
* asked by https://stackoverflow.com/users/244360/kong
*
* Used under CC 4 with modifications noted as follows as required by
* license:
* * 2021-08-15 -- cfraire@me.com, revised to check for errors.
*/
CharsetDecoder cd = StandardCharsets.UTF_8.newDecoder().
onMalformedInput(CodingErrorAction.REPORT).
onUnmappableCharacter(CodingErrorAction.REPORT);
ByteBuffer bin = ByteBuffer.wrap(bytes);
CharBuffer out = CharBuffer.allocate(MIN_CHARS_WHILE_REMAINING);
int numCharacters = 0;
CoderResult decodeResult = cd.decode(bin, out, isEOF);
if (decodeResult.isError()) {
return false;
}
int numChars = out.position();
out.position(0);
for (int i = 0; i < numChars; ++i) {
char c = out.charAt(i);
if (Character.isISOControl(c) && !Character.isWhitespace(c)) {
return false;
}
if (++numCharacters >= MIN_CHARS_WHILE_REMAINING) {
return true;
}
}
/*
* At this point, as no error has occurred, then if any character was
* read, consider the input as plain text.
*/
return (numCharacters > 0);
}
}
|
return "UTF-8, UTF-16BE, or UTF-16LE Byte Order Mark is present; or initial " +
"bytes are all UTF-8-encoded graphic characters or whitespace";
| 1,150 | 54 | 1,204 | 35,110 |
prometheus_client_java
|
client_java/prometheus-metrics-core/src/main/java/io/prometheus/metrics/core/metrics/MetricWithFixedMetadata.java
|
Builder
|
labelNames
|
class Builder<B extends Builder<B, M>, M extends MetricWithFixedMetadata> extends Metric.Builder<B, M> {
protected String name;
private Unit unit;
private String help;
private String[] labelNames = new String[0];
protected Builder(List<String> illegalLabelNames, PrometheusProperties properties) {
super(illegalLabelNames, properties);
}
public B name(String name) {
if (!PrometheusNaming.isValidMetricName(name)) {
throw new IllegalArgumentException("'" + name + "': Illegal metric name.");
}
this.name = name;
return self();
}
public B unit(Unit unit) {
this.unit = unit;
return self();
}
public B help(String help) {
this.help = help;
return self();
}
public B labelNames(String... labelNames) {<FILL_FUNCTION_BODY>}
public B constLabels(Labels constLabels) {
for (String labelName : labelNames) {
if (constLabels.contains(labelName)) { // Labels.contains() treats dots like underscores
throw new IllegalArgumentException(labelName + ": duplicate label name");
}
}
return super.constLabels(constLabels);
}
@Override
public abstract M build();
@Override
protected abstract B self();
}
|
for (String labelName : labelNames) {
if (!PrometheusNaming.isValidLabelName(labelName)) {
throw new IllegalArgumentException(labelName + ": illegal label name");
}
if (illegalLabelNames.contains(labelName)) {
throw new IllegalArgumentException(labelName + ": illegal label name for this metric type");
}
if (constLabels.contains(labelName)) {
throw new IllegalArgumentException(labelName + ": duplicate label name");
}
}
this.labelNames = labelNames;
return self();
| 364 | 142 | 506 | 38,683 |
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/context/LazyContextVariable.java
|
LazyContextVariable
|
getValue
|
class LazyContextVariable<T> implements ILazyContextVariable<T> {
private volatile boolean initialized = false;
private T value;
protected LazyContextVariable() {
super();
}
/**
* <p>
* Lazily resolve the value.
* </p>
* <p>
* This will be transparently called by the Thymeleaf engine at template rendering time when an object
* of this class is resolved in a Thymeleaf expression.
* </p>
* <p>
* Note lazy variables will be resolved just once, and their resolved values will be reused as many times
* as they appear in the template.
* </p>
*
* @return the resolved value.
*/
public final T getValue() {<FILL_FUNCTION_BODY>}
/**
* <p>
* Perform the actual resolution of the variable's value.
* </p>
* <p>
* This method will be called only once, the first time this variable is resolved.
* </p>
*
* @return the resolved value.
*/
protected abstract T loadValue();
}
|
if (!this.initialized) {
synchronized (this) {
if (!this.initialized) {
this.value = loadValue();
this.initialized = true;
}
}
}
return this.value;
| 312 | 65 | 377 | 45,732 |
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/common/BitSource.java
|
BitSource
|
readBits
|
class BitSource {
private final byte[] bytes;
private int byteOffset;
private int bitOffset;
/**
* @param bytes bytes from which this will read bits. Bits will be read from the first byte first.
* Bits are read within a byte from most-significant to least-significant bit.
*/
public BitSource(byte[] bytes) {
this.bytes = bytes;
}
/**
* @return index of next bit in current byte which would be read by the next call to {@link #readBits(int)}.
*/
public int getBitOffset() {
return bitOffset;
}
/**
* @return index of next byte in input byte array which would be read by the next call to {@link #readBits(int)}.
*/
public int getByteOffset() {
return byteOffset;
}
/**
* @param numBits number of bits to read
* @return int representing the bits read. The bits will appear as the least-significant
* bits of the int
* @throws IllegalArgumentException if numBits isn't in [1,32] or more than is available
*/
public int readBits(int numBits) {<FILL_FUNCTION_BODY>}
/**
* @return number of bits that can be read successfully
*/
public int available() {
return 8 * (bytes.length - byteOffset) - bitOffset;
}
}
|
if (numBits < 1 || numBits > 32 || numBits > available()) {
throw new IllegalArgumentException(String.valueOf(numBits));
}
int result = 0;
// First, read remainder from current byte
if (bitOffset > 0) {
int bitsLeft = 8 - bitOffset;
int toRead = Math.min(numBits, bitsLeft);
int bitsToNotRead = bitsLeft - toRead;
int mask = (0xFF >> (8 - toRead)) << bitsToNotRead;
result = (bytes[byteOffset] & mask) >> bitsToNotRead;
numBits -= toRead;
bitOffset += toRead;
if (bitOffset == 8) {
bitOffset = 0;
byteOffset++;
}
}
// Next read whole bytes
if (numBits > 0) {
while (numBits >= 8) {
result = (result << 8) | (bytes[byteOffset] & 0xFF);
byteOffset++;
numBits -= 8;
}
// Finally read a partial byte
if (numBits > 0) {
int bitsToNotRead = 8 - numBits;
int mask = (0xFF >> bitsToNotRead) << bitsToNotRead;
result = (result << numBits) | ((bytes[byteOffset] & mask) >> bitsToNotRead);
bitOffset += numBits;
}
}
return result;
| 367 | 378 | 745 | 4,727 |
alibaba_druid
|
druid/core/src/main/java/com/alibaba/druid/sql/dialect/hive/visitor/HiveSchemaStatVisitor.java
|
HiveSchemaStatVisitor
|
visit
|
class HiveSchemaStatVisitor extends SchemaStatVisitor implements HiveASTVisitor {
public HiveSchemaStatVisitor() {
super(DbType.hive);
}
public HiveSchemaStatVisitor(DbType dbType) {
super(dbType);
}
public HiveSchemaStatVisitor(SchemaRepository repository) {
super(repository);
}
@Override
public boolean visit(HiveInsert x) {
setMode(x, TableStat.Mode.Insert);
SQLExprTableSource tableSource = x.getTableSource();
SQLExpr tableName = tableSource != null ? tableSource.getExpr() : null;
if (tableName instanceof SQLName) {
TableStat stat = getTableStat((SQLName) tableName);
stat.incrementInsertCount();
}
for (SQLAssignItem partition : x.getPartitions()) {
partition.accept(this);
}
accept(x.getQuery());
return false;
}
@Override
public boolean visit(HiveMultiInsertStatement x) {
if (repository != null
&& x.getParent() == null) {
repository.resolve(x);
}
return true;
}
@Override
public boolean visit(HiveInsertStatement x) {
if (repository != null
&& x.getParent() == null) {
repository.resolve(x);
}
SQLWithSubqueryClause with = x.getWith();
if (with != null) {
with.accept(this);
}
setMode(x, TableStat.Mode.Insert);
SQLExprTableSource tableSource = x.getTableSource();
SQLExpr tableName = tableSource.getExpr();
if (tableName instanceof SQLName) {
TableStat stat = getTableStat((SQLName) tableName);
stat.incrementInsertCount();
List<SQLExpr> columns = x.getColumns();
for (SQLExpr column : columns) {
if (column instanceof SQLIdentifierExpr) {
addColumn((SQLName) tableName, ((SQLIdentifierExpr) column).normalizedName());
}
}
}
for (SQLAssignItem partition : x.getPartitions()) {
partition.accept(this);
}
accept(x.getQuery());
return false;
}
@Override
public boolean visit(HiveCreateFunctionStatement x) {
return false;
}
@Override
public boolean visit(HiveLoadDataStatement x) {<FILL_FUNCTION_BODY>}
@Override
public boolean visit(HiveMsckRepairStatement x) {
return false;
}
}
|
TableStat tableStat = getTableStat(x.getInto());
if (tableStat != null) {
tableStat.incrementInsertCount();
}
return false;
| 686 | 49 | 735 | 49,987 |
sofastack_sofa-jraft
|
sofa-jraft/jraft-rheakv/rheakv-core/src/main/java/com/alipay/sofa/jraft/rhea/cmd/pd/BaseResponse.java
|
BaseResponse
|
isSuccess
|
class BaseResponse<T> implements Serializable {
private static final long serialVersionUID = 7595480549808409921L;
private Errors error = Errors.NONE;
private long clusterId;
private T value;
public boolean isSuccess() {<FILL_FUNCTION_BODY>}
public Errors getError() {
return error;
}
public void setError(Errors error) {
this.error = error;
}
public long getClusterId() {
return clusterId;
}
public void setClusterId(long clusterId) {
this.clusterId = clusterId;
}
public T getValue() {
return value;
}
public void setValue(T value) {
this.value = value;
}
@Override
public String toString() {
return "BaseResponse{" + "error=" + error + ", clusterId=" + clusterId + ", value=" + value + '}';
}
}
|
return error == Errors.NONE;
| 274 | 14 | 288 | 63,012 |
killme2008_aviatorscript
|
aviatorscript/src/main/java/com/googlecode/aviator/runtime/function/system/PrintlnFunction.java
|
PrintlnFunction
|
call
|
class PrintlnFunction extends AbstractFunction {
private static final long serialVersionUID = -1592661531857237654L;
@Override
public String getName() {
return "println";
}
@Override
public AviatorObject call(Map<String, Object> env) {<FILL_FUNCTION_BODY>}
@Override
public AviatorObject call(Map<String, Object> env, AviatorObject arg1) {
System.out.println(arg1.getValue(env));
return AviatorNil.NIL;
}
@Override
public AviatorObject call(Map<String, Object> env, AviatorObject arg1, AviatorObject arg2) {
OutputStream out = (OutputStream) FunctionUtils.getJavaObject(arg1, env);
PrintStream printStream = new PrintStream(out);
printStream.println(arg2.getValue(env));
return AviatorNil.NIL;
}
}
|
System.out.println();
return AviatorNil.NIL;
| 268 | 23 | 291 | 27,446 |
crate_crate
|
crate/libs/guice/src/main/java/org/elasticsearch/common/inject/InjectorShell.java
|
Builder
|
addModules
|
class Builder {
private final List<Element> elements = new ArrayList<>();
private final List<Module> modules = new ArrayList<>();
/**
* lazily constructed
*/
private State state;
private InjectorImpl parent;
private Stage stage;
/**
* null unless this exists in a {@link Binder#newPrivateBinder private environment}
*/
private PrivateElementsImpl privateElements;
Builder parent(InjectorImpl parent) {
this.parent = parent;
this.state = new InheritingState(parent.state);
return this;
}
Builder stage(Stage stage) {
this.stage = stage;
return this;
}
Builder privateElements(PrivateElements privateElements) {
this.privateElements = (PrivateElementsImpl) privateElements;
this.elements.addAll(privateElements.getElements());
return this;
}
void addModules(Iterable<? extends Module> modules) {<FILL_FUNCTION_BODY>}
/**
* Synchronize on this before calling {@link #build}.
*/
Object lock() {
return getState().lock();
}
/**
* Creates and returns the injector shells for the current modules. Multiple shells will be
* returned if any modules contain {@link Binder#newPrivateBinder private environments}. The
* primary injector will be first in the returned list.
*/
List<InjectorShell> build(Initializer initializer, BindingProcessor bindingProcessor,
Stopwatch stopwatch, Errors errors) {
if (stage == null) {
throw new IllegalStateException("Stage not initialized");
}
if (privateElements != null && parent == null) {
throw new IllegalStateException("PrivateElements with no parent");
}
if (state == null) {
throw new IllegalStateException("no state. Did you remember to lock() ?");
}
InjectorImpl injector = new InjectorImpl(state, initializer);
if (privateElements != null) {
privateElements.initInjector(injector);
}
// bind Stage and Singleton if this is a top-level injector
if (parent == null) {
modules.add(0, new RootModule(stage));
new TypeConverterBindingProcessor(errors).prepareBuiltInConverters(injector);
}
elements.addAll(Elements.getElements(stage, modules));
stopwatch.resetAndLog("Module execution");
new MessageProcessor(errors).process(injector, elements);
new TypeListenerBindingProcessor(errors).process(injector, elements);
List<TypeListenerBinding> listenerBindings = injector.state.getTypeListenerBindings();
injector.membersInjectorStore = new MembersInjectorStore(injector, listenerBindings);
stopwatch.resetAndLog("TypeListeners creation");
new ScopeBindingProcessor(errors).process(injector, elements);
stopwatch.resetAndLog("Scopes creation");
new TypeConverterBindingProcessor(errors).process(injector, elements);
stopwatch.resetAndLog("Converters creation");
bindInjector(injector);
bindLogger(injector);
bindingProcessor.process(injector, elements);
stopwatch.resetAndLog("Binding creation");
List<InjectorShell> injectorShells = new ArrayList<>();
injectorShells.add(new InjectorShell(elements, injector));
// recursively build child shells
PrivateElementProcessor processor = new PrivateElementProcessor(errors, stage);
processor.process(injector, elements);
for (Builder builder : processor.getInjectorShellBuilders()) {
injectorShells.addAll(builder.build(initializer, bindingProcessor, stopwatch, errors));
}
stopwatch.resetAndLog("Private environment creation");
return injectorShells;
}
private State getState() {
if (state == null) {
state = new InheritingState(State.NONE);
}
return state;
}
}
|
for (Module module : modules) {
this.modules.add(module);
}
| 1,031 | 26 | 1,057 | 16,477 |
fabric8io_kubernetes-client
|
kubernetes-client/httpclient-vertx/src/main/java/io/fabric8/kubernetes/client/vertx/VertxWebSocket.java
|
VertxWebSocket
|
init
|
class VertxWebSocket implements WebSocket {
private static final Logger LOG = LoggerFactory.getLogger(VertxWebSocket.class);
private final io.vertx.core.http.WebSocket ws;
private final AtomicInteger pending = new AtomicInteger();
private final Listener listener;
VertxWebSocket(io.vertx.core.http.WebSocket ws, Listener listener) {
this.ws = ws;
this.listener = listener;
}
void init() {<FILL_FUNCTION_BODY>}
@Override
public boolean send(ByteBuffer buffer) {
Buffer vertxBuffer = Buffer.buffer(Unpooled.copiedBuffer(buffer));
int len = vertxBuffer.length();
pending.addAndGet(len);
Future<Void> res = ws.writeBinaryMessage(vertxBuffer);
if (res.isComplete()) {
pending.addAndGet(-len);
return res.succeeded();
}
res.onComplete(result -> {
if (result.cause() != null) {
LOG.error("Queued write did not succeed", result.cause());
}
pending.addAndGet(-len);
});
return true;
}
@Override
public synchronized boolean sendClose(int code, String reason) {
if (ws.isClosed()) {
return false;
}
Future<Void> res = ws.close((short) code, reason);
res.onComplete(result -> {
ws.fetch(1);
if (result.cause() != null) {
LOG.error("Queued close did not succeed", result.cause());
}
});
return true;
}
@Override
public long queueSize() {
return pending.get();
}
@Override
public void request() {
ws.fetch(1);
}
}
|
ws.binaryMessageHandler(msg -> {
ws.pause();
listener.onMessage(this, msg.getByteBuf().nioBuffer());
});
ws.textMessageHandler(msg -> {
ws.pause();
listener.onMessage(this, msg);
});
// use end, not close, because close is processed immediately vs. end is in frame order
ws.endHandler(v -> listener.onClose(this, ws.closeStatusCode(), ws.closeReason()));
ws.exceptionHandler(err -> {
try {
if (err instanceof CorruptedWebSocketFrameException) {
err = new ProtocolException().initCause(err);
} else if (err instanceof HttpClosedException) {
err = new IOException(err);
}
listener.onError(this, err);
} finally {
// onError should be terminal
if (!ws.isClosed()) {
ws.close();
}
}
});
listener.onOpen(this);
| 495 | 264 | 759 | 18,620 |
sofastack_sofa-jraft
|
sofa-jraft/jraft-core/src/main/java/com/alipay/sofa/jraft/util/ThreadHelper.java
|
DefaultSpinner
|
createSpinner
|
class DefaultSpinner extends Spinner {
@Override
public void onSpinWait() {
Thread.yield();
}
}
private static Spinner createSpinner() {<FILL_FUNCTION_BODY>
|
final String superClassName = Spinner.class.getName();
final String superClassNameInternal = superClassName.replace('.', '/');
final String spinnerClassName = superClassName + "Impl";
final String spinnerClassNameInternal = spinnerClassName.replace('.', '/');
final String threadClassNameInternal = Thread.class.getName().replace('.', '/');
final ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
cw.visit(V1_1, ACC_PUBLIC + ACC_SUPER, spinnerClassNameInternal, null, superClassNameInternal, null);
MethodVisitor mv;
// default constructor
{
mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
mv.visitCode();
mv.visitVarInsn(ALOAD, 0);
mv.visitMethodInsn(INVOKESPECIAL, superClassNameInternal, "<init>", "()V", false);
mv.visitInsn(RETURN);
mv.visitMaxs(0, 0);
mv.visitEnd();
}
// implementation of method: `public abstract void onSpinWait()`
{
mv = cw.visitMethod(ACC_PUBLIC + ACC_VARARGS, "onSpinWait", "()V", null, null);
mv.visitCode();
mv.visitMethodInsn(INVOKESTATIC, threadClassNameInternal, "onSpinWait", "()V", false);
mv.visitInsn(RETURN);
mv.visitMaxs(0, 0);
mv.visitEnd();
}
cw.visitEnd();
try {
final byte[] classBytes = cw.toByteArray();
final Class<?> spinnerClass = SpinnerClassLoader.INSTANCE.defineClass(spinnerClassName, classBytes);
return (Spinner) spinnerClass.getDeclaredConstructor().newInstance();
} catch (final Throwable t) {
LOG.warn("Error constructing spinner class: {}, will return a default spinner.", spinnerClassName, t);
return new DefaultSpinner();
}
| 60 | 584 | 644 | 62,867 |
iluwatar_java-design-patterns
|
java-design-patterns/identity-map/src/main/java/com/iluwatar/identitymap/PersonFinder.java
|
PersonFinder
|
getPerson
|
class PersonFinder {
private static final long serialVersionUID = 1L;
// Access to the Identity Map
private IdentityMap identityMap = new IdentityMap();
private PersonDbSimulatorImplementation db = new PersonDbSimulatorImplementation();
/**
* get person corresponding to input ID.
*
* @param key : personNationalId to look for.
*/
public Person getPerson(int key) {<FILL_FUNCTION_BODY>}
}
|
// Try to find person in the identity map
Person person = this.identityMap.getPerson(key);
if (person != null) {
LOGGER.info("Person found in the Map");
return person;
} else {
// Try to find person in the database
person = this.db.find(key);
if (person != null) {
this.identityMap.addPerson(person);
LOGGER.info("Person found in DB.");
return person;
}
LOGGER.info("Person with this ID does not exist.");
return null;
}
| 120 | 149 | 269 | 567 |
alibaba_druid
|
druid/core/src/main/java/com/alibaba/druid/proxy/jdbc/DataSourceProxyConfig.java
|
DataSourceProxyConfig
|
getRawUrl
|
class DataSourceProxyConfig {
private String rawUrl;
private String url;
private String rawDriverClassName;
private String name;
private boolean jmx;
private PasswordCallback passwordCallback;
private NameCallback userCallback;
private final List<Filter> filters = new ArrayList<Filter>();
public DataSourceProxyConfig() {
}
public boolean isJmxOption() {
return jmx;
}
public void setJmxOption(boolean jmx) {
this.jmx = jmx;
}
public void setJmxOption(String jmx) {
this.jmx = Boolean.parseBoolean(jmx);
}
public PasswordCallback getPasswordCallback() {
return passwordCallback;
}
public void setPasswordCallback(PasswordCallback passwordCallback) {
this.passwordCallback = passwordCallback;
}
public NameCallback getUserCallback() {
return userCallback;
}
public void setUserCallback(NameCallback userCallback) {
this.userCallback = userCallback;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Filter> getFilters() {
return filters;
}
public String getRawUrl() {<FILL_FUNCTION_BODY>}
public void setRawUrl(String rawUrl) {
this.rawUrl = rawUrl;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getRawDriverClassName() {
return rawDriverClassName;
}
public void setRawDriverClassName(String driverClassName) {
this.rawDriverClassName = driverClassName;
}
}
|
return rawUrl;
| 475 | 9 | 484 | 50,221 |
apache_incubator-seata
|
incubator-seata/saga/seata-saga-statelang/src/main/java/org/apache/seata/saga/statelang/parser/impl/StateMachineParserImpl.java
|
StateMachineParserImpl
|
parse
|
class StateMachineParserImpl implements StateMachineParser {
private static final Logger LOGGER = LoggerFactory.getLogger(StateMachineParserImpl.class);
private String jsonParserName = DomainConstants.DEFAULT_JSON_PARSER;
private final StateMachineValidator validator = new StateMachineValidator();
public StateMachineParserImpl(String jsonParserName) {
if (StringUtils.isNotBlank(jsonParserName)) {
this.jsonParserName = jsonParserName;
}
}
@Override
public StateMachine parse(String json) {<FILL_FUNCTION_BODY>}
public String getJsonParserName() {
return jsonParserName;
}
public void setJsonParserName(String jsonParserName) {
this.jsonParserName = jsonParserName;
}
}
|
JsonParser jsonParser = JsonParserFactory.getJsonParser(jsonParserName);
if (jsonParser == null) {
throw new RuntimeException("Cannot find JsonParer by name: " + jsonParserName);
}
Map<String, Object> node = jsonParser.parse(json, Map.class, true);
if (DesignerJsonTransformer.isDesignerJson(node)) {
node = DesignerJsonTransformer.toStandardJson(node);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("===== Transformed standard state language:\n{}", jsonParser.toJsonString(node, true));
}
}
StateMachineImpl stateMachine = new StateMachineImpl();
stateMachine.setName((String) node.get("Name"));
stateMachine.setComment((String) node.get("Comment"));
stateMachine.setVersion((String) node.get("Version"));
stateMachine.setStartState((String) node.get("StartState"));
String recoverStrategy = (String) node.get("RecoverStrategy");
if (StringUtils.isNotBlank(recoverStrategy)) {
stateMachine.setRecoverStrategy(RecoverStrategy.valueOf(recoverStrategy));
}
Object isPersist = node.get("IsPersist");
if (Boolean.FALSE.equals(isPersist)) {
stateMachine.setPersist(false);
}
// customize if update origin or append new retryStateInstLog
Object isRetryPersistModeUpdate = node.get("IsRetryPersistModeUpdate");
if (isRetryPersistModeUpdate instanceof Boolean) {
stateMachine.setRetryPersistModeUpdate(Boolean.TRUE.equals(isRetryPersistModeUpdate));
}
// customize if update last or append new compensateStateInstLog
Object isCompensatePersistModeUpdate = node.get("IsCompensatePersistModeUpdate");
if (isCompensatePersistModeUpdate instanceof Boolean) {
stateMachine.setCompensatePersistModeUpdate(Boolean.TRUE.equals(isCompensatePersistModeUpdate));
}
Map<String, Object> statesNode = (Map<String, Object>) node.get("States");
statesNode.forEach((stateName, value) -> {
Map<String, Object> stateNode = (Map<String, Object>) value;
String stateType = (String) stateNode.get("Type");
StateParser<?> stateParser = StateParserFactory.getStateParser(stateType);
if (stateParser == null) {
throw new IllegalArgumentException("State Type [" + stateType + "] is not support");
}
State state = stateParser.parse(stateNode);
if (state instanceof BaseState) {
((BaseState) state).setName(stateName);
}
if (stateMachine.getState(stateName) != null) {
throw new IllegalArgumentException("State[name:" + stateName + "] is already exists");
}
stateMachine.putState(stateName, state);
});
Map<String, State> stateMap = stateMachine.getStates();
for (State state : stateMap.values()) {
if (state instanceof AbstractTaskState) {
AbstractTaskState taskState = (AbstractTaskState) state;
if (StringUtils.isNotBlank(taskState.getCompensateState())) {
taskState.setForUpdate(true);
State compState = stateMap.get(taskState.getCompensateState());
if (compState instanceof AbstractTaskState) {
((AbstractTaskState) compState).setForCompensation(true);
}
}
}
}
validator.validate(stateMachine);
return stateMachine;
| 204 | 919 | 1,123 | 52,690 |
TheAlgorithms_Java
|
Java/src/main/java/com/thealgorithms/sorts/QuickSort.java
|
QuickSort
|
partition
|
class QuickSort implements SortAlgorithm {
/**
* This method implements the Generic Quick Sort
*
* @param array The array to be sorted Sorts the array in increasing order
*/
@Override
public <T extends Comparable<T>> T[] sort(T[] array) {
doSort(array, 0, array.length - 1);
return array;
}
/**
* The sorting process
*
* @param left The first index of an array
* @param right The last index of an array
* @param array The array to be sorted
*/
private static <T extends Comparable<T>> void doSort(T[] array, int left, int right) {
if (left < right) {
int pivot = randomPartition(array, left, right);
doSort(array, left, pivot - 1);
doSort(array, pivot, right);
}
}
/**
* Randomize the array to avoid the basically ordered sequences
*
* @param array The array to be sorted
* @param left The first index of an array
* @param right The last index of an array
* @return the partition index of the array
*/
private static <T extends Comparable<T>> int randomPartition(T[] array, int left, int right) {
int randomIndex = left + (int) (Math.random() * (right - left + 1));
swap(array, randomIndex, right);
return partition(array, left, right);
}
/**
* This method finds the partition index for an array
*
* @param array The array to be sorted
* @param left The first index of an array
* @param right The last index of an array Finds the partition index of an
* array
*/
private static <T extends Comparable<T>> int partition(T[] array, int left, int right) {<FILL_FUNCTION_BODY>}
}
|
int mid = (left + right) >>> 1;
T pivot = array[mid];
while (left <= right) {
while (less(array[left], pivot)) {
++left;
}
while (less(pivot, array[right])) {
--right;
}
if (left <= right) {
swap(array, left, right);
++left;
--right;
}
}
return left;
| 490 | 122 | 612 | 63,661 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.