proj_name
stringclasses 26
values | relative_path
stringlengths 42
165
| class_name
stringlengths 3
46
| func_name
stringlengths 2
44
| masked_class
stringlengths 80
7.9k
| func_body
stringlengths 76
5.98k
| initial_context
stringclasses 74
values | parent_class_output
stringlengths 20
1.75k
| parent_class_output_re_type
sequencelengths 0
9
| parent_class_output_re_method
sequencelengths 0
35
| func_body_re_type
sequencelengths 0
14
| func_body_re_method
sequencelengths 0
39
| parent_class_output_re
dict | relevant_context
stringlengths 0
82.6k
| relevant_context_no_cmt
stringlengths 0
25.5k
| retrieved_names
stringlengths 39
1.24k
| retrieved_types
stringlengths 2
106k
| retrieved_methods
stringlengths 2
11.5k
| similar_methods
stringlengths 2
3.74k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
eirslett_frontend-maven-plugin | frontend-maven-plugin/frontend-maven-plugin/src/main/java/com/github/eirslett/maven/plugins/frontend/mojo/GruntMojo.java | GruntMojo | shouldExecute | class GruntMojo extends AbstractFrontendMojo {
/**
* Grunt arguments. Default is empty (runs just the "grunt" command).
*/
@Parameter(property = "frontend.grunt.arguments")
private String arguments;
/**
* Files that should be checked for changes, in addition to the srcdir files.
* Defaults to Gruntfile.js in the {@link #workingDirectory}.
*/
@Parameter(property = "triggerfiles")
private List<File> triggerfiles;
/**
* The directory containing front end files that will be processed by grunt.
* If this is set then files in the directory will be checked for
* modifications before running grunt.
*/
@Parameter(property = "srcdir")
private File srcdir;
/**
* The directory where front end files will be output by grunt. If this is
* set then they will be refreshed so they correctly show as modified in
* Eclipse.
*/
@Parameter(property = "outputdir")
private File outputdir;
/**
* Skips execution of this mojo.
*/
@Parameter(property = "skip.grunt", defaultValue = "${skip.grunt}")
private boolean skip;
@Component
private BuildContext buildContext;
@Override
protected boolean skipExecution() {
return this.skip;
}
@Override
public synchronized void execute(FrontendPluginFactory factory) throws TaskRunnerException {
if (shouldExecute()) {
factory.getGruntRunner().execute(arguments, environmentVariables);
if (outputdir != null) {
getLog().info("Refreshing files after grunt: " + outputdir);
buildContext.refresh(outputdir);
}
} else {
getLog().info("Skipping grunt as no modified files in " + srcdir);
}
}
private boolean shouldExecute() {<FILL_FUNCTION_BODY>}
} |
if (triggerfiles == null || triggerfiles.isEmpty()) {
triggerfiles = Arrays.asList(new File(workingDirectory, "Gruntfile.js"));
}
return MojoUtils.shouldExecute(buildContext, triggerfiles, srcdir);
| public abstract class AbstractFrontendMojo extends AbstractMojo {
@Component protected MojoExecution execution;
/**
* Whether you should skip while running in the test phase (default is false)
*/
@Parameter(property="skipTests",required=false,defaultValue="false") protected Boolean skipTests;
/**
* Set this to true to ignore a failure during testing. Its use is NOT RECOMMENDED, but quite convenient on occasion.
* @since 1.4
*/
@Parameter(property="maven.test.failure.ignore",defaultValue="false") protected boolean testFailureIgnore;
/**
* The base directory for running all Node commands. (Usually the directory that contains package.json)
*/
@Parameter(defaultValue="${basedir}",property="workingDirectory",required=false) protected File workingDirectory;
/**
* The base directory for installing node and npm.
*/
@Parameter(property="installDirectory",required=false) protected File installDirectory;
/**
* Additional environment variables to pass to the build.
*/
@Parameter protected Map<String,String> environmentVariables;
@Parameter(defaultValue="${project}",readonly=true) private MavenProject project;
@Parameter(defaultValue="${repositorySystemSession}",readonly=true) private RepositorySystemSession repositorySystemSession;
/**
* Determines if this execution should be skipped.
*/
private boolean skipTestPhase();
/**
* Determines if the current execution is during a testing phase (e.g., "test" or "integration-test").
*/
private boolean isTestingPhase();
protected abstract void execute( FrontendPluginFactory factory) throws FrontendException ;
/**
* Implemented by children to determine if this execution should be skipped.
*/
protected abstract boolean skipExecution();
@Override public void execute() throws MojoFailureException;
}
|
if (srcdir == null) {
return true;
}
if (triggerfiles == null) {
triggerfiles = new ArrayList<File>();
}
triggerfiles.add(new File(srcdir, "Gruntfile.js"));
return buildContext.hasModifiedFiles(triggerfiles);
| [
"List<File>",
"BuildContext",
"File"
] | [
"add",
"hasModifiedFiles"
] | [
"BuildContext",
"File",
"List<File>"
] | [
"shouldExecute",
"asList",
"isEmpty"
] | {
"methods": [
"add",
"hasModifiedFiles"
],
"similar_methods": [
"shouldExecute"
],
"types": [
"List<File>",
"BuildContext",
"File"
]
} | interface FileDownloader {
void download( String downloadUrl, String destination, String userName, String password) throws DownloadException ;
}
public interface InstallConfig {
File getInstallDirectory();
File getWorkingDirectory();
CacheResolver getCacheResolver();
Platform getPlatform();
}
private static void addArgument(StringBuilder argumentBuilder,List<String> arguments){
if (argumentBuilder.length() > 0) {
String argument=argumentBuilder.toString();
arguments.add(argument);
argumentBuilder.setLength(0);
}
}
private void downloadFile(String downloadUrl,File destination,String userName,String password) throws DownloadException {
this.logger.info("Downloading {} to {}",downloadUrl,destination);
this.fileDownloader.download(downloadUrl,destination.getPath(),userName,password);
}
private boolean shouldExecute(){
if (triggerfiles == null || triggerfiles.isEmpty()) {
triggerfiles=Arrays.asList(new File(workingDirectory,"gulpfile.js"));
}
return MojoUtils.shouldExecute(buildContext,triggerfiles,srcdir);
}
| interface FileDownloader {
void download( String downloadUrl, String destination, String userName, String password) throws DownloadException ;
}
public interface InstallConfig {
File getInstallDirectory();
File getWorkingDirectory();
CacheResolver getCacheResolver();
Platform getPlatform();
}
private static void addArgument(StringBuilder argumentBuilder,List<String> arguments){
if (argumentBuilder.length() > 0) {
String argument=argumentBuilder.toString();
arguments.add(argument);
argumentBuilder.setLength(0);
}
}
private void downloadFile(String downloadUrl,File destination,String userName,String password) throws DownloadException {
this.logger.info("Downloading {} to {}",downloadUrl,destination);
this.fileDownloader.download(downloadUrl,destination.getPath(),userName,password);
}
private boolean shouldExecute(){
if (triggerfiles == null || triggerfiles.isEmpty()) {
triggerfiles=Arrays.asList(new File(workingDirectory,"gulpfile.js"));
}
return MojoUtils.shouldExecute(buildContext,triggerfiles,srcdir);
}
| {"types": [{"List<File>": "FileDownloader"}, {"BuildContext": "InstallConfig"}, {"File": "FileDownloader"}], "methods": [{"add": "addArgument"}, {"hasModifiedFiles": "downloadFile"}], "similar_methods": [{"shouldExecute": "shouldExecute"}]} | [{"List<File>": {"retrieved_name": "FileDownloader", "raw_body": "interface FileDownloader {\n void download( String downloadUrl, String destination, String userName, String password) throws DownloadException ;\n}\n", "raw_body_no_cmt": "interface FileDownloader {\n void download( String downloadUrl, String destination, String userName, String password) throws DownloadException ;\n}\n"}}, {"BuildContext": {"retrieved_name": "InstallConfig", "raw_body": "public interface InstallConfig {\n File getInstallDirectory();\n File getWorkingDirectory();\n CacheResolver getCacheResolver();\n Platform getPlatform();\n}\n", "raw_body_no_cmt": "public interface InstallConfig {\n File getInstallDirectory();\n File getWorkingDirectory();\n CacheResolver getCacheResolver();\n Platform getPlatform();\n}\n"}}] | [{"add": {"retrieved_name": "addArgument", "raw_body": "private static void addArgument(StringBuilder argumentBuilder,List<String> arguments){\n if (argumentBuilder.length() > 0) {\n String argument=argumentBuilder.toString();\n arguments.add(argument);\n argumentBuilder.setLength(0);\n }\n}\n"}}, {"hasModifiedFiles": {"retrieved_name": "downloadFile", "raw_body": "private void downloadFile(String downloadUrl,File destination,String userName,String password) throws DownloadException {\n this.logger.info(\"Downloading {} to {}\",downloadUrl,destination);\n this.fileDownloader.download(downloadUrl,destination.getPath(),userName,password);\n}\n"}}] | [{"shouldExecute": {"retrieved_name": "shouldExecute", "raw_body": "private boolean shouldExecute(){\n if (triggerfiles == null || triggerfiles.isEmpty()) {\n triggerfiles=Arrays.asList(new File(workingDirectory,\"gulpfile.js\"));\n }\n return MojoUtils.shouldExecute(buildContext,triggerfiles,srcdir);\n}\n"}}] |
YunaiV_ruoyi-vue-pro | ruoyi-vue-pro/yudao-framework/yudao-spring-boot-starter-excel/src/main/java/cn/iocoder/yudao/framework/excel/core/convert/MoneyConvert.java | MoneyConvert | convertToExcelData | class MoneyConvert implements Converter<Integer> {
@Override
public Class<?> supportJavaTypeKey() {
throw new UnsupportedOperationException("暂不支持,也不需要");
}
@Override
public CellDataTypeEnum supportExcelTypeKey() {
throw new UnsupportedOperationException("暂不支持,也不需要");
}
@Override
public WriteCellData<String> convertToExcelData(Integer value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {<FILL_FUNCTION_BODY>}
} |
BigDecimal result = BigDecimal.valueOf(value)
.divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);
return new WriteCellData<>(result.toString());
|
return new WriteCellData<>(value + "元");
| [
"GlobalConfiguration",
"ExcelContentProperty"
] | [] | [
"GlobalConfiguration",
"BigDecimal",
"ExcelContentProperty"
] | [
"divide",
"toString",
"valueOf"
] | {
"methods": [],
"similar_methods": [
"convertToExcelData"
],
"types": [
"GlobalConfiguration",
"ExcelContentProperty"
]
} | @Configuration(proxyBeanMethods=false) @EnableWebSecurity public class SecurityConfiguration {
@Resource private TokenAuthenticationFilter tokenAuthenticationFilter;
@Resource private AccessDeniedHandlerImpl accessDeniedHandler;
@Resource private AuthenticationEntryPoint authenticationEntryPoint;
@Bean protected SecurityFilterChain filterChain( HttpSecurity httpSecurity) throws Exception;
}
/**
* Xss 配置属性
* @author 芋道源码
*/
@ConfigurationProperties(prefix="yudao.xss") @Validated @Data public class XssProperties {
/**
* 是否开启,默认为 true
*/
private boolean enable=true;
/**
* 需要排除的 URL,默认为空
*/
private List<String> excludeUrls=Collections.emptyList();
}
@Override public WriteCellData<String> convertToExcelData(Object object,ExcelContentProperty contentProperty,GlobalConfiguration globalConfiguration){
if (object == null) {
return new WriteCellData<>("");
}
String type=getType(contentProperty);
String value=String.valueOf(object);
String label=DictFrameworkUtils.getDictDataLabel(type,value);
if (label == null) {
log.error("[convertToExcelData][type({}) 转换不了 label({})]",type,value);
return new WriteCellData<>("");
}
return new WriteCellData<>(label);
}
| public class SecurityConfiguration {
private TokenAuthenticationFilter tokenAuthenticationFilter;
private AccessDeniedHandlerImpl accessDeniedHandler;
private AuthenticationEntryPoint authenticationEntryPoint;
protected SecurityFilterChain filterChain( HttpSecurity httpSecurity) throws Exception;
}
public class XssProperties {
private boolean enable=true;
private List<String> excludeUrls=Collections.emptyList();
}
@Override public WriteCellData<String> convertToExcelData(Object object,ExcelContentProperty contentProperty,GlobalConfiguration globalConfiguration){
if (object == null) {
return new WriteCellData<>("");
}
String type=getType(contentProperty);
String value=String.valueOf(object);
String label=DictFrameworkUtils.getDictDataLabel(type,value);
if (label == null) {
log.error("[convertToExcelData][type({}) 转换不了 label({})]",type,value);
return new WriteCellData<>("");
}
return new WriteCellData<>(label);
}
| {"types": [{"GlobalConfiguration": "SecurityConfiguration"}, {"ExcelContentProperty": "XssProperties"}], "similar_methods": [{"convertToExcelData": "convertToExcelData"}]} | [{"GlobalConfiguration": {"retrieved_name": "SecurityConfiguration", "raw_body": "@Configuration(proxyBeanMethods=false) @EnableWebSecurity public class SecurityConfiguration {\n @Resource private TokenAuthenticationFilter tokenAuthenticationFilter;\n @Resource private AccessDeniedHandlerImpl accessDeniedHandler;\n @Resource private AuthenticationEntryPoint authenticationEntryPoint;\n @Bean protected SecurityFilterChain filterChain( HttpSecurity httpSecurity) throws Exception;\n}\n", "raw_body_no_cmt": "public class SecurityConfiguration {\n private TokenAuthenticationFilter tokenAuthenticationFilter;\n private AccessDeniedHandlerImpl accessDeniedHandler;\n private AuthenticationEntryPoint authenticationEntryPoint;\n protected SecurityFilterChain filterChain( HttpSecurity httpSecurity) throws Exception;\n}\n"}}, {"ExcelContentProperty": {"retrieved_name": "XssProperties", "raw_body": "/** \n * Xss \u914d\u7f6e\u5c5e\u6027\n * @author \u828b\u9053\u6e90\u7801\n */\n@ConfigurationProperties(prefix=\"yudao.xss\") @Validated @Data public class XssProperties {\n /** \n * \u662f\u5426\u5f00\u542f\uff0c\u9ed8\u8ba4\u4e3a true\n */\n private boolean enable=true;\n /** \n * \u9700\u8981\u6392\u9664\u7684 URL\uff0c\u9ed8\u8ba4\u4e3a\u7a7a\n */\n private List<String> excludeUrls=Collections.emptyList();\n}\n", "raw_body_no_cmt": "public class XssProperties {\n private boolean enable=true;\n private List<String> excludeUrls=Collections.emptyList();\n}\n"}}] | [] | [{"convertToExcelData": {"retrieved_name": "convertToExcelData", "raw_body": "@Override public WriteCellData<String> convertToExcelData(Object object,ExcelContentProperty contentProperty,GlobalConfiguration globalConfiguration){\n if (object == null) {\n return new WriteCellData<>(\"\");\n }\n String type=getType(contentProperty);\n String value=String.valueOf(object);\n String label=DictFrameworkUtils.getDictDataLabel(type,value);\n if (label == null) {\n log.error(\"[convertToExcelData][type({}) \u8f6c\u6362\u4e0d\u4e86 label({})]\",type,value);\n return new WriteCellData<>(\"\");\n }\n return new WriteCellData<>(label);\n}\n"}}] |
|
javamelody_javamelody | javamelody/javamelody-core/src/main/java/net/bull/javamelody/internal/model/SamplingProfiler.java | SampledMethod | limitDataSize | class SampledMethod implements Comparable<SampledMethod>, Serializable {
private static final long serialVersionUID = 1L;
private long count;
private final String className;
private final String methodName;
private transient int hash;
SampledMethod(String className, String methodName) {
super();
assert className != null;
assert methodName != null;
this.className = className;
this.methodName = methodName;
this.hash = className.hashCode() * 31 + methodName.hashCode();
}
// hash is transient
private Object readResolve() {
this.hash = className.hashCode() * 31 + methodName.hashCode();
return this;
}
void incrementCount() {
count++;
}
public long getCount() {
return count;
}
void setCount(long count) {
this.count = count;
}
public String getClassName() {
return this.className;
}
public String getMethodName() {
return this.methodName;
}
@Override
public int compareTo(SampledMethod method) {
return Long.compare(method.count, count);
}
@Override
public int hashCode() {
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
final SampledMethod other = (SampledMethod) obj;
return methodName.equals(other.methodName) && className.equals(other.className);
}
@Override
public String toString() {
return className + '.' + methodName;
}
}
/**
* Constructor.
* Excluded packages by default "java,sun,com.sun,javax,org.apache,org.hibernate,oracle,org.postgresql,org.eclipse"
*/
public SamplingProfiler() {
super();
this.excludedPackages = DEFAULT_EXCLUDED_PACKAGES;
this.includedPackages = null;
}
/**
* Constructor.
* @param excludedPackages List of excluded packages (can be null)
* @param includedPackages List of included packages (can be null)
*/
public SamplingProfiler(List<String> excludedPackages, List<String> includedPackages) {
super();
assert excludedPackages != null || includedPackages != null;
// In general, there are either excluded packages or included packages.
// (If both, excluded result has priority over included result: it excludes some included.)
this.excludedPackages = verifyPackageNames(excludedPackages);
this.includedPackages = verifyPackageNames(includedPackages);
}
/**
* Constructor.
* @param excludedPackages List of excluded packages separated by comma (can be null)
* @param includedPackages List of included packages separated by comma (can be null)
*/
public SamplingProfiler(String excludedPackages, String includedPackages) {
this(splitPackageNames(excludedPackages), splitPackageNames(includedPackages));
// In general, there are either excluded packages or included packages.
// (If both, excluded result has priority over included result: it excludes some included.)
}
private static List<String> splitPackageNames(String packageNames) {
if (packageNames == null) {
return null;
}
return Arrays.asList(packageNames.split(","));
}
private String[] verifyPackageNames(List<String> packageNames) {
if (packageNames == null) {
return null;
}
final String[] packages = packageNames.toArray(new String[0]);
for (int i = 0; i < packages.length; i++) {
packages[i] = packages[i].trim(); // NOPMD
if (packages[i].isEmpty()) {
throw new IllegalArgumentException(
"A package can not be empty, item " + i + " in " + packageNames);
}
if (!packages[i].endsWith(".")) {
packages[i] = packages[i] + '.'; // NOPMD
}
}
return packages;
}
public synchronized void update() {
final Map<Thread, StackTraceElement[]> stackTraces = Thread.getAllStackTraces();
try {
final Thread currentThread = Thread.currentThread();
for (final Map.Entry<Thread, StackTraceElement[]> entry : stackTraces.entrySet()) {
final Thread thread = entry.getKey();
final StackTraceElement[] stackTrace = entry.getValue();
if (stackTrace.length > 0 && thread.getState() == Thread.State.RUNNABLE
&& thread != currentThread) {
for (final StackTraceElement element : stackTrace) {
if (!isPackageExcluded(element)) {
addSample(element);
break;
}
}
}
}
} finally {
limitDataSize();
}
}
private void addSample(StackTraceElement element) {
final SampledMethod key = new SampledMethod(element.getClassName(),
element.getMethodName());
// or final String key = element.getClassName() + '.' + element.getMethodName();
SampledMethod method = this.data.get(key);
if (method == null) {
method = key;
// or method = new SampledMethod(element.getClassName(), element.getMethodName());
this.data.put(key, method);
}
// on pourrait incrémenter la valeur selon l'augmentation de cpuTime pour ce thread,
// mais l'intervalle entre deux samples est probablement trop grand
// pour que le cpu du thread entre les deux intervalles ait un rapport avec cette méthode
method.incrementCount();
}
private void limitDataSize() {<FILL_FUNCTION_BODY> |
long minCount = 1;
int size = data.size();
while (size > MAX_DATA_SIZE) {
final Iterator<SampledMethod> iterator = data.keySet().iterator();
while (iterator.hasNext() && size > MAX_DATA_SIZE) {
final SampledMethod method = iterator.next();
if (method.getCount() <= minCount) {
iterator.remove();
size--;
}
}
minCount++;
}
|
if (this.data.size() > MAX_DATA_SIZE) {
final List<SampledMethod> list = new ArrayList<>(this.data.values());
Collections.sort(list);
final int toRemove = list.size() - MAX_DATA_SIZE;
for (int i = 0; i < toRemove; i++) {
this.data.remove(list.get(i));
}
}
| [
"Map<SampledMethod,SampledMethod>",
"Iterator<SampledMethod>",
"SampledMethod"
] | [
"iterator",
"size",
"remove",
"next",
"keySet",
"hasNext",
"getCount"
] | [
"Iterator<SampledMethod>",
"Map<SampledMethod,SampledMethod>",
"SampledMethod"
] | [
"getCount",
"hasNext",
"remove",
"size",
"keySet",
"iterator",
"next"
] | {
"methods": [
"iterator",
"size",
"remove",
"next",
"keySet",
"hasNext",
"getCount"
],
"similar_methods": [
"limitDataSize"
],
"types": [
"Map<SampledMethod,SampledMethod>",
"Iterator<SampledMethod>",
"SampledMethod"
]
} | /**
* Maps of http requests to methods of controllers, based on request parameters and annotations on methods and parameters.
* @param < T > Type of the controller having methods annotated with @HttpPart
* @author Emeric Vernat
*/
class RequestToMethodMapper<T> {
private final Map<HttpPart,Method> methodsByPart=new HashMap<>();
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @interface RequestPart { /**
* @return String
*/
HttpPart value();
}
@Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) @interface RequestParameter { /**
* @return String
*/
HttpParameter value();
}
@Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) @interface RequestAttribute { /**
* @return String
*/
String value();
}
@Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) @interface RequestHeader { /**
* @return String
*/
String value();
}
RequestToMethodMapper( Class<T> clazz);
void invoke( HttpServletRequest httpRequest, T controller) throws IOException;
Object invokeAndReturn( HttpServletRequest httpRequest, T controller) throws IOException;
private Object[] getParameterValues( HttpServletRequest request, Method method);
}
/**
* Test unitaire de la classe SamplingProfiler.
* @author Emeric Vernat
*/
public class TestSamplingProfiler {
private static final int NB_ROWS=100;
/**
* Test.
*/
@Test public void test1();
/**
* Test.
*/
@Test public void test2();
/**
* Test that classes from packages are included.
*/
@Test public void testClassesInInclude();
/**
* Test that classes from packages are included, where include pattern does not match any packages.
*/
@Test public void testClassesInIncludeNoneMatching();
/**
* Test.
*/
@Test public void testConstructor();
/**
* Test include packages.
*/
@Test public void testConstructorInclude();
/**
* Test.
*/
@SuppressWarnings("unused") @Test(expected=Exception.class) public void testConstructor2();
/**
* Test.
*/
@Test public void testConstructor3();
/**
* Test.
* @throws IOException e
* @throws ClassNotFoundException e
*/
@Test public void testSampledMethod() throws IOException, ClassNotFoundException;
private static void assertEmptyHotspots( SamplingProfiler samplingProfiler);
private static void assertNotEmptyHotspots( final SamplingProfiler samplingProfiler);
private static void doSomeWorkAndTakeSample( SamplingProfiler samplingProfiler);
static class DummyTask implements Runnable {
@Override public void run();
}
/**
* Compute PI just to have something to do. from http://rosettacode.org/wiki/Pi#Java
*/
static class Pi {
private static final BigInteger TWO=BigInteger.valueOf(2);
private static final BigInteger THREE=BigInteger.valueOf(3);
private static final BigInteger FOUR=BigInteger.valueOf(4);
private static final BigInteger SEVEN=BigInteger.valueOf(7);
private BigInteger q=BigInteger.ONE;
private BigInteger r=BigInteger.ZERO;
private BigInteger t=BigInteger.ONE;
private BigInteger k=BigInteger.ONE;
private BigInteger n=BigInteger.valueOf(3);
private BigInteger l=BigInteger.valueOf(3);
/**
* Start.
* @param limit Number of digits
*/
public void calcPiDigits( int limit);
}
}
/**
* {@inheritDoc}
*/
@Override public Object invoke(Object proxy,Method method,Object[] args) throws Throwable {
final String methodName=method.getName();
if (isEqualsMethod(methodName,args)) {
return areConnectionsEquals(args[0]);
}
else if (isHashCodeMethod(methodName,args)) {
return connection.hashCode();
}
try {
Object result=method.invoke(connection,args);
if (result instanceof Statement) {
final String requestName;
if ("prepareStatement".equals(methodName) || "prepareCall".equals(methodName)) {
requestName=(String)args[0];
}
else {
requestName=null;
}
result=createStatementProxy(requestName,(Statement)result,(Connection)proxy);
}
return result;
}
finally {
if ("close".equals(methodName) && !alreadyClosed) {
USED_CONNECTION_COUNT.decrementAndGet();
USED_CONNECTION_INFORMATIONS.remove(ConnectionInformations.getUniqueIdOfConnection(connection));
alreadyClosed=true;
}
}
}
static int getObjectSize(Object object){
if (!(object instanceof Serializable)) {
return -1;
}
final Serializable serializable=(Serializable)object;
synchronized (TEMP_OUTPUT) {
TEMP_OUTPUT.reset();
try {
try (ObjectOutputStream out=new ObjectOutputStream(TEMP_OUTPUT)){
out.writeObject(serializable);
}
return TEMP_OUTPUT.size();
}
catch ( final Throwable e) {
return -1;
}
}
}
/**
* {@inheritDoc}
*/
@Override public void remove(Component comp){
contentPane.remove(comp);
}
void nextRow(){
if (oddRow) {
getDefaultCell().setGrayFill(0.97f);
}
else {
getDefaultCell().setGrayFill(1);
}
oddRow=!oddRow;
}
@Override public void keyPressed(final KeyEvent keyEvent){
final Object source=keyEvent.getSource();
if (source instanceof MTextField) {
((MTextField<?>)source).keyEvent(keyEvent);
}
}
private String getNextId(){
return 'x' + pid + '_'+ sequence++;
}
/**
* @return La liste des {@link Counter}s de ce collector
*/
public List<Counter> getCounters(){
return counters;
}
/**
* {@inheritDoc}
*/
@Override public void setMaximumSize(Dimension maximumSize){
contentPane.setMaximumSize(maximumSize);
}
| class RequestToMethodMapper<T> {
private final Map<HttpPart,Method> methodsByPart=new HashMap<>();
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @interface RequestPart { /**
* @return String
*/
HttpPart value();
}
@Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) @interface RequestParameter { /**
* @return String
*/
HttpParameter value();
}
@Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) @interface RequestAttribute { /**
* @return String
*/
String value();
}
@Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) @interface RequestHeader { /**
* @return String
*/
String value();
}
RequestToMethodMapper( Class<T> clazz);
void invoke( HttpServletRequest httpRequest, T controller) throws IOException;
Object invokeAndReturn( HttpServletRequest httpRequest, T controller) throws IOException;
private Object[] getParameterValues( HttpServletRequest request, Method method);
}
public class TestSamplingProfiler {
private static final int NB_ROWS=100;
public void test1();
public void test2();
public void testClassesInInclude();
public void testClassesInIncludeNoneMatching();
public void testConstructor();
public void testConstructorInclude();
public void testConstructor2();
public void testConstructor3();
public void testSampledMethod() throws IOException, ClassNotFoundException;
private static void assertEmptyHotspots( SamplingProfiler samplingProfiler);
private static void assertNotEmptyHotspots( final SamplingProfiler samplingProfiler);
private static void doSomeWorkAndTakeSample( SamplingProfiler samplingProfiler);
static class DummyTask implements Runnable {
public void run();
}
static class Pi {
private static final BigInteger TWO=BigInteger.valueOf(2);
private static final BigInteger THREE=BigInteger.valueOf(3);
private static final BigInteger FOUR=BigInteger.valueOf(4);
private static final BigInteger SEVEN=BigInteger.valueOf(7);
private BigInteger q=BigInteger.ONE;
private BigInteger r=BigInteger.ZERO;
private BigInteger t=BigInteger.ONE;
private BigInteger k=BigInteger.ONE;
private BigInteger n=BigInteger.valueOf(3);
private BigInteger l=BigInteger.valueOf(3);
public void calcPiDigits( int limit);
}
}
/**
* {@inheritDoc}
*/
@Override public Object invoke(Object proxy,Method method,Object[] args) throws Throwable {
final String methodName=method.getName();
if (isEqualsMethod(methodName,args)) {
return areConnectionsEquals(args[0]);
}
else if (isHashCodeMethod(methodName,args)) {
return connection.hashCode();
}
try {
Object result=method.invoke(connection,args);
if (result instanceof Statement) {
final String requestName;
if ("prepareStatement".equals(methodName) || "prepareCall".equals(methodName)) {
requestName=(String)args[0];
}
else {
requestName=null;
}
result=createStatementProxy(requestName,(Statement)result,(Connection)proxy);
}
return result;
}
finally {
if ("close".equals(methodName) && !alreadyClosed) {
USED_CONNECTION_COUNT.decrementAndGet();
USED_CONNECTION_INFORMATIONS.remove(ConnectionInformations.getUniqueIdOfConnection(connection));
alreadyClosed=true;
}
}
}
static int getObjectSize(Object object){
if (!(object instanceof Serializable)) {
return -1;
}
final Serializable serializable=(Serializable)object;
synchronized (TEMP_OUTPUT) {
TEMP_OUTPUT.reset();
try {
try (ObjectOutputStream out=new ObjectOutputStream(TEMP_OUTPUT)){
out.writeObject(serializable);
}
return TEMP_OUTPUT.size();
}
catch ( final Throwable e) {
return -1;
}
}
}
/**
* {@inheritDoc}
*/
@Override public void remove(Component comp){
contentPane.remove(comp);
}
void nextRow(){
if (oddRow) {
getDefaultCell().setGrayFill(0.97f);
}
else {
getDefaultCell().setGrayFill(1);
}
oddRow=!oddRow;
}
@Override public void keyPressed(final KeyEvent keyEvent){
final Object source=keyEvent.getSource();
if (source instanceof MTextField) {
((MTextField<?>)source).keyEvent(keyEvent);
}
}
private String getNextId(){
return 'x' + pid + '_'+ sequence++;
}
/**
* @return La liste des {@link Counter}s de ce collector
*/
public List<Counter> getCounters(){
return counters;
}
/**
* {@inheritDoc}
*/
@Override public void setMaximumSize(Dimension maximumSize){
contentPane.setMaximumSize(maximumSize);
}
| {"types": [{"Map<SampledMethod,SampledMethod>": "RequestToMethodMapper"}, {"Iterator<SampledMethod>": "TestSamplingProfiler"}, {"SampledMethod": "TestSamplingProfiler"}], "methods": [{"iterator": "invoke"}, {"size": "getObjectSize"}, {"remove": "remove"}, {"next": "nextRow"}, {"keySet": "keyPressed"}, {"hasNext": "getNextId"}, {"getCount": "getCounters"}], "similar_methods": [{"limitDataSize": "setMaximumSize"}]} | [{"Map<SampledMethod,SampledMethod>": {"retrieved_name": "RequestToMethodMapper", "raw_body": "/** \n * Maps of http requests to methods of controllers, based on request parameters and annotations on methods and parameters.\n * @param < T > Type of the controller having methods annotated with @HttpPart\n * @author Emeric Vernat\n */\nclass RequestToMethodMapper<T> {\n private final Map<HttpPart,Method> methodsByPart=new HashMap<>();\n @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @interface RequestPart { /** \n * @return String\n */\n HttpPart value();\n}\n @Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) @interface RequestParameter { /** \n * @return String\n */\n HttpParameter value();\n}\n @Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) @interface RequestAttribute { /** \n * @return String\n */\n String value();\n}\n @Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) @interface RequestHeader { /** \n * @return String\n */\n String value();\n}\n RequestToMethodMapper( Class<T> clazz);\n void invoke( HttpServletRequest httpRequest, T controller) throws IOException;\n Object invokeAndReturn( HttpServletRequest httpRequest, T controller) throws IOException;\n private Object[] getParameterValues( HttpServletRequest request, Method method);\n}\n", "raw_body_no_cmt": "class RequestToMethodMapper<T> {\n private final Map<HttpPart,Method> methodsByPart=new HashMap<>();\n @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @interface RequestPart { /** \n * @return String\n */\n HttpPart value();\n}\n @Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) @interface RequestParameter { /** \n * @return String\n */\n HttpParameter value();\n}\n @Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) @interface RequestAttribute { /** \n * @return String\n */\n String value();\n}\n @Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) @interface RequestHeader { /** \n * @return String\n */\n String value();\n}\n RequestToMethodMapper( Class<T> clazz);\n void invoke( HttpServletRequest httpRequest, T controller) throws IOException;\n Object invokeAndReturn( HttpServletRequest httpRequest, T controller) throws IOException;\n private Object[] getParameterValues( HttpServletRequest request, Method method);\n}\n"}}, {"Iterator<SampledMethod>": {"retrieved_name": "TestSamplingProfiler", "raw_body": "/** \n * Test unitaire de la classe SamplingProfiler.\n * @author Emeric Vernat\n */\npublic class TestSamplingProfiler {\n private static final int NB_ROWS=100;\n /** \n * Test.\n */\n @Test public void test1();\n /** \n * Test.\n */\n @Test public void test2();\n /** \n * Test that classes from packages are included.\n */\n @Test public void testClassesInInclude();\n /** \n * Test that classes from packages are included, where include pattern does not match any packages.\n */\n @Test public void testClassesInIncludeNoneMatching();\n /** \n * Test.\n */\n @Test public void testConstructor();\n /** \n * Test include packages.\n */\n @Test public void testConstructorInclude();\n /** \n * Test.\n */\n @SuppressWarnings(\"unused\") @Test(expected=Exception.class) public void testConstructor2();\n /** \n * Test.\n */\n @Test public void testConstructor3();\n /** \n * Test.\n * @throws IOException e\n * @throws ClassNotFoundException e\n */\n @Test public void testSampledMethod() throws IOException, ClassNotFoundException;\n private static void assertEmptyHotspots( SamplingProfiler samplingProfiler);\n private static void assertNotEmptyHotspots( final SamplingProfiler samplingProfiler);\n private static void doSomeWorkAndTakeSample( SamplingProfiler samplingProfiler);\nstatic class DummyTask implements Runnable {\n @Override public void run();\n }\n /** \n * Compute PI just to have something to do. from http://rosettacode.org/wiki/Pi#Java\n */\nstatic class Pi {\n private static final BigInteger TWO=BigInteger.valueOf(2);\n private static final BigInteger THREE=BigInteger.valueOf(3);\n private static final BigInteger FOUR=BigInteger.valueOf(4);\n private static final BigInteger SEVEN=BigInteger.valueOf(7);\n private BigInteger q=BigInteger.ONE;\n private BigInteger r=BigInteger.ZERO;\n private BigInteger t=BigInteger.ONE;\n private BigInteger k=BigInteger.ONE;\n private BigInteger n=BigInteger.valueOf(3);\n private BigInteger l=BigInteger.valueOf(3);\n /** \n * Start.\n * @param limit Number of digits\n */\n public void calcPiDigits( int limit);\n }\n}\n", "raw_body_no_cmt": "public class TestSamplingProfiler {\n private static final int NB_ROWS=100;\n public void test1();\n public void test2();\n public void testClassesInInclude();\n public void testClassesInIncludeNoneMatching();\n public void testConstructor();\n public void testConstructorInclude();\n public void testConstructor2();\n public void testConstructor3();\n public void testSampledMethod() throws IOException, ClassNotFoundException;\n private static void assertEmptyHotspots( SamplingProfiler samplingProfiler);\n private static void assertNotEmptyHotspots( final SamplingProfiler samplingProfiler);\n private static void doSomeWorkAndTakeSample( SamplingProfiler samplingProfiler);\nstatic class DummyTask implements Runnable {\n public void run();\n }\n static class Pi {\n private static final BigInteger TWO=BigInteger.valueOf(2);\n private static final BigInteger THREE=BigInteger.valueOf(3);\n private static final BigInteger FOUR=BigInteger.valueOf(4);\n private static final BigInteger SEVEN=BigInteger.valueOf(7);\n private BigInteger q=BigInteger.ONE;\n private BigInteger r=BigInteger.ZERO;\n private BigInteger t=BigInteger.ONE;\n private BigInteger k=BigInteger.ONE;\n private BigInteger n=BigInteger.valueOf(3);\n private BigInteger l=BigInteger.valueOf(3);\n public void calcPiDigits( int limit);\n }\n}\n"}}] | [{"iterator": {"retrieved_name": "invoke", "raw_body": "/** \n * {@inheritDoc} \n */\n@Override public Object invoke(Object proxy,Method method,Object[] args) throws Throwable {\n final String methodName=method.getName();\n if (isEqualsMethod(methodName,args)) {\n return areConnectionsEquals(args[0]);\n }\n else if (isHashCodeMethod(methodName,args)) {\n return connection.hashCode();\n }\n try {\n Object result=method.invoke(connection,args);\n if (result instanceof Statement) {\n final String requestName;\n if (\"prepareStatement\".equals(methodName) || \"prepareCall\".equals(methodName)) {\n requestName=(String)args[0];\n }\n else {\n requestName=null;\n }\n result=createStatementProxy(requestName,(Statement)result,(Connection)proxy);\n }\n return result;\n }\n finally {\n if (\"close\".equals(methodName) && !alreadyClosed) {\n USED_CONNECTION_COUNT.decrementAndGet();\n USED_CONNECTION_INFORMATIONS.remove(ConnectionInformations.getUniqueIdOfConnection(connection));\n alreadyClosed=true;\n }\n }\n}\n"}}, {"size": {"retrieved_name": "getObjectSize", "raw_body": "static int getObjectSize(Object object){\n if (!(object instanceof Serializable)) {\n return -1;\n }\n final Serializable serializable=(Serializable)object;\nsynchronized (TEMP_OUTPUT) {\n TEMP_OUTPUT.reset();\n try {\n try (ObjectOutputStream out=new ObjectOutputStream(TEMP_OUTPUT)){\n out.writeObject(serializable);\n }\n return TEMP_OUTPUT.size();\n }\n catch ( final Throwable e) {\n return -1;\n }\n }\n}\n"}}, {"remove": {"retrieved_name": "remove", "raw_body": "/** \n * {@inheritDoc} \n */\n@Override public void remove(Component comp){\n contentPane.remove(comp);\n}\n"}}, {"next": {"retrieved_name": "nextRow", "raw_body": "void nextRow(){\n if (oddRow) {\n getDefaultCell().setGrayFill(0.97f);\n }\n else {\n getDefaultCell().setGrayFill(1);\n }\n oddRow=!oddRow;\n}\n"}}, {"keySet": {"retrieved_name": "keyPressed", "raw_body": "@Override public void keyPressed(final KeyEvent keyEvent){\n final Object source=keyEvent.getSource();\n if (source instanceof MTextField) {\n ((MTextField<?>)source).keyEvent(keyEvent);\n }\n}\n"}}, {"hasNext": {"retrieved_name": "getNextId", "raw_body": "private String getNextId(){\n return 'x' + pid + '_'+ sequence++;\n}\n"}}, {"getCount": {"retrieved_name": "getCounters", "raw_body": "/** \n * @return La liste des {@link Counter}s de ce collector\n */\npublic List<Counter> getCounters(){\n return counters;\n}\n"}}] | [{"limitDataSize": {"retrieved_name": "setMaximumSize", "raw_body": "/** \n * {@inheritDoc} \n */\n@Override public void setMaximumSize(Dimension maximumSize){\n contentPane.setMaximumSize(maximumSize);\n}\n"}}] |
|
logfellow_logstash-logback-encoder | logstash-logback-encoder/src/main/java/net/logstash/logback/appender/AsyncDisruptorAppender.java | EventClearingEventHandler | stop | class EventClearingEventHandler<Event> implements SequenceReportingEventHandler<LogEvent<Event>>, LifecycleAware {
private final EventHandler<LogEvent<Event>> delegate;
private Sequence sequenceCallback;
EventClearingEventHandler(EventHandler<LogEvent<Event>> delegate) {
super();
this.delegate = delegate;
}
@Override
public void onEvent(LogEvent<Event> event, long sequence, boolean endOfBatch) throws Exception {
try {
delegate.onEvent(event, sequence, endOfBatch);
} finally {
/*
* Clear the event so that it can be garbage collected.
*/
event.recycle();
/*
* Notify the BatchEventProcessor that the sequence has progressed.
* Without this callback the sequence would not be progressed
* until the batch has completely finished.
*/
sequenceCallback.set(sequence);
}
}
@Override
public void onStart() {
if (delegate instanceof LifecycleAware) {
((LifecycleAware) delegate).onStart();
}
}
@Override
public void onShutdown() {
if (delegate instanceof LifecycleAware) {
((LifecycleAware) delegate).onShutdown();
}
}
@Override
public void setSequenceCallback(final Sequence sequenceCallback) {
this.sequenceCallback = sequenceCallback;
}
}
@Override
public void start() {
if (addDefaultStatusListener && getStatusManager() != null && getStatusManager().getCopyOfStatusListenerList().isEmpty()) {
LevelFilteringStatusListener statusListener = new LevelFilteringStatusListener();
statusListener.setLevelValue(Status.WARN);
statusListener.setDelegate(new OnConsoleStatusListener());
statusListener.setContext(getContext());
statusListener.start();
getStatusManager().add(statusListener);
}
this.disruptor = new Disruptor<>(
this.eventFactory,
this.ringBufferSize,
this.threadFactory,
this.producerType,
this.waitStrategy);
/*
* Define the exceptionHandler first, so that it applies
* to all future eventHandlers.
*/
this.disruptor.setDefaultExceptionHandler(this.exceptionHandler);
this.disruptor.handleEventsWith(new EventClearingEventHandler<>(createEventHandler()));
this.disruptor.start();
super.start();
fireAppenderStarted();
}
@Override
public void stop() {<FILL_FUNCTION_BODY> |
/*
* Check super.isStarted() instead of isStarted() because subclasses
* might override isStarted() to perform other comparisons that we don't
* want to check here. Those should be checked by subclasses
* prior to calling super.stop()
*/
if (!super.isStarted()) {
return;
}
/*
* Don't allow any more events to be appended.
*/
super.stop();
/*
* Shutdown Disruptor
*
* Calling Disruptor#shutdown() will wait until all enqueued events are fully processed,
* but this waiting happens in a busy-spin. To avoid wasting CPU we wait for at most the configured
* grace period before asking the Disruptor for an immediate shutdown.
*/
long deadline = getShutdownGracePeriod().getMilliseconds() < 0 ? Long.MAX_VALUE : System.currentTimeMillis() + getShutdownGracePeriod().getMilliseconds();
while (!isRingBufferEmpty() && (System.currentTimeMillis() < deadline)) {
LockSupport.parkNanos(SLEEP_TIME_DURING_SHUTDOWN);
}
this.disruptor.halt();
if (!isRingBufferEmpty()) {
addWarn("Some queued events have not been logged due to requested shutdown");
}
fireAppenderStopped();
|
super.stop();
if (this.disruptor != null) {
this.disruptor.shutdown();
}
fireAppenderStopped();
| [
"Disruptor<LogEvent<Event>>"
] | [
"halt",
"getMilliseconds",
"parkNanos",
"currentTimeMillis",
"isStarted"
] | [
"Disruptor<LogEvent<Event>>"
] | [
"isStarted",
"parkNanos",
"currentTimeMillis",
"halt",
"getMilliseconds"
] | {
"methods": [
"halt",
"getMilliseconds",
"parkNanos",
"currentTimeMillis",
"isStarted"
],
"similar_methods": [
"stop"
],
"types": [
"Disruptor<LogEvent<Event>>"
]
} | /**
* A {@link DelegatingAsyncDisruptorAppender} for {@link ILoggingEvent}s.
*/
public class LoggingEventAsyncDisruptorAppender extends DelegatingAsyncDisruptorAppender<ILoggingEvent,AppenderListener<ILoggingEvent>> {
/**
* Set to true if the caller data should be captured before publishing the event to the {@link RingBuffer}
*/
private boolean includeCallerData;
protected void prepareForDeferredProcessing( ILoggingEvent event);
public boolean isIncludeCallerData();
public void setIncludeCallerData( boolean includeCallerData);
}
public static void stop(Object component){
if (component instanceof LifeCycle) {
((LifeCycle)component).stop();
}
}
@TestFactory public Collection<DynamicTest> checkMillisDigits(){
return doForAllSupportedFormats(zone,(formatter,fast) -> {
Instant instant=ZonedDateTime.of(2020,01,01,10,20,0,0,zone).toInstant();
assertThat(fast.format(instant)).isEqualTo(formatter.format(instant));
instant=ZonedDateTime.of(2020,01,01,10,20,30,0,zone).toInstant();
assertThat(fast.format(instant)).isEqualTo(formatter.format(instant));
instant=ZonedDateTime.of(2020,01,01,10,20,30,1,zone).toInstant();
assertThat(fast.format(instant)).isEqualTo(formatter.format(instant));
instant=ZonedDateTime.of(2020,01,01,10,20,30,(int)TimeUnit.MILLISECONDS.toNanos(1),zone).toInstant();
assertThat(fast.format(instant)).isEqualTo(formatter.format(instant));
instant=ZonedDateTime.of(2020,01,01,10,20,30,(int)TimeUnit.MILLISECONDS.toNanos(10),zone).toInstant();
assertThat(fast.format(instant)).isEqualTo(formatter.format(instant));
instant=ZonedDateTime.of(2020,01,01,10,20,30,(int)TimeUnit.MILLISECONDS.toNanos(100),zone).toInstant();
assertThat(fast.format(instant)).isEqualTo(formatter.format(instant));
instant=ZonedDateTime.of(2020,01,01,10,20,30,(int)TimeUnit.MILLISECONDS.toNanos(123),zone).toInstant();
assertThat(fast.format(instant)).isEqualTo(formatter.format(instant));
instant=ZonedDateTime.of(2020,01,01,10,20,30,123_400_000,zone).toInstant();
assertThat(fast.format(instant)).isEqualTo(formatter.format(instant));
}
);
}
/**
* Parse a {@link JsonNode} and produce the corresponding {@link NodeWriter}.
* @param node the {@link JsonNode} to parse.
* @return a {@link NodeWriter} corresponding to the given JSON node
* @throws JsonPatternException denotes an invalid pattern
*/
private NodeWriter<Event> parseNode(JsonPointer location,JsonNode node) throws JsonPatternException {
if (node.isTextual()) {
try {
ValueGetter<Event,?> getter=makeComputableValueGetter(node.asText());
return new ValueWriter<>(getter);
}
catch ( RuntimeException e) {
String msg="Invalid JSON property '" + location + "' (was '"+ node.asText()+ "'): "+ e.getMessage();
throw new JsonPatternException(msg,e);
}
}
if (node.isArray()) {
return parseArray(location,(ArrayNode)node);
}
if (node.isObject()) {
return parseObject(location,(ObjectNode)node);
}
return new ValueWriter<>(g -> node);
}
@TestFactory public Collection<DynamicTest> checkMillisDigits(){
return doForAllSupportedFormats(zone,(formatter,fast) -> {
Instant instant=ZonedDateTime.of(2020,01,01,10,20,0,0,zone).toInstant();
assertThat(fast.format(instant)).isEqualTo(formatter.format(instant));
instant=ZonedDateTime.of(2020,01,01,10,20,30,0,zone).toInstant();
assertThat(fast.format(instant)).isEqualTo(formatter.format(instant));
instant=ZonedDateTime.of(2020,01,01,10,20,30,1,zone).toInstant();
assertThat(fast.format(instant)).isEqualTo(formatter.format(instant));
instant=ZonedDateTime.of(2020,01,01,10,20,30,(int)TimeUnit.MILLISECONDS.toNanos(1),zone).toInstant();
assertThat(fast.format(instant)).isEqualTo(formatter.format(instant));
instant=ZonedDateTime.of(2020,01,01,10,20,30,(int)TimeUnit.MILLISECONDS.toNanos(10),zone).toInstant();
assertThat(fast.format(instant)).isEqualTo(formatter.format(instant));
instant=ZonedDateTime.of(2020,01,01,10,20,30,(int)TimeUnit.MILLISECONDS.toNanos(100),zone).toInstant();
assertThat(fast.format(instant)).isEqualTo(formatter.format(instant));
instant=ZonedDateTime.of(2020,01,01,10,20,30,(int)TimeUnit.MILLISECONDS.toNanos(123),zone).toInstant();
assertThat(fast.format(instant)).isEqualTo(formatter.format(instant));
instant=ZonedDateTime.of(2020,01,01,10,20,30,123_400_000,zone).toInstant();
assertThat(fast.format(instant)).isEqualTo(formatter.format(instant));
}
);
}
@Override public boolean isStarted(){
CountDownLatch latch=this.shutdownLatch;
return latch != null && latch.getCount() != 0;
}
@Override public void stop(){
super.stop();
getLayout().stop();
fireAppenderStopped();
}
| public class LoggingEventAsyncDisruptorAppender extends DelegatingAsyncDisruptorAppender<ILoggingEvent,AppenderListener<ILoggingEvent>> {
private boolean includeCallerData;
protected void prepareForDeferredProcessing( ILoggingEvent event);
public boolean isIncludeCallerData();
public void setIncludeCallerData( boolean includeCallerData);
}
public static void stop(Object component){
if (component instanceof LifeCycle) {
((LifeCycle)component).stop();
}
}
@TestFactory public Collection<DynamicTest> checkMillisDigits(){
return doForAllSupportedFormats(zone,(formatter,fast) -> {
Instant instant=ZonedDateTime.of(2020,01,01,10,20,0,0,zone).toInstant();
assertThat(fast.format(instant)).isEqualTo(formatter.format(instant));
instant=ZonedDateTime.of(2020,01,01,10,20,30,0,zone).toInstant();
assertThat(fast.format(instant)).isEqualTo(formatter.format(instant));
instant=ZonedDateTime.of(2020,01,01,10,20,30,1,zone).toInstant();
assertThat(fast.format(instant)).isEqualTo(formatter.format(instant));
instant=ZonedDateTime.of(2020,01,01,10,20,30,(int)TimeUnit.MILLISECONDS.toNanos(1),zone).toInstant();
assertThat(fast.format(instant)).isEqualTo(formatter.format(instant));
instant=ZonedDateTime.of(2020,01,01,10,20,30,(int)TimeUnit.MILLISECONDS.toNanos(10),zone).toInstant();
assertThat(fast.format(instant)).isEqualTo(formatter.format(instant));
instant=ZonedDateTime.of(2020,01,01,10,20,30,(int)TimeUnit.MILLISECONDS.toNanos(100),zone).toInstant();
assertThat(fast.format(instant)).isEqualTo(formatter.format(instant));
instant=ZonedDateTime.of(2020,01,01,10,20,30,(int)TimeUnit.MILLISECONDS.toNanos(123),zone).toInstant();
assertThat(fast.format(instant)).isEqualTo(formatter.format(instant));
instant=ZonedDateTime.of(2020,01,01,10,20,30,123_400_000,zone).toInstant();
assertThat(fast.format(instant)).isEqualTo(formatter.format(instant));
}
);
}
/**
* Parse a {@link JsonNode} and produce the corresponding {@link NodeWriter}.
* @param node the {@link JsonNode} to parse.
* @return a {@link NodeWriter} corresponding to the given JSON node
* @throws JsonPatternException denotes an invalid pattern
*/
private NodeWriter<Event> parseNode(JsonPointer location,JsonNode node) throws JsonPatternException {
if (node.isTextual()) {
try {
ValueGetter<Event,?> getter=makeComputableValueGetter(node.asText());
return new ValueWriter<>(getter);
}
catch ( RuntimeException e) {
String msg="Invalid JSON property '" + location + "' (was '"+ node.asText()+ "'): "+ e.getMessage();
throw new JsonPatternException(msg,e);
}
}
if (node.isArray()) {
return parseArray(location,(ArrayNode)node);
}
if (node.isObject()) {
return parseObject(location,(ObjectNode)node);
}
return new ValueWriter<>(g -> node);
}
@TestFactory public Collection<DynamicTest> checkMillisDigits(){
return doForAllSupportedFormats(zone,(formatter,fast) -> {
Instant instant=ZonedDateTime.of(2020,01,01,10,20,0,0,zone).toInstant();
assertThat(fast.format(instant)).isEqualTo(formatter.format(instant));
instant=ZonedDateTime.of(2020,01,01,10,20,30,0,zone).toInstant();
assertThat(fast.format(instant)).isEqualTo(formatter.format(instant));
instant=ZonedDateTime.of(2020,01,01,10,20,30,1,zone).toInstant();
assertThat(fast.format(instant)).isEqualTo(formatter.format(instant));
instant=ZonedDateTime.of(2020,01,01,10,20,30,(int)TimeUnit.MILLISECONDS.toNanos(1),zone).toInstant();
assertThat(fast.format(instant)).isEqualTo(formatter.format(instant));
instant=ZonedDateTime.of(2020,01,01,10,20,30,(int)TimeUnit.MILLISECONDS.toNanos(10),zone).toInstant();
assertThat(fast.format(instant)).isEqualTo(formatter.format(instant));
instant=ZonedDateTime.of(2020,01,01,10,20,30,(int)TimeUnit.MILLISECONDS.toNanos(100),zone).toInstant();
assertThat(fast.format(instant)).isEqualTo(formatter.format(instant));
instant=ZonedDateTime.of(2020,01,01,10,20,30,(int)TimeUnit.MILLISECONDS.toNanos(123),zone).toInstant();
assertThat(fast.format(instant)).isEqualTo(formatter.format(instant));
instant=ZonedDateTime.of(2020,01,01,10,20,30,123_400_000,zone).toInstant();
assertThat(fast.format(instant)).isEqualTo(formatter.format(instant));
}
);
}
@Override public boolean isStarted(){
CountDownLatch latch=this.shutdownLatch;
return latch != null && latch.getCount() != 0;
}
@Override public void stop(){
super.stop();
getLayout().stop();
fireAppenderStopped();
}
| {"types": [{"Disruptor<LogEvent<Event>>": "LoggingEventAsyncDisruptorAppender"}], "methods": [{"halt": "stop"}, {"getMilliseconds": "checkMillisDigits"}, {"parkNanos": "parseNode"}, {"currentTimeMillis": "checkMillisDigits"}, {"isStarted": "isStarted"}], "similar_methods": [{"stop": "stop"}]} | [{"Disruptor<LogEvent<Event>>": {"retrieved_name": "LoggingEventAsyncDisruptorAppender", "raw_body": "/** \n * A {@link DelegatingAsyncDisruptorAppender} for {@link ILoggingEvent}s.\n */\npublic class LoggingEventAsyncDisruptorAppender extends DelegatingAsyncDisruptorAppender<ILoggingEvent,AppenderListener<ILoggingEvent>> {\n /** \n * Set to true if the caller data should be captured before publishing the event to the {@link RingBuffer}\n */\n private boolean includeCallerData;\n protected void prepareForDeferredProcessing( ILoggingEvent event);\n public boolean isIncludeCallerData();\n public void setIncludeCallerData( boolean includeCallerData);\n}\n", "raw_body_no_cmt": "public class LoggingEventAsyncDisruptorAppender extends DelegatingAsyncDisruptorAppender<ILoggingEvent,AppenderListener<ILoggingEvent>> {\n private boolean includeCallerData;\n protected void prepareForDeferredProcessing( ILoggingEvent event);\n public boolean isIncludeCallerData();\n public void setIncludeCallerData( boolean includeCallerData);\n}\n"}}] | [{"halt": {"retrieved_name": "stop", "raw_body": "public static void stop(Object component){\n if (component instanceof LifeCycle) {\n ((LifeCycle)component).stop();\n }\n}\n"}}, {"getMilliseconds": {"retrieved_name": "checkMillisDigits", "raw_body": "@TestFactory public Collection<DynamicTest> checkMillisDigits(){\n return doForAllSupportedFormats(zone,(formatter,fast) -> {\n Instant instant=ZonedDateTime.of(2020,01,01,10,20,0,0,zone).toInstant();\n assertThat(fast.format(instant)).isEqualTo(formatter.format(instant));\n instant=ZonedDateTime.of(2020,01,01,10,20,30,0,zone).toInstant();\n assertThat(fast.format(instant)).isEqualTo(formatter.format(instant));\n instant=ZonedDateTime.of(2020,01,01,10,20,30,1,zone).toInstant();\n assertThat(fast.format(instant)).isEqualTo(formatter.format(instant));\n instant=ZonedDateTime.of(2020,01,01,10,20,30,(int)TimeUnit.MILLISECONDS.toNanos(1),zone).toInstant();\n assertThat(fast.format(instant)).isEqualTo(formatter.format(instant));\n instant=ZonedDateTime.of(2020,01,01,10,20,30,(int)TimeUnit.MILLISECONDS.toNanos(10),zone).toInstant();\n assertThat(fast.format(instant)).isEqualTo(formatter.format(instant));\n instant=ZonedDateTime.of(2020,01,01,10,20,30,(int)TimeUnit.MILLISECONDS.toNanos(100),zone).toInstant();\n assertThat(fast.format(instant)).isEqualTo(formatter.format(instant));\n instant=ZonedDateTime.of(2020,01,01,10,20,30,(int)TimeUnit.MILLISECONDS.toNanos(123),zone).toInstant();\n assertThat(fast.format(instant)).isEqualTo(formatter.format(instant));\n instant=ZonedDateTime.of(2020,01,01,10,20,30,123_400_000,zone).toInstant();\n assertThat(fast.format(instant)).isEqualTo(formatter.format(instant));\n }\n);\n}\n"}}, {"parkNanos": {"retrieved_name": "parseNode", "raw_body": "/** \n * Parse a {@link JsonNode} and produce the corresponding {@link NodeWriter}.\n * @param node the {@link JsonNode} to parse.\n * @return a {@link NodeWriter} corresponding to the given JSON node\n * @throws JsonPatternException denotes an invalid pattern\n */\nprivate NodeWriter<Event> parseNode(JsonPointer location,JsonNode node) throws JsonPatternException {\n if (node.isTextual()) {\n try {\n ValueGetter<Event,?> getter=makeComputableValueGetter(node.asText());\n return new ValueWriter<>(getter);\n }\n catch ( RuntimeException e) {\n String msg=\"Invalid JSON property '\" + location + \"' (was '\"+ node.asText()+ \"'): \"+ e.getMessage();\n throw new JsonPatternException(msg,e);\n }\n }\n if (node.isArray()) {\n return parseArray(location,(ArrayNode)node);\n }\n if (node.isObject()) {\n return parseObject(location,(ObjectNode)node);\n }\n return new ValueWriter<>(g -> node);\n}\n"}}, {"currentTimeMillis": {"retrieved_name": "checkMillisDigits", "raw_body": "@TestFactory public Collection<DynamicTest> checkMillisDigits(){\n return doForAllSupportedFormats(zone,(formatter,fast) -> {\n Instant instant=ZonedDateTime.of(2020,01,01,10,20,0,0,zone).toInstant();\n assertThat(fast.format(instant)).isEqualTo(formatter.format(instant));\n instant=ZonedDateTime.of(2020,01,01,10,20,30,0,zone).toInstant();\n assertThat(fast.format(instant)).isEqualTo(formatter.format(instant));\n instant=ZonedDateTime.of(2020,01,01,10,20,30,1,zone).toInstant();\n assertThat(fast.format(instant)).isEqualTo(formatter.format(instant));\n instant=ZonedDateTime.of(2020,01,01,10,20,30,(int)TimeUnit.MILLISECONDS.toNanos(1),zone).toInstant();\n assertThat(fast.format(instant)).isEqualTo(formatter.format(instant));\n instant=ZonedDateTime.of(2020,01,01,10,20,30,(int)TimeUnit.MILLISECONDS.toNanos(10),zone).toInstant();\n assertThat(fast.format(instant)).isEqualTo(formatter.format(instant));\n instant=ZonedDateTime.of(2020,01,01,10,20,30,(int)TimeUnit.MILLISECONDS.toNanos(100),zone).toInstant();\n assertThat(fast.format(instant)).isEqualTo(formatter.format(instant));\n instant=ZonedDateTime.of(2020,01,01,10,20,30,(int)TimeUnit.MILLISECONDS.toNanos(123),zone).toInstant();\n assertThat(fast.format(instant)).isEqualTo(formatter.format(instant));\n instant=ZonedDateTime.of(2020,01,01,10,20,30,123_400_000,zone).toInstant();\n assertThat(fast.format(instant)).isEqualTo(formatter.format(instant));\n }\n);\n}\n"}}, {"isStarted": {"retrieved_name": "isStarted", "raw_body": "@Override public boolean isStarted(){\n CountDownLatch latch=this.shutdownLatch;\n return latch != null && latch.getCount() != 0;\n}\n"}}] | [{"stop": {"retrieved_name": "stop", "raw_body": "@Override public void stop(){\n super.stop();\n getLayout().stop();\n fireAppenderStopped();\n}\n"}}] |
|
graphhopper_graphhopper | graphhopper/core/src/main/java/com/graphhopper/routing/util/parsers/StateParser.java | StateParser | handleWayTags | class StateParser implements TagParser {
private final EnumEncodedValue<State> stateEnc;
public StateParser(EnumEncodedValue<State> stateEnc) {
this.stateEnc = stateEnc;
}
@Override
public void handleWayTags(int edgeId, EdgeIntAccess edgeIntAccess, ReaderWay way, IntsRef relationFlags) {<FILL_FUNCTION_BODY>}
} |
State country = way.getTag("country_state", State.MISSING);
stateEnc.setEnum(false, edgeId, edgeIntAccess, country);
|
if (way.hasTag(stateEnc)) {
edgeIntAccess.set(edgeId, stateEnc.getIndex(), stateEnc.getValue(way.getTag(stateEnc)));
}
| [
"IntsRef",
"EdgeIntAccess",
"ReaderWay",
"EnumEncodedValue<State>"
] | [
"hasTag",
"getValue",
"getTag",
"set",
"getIndex"
] | [
"ReaderWay",
"State",
"EnumEncodedValue<State>",
"IntsRef",
"EdgeIntAccess"
] | [
"setEnum",
"getTag"
] | {
"methods": [
"hasTag",
"getValue",
"getTag",
"set",
"getIndex"
],
"similar_methods": [
"handleWayTags"
],
"types": [
"IntsRef",
"EdgeIntAccess",
"ReaderWay",
"EnumEncodedValue<State>"
]
} | /**
* Idea and most of the code is from Lucene. But the variables are final, except for the array content.
*/
public final class IntsRef implements Comparable<IntsRef> {
/**
* An IntsRef with an array of size 0.
*/
public static final IntsRef EMPTY=new IntsRef(0,false);
/**
* The contents of the IntsRef. Cannot be {@code null}.
*/
public final int[] ints;
/**
* Offset of first valid integer.
*/
public final int offset;
/**
* Length of used ints.
*/
public final int length;
/**
* Create a IntsRef pointing to a new int array of size <code>capacity</code> leading to capacity*32 bits. Offset will be zero and length will be the capacity.
*/
public IntsRef( int capacity);
private IntsRef( int capacity, boolean checked);
/**
* This instance will directly reference ints w/o making a copy. ints should not be null.
*/
public IntsRef( int[] ints, int offset, int length);
@Override public int hashCode();
@Override public boolean equals( Object other);
public boolean intsEquals( IntsRef other);
/**
* Signed int order comparison
*/
@Override public int compareTo( IntsRef other);
/**
* Creates a new IntsRef that points to a copy of the ints from <code>other</code> <p> The returned IntsRef will have a length of other.length and an offset of zero.
*/
public static IntsRef deepCopyOf( IntsRef other);
/**
* Performs internal consistency checks. Always returns true (or throws IllegalStateException)
*/
public boolean isValid();
@Override public String toString();
public boolean isEmpty();
}
public interface EdgeIntAccess {
/**
* Gets the int value at the given index for the given edgeId
*/
int getInt( int edgeId, int index);
/**
* Sets the int value at the given index for the given edgeId
*/
void setInt( int edgeId, int index, int value);
}
/**
* Represents a way received from the reader. <p>
* @author Nop
*/
public class ReaderWay extends ReaderElement {
protected final LongArrayList nodes=new LongArrayList(5);
public ReaderWay( long id);
public LongArrayList getNodes();
@Override public String toString();
}
/**
* This class allows to store distinct values via an enum. I.e. it stores just the indices
*/
public final class EnumEncodedValue<E extends Enum> extends IntEncodedValueImpl {
@JsonIgnore private final E[] arr;
private final Class<E> enumType;
public EnumEncodedValue( String name, Class<E> enumType);
public EnumEncodedValue( String name, Class<E> enumType, boolean storeTwoDirections);
@JsonCreator(mode=JsonCreator.Mode.PROPERTIES) EnumEncodedValue( @JsonProperty("name") String name, @JsonProperty("bits") int bits, @JsonProperty("min_storable_value") int minStorableValue, @JsonProperty("max_storable_value") int maxStorableValue, @JsonProperty("max_value") int maxValue, @JsonProperty("negate_reverse_direction") boolean negateReverseDirection, @JsonProperty("store_two_directions") boolean storeTwoDirections, @JsonProperty("fwd_data_index") int fwdDataIndex, @JsonProperty("bwd_data_index") int bwdDataIndex, @JsonProperty("fwd_shift") int fwdShift, @JsonProperty("bwd_shift") int bwdShift, @JsonProperty("fwd_mask") int fwdMask, @JsonProperty("bwd_mask") int bwdMask, @JsonProperty("enum_type") Class<E> enumType);
public Class<E> getEnumType();
public E[] getValues();
public final void setEnum( boolean reverse, int edgeId, EdgeIntAccess edgeIntAccess, E value);
public final E getEnum( boolean reverse, int edgeId, EdgeIntAccess edgeIntAccess);
}
/**
* Check a number of tags in the given order if their value is equal to the specified value.
*/
public boolean hasTag(List<String> keyList,Object value){
for ( String key : keyList) {
if (value.equals(getTag(key,null))) return true;
}
return false;
}
public String getValue(){
return value;
}
@SuppressWarnings("unchecked") public <T>T getTag(String key,T defaultValue){
T val=(T)properties.get(key);
if (val == null) return defaultValue;
return val;
}
@Override public <T extends Enum<?>>EdgeIteratorState set(EnumEncodedValue<T> property,T value){
throw new RuntimeException();
}
private long getIndex(int edgeId,boolean reverse){
return storeTwoDirections ? (2L * edgeId + (reverse ? 1 : 0)) : edgeId;
}
@Override public void handleWayTags(int edgeId,EdgeIntAccess edgeIntAccess,ReaderWay way,IntsRef relationFlags){
if (isFerry(way)) {
double ferrySpeed=minmax(getSpeed(way),ferrySpeedEnc);
ferrySpeedEnc.setDecimal(false,edgeId,edgeIntAccess,ferrySpeed);
}
}
| public final class IntsRef implements Comparable<IntsRef> {
public static final IntsRef EMPTY=new IntsRef(0,false);
public final int[] ints;
public final int offset;
public final int length;
public IntsRef( int capacity);
private IntsRef( int capacity, boolean checked);
public IntsRef( int[] ints, int offset, int length);
public int hashCode();
public boolean equals( Object other);
public boolean intsEquals( IntsRef other);
public int compareTo( IntsRef other);
public static IntsRef deepCopyOf( IntsRef other);
public boolean isValid();
public String toString();
public boolean isEmpty();
}
public interface EdgeIntAccess {
int getInt( int edgeId, int index);
void setInt( int edgeId, int index, int value);
}
public class ReaderWay extends ReaderElement {
protected final LongArrayList nodes=new LongArrayList(5);
public ReaderWay( long id);
public LongArrayList getNodes();
public String toString();
}
public final class EnumEncodedValue<E extends Enum> extends IntEncodedValueImpl {
private final E[] arr;
private final Class<E> enumType;
public EnumEncodedValue( String name, Class<E> enumType);
public EnumEncodedValue( String name, Class<E> enumType, boolean storeTwoDirections);
EnumEncodedValue( String name, int bits, int minStorableValue, int maxStorableValue, int maxValue, boolean negateReverseDirection, boolean storeTwoDirections, int fwdDataIndex, int bwdDataIndex, int fwdShift, int bwdShift, int fwdMask, int bwdMask, Class<E> enumType);
public Class<E> getEnumType();
public E[] getValues();
public final void setEnum( boolean reverse, int edgeId, EdgeIntAccess edgeIntAccess, E value);
public final E getEnum( boolean reverse, int edgeId, EdgeIntAccess edgeIntAccess);
}
/**
* Check a number of tags in the given order if their value is equal to the specified value.
*/
public boolean hasTag(List<String> keyList,Object value){
for ( String key : keyList) {
if (value.equals(getTag(key,null))) return true;
}
return false;
}
public String getValue(){
return value;
}
@SuppressWarnings("unchecked") public <T>T getTag(String key,T defaultValue){
T val=(T)properties.get(key);
if (val == null) return defaultValue;
return val;
}
@Override public <T extends Enum<?>>EdgeIteratorState set(EnumEncodedValue<T> property,T value){
throw new RuntimeException();
}
private long getIndex(int edgeId,boolean reverse){
return storeTwoDirections ? (2L * edgeId + (reverse ? 1 : 0)) : edgeId;
}
@Override public void handleWayTags(int edgeId,EdgeIntAccess edgeIntAccess,ReaderWay way,IntsRef relationFlags){
if (isFerry(way)) {
double ferrySpeed=minmax(getSpeed(way),ferrySpeedEnc);
ferrySpeedEnc.setDecimal(false,edgeId,edgeIntAccess,ferrySpeed);
}
}
| {"types": [{"IntsRef": "IntsRef"}, {"EdgeIntAccess": "EdgeIntAccess"}, {"ReaderWay": "ReaderWay"}, {"EnumEncodedValue<State>": "EnumEncodedValue"}], "methods": [{"hasTag": "hasTag"}, {"getValue": "getValue"}, {"getTag": "getTag"}, {"set": "set"}, {"getIndex": "getIndex"}], "similar_methods": [{"handleWayTags": "handleWayTags"}]} | [{"IntsRef": {"retrieved_name": "IntsRef", "raw_body": "/** \n * Idea and most of the code is from Lucene. But the variables are final, except for the array content.\n */\npublic final class IntsRef implements Comparable<IntsRef> {\n /** \n * An IntsRef with an array of size 0.\n */\n public static final IntsRef EMPTY=new IntsRef(0,false);\n /** \n * The contents of the IntsRef. Cannot be {@code null}.\n */\n public final int[] ints;\n /** \n * Offset of first valid integer.\n */\n public final int offset;\n /** \n * Length of used ints.\n */\n public final int length;\n /** \n * Create a IntsRef pointing to a new int array of size <code>capacity</code> leading to capacity*32 bits. Offset will be zero and length will be the capacity.\n */\n public IntsRef( int capacity);\n private IntsRef( int capacity, boolean checked);\n /** \n * This instance will directly reference ints w/o making a copy. ints should not be null.\n */\n public IntsRef( int[] ints, int offset, int length);\n @Override public int hashCode();\n @Override public boolean equals( Object other);\n public boolean intsEquals( IntsRef other);\n /** \n * Signed int order comparison\n */\n @Override public int compareTo( IntsRef other);\n /** \n * Creates a new IntsRef that points to a copy of the ints from <code>other</code> <p> The returned IntsRef will have a length of other.length and an offset of zero.\n */\n public static IntsRef deepCopyOf( IntsRef other);\n /** \n * Performs internal consistency checks. Always returns true (or throws IllegalStateException)\n */\n public boolean isValid();\n @Override public String toString();\n public boolean isEmpty();\n}\n", "raw_body_no_cmt": "public final class IntsRef implements Comparable<IntsRef> {\n public static final IntsRef EMPTY=new IntsRef(0,false);\n public final int[] ints;\n public final int offset;\n public final int length;\n public IntsRef( int capacity);\n private IntsRef( int capacity, boolean checked);\n public IntsRef( int[] ints, int offset, int length);\n public int hashCode();\n public boolean equals( Object other);\n public boolean intsEquals( IntsRef other);\n public int compareTo( IntsRef other);\n public static IntsRef deepCopyOf( IntsRef other);\n public boolean isValid();\n public String toString();\n public boolean isEmpty();\n}\n"}}, {"EdgeIntAccess": {"retrieved_name": "EdgeIntAccess", "raw_body": "public interface EdgeIntAccess {\n /** \n * Gets the int value at the given index for the given edgeId\n */\n int getInt( int edgeId, int index);\n /** \n * Sets the int value at the given index for the given edgeId\n */\n void setInt( int edgeId, int index, int value);\n}\n", "raw_body_no_cmt": "public interface EdgeIntAccess {\n int getInt( int edgeId, int index);\n void setInt( int edgeId, int index, int value);\n}\n"}}, {"ReaderWay": {"retrieved_name": "ReaderWay", "raw_body": "/** \n * Represents a way received from the reader. <p>\n * @author Nop\n */\npublic class ReaderWay extends ReaderElement {\n protected final LongArrayList nodes=new LongArrayList(5);\n public ReaderWay( long id);\n public LongArrayList getNodes();\n @Override public String toString();\n}\n", "raw_body_no_cmt": "public class ReaderWay extends ReaderElement {\n protected final LongArrayList nodes=new LongArrayList(5);\n public ReaderWay( long id);\n public LongArrayList getNodes();\n public String toString();\n}\n"}}, {"EnumEncodedValue<State>": {"retrieved_name": "EnumEncodedValue", "raw_body": "/** \n * This class allows to store distinct values via an enum. I.e. it stores just the indices\n */\npublic final class EnumEncodedValue<E extends Enum> extends IntEncodedValueImpl {\n @JsonIgnore private final E[] arr;\n private final Class<E> enumType;\n public EnumEncodedValue( String name, Class<E> enumType);\n public EnumEncodedValue( String name, Class<E> enumType, boolean storeTwoDirections);\n @JsonCreator(mode=JsonCreator.Mode.PROPERTIES) EnumEncodedValue( @JsonProperty(\"name\") String name, @JsonProperty(\"bits\") int bits, @JsonProperty(\"min_storable_value\") int minStorableValue, @JsonProperty(\"max_storable_value\") int maxStorableValue, @JsonProperty(\"max_value\") int maxValue, @JsonProperty(\"negate_reverse_direction\") boolean negateReverseDirection, @JsonProperty(\"store_two_directions\") boolean storeTwoDirections, @JsonProperty(\"fwd_data_index\") int fwdDataIndex, @JsonProperty(\"bwd_data_index\") int bwdDataIndex, @JsonProperty(\"fwd_shift\") int fwdShift, @JsonProperty(\"bwd_shift\") int bwdShift, @JsonProperty(\"fwd_mask\") int fwdMask, @JsonProperty(\"bwd_mask\") int bwdMask, @JsonProperty(\"enum_type\") Class<E> enumType);\n public Class<E> getEnumType();\n public E[] getValues();\n public final void setEnum( boolean reverse, int edgeId, EdgeIntAccess edgeIntAccess, E value);\n public final E getEnum( boolean reverse, int edgeId, EdgeIntAccess edgeIntAccess);\n}\n", "raw_body_no_cmt": "public final class EnumEncodedValue<E extends Enum> extends IntEncodedValueImpl {\n private final E[] arr;\n private final Class<E> enumType;\n public EnumEncodedValue( String name, Class<E> enumType);\n public EnumEncodedValue( String name, Class<E> enumType, boolean storeTwoDirections);\n EnumEncodedValue( String name, int bits, int minStorableValue, int maxStorableValue, int maxValue, boolean negateReverseDirection, boolean storeTwoDirections, int fwdDataIndex, int bwdDataIndex, int fwdShift, int bwdShift, int fwdMask, int bwdMask, Class<E> enumType);\n public Class<E> getEnumType();\n public E[] getValues();\n public final void setEnum( boolean reverse, int edgeId, EdgeIntAccess edgeIntAccess, E value);\n public final E getEnum( boolean reverse, int edgeId, EdgeIntAccess edgeIntAccess);\n}\n"}}] | [{"hasTag": {"retrieved_name": "hasTag", "raw_body": "/** \n * Check a number of tags in the given order if their value is equal to the specified value.\n */\npublic boolean hasTag(List<String> keyList,Object value){\n for ( String key : keyList) {\n if (value.equals(getTag(key,null))) return true;\n }\n return false;\n}\n"}}, {"getValue": {"retrieved_name": "getValue", "raw_body": "public String getValue(){\n return value;\n}\n"}}, {"getTag": {"retrieved_name": "getTag", "raw_body": "@SuppressWarnings(\"unchecked\") public <T>T getTag(String key,T defaultValue){\n T val=(T)properties.get(key);\n if (val == null) return defaultValue;\n return val;\n}\n"}}, {"set": {"retrieved_name": "set", "raw_body": "@Override public <T extends Enum<?>>EdgeIteratorState set(EnumEncodedValue<T> property,T value){\n throw new RuntimeException();\n}\n"}}, {"getIndex": {"retrieved_name": "getIndex", "raw_body": "private long getIndex(int edgeId,boolean reverse){\n return storeTwoDirections ? (2L * edgeId + (reverse ? 1 : 0)) : edgeId;\n}\n"}}] | [{"handleWayTags": {"retrieved_name": "handleWayTags", "raw_body": "@Override public void handleWayTags(int edgeId,EdgeIntAccess edgeIntAccess,ReaderWay way,IntsRef relationFlags){\n if (isFerry(way)) {\n double ferrySpeed=minmax(getSpeed(way),ferrySpeedEnc);\n ferrySpeedEnc.setDecimal(false,edgeId,edgeIntAccess,ferrySpeed);\n }\n}\n"}}] |
|
eirslett_frontend-maven-plugin | frontend-maven-plugin/frontend-plugin-core/src/main/java/com/github/eirslett/maven/plugins/frontend/lib/ProxyConfig.java | Proxy | getUri | class Proxy {
public final String id;
public final String protocol;
public final String host;
public final int port;
public final String username;
public final String password;
public final String nonProxyHosts;
public Proxy(String id, String protocol, String host, int port, String username, String password, String nonProxyHosts) {
this.host = host;
this.id = id;
this.protocol = protocol;
this.port = port;
this.username = username;
this.password = password;
this.nonProxyHosts = nonProxyHosts;
}
public boolean useAuthentication(){
return username != null && !username.isEmpty();
}
public URI getUri() {<FILL_FUNCTION_BODY>}
public boolean isSecure(){
return "https".equals(protocol);
}
public boolean isNonProxyHost(String host) {
if (host != null && nonProxyHosts != null && nonProxyHosts.length() > 0) {
for (StringTokenizer tokenizer = new StringTokenizer(nonProxyHosts, "|"); tokenizer.hasMoreTokens(); ) {
String pattern = tokenizer.nextToken();
pattern = pattern.replace(".", "\\.").replace("*", ".*");
if (host.matches(pattern)) {
return true;
}
}
}
return false;
}
/**
* As per https://docs.npmjs.com/misc/config#noproxy , npm expects a comma (`,`) separated list but
* maven settings.xml usually specifies the no proxy hosts as a bar (`|`) separated list (see
* http://maven.apache.org/guides/mini/guide-proxies.html) .
*
* We could do the conversion here but npm seems to accept the bar separated list regardless
* of what the documentation says so we do no conversion for now.
* @return
*/
public String getNonProxyHosts() {
return nonProxyHosts;
}
@Override
public String toString() {
return id + "{" +
"protocol='" + protocol + '\'' +
", host='" + host + '\'' +
", port=" + port +
", nonProxyHosts='" + nonProxyHosts + '\'' +
(useAuthentication()? ", with username/passport authentication" : "") +
'}';
}
} |
String authentication = useAuthentication() ? username + ":" + password : null;
try {
// Proxies should be schemed with http, even if the protocol is https
return new URI("http", authentication, host, port, null, null, null);
} catch (URISyntaxException e) {
throw new ProxyConfigException("Invalid proxy settings", e);
}
|
return URI.create(protocol + "://" + host + ":" + port);
| [] | [
"create"
] | [
"URISyntaxException",
"Proxy"
] | [] | {
"methods": [
"create"
],
"similar_methods": [
"getUri"
],
"types": []
} | private Map<String,String> createEnvironment(final List<String> paths,final Platform platform,final Map<String,String> additionalEnvironment){
final Map<String,String> environment=new HashMap<>(System.getenv());
if (additionalEnvironment != null) {
environment.putAll(additionalEnvironment);
}
if (platform.isWindows()) {
for ( final Map.Entry<String,String> entry : environment.entrySet()) {
final String pathName=entry.getKey();
if (PATH_ENV_VAR.equalsIgnoreCase(pathName)) {
final String pathValue=entry.getValue();
environment.put(pathName,extendPathVariable(pathValue,paths));
}
}
}
else {
final String pathValue=environment.get(PATH_ENV_VAR);
environment.put(PATH_ENV_VAR,extendPathVariable(pathValue,paths));
}
return environment;
}
public String getName(){
return name;
}
| private Map<String,String> createEnvironment(final List<String> paths,final Platform platform,final Map<String,String> additionalEnvironment){
final Map<String,String> environment=new HashMap<>(System.getenv());
if (additionalEnvironment != null) {
environment.putAll(additionalEnvironment);
}
if (platform.isWindows()) {
for ( final Map.Entry<String,String> entry : environment.entrySet()) {
final String pathName=entry.getKey();
if (PATH_ENV_VAR.equalsIgnoreCase(pathName)) {
final String pathValue=entry.getValue();
environment.put(pathName,extendPathVariable(pathValue,paths));
}
}
}
else {
final String pathValue=environment.get(PATH_ENV_VAR);
environment.put(PATH_ENV_VAR,extendPathVariable(pathValue,paths));
}
return environment;
}
public String getName(){
return name;
}
| {"methods": [{"create": "createEnvironment"}], "similar_methods": [{"getUri": "getName"}]} | [] | [{"create": {"retrieved_name": "createEnvironment", "raw_body": "private Map<String,String> createEnvironment(final List<String> paths,final Platform platform,final Map<String,String> additionalEnvironment){\n final Map<String,String> environment=new HashMap<>(System.getenv());\n if (additionalEnvironment != null) {\n environment.putAll(additionalEnvironment);\n }\n if (platform.isWindows()) {\n for ( final Map.Entry<String,String> entry : environment.entrySet()) {\n final String pathName=entry.getKey();\n if (PATH_ENV_VAR.equalsIgnoreCase(pathName)) {\n final String pathValue=entry.getValue();\n environment.put(pathName,extendPathVariable(pathValue,paths));\n }\n }\n }\n else {\n final String pathValue=environment.get(PATH_ENV_VAR);\n environment.put(PATH_ENV_VAR,extendPathVariable(pathValue,paths));\n }\n return environment;\n}\n"}}] | [{"getUri": {"retrieved_name": "getName", "raw_body": "public String getName(){\n return name;\n}\n"}}] |
|
elunez_eladmin | eladmin/eladmin-common/src/main/java/me/zhengjie/utils/SpringContextHolder.java | SpringContextHolder | setApplicationContext | class SpringContextHolder implements ApplicationContextAware, DisposableBean {
private static ApplicationContext applicationContext = null;
private static final List<CallBack> CALL_BACKS = new ArrayList<>();
private static boolean addCallback = true;
/**
* 针对 某些初始化方法,在SpringContextHolder 未初始化时 提交回调方法。
* 在SpringContextHolder 初始化后,进行回调使用
*
* @param callBack 回调函数
*/
public synchronized static void addCallBacks(CallBack callBack) {
if (addCallback) {
SpringContextHolder.CALL_BACKS.add(callBack);
} else {
log.warn("CallBack:{} 已无法添加!立即执行", callBack.getCallBackName());
callBack.executor();
}
}
/**
* 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
*/
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) {
assertContextInjected();
return (T) applicationContext.getBean(name);
}
/**
* 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
*/
public static <T> T getBean(Class<T> requiredType) {
assertContextInjected();
return applicationContext.getBean(requiredType);
}
/**
* 获取SpringBoot 配置信息
*
* @param property 属性key
* @param defaultValue 默认值
* @param requiredType 返回类型
* @return /
*/
public static <T> T getProperties(String property, T defaultValue, Class<T> requiredType) {
T result = defaultValue;
try {
result = getBean(Environment.class).getProperty(property, requiredType);
} catch (Exception ignored) {}
return result;
}
/**
* 获取SpringBoot 配置信息
*
* @param property 属性key
* @return /
*/
public static String getProperties(String property) {
return getProperties(property, null, String.class);
}
/**
* 获取SpringBoot 配置信息
*
* @param property 属性key
* @param requiredType 返回类型
* @return /
*/
public static <T> T getProperties(String property, Class<T> requiredType) {
return getProperties(property, null, requiredType);
}
/**
* 检查ApplicationContext不为空.
*/
private static void assertContextInjected() {
if (applicationContext == null) {
throw new IllegalStateException("applicaitonContext属性未注入, 请在applicationContext" +
".xml中定义SpringContextHolder或在SpringBoot启动类中注册SpringContextHolder.");
}
}
/**
* 清除SpringContextHolder中的ApplicationContext为Null.
*/
private static void clearHolder() {
log.debug("清除SpringContextHolder中的ApplicationContext:"
+ applicationContext);
applicationContext = null;
}
@Override
public void destroy() {
SpringContextHolder.clearHolder();
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {<FILL_FUNCTION_BODY>}
/**
* 获取 @Service 的所有 bean 名称
* @return /
*/
public static List<String> getAllServiceBeanName() {
return new ArrayList<>(Arrays.asList(applicationContext
.getBeanNamesForAnnotation(Service.class)));
}
} |
if (SpringContextHolder.applicationContext != null) {
log.warn("SpringContextHolder中的ApplicationContext被覆盖, 原有ApplicationContext为:" + SpringContextHolder.applicationContext);
}
SpringContextHolder.applicationContext = applicationContext;
if (addCallback) {
for (CallBack callBack : SpringContextHolder.CALL_BACKS) {
callBack.executor();
}
CALL_BACKS.clear();
}
SpringContextHolder.addCallback = false;
|
SpringContextHolder.applicationContext = applicationContext;
if (addCallback) {
for (CallBack callBack : CALL_BACKS) {
callBack.executor();
}
addCallback = false;
}
| [
"List<CallBack>",
"ApplicationContext",
"CallBack"
] | [
"executor"
] | [
"ApplicationContext",
"List<CallBack>",
"CallBack"
] | [
"clear",
"warn",
"executor"
] | {
"methods": [
"executor"
],
"similar_methods": [
"setApplicationContext"
],
"types": [
"List<CallBack>",
"ApplicationContext",
"CallBack"
]
} | /**
* @author : liaojinlong
* @date : 2020/6/9 17:02
* @since : 1.0
* @see {@link SpringContextHolder}针对某些初始化方法,在SpringContextHolder 初始化前时,<br> 可提交一个 提交回调任务。<br> 在SpringContextHolder 初始化后,进行回调使用
*/
public interface CallBack {
/**
* 回调执行方法
*/
void executor();
/**
* 本回调任务名称
* @return /
*/
default String getCallBackName();
}
/**
* @author zhanghouying
* @date 2019-08-24
*/
@Entity @Getter @Setter @Table(name="mnt_app") public class App extends BaseEntity implements Serializable {
@Id @Column(name="app_id") @ApiModelProperty(value="ID",hidden=true) @GeneratedValue(strategy=GenerationType.IDENTITY) private Long id;
@ApiModelProperty(value="名称") private String name;
@ApiModelProperty(value="端口") private int port;
@ApiModelProperty(value="上传路径") private String uploadPath;
@ApiModelProperty(value="部署路径") private String deployPath;
@ApiModelProperty(value="备份路径") private String backupPath;
@ApiModelProperty(value="启动脚本") private String startScript;
@ApiModelProperty(value="部署脚本") private String deployScript;
public void copy( App source);
}
/**
* 回调执行方法
*/
void executor();
static synchronized public ScpClientUtil getInstance(String ip,int port,String username,String password){
if (instance.get(ip) == null) {
instance.put(ip,new ScpClientUtil(ip,port,username,password));
}
return instance.get(ip);
}
| public interface CallBack {
void executor();
default String getCallBackName();
}
public class App extends BaseEntity implements Serializable {
private Long id;
private String name;
private int port;
private String uploadPath;
private String deployPath;
private String backupPath;
private String startScript;
private String deployScript;
public void copy( App source);
}
/**
* 回调执行方法
*/
void executor();
static synchronized public ScpClientUtil getInstance(String ip,int port,String username,String password){
if (instance.get(ip) == null) {
instance.put(ip,new ScpClientUtil(ip,port,username,password));
}
return instance.get(ip);
}
| {"types": [{"List<CallBack>": "CallBack"}, {"ApplicationContext": "App"}, {"CallBack": "CallBack"}], "methods": [{"executor": "executor"}], "similar_methods": [{"setApplicationContext": "getInstance"}]} | [{"List<CallBack>": {"retrieved_name": "CallBack", "raw_body": "/** \n * @author : liaojinlong\n * @date : 2020/6/9 17:02\n * @since : 1.0\n * @see {@link SpringContextHolder}\u9488\u5bf9\u67d0\u4e9b\u521d\u59cb\u5316\u65b9\u6cd5\uff0c\u5728SpringContextHolder \u521d\u59cb\u5316\u524d\u65f6\uff0c<br> \u53ef\u63d0\u4ea4\u4e00\u4e2a \u63d0\u4ea4\u56de\u8c03\u4efb\u52a1\u3002<br> \u5728SpringContextHolder \u521d\u59cb\u5316\u540e\uff0c\u8fdb\u884c\u56de\u8c03\u4f7f\u7528\n */\npublic interface CallBack {\n /** \n * \u56de\u8c03\u6267\u884c\u65b9\u6cd5\n */\n void executor();\n /** \n * \u672c\u56de\u8c03\u4efb\u52a1\u540d\u79f0\n * @return /\n */\n default String getCallBackName();\n}\n", "raw_body_no_cmt": "public interface CallBack {\n void executor();\n default String getCallBackName();\n}\n"}}, {"ApplicationContext": {"retrieved_name": "App", "raw_body": "/** \n * @author zhanghouying\n * @date 2019-08-24\n */\n@Entity @Getter @Setter @Table(name=\"mnt_app\") public class App extends BaseEntity implements Serializable {\n @Id @Column(name=\"app_id\") @ApiModelProperty(value=\"ID\",hidden=true) @GeneratedValue(strategy=GenerationType.IDENTITY) private Long id;\n @ApiModelProperty(value=\"\u540d\u79f0\") private String name;\n @ApiModelProperty(value=\"\u7aef\u53e3\") private int port;\n @ApiModelProperty(value=\"\u4e0a\u4f20\u8def\u5f84\") private String uploadPath;\n @ApiModelProperty(value=\"\u90e8\u7f72\u8def\u5f84\") private String deployPath;\n @ApiModelProperty(value=\"\u5907\u4efd\u8def\u5f84\") private String backupPath;\n @ApiModelProperty(value=\"\u542f\u52a8\u811a\u672c\") private String startScript;\n @ApiModelProperty(value=\"\u90e8\u7f72\u811a\u672c\") private String deployScript;\n public void copy( App source);\n}\n", "raw_body_no_cmt": "public class App extends BaseEntity implements Serializable {\n private Long id;\n private String name;\n private int port;\n private String uploadPath;\n private String deployPath;\n private String backupPath;\n private String startScript;\n private String deployScript;\n public void copy( App source);\n}\n"}}] | [{"executor": {"retrieved_name": "executor", "raw_body": "/** \n * \u56de\u8c03\u6267\u884c\u65b9\u6cd5\n */\nvoid executor();\n"}}] | [{"setApplicationContext": {"retrieved_name": "getInstance", "raw_body": "static synchronized public ScpClientUtil getInstance(String ip,int port,String username,String password){\n if (instance.get(ip) == null) {\n instance.put(ip,new ScpClientUtil(ip,port,username,password));\n }\n return instance.get(ip);\n}\n"}}] |
|
jeecgboot_jeecg-boot | jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/system/service/impl/SysPositionServiceImpl.java | SysPositionServiceImpl | getPositionName | class SysPositionServiceImpl extends ServiceImpl<SysPositionMapper, SysPosition> implements ISysPositionService {
@Override
public SysPosition getByCode(String code) {
LambdaQueryWrapper<SysPosition> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(SysPosition::getCode, code);
return super.getOne(queryWrapper);
}
@Override
public List<SysPosition> getPositionList(String userId) {
return this.baseMapper.getPositionList(userId);
}
@Override
public String getPositionName(List<String> postList) {<FILL_FUNCTION_BODY>}
} |
List<SysPosition> positionNameList = this.baseMapper.getPositionName(postList);
if (null != positionNameList && positionNameList.size()>0) {
return positionNameList.stream().map(SysPosition::getName).collect(Collectors.joining(SymbolConstant.COMMA));
}
return "";
|
return this.baseMapper.getPositionName(postList);
| [
"List<String>"
] | [
"getPositionName"
] | [
"List<String>",
"List<SysPosition>"
] | [
"joining",
"getPositionName",
"collect",
"size",
"map",
"stream"
] | {
"methods": [
"getPositionName"
],
"similar_methods": [
"getPositionName"
],
"types": [
"List<String>"
]
} | /**
* @Description : EncryptedString
* @author : jeecg-boot
*/
@Data public class EncryptedString {
/**
* 长度为16个字符
*/
public static String key="1234567890adbcde";
/**
* 长度为16个字符
*/
public static String iv="1234567890hjlkew";
}
/**
* 获取职位名称
* @param postList
* @return
*/
String getPositionName(List<String> postList);
/**
* 获取职位名称
* @param postList
* @return
*/
String getPositionName(List<String> postList);
| public class EncryptedString {
public static String key="1234567890adbcde";
public static String iv="1234567890hjlkew";
}
/**
* 获取职位名称
* @param postList
* @return
*/
String getPositionName(List<String> postList);
/**
* 获取职位名称
* @param postList
* @return
*/
String getPositionName(List<String> postList);
| {"types": [{"List<String>": "EncryptedString"}], "methods": [{"getPositionName": "getPositionName"}], "similar_methods": [{"getPositionName": "getPositionName"}]} | [{"List<String>": {"retrieved_name": "EncryptedString", "raw_body": "/** \n * @Description : EncryptedString\n * @author : jeecg-boot\n */\n@Data public class EncryptedString {\n /** \n * \u957f\u5ea6\u4e3a16\u4e2a\u5b57\u7b26\n */\n public static String key=\"1234567890adbcde\";\n /** \n * \u957f\u5ea6\u4e3a16\u4e2a\u5b57\u7b26\n */\n public static String iv=\"1234567890hjlkew\";\n}\n", "raw_body_no_cmt": "public class EncryptedString {\n public static String key=\"1234567890adbcde\";\n public static String iv=\"1234567890hjlkew\";\n}\n"}}] | [{"getPositionName": {"retrieved_name": "getPositionName", "raw_body": "/** \n * \u83b7\u53d6\u804c\u4f4d\u540d\u79f0\n * @param postList\n * @return\n */\nString getPositionName(List<String> postList);\n"}}] | [{"getPositionName": {"retrieved_name": "getPositionName", "raw_body": "/** \n * \u83b7\u53d6\u804c\u4f4d\u540d\u79f0\n * @param postList\n * @return\n */\nString getPositionName(List<String> postList);\n"}}] |
|
docker-java_docker-java | docker-java/docker-java-core/src/main/java/com/github/dockerjava/core/command/RenameContainerCmdImpl.java | RenameContainerCmdImpl | withContainerId | class RenameContainerCmdImpl extends AbstrDockerCmd<RenameContainerCmd, Void> implements RenameContainerCmd {
private String containerId;
private String name;
public RenameContainerCmdImpl(RenameContainerCmd.Exec exec, String containerId) {
super(exec);
withContainerId(containerId);
}
@Override
public String getContainerId() {
return containerId;
}
@Override
public String getName() {
return name;
}
@Override
public RenameContainerCmd withContainerId(@Nonnull String containerId) {<FILL_FUNCTION_BODY>}
@Override
public RenameContainerCmd withName(@Nonnull String name) {
this.name = Objects.requireNonNull(name, "name was not specified");
return this;
}
/**
* @throws NotFoundException No such container
*/
@Override
public Void exec() throws NotFoundException {
return super.exec();
}
} |
this.containerId = Objects.requireNonNull(containerId, "containerId was not specified");
return this;
|
this.containerId = Objects.requireNonNull(containerId, "containerId was not specified");
return this;
| [] | [
"requireNonNull"
] | [] | [
"requireNonNull"
] | {
"methods": [
"requireNonNull"
],
"similar_methods": [
"withContainerId"
],
"types": []
} | @CheckForNull private static AuthConfigurations firstNonNull(@CheckForNull final AuthConfigurations fromCommand,@CheckForNull final AuthConfigurations fromConfig){
if (fromCommand != null) {
return fromCommand;
}
if (fromConfig != null) {
return fromConfig;
}
return null;
}
@Override public CopyArchiveFromContainerCmdImpl withContainerId(String containerId){
this.containerId=Objects.requireNonNull(containerId,"containerId was not specified");
return this;
}
| @CheckForNull private static AuthConfigurations firstNonNull(@CheckForNull final AuthConfigurations fromCommand,@CheckForNull final AuthConfigurations fromConfig){
if (fromCommand != null) {
return fromCommand;
}
if (fromConfig != null) {
return fromConfig;
}
return null;
}
@Override public CopyArchiveFromContainerCmdImpl withContainerId(String containerId){
this.containerId=Objects.requireNonNull(containerId,"containerId was not specified");
return this;
}
| {"methods": [{"requireNonNull": "firstNonNull"}], "similar_methods": [{"withContainerId": "withContainerId"}]} | [] | [{"requireNonNull": {"retrieved_name": "firstNonNull", "raw_body": "@CheckForNull private static AuthConfigurations firstNonNull(@CheckForNull final AuthConfigurations fromCommand,@CheckForNull final AuthConfigurations fromConfig){\n if (fromCommand != null) {\n return fromCommand;\n }\n if (fromConfig != null) {\n return fromConfig;\n }\n return null;\n}\n"}}] | [{"withContainerId": {"retrieved_name": "withContainerId", "raw_body": "@Override public CopyArchiveFromContainerCmdImpl withContainerId(String containerId){\n this.containerId=Objects.requireNonNull(containerId,\"containerId was not specified\");\n return this;\n}\n"}}] |
|
subhra74_snowflake | snowflake/muon-app/src/main/java/muon/app/ui/components/session/HopEntry.java | HopEntry | toString | class HopEntry {
public HopEntry(String id, String host, int port, String user, String password, String keypath) {
super();
this.id = id;
this.host = host;
this.port = port;
this.user = user;
this.password = password;
this.keypath = keypath;
}
public HopEntry() {
// TODO Auto-generated constructor stub
}
private String id, host, user, password, keypath;
private int port;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getKeypath() {
return keypath;
}
public void setKeypath(String keypath) {
this.keypath = keypath;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
} |
return host != null ? (user != null ? user + "@" + host : host) : "";
|
return "HopEntry [id=" + id + ", host=" + host + ", port=" + port + ", user=" + user + ", password="
+ password + ", keypath=" + keypath + "]";
| [] | [] | [] | [] | {
"methods": [],
"similar_methods": [
"toString"
],
"types": []
} | @Override public String toString(){
if (remoteFile != null) return remoteFile.getName();
return "";
}
| @Override public String toString(){
if (remoteFile != null) return remoteFile.getName();
return "";
}
| {"similar_methods": [{"toString": "toString"}]} | [] | [] | [{"toString": {"retrieved_name": "toString", "raw_body": "@Override public String toString(){\n if (remoteFile != null) return remoteFile.getName();\n return \"\";\n}\n"}}] |
|
orientechnologies_orientdb | orientdb/client/src/main/java/com/orientechnologies/orient/client/remote/message/OBeginTransactionRequest.java | OBeginTransactionRequest | write | class OBeginTransactionRequest implements OBinaryRequest<OBeginTransactionResponse> {
private int txId;
private boolean usingLog;
private boolean hasContent;
private List<ORecordOperationRequest> operations;
private List<IndexChange> indexChanges;
public OBeginTransactionRequest(
int txId,
boolean hasContent,
boolean usingLog,
Iterable<ORecordOperation> operations,
Map<String, OTransactionIndexChanges> indexChanges) {
super();
this.txId = txId;
this.hasContent = hasContent;
this.usingLog = usingLog;
this.indexChanges = new ArrayList<>();
this.operations = new ArrayList<>();
if (hasContent) {
for (ORecordOperation txEntry : operations) {
if (txEntry.type == ORecordOperation.LOADED) continue;
ORecordOperationRequest request = new ORecordOperationRequest();
request.setType(txEntry.type);
request.setVersion(txEntry.getRecord().getVersion());
request.setId(txEntry.getRecord().getIdentity());
request.setRecordType(ORecordInternal.getRecordType(txEntry.getRecord()));
switch (txEntry.type) {
case ORecordOperation.CREATED:
case ORecordOperation.UPDATED:
request.setRecord(
ORecordSerializerNetworkV37Client.INSTANCE.toStream(txEntry.getRecord()));
request.setContentChanged(ORecordInternal.isContentChanged(txEntry.getRecord()));
break;
}
this.operations.add(request);
}
for (Map.Entry<String, OTransactionIndexChanges> change : indexChanges.entrySet()) {
this.indexChanges.add(new IndexChange(change.getKey(), change.getValue()));
}
}
}
public OBeginTransactionRequest() {}
@Override
public void write(OChannelDataOutput network, OStorageRemoteSession session) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public void read(OChannelDataInput channel, int protocolVersion, ORecordSerializer serializer)
throws IOException {
txId = channel.readInt();
hasContent = channel.readBoolean();
usingLog = channel.readBoolean();
operations = new ArrayList<>();
if (hasContent) {
byte hasEntry;
do {
hasEntry = channel.readByte();
if (hasEntry == 1) {
ORecordOperationRequest entry = OMessageHelper.readTransactionEntry(channel, serializer);
operations.add(entry);
}
} while (hasEntry == 1);
// RECEIVE MANUAL INDEX CHANGES
this.indexChanges =
OMessageHelper.readTransactionIndexChanges(
channel, (ORecordSerializerNetworkV37) serializer);
} else {
this.indexChanges = new ArrayList<>();
}
}
@Override
public byte getCommand() {
return OChannelBinaryProtocol.REQUEST_TX_BEGIN;
}
@Override
public OBeginTransactionResponse createResponse() {
return new OBeginTransactionResponse();
}
@Override
public OBinaryResponse execute(OBinaryRequestExecutor executor) {
return executor.executeBeginTransaction(this);
}
@Override
public String getDescription() {
return "Begin Transaction";
}
public List<ORecordOperationRequest> getOperations() {
return operations;
}
public List<IndexChange> getIndexChanges() {
return indexChanges;
}
public int getTxId() {
return txId;
}
public boolean isUsingLog() {
return usingLog;
}
public boolean isHasContent() {
return hasContent;
}
} |
// from 3.0 the the serializer is bound to the protocol
ORecordSerializerNetworkV37Client serializer = ORecordSerializerNetworkV37Client.INSTANCE;
network.writeInt(txId);
network.writeBoolean(hasContent);
network.writeBoolean(usingLog);
if (hasContent) {
for (ORecordOperationRequest txEntry : operations) {
network.writeByte((byte) 1);
OMessageHelper.writeTransactionEntry(network, txEntry, serializer);
}
// END OF RECORD ENTRIES
network.writeByte((byte) 0);
// SEND MANUAL INDEX CHANGES
OMessageHelper.writeTransactionIndexChanges(network, serializer, indexChanges);
}
|
network.writeInt(txId);
network.writeBoolean(hasContent);
network.writeBoolean(usingLog);
if (hasContent) {
for (ORecordOperationRequest entry : operations) {
network.writeByte(1);
OMessageHelper.writeTransactionEntry(network, entry);
}
network.writeByte(0);
// SEND MANUAL INDEX CHANGES
OMessageHelper.writeTransactionIndexChanges(network, indexChanges);
}
| [
"Iterable<ORecordOperation>",
"OChannelDataOutput",
"Map<String,OTransactionIndexChanges>",
"ORecordOperationRequest",
"OStorageRemoteSession"
] | [
"writeBoolean",
"writeInt",
"writeByte",
"writeTransactionIndexChanges",
"writeTransactionEntry"
] | [
"Iterable<ORecordOperation>",
"ORecordOperationRequest",
"OStorageRemoteSession",
"Map<String,OTransactionIndexChanges>",
"ORecordSerializer",
"OChannelDataOutput"
] | [
"writeInt",
"writeBoolean",
"writeByte",
"writeTransactionEntry",
"writeTransactionIndexChanges"
] | {
"methods": [
"writeBoolean",
"writeInt",
"writeByte",
"writeTransactionIndexChanges",
"writeTransactionEntry"
],
"similar_methods": [
"write"
],
"types": [
"Iterable<ORecordOperation>",
"OChannelDataOutput",
"Map<String,OTransactionIndexChanges>",
"ORecordOperationRequest",
"OStorageRemoteSession"
]
} | /**
* @author Artem Orobets (enisher-at-gmail.com)
*/
public interface OIterableRecordSource {
Iterator<OIdentifiable> iterator( final Map<Object,Object> iArgs);
}
/**
* Created by luigidellaquila on 12/12/16.
*/
public interface OChannelDataOutput {
OChannelDataOutput writeByte( final byte iContent) throws IOException ;
OChannelDataOutput writeBoolean( final boolean iContent) throws IOException ;
OChannelDataOutput writeInt( final int iContent) throws IOException ;
OChannelDataOutput writeLong( final long iContent) throws IOException ;
OChannelDataOutput writeShort( final short iContent) throws IOException ;
OChannelDataOutput writeString( final String iContent) throws IOException ;
OChannelDataOutput writeBytes( final byte[] iContent) throws IOException ;
OChannelDataOutput writeBytes( final byte[] iContent, final int iLength) throws IOException ;
void writeRID( final ORID iRID) throws IOException ;
void writeVersion( final int version) throws IOException ;
OutputStream getDataOutput();
}
/**
* Collects the changes to an index for a certain key
* @author Luca Garulli (l.garulli--(at)--orientdb.com)
*/
public class OTransactionIndexChanges {
public enum OPERATION { PUT, REMOVE, CLEAR}
public NavigableMap<Object,OTransactionIndexChangesPerKey> changesPerKey=new TreeMap<Object,OTransactionIndexChangesPerKey>(ODefaultComparator.INSTANCE);
public OTransactionIndexChangesPerKey nullKeyChanges=new OTransactionIndexChangesPerKey(null);
public boolean cleared=false;
private OIndexInternal resolvedIndex=null;
public OTransactionIndexChangesPerKey getChangesPerKey( final Object key);
public void setCleared();
public Object getFirstKey();
public Object getLastKey();
public Object getLowerKey( Object key);
public Object getHigherKey( Object key);
public Object getCeilingKey( Object key);
public Object[] firstAndLastKeys( Object from, boolean fromInclusive, Object to, boolean toInclusive);
public Object getFloorKey( Object key);
public OIndexInternal resolveAssociatedIndex( String indexName, OIndexManagerAbstract indexManager, ODatabaseDocumentInternal db);
public OIndexInternal getAssociatedIndex();
}
public class ORecordOperationRequest {
private byte type;
private byte recordType;
private ORID id;
private ORID oldId;
private byte[] record;
private int version;
private boolean contentChanged;
public ORecordOperationRequest();
public ORecordOperationRequest( byte type, byte recordType, ORID id, ORID oldId, byte[] record, int version, boolean contentChanged);
public ORID getId();
public void setId( ORID id);
public ORID getOldId();
public void setOldId( ORID oldId);
public byte[] getRecord();
public void setRecord( byte[] record);
public byte getRecordType();
public void setRecordType( byte recordType);
public byte getType();
public void setType( byte type);
public int getVersion();
public void setVersion( int version);
public void setContentChanged( boolean contentChanged);
public boolean isContentChanged();
public void deserialize( DataInput input) throws IOException;
public void serialize( DataOutput output) throws IOException;
}
/**
* Created by tglman on 31/03/16.
*/
public class OStorageRemoteSession {
public boolean commandExecuting=false;
protected int serverURLIndex=-1;
protected String connectionUserName=null;
protected String connectionUserPassword=null;
protected Map<String,OStorageRemoteNodeSession> sessions=new HashMap<String,OStorageRemoteNodeSession>();
private Set<OChannelBinary> connections=Collections.newSetFromMap(new WeakHashMap<OChannelBinary,Boolean>());
private final int uniqueClientSessionId;
private boolean closed=true;
/**
* Make the retry to happen only on the current session, if the current session is invalid or the server is offline it kill the operation. <p>this is for avoid to send to the server wrong request expecting a specific state that is not there anymore.
*/
private int stickToSession=0;
protected String currentUrl;
public OStorageRemoteSession( final int sessionId);
public boolean hasConnection( final OChannelBinary connection);
public OStorageRemoteNodeSession getServerSession( final String serverURL);
public synchronized OStorageRemoteNodeSession getOrCreateServerSession( final String serverURL);
public void addConnection( final OChannelBinary connection);
public void close();
public boolean isClosed();
public Integer getSessionId();
public String getServerUrl();
public synchronized void removeServerSession( final String serverURL);
public synchronized Collection<OStorageRemoteNodeSession> getAllServerSessions();
public void stickToSession();
public void unStickToSession();
public boolean isStickToSession();
public void closeAllSessions( ORemoteConnectionManager connectionManager, OContextConfiguration clientConfiguration);
public String getDebugLastHost();
public String getCurrentUrl();
}
public OChannelBinary writeBoolean(final boolean iContent) throws IOException {
if (debug) OLogManager.instance().info(this,"%s - Writing boolean (1 byte): %b",socket.getRemoteSocketAddress(),iContent);
out.writeBoolean(iContent);
updateMetricTransmittedBytes(OBinaryProtocol.SIZE_BYTE);
return this;
}
public OChannelBinary writeInt(final int iContent) throws IOException {
if (debug) OLogManager.instance().info(this,"%s - Writing int (4 bytes): %d",socket.getRemoteSocketAddress(),iContent);
out.writeInt(iContent);
updateMetricTransmittedBytes(OBinaryProtocol.SIZE_INT);
return this;
}
public OChannelBinary writeByte(final byte iContent) throws IOException {
if (debug) OLogManager.instance().info(this,"%s - Writing byte (1 byte): %d",socket.getRemoteSocketAddress(),iContent);
out.write(iContent);
updateMetricTransmittedBytes(OBinaryProtocol.SIZE_BYTE);
return this;
}
static void writeTransactionIndexChanges(OChannelDataOutput network,ORecordSerializerNetworkV37 serializer,List<IndexChange> changes) throws IOException {
network.writeInt(changes.size());
for ( IndexChange indexChange : changes) {
network.writeString(indexChange.getName());
network.writeBoolean(indexChange.getKeyChanges().cleared);
int size=indexChange.getKeyChanges().changesPerKey.size();
if (indexChange.getKeyChanges().nullKeyChanges != null) {
size+=1;
}
network.writeInt(size);
if (indexChange.getKeyChanges().nullKeyChanges != null) {
network.writeByte((byte)-1);
network.writeInt(indexChange.getKeyChanges().nullKeyChanges.size());
for ( OTransactionIndexChangesPerKey.OTransactionIndexEntry perKeyChange : indexChange.getKeyChanges().nullKeyChanges.getEntriesAsList()) {
network.writeInt(perKeyChange.getOperation().ordinal());
network.writeRID(perKeyChange.getValue().getIdentity());
}
}
for ( OTransactionIndexChangesPerKey change : indexChange.getKeyChanges().changesPerKey.values()) {
OType type=OType.getTypeByValue(change.key);
byte[] value=serializer.serializeValue(change.key,type);
network.writeByte((byte)type.getId());
network.writeBytes(value);
network.writeInt(change.size());
for ( OTransactionIndexChangesPerKey.OTransactionIndexEntry perKeyChange : change.getEntriesAsList()) {
OTransactionIndexChanges.OPERATION op=perKeyChange.getOperation();
if (op == OTransactionIndexChanges.OPERATION.REMOVE && perKeyChange.getValue() == null) op=OTransactionIndexChanges.OPERATION.CLEAR;
network.writeInt(op.ordinal());
if (op != OTransactionIndexChanges.OPERATION.CLEAR) network.writeRID(perKeyChange.getValue().getIdentity());
}
}
}
}
static void writeTransactionEntry(final OChannelDataOutput iNetwork,final ORecordOperationRequest txEntry,ORecordSerializer serializer) throws IOException {
iNetwork.writeByte((byte)1);
iNetwork.writeByte(txEntry.getType());
iNetwork.writeRID(txEntry.getId());
iNetwork.writeRID(txEntry.getOldId());
iNetwork.writeByte(txEntry.getRecordType());
switch (txEntry.getType()) {
case ORecordOperation.CREATED:
iNetwork.writeBytes(txEntry.getRecord());
break;
case ORecordOperation.UPDATED:
iNetwork.writeVersion(txEntry.getVersion());
iNetwork.writeBytes(txEntry.getRecord());
iNetwork.writeBoolean(txEntry.isContentChanged());
break;
case ORecordOperation.DELETED:
iNetwork.writeVersion(txEntry.getVersion());
iNetwork.writeBytes(txEntry.getRecord());
break;
}
}
@Override public void write(OChannelDataOutput network,OStorageRemoteSession session) throws IOException {
}
| public interface OIterableRecordSource {
Iterator<OIdentifiable> iterator( final Map<Object,Object> iArgs);
}
public interface OChannelDataOutput {
OChannelDataOutput writeByte( final byte iContent) throws IOException ;
OChannelDataOutput writeBoolean( final boolean iContent) throws IOException ;
OChannelDataOutput writeInt( final int iContent) throws IOException ;
OChannelDataOutput writeLong( final long iContent) throws IOException ;
OChannelDataOutput writeShort( final short iContent) throws IOException ;
OChannelDataOutput writeString( final String iContent) throws IOException ;
OChannelDataOutput writeBytes( final byte[] iContent) throws IOException ;
OChannelDataOutput writeBytes( final byte[] iContent, final int iLength) throws IOException ;
void writeRID( final ORID iRID) throws IOException ;
void writeVersion( final int version) throws IOException ;
OutputStream getDataOutput();
}
public class OTransactionIndexChanges {
public enum OPERATION { PUT, REMOVE, CLEAR}
public NavigableMap<Object,OTransactionIndexChangesPerKey> changesPerKey=new TreeMap<Object,OTransactionIndexChangesPerKey>(ODefaultComparator.INSTANCE);
public OTransactionIndexChangesPerKey nullKeyChanges=new OTransactionIndexChangesPerKey(null);
public boolean cleared=false;
private OIndexInternal resolvedIndex=null;
public OTransactionIndexChangesPerKey getChangesPerKey( final Object key);
public void setCleared();
public Object getFirstKey();
public Object getLastKey();
public Object getLowerKey( Object key);
public Object getHigherKey( Object key);
public Object getCeilingKey( Object key);
public Object[] firstAndLastKeys( Object from, boolean fromInclusive, Object to, boolean toInclusive);
public Object getFloorKey( Object key);
public OIndexInternal resolveAssociatedIndex( String indexName, OIndexManagerAbstract indexManager, ODatabaseDocumentInternal db);
public OIndexInternal getAssociatedIndex();
}
public class ORecordOperationRequest {
private byte type;
private byte recordType;
private ORID id;
private ORID oldId;
private byte[] record;
private int version;
private boolean contentChanged;
public ORecordOperationRequest();
public ORecordOperationRequest( byte type, byte recordType, ORID id, ORID oldId, byte[] record, int version, boolean contentChanged);
public ORID getId();
public void setId( ORID id);
public ORID getOldId();
public void setOldId( ORID oldId);
public byte[] getRecord();
public void setRecord( byte[] record);
public byte getRecordType();
public void setRecordType( byte recordType);
public byte getType();
public void setType( byte type);
public int getVersion();
public void setVersion( int version);
public void setContentChanged( boolean contentChanged);
public boolean isContentChanged();
public void deserialize( DataInput input) throws IOException;
public void serialize( DataOutput output) throws IOException;
}
public class OStorageRemoteSession {
public boolean commandExecuting=false;
protected int serverURLIndex=-1;
protected String connectionUserName=null;
protected String connectionUserPassword=null;
protected Map<String,OStorageRemoteNodeSession> sessions=new HashMap<String,OStorageRemoteNodeSession>();
private Set<OChannelBinary> connections=Collections.newSetFromMap(new WeakHashMap<OChannelBinary,Boolean>());
private final int uniqueClientSessionId;
private boolean closed=true;
private int stickToSession=0;
protected String currentUrl;
public OStorageRemoteSession( final int sessionId);
public boolean hasConnection( final OChannelBinary connection);
public OStorageRemoteNodeSession getServerSession( final String serverURL);
public synchronized OStorageRemoteNodeSession getOrCreateServerSession( final String serverURL);
public void addConnection( final OChannelBinary connection);
public void close();
public boolean isClosed();
public Integer getSessionId();
public String getServerUrl();
public synchronized void removeServerSession( final String serverURL);
public synchronized Collection<OStorageRemoteNodeSession> getAllServerSessions();
public void stickToSession();
public void unStickToSession();
public boolean isStickToSession();
public void closeAllSessions( ORemoteConnectionManager connectionManager, OContextConfiguration clientConfiguration);
public String getDebugLastHost();
public String getCurrentUrl();
}
public OChannelBinary writeBoolean(final boolean iContent) throws IOException {
if (debug) OLogManager.instance().info(this,"%s - Writing boolean (1 byte): %b",socket.getRemoteSocketAddress(),iContent);
out.writeBoolean(iContent);
updateMetricTransmittedBytes(OBinaryProtocol.SIZE_BYTE);
return this;
}
public OChannelBinary writeInt(final int iContent) throws IOException {
if (debug) OLogManager.instance().info(this,"%s - Writing int (4 bytes): %d",socket.getRemoteSocketAddress(),iContent);
out.writeInt(iContent);
updateMetricTransmittedBytes(OBinaryProtocol.SIZE_INT);
return this;
}
public OChannelBinary writeByte(final byte iContent) throws IOException {
if (debug) OLogManager.instance().info(this,"%s - Writing byte (1 byte): %d",socket.getRemoteSocketAddress(),iContent);
out.write(iContent);
updateMetricTransmittedBytes(OBinaryProtocol.SIZE_BYTE);
return this;
}
static void writeTransactionIndexChanges(OChannelDataOutput network,ORecordSerializerNetworkV37 serializer,List<IndexChange> changes) throws IOException {
network.writeInt(changes.size());
for ( IndexChange indexChange : changes) {
network.writeString(indexChange.getName());
network.writeBoolean(indexChange.getKeyChanges().cleared);
int size=indexChange.getKeyChanges().changesPerKey.size();
if (indexChange.getKeyChanges().nullKeyChanges != null) {
size+=1;
}
network.writeInt(size);
if (indexChange.getKeyChanges().nullKeyChanges != null) {
network.writeByte((byte)-1);
network.writeInt(indexChange.getKeyChanges().nullKeyChanges.size());
for ( OTransactionIndexChangesPerKey.OTransactionIndexEntry perKeyChange : indexChange.getKeyChanges().nullKeyChanges.getEntriesAsList()) {
network.writeInt(perKeyChange.getOperation().ordinal());
network.writeRID(perKeyChange.getValue().getIdentity());
}
}
for ( OTransactionIndexChangesPerKey change : indexChange.getKeyChanges().changesPerKey.values()) {
OType type=OType.getTypeByValue(change.key);
byte[] value=serializer.serializeValue(change.key,type);
network.writeByte((byte)type.getId());
network.writeBytes(value);
network.writeInt(change.size());
for ( OTransactionIndexChangesPerKey.OTransactionIndexEntry perKeyChange : change.getEntriesAsList()) {
OTransactionIndexChanges.OPERATION op=perKeyChange.getOperation();
if (op == OTransactionIndexChanges.OPERATION.REMOVE && perKeyChange.getValue() == null) op=OTransactionIndexChanges.OPERATION.CLEAR;
network.writeInt(op.ordinal());
if (op != OTransactionIndexChanges.OPERATION.CLEAR) network.writeRID(perKeyChange.getValue().getIdentity());
}
}
}
}
static void writeTransactionEntry(final OChannelDataOutput iNetwork,final ORecordOperationRequest txEntry,ORecordSerializer serializer) throws IOException {
iNetwork.writeByte((byte)1);
iNetwork.writeByte(txEntry.getType());
iNetwork.writeRID(txEntry.getId());
iNetwork.writeRID(txEntry.getOldId());
iNetwork.writeByte(txEntry.getRecordType());
switch (txEntry.getType()) {
case ORecordOperation.CREATED:
iNetwork.writeBytes(txEntry.getRecord());
break;
case ORecordOperation.UPDATED:
iNetwork.writeVersion(txEntry.getVersion());
iNetwork.writeBytes(txEntry.getRecord());
iNetwork.writeBoolean(txEntry.isContentChanged());
break;
case ORecordOperation.DELETED:
iNetwork.writeVersion(txEntry.getVersion());
iNetwork.writeBytes(txEntry.getRecord());
break;
}
}
@Override public void write(OChannelDataOutput network,OStorageRemoteSession session) throws IOException {
}
| {"types": [{"Iterable<ORecordOperation>": "OIterableRecordSource"}, {"OChannelDataOutput": "OChannelDataOutput"}, {"Map<String,OTransactionIndexChanges>": "OTransactionIndexChanges"}, {"ORecordOperationRequest": "ORecordOperationRequest"}, {"OStorageRemoteSession": "OStorageRemoteSession"}], "methods": [{"writeBoolean": "writeBoolean"}, {"writeInt": "writeInt"}, {"writeByte": "writeByte"}, {"writeTransactionIndexChanges": "writeTransactionIndexChanges"}, {"writeTransactionEntry": "writeTransactionEntry"}], "similar_methods": [{"write": "write"}]} | [{"Iterable<ORecordOperation>": {"retrieved_name": "OIterableRecordSource", "raw_body": "/** \n * @author Artem Orobets (enisher-at-gmail.com) \n */\npublic interface OIterableRecordSource {\n Iterator<OIdentifiable> iterator( final Map<Object,Object> iArgs);\n}\n", "raw_body_no_cmt": "public interface OIterableRecordSource {\n Iterator<OIdentifiable> iterator( final Map<Object,Object> iArgs);\n}\n"}}, {"OChannelDataOutput": {"retrieved_name": "OChannelDataOutput", "raw_body": "/** \n * Created by luigidellaquila on 12/12/16. \n */\npublic interface OChannelDataOutput {\n OChannelDataOutput writeByte( final byte iContent) throws IOException ;\n OChannelDataOutput writeBoolean( final boolean iContent) throws IOException ;\n OChannelDataOutput writeInt( final int iContent) throws IOException ;\n OChannelDataOutput writeLong( final long iContent) throws IOException ;\n OChannelDataOutput writeShort( final short iContent) throws IOException ;\n OChannelDataOutput writeString( final String iContent) throws IOException ;\n OChannelDataOutput writeBytes( final byte[] iContent) throws IOException ;\n OChannelDataOutput writeBytes( final byte[] iContent, final int iLength) throws IOException ;\n void writeRID( final ORID iRID) throws IOException ;\n void writeVersion( final int version) throws IOException ;\n OutputStream getDataOutput();\n}\n", "raw_body_no_cmt": "public interface OChannelDataOutput {\n OChannelDataOutput writeByte( final byte iContent) throws IOException ;\n OChannelDataOutput writeBoolean( final boolean iContent) throws IOException ;\n OChannelDataOutput writeInt( final int iContent) throws IOException ;\n OChannelDataOutput writeLong( final long iContent) throws IOException ;\n OChannelDataOutput writeShort( final short iContent) throws IOException ;\n OChannelDataOutput writeString( final String iContent) throws IOException ;\n OChannelDataOutput writeBytes( final byte[] iContent) throws IOException ;\n OChannelDataOutput writeBytes( final byte[] iContent, final int iLength) throws IOException ;\n void writeRID( final ORID iRID) throws IOException ;\n void writeVersion( final int version) throws IOException ;\n OutputStream getDataOutput();\n}\n"}}, {"Map<String,OTransactionIndexChanges>": {"retrieved_name": "OTransactionIndexChanges", "raw_body": "/** \n * Collects the changes to an index for a certain key\n * @author Luca Garulli (l.garulli--(at)--orientdb.com)\n */\npublic class OTransactionIndexChanges {\n public enum OPERATION { PUT, REMOVE, CLEAR}\n public NavigableMap<Object,OTransactionIndexChangesPerKey> changesPerKey=new TreeMap<Object,OTransactionIndexChangesPerKey>(ODefaultComparator.INSTANCE);\n public OTransactionIndexChangesPerKey nullKeyChanges=new OTransactionIndexChangesPerKey(null);\n public boolean cleared=false;\n private OIndexInternal resolvedIndex=null;\n public OTransactionIndexChangesPerKey getChangesPerKey( final Object key);\n public void setCleared();\n public Object getFirstKey();\n public Object getLastKey();\n public Object getLowerKey( Object key);\n public Object getHigherKey( Object key);\n public Object getCeilingKey( Object key);\n public Object[] firstAndLastKeys( Object from, boolean fromInclusive, Object to, boolean toInclusive);\n public Object getFloorKey( Object key);\n public OIndexInternal resolveAssociatedIndex( String indexName, OIndexManagerAbstract indexManager, ODatabaseDocumentInternal db);\n public OIndexInternal getAssociatedIndex();\n}\n", "raw_body_no_cmt": "public class OTransactionIndexChanges {\n public enum OPERATION { PUT, REMOVE, CLEAR}\n public NavigableMap<Object,OTransactionIndexChangesPerKey> changesPerKey=new TreeMap<Object,OTransactionIndexChangesPerKey>(ODefaultComparator.INSTANCE);\n public OTransactionIndexChangesPerKey nullKeyChanges=new OTransactionIndexChangesPerKey(null);\n public boolean cleared=false;\n private OIndexInternal resolvedIndex=null;\n public OTransactionIndexChangesPerKey getChangesPerKey( final Object key);\n public void setCleared();\n public Object getFirstKey();\n public Object getLastKey();\n public Object getLowerKey( Object key);\n public Object getHigherKey( Object key);\n public Object getCeilingKey( Object key);\n public Object[] firstAndLastKeys( Object from, boolean fromInclusive, Object to, boolean toInclusive);\n public Object getFloorKey( Object key);\n public OIndexInternal resolveAssociatedIndex( String indexName, OIndexManagerAbstract indexManager, ODatabaseDocumentInternal db);\n public OIndexInternal getAssociatedIndex();\n}\n"}}, {"ORecordOperationRequest": {"retrieved_name": "ORecordOperationRequest", "raw_body": "public class ORecordOperationRequest {\n private byte type;\n private byte recordType;\n private ORID id;\n private ORID oldId;\n private byte[] record;\n private int version;\n private boolean contentChanged;\n public ORecordOperationRequest();\n public ORecordOperationRequest( byte type, byte recordType, ORID id, ORID oldId, byte[] record, int version, boolean contentChanged);\n public ORID getId();\n public void setId( ORID id);\n public ORID getOldId();\n public void setOldId( ORID oldId);\n public byte[] getRecord();\n public void setRecord( byte[] record);\n public byte getRecordType();\n public void setRecordType( byte recordType);\n public byte getType();\n public void setType( byte type);\n public int getVersion();\n public void setVersion( int version);\n public void setContentChanged( boolean contentChanged);\n public boolean isContentChanged();\n public void deserialize( DataInput input) throws IOException;\n public void serialize( DataOutput output) throws IOException;\n}\n", "raw_body_no_cmt": "public class ORecordOperationRequest {\n private byte type;\n private byte recordType;\n private ORID id;\n private ORID oldId;\n private byte[] record;\n private int version;\n private boolean contentChanged;\n public ORecordOperationRequest();\n public ORecordOperationRequest( byte type, byte recordType, ORID id, ORID oldId, byte[] record, int version, boolean contentChanged);\n public ORID getId();\n public void setId( ORID id);\n public ORID getOldId();\n public void setOldId( ORID oldId);\n public byte[] getRecord();\n public void setRecord( byte[] record);\n public byte getRecordType();\n public void setRecordType( byte recordType);\n public byte getType();\n public void setType( byte type);\n public int getVersion();\n public void setVersion( int version);\n public void setContentChanged( boolean contentChanged);\n public boolean isContentChanged();\n public void deserialize( DataInput input) throws IOException;\n public void serialize( DataOutput output) throws IOException;\n}\n"}}, {"OStorageRemoteSession": {"retrieved_name": "OStorageRemoteSession", "raw_body": "/** \n * Created by tglman on 31/03/16. \n */\npublic class OStorageRemoteSession {\n public boolean commandExecuting=false;\n protected int serverURLIndex=-1;\n protected String connectionUserName=null;\n protected String connectionUserPassword=null;\n protected Map<String,OStorageRemoteNodeSession> sessions=new HashMap<String,OStorageRemoteNodeSession>();\n private Set<OChannelBinary> connections=Collections.newSetFromMap(new WeakHashMap<OChannelBinary,Boolean>());\n private final int uniqueClientSessionId;\n private boolean closed=true;\n /** \n * Make the retry to happen only on the current session, if the current session is invalid or the server is offline it kill the operation. <p>this is for avoid to send to the server wrong request expecting a specific state that is not there anymore.\n */\n private int stickToSession=0;\n protected String currentUrl;\n public OStorageRemoteSession( final int sessionId);\n public boolean hasConnection( final OChannelBinary connection);\n public OStorageRemoteNodeSession getServerSession( final String serverURL);\n public synchronized OStorageRemoteNodeSession getOrCreateServerSession( final String serverURL);\n public void addConnection( final OChannelBinary connection);\n public void close();\n public boolean isClosed();\n public Integer getSessionId();\n public String getServerUrl();\n public synchronized void removeServerSession( final String serverURL);\n public synchronized Collection<OStorageRemoteNodeSession> getAllServerSessions();\n public void stickToSession();\n public void unStickToSession();\n public boolean isStickToSession();\n public void closeAllSessions( ORemoteConnectionManager connectionManager, OContextConfiguration clientConfiguration);\n public String getDebugLastHost();\n public String getCurrentUrl();\n}\n", "raw_body_no_cmt": "public class OStorageRemoteSession {\n public boolean commandExecuting=false;\n protected int serverURLIndex=-1;\n protected String connectionUserName=null;\n protected String connectionUserPassword=null;\n protected Map<String,OStorageRemoteNodeSession> sessions=new HashMap<String,OStorageRemoteNodeSession>();\n private Set<OChannelBinary> connections=Collections.newSetFromMap(new WeakHashMap<OChannelBinary,Boolean>());\n private final int uniqueClientSessionId;\n private boolean closed=true;\n private int stickToSession=0;\n protected String currentUrl;\n public OStorageRemoteSession( final int sessionId);\n public boolean hasConnection( final OChannelBinary connection);\n public OStorageRemoteNodeSession getServerSession( final String serverURL);\n public synchronized OStorageRemoteNodeSession getOrCreateServerSession( final String serverURL);\n public void addConnection( final OChannelBinary connection);\n public void close();\n public boolean isClosed();\n public Integer getSessionId();\n public String getServerUrl();\n public synchronized void removeServerSession( final String serverURL);\n public synchronized Collection<OStorageRemoteNodeSession> getAllServerSessions();\n public void stickToSession();\n public void unStickToSession();\n public boolean isStickToSession();\n public void closeAllSessions( ORemoteConnectionManager connectionManager, OContextConfiguration clientConfiguration);\n public String getDebugLastHost();\n public String getCurrentUrl();\n}\n"}}] | [{"writeBoolean": {"retrieved_name": "writeBoolean", "raw_body": "public OChannelBinary writeBoolean(final boolean iContent) throws IOException {\n if (debug) OLogManager.instance().info(this,\"%s - Writing boolean (1 byte): %b\",socket.getRemoteSocketAddress(),iContent);\n out.writeBoolean(iContent);\n updateMetricTransmittedBytes(OBinaryProtocol.SIZE_BYTE);\n return this;\n}\n"}}, {"writeInt": {"retrieved_name": "writeInt", "raw_body": "public OChannelBinary writeInt(final int iContent) throws IOException {\n if (debug) OLogManager.instance().info(this,\"%s - Writing int (4 bytes): %d\",socket.getRemoteSocketAddress(),iContent);\n out.writeInt(iContent);\n updateMetricTransmittedBytes(OBinaryProtocol.SIZE_INT);\n return this;\n}\n"}}, {"writeByte": {"retrieved_name": "writeByte", "raw_body": "public OChannelBinary writeByte(final byte iContent) throws IOException {\n if (debug) OLogManager.instance().info(this,\"%s - Writing byte (1 byte): %d\",socket.getRemoteSocketAddress(),iContent);\n out.write(iContent);\n updateMetricTransmittedBytes(OBinaryProtocol.SIZE_BYTE);\n return this;\n}\n"}}, {"writeTransactionIndexChanges": {"retrieved_name": "writeTransactionIndexChanges", "raw_body": "static void writeTransactionIndexChanges(OChannelDataOutput network,ORecordSerializerNetworkV37 serializer,List<IndexChange> changes) throws IOException {\n network.writeInt(changes.size());\n for ( IndexChange indexChange : changes) {\n network.writeString(indexChange.getName());\n network.writeBoolean(indexChange.getKeyChanges().cleared);\n int size=indexChange.getKeyChanges().changesPerKey.size();\n if (indexChange.getKeyChanges().nullKeyChanges != null) {\n size+=1;\n }\n network.writeInt(size);\n if (indexChange.getKeyChanges().nullKeyChanges != null) {\n network.writeByte((byte)-1);\n network.writeInt(indexChange.getKeyChanges().nullKeyChanges.size());\n for ( OTransactionIndexChangesPerKey.OTransactionIndexEntry perKeyChange : indexChange.getKeyChanges().nullKeyChanges.getEntriesAsList()) {\n network.writeInt(perKeyChange.getOperation().ordinal());\n network.writeRID(perKeyChange.getValue().getIdentity());\n }\n }\n for ( OTransactionIndexChangesPerKey change : indexChange.getKeyChanges().changesPerKey.values()) {\n OType type=OType.getTypeByValue(change.key);\n byte[] value=serializer.serializeValue(change.key,type);\n network.writeByte((byte)type.getId());\n network.writeBytes(value);\n network.writeInt(change.size());\n for ( OTransactionIndexChangesPerKey.OTransactionIndexEntry perKeyChange : change.getEntriesAsList()) {\n OTransactionIndexChanges.OPERATION op=perKeyChange.getOperation();\n if (op == OTransactionIndexChanges.OPERATION.REMOVE && perKeyChange.getValue() == null) op=OTransactionIndexChanges.OPERATION.CLEAR;\n network.writeInt(op.ordinal());\n if (op != OTransactionIndexChanges.OPERATION.CLEAR) network.writeRID(perKeyChange.getValue().getIdentity());\n }\n }\n }\n}\n"}}, {"writeTransactionEntry": {"retrieved_name": "writeTransactionEntry", "raw_body": "static void writeTransactionEntry(final OChannelDataOutput iNetwork,final ORecordOperationRequest txEntry,ORecordSerializer serializer) throws IOException {\n iNetwork.writeByte((byte)1);\n iNetwork.writeByte(txEntry.getType());\n iNetwork.writeRID(txEntry.getId());\n iNetwork.writeRID(txEntry.getOldId());\n iNetwork.writeByte(txEntry.getRecordType());\nswitch (txEntry.getType()) {\ncase ORecordOperation.CREATED:\n iNetwork.writeBytes(txEntry.getRecord());\n break;\ncase ORecordOperation.UPDATED:\niNetwork.writeVersion(txEntry.getVersion());\niNetwork.writeBytes(txEntry.getRecord());\niNetwork.writeBoolean(txEntry.isContentChanged());\nbreak;\ncase ORecordOperation.DELETED:\niNetwork.writeVersion(txEntry.getVersion());\niNetwork.writeBytes(txEntry.getRecord());\nbreak;\n}\n}\n"}}] | [{"write": {"retrieved_name": "write", "raw_body": "@Override public void write(OChannelDataOutput network,OStorageRemoteSession session) throws IOException {\n}\n"}}] |
|
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-serializer/autoload-cache-serializer-protobuf/src/main/java/com/jarvis/cache/serializer/protobuf/ProtoBufSerializer.java | ProtoBufSerializer | deepCloneMethodArgs | class ProtoBufSerializer implements ISerializer<CacheWrapper<Object>> {
private ConcurrentHashMap<Class, Lambda> lambdaMap = new ConcurrentHashMap<>();
private static final ObjectMapper MAPPER = new ObjectMapper();
public ProtoBufSerializer() {
MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
MAPPER.registerModule(new SimpleModule().addSerializer(new NullValueSerializer(null)));
MAPPER.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
}
@Override
public byte[] serialize(CacheWrapper<Object> obj) throws Exception {
WriteByteBuf byteBuf = new WriteByteBuf();
byteBuf.writeInt(obj.getExpire());
byteBuf.writeLong(obj.getLastLoadTime());
Object cacheObj = obj.getCacheObject();
if (cacheObj != null) {
if (cacheObj instanceof Message) {
byteBuf.writeBytes(((Message) cacheObj).toByteArray());
} else {
MAPPER.writeValue(byteBuf, cacheObj);
}
}
return byteBuf.toByteArray();
}
@Override
public CacheWrapper<Object> deserialize(final byte[] bytes, Type returnType) throws Exception {
if (bytes == null || bytes.length == 0) {
return null;
}
CacheWrapper<Object> cacheWrapper = new CacheWrapper<>();
ReadByteBuf byteBuf = new ReadByteBuf(bytes);
cacheWrapper.setExpire(byteBuf.readInt());
cacheWrapper.setLastLoadTime(byteBuf.readLong());
byte[] body = byteBuf.readableBytes();
if (body == null || body.length == 0) {
return cacheWrapper;
}
Class<?> clazz = TypeFactory.rawClass(returnType);
if (Message.class.isAssignableFrom(clazz)) {
Lambda lambda = getLambda(clazz);
Object obj = lambda.invoke_for_Object(new ByteArrayInputStream(body));
cacheWrapper.setCacheObject(obj);
} else {
Type[] agsType = new Type[]{returnType};
JavaType javaType = MAPPER.getTypeFactory().constructType(ParameterizedTypeImpl.make(CacheWrapper.class, agsType, null));
cacheWrapper.setCacheObject(MAPPER.readValue(body, clazz));
}
return cacheWrapper;
}
@SuppressWarnings("unchecked")
@Override
public Object deepClone(Object obj, Type type) throws Exception {
if (null == obj) {
return null;
}
Class<?> clazz = obj.getClass();
if (BeanUtil.isPrimitive(obj) || clazz.isEnum() || obj instanceof Class || clazz.isAnnotation()
|| clazz.isSynthetic()) {// 常见不会被修改的数据类型
return obj;
}
if (obj instanceof Date) {
return ((Date) obj).clone();
} else if (obj instanceof Calendar) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(((Calendar) obj).getTime().getTime());
return cal;
}
if (obj instanceof CacheWrapper) {
CacheWrapper<Object> wrapper = (CacheWrapper<Object>) obj;
CacheWrapper<Object> res = new CacheWrapper<>();
res.setExpire(wrapper.getExpire());
res.setLastLoadTime(wrapper.getLastLoadTime());
res.setCacheObject(deepClone(wrapper.getCacheObject(), null));
return res;
}
if (obj instanceof Message) {
return ((Message) obj).toBuilder().build();
}
return MAPPER.readValue(MAPPER.writeValueAsBytes(obj), clazz);
}
@Override
public Object[] deepCloneMethodArgs(Method method, Object[] args) throws Exception {<FILL_FUNCTION_BODY>}
@SuppressWarnings("unchecked")
private Lambda getLambda(Class clazz) throws NoSuchMethodException {
Lambda lambda = lambdaMap.get(clazz);
if (lambda == null) {
Method method = clazz.getDeclaredMethod("parseFrom", InputStream.class);
try {
lambda = LambdaFactory.create(method);
lambdaMap.put(clazz, lambda);
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
return lambda;
}
private class NullValueSerializer extends StdSerializer<NullValue> {
private static final long serialVersionUID = 1999052150548658808L;
private final String classIdentifier;
/**
* @param classIdentifier can be {@literal null} and will be defaulted
* to {@code @class}.
*/
NullValueSerializer(String classIdentifier) {
super(NullValue.class);
this.classIdentifier = StringUtil.hasText(classIdentifier) ? classIdentifier : "@class";
}
/*
* (non-Javadoc)
* @see
* com.fasterxml.jackson.databind.ser.std.StdSerializer#serialize(java.
* lang.Object, com.fasterxml.jackson.core.JsonGenerator,
* com.fasterxml.jackson.databind.SerializerProvider)
*/
@Override
public void serialize(NullValue value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
jgen.writeStartObject();
jgen.writeStringField(classIdentifier, NullValue.class.getName());
jgen.writeEndObject();
}
}
} |
if (null == args || args.length == 0) {
return args;
}
Type[] genericParameterTypes = method.getGenericParameterTypes();
if (args.length != genericParameterTypes.length) {
throw new Exception("the length of " + method.getDeclaringClass().getName() + "." + method.getName() + " must " + genericParameterTypes.length);
}
Object[] res = new Object[args.length];
int len = genericParameterTypes.length;
for (int i = 0; i < len; i++) {
res[i] = deepClone(args[i], null);
}
return res;
|
if (args == null || args.length == 0) {
return args;
}
Object[] res = new Object[args.length];
for (int i = 0; i < args.length; i++) {
res[i] = deepClone(args[i], method.getGenericParameterTypes()[i]);
}
return res;
| [
"Method"
] | [
"getGenericParameterTypes"
] | [
"Method",
"Type[]"
] | [
"getGenericParameterTypes",
"getName",
"getDeclaringClass"
] | {
"methods": [
"getGenericParameterTypes"
],
"similar_methods": [
"deepCloneMethodArgs"
],
"types": [
"Method"
]
} | /**
* Copyright 2016 Anders Granau Høfft Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. END OF NOTICE
* @author Anders Granau Høfft
*/
enum MethodParameter {BOOLEAN(boolean.class), CHAR(char.class), SHORT(short.class), BYTE(byte.class), INT(int.class), FLOAT(float.class), LONG(long.class), DOUBLE(double.class), OBJECT(Object.class); private Class<?> type;
private MethodParameter(Class<?> type){
this.type=type;
}
Class<?> getType(){
return type;
}
String getTypeAsSourceCodeString(){
return getType().getSimpleName();
}
}
Class<?> getType(){
return type;
}
@Override public Object[] deepCloneMethodArgs(Method method,Object[] args) throws Exception {
if (null == args || args.length == 0) {
return args;
}
Type[] genericParameterTypes=method.getGenericParameterTypes();
if (args.length != genericParameterTypes.length) {
throw new Exception("the length of " + method.getDeclaringClass().getName() + "."+ method.getName()+ " must "+ genericParameterTypes.length);
}
Object[] res=new Object[args.length];
int len=genericParameterTypes.length;
for (int i=0; i < len; i++) {
res[i]=deepClone(args[i],null);
}
return res;
}
| /**
* Copyright 2016 Anders Granau Høfft Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. END OF NOTICE
* @author Anders Granau Høfft
*/
enum MethodParameter {BOOLEAN(boolean.class), CHAR(char.class), SHORT(short.class), BYTE(byte.class), INT(int.class), FLOAT(float.class), LONG(long.class), DOUBLE(double.class), OBJECT(Object.class); private Class<?> type;
private MethodParameter(Class<?> type){
this.type=type;
}
Class<?> getType(){
return type;
}
String getTypeAsSourceCodeString(){
return getType().getSimpleName();
}
}
Class<?> getType(){
return type;
}
@Override public Object[] deepCloneMethodArgs(Method method,Object[] args) throws Exception {
if (null == args || args.length == 0) {
return args;
}
Type[] genericParameterTypes=method.getGenericParameterTypes();
if (args.length != genericParameterTypes.length) {
throw new Exception("the length of " + method.getDeclaringClass().getName() + "."+ method.getName()+ " must "+ genericParameterTypes.length);
}
Object[] res=new Object[args.length];
int len=genericParameterTypes.length;
for (int i=0; i < len; i++) {
res[i]=deepClone(args[i],null);
}
return res;
}
| {"types": [{"Method": "MethodParameter"}], "methods": [{"getGenericParameterTypes": "getType"}], "similar_methods": [{"deepCloneMethodArgs": "deepCloneMethodArgs"}]} | [{"Method": {"retrieved_name": "MethodParameter", "raw_body": "/** \n * Copyright 2016 Anders Granau H\u00f8fft Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. END OF NOTICE\n * @author Anders Granau H\u00f8fft\n */\nenum MethodParameter {BOOLEAN(boolean.class), CHAR(char.class), SHORT(short.class), BYTE(byte.class), INT(int.class), FLOAT(float.class), LONG(long.class), DOUBLE(double.class), OBJECT(Object.class); private Class<?> type;\nprivate MethodParameter(Class<?> type){\n this.type=type;\n}\nClass<?> getType(){\n return type;\n}\nString getTypeAsSourceCodeString(){\n return getType().getSimpleName();\n}\n}\n", "raw_body_no_cmt": "/** \n * Copyright 2016 Anders Granau H\u00f8fft Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. END OF NOTICE\n * @author Anders Granau H\u00f8fft\n */\nenum MethodParameter {BOOLEAN(boolean.class), CHAR(char.class), SHORT(short.class), BYTE(byte.class), INT(int.class), FLOAT(float.class), LONG(long.class), DOUBLE(double.class), OBJECT(Object.class); private Class<?> type;\nprivate MethodParameter(Class<?> type){\n this.type=type;\n}\nClass<?> getType(){\n return type;\n}\nString getTypeAsSourceCodeString(){\n return getType().getSimpleName();\n}\n}\n"}}] | [{"getGenericParameterTypes": {"retrieved_name": "getType", "raw_body": "Class<?> getType(){\n return type;\n}\n"}}] | [{"deepCloneMethodArgs": {"retrieved_name": "deepCloneMethodArgs", "raw_body": "@Override public Object[] deepCloneMethodArgs(Method method,Object[] args) throws Exception {\n if (null == args || args.length == 0) {\n return args;\n }\n Type[] genericParameterTypes=method.getGenericParameterTypes();\n if (args.length != genericParameterTypes.length) {\n throw new Exception(\"the length of \" + method.getDeclaringClass().getName() + \".\"+ method.getName()+ \" must \"+ genericParameterTypes.length);\n }\n Object[] res=new Object[args.length];\n int len=genericParameterTypes.length;\n for (int i=0; i < len; i++) {\n res[i]=deepClone(args[i],null);\n }\n return res;\n}\n"}}] |
|
joelittlejohn_jsonschema2pojo | jsonschema2pojo/jsonschema2pojo-core/src/main/java/org/jsonschema2pojo/rules/CommentRule.java | CommentRule | apply | class CommentRule implements Rule<JDocCommentable, JDocComment> {
protected CommentRule() {
}
/**
* Applies this schema rule to take the required code generation steps.
* <p>
* When a $comment node is found and applied with this rule, the value of
* the $comment is added as a method and field level JavaDoc comment.
*
* @param nodeName
* the name of the object to which this description applies
* @param node
* the "$comment" schema node
* @param parent
* the parent node
* @param generatableType
* comment-able code generation construct, usually a java class,
* which should have this description applied
* @return the JavaDoc comment created to contain the description
*/
@Override
public JDocComment apply(String nodeName, JsonNode node, JsonNode parent, JDocCommentable generatableType, Schema schema) {<FILL_FUNCTION_BODY>}
} |
JDocComment javadoc = generatableType.javadoc();
String descriptionText = node.asText();
if(StringUtils.isNotBlank(descriptionText)) {
String[] lines = node.asText().split("/\r?\n/");
for(String line : lines) {
javadoc.append(line);
}
}
return javadoc;
|
JDocComment comment = new JDocComment(node.asText());
generatableType.addComment(comment);
return comment;
| [
"Schema",
"JDocCommentable",
"JsonNode",
"JDocComment"
] | [
"asText",
"addComment"
] | [
"JsonNode",
"Schema",
"JDocCommentable",
"JDocComment"
] | [
"javadoc",
"append",
"asText",
"isNotBlank",
"split"
] | {
"methods": [
"asText",
"addComment"
],
"similar_methods": [
"apply"
],
"types": [
"Schema",
"JDocCommentable",
"JsonNode",
"JDocComment"
]
} | /**
* A JSON Schema document.
*/
public class Schema {
private final URI id;
private final JsonNode content;
private final Schema parent;
private JType javaType;
public Schema( URI id, JsonNode content, Schema parent);
public JType getJavaType();
public void setJavaType( JType javaType);
public void setJavaTypeIfEmpty( JType javaType);
public URI getId();
public JsonNode getContent();
public Schema getParent();
public Schema getGrandParent();
public boolean isGenerated();
}
public class DollarCommentIT {
@ClassRule public static Jsonschema2PojoRule schemaRule=new Jsonschema2PojoRule();
private static JavaClass classWithDescription;
@BeforeClass public static void generateClasses() throws IOException;
@Test public void dollarCommentAppearsInClassJavadoc();
@Test public void dollarCommentAppearsInFieldJavadoc();
@Test public void dollarCommentAppearsInGetterJavadoc();
@Test public void dollarCommentAppearsInSetterJavadoc();
@Test public void descriptionAndCommentCanCoexist();
}
@RunWith(Parameterized.class) public class JsonTypesIT {
@Parameters(name="{0}") public static List<Object[]> data();
@Rule public Jsonschema2PojoRule schemaRule=new Jsonschema2PojoRule();
@Rule public ExpectedException thrown=ExpectedException.none();
private final String format;
private final ObjectMapper objectMapper;
public JsonTypesIT( final String format, final ObjectMapper objectMapper);
private String filePath( String baseName);
@Test public void simpleTypesInExampleAreMappedToCorrectJavaTypes() throws Exception;
@Test public void integerIsMappedToBigInteger() throws Exception;
@Test public void numberIsMappedToBigDecimal() throws Exception;
@Test(expected=ClassNotFoundException.class) public void simpleTypeAtRootProducesNoJavaTypes() throws ClassNotFoundException;
@Test @SuppressWarnings("unchecked") public void complexTypesProduceObjects() throws Exception;
@Test @SuppressWarnings("rawtypes") public void arrayTypePropertiesProduceLists() throws Exception;
@Test public void arrayItemsAreRecursivelyMerged() throws Exception;
@Test public void arrayItemsAreNotRecursivelyMerged() throws Exception;
@Test(expected=ClassNotFoundException.class) public void arrayAtRootWithSimpleTypeProducesNoJavaTypes() throws Exception;
@Test public void propertiesWithSameNameOnDifferentObjects() throws Exception;
}
public static Matcher<File> containsText(String searchText){
return new FileSearchMatcher(searchText);
}
public Builder addIncludes(String... includes){
if (includes != null) {
addIncludes(asList(includes));
}
return this;
}
/**
* Applies this schema rule to take the required code generation steps. <p> If additionalProperties is specified and set to the boolean value <code>false</code>, this rule does not make any change to the generated Java type (the type does not allow additional properties). <p> If the additionalProperties node is <code>null</code> (not specified in the schema) or empty, then a new bean property named "additionalProperties", of type {@link Map}{@literal <String,Object>} isadded to the generated type (with appropriate accessors). The accessors are annotated to allow unrecognised (additional) properties found in JSON data to be marshalled/unmarshalled from/to this map. <p> If the additionalProperties node is present and specifies a schema, then an "additionalProperties" map is added to the generated type. This time the map values will be restricted and must be instances of a newly generated Java type that will be created based on the additionalProperties schema provided. If the schema does not specify the javaType property, the name of the newly generated type will be derived from the nodeName and the suffix 'Property'.
* @param nodeName the name of the schema node for which the additionalProperties node applies
* @param node the additionalProperties node itself, found in the schema (may be null if not specified in the schema)
* @param jclass the Java type that is being generated to represent this schema
* @return the given Java type jclass
*/
@Override public JDefinedClass apply(String nodeName,JsonNode node,JsonNode parent,JDefinedClass jclass,Schema schema){
if (node != null && node.isBoolean() && node.asBoolean() == false) {
return jclass;
}
if (!this.ruleFactory.getGenerationConfig().isIncludeAdditionalProperties()) {
return jclass;
}
if (!ruleFactory.getAnnotator().isAdditionalPropertiesSupported()) {
return jclass;
}
JType propertyType;
if (node != null && node.size() != 0) {
String pathToAdditionalProperties;
if (schema.getId() == null || schema.getId().getFragment() == null) {
pathToAdditionalProperties="#/additionalProperties";
}
else {
pathToAdditionalProperties="#" + schema.getId().getFragment() + "/additionalProperties";
}
Schema additionalPropertiesSchema=ruleFactory.getSchemaStore().create(schema,pathToAdditionalProperties,ruleFactory.getGenerationConfig().getRefFragmentPathDelimiters());
propertyType=ruleFactory.getSchemaRule().apply(nodeName + "Property",node,parent,jclass,additionalPropertiesSchema);
additionalPropertiesSchema.setJavaTypeIfEmpty(propertyType);
}
else {
propertyType=jclass.owner().ref(Object.class);
}
JFieldVar field=addAdditionalPropertiesField(jclass,propertyType);
addGetter(jclass,field);
addSetter(jclass,propertyType,field);
if (ruleFactory.getGenerationConfig().isIncludeJsr303Annotations()) {
ruleFactory.getValidRule().apply(nodeName,node,parent,field,schema);
}
if (ruleFactory.getGenerationConfig().isGenerateBuilders()) {
addBuilder(jclass,propertyType,field);
}
return jclass;
}
| public class Schema {
private final URI id;
private final JsonNode content;
private final Schema parent;
private JType javaType;
public Schema( URI id, JsonNode content, Schema parent);
public JType getJavaType();
public void setJavaType( JType javaType);
public void setJavaTypeIfEmpty( JType javaType);
public URI getId();
public JsonNode getContent();
public Schema getParent();
public Schema getGrandParent();
public boolean isGenerated();
}
public class DollarCommentIT {
public static Jsonschema2PojoRule schemaRule=new Jsonschema2PojoRule();
private static JavaClass classWithDescription;
public static void generateClasses() throws IOException;
public void dollarCommentAppearsInClassJavadoc();
public void dollarCommentAppearsInFieldJavadoc();
public void dollarCommentAppearsInGetterJavadoc();
public void dollarCommentAppearsInSetterJavadoc();
public void descriptionAndCommentCanCoexist();
}
public class JsonTypesIT {
public static List<Object[]> data();
public Jsonschema2PojoRule schemaRule=new Jsonschema2PojoRule();
public ExpectedException thrown=ExpectedException.none();
private final String format;
private final ObjectMapper objectMapper;
public JsonTypesIT( final String format, final ObjectMapper objectMapper);
private String filePath( String baseName);
public void simpleTypesInExampleAreMappedToCorrectJavaTypes() throws Exception;
public void integerIsMappedToBigInteger() throws Exception;
public void numberIsMappedToBigDecimal() throws Exception;
public void simpleTypeAtRootProducesNoJavaTypes() throws ClassNotFoundException;
public void complexTypesProduceObjects() throws Exception;
public void arrayTypePropertiesProduceLists() throws Exception;
public void arrayItemsAreRecursivelyMerged() throws Exception;
public void arrayItemsAreNotRecursivelyMerged() throws Exception;
public void arrayAtRootWithSimpleTypeProducesNoJavaTypes() throws Exception;
public void propertiesWithSameNameOnDifferentObjects() throws Exception;
}
public static Matcher<File> containsText(String searchText){
return new FileSearchMatcher(searchText);
}
public Builder addIncludes(String... includes){
if (includes != null) {
addIncludes(asList(includes));
}
return this;
}
/**
* Applies this schema rule to take the required code generation steps. <p> If additionalProperties is specified and set to the boolean value <code>false</code>, this rule does not make any change to the generated Java type (the type does not allow additional properties). <p> If the additionalProperties node is <code>null</code> (not specified in the schema) or empty, then a new bean property named "additionalProperties", of type {@link Map}{@literal <String,Object>} isadded to the generated type (with appropriate accessors). The accessors are annotated to allow unrecognised (additional) properties found in JSON data to be marshalled/unmarshalled from/to this map. <p> If the additionalProperties node is present and specifies a schema, then an "additionalProperties" map is added to the generated type. This time the map values will be restricted and must be instances of a newly generated Java type that will be created based on the additionalProperties schema provided. If the schema does not specify the javaType property, the name of the newly generated type will be derived from the nodeName and the suffix 'Property'.
* @param nodeName the name of the schema node for which the additionalProperties node applies
* @param node the additionalProperties node itself, found in the schema (may be null if not specified in the schema)
* @param jclass the Java type that is being generated to represent this schema
* @return the given Java type jclass
*/
@Override public JDefinedClass apply(String nodeName,JsonNode node,JsonNode parent,JDefinedClass jclass,Schema schema){
if (node != null && node.isBoolean() && node.asBoolean() == false) {
return jclass;
}
if (!this.ruleFactory.getGenerationConfig().isIncludeAdditionalProperties()) {
return jclass;
}
if (!ruleFactory.getAnnotator().isAdditionalPropertiesSupported()) {
return jclass;
}
JType propertyType;
if (node != null && node.size() != 0) {
String pathToAdditionalProperties;
if (schema.getId() == null || schema.getId().getFragment() == null) {
pathToAdditionalProperties="#/additionalProperties";
}
else {
pathToAdditionalProperties="#" + schema.getId().getFragment() + "/additionalProperties";
}
Schema additionalPropertiesSchema=ruleFactory.getSchemaStore().create(schema,pathToAdditionalProperties,ruleFactory.getGenerationConfig().getRefFragmentPathDelimiters());
propertyType=ruleFactory.getSchemaRule().apply(nodeName + "Property",node,parent,jclass,additionalPropertiesSchema);
additionalPropertiesSchema.setJavaTypeIfEmpty(propertyType);
}
else {
propertyType=jclass.owner().ref(Object.class);
}
JFieldVar field=addAdditionalPropertiesField(jclass,propertyType);
addGetter(jclass,field);
addSetter(jclass,propertyType,field);
if (ruleFactory.getGenerationConfig().isIncludeJsr303Annotations()) {
ruleFactory.getValidRule().apply(nodeName,node,parent,field,schema);
}
if (ruleFactory.getGenerationConfig().isGenerateBuilders()) {
addBuilder(jclass,propertyType,field);
}
return jclass;
}
| {"types": [{"Schema": "Schema"}, {"JDocCommentable": "DollarCommentIT"}, {"JsonNode": "JsonTypesIT"}, {"JDocComment": "DollarCommentIT"}], "methods": [{"asText": "containsText"}, {"addComment": "addIncludes"}], "similar_methods": [{"apply": "apply"}]} | [{"Schema": {"retrieved_name": "Schema", "raw_body": "/** \n * A JSON Schema document.\n */\npublic class Schema {\n private final URI id;\n private final JsonNode content;\n private final Schema parent;\n private JType javaType;\n public Schema( URI id, JsonNode content, Schema parent);\n public JType getJavaType();\n public void setJavaType( JType javaType);\n public void setJavaTypeIfEmpty( JType javaType);\n public URI getId();\n public JsonNode getContent();\n public Schema getParent();\n public Schema getGrandParent();\n public boolean isGenerated();\n}\n", "raw_body_no_cmt": "public class Schema {\n private final URI id;\n private final JsonNode content;\n private final Schema parent;\n private JType javaType;\n public Schema( URI id, JsonNode content, Schema parent);\n public JType getJavaType();\n public void setJavaType( JType javaType);\n public void setJavaTypeIfEmpty( JType javaType);\n public URI getId();\n public JsonNode getContent();\n public Schema getParent();\n public Schema getGrandParent();\n public boolean isGenerated();\n}\n"}}, {"JDocCommentable": {"retrieved_name": "DollarCommentIT", "raw_body": "public class DollarCommentIT {\n @ClassRule public static Jsonschema2PojoRule schemaRule=new Jsonschema2PojoRule();\n private static JavaClass classWithDescription;\n @BeforeClass public static void generateClasses() throws IOException;\n @Test public void dollarCommentAppearsInClassJavadoc();\n @Test public void dollarCommentAppearsInFieldJavadoc();\n @Test public void dollarCommentAppearsInGetterJavadoc();\n @Test public void dollarCommentAppearsInSetterJavadoc();\n @Test public void descriptionAndCommentCanCoexist();\n}\n", "raw_body_no_cmt": "public class DollarCommentIT {\n public static Jsonschema2PojoRule schemaRule=new Jsonschema2PojoRule();\n private static JavaClass classWithDescription;\n public static void generateClasses() throws IOException;\n public void dollarCommentAppearsInClassJavadoc();\n public void dollarCommentAppearsInFieldJavadoc();\n public void dollarCommentAppearsInGetterJavadoc();\n public void dollarCommentAppearsInSetterJavadoc();\n public void descriptionAndCommentCanCoexist();\n}\n"}}, {"JsonNode": {"retrieved_name": "JsonTypesIT", "raw_body": "@RunWith(Parameterized.class) public class JsonTypesIT {\n @Parameters(name=\"{0}\") public static List<Object[]> data();\n @Rule public Jsonschema2PojoRule schemaRule=new Jsonschema2PojoRule();\n @Rule public ExpectedException thrown=ExpectedException.none();\n private final String format;\n private final ObjectMapper objectMapper;\n public JsonTypesIT( final String format, final ObjectMapper objectMapper);\n private String filePath( String baseName);\n @Test public void simpleTypesInExampleAreMappedToCorrectJavaTypes() throws Exception;\n @Test public void integerIsMappedToBigInteger() throws Exception;\n @Test public void numberIsMappedToBigDecimal() throws Exception;\n @Test(expected=ClassNotFoundException.class) public void simpleTypeAtRootProducesNoJavaTypes() throws ClassNotFoundException;\n @Test @SuppressWarnings(\"unchecked\") public void complexTypesProduceObjects() throws Exception;\n @Test @SuppressWarnings(\"rawtypes\") public void arrayTypePropertiesProduceLists() throws Exception;\n @Test public void arrayItemsAreRecursivelyMerged() throws Exception;\n @Test public void arrayItemsAreNotRecursivelyMerged() throws Exception;\n @Test(expected=ClassNotFoundException.class) public void arrayAtRootWithSimpleTypeProducesNoJavaTypes() throws Exception;\n @Test public void propertiesWithSameNameOnDifferentObjects() throws Exception;\n}\n", "raw_body_no_cmt": "public class JsonTypesIT {\n public static List<Object[]> data();\n public Jsonschema2PojoRule schemaRule=new Jsonschema2PojoRule();\n public ExpectedException thrown=ExpectedException.none();\n private final String format;\n private final ObjectMapper objectMapper;\n public JsonTypesIT( final String format, final ObjectMapper objectMapper);\n private String filePath( String baseName);\n public void simpleTypesInExampleAreMappedToCorrectJavaTypes() throws Exception;\n public void integerIsMappedToBigInteger() throws Exception;\n public void numberIsMappedToBigDecimal() throws Exception;\n public void simpleTypeAtRootProducesNoJavaTypes() throws ClassNotFoundException;\n public void complexTypesProduceObjects() throws Exception;\n public void arrayTypePropertiesProduceLists() throws Exception;\n public void arrayItemsAreRecursivelyMerged() throws Exception;\n public void arrayItemsAreNotRecursivelyMerged() throws Exception;\n public void arrayAtRootWithSimpleTypeProducesNoJavaTypes() throws Exception;\n public void propertiesWithSameNameOnDifferentObjects() throws Exception;\n}\n"}}] | [{"asText": {"retrieved_name": "containsText", "raw_body": "public static Matcher<File> containsText(String searchText){\n return new FileSearchMatcher(searchText);\n}\n"}}, {"addComment": {"retrieved_name": "addIncludes", "raw_body": "public Builder addIncludes(String... includes){\n if (includes != null) {\n addIncludes(asList(includes));\n }\n return this;\n}\n"}}] | [{"apply": {"retrieved_name": "apply", "raw_body": "/** \n * Applies this schema rule to take the required code generation steps. <p> If additionalProperties is specified and set to the boolean value <code>false</code>, this rule does not make any change to the generated Java type (the type does not allow additional properties). <p> If the additionalProperties node is <code>null</code> (not specified in the schema) or empty, then a new bean property named \"additionalProperties\", of type {@link Map}{@literal <String,Object>} isadded to the generated type (with appropriate accessors). The accessors are annotated to allow unrecognised (additional) properties found in JSON data to be marshalled/unmarshalled from/to this map. <p> If the additionalProperties node is present and specifies a schema, then an \"additionalProperties\" map is added to the generated type. This time the map values will be restricted and must be instances of a newly generated Java type that will be created based on the additionalProperties schema provided. If the schema does not specify the javaType property, the name of the newly generated type will be derived from the nodeName and the suffix 'Property'.\n * @param nodeName the name of the schema node for which the additionalProperties node applies\n * @param node the additionalProperties node itself, found in the schema (may be null if not specified in the schema)\n * @param jclass the Java type that is being generated to represent this schema\n * @return the given Java type jclass\n */\n@Override public JDefinedClass apply(String nodeName,JsonNode node,JsonNode parent,JDefinedClass jclass,Schema schema){\n if (node != null && node.isBoolean() && node.asBoolean() == false) {\n return jclass;\n }\n if (!this.ruleFactory.getGenerationConfig().isIncludeAdditionalProperties()) {\n return jclass;\n }\n if (!ruleFactory.getAnnotator().isAdditionalPropertiesSupported()) {\n return jclass;\n }\n JType propertyType;\n if (node != null && node.size() != 0) {\n String pathToAdditionalProperties;\n if (schema.getId() == null || schema.getId().getFragment() == null) {\n pathToAdditionalProperties=\"#/additionalProperties\";\n }\n else {\n pathToAdditionalProperties=\"#\" + schema.getId().getFragment() + \"/additionalProperties\";\n }\n Schema additionalPropertiesSchema=ruleFactory.getSchemaStore().create(schema,pathToAdditionalProperties,ruleFactory.getGenerationConfig().getRefFragmentPathDelimiters());\n propertyType=ruleFactory.getSchemaRule().apply(nodeName + \"Property\",node,parent,jclass,additionalPropertiesSchema);\n additionalPropertiesSchema.setJavaTypeIfEmpty(propertyType);\n }\n else {\n propertyType=jclass.owner().ref(Object.class);\n }\n JFieldVar field=addAdditionalPropertiesField(jclass,propertyType);\n addGetter(jclass,field);\n addSetter(jclass,propertyType,field);\n if (ruleFactory.getGenerationConfig().isIncludeJsr303Annotations()) {\n ruleFactory.getValidRule().apply(nodeName,node,parent,field,schema);\n }\n if (ruleFactory.getGenerationConfig().isGenerateBuilders()) {\n addBuilder(jclass,propertyType,field);\n }\n return jclass;\n}\n"}}] |
|
pmd_pmd | pmd/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/table/coreimpl/MostlySingularMultimap.java | Builder | appendValue | class Builder<K, V> {
private final MapMaker<K> mapMaker;
private @Nullable Map<K, Object> map;
private boolean consumed;
/** True unless some entry has a list of values. */
private boolean isSingular = true;
private Builder(MapMaker<K> mapMaker) {
this.mapMaker = mapMaker;
}
private Map<K, Object> getMapInternal() {
if (map == null) {
map = mapMaker.copy(Collections.emptyMap());
Validate.isTrue(map.isEmpty(), "Map should be empty");
}
return map;
}
public void replaceValue(K key, V v) {
checkKeyValue(key, v);
getMapInternal().put(key, v);
}
public void addUnlessKeyExists(K key, V v) {
checkKeyValue(key, v);
getMapInternal().putIfAbsent(key, v);
}
public void appendValue(K key, V v) {
appendValue(key, v, false);
}
public void appendValue(K key, V v, boolean noDuplicate) {<FILL_FUNCTION_BODY>}
private void checkKeyValue(K key, V v) {
ensureOpen();
AssertionUtil.requireParamNotNull("value", v);
AssertionUtil.requireParamNotNull("key", key);
}
public Builder<K, V> groupBy(Iterable<? extends V> values,
Function<? super V, ? extends K> keyExtractor) {
ensureOpen();
return groupBy(values, keyExtractor, Function.identity());
}
public <I> Builder<K, V> groupBy(Iterable<? extends I> values,
Function<? super I, ? extends K> keyExtractor,
Function<? super I, ? extends V> valueExtractor) {
ensureOpen();
for (I i : values) {
appendValue(keyExtractor.apply(i), valueExtractor.apply(i));
}
return this;
}
// no duplicates
public Builder<K, V> absorb(Builder<K, V> other) {
ensureOpen();
other.ensureOpen();
if (this.map == null) {
this.map = other.map;
this.isSingular = other.isSingular;
} else {
// isSingular may be changed in the loop by appendSingle
this.isSingular &= other.isSingular;
for (Entry<K, Object> otherEntry : other.getMapInternal().entrySet()) {
K key = otherEntry.getKey();
Object otherV = otherEntry.getValue();
map.compute(key, (k, myV) -> {
if (myV == null) {
return otherV;
} else if (otherV instanceof VList) {
Object newV = myV;
for (V v : (VList<V>) otherV) {
newV = appendSingle(newV, v, true);
}
return newV;
} else {
return appendSingle(myV, (V) otherV, true);
}
});
}
}
other.consume();
return this;
}
private Object appendSingle(@Nullable Object vs, V v, boolean noDuplicate) {
if (vs == null) {
return v;
} else if (vs instanceof VList) {
if (noDuplicate && ((VList) vs).contains(v)) {
return vs;
}
((VList) vs).add(v);
return vs;
} else {
if (noDuplicate && vs.equals(v)) {
return vs;
}
List<V> vs2 = new VList<>(2);
isSingular = false;
vs2.add((V) vs);
vs2.add(v);
return vs2;
}
}
public MostlySingularMultimap<K, V> build() {
consume();
return isEmpty() ? empty() : new MostlySingularMultimap<>(getMapInternal());
}
public @Nullable Map<K, V> buildAsSingular() {
consume();
if (!isSingular) {
return null; // NOPMD: returning null as in the spec (Nullable)
}
return (Map<K, V>) map;
}
private void consume() {
ensureOpen();
consumed = true;
}
private void ensureOpen() {
Validate.isTrue(!consumed, "Builder was already consumed");
}
public boolean isSingular() {
return isSingular;
}
public Map<K, List<V>> getMutableMap() {
Map<K, List<V>> mutable = mapMaker.copy(Collections.emptyMap());
for (Entry<K, Object> entry : getMapInternal().entrySet()) {
mutable.put(entry.getKey(), interpretValue(entry.getValue()));
}
return mutable;
}
public boolean isEmpty() {
return map == null || map.isEmpty();
}
} |
checkKeyValue(key, v);
getMapInternal().compute(key, (k, oldV) -> {
return appendSingle(oldV, v, noDuplicate);
});
|
checkKeyValue(key, v);
getMapInternal().compute(key, (k, myV) -> appendSingle(myV, v, noDuplicate));
| [
"V",
"K"
] | [
"compute"
] | [
"K",
"V"
] | [
"compute"
] | {
"methods": [
"compute"
],
"similar_methods": [
"appendValue"
],
"types": [
"V",
"K"
]
} | public class C {
private C();
public class IC {
}
public static class ISC {
}
public static final String V="";
}
/**
* Create or replace a mapping with a value computed from the current value (or null if missing).
* @param key Key
* @param function Supplier for a value
* @param < T > Type of the data
* @return Value returned by the parameter function
*/
@SuppressWarnings("unchecked") public <T>T compute(DataKey<? extends K,T> key,Function<? super @Nullable T,? extends T> function){
return (T)getMap().compute(key,(k,v) -> function.apply((T)v));
}
@Override void addValue(@NonNull V v){
collector().accumulator().accept(accumulator,v);
}
| public class C {
private C();
public class IC {
}
public static class ISC {
}
public static final String V="";
}
/**
* Create or replace a mapping with a value computed from the current value (or null if missing).
* @param key Key
* @param function Supplier for a value
* @param < T > Type of the data
* @return Value returned by the parameter function
*/
@SuppressWarnings("unchecked") public <T>T compute(DataKey<? extends K,T> key,Function<? super @Nullable T,? extends T> function){
return (T)getMap().compute(key,(k,v) -> function.apply((T)v));
}
@Override void addValue(@NonNull V v){
collector().accumulator().accept(accumulator,v);
}
| {"types": [{"V": "C"}, {"K": "C"}], "methods": [{"compute": "compute"}], "similar_methods": [{"appendValue": "addValue"}]} | [{"V": {"retrieved_name": "C", "raw_body": "public class C {\n private C();\npublic class IC {\n }\npublic static class ISC {\n }\n public static final String V=\"\";\n}\n", "raw_body_no_cmt": "public class C {\n private C();\npublic class IC {\n }\npublic static class ISC {\n }\n public static final String V=\"\";\n}\n"}}] | [{"compute": {"retrieved_name": "compute", "raw_body": "/** \n * Create or replace a mapping with a value computed from the current value (or null if missing).\n * @param key Key\n * @param function Supplier for a value\n * @param < T > Type of the data\n * @return Value returned by the parameter function\n */\n@SuppressWarnings(\"unchecked\") public <T>T compute(DataKey<? extends K,T> key,Function<? super @Nullable T,? extends T> function){\n return (T)getMap().compute(key,(k,v) -> function.apply((T)v));\n}\n"}}] | [{"appendValue": {"retrieved_name": "addValue", "raw_body": "@Override void addValue(@NonNull V v){\n collector().accumulator().accept(accumulator,v);\n}\n"}}] |
|
houbb_sensitive-word | sensitive-word/src/main/java/com/github/houbb/sensitive/word/support/result/WordResultHandlerWordTags.java | WordResultHandlerWordTags | doHandle | class WordResultHandlerWordTags extends AbstractWordResultHandler<WordTagsDto> {
@Override
protected WordTagsDto doHandle(IWordResult wordResult, IWordContext wordContext, String originalText) {<FILL_FUNCTION_BODY>}
} |
// 截取
String word = InnerWordCharUtils.getString(originalText.toCharArray(), wordResult);
// 标签
WordTagsDto dto = new WordTagsDto();
dto.setWord(word);
// 获取 tags
Set<String> wordTags = wordContext.wordTag().getTag(word);
dto.setTags(wordTags);
return dto;
|
return new WordTagsDto(wordResult.getWord(), wordResult.getTags());
| [
"IWordContext",
"IWordResult"
] | [
"getTags",
"getWord"
] | [
"IWordResult",
"Set<String>",
"IWordContext",
"WordTagsDto"
] | [
"toCharArray",
"wordTag",
"setWord",
"getTag",
"getString",
"setTags"
] | {
"methods": [
"getTags",
"getWord"
],
"similar_methods": [
"doHandle"
],
"types": [
"IWordContext",
"IWordResult"
]
} | /**
* @author binbin.hou
* @since 0.0.4
*/
public interface IWordContext {
/**
* 是否忽略大小写
* @return 是否
* @since 0.0.4
*/
boolean ignoreCase();
/**
* 是否忽略半角圆角
* @return 是否
* @since 0.0.4
*/
boolean ignoreWidth();
/**
* 是否忽略数字格式
* @return 是否
* @since 0.0.5
*/
boolean ignoreNumStyle();
/**
* 设置是否忽略大小写
* @param ignoreCase 是否忽略大小写
* @return this
* @since 0.0.4
*/
IWordContext ignoreCase( boolean ignoreCase);
/**
* 设置是否忽略半角圆角
* @param ignoreWidth 是否忽略半角圆角
* @return this
* @since 0.0.4
*/
IWordContext ignoreWidth( boolean ignoreWidth);
/**
* 设置是否忽略半角圆角
* @param ignoreNumStyle 是否忽略半角圆角
* @return this
* @since 0.0.5
*/
IWordContext ignoreNumStyle( boolean ignoreNumStyle);
/**
* 忽略中文繁简体格式
* @return 是否
* @since 0.0.6
*/
boolean ignoreChineseStyle();
/**
* 设置是否忽略中文繁简体格式
* @param ignoreChineseStyle 是否忽略
* @return this
* @since 0.0.6
*/
IWordContext ignoreChineseStyle( final boolean ignoreChineseStyle);
/**
* 是否启用单词
* @return 是否
*/
boolean enableWordCheck();
/**
* 设置是否启用单词
* @param enableWordCheck 是否
* @return 结果
*/
IWordContext enableWordCheck( boolean enableWordCheck);
/**
* 敏感数字检测
* @return 数字检测
* @since 0.0.5
*/
boolean enableNumCheck();
/**
* 设置敏感数字检测
* @param enableNumCheck 数字格式检测
* @return this
* @since 0.0.5
*/
IWordContext enableNumCheck( final boolean enableNumCheck);
/**
* 是否进行邮箱检测
* @return this
* @since 0.0.9
*/
boolean enableEmailCheck();
/**
* 设置敏感邮箱检测
* @param enableEmailCheck 是否检测
* @return this
* @since 0.0.9
*/
IWordContext enableEmailCheck( final boolean enableEmailCheck);
/**
* 敏感链接检测
* @return 是否启用
* @since 0.
*/
boolean enableUrlCheck();
/**
* 设置敏感邮箱检测
* @param enableUrlCheck 是否检测
* @return this
* @since 0.0.9
*/
IWordContext enableUrlCheck( final boolean enableUrlCheck);
/**
* 忽略英文的写法
* @return 数字检测
* @since 0.0.6
*/
boolean ignoreEnglishStyle();
/**
* 设置忽略英文的写法
* @param ignoreEnglishStyle 是否忽略
* @return this
* @since 0.0.6
*/
IWordContext ignoreEnglishStyle( final boolean ignoreEnglishStyle);
/**
* 忽略重复词
* @return 是否忽略
* @since 0.0.7
*/
boolean ignoreRepeat();
/**
* 设置忽略重复词
* @param ignoreRepeat 是否忽略
* @return this
* @since 0.0.7
*/
IWordContext ignoreRepeat( final boolean ignoreRepeat);
/**
* 敏感数字检测
* @return 数字检测
* @since 0.2.1
*/
int sensitiveCheckNumLen();
/**
* 设置敏感数字检测长度
* @param sensitiveCheckNumLen 数字格式检测长度
* @return this
* @since 0.2.1
*/
IWordContext sensitiveCheckNumLen( final int sensitiveCheckNumLen);
/**
* 设置检测策略
* @param sensitiveCheck 检测策略
* @return this
* @since 0.3.0
*/
IWordContext sensitiveCheck( final IWordCheck sensitiveCheck);
/**
* 获取检测策略
* @return 检测策略
* @since 0.3.0
*/
IWordCheck sensitiveCheck();
/**
* 设置敏感词替换策略
* @param wordReplace 策略
* @return this
* @since 0.3.0
*/
IWordContext wordReplace( final IWordReplace wordReplace);
/**
* 敏感词替换策略
* @return 替换策略
* @since 0.3.0
*/
IWordReplace wordReplace();
/**
* 设置统一的字符处理
* @param wordFormat 字符处理
* @return 结果
* @since 0.3.0
*/
IWordContext wordFormat( final IWordFormat wordFormat);
/**
* 获取格式化策略
* @return 策略
* @since 0.3.0
*/
IWordFormat wordFormat();
/**
* 获取 wordMap 策略
* @return 策略
* @since 0.3.2
*/
IWordData wordData();
/**
* 设置 wordMap 策略
* @param wordMap 策略
* @return this
* @since 0.3.2
*/
IWordContext wordData( IWordData wordMap);
IWordTag wordTag();
SensitiveWordContext wordTag( IWordTag wordTag);
ISensitiveWordCharIgnore charIgnore();
SensitiveWordContext charIgnore( ISensitiveWordCharIgnore charIgnore);
IWordResultCondition wordResultCondition();
SensitiveWordContext wordResultCondition( IWordResultCondition wordResultCondition);
}
/**
* 敏感词的结果
* @author binbin.hou
* @since 0.1.0
*/
public interface IWordResult {
/**
* 开始下标
* @return 开始下标
* @since 0.1.0
*/
int startIndex();
/**
* 结束下标
* @return 结束下标
* @since 0.1.0
*/
int endIndex();
/**
* 类别
* @return 类别
* @since 0.14.0
*/
String type();
}
public Set<String> getTags(){
return tags;
}
public String getWord(){
return word;
}
protected abstract R doHandle(IWordResult wordResult,IWordContext wordContext,String originalText);
| public interface IWordContext {
boolean ignoreCase();
boolean ignoreWidth();
boolean ignoreNumStyle();
IWordContext ignoreCase( boolean ignoreCase);
IWordContext ignoreWidth( boolean ignoreWidth);
IWordContext ignoreNumStyle( boolean ignoreNumStyle);
boolean ignoreChineseStyle();
IWordContext ignoreChineseStyle( final boolean ignoreChineseStyle);
boolean enableWordCheck();
IWordContext enableWordCheck( boolean enableWordCheck);
boolean enableNumCheck();
IWordContext enableNumCheck( final boolean enableNumCheck);
boolean enableEmailCheck();
IWordContext enableEmailCheck( final boolean enableEmailCheck);
boolean enableUrlCheck();
IWordContext enableUrlCheck( final boolean enableUrlCheck);
boolean ignoreEnglishStyle();
IWordContext ignoreEnglishStyle( final boolean ignoreEnglishStyle);
boolean ignoreRepeat();
IWordContext ignoreRepeat( final boolean ignoreRepeat);
int sensitiveCheckNumLen();
IWordContext sensitiveCheckNumLen( final int sensitiveCheckNumLen);
IWordContext sensitiveCheck( final IWordCheck sensitiveCheck);
IWordCheck sensitiveCheck();
IWordContext wordReplace( final IWordReplace wordReplace);
IWordReplace wordReplace();
IWordContext wordFormat( final IWordFormat wordFormat);
IWordFormat wordFormat();
IWordData wordData();
IWordContext wordData( IWordData wordMap);
IWordTag wordTag();
SensitiveWordContext wordTag( IWordTag wordTag);
ISensitiveWordCharIgnore charIgnore();
SensitiveWordContext charIgnore( ISensitiveWordCharIgnore charIgnore);
IWordResultCondition wordResultCondition();
SensitiveWordContext wordResultCondition( IWordResultCondition wordResultCondition);
}
public interface IWordResult {
int startIndex();
int endIndex();
String type();
}
public Set<String> getTags(){
return tags;
}
public String getWord(){
return word;
}
protected abstract R doHandle(IWordResult wordResult,IWordContext wordContext,String originalText);
| {"types": [{"IWordContext": "IWordContext"}, {"IWordResult": "IWordResult"}], "methods": [{"getTags": "getTags"}, {"getWord": "getWord"}], "similar_methods": [{"doHandle": "doHandle"}]} | [{"IWordContext": {"retrieved_name": "IWordContext", "raw_body": "/** \n * @author binbin.hou\n * @since 0.0.4\n */\npublic interface IWordContext {\n /** \n * \u662f\u5426\u5ffd\u7565\u5927\u5c0f\u5199\n * @return \u662f\u5426\n * @since 0.0.4\n */\n boolean ignoreCase();\n /** \n * \u662f\u5426\u5ffd\u7565\u534a\u89d2\u5706\u89d2\n * @return \u662f\u5426\n * @since 0.0.4\n */\n boolean ignoreWidth();\n /** \n * \u662f\u5426\u5ffd\u7565\u6570\u5b57\u683c\u5f0f\n * @return \u662f\u5426\n * @since 0.0.5\n */\n boolean ignoreNumStyle();\n /** \n * \u8bbe\u7f6e\u662f\u5426\u5ffd\u7565\u5927\u5c0f\u5199\n * @param ignoreCase \u662f\u5426\u5ffd\u7565\u5927\u5c0f\u5199\n * @return this\n * @since 0.0.4\n */\n IWordContext ignoreCase( boolean ignoreCase);\n /** \n * \u8bbe\u7f6e\u662f\u5426\u5ffd\u7565\u534a\u89d2\u5706\u89d2\n * @param ignoreWidth \u662f\u5426\u5ffd\u7565\u534a\u89d2\u5706\u89d2\n * @return this\n * @since 0.0.4\n */\n IWordContext ignoreWidth( boolean ignoreWidth);\n /** \n * \u8bbe\u7f6e\u662f\u5426\u5ffd\u7565\u534a\u89d2\u5706\u89d2\n * @param ignoreNumStyle \u662f\u5426\u5ffd\u7565\u534a\u89d2\u5706\u89d2\n * @return this\n * @since 0.0.5\n */\n IWordContext ignoreNumStyle( boolean ignoreNumStyle);\n /** \n * \u5ffd\u7565\u4e2d\u6587\u7e41\u7b80\u4f53\u683c\u5f0f\n * @return \u662f\u5426\n * @since 0.0.6\n */\n boolean ignoreChineseStyle();\n /** \n * \u8bbe\u7f6e\u662f\u5426\u5ffd\u7565\u4e2d\u6587\u7e41\u7b80\u4f53\u683c\u5f0f\n * @param ignoreChineseStyle \u662f\u5426\u5ffd\u7565\n * @return this\n * @since 0.0.6\n */\n IWordContext ignoreChineseStyle( final boolean ignoreChineseStyle);\n /** \n * \u662f\u5426\u542f\u7528\u5355\u8bcd\n * @return \u662f\u5426\n */\n boolean enableWordCheck();\n /** \n * \u8bbe\u7f6e\u662f\u5426\u542f\u7528\u5355\u8bcd\n * @param enableWordCheck \u662f\u5426\n * @return \u7ed3\u679c\n */\n IWordContext enableWordCheck( boolean enableWordCheck);\n /** \n * \u654f\u611f\u6570\u5b57\u68c0\u6d4b\n * @return \u6570\u5b57\u68c0\u6d4b\n * @since 0.0.5\n */\n boolean enableNumCheck();\n /** \n * \u8bbe\u7f6e\u654f\u611f\u6570\u5b57\u68c0\u6d4b\n * @param enableNumCheck \u6570\u5b57\u683c\u5f0f\u68c0\u6d4b\n * @return this\n * @since 0.0.5\n */\n IWordContext enableNumCheck( final boolean enableNumCheck);\n /** \n * \u662f\u5426\u8fdb\u884c\u90ae\u7bb1\u68c0\u6d4b\n * @return this\n * @since 0.0.9\n */\n boolean enableEmailCheck();\n /** \n * \u8bbe\u7f6e\u654f\u611f\u90ae\u7bb1\u68c0\u6d4b\n * @param enableEmailCheck \u662f\u5426\u68c0\u6d4b\n * @return this\n * @since 0.0.9\n */\n IWordContext enableEmailCheck( final boolean enableEmailCheck);\n /** \n * \u654f\u611f\u94fe\u63a5\u68c0\u6d4b\n * @return \u662f\u5426\u542f\u7528\n * @since 0.\n */\n boolean enableUrlCheck();\n /** \n * \u8bbe\u7f6e\u654f\u611f\u90ae\u7bb1\u68c0\u6d4b\n * @param enableUrlCheck \u662f\u5426\u68c0\u6d4b\n * @return this\n * @since 0.0.9\n */\n IWordContext enableUrlCheck( final boolean enableUrlCheck);\n /** \n * \u5ffd\u7565\u82f1\u6587\u7684\u5199\u6cd5\n * @return \u6570\u5b57\u68c0\u6d4b\n * @since 0.0.6\n */\n boolean ignoreEnglishStyle();\n /** \n * \u8bbe\u7f6e\u5ffd\u7565\u82f1\u6587\u7684\u5199\u6cd5\n * @param ignoreEnglishStyle \u662f\u5426\u5ffd\u7565\n * @return this\n * @since 0.0.6\n */\n IWordContext ignoreEnglishStyle( final boolean ignoreEnglishStyle);\n /** \n * \u5ffd\u7565\u91cd\u590d\u8bcd\n * @return \u662f\u5426\u5ffd\u7565\n * @since 0.0.7\n */\n boolean ignoreRepeat();\n /** \n * \u8bbe\u7f6e\u5ffd\u7565\u91cd\u590d\u8bcd\n * @param ignoreRepeat \u662f\u5426\u5ffd\u7565\n * @return this\n * @since 0.0.7\n */\n IWordContext ignoreRepeat( final boolean ignoreRepeat);\n /** \n * \u654f\u611f\u6570\u5b57\u68c0\u6d4b\n * @return \u6570\u5b57\u68c0\u6d4b\n * @since 0.2.1\n */\n int sensitiveCheckNumLen();\n /** \n * \u8bbe\u7f6e\u654f\u611f\u6570\u5b57\u68c0\u6d4b\u957f\u5ea6\n * @param sensitiveCheckNumLen \u6570\u5b57\u683c\u5f0f\u68c0\u6d4b\u957f\u5ea6\n * @return this\n * @since 0.2.1\n */\n IWordContext sensitiveCheckNumLen( final int sensitiveCheckNumLen);\n /** \n * \u8bbe\u7f6e\u68c0\u6d4b\u7b56\u7565\n * @param sensitiveCheck \u68c0\u6d4b\u7b56\u7565\n * @return this\n * @since 0.3.0\n */\n IWordContext sensitiveCheck( final IWordCheck sensitiveCheck);\n /** \n * \u83b7\u53d6\u68c0\u6d4b\u7b56\u7565\n * @return \u68c0\u6d4b\u7b56\u7565\n * @since 0.3.0\n */\n IWordCheck sensitiveCheck();\n /** \n * \u8bbe\u7f6e\u654f\u611f\u8bcd\u66ff\u6362\u7b56\u7565\n * @param wordReplace \u7b56\u7565\n * @return this\n * @since 0.3.0\n */\n IWordContext wordReplace( final IWordReplace wordReplace);\n /** \n * \u654f\u611f\u8bcd\u66ff\u6362\u7b56\u7565\n * @return \u66ff\u6362\u7b56\u7565\n * @since 0.3.0\n */\n IWordReplace wordReplace();\n /** \n * \u8bbe\u7f6e\u7edf\u4e00\u7684\u5b57\u7b26\u5904\u7406\n * @param wordFormat \u5b57\u7b26\u5904\u7406\n * @return \u7ed3\u679c\n * @since 0.3.0\n */\n IWordContext wordFormat( final IWordFormat wordFormat);\n /** \n * \u83b7\u53d6\u683c\u5f0f\u5316\u7b56\u7565\n * @return \u7b56\u7565\n * @since 0.3.0\n */\n IWordFormat wordFormat();\n /** \n * \u83b7\u53d6 wordMap \u7b56\u7565\n * @return \u7b56\u7565\n * @since 0.3.2\n */\n IWordData wordData();\n /** \n * \u8bbe\u7f6e wordMap \u7b56\u7565\n * @param wordMap \u7b56\u7565\n * @return this\n * @since 0.3.2\n */\n IWordContext wordData( IWordData wordMap);\n IWordTag wordTag();\n SensitiveWordContext wordTag( IWordTag wordTag);\n ISensitiveWordCharIgnore charIgnore();\n SensitiveWordContext charIgnore( ISensitiveWordCharIgnore charIgnore);\n IWordResultCondition wordResultCondition();\n SensitiveWordContext wordResultCondition( IWordResultCondition wordResultCondition);\n}\n", "raw_body_no_cmt": "public interface IWordContext {\n boolean ignoreCase();\n boolean ignoreWidth();\n boolean ignoreNumStyle();\n IWordContext ignoreCase( boolean ignoreCase);\n IWordContext ignoreWidth( boolean ignoreWidth);\n IWordContext ignoreNumStyle( boolean ignoreNumStyle);\n boolean ignoreChineseStyle();\n IWordContext ignoreChineseStyle( final boolean ignoreChineseStyle);\n boolean enableWordCheck();\n IWordContext enableWordCheck( boolean enableWordCheck);\n boolean enableNumCheck();\n IWordContext enableNumCheck( final boolean enableNumCheck);\n boolean enableEmailCheck();\n IWordContext enableEmailCheck( final boolean enableEmailCheck);\n boolean enableUrlCheck();\n IWordContext enableUrlCheck( final boolean enableUrlCheck);\n boolean ignoreEnglishStyle();\n IWordContext ignoreEnglishStyle( final boolean ignoreEnglishStyle);\n boolean ignoreRepeat();\n IWordContext ignoreRepeat( final boolean ignoreRepeat);\n int sensitiveCheckNumLen();\n IWordContext sensitiveCheckNumLen( final int sensitiveCheckNumLen);\n IWordContext sensitiveCheck( final IWordCheck sensitiveCheck);\n IWordCheck sensitiveCheck();\n IWordContext wordReplace( final IWordReplace wordReplace);\n IWordReplace wordReplace();\n IWordContext wordFormat( final IWordFormat wordFormat);\n IWordFormat wordFormat();\n IWordData wordData();\n IWordContext wordData( IWordData wordMap);\n IWordTag wordTag();\n SensitiveWordContext wordTag( IWordTag wordTag);\n ISensitiveWordCharIgnore charIgnore();\n SensitiveWordContext charIgnore( ISensitiveWordCharIgnore charIgnore);\n IWordResultCondition wordResultCondition();\n SensitiveWordContext wordResultCondition( IWordResultCondition wordResultCondition);\n}\n"}}, {"IWordResult": {"retrieved_name": "IWordResult", "raw_body": "/** \n * \u654f\u611f\u8bcd\u7684\u7ed3\u679c\n * @author binbin.hou\n * @since 0.1.0\n */\npublic interface IWordResult {\n /** \n * \u5f00\u59cb\u4e0b\u6807\n * @return \u5f00\u59cb\u4e0b\u6807\n * @since 0.1.0\n */\n int startIndex();\n /** \n * \u7ed3\u675f\u4e0b\u6807\n * @return \u7ed3\u675f\u4e0b\u6807\n * @since 0.1.0\n */\n int endIndex();\n /** \n * \u7c7b\u522b\n * @return \u7c7b\u522b\n * @since 0.14.0\n */\n String type();\n}\n", "raw_body_no_cmt": "public interface IWordResult {\n int startIndex();\n int endIndex();\n String type();\n}\n"}}] | [{"getTags": {"retrieved_name": "getTags", "raw_body": "public Set<String> getTags(){\n return tags;\n}\n"}}, {"getWord": {"retrieved_name": "getWord", "raw_body": "public String getWord(){\n return word;\n}\n"}}] | [{"doHandle": {"retrieved_name": "doHandle", "raw_body": "protected abstract R doHandle(IWordResult wordResult,IWordContext wordContext,String originalText);\n"}}] |
|
orientechnologies_orientdb | orientdb/client/src/main/java/com/orientechnologies/orient/client/remote/message/OReadRecordResponse.java | OReadRecordResponse | read | class OReadRecordResponse implements OBinaryResponse {
private byte recordType;
private int version;
private byte[] record;
private Set<ORecord> recordsToSend;
private ORawBuffer result;
public OReadRecordResponse() {}
public OReadRecordResponse(
byte recordType, int version, byte[] record, Set<ORecord> recordsToSend) {
this.recordType = recordType;
this.version = version;
this.record = record;
this.recordsToSend = recordsToSend;
}
public void write(OChannelDataOutput network, int protocolVersion, ORecordSerializer serializer)
throws IOException {
if (record != null) {
network.writeByte((byte) 1);
if (protocolVersion <= OChannelBinaryProtocol.PROTOCOL_VERSION_27) {
network.writeBytes(record);
network.writeVersion(version);
network.writeByte(recordType);
} else {
network.writeByte(recordType);
network.writeVersion(version);
network.writeBytes(record);
}
for (ORecord d : recordsToSend) {
if (d.getIdentity().isValid()) {
network.writeByte((byte) 2); // CLIENT CACHE
// RECORD. IT ISN'T PART OF THE RESULT SET
OMessageHelper.writeRecord(network, d, serializer);
}
}
}
// End of the response
network.writeByte((byte) 0);
}
@Override
public void read(OChannelDataInput network, OStorageRemoteSession session) throws IOException {<FILL_FUNCTION_BODY>}
public byte[] getRecord() {
return record;
}
public ORawBuffer getResult() {
return result;
}
} |
ORecordSerializerNetworkV37Client serializer = ORecordSerializerNetworkV37Client.INSTANCE;
if (network.readByte() == 0) return;
final ORawBuffer buffer;
final byte type = network.readByte();
final int recVersion = network.readVersion();
final byte[] bytes = network.readBytes();
buffer = new ORawBuffer(bytes, recVersion, type);
// TODO: This should not be here, move it in a callback or similar
final ODatabaseDocument database = ODatabaseRecordThreadLocal.instance().getIfDefined();
ORecord record;
while (network.readByte() == 2) {
record = (ORecord) OMessageHelper.readIdentifiable(network, serializer);
if (database != null)
// PUT IN THE CLIENT LOCAL CACHE
database.getLocalCache().updateRecord(record);
}
result = buffer;
|
byte type = network.readByte();
if (type == 1) {
record = network.readBytes();
version = network.readVersion();
recordType = network.readByte();
result = new ORawBuffer(record);
} else if (type == 2) {
ORecord record = OMessageHelper.readRecord(network, session);
recordsToSend.add(record);
} else if (type == 0) {
// End of the response
return;
} else {
throw new IOException("Unexpected response type: " + type);
}
| [
"ORecord",
"OChannelDataInput",
"ORawBuffer",
"OStorageRemoteSession",
"Set<ORecord>"
] | [
"add",
"readRecord",
"readByte",
"readBytes",
"readVersion"
] | [
"ODatabaseDocument",
"ORawBuffer",
"OStorageRemoteSession",
"ORecord",
"OChannelDataInput",
"ORecordSerializerNetworkV37Client"
] | [
"readBytes",
"instance",
"readByte",
"getIfDefined",
"getLocalCache",
"readVersion",
"readIdentifiable",
"updateRecord"
] | {
"methods": [
"add",
"readRecord",
"readByte",
"readBytes",
"readVersion"
],
"similar_methods": [
"read"
],
"types": [
"ORecord",
"OChannelDataInput",
"ORawBuffer",
"OStorageRemoteSession",
"Set<ORecord>"
]
} | /**
* Generic record representation. The object can be reused across multiple calls to the database by using the {@link #reset()} method.
*/
public interface ORecord extends ORecordElement, OIdentifiable, Serializable, OSerializableStream {
/**
* Removes all the dependencies with other records. All the relationships remain in form of RecordID. If some links contain dirty records, the detach cannot be complete and this method returns false.
* @return True if the document has been successfully detached, otherwise false.
*/
boolean detach();
/**
* Resets the record to be reused. The record is fresh like just created. Use this method to recycle records avoiding the creation of them stressing the JVM Garbage Collector.
* @return The Object instance itself giving a "fluent interface". Useful to call multiple methodsin chain.
*/
<RET extends ORecord>RET reset();
/**
* Unloads current record. All information are lost but the record identity. At the next access the record will be auto-reloaded. Useful to free memory or to avoid to keep an old version of it.
* @return The Object instance itself giving a "fluent interface". Useful to call multiple methodsin chain.
*/
<RET extends ORecord>RET unload();
/**
* All the fields are deleted but the record identity is maintained. Use this to remove all the document's fields.
* @return The Object instance itself giving a "fluent interface". Useful to call multiple methodsin chain.
*/
<RET extends ORecord>RET clear();
/**
* Creates a copy of the record. All the record contents are copied.
* @return The Object instance itself giving a "fluent interface". Useful to call multiple methodsin chain.
*/
<RET extends ORecord>RET copy();
/**
* Returns the record identity as <cluster-id>:<cluster-position>
*/
ORID getIdentity();
/**
* Returns the current version number of the record. When the record is created has version = 0. At every change the storage increment the version number. Version number is used by Optimistic transactions to check if the record is changed in the meanwhile of the transaction.
* @see OTransactionOptimistic
* @return The version number. 0 if it's a brand new record.
*/
int getVersion();
/**
* Returns the database where the record belongs.
* @return
*/
ODatabaseDocument getDatabase();
/**
* Checks if the record is dirty, namely if it was changed in memory.
* @return True if dirty, otherwise false
*/
boolean isDirty();
/**
* Loads the record content in memory. If the record is in cache will be returned a new instance, so pay attention to use the returned. If the record is dirty, then it returns to the original content. If the record does not exist a ORecordNotFoundException exception is thrown.
* @return The record loaded or itself if the record has been reloaded from the storage. Useful tocall methods in chain.
*/
<RET extends ORecord>RET load() throws ORecordNotFoundException ;
/**
* Loads the record content in memory. No cache is used. If the record is dirty, then it returns to the original content. If the record does not exist a ORecordNotFoundException exception is thrown.
* @return The Object instance itself giving a "fluent interface". Useful to call multiple methodsin chain.
*/
<RET extends ORecord>RET reload() throws ORecordNotFoundException ;
<RET extends ORecord>RET reload( final String fetchPlan, final boolean ignoreCache, boolean force) throws ORecordNotFoundException ;
/**
* Saves in-memory changes to the database. Behavior depends by the current running transaction if any. If no transaction is running then changes apply immediately. If an Optimistic transaction is running then the record will be changed at commit time. The current transaction will continue to see the record as modified, while others not. If a Pessimistic transaction is running, then an exclusive lock is acquired against the record. Current transaction will continue to see the record as modified, while others cannot access to it since it's locked.
* @return The Object instance itself giving a "fluent interface". Useful to call multiple methodsin chain.
*/
<RET extends ORecord>RET save();
/**
* Saves in-memory changes to the database defining a specific cluster where to save it. Behavior depends by the current running transaction if any. If no transaction is running then changes apply immediately. If an Optimistic transaction is running then the record will be changed at commit time. The current transaction will continue to see the record as modified, while others not. If a Pessimistic transaction is running, then an exclusive lock is acquired against the record. Current transaction will continue to see the record as modified, while others cannot access to it since it's locked.
* @return The Object instance itself giving a "fluent interface". Useful to call multiple methodsin chain.
*/
<RET extends ORecord>RET save( String iCluster);
<RET extends ORecord>RET save( boolean forceCreate);
<RET extends ORecord>RET save( String iCluster, boolean forceCreate);
/**
* Deletes the record from the database. Behavior depends by the current running transaction if any. If no transaction is running then the record is deleted immediately. If an Optimistic transaction is running then the record will be deleted at commit time. The current transaction will continue to see the record as deleted, while others not. If a Pessimistic transaction is running, then an exclusive lock is acquired against the record. Current transaction will continue to see the record as deleted, while others cannot access to it since it's locked.
* @return The Object instance itself giving a "fluent interface". Useful to call multiple methodsin chain.
*/
<RET extends ORecord>RET delete();
/**
* Fills the record parsing the content in JSON format.
* @param iJson Object content in JSON format
* @return The Object instance itself giving a "fluent interface". Useful to call multiple methodsin chain.
*/
<RET extends ORecord>RET fromJSON( String iJson);
/**
* Exports the record in JSON format.
* @return Object content in JSON format
*/
String toJSON();
/**
* Exports the record in JSON format specifying additional formatting settings.
* @param iFormat Format settings separated by comma. Available settings are:<ul> <li><b>rid</b>: exports the record's id as property "@rid" <li><b>version</b>: exports the record's version as property "@version" <li><b>class</b>: exports the record's class as property "@class" <li><b>attribSameRow</b>: exports all the record attributes in the same row <li><b>indent:<level></b>: Indents the output if the <level> specified. Default is 0 </ul> Example: "rid,version,class,indent:6" exports record id, version and class properties along with record properties using an indenting level equals of 6.
* @return Object content in JSON format
*/
String toJSON( String iFormat);
/**
* Returns the size in bytes of the record. The size can be computed only for not new records.
* @return the size in bytes
*/
int getSize();
/**
* Returns the current status of the record.
* @return Current status as value between the defined values in the enum {@link STATUS}
*/
STATUS getInternalStatus();
/**
* Changes the current internal status.
* @param iStatus status between the values defined in the enum {@link STATUS}
*/
void setInternalStatus( STATUS iStatus);
}
/**
* Created by luigidellaquila on 12/12/16.
*/
public interface OChannelDataInput {
byte readByte() throws IOException ;
boolean readBoolean() throws IOException ;
int readInt() throws IOException ;
long readLong() throws IOException ;
short readShort() throws IOException ;
String readString() throws IOException ;
byte[] readBytes() throws IOException ;
ORecordId readRID() throws IOException ;
int readVersion() throws IOException ;
InputStream getDataInput();
}
public class ORawBuffer extends OBuffer {
public int version;
public byte recordType;
/**
* Constructor used by serialization.
*/
public ORawBuffer();
public ORawBuffer( final byte[] buffer, final int version, final byte recordType);
/**
* Creates a new object by the record received.
*/
public ORawBuffer( final ORecord iRecord);
@Override public void readExternal( final ObjectInput iInput) throws IOException, ClassNotFoundException;
@Override public void writeExternal( final ObjectOutput iOutput) throws IOException;
@Override public boolean equals( final Object o);
@Override public int hashCode();
}
/**
* Created by tglman on 31/03/16.
*/
public class OStorageRemoteSession {
public boolean commandExecuting=false;
protected int serverURLIndex=-1;
protected String connectionUserName=null;
protected String connectionUserPassword=null;
protected Map<String,OStorageRemoteNodeSession> sessions=new HashMap<String,OStorageRemoteNodeSession>();
private Set<OChannelBinary> connections=Collections.newSetFromMap(new WeakHashMap<OChannelBinary,Boolean>());
private final int uniqueClientSessionId;
private boolean closed=true;
/**
* Make the retry to happen only on the current session, if the current session is invalid or the server is offline it kill the operation. <p>this is for avoid to send to the server wrong request expecting a specific state that is not there anymore.
*/
private int stickToSession=0;
protected String currentUrl;
public OStorageRemoteSession( final int sessionId);
public boolean hasConnection( final OChannelBinary connection);
public OStorageRemoteNodeSession getServerSession( final String serverURL);
public synchronized OStorageRemoteNodeSession getOrCreateServerSession( final String serverURL);
public void addConnection( final OChannelBinary connection);
public void close();
public boolean isClosed();
public Integer getSessionId();
public String getServerUrl();
public synchronized void removeServerSession( final String serverURL);
public synchronized Collection<OStorageRemoteNodeSession> getAllServerSessions();
public void stickToSession();
public void unStickToSession();
public boolean isStickToSession();
public void closeAllSessions( ORemoteConnectionManager connectionManager, OContextConfiguration clientConfiguration);
public String getDebugLastHost();
public String getCurrentUrl();
}
/**
* Base interface that represents a record element.
* @author Luca Garulli (l.garulli--(at)--orientdb.com)
*/
public interface ORecordElement {
/**
* Available record statuses.
*/
enum STATUS { NOT_LOADED, LOADED, MARSHALLING, UNMARSHALLING}
/**
* Marks the instance as dirty. The dirty status could be propagated up if the implementation supports ownership concept.
* @return The object it self. Useful to call methods in chain.
*/
<RET>RET setDirty();
void setDirtyNoChanged();
/**
* @return Returns record element which contains given one.
*/
ORecordElement getOwner();
}
@Override public boolean add(OIdentifiable e){
preAdd(e);
lazyLoad(true);
return super.add(e);
}
@Override public ORawBuffer readRecord(final long clusterPosition,final boolean prefetchRecords) throws IOException {
return readRecord(clusterPosition);
}
private byte readByte(final BytesContainer container){
return container.bytes[container.offset++];
}
public byte[] readBytes() throws IOException {
if (debug) OLogManager.instance().info(this,"%s - Reading chunk of bytes. Reading chunk length as int (4 bytes)...",socket.getRemoteSocketAddress());
final int len=in.readInt();
if (len > maxChunkSize) {
throw new IOException("Impossible to read a chunk of length:" + len + " max allowed chunk length:"+ maxChunkSize+ " see NETWORK_BINARY_MAX_CONTENT_LENGTH settings ");
}
updateMetricReceivedBytes(OBinaryProtocol.SIZE_INT + len);
if (debug) OLogManager.instance().info(this,"%s - Read chunk length: %d",socket.getRemoteSocketAddress(),len);
if (len < 0) return null;
if (debug) OLogManager.instance().info(this,"%s - Reading %d bytes...",socket.getRemoteSocketAddress(),len);
final byte[] tmp=new byte[len];
in.readFully(tmp);
if (debug) OLogManager.instance().info(this,"%s - Read %d bytes: %s",socket.getRemoteSocketAddress(),len,new String(tmp));
return tmp;
}
public int readVersion() throws IOException {
return readInt();
}
@Override public void read(OChannelDataInput network,OStorageRemoteSession session) throws IOException {
response.read(network,session);
}
| public interface ORecord extends ORecordElement, OIdentifiable, Serializable, OSerializableStream {
boolean detach();
<RET extends ORecord>RET reset();
<RET extends ORecord>RET unload();
<RET extends ORecord>RET clear();
<RET extends ORecord>RET copy();
ORID getIdentity();
int getVersion();
ODatabaseDocument getDatabase();
boolean isDirty();
<RET extends ORecord>RET load() throws ORecordNotFoundException ;
<RET extends ORecord>RET reload() throws ORecordNotFoundException ;
<RET extends ORecord>RET reload( final String fetchPlan, final boolean ignoreCache, boolean force) throws ORecordNotFoundException ;
<RET extends ORecord>RET save();
<RET extends ORecord>RET save( String iCluster);
<RET extends ORecord>RET save( boolean forceCreate);
<RET extends ORecord>RET save( String iCluster, boolean forceCreate);
<RET extends ORecord>RET delete();
<RET extends ORecord>RET fromJSON( String iJson);
String toJSON();
String toJSON( String iFormat);
int getSize();
STATUS getInternalStatus();
void setInternalStatus( STATUS iStatus);
}
public interface OChannelDataInput {
byte readByte() throws IOException ;
boolean readBoolean() throws IOException ;
int readInt() throws IOException ;
long readLong() throws IOException ;
short readShort() throws IOException ;
String readString() throws IOException ;
byte[] readBytes() throws IOException ;
ORecordId readRID() throws IOException ;
int readVersion() throws IOException ;
InputStream getDataInput();
}
public class ORawBuffer extends OBuffer {
public int version;
public byte recordType;
public ORawBuffer();
public ORawBuffer( final byte[] buffer, final int version, final byte recordType);
public ORawBuffer( final ORecord iRecord);
public void readExternal( final ObjectInput iInput) throws IOException, ClassNotFoundException;
public void writeExternal( final ObjectOutput iOutput) throws IOException;
public boolean equals( final Object o);
public int hashCode();
}
public class OStorageRemoteSession {
public boolean commandExecuting=false;
protected int serverURLIndex=-1;
protected String connectionUserName=null;
protected String connectionUserPassword=null;
protected Map<String,OStorageRemoteNodeSession> sessions=new HashMap<String,OStorageRemoteNodeSession>();
private Set<OChannelBinary> connections=Collections.newSetFromMap(new WeakHashMap<OChannelBinary,Boolean>());
private final int uniqueClientSessionId;
private boolean closed=true;
private int stickToSession=0;
protected String currentUrl;
public OStorageRemoteSession( final int sessionId);
public boolean hasConnection( final OChannelBinary connection);
public OStorageRemoteNodeSession getServerSession( final String serverURL);
public synchronized OStorageRemoteNodeSession getOrCreateServerSession( final String serverURL);
public void addConnection( final OChannelBinary connection);
public void close();
public boolean isClosed();
public Integer getSessionId();
public String getServerUrl();
public synchronized void removeServerSession( final String serverURL);
public synchronized Collection<OStorageRemoteNodeSession> getAllServerSessions();
public void stickToSession();
public void unStickToSession();
public boolean isStickToSession();
public void closeAllSessions( ORemoteConnectionManager connectionManager, OContextConfiguration clientConfiguration);
public String getDebugLastHost();
public String getCurrentUrl();
}
public interface ORecordElement {
enum STATUS { NOT_LOADED, LOADED, MARSHALLING, UNMARSHALLING}
<RET>RET setDirty();
void setDirtyNoChanged();
ORecordElement getOwner();
}
@Override public boolean add(OIdentifiable e){
preAdd(e);
lazyLoad(true);
return super.add(e);
}
@Override public ORawBuffer readRecord(final long clusterPosition,final boolean prefetchRecords) throws IOException {
return readRecord(clusterPosition);
}
private byte readByte(final BytesContainer container){
return container.bytes[container.offset++];
}
public byte[] readBytes() throws IOException {
if (debug) OLogManager.instance().info(this,"%s - Reading chunk of bytes. Reading chunk length as int (4 bytes)...",socket.getRemoteSocketAddress());
final int len=in.readInt();
if (len > maxChunkSize) {
throw new IOException("Impossible to read a chunk of length:" + len + " max allowed chunk length:"+ maxChunkSize+ " see NETWORK_BINARY_MAX_CONTENT_LENGTH settings ");
}
updateMetricReceivedBytes(OBinaryProtocol.SIZE_INT + len);
if (debug) OLogManager.instance().info(this,"%s - Read chunk length: %d",socket.getRemoteSocketAddress(),len);
if (len < 0) return null;
if (debug) OLogManager.instance().info(this,"%s - Reading %d bytes...",socket.getRemoteSocketAddress(),len);
final byte[] tmp=new byte[len];
in.readFully(tmp);
if (debug) OLogManager.instance().info(this,"%s - Read %d bytes: %s",socket.getRemoteSocketAddress(),len,new String(tmp));
return tmp;
}
public int readVersion() throws IOException {
return readInt();
}
@Override public void read(OChannelDataInput network,OStorageRemoteSession session) throws IOException {
response.read(network,session);
}
| {"types": [{"ORecord": "ORecord"}, {"OChannelDataInput": "OChannelDataInput"}, {"ORawBuffer": "ORawBuffer"}, {"OStorageRemoteSession": "OStorageRemoteSession"}, {"Set<ORecord>": "ORecordElement"}], "methods": [{"add": "add"}, {"readRecord": "readRecord"}, {"readByte": "readByte"}, {"readBytes": "readBytes"}, {"readVersion": "readVersion"}], "similar_methods": [{"read": "read"}]} | [{"ORecord": {"retrieved_name": "ORecord", "raw_body": "/** \n * Generic record representation. The object can be reused across multiple calls to the database by using the {@link #reset()} method.\n */\npublic interface ORecord extends ORecordElement, OIdentifiable, Serializable, OSerializableStream {\n /** \n * Removes all the dependencies with other records. All the relationships remain in form of RecordID. If some links contain dirty records, the detach cannot be complete and this method returns false.\n * @return True if the document has been successfully detached, otherwise false.\n */\n boolean detach();\n /** \n * Resets the record to be reused. The record is fresh like just created. Use this method to recycle records avoiding the creation of them stressing the JVM Garbage Collector.\n * @return The Object instance itself giving a \"fluent interface\". Useful to call multiple methodsin chain.\n */\n <RET extends ORecord>RET reset();\n /** \n * Unloads current record. All information are lost but the record identity. At the next access the record will be auto-reloaded. Useful to free memory or to avoid to keep an old version of it.\n * @return The Object instance itself giving a \"fluent interface\". Useful to call multiple methodsin chain.\n */\n <RET extends ORecord>RET unload();\n /** \n * All the fields are deleted but the record identity is maintained. Use this to remove all the document's fields.\n * @return The Object instance itself giving a \"fluent interface\". Useful to call multiple methodsin chain.\n */\n <RET extends ORecord>RET clear();\n /** \n * Creates a copy of the record. All the record contents are copied.\n * @return The Object instance itself giving a \"fluent interface\". Useful to call multiple methodsin chain.\n */\n <RET extends ORecord>RET copy();\n /** \n * Returns the record identity as <cluster-id>:<cluster-position> \n */\n ORID getIdentity();\n /** \n * Returns the current version number of the record. When the record is created has version = 0. At every change the storage increment the version number. Version number is used by Optimistic transactions to check if the record is changed in the meanwhile of the transaction.\n * @see OTransactionOptimistic\n * @return The version number. 0 if it's a brand new record.\n */\n int getVersion();\n /** \n * Returns the database where the record belongs.\n * @return\n */\n ODatabaseDocument getDatabase();\n /** \n * Checks if the record is dirty, namely if it was changed in memory.\n * @return True if dirty, otherwise false\n */\n boolean isDirty();\n /** \n * Loads the record content in memory. If the record is in cache will be returned a new instance, so pay attention to use the returned. If the record is dirty, then it returns to the original content. If the record does not exist a ORecordNotFoundException exception is thrown.\n * @return The record loaded or itself if the record has been reloaded from the storage. Useful tocall methods in chain.\n */\n <RET extends ORecord>RET load() throws ORecordNotFoundException ;\n /** \n * Loads the record content in memory. No cache is used. If the record is dirty, then it returns to the original content. If the record does not exist a ORecordNotFoundException exception is thrown.\n * @return The Object instance itself giving a \"fluent interface\". Useful to call multiple methodsin chain.\n */\n <RET extends ORecord>RET reload() throws ORecordNotFoundException ;\n <RET extends ORecord>RET reload( final String fetchPlan, final boolean ignoreCache, boolean force) throws ORecordNotFoundException ;\n /** \n * Saves in-memory changes to the database. Behavior depends by the current running transaction if any. If no transaction is running then changes apply immediately. If an Optimistic transaction is running then the record will be changed at commit time. The current transaction will continue to see the record as modified, while others not. If a Pessimistic transaction is running, then an exclusive lock is acquired against the record. Current transaction will continue to see the record as modified, while others cannot access to it since it's locked.\n * @return The Object instance itself giving a \"fluent interface\". Useful to call multiple methodsin chain.\n */\n <RET extends ORecord>RET save();\n /** \n * Saves in-memory changes to the database defining a specific cluster where to save it. Behavior depends by the current running transaction if any. If no transaction is running then changes apply immediately. If an Optimistic transaction is running then the record will be changed at commit time. The current transaction will continue to see the record as modified, while others not. If a Pessimistic transaction is running, then an exclusive lock is acquired against the record. Current transaction will continue to see the record as modified, while others cannot access to it since it's locked.\n * @return The Object instance itself giving a \"fluent interface\". Useful to call multiple methodsin chain.\n */\n <RET extends ORecord>RET save( String iCluster);\n <RET extends ORecord>RET save( boolean forceCreate);\n <RET extends ORecord>RET save( String iCluster, boolean forceCreate);\n /** \n * Deletes the record from the database. Behavior depends by the current running transaction if any. If no transaction is running then the record is deleted immediately. If an Optimistic transaction is running then the record will be deleted at commit time. The current transaction will continue to see the record as deleted, while others not. If a Pessimistic transaction is running, then an exclusive lock is acquired against the record. Current transaction will continue to see the record as deleted, while others cannot access to it since it's locked.\n * @return The Object instance itself giving a \"fluent interface\". Useful to call multiple methodsin chain.\n */\n <RET extends ORecord>RET delete();\n /** \n * Fills the record parsing the content in JSON format.\n * @param iJson Object content in JSON format\n * @return The Object instance itself giving a \"fluent interface\". Useful to call multiple methodsin chain.\n */\n <RET extends ORecord>RET fromJSON( String iJson);\n /** \n * Exports the record in JSON format.\n * @return Object content in JSON format\n */\n String toJSON();\n /** \n * Exports the record in JSON format specifying additional formatting settings.\n * @param iFormat Format settings separated by comma. Available settings are:<ul> <li><b>rid</b>: exports the record's id as property \"@rid\" <li><b>version</b>: exports the record's version as property \"@version\" <li><b>class</b>: exports the record's class as property \"@class\" <li><b>attribSameRow</b>: exports all the record attributes in the same row <li><b>indent:<level></b>: Indents the output if the <level> specified. Default is 0 </ul> Example: \"rid,version,class,indent:6\" exports record id, version and class properties along with record properties using an indenting level equals of 6.\n * @return Object content in JSON format\n */\n String toJSON( String iFormat);\n /** \n * Returns the size in bytes of the record. The size can be computed only for not new records.\n * @return the size in bytes\n */\n int getSize();\n /** \n * Returns the current status of the record.\n * @return Current status as value between the defined values in the enum {@link STATUS}\n */\n STATUS getInternalStatus();\n /** \n * Changes the current internal status.\n * @param iStatus status between the values defined in the enum {@link STATUS}\n */\n void setInternalStatus( STATUS iStatus);\n}\n", "raw_body_no_cmt": "public interface ORecord extends ORecordElement, OIdentifiable, Serializable, OSerializableStream {\n boolean detach();\n <RET extends ORecord>RET reset();\n <RET extends ORecord>RET unload();\n <RET extends ORecord>RET clear();\n <RET extends ORecord>RET copy();\n ORID getIdentity();\n int getVersion();\n ODatabaseDocument getDatabase();\n boolean isDirty();\n <RET extends ORecord>RET load() throws ORecordNotFoundException ;\n <RET extends ORecord>RET reload() throws ORecordNotFoundException ;\n <RET extends ORecord>RET reload( final String fetchPlan, final boolean ignoreCache, boolean force) throws ORecordNotFoundException ;\n <RET extends ORecord>RET save();\n <RET extends ORecord>RET save( String iCluster);\n <RET extends ORecord>RET save( boolean forceCreate);\n <RET extends ORecord>RET save( String iCluster, boolean forceCreate);\n <RET extends ORecord>RET delete();\n <RET extends ORecord>RET fromJSON( String iJson);\n String toJSON();\n String toJSON( String iFormat);\n int getSize();\n STATUS getInternalStatus();\n void setInternalStatus( STATUS iStatus);\n}\n"}}, {"OChannelDataInput": {"retrieved_name": "OChannelDataInput", "raw_body": "/** \n * Created by luigidellaquila on 12/12/16. \n */\npublic interface OChannelDataInput {\n byte readByte() throws IOException ;\n boolean readBoolean() throws IOException ;\n int readInt() throws IOException ;\n long readLong() throws IOException ;\n short readShort() throws IOException ;\n String readString() throws IOException ;\n byte[] readBytes() throws IOException ;\n ORecordId readRID() throws IOException ;\n int readVersion() throws IOException ;\n InputStream getDataInput();\n}\n", "raw_body_no_cmt": "public interface OChannelDataInput {\n byte readByte() throws IOException ;\n boolean readBoolean() throws IOException ;\n int readInt() throws IOException ;\n long readLong() throws IOException ;\n short readShort() throws IOException ;\n String readString() throws IOException ;\n byte[] readBytes() throws IOException ;\n ORecordId readRID() throws IOException ;\n int readVersion() throws IOException ;\n InputStream getDataInput();\n}\n"}}, {"ORawBuffer": {"retrieved_name": "ORawBuffer", "raw_body": "public class ORawBuffer extends OBuffer {\n public int version;\n public byte recordType;\n /** \n * Constructor used by serialization. \n */\n public ORawBuffer();\n public ORawBuffer( final byte[] buffer, final int version, final byte recordType);\n /** \n * Creates a new object by the record received. \n */\n public ORawBuffer( final ORecord iRecord);\n @Override public void readExternal( final ObjectInput iInput) throws IOException, ClassNotFoundException;\n @Override public void writeExternal( final ObjectOutput iOutput) throws IOException;\n @Override public boolean equals( final Object o);\n @Override public int hashCode();\n}\n", "raw_body_no_cmt": "public class ORawBuffer extends OBuffer {\n public int version;\n public byte recordType;\n public ORawBuffer();\n public ORawBuffer( final byte[] buffer, final int version, final byte recordType);\n public ORawBuffer( final ORecord iRecord);\n public void readExternal( final ObjectInput iInput) throws IOException, ClassNotFoundException;\n public void writeExternal( final ObjectOutput iOutput) throws IOException;\n public boolean equals( final Object o);\n public int hashCode();\n}\n"}}, {"OStorageRemoteSession": {"retrieved_name": "OStorageRemoteSession", "raw_body": "/** \n * Created by tglman on 31/03/16. \n */\npublic class OStorageRemoteSession {\n public boolean commandExecuting=false;\n protected int serverURLIndex=-1;\n protected String connectionUserName=null;\n protected String connectionUserPassword=null;\n protected Map<String,OStorageRemoteNodeSession> sessions=new HashMap<String,OStorageRemoteNodeSession>();\n private Set<OChannelBinary> connections=Collections.newSetFromMap(new WeakHashMap<OChannelBinary,Boolean>());\n private final int uniqueClientSessionId;\n private boolean closed=true;\n /** \n * Make the retry to happen only on the current session, if the current session is invalid or the server is offline it kill the operation. <p>this is for avoid to send to the server wrong request expecting a specific state that is not there anymore.\n */\n private int stickToSession=0;\n protected String currentUrl;\n public OStorageRemoteSession( final int sessionId);\n public boolean hasConnection( final OChannelBinary connection);\n public OStorageRemoteNodeSession getServerSession( final String serverURL);\n public synchronized OStorageRemoteNodeSession getOrCreateServerSession( final String serverURL);\n public void addConnection( final OChannelBinary connection);\n public void close();\n public boolean isClosed();\n public Integer getSessionId();\n public String getServerUrl();\n public synchronized void removeServerSession( final String serverURL);\n public synchronized Collection<OStorageRemoteNodeSession> getAllServerSessions();\n public void stickToSession();\n public void unStickToSession();\n public boolean isStickToSession();\n public void closeAllSessions( ORemoteConnectionManager connectionManager, OContextConfiguration clientConfiguration);\n public String getDebugLastHost();\n public String getCurrentUrl();\n}\n", "raw_body_no_cmt": "public class OStorageRemoteSession {\n public boolean commandExecuting=false;\n protected int serverURLIndex=-1;\n protected String connectionUserName=null;\n protected String connectionUserPassword=null;\n protected Map<String,OStorageRemoteNodeSession> sessions=new HashMap<String,OStorageRemoteNodeSession>();\n private Set<OChannelBinary> connections=Collections.newSetFromMap(new WeakHashMap<OChannelBinary,Boolean>());\n private final int uniqueClientSessionId;\n private boolean closed=true;\n private int stickToSession=0;\n protected String currentUrl;\n public OStorageRemoteSession( final int sessionId);\n public boolean hasConnection( final OChannelBinary connection);\n public OStorageRemoteNodeSession getServerSession( final String serverURL);\n public synchronized OStorageRemoteNodeSession getOrCreateServerSession( final String serverURL);\n public void addConnection( final OChannelBinary connection);\n public void close();\n public boolean isClosed();\n public Integer getSessionId();\n public String getServerUrl();\n public synchronized void removeServerSession( final String serverURL);\n public synchronized Collection<OStorageRemoteNodeSession> getAllServerSessions();\n public void stickToSession();\n public void unStickToSession();\n public boolean isStickToSession();\n public void closeAllSessions( ORemoteConnectionManager connectionManager, OContextConfiguration clientConfiguration);\n public String getDebugLastHost();\n public String getCurrentUrl();\n}\n"}}, {"Set<ORecord>": {"retrieved_name": "ORecordElement", "raw_body": "/** \n * Base interface that represents a record element.\n * @author Luca Garulli (l.garulli--(at)--orientdb.com)\n */\npublic interface ORecordElement {\n /** \n * Available record statuses. \n */\n enum STATUS { NOT_LOADED, LOADED, MARSHALLING, UNMARSHALLING}\n /** \n * Marks the instance as dirty. The dirty status could be propagated up if the implementation supports ownership concept.\n * @return The object it self. Useful to call methods in chain.\n */\n <RET>RET setDirty();\n void setDirtyNoChanged();\n /** \n * @return Returns record element which contains given one. \n */\n ORecordElement getOwner();\n}\n", "raw_body_no_cmt": "public interface ORecordElement {\n enum STATUS { NOT_LOADED, LOADED, MARSHALLING, UNMARSHALLING}\n <RET>RET setDirty();\n void setDirtyNoChanged();\n ORecordElement getOwner();\n}\n"}}] | [{"add": {"retrieved_name": "add", "raw_body": "@Override public boolean add(OIdentifiable e){\n preAdd(e);\n lazyLoad(true);\n return super.add(e);\n}\n"}}, {"readRecord": {"retrieved_name": "readRecord", "raw_body": "@Override public ORawBuffer readRecord(final long clusterPosition,final boolean prefetchRecords) throws IOException {\n return readRecord(clusterPosition);\n}\n"}}, {"readByte": {"retrieved_name": "readByte", "raw_body": "private byte readByte(final BytesContainer container){\n return container.bytes[container.offset++];\n}\n"}}, {"readBytes": {"retrieved_name": "readBytes", "raw_body": "public byte[] readBytes() throws IOException {\n if (debug) OLogManager.instance().info(this,\"%s - Reading chunk of bytes. Reading chunk length as int (4 bytes)...\",socket.getRemoteSocketAddress());\n final int len=in.readInt();\n if (len > maxChunkSize) {\n throw new IOException(\"Impossible to read a chunk of length:\" + len + \" max allowed chunk length:\"+ maxChunkSize+ \" see NETWORK_BINARY_MAX_CONTENT_LENGTH settings \");\n }\n updateMetricReceivedBytes(OBinaryProtocol.SIZE_INT + len);\n if (debug) OLogManager.instance().info(this,\"%s - Read chunk length: %d\",socket.getRemoteSocketAddress(),len);\n if (len < 0) return null;\n if (debug) OLogManager.instance().info(this,\"%s - Reading %d bytes...\",socket.getRemoteSocketAddress(),len);\n final byte[] tmp=new byte[len];\n in.readFully(tmp);\n if (debug) OLogManager.instance().info(this,\"%s - Read %d bytes: %s\",socket.getRemoteSocketAddress(),len,new String(tmp));\n return tmp;\n}\n"}}, {"readVersion": {"retrieved_name": "readVersion", "raw_body": "public int readVersion() throws IOException {\n return readInt();\n}\n"}}] | [{"read": {"retrieved_name": "read", "raw_body": "@Override public void read(OChannelDataInput network,OStorageRemoteSession session) throws IOException {\n response.read(network,session);\n}\n"}}] |
|
Pay-Group_best-pay-sdk | best-pay-sdk/src/main/java/com/lly835/bestpay/config/WxPayConfig.java | WxPayConfig | initSSLContext | class WxPayConfig extends PayConfig {
/**
* 公众号appId
*/
private String appId;
/**
* 公众号appSecret
*/
private String appSecret;
/**
* 小程序appId
*/
private String miniAppId;
/**
* app应用appid
*/
private String appAppId;
/**
* 商户号
*/
private String mchId;
/**
* 商户密钥
*/
private String mchKey;
/**
* 商户证书路径
*/
private String keyPath;
/**
* 证书内容
*/
private SSLContext sslContext;
/**
* 初始化证书
* @return
*/
public SSLContext initSSLContext() {<FILL_FUNCTION_BODY>}
} |
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(new File(this.keyPath));
} catch (IOException e) {
throw new RuntimeException("读取微信商户证书文件出错", e);
}
try {
KeyStore keystore = KeyStore.getInstance("PKCS12");
char[] partnerId2charArray = mchId.toCharArray();
keystore.load(inputStream, partnerId2charArray);
this.sslContext = SSLContexts.custom().loadKeyMaterial(keystore, partnerId2charArray).build();
return this.sslContext;
} catch (Exception e) {
throw new RuntimeException("证书文件有问题,请核实!", e);
} finally {
IOUtils.closeQuietly(inputStream);
}
| class PayConfig {
/**
* 支付完成后的异步通知地址.
*/
private String notifyUrl;
/**
* 支付完成后的同步返回地址.
*/
private String returnUrl;
/**
* 默认非沙箱测试
*/
private boolean sandbox=false;
public boolean isSandbox();
public void setSandbox( boolean sandbox);
public String getNotifyUrl();
public void setNotifyUrl( String notifyUrl);
public String getReturnUrl();
public void setReturnUrl( String returnUrl);
public void check();
}
|
try {
if (sslContext == null) {
sslContext = new SSLContextBuilder().loadTrustMaterial(new File(keyPath), null).build();
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return sslContext;
| [
"SSLContext",
"Exception"
] | [
"loadTrustMaterial",
"build"
] | [
"FileInputStream",
"Exception",
"SSLContext",
"KeyStore"
] | [
"toCharArray",
"loadKeyMaterial",
"load",
"build",
"custom",
"getInstance",
"closeQuietly"
] | {
"methods": [
"loadTrustMaterial",
"build"
],
"similar_methods": [
"initSSLContext"
],
"types": [
"SSLContext",
"Exception"
]
} | /**
* Created by this on 2019/9/8 16:31
*/
@Data public class AliPayConfig extends PayConfig {
/**
* appId
*/
private String appId;
/**
* 商户私钥
*/
private String privateKey;
/**
* 支付宝公钥
*/
private String aliPayPublicKey;
public void check();
}
/**
* Created by null on 2017/2/23.
*/
public class BestPayException extends RuntimeException {
private Integer code;
public BestPayException( BestPayResultEnum resultEnum);
public Integer getCode();
}
public static String getSignCheckContentV1(Map<String,String> params){
if (params == null) {
return null;
}
params.remove("sign");
params.remove("sign_type");
StringBuffer content=new StringBuffer();
List<String> keys=new ArrayList<String>(params.keySet());
Collections.sort(keys);
for (int i=0; i < keys.size(); i++) {
String key=keys.get(i);
String value=params.get(key);
content.append((i == 0 ? "" : "&") + key + "="+ value);
}
return content.toString();
}
public static String buildQuery(Map<String,String> params,String charset) throws IOException {
if (params != null && !params.isEmpty()) {
StringBuilder query=new StringBuilder();
Set<Map.Entry<String,String>> entries=params.entrySet();
boolean hasParam=false;
Iterator var5=entries.iterator();
while (var5.hasNext()) {
Map.Entry<String,String> entry=(Map.Entry)var5.next();
String name=entry.getKey();
String value=entry.getValue();
if (StringUtil.areNotEmpty(new String[]{name,value})) {
if (hasParam) {
query.append("&");
}
else {
hasParam=true;
}
query.append(name).append("=").append(URLEncoder.encode(value,charset));
}
}
return query.toString();
}
else {
return null;
}
}
public void setSandbox(boolean sandbox){
this.sandbox=sandbox;
}
| public class AliPayConfig extends PayConfig {
private String appId;
private String privateKey;
private String aliPayPublicKey;
public void check();
}
public class BestPayException extends RuntimeException {
private Integer code;
public BestPayException( BestPayResultEnum resultEnum);
public Integer getCode();
}
public static String getSignCheckContentV1(Map<String,String> params){
if (params == null) {
return null;
}
params.remove("sign");
params.remove("sign_type");
StringBuffer content=new StringBuffer();
List<String> keys=new ArrayList<String>(params.keySet());
Collections.sort(keys);
for (int i=0; i < keys.size(); i++) {
String key=keys.get(i);
String value=params.get(key);
content.append((i == 0 ? "" : "&") + key + "="+ value);
}
return content.toString();
}
public static String buildQuery(Map<String,String> params,String charset) throws IOException {
if (params != null && !params.isEmpty()) {
StringBuilder query=new StringBuilder();
Set<Map.Entry<String,String>> entries=params.entrySet();
boolean hasParam=false;
Iterator var5=entries.iterator();
while (var5.hasNext()) {
Map.Entry<String,String> entry=(Map.Entry)var5.next();
String name=entry.getKey();
String value=entry.getValue();
if (StringUtil.areNotEmpty(new String[]{name,value})) {
if (hasParam) {
query.append("&");
}
else {
hasParam=true;
}
query.append(name).append("=").append(URLEncoder.encode(value,charset));
}
}
return query.toString();
}
else {
return null;
}
}
public void setSandbox(boolean sandbox){
this.sandbox=sandbox;
}
| {"types": [{"SSLContext": "AliPayConfig"}, {"Exception": "BestPayException"}], "methods": [{"loadTrustMaterial": "getSignCheckContentV1"}, {"build": "buildQuery"}], "similar_methods": [{"initSSLContext": "setSandbox"}]} | [{"SSLContext": {"retrieved_name": "AliPayConfig", "raw_body": "/** \n * Created by this on 2019/9/8 16:31\n */\n@Data public class AliPayConfig extends PayConfig {\n /** \n * appId\n */\n private String appId;\n /** \n * \u5546\u6237\u79c1\u94a5\n */\n private String privateKey;\n /** \n * \u652f\u4ed8\u5b9d\u516c\u94a5\n */\n private String aliPayPublicKey;\n public void check();\n}\n", "raw_body_no_cmt": "public class AliPayConfig extends PayConfig {\n private String appId;\n private String privateKey;\n private String aliPayPublicKey;\n public void check();\n}\n"}}, {"Exception": {"retrieved_name": "BestPayException", "raw_body": "/** \n * Created by null on 2017/2/23.\n */\npublic class BestPayException extends RuntimeException {\n private Integer code;\n public BestPayException( BestPayResultEnum resultEnum);\n public Integer getCode();\n}\n", "raw_body_no_cmt": "public class BestPayException extends RuntimeException {\n private Integer code;\n public BestPayException( BestPayResultEnum resultEnum);\n public Integer getCode();\n}\n"}}] | [{"loadTrustMaterial": {"retrieved_name": "getSignCheckContentV1", "raw_body": "public static String getSignCheckContentV1(Map<String,String> params){\n if (params == null) {\n return null;\n }\n params.remove(\"sign\");\n params.remove(\"sign_type\");\n StringBuffer content=new StringBuffer();\n List<String> keys=new ArrayList<String>(params.keySet());\n Collections.sort(keys);\n for (int i=0; i < keys.size(); i++) {\n String key=keys.get(i);\n String value=params.get(key);\n content.append((i == 0 ? \"\" : \"&\") + key + \"=\"+ value);\n }\n return content.toString();\n}\n"}}, {"build": {"retrieved_name": "buildQuery", "raw_body": "public static String buildQuery(Map<String,String> params,String charset) throws IOException {\n if (params != null && !params.isEmpty()) {\n StringBuilder query=new StringBuilder();\n Set<Map.Entry<String,String>> entries=params.entrySet();\n boolean hasParam=false;\n Iterator var5=entries.iterator();\n while (var5.hasNext()) {\n Map.Entry<String,String> entry=(Map.Entry)var5.next();\n String name=entry.getKey();\n String value=entry.getValue();\n if (StringUtil.areNotEmpty(new String[]{name,value})) {\n if (hasParam) {\n query.append(\"&\");\n }\n else {\n hasParam=true;\n }\n query.append(name).append(\"=\").append(URLEncoder.encode(value,charset));\n }\n }\n return query.toString();\n }\n else {\n return null;\n }\n}\n"}}] | [{"initSSLContext": {"retrieved_name": "setSandbox", "raw_body": "public void setSandbox(boolean sandbox){\n this.sandbox=sandbox;\n}\n"}}] |
graphhopper_graphhopper | graphhopper/core/src/main/java/com/graphhopper/routing/AbstractRoutingAlgorithm.java | AbstractRoutingAlgorithm | accept | class AbstractRoutingAlgorithm implements RoutingAlgorithm {
protected final Graph graph;
protected final Weighting weighting;
protected final TraversalMode traversalMode;
protected final NodeAccess nodeAccess;
protected final EdgeExplorer edgeExplorer;
protected int maxVisitedNodes = Integer.MAX_VALUE;
protected long timeoutMillis = Long.MAX_VALUE;
private long finishTimeMillis = Long.MAX_VALUE;
private boolean alreadyRun;
/**
* @param graph specifies the graph where this algorithm will run on
* @param weighting set the used weight calculation (e.g. fastest, shortest).
* @param traversalMode how the graph is traversed e.g. if via nodes or edges.
*/
public AbstractRoutingAlgorithm(Graph graph, Weighting weighting, TraversalMode traversalMode) {
if (weighting.hasTurnCosts() && !traversalMode.isEdgeBased())
throw new IllegalStateException("Weightings supporting turn costs cannot be used with node-based traversal mode");
this.weighting = weighting;
this.traversalMode = traversalMode;
this.graph = graph;
this.nodeAccess = graph.getNodeAccess();
edgeExplorer = graph.createEdgeExplorer();
}
@Override
public void setMaxVisitedNodes(int numberOfNodes) {
this.maxVisitedNodes = numberOfNodes;
}
@Override
public void setTimeoutMillis(long timeoutMillis) {
this.timeoutMillis = timeoutMillis;
}
protected boolean accept(EdgeIteratorState iter, int prevOrNextEdgeId) {<FILL_FUNCTION_BODY>}
protected void checkAlreadyRun() {
if (alreadyRun)
throw new IllegalStateException("Create a new instance per call");
alreadyRun = true;
}
protected void setupFinishTime() {
try {
this.finishTimeMillis = Math.addExact(System.currentTimeMillis(), timeoutMillis);
} catch (ArithmeticException e) {
this.finishTimeMillis = Long.MAX_VALUE;
}
}
@Override
public List<Path> calcPaths(int from, int to) {
return Collections.singletonList(calcPath(from, to));
}
protected Path createEmptyPath() {
return new Path(graph);
}
@Override
public String getName() {
return getClass().getSimpleName();
}
@Override
public String toString() {
return getName() + "|" + weighting;
}
protected boolean isMaxVisitedNodesExceeded() {
return maxVisitedNodes < getVisitedNodes();
}
protected boolean isTimeoutExceeded() {
return finishTimeMillis < Long.MAX_VALUE && System.currentTimeMillis() > finishTimeMillis;
}
} |
// for edge-based traversal we leave it for TurnWeighting to decide whether or not a u-turn is acceptable,
// but for node-based traversal we exclude such a turn for performance reasons already here
return traversalMode.isEdgeBased() || iter.getEdge() != prevOrNextEdgeId;
|
return true;
| [
"EdgeIteratorState"
] | [] | [
"EdgeIteratorState",
"TraversalMode"
] | [
"isEdgeBased",
"getEdge"
] | {
"methods": [],
"similar_methods": [
"accept"
],
"types": [
"EdgeIteratorState"
]
} | /**
* This interface represents an edge and is one possible state of an EdgeIterator. Example: <span> EdgeExplorer expl = graph.createEdgeExplorer(); EdgeIterator iter = expl.setBaseNode(baseNode); while(iter.next()) { iter.getBaseBase() // equals to the specified baseNode } </span>
* @author Peter Karich
* @see EdgeIterator
* @see EdgeExplorer
*/
public interface EdgeIteratorState {
BooleanEncodedValue UNFAVORED_EDGE=new SimpleBooleanEncodedValue("unfavored");
/**
* This method can be used to fetch the internal reverse state of an edge.
*/
BooleanEncodedValue REVERSE_STATE=new BooleanEncodedValue(){
@Override public int init( InitializerConfig init);
@Override public String getName();
@Override public boolean getBool( boolean reverse, int edgeId, EdgeIntAccess edgeIntAccess);
@Override public void setBool( boolean reverse, int edgeId, EdgeIntAccess edgeIntAccess, boolean value);
@Override public boolean isStoreTwoDirections();
}
;
/**
* @return the edge id of the current edge. Do not make any assumptions about the concretevalues, except that for an implementation it is recommended that they'll be contiguous.
*/
int getEdge();
/**
* Returns the edge key of the current edge. The edge id can be derived from the edge key by calling {@link GHUtility#getEdgeFromEdgeKey(int)}, but the edge key also contains information about the direction of the edge. The edge key is even when the edge is oriented in storage direction and odd otherwise. You can use the edge key to retrieve an edge state in the associated direction using {@link Graph#getEdgeIteratorStateForKey(int)}.
*/
int getEdgeKey();
/**
* Like #getEdgeKey, but returns the reverse key.
*/
int getReverseEdgeKey();
/**
* Returns the node used to instantiate the EdgeIterator. Often only used for convenience reasons. Do not confuse this with a <i>source node</i> of a directed edge.
* @return the requested node itself
* @see EdgeIterator
*/
int getBaseNode();
/**
* @return the adjacent node of baseNode for the current edge.
* @see EdgeIterator
*/
int getAdjNode();
/**
* For road network data like OSM a way is often not just a straight line. The nodes between the junction nodes are called pillar nodes. The junction nodes are called tower nodes and used for routing. The pillar nodes are necessary to have an exact geometry. See the docs for more information (docs/core/low-level-api.md#what-are-pillar-and-tower-nodes). Updates to the returned list are not reflected in the graph, for that you've to use setWayGeometry.
* @param mode {@link FetchMode}
* @return the pillar and/or tower nodes depending on the mode.
*/
PointList fetchWayGeometry( FetchMode mode);
/**
* @param list is a sorted collection of coordinates between the base node and the current adjacent node. Specifythe list without the adjacent and base node. This method can be called multiple times, but if the distance changes, the setDistance method is not called automatically.
*/
EdgeIteratorState setWayGeometry( PointList list);
/**
* @return the distance of the current edge in meter
*/
double getDistance();
EdgeIteratorState setDistance( double dist);
/**
* Returns edge properties stored in direction of the raw database layout. So do not use it directly, instead use the appropriate set/get methods with its EncodedValue object.
*/
IntsRef getFlags();
/**
* Stores the specified edgeFlags down to the DataAccess
*/
EdgeIteratorState setFlags( IntsRef edgeFlags);
boolean get( BooleanEncodedValue property);
EdgeIteratorState set( BooleanEncodedValue property, boolean value);
boolean getReverse( BooleanEncodedValue property);
EdgeIteratorState setReverse( BooleanEncodedValue property, boolean value);
EdgeIteratorState set( BooleanEncodedValue property, boolean fwd, boolean bwd);
int get( IntEncodedValue property);
EdgeIteratorState set( IntEncodedValue property, int value);
int getReverse( IntEncodedValue property);
EdgeIteratorState setReverse( IntEncodedValue property, int value);
EdgeIteratorState set( IntEncodedValue property, int fwd, int bwd);
double get( DecimalEncodedValue property);
EdgeIteratorState set( DecimalEncodedValue property, double value);
double getReverse( DecimalEncodedValue property);
EdgeIteratorState setReverse( DecimalEncodedValue property, double value);
EdgeIteratorState set( DecimalEncodedValue property, double fwd, double bwd);
<T extends Enum<?>>T get( EnumEncodedValue<T> property);
<T extends Enum<?>>EdgeIteratorState set( EnumEncodedValue<T> property, T value);
<T extends Enum<?>>T getReverse( EnumEncodedValue<T> property);
<T extends Enum<?>>EdgeIteratorState setReverse( EnumEncodedValue<T> property, T value);
<T extends Enum<?>>EdgeIteratorState set( EnumEncodedValue<T> property, T fwd, T bwd);
String get( StringEncodedValue property);
EdgeIteratorState set( StringEncodedValue property, String value);
String getReverse( StringEncodedValue property);
EdgeIteratorState setReverse( StringEncodedValue property, String value);
EdgeIteratorState set( StringEncodedValue property, String fwd, String bwd);
/**
* Identical to calling getKeyValues().get("name") if name is stored for both directions. Note that for backward compatibility this method returns an empty String instead of null if there was no KeyPair with key==name stored.
* @return the stored value for the key "name" in the KeyValue list of this EdgeIteratorState.
*/
String getName();
/**
* This stores the specified key-value pairs in the storage of this EdgeIteratorState. This is more flexible compared to the mechanism of flags and EncodedValue and allows storing sparse key value pairs more efficient. But it might be slow and more inefficient on retrieval. Call this setKeyValues method only once per EdgeIteratorState as it allocates new space everytime this method is called.
*/
EdgeIteratorState setKeyValues( List<KVStorage.KeyValue> map);
/**
* This method returns KeyValue pairs for both directions in contrast to {@link #getValue(String)}.
* @see #setKeyValues(List)
*/
List<KVStorage.KeyValue> getKeyValues();
/**
* This method returns the *first* value for the specified key and only if stored for the direction of this EdgeIteratorState. If you need more than one value see also {@link #getKeyValues()}. Avoid storing KeyPairs with duplicate keys as only the first will be reachable with this method. Currently, there is no support to use this method in a custom_model, and you should use EncodedValues instead.
*/
Object getValue( String key);
/**
* Clones this EdgeIteratorState.
* @param reverse if true a detached edgeState with reversed properties is created where baseand adjacent nodes, flags and wayGeometry are in reversed order. See #162 for more details about why we need the reverse parameter.
*/
EdgeIteratorState detach( boolean reverse);
/**
* Copies the properties of the specified edge into this edge. Does not change nodes!
* @return the specified edge e
*/
EdgeIteratorState copyPropertiesFrom( EdgeIteratorState e);
}
@Test public void accept(){
EdgeFilter trueFilter=edgeState -> true;
EncodingManager em=new EncodingManager.Builder().add(RoadClass.create()).add(RoadEnvironment.create()).build();
EnumEncodedValue<RoadClass> rcEnc=em.getEnumEncodedValue(RoadClass.KEY,RoadClass.class);
EnumEncodedValue<RoadEnvironment> reEnc=em.getEnumEncodedValue(RoadEnvironment.KEY,RoadEnvironment.class);
SnapPreventionEdgeFilter filter=new SnapPreventionEdgeFilter(trueFilter,rcEnc,reEnc,Arrays.asList("motorway","ferry"));
BaseGraph graph=new BaseGraph.Builder(em).create();
EdgeIteratorState edge=graph.edge(0,1).setDistance(1);
assertTrue(filter.accept(edge));
edge.set(reEnc,RoadEnvironment.FERRY);
assertFalse(filter.accept(edge));
edge.set(reEnc,RoadEnvironment.FORD);
assertTrue(filter.accept(edge));
edge.set(rcEnc,RoadClass.RESIDENTIAL);
assertTrue(filter.accept(edge));
edge.set(rcEnc,RoadClass.MOTORWAY);
assertFalse(filter.accept(edge));
}
| public interface EdgeIteratorState {
BooleanEncodedValue UNFAVORED_EDGE=new SimpleBooleanEncodedValue("unfavored");
BooleanEncodedValue REVERSE_STATE=new BooleanEncodedValue(){
public int init( InitializerConfig init);
public String getName();
public boolean getBool( boolean reverse, int edgeId, EdgeIntAccess edgeIntAccess);
public void setBool( boolean reverse, int edgeId, EdgeIntAccess edgeIntAccess, boolean value);
public boolean isStoreTwoDirections();
}
;
int getEdge();
int getEdgeKey();
int getReverseEdgeKey();
int getBaseNode();
int getAdjNode();
PointList fetchWayGeometry( FetchMode mode);
EdgeIteratorState setWayGeometry( PointList list);
double getDistance();
EdgeIteratorState setDistance( double dist);
IntsRef getFlags();
EdgeIteratorState setFlags( IntsRef edgeFlags);
boolean get( BooleanEncodedValue property);
EdgeIteratorState set( BooleanEncodedValue property, boolean value);
boolean getReverse( BooleanEncodedValue property);
EdgeIteratorState setReverse( BooleanEncodedValue property, boolean value);
EdgeIteratorState set( BooleanEncodedValue property, boolean fwd, boolean bwd);
int get( IntEncodedValue property);
EdgeIteratorState set( IntEncodedValue property, int value);
int getReverse( IntEncodedValue property);
EdgeIteratorState setReverse( IntEncodedValue property, int value);
EdgeIteratorState set( IntEncodedValue property, int fwd, int bwd);
double get( DecimalEncodedValue property);
EdgeIteratorState set( DecimalEncodedValue property, double value);
double getReverse( DecimalEncodedValue property);
EdgeIteratorState setReverse( DecimalEncodedValue property, double value);
EdgeIteratorState set( DecimalEncodedValue property, double fwd, double bwd);
<T extends Enum<?>>T get( EnumEncodedValue<T> property);
<T extends Enum<?>>EdgeIteratorState set( EnumEncodedValue<T> property, T value);
<T extends Enum<?>>T getReverse( EnumEncodedValue<T> property);
<T extends Enum<?>>EdgeIteratorState setReverse( EnumEncodedValue<T> property, T value);
<T extends Enum<?>>EdgeIteratorState set( EnumEncodedValue<T> property, T fwd, T bwd);
String get( StringEncodedValue property);
EdgeIteratorState set( StringEncodedValue property, String value);
String getReverse( StringEncodedValue property);
EdgeIteratorState setReverse( StringEncodedValue property, String value);
EdgeIteratorState set( StringEncodedValue property, String fwd, String bwd);
String getName();
EdgeIteratorState setKeyValues( List<KVStorage.KeyValue> map);
List<KVStorage.KeyValue> getKeyValues();
Object getValue( String key);
EdgeIteratorState detach( boolean reverse);
EdgeIteratorState copyPropertiesFrom( EdgeIteratorState e);
}
@Test public void accept(){
EdgeFilter trueFilter=edgeState -> true;
EncodingManager em=new EncodingManager.Builder().add(RoadClass.create()).add(RoadEnvironment.create()).build();
EnumEncodedValue<RoadClass> rcEnc=em.getEnumEncodedValue(RoadClass.KEY,RoadClass.class);
EnumEncodedValue<RoadEnvironment> reEnc=em.getEnumEncodedValue(RoadEnvironment.KEY,RoadEnvironment.class);
SnapPreventionEdgeFilter filter=new SnapPreventionEdgeFilter(trueFilter,rcEnc,reEnc,Arrays.asList("motorway","ferry"));
BaseGraph graph=new BaseGraph.Builder(em).create();
EdgeIteratorState edge=graph.edge(0,1).setDistance(1);
assertTrue(filter.accept(edge));
edge.set(reEnc,RoadEnvironment.FERRY);
assertFalse(filter.accept(edge));
edge.set(reEnc,RoadEnvironment.FORD);
assertTrue(filter.accept(edge));
edge.set(rcEnc,RoadClass.RESIDENTIAL);
assertTrue(filter.accept(edge));
edge.set(rcEnc,RoadClass.MOTORWAY);
assertFalse(filter.accept(edge));
}
| {"types": [{"EdgeIteratorState": "EdgeIteratorState"}], "similar_methods": [{"accept": "accept"}]} | [{"EdgeIteratorState": {"retrieved_name": "EdgeIteratorState", "raw_body": "/** \n * This interface represents an edge and is one possible state of an EdgeIterator. Example: <span> EdgeExplorer expl = graph.createEdgeExplorer(); EdgeIterator iter = expl.setBaseNode(baseNode); while(iter.next()) { iter.getBaseBase() // equals to the specified baseNode } </span>\n * @author Peter Karich\n * @see EdgeIterator\n * @see EdgeExplorer\n */\npublic interface EdgeIteratorState {\n BooleanEncodedValue UNFAVORED_EDGE=new SimpleBooleanEncodedValue(\"unfavored\");\n /** \n * This method can be used to fetch the internal reverse state of an edge.\n */\n BooleanEncodedValue REVERSE_STATE=new BooleanEncodedValue(){\n @Override public int init( InitializerConfig init);\n @Override public String getName();\n @Override public boolean getBool( boolean reverse, int edgeId, EdgeIntAccess edgeIntAccess);\n @Override public void setBool( boolean reverse, int edgeId, EdgeIntAccess edgeIntAccess, boolean value);\n @Override public boolean isStoreTwoDirections();\n }\n;\n /** \n * @return the edge id of the current edge. Do not make any assumptions about the concretevalues, except that for an implementation it is recommended that they'll be contiguous.\n */\n int getEdge();\n /** \n * Returns the edge key of the current edge. The edge id can be derived from the edge key by calling {@link GHUtility#getEdgeFromEdgeKey(int)}, but the edge key also contains information about the direction of the edge. The edge key is even when the edge is oriented in storage direction and odd otherwise. You can use the edge key to retrieve an edge state in the associated direction using {@link Graph#getEdgeIteratorStateForKey(int)}.\n */\n int getEdgeKey();\n /** \n * Like #getEdgeKey, but returns the reverse key.\n */\n int getReverseEdgeKey();\n /** \n * Returns the node used to instantiate the EdgeIterator. Often only used for convenience reasons. Do not confuse this with a <i>source node</i> of a directed edge.\n * @return the requested node itself\n * @see EdgeIterator\n */\n int getBaseNode();\n /** \n * @return the adjacent node of baseNode for the current edge.\n * @see EdgeIterator\n */\n int getAdjNode();\n /** \n * For road network data like OSM a way is often not just a straight line. The nodes between the junction nodes are called pillar nodes. The junction nodes are called tower nodes and used for routing. The pillar nodes are necessary to have an exact geometry. See the docs for more information (docs/core/low-level-api.md#what-are-pillar-and-tower-nodes). Updates to the returned list are not reflected in the graph, for that you've to use setWayGeometry.\n * @param mode {@link FetchMode}\n * @return the pillar and/or tower nodes depending on the mode.\n */\n PointList fetchWayGeometry( FetchMode mode);\n /** \n * @param list is a sorted collection of coordinates between the base node and the current adjacent node. Specifythe list without the adjacent and base node. This method can be called multiple times, but if the distance changes, the setDistance method is not called automatically.\n */\n EdgeIteratorState setWayGeometry( PointList list);\n /** \n * @return the distance of the current edge in meter\n */\n double getDistance();\n EdgeIteratorState setDistance( double dist);\n /** \n * Returns edge properties stored in direction of the raw database layout. So do not use it directly, instead use the appropriate set/get methods with its EncodedValue object.\n */\n IntsRef getFlags();\n /** \n * Stores the specified edgeFlags down to the DataAccess\n */\n EdgeIteratorState setFlags( IntsRef edgeFlags);\n boolean get( BooleanEncodedValue property);\n EdgeIteratorState set( BooleanEncodedValue property, boolean value);\n boolean getReverse( BooleanEncodedValue property);\n EdgeIteratorState setReverse( BooleanEncodedValue property, boolean value);\n EdgeIteratorState set( BooleanEncodedValue property, boolean fwd, boolean bwd);\n int get( IntEncodedValue property);\n EdgeIteratorState set( IntEncodedValue property, int value);\n int getReverse( IntEncodedValue property);\n EdgeIteratorState setReverse( IntEncodedValue property, int value);\n EdgeIteratorState set( IntEncodedValue property, int fwd, int bwd);\n double get( DecimalEncodedValue property);\n EdgeIteratorState set( DecimalEncodedValue property, double value);\n double getReverse( DecimalEncodedValue property);\n EdgeIteratorState setReverse( DecimalEncodedValue property, double value);\n EdgeIteratorState set( DecimalEncodedValue property, double fwd, double bwd);\n <T extends Enum<?>>T get( EnumEncodedValue<T> property);\n <T extends Enum<?>>EdgeIteratorState set( EnumEncodedValue<T> property, T value);\n <T extends Enum<?>>T getReverse( EnumEncodedValue<T> property);\n <T extends Enum<?>>EdgeIteratorState setReverse( EnumEncodedValue<T> property, T value);\n <T extends Enum<?>>EdgeIteratorState set( EnumEncodedValue<T> property, T fwd, T bwd);\n String get( StringEncodedValue property);\n EdgeIteratorState set( StringEncodedValue property, String value);\n String getReverse( StringEncodedValue property);\n EdgeIteratorState setReverse( StringEncodedValue property, String value);\n EdgeIteratorState set( StringEncodedValue property, String fwd, String bwd);\n /** \n * Identical to calling getKeyValues().get(\"name\") if name is stored for both directions. Note that for backward compatibility this method returns an empty String instead of null if there was no KeyPair with key==name stored.\n * @return the stored value for the key \"name\" in the KeyValue list of this EdgeIteratorState.\n */\n String getName();\n /** \n * This stores the specified key-value pairs in the storage of this EdgeIteratorState. This is more flexible compared to the mechanism of flags and EncodedValue and allows storing sparse key value pairs more efficient. But it might be slow and more inefficient on retrieval. Call this setKeyValues method only once per EdgeIteratorState as it allocates new space everytime this method is called.\n */\n EdgeIteratorState setKeyValues( List<KVStorage.KeyValue> map);\n /** \n * This method returns KeyValue pairs for both directions in contrast to {@link #getValue(String)}.\n * @see #setKeyValues(List)\n */\n List<KVStorage.KeyValue> getKeyValues();\n /** \n * This method returns the *first* value for the specified key and only if stored for the direction of this EdgeIteratorState. If you need more than one value see also {@link #getKeyValues()}. Avoid storing KeyPairs with duplicate keys as only the first will be reachable with this method. Currently, there is no support to use this method in a custom_model, and you should use EncodedValues instead.\n */\n Object getValue( String key);\n /** \n * Clones this EdgeIteratorState.\n * @param reverse if true a detached edgeState with reversed properties is created where baseand adjacent nodes, flags and wayGeometry are in reversed order. See #162 for more details about why we need the reverse parameter.\n */\n EdgeIteratorState detach( boolean reverse);\n /** \n * Copies the properties of the specified edge into this edge. Does not change nodes!\n * @return the specified edge e\n */\n EdgeIteratorState copyPropertiesFrom( EdgeIteratorState e);\n}\n", "raw_body_no_cmt": "public interface EdgeIteratorState {\n BooleanEncodedValue UNFAVORED_EDGE=new SimpleBooleanEncodedValue(\"unfavored\");\n BooleanEncodedValue REVERSE_STATE=new BooleanEncodedValue(){\n public int init( InitializerConfig init);\n public String getName();\n public boolean getBool( boolean reverse, int edgeId, EdgeIntAccess edgeIntAccess);\n public void setBool( boolean reverse, int edgeId, EdgeIntAccess edgeIntAccess, boolean value);\n public boolean isStoreTwoDirections();\n }\n;\n int getEdge();\n int getEdgeKey();\n int getReverseEdgeKey();\n int getBaseNode();\n int getAdjNode();\n PointList fetchWayGeometry( FetchMode mode);\n EdgeIteratorState setWayGeometry( PointList list);\n double getDistance();\n EdgeIteratorState setDistance( double dist);\n IntsRef getFlags();\n EdgeIteratorState setFlags( IntsRef edgeFlags);\n boolean get( BooleanEncodedValue property);\n EdgeIteratorState set( BooleanEncodedValue property, boolean value);\n boolean getReverse( BooleanEncodedValue property);\n EdgeIteratorState setReverse( BooleanEncodedValue property, boolean value);\n EdgeIteratorState set( BooleanEncodedValue property, boolean fwd, boolean bwd);\n int get( IntEncodedValue property);\n EdgeIteratorState set( IntEncodedValue property, int value);\n int getReverse( IntEncodedValue property);\n EdgeIteratorState setReverse( IntEncodedValue property, int value);\n EdgeIteratorState set( IntEncodedValue property, int fwd, int bwd);\n double get( DecimalEncodedValue property);\n EdgeIteratorState set( DecimalEncodedValue property, double value);\n double getReverse( DecimalEncodedValue property);\n EdgeIteratorState setReverse( DecimalEncodedValue property, double value);\n EdgeIteratorState set( DecimalEncodedValue property, double fwd, double bwd);\n <T extends Enum<?>>T get( EnumEncodedValue<T> property);\n <T extends Enum<?>>EdgeIteratorState set( EnumEncodedValue<T> property, T value);\n <T extends Enum<?>>T getReverse( EnumEncodedValue<T> property);\n <T extends Enum<?>>EdgeIteratorState setReverse( EnumEncodedValue<T> property, T value);\n <T extends Enum<?>>EdgeIteratorState set( EnumEncodedValue<T> property, T fwd, T bwd);\n String get( StringEncodedValue property);\n EdgeIteratorState set( StringEncodedValue property, String value);\n String getReverse( StringEncodedValue property);\n EdgeIteratorState setReverse( StringEncodedValue property, String value);\n EdgeIteratorState set( StringEncodedValue property, String fwd, String bwd);\n String getName();\n EdgeIteratorState setKeyValues( List<KVStorage.KeyValue> map);\n List<KVStorage.KeyValue> getKeyValues();\n Object getValue( String key);\n EdgeIteratorState detach( boolean reverse);\n EdgeIteratorState copyPropertiesFrom( EdgeIteratorState e);\n}\n"}}] | [] | [{"accept": {"retrieved_name": "accept", "raw_body": "@Test public void accept(){\n EdgeFilter trueFilter=edgeState -> true;\n EncodingManager em=new EncodingManager.Builder().add(RoadClass.create()).add(RoadEnvironment.create()).build();\n EnumEncodedValue<RoadClass> rcEnc=em.getEnumEncodedValue(RoadClass.KEY,RoadClass.class);\n EnumEncodedValue<RoadEnvironment> reEnc=em.getEnumEncodedValue(RoadEnvironment.KEY,RoadEnvironment.class);\n SnapPreventionEdgeFilter filter=new SnapPreventionEdgeFilter(trueFilter,rcEnc,reEnc,Arrays.asList(\"motorway\",\"ferry\"));\n BaseGraph graph=new BaseGraph.Builder(em).create();\n EdgeIteratorState edge=graph.edge(0,1).setDistance(1);\n assertTrue(filter.accept(edge));\n edge.set(reEnc,RoadEnvironment.FERRY);\n assertFalse(filter.accept(edge));\n edge.set(reEnc,RoadEnvironment.FORD);\n assertTrue(filter.accept(edge));\n edge.set(rcEnc,RoadClass.RESIDENTIAL);\n assertTrue(filter.accept(edge));\n edge.set(rcEnc,RoadClass.MOTORWAY);\n assertFalse(filter.accept(edge));\n}\n"}}] |
|
PlayEdu_PlayEdu | PlayEdu/playedu-course/src/main/java/xyz/playedu/course/domain/CourseCategory.java | CourseCategory | equals | class CourseCategory implements Serializable {
/** */
@JsonProperty("course_id")
private Integer courseId;
/** */
@JsonProperty("category_id")
private Integer categoryId;
@TableField(exist = false)
private static final long serialVersionUID = 1L;
@Override
public boolean equals(Object that) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((getCourseId() == null) ? 0 : getCourseId().hashCode());
result = prime * result + ((getCategoryId() == null) ? 0 : getCategoryId().hashCode());
return result;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", courseId=").append(courseId);
sb.append(", categoryId=").append(categoryId);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} |
if (this == that) {
return true;
}
if (that == null) {
return false;
}
if (getClass() != that.getClass()) {
return false;
}
CourseCategory other = (CourseCategory) that;
return (this.getCourseId() == null
? other.getCourseId() == null
: this.getCourseId().equals(other.getCourseId()))
&& (this.getCategoryId() == null
? other.getCategoryId() == null
: this.getCategoryId().equals(other.getCategoryId()));
|
if (this == that) {
return true;
}
if (that == null) {
return false;
}
if (getClass() != that.getClass()) {
return false;
}
CourseCategory other = (CourseCategory) that;
return (this.getCourseId() == null ? other.getCourseId() == null : this.getCourseId().equals(other.getCourseId()))
&& (this.getCategoryId() == null ? other.getCategoryId() == null : this.getCategoryId().equals(other.getCategoryId()));
| [
"CourseCategory"
] | [
"getCategoryId",
"getCourseId",
"equals",
"getClass"
] | [
"CourseCategory"
] | [
"getClass",
"equals",
"getCourseId",
"getCategoryId"
] | {
"methods": [
"getCategoryId",
"getCourseId",
"equals",
"getClass"
],
"similar_methods": [
"equals"
],
"types": [
"CourseCategory"
]
} | /**
* @author tengteng
* @description 针对表【resource_course_category】的数据库操作Service
* @createDate 2023-03-09 09:54:22
*/
public interface CourseCategoryService extends IService<CourseCategory> {
List<Integer> getCourseIdsByCategoryIds( List<Integer> categoryIds);
void removeByCourseId( Integer id);
void removeByCategoryId( Integer id);
List<Integer> getCategoryIdsByCourseId( Integer courseId);
List<Integer> getCourseIdsByCategoryId( Integer id);
}
Map<Integer,List<Integer>> getCategoryIdsGroup(List<Integer> courseIds);
List<Integer> getRidsByCourseId(Integer courseId);
@Override public boolean equals(Object that){
if (this == that) {
return true;
}
if (that == null) {
return false;
}
if (getClass() != that.getClass()) {
return false;
}
CourseAttachment other=(CourseAttachment)that;
return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId())) && (this.getCourseId() == null ? other.getCourseId() == null : this.getCourseId().equals(other.getCourseId())) && (this.getSort() == null ? other.getSort() == null : this.getSort().equals(other.getSort()))&& (this.getTitle() == null ? other.getTitle() == null : this.getTitle().equals(other.getTitle()))&& (this.getExt() == null ? other.getExt() == null : this.getExt().equals(other.getExt()))&& (this.getType() == null ? other.getType() == null : this.getType().equals(other.getType()))&& (this.getRid() == null ? other.getRid() == null : this.getRid().equals(other.getRid()))&& (this.getUrl() == null ? other.getUrl() == null : this.getUrl().equals(other.getUrl()))&& (this.getCreatedAt() == null ? other.getCreatedAt() == null : this.getCreatedAt().equals(other.getCreatedAt()));
}
public Long get(Integer userId){
return (Long)RedisUtil.hGet(groupName,userId + "");
}
@Override public boolean equals(Object that){
if (this == that) {
return true;
}
if (that == null) {
return false;
}
if (getClass() != that.getClass()) {
return false;
}
CourseAttachment other=(CourseAttachment)that;
return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId())) && (this.getCourseId() == null ? other.getCourseId() == null : this.getCourseId().equals(other.getCourseId())) && (this.getSort() == null ? other.getSort() == null : this.getSort().equals(other.getSort()))&& (this.getTitle() == null ? other.getTitle() == null : this.getTitle().equals(other.getTitle()))&& (this.getExt() == null ? other.getExt() == null : this.getExt().equals(other.getExt()))&& (this.getType() == null ? other.getType() == null : this.getType().equals(other.getType()))&& (this.getRid() == null ? other.getRid() == null : this.getRid().equals(other.getRid()))&& (this.getUrl() == null ? other.getUrl() == null : this.getUrl().equals(other.getUrl()))&& (this.getCreatedAt() == null ? other.getCreatedAt() == null : this.getCreatedAt().equals(other.getCreatedAt()));
}
| public interface CourseCategoryService extends IService<CourseCategory> {
List<Integer> getCourseIdsByCategoryIds( List<Integer> categoryIds);
void removeByCourseId( Integer id);
void removeByCategoryId( Integer id);
List<Integer> getCategoryIdsByCourseId( Integer courseId);
List<Integer> getCourseIdsByCategoryId( Integer id);
}
Map<Integer,List<Integer>> getCategoryIdsGroup(List<Integer> courseIds);
List<Integer> getRidsByCourseId(Integer courseId);
@Override public boolean equals(Object that){
if (this == that) {
return true;
}
if (that == null) {
return false;
}
if (getClass() != that.getClass()) {
return false;
}
CourseAttachment other=(CourseAttachment)that;
return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId())) && (this.getCourseId() == null ? other.getCourseId() == null : this.getCourseId().equals(other.getCourseId())) && (this.getSort() == null ? other.getSort() == null : this.getSort().equals(other.getSort()))&& (this.getTitle() == null ? other.getTitle() == null : this.getTitle().equals(other.getTitle()))&& (this.getExt() == null ? other.getExt() == null : this.getExt().equals(other.getExt()))&& (this.getType() == null ? other.getType() == null : this.getType().equals(other.getType()))&& (this.getRid() == null ? other.getRid() == null : this.getRid().equals(other.getRid()))&& (this.getUrl() == null ? other.getUrl() == null : this.getUrl().equals(other.getUrl()))&& (this.getCreatedAt() == null ? other.getCreatedAt() == null : this.getCreatedAt().equals(other.getCreatedAt()));
}
public Long get(Integer userId){
return (Long)RedisUtil.hGet(groupName,userId + "");
}
@Override public boolean equals(Object that){
if (this == that) {
return true;
}
if (that == null) {
return false;
}
if (getClass() != that.getClass()) {
return false;
}
CourseAttachment other=(CourseAttachment)that;
return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId())) && (this.getCourseId() == null ? other.getCourseId() == null : this.getCourseId().equals(other.getCourseId())) && (this.getSort() == null ? other.getSort() == null : this.getSort().equals(other.getSort()))&& (this.getTitle() == null ? other.getTitle() == null : this.getTitle().equals(other.getTitle()))&& (this.getExt() == null ? other.getExt() == null : this.getExt().equals(other.getExt()))&& (this.getType() == null ? other.getType() == null : this.getType().equals(other.getType()))&& (this.getRid() == null ? other.getRid() == null : this.getRid().equals(other.getRid()))&& (this.getUrl() == null ? other.getUrl() == null : this.getUrl().equals(other.getUrl()))&& (this.getCreatedAt() == null ? other.getCreatedAt() == null : this.getCreatedAt().equals(other.getCreatedAt()));
}
| {"types": [{"CourseCategory": "CourseCategoryService"}], "methods": [{"getCategoryId": "getCategoryIdsGroup"}, {"getCourseId": "getRidsByCourseId"}, {"equals": "equals"}, {"getClass": "get"}], "similar_methods": [{"equals": "equals"}]} | [{"CourseCategory": {"retrieved_name": "CourseCategoryService", "raw_body": "/** \n * @author tengteng\n * @description \u9488\u5bf9\u8868\u3010resource_course_category\u3011\u7684\u6570\u636e\u5e93\u64cd\u4f5cService\n * @createDate 2023-03-09 09:54:22\n */\npublic interface CourseCategoryService extends IService<CourseCategory> {\n List<Integer> getCourseIdsByCategoryIds( List<Integer> categoryIds);\n void removeByCourseId( Integer id);\n void removeByCategoryId( Integer id);\n List<Integer> getCategoryIdsByCourseId( Integer courseId);\n List<Integer> getCourseIdsByCategoryId( Integer id);\n}\n", "raw_body_no_cmt": "public interface CourseCategoryService extends IService<CourseCategory> {\n List<Integer> getCourseIdsByCategoryIds( List<Integer> categoryIds);\n void removeByCourseId( Integer id);\n void removeByCategoryId( Integer id);\n List<Integer> getCategoryIdsByCourseId( Integer courseId);\n List<Integer> getCourseIdsByCategoryId( Integer id);\n}\n"}}] | [{"getCategoryId": {"retrieved_name": "getCategoryIdsGroup", "raw_body": "Map<Integer,List<Integer>> getCategoryIdsGroup(List<Integer> courseIds);\n"}}, {"getCourseId": {"retrieved_name": "getRidsByCourseId", "raw_body": "List<Integer> getRidsByCourseId(Integer courseId);\n"}}, {"equals": {"retrieved_name": "equals", "raw_body": "@Override public boolean equals(Object that){\n if (this == that) {\n return true;\n }\n if (that == null) {\n return false;\n }\n if (getClass() != that.getClass()) {\n return false;\n }\n CourseAttachment other=(CourseAttachment)that;\n return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId())) && (this.getCourseId() == null ? other.getCourseId() == null : this.getCourseId().equals(other.getCourseId())) && (this.getSort() == null ? other.getSort() == null : this.getSort().equals(other.getSort()))&& (this.getTitle() == null ? other.getTitle() == null : this.getTitle().equals(other.getTitle()))&& (this.getExt() == null ? other.getExt() == null : this.getExt().equals(other.getExt()))&& (this.getType() == null ? other.getType() == null : this.getType().equals(other.getType()))&& (this.getRid() == null ? other.getRid() == null : this.getRid().equals(other.getRid()))&& (this.getUrl() == null ? other.getUrl() == null : this.getUrl().equals(other.getUrl()))&& (this.getCreatedAt() == null ? other.getCreatedAt() == null : this.getCreatedAt().equals(other.getCreatedAt()));\n}\n"}}, {"getClass": {"retrieved_name": "get", "raw_body": "public Long get(Integer userId){\n return (Long)RedisUtil.hGet(groupName,userId + \"\");\n}\n"}}] | [{"equals": {"retrieved_name": "equals", "raw_body": "@Override public boolean equals(Object that){\n if (this == that) {\n return true;\n }\n if (that == null) {\n return false;\n }\n if (getClass() != that.getClass()) {\n return false;\n }\n CourseAttachment other=(CourseAttachment)that;\n return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId())) && (this.getCourseId() == null ? other.getCourseId() == null : this.getCourseId().equals(other.getCourseId())) && (this.getSort() == null ? other.getSort() == null : this.getSort().equals(other.getSort()))&& (this.getTitle() == null ? other.getTitle() == null : this.getTitle().equals(other.getTitle()))&& (this.getExt() == null ? other.getExt() == null : this.getExt().equals(other.getExt()))&& (this.getType() == null ? other.getType() == null : this.getType().equals(other.getType()))&& (this.getRid() == null ? other.getRid() == null : this.getRid().equals(other.getRid()))&& (this.getUrl() == null ? other.getUrl() == null : this.getUrl().equals(other.getUrl()))&& (this.getCreatedAt() == null ? other.getCreatedAt() == null : this.getCreatedAt().equals(other.getCreatedAt()));\n}\n"}}] |
|
orientechnologies_orientdb | orientdb/graphdb/src/main/java/com/tinkerpop/blueprints/impls/orient/OrientTransactionalGraph.java | OrientTransactionalGraph | autoStartTransaction | class OrientTransactionalGraph extends OrientBaseGraph
implements TransactionalGraph {
/**
* Constructs a new object using an existent database instance.
*
* @param iDatabase Underlying database object to attach
*/
protected OrientTransactionalGraph(final ODatabaseDocumentInternal iDatabase) {
this(iDatabase, true, null, null);
}
protected OrientTransactionalGraph(
final ODatabaseDocumentInternal iDatabase,
final String iUserName,
final String iUserPasswd,
final Settings iConfiguration) {
super(iDatabase, iUserName, iUserPasswd, iConfiguration);
setCurrentGraphInThreadLocal();
super.setAutoStartTx(isAutoStartTx());
if (isAutoStartTx()) ensureTransaction();
}
protected OrientTransactionalGraph(
final ODatabaseDocumentInternal iDatabase,
final boolean iAutoStartTx,
final String iUserName,
final String iUserPasswd) {
super(iDatabase, iUserName, iUserPasswd, null);
setCurrentGraphInThreadLocal();
super.setAutoStartTx(iAutoStartTx);
if (iAutoStartTx) ensureTransaction();
}
protected OrientTransactionalGraph(final OPartitionedDatabasePool pool) {
super(pool);
setCurrentGraphInThreadLocal();
ensureTransaction();
}
protected OrientTransactionalGraph(
final OPartitionedDatabasePool pool, final Settings configuration) {
super(pool, configuration);
setCurrentGraphInThreadLocal();
if (configuration.isAutoStartTx()) ensureTransaction();
}
protected OrientTransactionalGraph(final String url) {
this(url, true);
}
protected OrientTransactionalGraph(final String url, final boolean iAutoStartTx) {
super(url, ADMIN, ADMIN);
setCurrentGraphInThreadLocal();
setAutoStartTx(iAutoStartTx);
if (iAutoStartTx) ensureTransaction();
}
protected OrientTransactionalGraph(
final String url, final String username, final String password) {
this(url, username, password, true);
}
protected OrientTransactionalGraph(
final String url, final String username, final String password, final boolean iAutoStartTx) {
super(url, username, password);
setCurrentGraphInThreadLocal();
this.setAutoStartTx(iAutoStartTx);
if (iAutoStartTx) ensureTransaction();
}
protected OrientTransactionalGraph(final Configuration configuration) {
super(configuration);
final Boolean autoStartTx = configuration.getBoolean("blueprints.orientdb.autoStartTx", null);
if (autoStartTx != null) setAutoStartTx(autoStartTx);
}
public boolean isUseLog() {
makeActive();
return settings.isUseLog();
}
public OrientTransactionalGraph setUseLog(final boolean useLog) {
makeActive();
settings.setUseLog(useLog);
return this;
}
@Override
public void setAutoStartTx(boolean autoStartTx) {
makeActive();
final boolean showWarning;
if (!autoStartTx
&& isAutoStartTx()
&& getDatabase() != null
&& getDatabase().getTransaction().isActive()) {
if (getDatabase().getTransaction().getEntryCount() == 0) {
getDatabase().getTransaction().rollback();
showWarning = false;
} else showWarning = true;
} else showWarning = false;
super.setAutoStartTx(autoStartTx);
if (showWarning)
OLogManager.instance()
.warn(
this,
"Auto Transaction for graphs setting has been turned off, but a transaction was"
+ " already started. Commit it manually or consider disabling auto transactions"
+ " while creating the graph.");
}
/**
* Closes a transaction.
*
* @param conclusion Can be SUCCESS for commit and FAILURE to rollback.
*/
@SuppressWarnings("deprecation")
@Override
public void stopTransaction(final Conclusion conclusion) {
makeActive();
if (getDatabase().isClosed()
|| getDatabase().getTransaction() instanceof OTransactionNoTx
|| getDatabase().getTransaction().getStatus() != TXSTATUS.BEGUN) return;
if (Conclusion.SUCCESS == conclusion) commit();
else rollback();
}
/** Commits the current active transaction. */
public void commit() {
makeActive();
if (getDatabase() == null) return;
getDatabase().commit();
if (isAutoStartTx()) ensureTransaction();
}
/** Rollbacks the current active transaction. All the pending changes are rollbacked. */
public void rollback() {
makeActive();
if (getDatabase() == null) return;
getDatabase().rollback();
if (isAutoStartTx()) ensureTransaction();
}
@Override
public void begin() {
makeActive();
// XXX: Under some circumstances, auto started transactions are committed outside of the graph
// using the
// underlying database and later restarted using the graph. So we have to check the status of
// the
// database transaction to support this behaviour.
if (isAutoStartTx() && getDatabase().getTransaction().isActive())
throw new OTransactionException(
"A mixture of auto started and manually started transactions is not allowed. "
+ "Disable auto transactions for the graph before starting a manual transaction.");
getDatabase().begin();
getDatabase().getTransaction().setUsingLog(settings.isUseLog());
}
@Override
protected void autoStartTransaction() {<FILL_FUNCTION_BODY>}
private void ensureTransaction() {
final boolean txBegun = getDatabase().getTransaction().isActive();
if (!txBegun) {
getDatabase().begin();
getDatabase().getTransaction().setUsingLog(settings.isUseLog());
}
}
} |
final boolean txBegun = getDatabase().getTransaction().isActive();
if (!isAutoStartTx()) {
if (isRequireTransaction() && !txBegun)
throw new OTransactionException("Transaction required to change the Graph");
return;
}
if (!txBegun) {
getDatabase().begin();
getDatabase().getTransaction().setUsingLog(settings.isUseLog());
}
| /**
* A Blueprints implementation of the graph database OrientDB (http://orientdb.com)
* @author Luca Garulli (l.garulli--(at)--orientdb.com) (http://orientdb.com)
*/
public abstract class OrientBaseGraph extends OrientConfigurableGraph implements OrientExtendedGraph, OStorageRecoverListener {
public static final String CONNECTION_OUT="out";
public static final String CONNECTION_IN="in";
public static final String CLASS_PREFIX="class:";
public static final String CLUSTER_PREFIX="cluster:";
public static final String ADMIN="admin";
private static volatile ThreadLocal<OrientBaseGraph> activeGraph=new ThreadLocal<OrientBaseGraph>();
private static volatile ThreadLocal<Deque<OrientBaseGraph>> initializationStack=new InitializationStackThreadLocal();
private Map<String,Object> properties;
static {
Orient.instance().registerListener(new OOrientListenerAbstract(){
@Override public void onStartup();
@Override public void onShutdown();
}
);
}
private final OPartitionedDatabasePool pool;
protected ODatabaseDocumentInternal database;
private String url;
private String username;
private String password;
/**
* Constructs a new object using an existent database instance.
* @param iDatabase Underlying database object to attach
*/
public OrientBaseGraph( final ODatabaseDocumentInternal iDatabase, final String iUserName, final String iUserPassword, final Settings iConfiguration);
public OrientBaseGraph( final OPartitionedDatabasePool pool);
public OrientBaseGraph( final OPartitionedDatabasePool pool, final Settings iConfiguration);
public OrientBaseGraph( final String url);
public OrientBaseGraph( final String url, final String username, final String password);
/**
* Builds a OrientGraph instance passing a configuration. Supported configuration settings are: <table> <tr> <td><b>Name</b></td> <td><b>Description</b></td> <td><b>Default value</b></td> </tr> <tr> <td>blueprints.orientdb.url</td> <td>Database URL</td> <td>-</td> </tr> <tr> <td>blueprints.orientdb.username</td> <td>User name</td> <td>admin</td> </tr> <tr> <td>blueprints.orientdb.password</td> <td>User password</td> <td>admin</td> </tr> <tr> <td>blueprints.orientdb.saveOriginalIds</td> <td>Saves the original element IDs by using the property origId. This could be useful on import of graph to preserve original ids</td> <td>false</td> </tr> <tr> <td>blueprints.orientdb.keepInMemoryReferences</td> <td>Avoid to keep records in memory but only RIDs</td> <td>false</td> </tr> <tr> <td>blueprints.orientdb.useCustomClassesForEdges</td> <td>Use Edge's label as OrientDB class. If doesn't exist create it under the hood</td> <td>true</td> </tr> <tr> <td>blueprints.orientdb.useCustomClassesForVertex</td> <td>Use Vertex's label as OrientDB class. If doesn't exist create it under the hood</td> <td>true</td> </tr> <tr> <td>blueprints.orientdb.useVertexFieldsForEdgeLabels</td> <td>Store the edge relationships in vertex by using the Edge's class. This allow to use multiple fields and make faster traversal by edge's label (class)</td> <td>true</td> </tr> <tr> <td>blueprints.orientdb.lightweightEdges</td> <td>Uses lightweight edges. This avoid to create a physical document per edge. Documents are created only when they have properties</td> <td>true</td> </tr> <tr> <td>blueprints.orientdb.autoScaleEdgeType</td> <td>Set auto scale of edge type. True means one edge is managed as LINK, 2 or more are managed with a LINKBAG</td> <td>false</td> </tr> <tr> <td>blueprints.orientdb.edgeContainerEmbedded2TreeThreshold</td> <td>Changes the minimum number of edges for edge containers to transform the underlying structure from embedded to tree. Use -1 to disable transformation</td> <td>-1</td> </tr> <tr> <td>blueprints.orientdb.edgeContainerTree2EmbeddedThreshold</td> <td>Changes the minimum number of edges for edge containers to transform the underlying structure from tree to embedded. Use -1 to disable transformation</td> <td>-1</td> </tr> </table>
* @param configuration of graph
*/
public OrientBaseGraph( final Configuration configuration);
abstract OrientEdge addEdgeInternal( OrientVertex currentVertex, String label, OrientVertex inVertex, String iClassName, String iClusterName, Object... fields);
abstract void removeEdgesInternal( final OrientVertex vertex, final ODocument iVertex, final OIdentifiable iVertexToRemove, final boolean iAlsoInverse, final boolean useVertexFieldsForEdgeLabels, final boolean autoScaleEdgeType);
abstract void removeEdgeInternal( OrientEdge currentVertex);
public static OrientBaseGraph getActiveGraph();
/**
* Internal use only.
*/
public static void clearInitStack();
@Override public void onStorageRecover();
/**
* (Internal)
*/
public static void encodeClassNames( final String... iLabels);
/**
* (Internal) Returns the case sensitive edge class names.
*/
public static void getEdgeClassNames( final OrientBaseGraph graph, final String... iLabels);
/**
* (Internal)
*/
public static String encodeClassName( String iClassName);
/**
* (Internal)
*/
public static String decodeClassName( String iClassName);
public void makeActive();
/**
* (Blueprints Extension) Configure the Graph instance.
* @param iSetting Settings object containing all the settings
*/
public OrientBaseGraph configure( final Settings iSetting);
/**
* (Blueprints Extension) Drops the database
*/
public void drop();
@SuppressWarnings({"unchecked","rawtypes"}) public <T extends Element>Index<T> createIndex( final String indexName, final Class<T> indexClass, final Parameter... indexParameters);
/**
* Returns an index by name and class
* @param indexName Index name
* @param indexClass Class as one or subclass of Vertex.class and Edge.class
* @return Index instance
*/
@SuppressWarnings("unchecked") @Override public <T extends Element>Index<T> getIndex( final String indexName, final Class<T> indexClass);
/**
* Returns all the indices.
* @return Iterable of Index instances
*/
public Iterable<Index<? extends Element>> getIndices();
/**
* Drops an index by name.
* @param indexName Index name
*/
public void dropIndex( final String indexName);
/**
* Creates a new unconnected vertex with no fields in the Graph.
* @param id Optional, can contains the Vertex's class name by prefixing with "class:"
* @return The new OrientVertex created
*/
@Override public OrientVertex addVertex( final Object id);
public ORecordConflictStrategy getConflictStrategy();
public OrientBaseGraph setConflictStrategy( final String iStrategyName);
public OrientBaseGraph setConflictStrategy( final ORecordConflictStrategy iResolver);
/**
* (Blueprints Extension) Creates a new unconnected vertex in the Graph setting the initial field values.
* @param id Optional, can contains the Vertex's class name by prefixing with "class:"
* @param prop Fields must be a odd pairs of key/value or a single object as Map containingentries as key/value pairs
* @return The new OrientVertex created
*/
public OrientVertex addVertex( Object id, final Object... prop);
/**
* (Blueprints Extension) Creates a new unconnected vertex with no fields of specific class in a cluster in the Graph.
* @param iClassName Vertex class name
* @param iClusterName Vertex cluster name
* @return New vertex created
*/
public OrientVertex addVertex( final String iClassName, final String iClusterName);
/**
* (Blueprints Extension) Creates a temporary vertex setting the initial field values. The vertex is not saved and the transaction is not started.
* @param iClassName Vertex's class name
* @param prop Fields must be a odd pairs of key/value or a single object as Map containingentries as key/value pairs
* @return added vertex
*/
public OrientVertex addTemporaryVertex( final String iClassName, final Object... prop);
/**
* Creates an edge between a source Vertex and a destination Vertex setting label as Edge's label.
* @param id Optional, can contains the Edge's class name by prefixing with "class:"
* @param outVertex Source vertex
* @param inVertex Destination vertex
* @param label Edge's label
*/
@Override public OrientEdge addEdge( final Object id, Vertex outVertex, Vertex inVertex, final String label);
/**
* Returns a vertex by an ID.
* @param id Can by a String, ODocument or an OIdentifiable object.
*/
public OrientVertex getVertex( final Object id);
/**
* Removes a vertex from the Graph. All the edges connected to the Vertex are automatically removed.
* @param vertex Vertex to remove
*/
public void removeVertex( final Vertex vertex);
/**
* Get all the Vertices in Graph.
* @return Vertices as Iterable
*/
public Iterable<Vertex> getVertices();
/**
* Get all the Vertices in Graph specifying if consider or not sub-classes of V.
* @param iPolymorphic If true then get all the vertices of any sub-class
* @return Vertices as Iterable
*/
public Iterable<Vertex> getVertices( final boolean iPolymorphic);
/**
* Get all the Vertices in Graph of a specific vertex class and all sub-classes.
* @param iClassName Vertex class name to filter
* @return Vertices as Iterable
*/
public Iterable<Vertex> getVerticesOfClass( final String iClassName);
/**
* Get all the Vertices in Graph of a specific vertex class and all sub-classes only if iPolymorphic is true.
* @param iClassName Vertex class name to filter
* @param iPolymorphic If true consider also Vertex iClassName sub-classes
* @return Vertices as Iterable
*/
public Iterable<Vertex> getVerticesOfClass( final String iClassName, final boolean iPolymorphic);
/**
* Get all the Vertices in Graph filtering by field name and value. Example:<code> Iterable<Vertex> resultset = getVertices("name", "Jay"); </code>
* @param iKey Field name
* @param iValue Field value
* @return Vertices as Iterable
*/
public Iterable<Vertex> getVertices( final String iKey, Object iValue);
/**
* Lookup for a vertex by id using an index.<br> This API relies on Unique index (SBTREE/HASH) but is deprecated.<br> Example:<code> Vertex v = getVertexByKey("V.name", "name", "Jay"); </code>
* @param iKey Name of the indexed property
* @param iValue Field value
* @return Vertex instance if found, otherwise null
* @see #getVertices(String,Object)
*/
@Deprecated public Vertex getVertexByKey( final String iKey, Object iValue);
/**
* Get all the Vertices in Graph filtering by field name and value. Example:<code> Iterable<Vertex> resultset = getVertices("Person",new String[] {"name","surname"},new Object[] { "Sherlock" ,"Holmes"}); </code>
* @param iKey Fields name
* @param iValue Fields value
* @return Vertices as Iterable
*/
public Iterable<Vertex> getVertices( final String label, final String[] iKey, Object[] iValue);
/**
* Returns all the edges in Graph.
* @return Edges as Iterable
*/
public Iterable<Edge> getEdges();
/**
* Get all the Edges in Graph specifying if consider or not sub-classes of E.
* @param iPolymorphic If true then get all the edge of any sub-class
* @return Edges as Iterable
*/
public Iterable<Edge> getEdges( final boolean iPolymorphic);
/**
* Get all the Edges in Graph of a specific edge class and all sub-classes.
* @param iClassName Edge class name to filter
* @return Edges as Iterable
*/
public Iterable<Edge> getEdgesOfClass( final String iClassName);
/**
* Get all the Edges in Graph of a specific edges class and all sub-classes only if iPolymorphic is true.
* @param iClassName Edge class name to filter
* @param iPolymorphic If true consider also iClassName Edge sub-classes
* @return Edges as Iterable
*/
public Iterable<Edge> getEdgesOfClass( final String iClassName, final boolean iPolymorphic);
/**
* Get all the Edges in Graph filtering by field name and value. Example:<code> Iterable<Edges> resultset = getEdges("name", "Jay"); </code>
* @param iKey Field name
* @param value Field value
* @return Edges as Iterable
*/
public Iterable<Edge> getEdges( final String iKey, Object value);
/**
* Returns a edge by an ID.
* @param id Can by a String, ODocument or an OIdentifiable object.
*/
public OrientEdge getEdge( final Object id);
/**
* Removes an edge from the Graph.
* @param edge Edge to remove
*/
public void removeEdge( final Edge edge);
/**
* Reuses the underlying database avoiding to create and open it every time.
* @param iDatabase Underlying database object
*/
public OrientBaseGraph reuse( final ODatabaseDocumentInternal iDatabase);
/**
* Checks if the Graph has been closed.
* @return True if it is closed, otherwise false
*/
public boolean isClosed();
/**
* Closes the Graph. After closing the Graph cannot be used.
*/
public void shutdown();
/**
* Closes the Graph. After closing the Graph cannot be used.
*/
public void shutdown( boolean closeDb);
/**
* Closes the Graph. After closing the Graph cannot be used.
*/
public void shutdown( boolean closeDb, boolean commitTx);
/**
* Returns the Graph URL.
*/
public String toString();
/**
* Returns the underlying Database instance as ODatabaseDocumentTx instance.
*/
public ODatabaseDocument getRawGraph();
/**
* begins current transaction (if the graph is transactional)
*/
public void begin();
/**
* Commits the current active transaction.
*/
public void commit();
/**
* Rollbacks the current active transaction. All the pending changes are rollbacked.
*/
public void rollback();
/**
* Returns the V persistent class as OrientVertexType instance.
*/
public OrientVertexType getVertexBaseType();
/**
* Returns the persistent class for type iTypeName as OrientVertexType instance.
* @param iTypeName Vertex class name
*/
public OrientVertexType getVertexType( final String iTypeName);
/**
* Creates a new Vertex persistent class.
* @param iClassName Vertex class name
* @return OrientVertexType instance representing the persistent class
*/
public OrientVertexType createVertexType( final String iClassName);
/**
* Creates a new Vertex persistent class.
* @param iClassName Vertex class name
* @param clusters The number of clusters to create for the new class. By default theMINIMUMCLUSTERS database setting is used. In v2.2 and later, the number of clusters are proportioned to the amount of cores found on the machine
* @return OrientVertexType instance representing the persistent class
*/
public OrientVertexType createVertexType( final String iClassName, final int clusters);
/**
* Creates a new Vertex persistent class specifying the super class.
* @param iClassName Vertex class name
* @param iSuperClassName Vertex class name to extend
* @return OrientVertexType instance representing the persistent class
*/
public OrientVertexType createVertexType( final String iClassName, final String iSuperClassName);
/**
* Creates a new Vertex persistent class specifying the super class.
* @param iClassName Vertex class name
* @param iSuperClassName Vertex class name to extend
* @param clusters The number of clusters to create for the new class. By default theMINIMUMCLUSTERS database setting is used. In v2.2 and later, the number of clusters are proportioned to the amount of cores found on the machine
* @return OrientVertexType instance representing the persistent class
*/
public OrientVertexType createVertexType( final String iClassName, final String iSuperClassName, final int clusters);
/**
* Creates a new Vertex persistent class specifying the super class.
* @param iClassName Vertex class name
* @param iSuperClass OClass Vertex to extend
* @return OrientVertexType instance representing the persistent class
*/
public OrientVertexType createVertexType( final String iClassName, final OClass iSuperClass);
/**
* Creates a new Vertex persistent class specifying the super class.
* @param iClassName Vertex class name
* @param iSuperClass OClass Vertex to extend
* @return OrientVertexType instance representing the persistent class
*/
public OrientVertexType createVertexType( final String iClassName, final OClass iSuperClass, final int clusters);
/**
* Drop a vertex class.
* @param iTypeName Vertex class name
*/
public void dropVertexType( final String iTypeName);
/**
* Returns the E persistent class as OrientEdgeType instance.
*/
public OrientEdgeType getEdgeBaseType();
/**
* Returns the persistent class for type iTypeName as OrientEdgeType instance.
* @param iTypeName Edge class name
*/
public OrientEdgeType getEdgeType( final String iTypeName);
/**
* Creates a new Edge persistent class.
* @param iClassName Edge class name
* @return OrientEdgeType instance representing the persistent class
*/
public OrientEdgeType createEdgeType( final String iClassName);
/**
* Creates a new Edge persistent class.
* @param iClassName Edge class name
* @param clusters The number of clusters to create for the new class. By default theMINIMUMCLUSTERS database setting is used. In v2.2 and later, the number of clusters are proportioned to the amount of cores found on the machine
* @return OrientEdgeType instance representing the persistent class
*/
public OrientEdgeType createEdgeType( final String iClassName, final int clusters);
/**
* Creates a new Edge persistent class specifying the super class.
* @param iClassName Edge class name
* @param iSuperClassName Edge class name to extend
* @return OrientEdgeType instance representing the persistent class
*/
public OrientEdgeType createEdgeType( final String iClassName, final String iSuperClassName);
/**
* Creates a new Edge persistent class specifying the super class.
* @param iClassName Edge class name
* @param iSuperClassName Edge class name to extend
* @param clusters The number of clusters to create for the new class. By default theMINIMUMCLUSTERS database setting is used. In v2.2 and later, the number of clusters are proportioned to the amount of cores found on the machine
* @return OrientEdgeType instance representing the persistent class
*/
public OrientEdgeType createEdgeType( final String iClassName, final String iSuperClassName, final int clusters);
/**
* Creates a new Edge persistent class specifying the super class.
* @param iClassName Edge class name
* @param iSuperClass OClass Edge to extend
* @param clusters The number of clusters to create for the new class. By default theMINIMUMCLUSTERS database setting is used. In v2.2 and later, the number of clusters are proportioned to the amount of cores found on the machine
* @return OrientEdgeType instance representing the persistent class
*/
public OrientEdgeType createEdgeType( final String iClassName, final OClass iSuperClass, final int clusters);
/**
* Creates a new Edge persistent class specifying the super class.
* @param iClassName Edge class name
* @param iSuperClass OClass Edge to extend
* @return OrientEdgeType instance representing the persistent class
*/
public OrientEdgeType createEdgeType( final String iClassName, final OClass iSuperClass);
/**
* Drops an edge class.
* @param iTypeName Edge class name
*/
public void dropEdgeType( final String iTypeName);
/**
* Detaches a Graph Element to be used offline. All the changes will be committed on further @attach call.
* @param iElement Graph element to detach
* @return The detached element
* @see #attach(OrientElement)
*/
public OrientElement detach( final OrientElement iElement);
/**
* Attaches a previously detached Graph Element to the current Graph. All the pending changes will be committed.
* @param iElement Graph element to attach
* @return The attached element
* @see #detach(OrientElement)
*/
public OrientElement attach( final OrientElement iElement);
/**
* Returns a graph element, vertex or edge, starting from an ID.
* @param id Can by a String, ODocument or an OIdentifiable object.
* @return OrientElement subclass such as OrientVertex or OrientEdge
*/
public OrientElement getElement( final Object id);
/**
* Drops the index against a field name.
* @param key Field name
* @param elementClass Element class as instances of Vertex and Edge
*/
public <T extends Element>void dropKeyIndex( final String key, final Class<T> elementClass);
/**
* Creates an automatic indexing structure for indexing provided key for element class.
* @param key the key to create the index for
* @param elementClass the element class that the index is for
* @param indexParameters a collection of parameters for the underlying index implementation:<ul> <li>"type" is the index type between the supported types (UNIQUE, NOTUNIQUE, FULLTEXT). The default type is NOT_UNIQUE <li>"class" is the class to index when it's a custom type derived by Vertex (V) or Edge (E) <li>"keytype" to use a key type different by OType.STRING, </ul>
* @param < T > the element class specification
*/
@SuppressWarnings({"rawtypes"}) @Override public <T extends Element>void createKeyIndex( final String key, final Class<T> elementClass, final Parameter... indexParameters);
/**
* Returns the indexed properties.
* @param elementClass the element class that the index is for
* @return Set of String containing the indexed properties
*/
@Override public <T extends Element>Set<String> getIndexedKeys( final Class<T> elementClass);
/**
* Returns the indexed properties.
* @param elementClass the element class that the index is for
* @param includeClassNames If true includes also the class name as prefix of fields
* @return Set of String containing the indexed properties
*/
public <T extends Element>Set<String> getIndexedKeys( final Class<T> elementClass, final boolean includeClassNames);
/**
* Returns a GraphQuery object to execute queries against the Graph.
* @return new GraphQuery instance
*/
@Override public GraphQuery query();
/**
* Returns a OTraverse object to start traversing the graph.
*/
public OTraverse traverse();
/**
* Executes commands against the graph. Commands are executed outside transaction.
* @param iCommand Command request between SQL, GREMLIN and SCRIPT commands
*/
public OCommandRequest command( final OCommandRequest iCommand);
public OResultSet sqlCommand( String iCommand);
public OResultSet sqlQuery( String iCommand);
public OResultSet sqlCommand( String iCommand, Object... args);
public OResultSet sqlQuery( String iCommand, Object... args);
/**
* Counts the vertices in graph.
* @return Long as number of total vertices
*/
public long countVertices();
/**
* Counts the vertices in graph of a particular class.
* @return Long as number of total vertices
*/
public long countVertices( final String iClassName);
/**
* Counts the edges in graph. Edge counting works only if useLightweightEdges is false.
* @return Long as number of total edges
*/
public long countEdges();
/**
* Counts the edges in graph of a particular class. Edge counting works only if useLightweightEdges is false.
* @return Long as number of total edges
*/
public long countEdges( final String iClassName);
public <RET>RET executeOutsideTx( final OCallable<RET,OrientBaseGraph> iCallable, final String... iOperationStrings) throws RuntimeException;
protected void autoStartTransaction();
protected void saveIndexConfiguration();
protected <T>String getClassName( final Class<T> elementClass);
protected Object convertKey( final OIndex idx, Object iValue);
protected Object[] convertKeys( final OIndex idx, Object[] iValue);
void throwRecordNotFoundException( final ORID identity, final String message);
protected void setCurrentGraphInThreadLocal();
private void putInInitializationStack();
private void pollGraphFromStack( boolean updateDb);
@SuppressWarnings("unchecked") private void readDatabaseConfiguration();
private void openOrCreate();
private List<Index<? extends Element>> loadManualIndexes();
private boolean hasIndexClass( OIndex idx);
protected ODatabaseDocumentInternal getDatabase();
private static class InitializationStackThreadLocal extends ThreadLocal<Deque<OrientBaseGraph>> {
@Override protected Deque<OrientBaseGraph> initialValue();
}
/**
* (Internal only)
*/
protected static void removeEdges( final OrientBaseGraph graph, final ODocument iVertex, final String iFieldName, final OIdentifiable iVertexToRemove, final boolean iAlsoInverse, final boolean useVertexFieldsForEdgeLabels, final boolean autoScaleEdgeType, final boolean forceReload);
/**
* (Internal only)
*/
private static void removeInverseEdge( final OrientBaseGraph graph, final ODocument iVertex, final String iFieldName, final OIdentifiable iVertexToRemove, final OIdentifiable currentRecord, final boolean useVertexFieldsForEdgeLabels, final boolean autoScaleEdgeType, boolean forceReload);
protected static ODocument getDocument( final OIdentifiable id, final boolean forceReload);
/**
* (Internal only)
*/
protected static void deleteEdgeIfAny( final OIdentifiable iRecord, boolean forceReload);
protected OrientVertex getVertexInstance( final OIdentifiable id);
protected OrientVertex getVertexInstance( final String className, final Object... fields);
protected OrientEdge getEdgeInstance( final OIdentifiable id);
protected OrientEdge getEdgeInstance( final String className, final Object... fields);
protected OrientEdge getEdgeInstance( final OIdentifiable from, final OIdentifiable to, final String label);
public OrientConfigurableGraph setUseLightweightEdges( final boolean useDynamicEdges);
@Override protected Object setProperty( String iName, Object iValue);
@Override protected Object getProperty( String iName);
@Override public Map<String,Object> getProperties();
}
| , final Object key);
protected Object convertKey( final OIndex idx, final String key);
protected Object convertKey( final OIndex idx, final ODocument key);
protected Object convertKey( final OIndex idx, final OIdentifiable key);
protected Object convertKey( final OIndex idx, final OIdentifiable key, final String iClassName);
protected Object convertKey( final OIndex idx, final OIdentifiable key, final String iClassName, final String iClusterName);
protected Object convertKey( final OIndex idx, final OIdentifiable key, final OClass iClass);
protected Object convertKey( final OIndex idx, final OIdentifiable key, final OClass iClass, final String iClusterName);
protected Object convertKey( final OIndex idx, final OIdentifiable key, final OClass iClass, final OClass iClusterClass);
protected Object convertKey( final OIndex idx, final OIdentifiable key, final OClass iClass, final OClass iClusterClass, final String iClusterName);
protected Object convertKey( final OIndex idx, final OIdentifiable key, final OClass iClass, final OClass iClusterClass, final OClass iClusterNameClass);
protected Object convertKey( final OIndex idx, final OIdentifiable key, final OClass iClass, final OClass iClusterClass, final OClass iClusterNameClass, final String iClusterName);
protected Object convertKey( final OIndex idx, final OIdentifiable key, final OClass iClass, final OClass iClusterClass, final OClass iClusterNameClass | [] | [] | [] | [
"setUsingLog",
"isActive",
"getTransaction",
"isUseLog",
"begin"
] | {
"methods": [],
"similar_methods": [
"autoStartTransaction"
],
"types": []
} | protected void autoStartTransaction(){
}
| protected void autoStartTransaction(){
}
| {"similar_methods": [{"autoStartTransaction": "autoStartTransaction"}]} | [] | [] | [{"autoStartTransaction": {"retrieved_name": "autoStartTransaction", "raw_body": "protected void autoStartTransaction(){\n}\n"}}] |
javamelody_javamelody | javamelody/javamelody-core/src/main/java/net/bull/javamelody/internal/model/CounterRequestRumData.java | CounterRequestRumData | removeHits | class CounterRequestRumData implements Serializable, Cloneable {
private static final long serialVersionUID = 745110095604593659L;
// au-delà de 5 minutes, on considère une valeur RUM comme aberrante et à ignorer
private static final long ABERRANT_VALUE = 5 * 60 * 1000;
private long hits;
private long networkTimeSum;
private long domProcessingSum;
private long pageRenderingSum;
public long getHits() {
return hits;
}
public int getNetworkTimeMean() {
if (hits > 0) {
return (int) (networkTimeSum / hits);
}
return -1;
}
public int getDomProcessingMean() {
if (hits > 0) {
return (int) (domProcessingSum / hits);
}
return -1;
}
public int getPageRenderingMean() {
if (hits > 0) {
return (int) (pageRenderingSum / hits);
}
return -1;
}
void addHit(long networkTime, long domProcessing, long pageRendering) {
if (networkTime < 0 || networkTime > ABERRANT_VALUE || domProcessing < 0
|| domProcessing > ABERRANT_VALUE || pageRendering < 0
|| pageRendering > ABERRANT_VALUE) {
// aberrant value, we ignore it
return;
}
networkTimeSum += networkTime;
domProcessingSum += domProcessing;
pageRenderingSum += pageRendering;
hits++;
}
void addHits(CounterRequestRumData rumData) {
if (rumData.hits != 0) {
hits += rumData.hits;
networkTimeSum += rumData.networkTimeSum;
domProcessingSum += rumData.domProcessingSum;
pageRenderingSum += rumData.pageRenderingSum;
}
}
void removeHits(CounterRequestRumData rumData) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override
public CounterRequestRumData clone() { // NOPMD
try {
return (CounterRequestRumData) super.clone();
} catch (final CloneNotSupportedException e) {
// ne peut arriver puisque CounterRequest implémente Cloneable
throw new IllegalStateException(e);
}
}
/** {@inheritDoc} */
@Override
public String toString() {
return getClass().getSimpleName() + "[hits=" + hits + ']';
}
} |
if (rumData.hits != 0) {
hits -= rumData.hits;
networkTimeSum -= rumData.networkTimeSum;
domProcessingSum -= rumData.domProcessingSum;
pageRenderingSum -= rumData.pageRenderingSum;
}
|
if (rumData.hits != 0) {
hits -= rumData.hits;
networkTimeSum -= rumData.networkTimeSum;
domProcessingSum -= rumData.domProcessingSum;
pageRenderingSum -= rumData.pageRenderingSum;
}
| [
"CounterRequestRumData"
] | [] | [
"CounterRequestRumData"
] | [] | {
"methods": [],
"similar_methods": [
"removeHits"
],
"types": [
"CounterRequestRumData"
]
} | /**
* Données pour le tableau des requêtes courantes.
* @author Emeric Vernat
*/
public class CounterRequestContextData {
private final List<Counter> counters;
private final JavaInformations javaInformations;
private final Map<Long,ThreadInformations> threadInformationsById;
private final List<CounterRequestContext> contexts;
private final List<CounterRequestContext> allContexts;
private final List<CounterRequest> allRequests;
private final Map<Counter,CounterRequestAggregation> aggregationsByCounter=new HashMap<>();
private final boolean stackTraceEnabled;
private final boolean childHitsDisplayed;
private final boolean remoteUserDisplayed;
public CounterRequestContextData( List<Counter> counters, List<CounterRequestContext> currentRequests, JavaInformations javaInformations);
private Map<String,CounterRequest> mapAllRequestsById();
public CounterRequestAggregation getAggregationForCounter( Counter counter);
public ThreadInformations getThreadInformationsByCounterRequestContext( CounterRequestContext counterRequestContext);
public boolean isStackTraceEnabled();
public boolean isChildHitsDisplayed();
public boolean isRemoteUserDisplayed();
public final List<CounterRequestContext> getRootContexts();
public List<CounterRequestContext> getAllContexts();
public List<CounterRequest> getAllRequests();
JavaInformations getJavaInformations();
}
void removeHits(CounterRequest request){
assert request != null;
if (request.hits != 0) {
hits-=request.hits;
durationsSum-=request.durationsSum;
durationsSquareSum-=request.durationsSquareSum;
if (request.maximum >= maximum) {
if (hits > 0) {
maximum=durationsSum / hits;
}
else {
maximum=-1;
}
}
cpuTimeSum-=request.cpuTimeSum;
allocatedKBytesSum-=request.allocatedKBytesSum;
systemErrors-=request.systemErrors;
responseSizesSum-=request.responseSizesSum;
childHits-=request.childHits;
childDurationsSum-=request.childDurationsSum;
removeChildHits(request);
}
if (rumData != null && request.rumData != null) {
rumData.removeHits(request.rumData);
}
}
| public class CounterRequestContextData {
private final List<Counter> counters;
private final JavaInformations javaInformations;
private final Map<Long,ThreadInformations> threadInformationsById;
private final List<CounterRequestContext> contexts;
private final List<CounterRequestContext> allContexts;
private final List<CounterRequest> allRequests;
private final Map<Counter,CounterRequestAggregation> aggregationsByCounter=new HashMap<>();
private final boolean stackTraceEnabled;
private final boolean childHitsDisplayed;
private final boolean remoteUserDisplayed;
public CounterRequestContextData( List<Counter> counters, List<CounterRequestContext> currentRequests, JavaInformations javaInformations);
private Map<String,CounterRequest> mapAllRequestsById();
public CounterRequestAggregation getAggregationForCounter( Counter counter);
public ThreadInformations getThreadInformationsByCounterRequestContext( CounterRequestContext counterRequestContext);
public boolean isStackTraceEnabled();
public boolean isChildHitsDisplayed();
public boolean isRemoteUserDisplayed();
public final List<CounterRequestContext> getRootContexts();
public List<CounterRequestContext> getAllContexts();
public List<CounterRequest> getAllRequests();
JavaInformations getJavaInformations();
}
void removeHits(CounterRequest request){
assert request != null;
if (request.hits != 0) {
hits-=request.hits;
durationsSum-=request.durationsSum;
durationsSquareSum-=request.durationsSquareSum;
if (request.maximum >= maximum) {
if (hits > 0) {
maximum=durationsSum / hits;
}
else {
maximum=-1;
}
}
cpuTimeSum-=request.cpuTimeSum;
allocatedKBytesSum-=request.allocatedKBytesSum;
systemErrors-=request.systemErrors;
responseSizesSum-=request.responseSizesSum;
childHits-=request.childHits;
childDurationsSum-=request.childDurationsSum;
removeChildHits(request);
}
if (rumData != null && request.rumData != null) {
rumData.removeHits(request.rumData);
}
}
| {"types": [{"CounterRequestRumData": "CounterRequestContextData"}], "similar_methods": [{"removeHits": "removeHits"}]} | [{"CounterRequestRumData": {"retrieved_name": "CounterRequestContextData", "raw_body": "/** \n * Donn\u00e9es pour le tableau des requ\u00eates courantes.\n * @author Emeric Vernat\n */\npublic class CounterRequestContextData {\n private final List<Counter> counters;\n private final JavaInformations javaInformations;\n private final Map<Long,ThreadInformations> threadInformationsById;\n private final List<CounterRequestContext> contexts;\n private final List<CounterRequestContext> allContexts;\n private final List<CounterRequest> allRequests;\n private final Map<Counter,CounterRequestAggregation> aggregationsByCounter=new HashMap<>();\n private final boolean stackTraceEnabled;\n private final boolean childHitsDisplayed;\n private final boolean remoteUserDisplayed;\n public CounterRequestContextData( List<Counter> counters, List<CounterRequestContext> currentRequests, JavaInformations javaInformations);\n private Map<String,CounterRequest> mapAllRequestsById();\n public CounterRequestAggregation getAggregationForCounter( Counter counter);\n public ThreadInformations getThreadInformationsByCounterRequestContext( CounterRequestContext counterRequestContext);\n public boolean isStackTraceEnabled();\n public boolean isChildHitsDisplayed();\n public boolean isRemoteUserDisplayed();\n public final List<CounterRequestContext> getRootContexts();\n public List<CounterRequestContext> getAllContexts();\n public List<CounterRequest> getAllRequests();\n JavaInformations getJavaInformations();\n}\n", "raw_body_no_cmt": "public class CounterRequestContextData {\n private final List<Counter> counters;\n private final JavaInformations javaInformations;\n private final Map<Long,ThreadInformations> threadInformationsById;\n private final List<CounterRequestContext> contexts;\n private final List<CounterRequestContext> allContexts;\n private final List<CounterRequest> allRequests;\n private final Map<Counter,CounterRequestAggregation> aggregationsByCounter=new HashMap<>();\n private final boolean stackTraceEnabled;\n private final boolean childHitsDisplayed;\n private final boolean remoteUserDisplayed;\n public CounterRequestContextData( List<Counter> counters, List<CounterRequestContext> currentRequests, JavaInformations javaInformations);\n private Map<String,CounterRequest> mapAllRequestsById();\n public CounterRequestAggregation getAggregationForCounter( Counter counter);\n public ThreadInformations getThreadInformationsByCounterRequestContext( CounterRequestContext counterRequestContext);\n public boolean isStackTraceEnabled();\n public boolean isChildHitsDisplayed();\n public boolean isRemoteUserDisplayed();\n public final List<CounterRequestContext> getRootContexts();\n public List<CounterRequestContext> getAllContexts();\n public List<CounterRequest> getAllRequests();\n JavaInformations getJavaInformations();\n}\n"}}] | [] | [{"removeHits": {"retrieved_name": "removeHits", "raw_body": "void removeHits(CounterRequest request){\n assert request != null;\n if (request.hits != 0) {\n hits-=request.hits;\n durationsSum-=request.durationsSum;\n durationsSquareSum-=request.durationsSquareSum;\n if (request.maximum >= maximum) {\n if (hits > 0) {\n maximum=durationsSum / hits;\n }\n else {\n maximum=-1;\n }\n }\n cpuTimeSum-=request.cpuTimeSum;\n allocatedKBytesSum-=request.allocatedKBytesSum;\n systemErrors-=request.systemErrors;\n responseSizesSum-=request.responseSizesSum;\n childHits-=request.childHits;\n childDurationsSum-=request.childDurationsSum;\n removeChildHits(request);\n }\n if (rumData != null && request.rumData != null) {\n rumData.removeHits(request.rumData);\n }\n}\n"}}] |
|
orientechnologies_orientdb | orientdb/core/src/main/java/com/orientechnologies/orient/core/index/OIndexFullText.java | OIndexFullText | splitIntoWords | class OIndexFullText extends OIndexMultiValues {
private static final String CONFIG_STOP_WORDS = "stopWords";
private static final String CONFIG_SEPARATOR_CHARS = "separatorChars";
private static final String CONFIG_IGNORE_CHARS = "ignoreChars";
private static final String CONFIG_INDEX_RADIX = "indexRadix";
private static final String CONFIG_MIN_WORD_LEN = "minWordLength";
private static final boolean DEF_INDEX_RADIX = true;
private static final String DEF_SEPARATOR_CHARS = " \r\n\t:;,.|+*/\\=!?[]()";
private static final String DEF_IGNORE_CHARS = "'\"";
private static final String DEF_STOP_WORDS =
"the in a at as and or for his her "
+ "him this that what which while "
+ "up with be was were is";
private boolean indexRadix;
private String separatorChars;
private String ignoreChars;
private int minWordLength;
private Set<String> stopWords;
public OIndexFullText(OIndexMetadata im, final OStorage storage) {
super(im, storage);
acquireExclusiveLock();
try {
config();
configWithMetadata(im.getMetadata());
} finally {
releaseExclusiveLock();
}
}
/**
* Indexes a value and save the index. Splits the value in single words and index each one. Save
* of the index is responsibility of the caller.
*/
@Override
public OIndexFullText put(Object key, final OIdentifiable value) {
if (key == null) {
return this;
}
final ORID rid = value.getIdentity();
if (!rid.isValid()) {
if (value instanceof ORecord) {
// EARLY SAVE IT
((ORecord) value).save();
} else {
throw new IllegalArgumentException(
"Cannot store non persistent RID as index value for key '" + key + "'");
}
}
key = getCollatingValue(key);
final Set<String> words = splitIntoWords(key.toString());
ODatabaseDocumentInternal database = getDatabase();
if (database.getTransaction().isActive()) {
OTransaction singleTx = database.getTransaction();
for (String word : words) {
singleTx.addIndexEntry(
this, super.getName(), OTransactionIndexChanges.OPERATION.PUT, word, value);
}
} else {
database.begin();
OTransaction singleTx = database.getTransaction();
for (String word : words) {
singleTx.addIndexEntry(
this, super.getName(), OTransactionIndexChanges.OPERATION.PUT, word, value);
}
database.commit();
}
return this;
}
/**
* Splits passed in key on several words and remove records with keys equals to any item of split
* result and values equals to passed in value.
*
* @param key Key to remove.
* @param rid Value to remove.
* @return <code>true</code> if at least one record is removed.
*/
@Override
public boolean remove(Object key, final OIdentifiable rid) {
if (key == null) {
return false;
}
key = getCollatingValue(key);
final Set<String> words = splitIntoWords(key.toString());
ODatabaseDocumentInternal database = getDatabase();
if (database.getTransaction().isActive()) {
for (final String word : words) {
database.getTransaction().addIndexEntry(this, super.getName(), OPERATION.REMOVE, word, rid);
}
} else {
database.begin();
for (final String word : words) {
database.getTransaction().addIndexEntry(this, super.getName(), OPERATION.REMOVE, word, rid);
}
database.commit();
}
return true;
}
@Override
public OIndexMultiValues create(
OIndexMetadata metadata, boolean rebuild, OProgressListener progressListener) {
if (metadata.getIndexDefinition().getFields().size() > 1) {
throw new OIndexException(getType() + " indexes cannot be used as composite ones.");
}
super.create(metadata, rebuild, progressListener);
return this;
}
@Override
public ODocument updateConfiguration() {
ODocument document = super.updateConfiguration();
document.field(CONFIG_SEPARATOR_CHARS, separatorChars);
document.field(CONFIG_IGNORE_CHARS, ignoreChars);
document.field(CONFIG_STOP_WORDS, stopWords);
document.field(CONFIG_MIN_WORD_LEN, minWordLength);
document.field(CONFIG_INDEX_RADIX, indexRadix);
return document;
}
public boolean canBeUsedInEqualityOperators() {
return false;
}
public boolean supportsOrderedIterations() {
return false;
}
private void configWithMetadata(ODocument metadata) {
if (metadata != null) {
if (metadata.containsField(CONFIG_IGNORE_CHARS)) {
ignoreChars = metadata.field(CONFIG_IGNORE_CHARS);
}
if (metadata.containsField(CONFIG_INDEX_RADIX)) {
indexRadix = metadata.field(CONFIG_INDEX_RADIX);
}
if (metadata.containsField(CONFIG_SEPARATOR_CHARS)) {
separatorChars = metadata.field(CONFIG_SEPARATOR_CHARS);
}
if (metadata.containsField(CONFIG_MIN_WORD_LEN)) {
minWordLength = metadata.field(CONFIG_MIN_WORD_LEN);
}
if (metadata.containsField(CONFIG_STOP_WORDS)) {
stopWords = new HashSet<>(metadata.field(CONFIG_STOP_WORDS));
}
}
}
private void config() {
ignoreChars = DEF_IGNORE_CHARS;
indexRadix = DEF_INDEX_RADIX;
separatorChars = DEF_SEPARATOR_CHARS;
minWordLength = 3;
stopWords = new HashSet<>(OStringSerializerHelper.split(DEF_STOP_WORDS, ' '));
}
private Set<String> splitIntoWords(final String iKey) {<FILL_FUNCTION_BODY>}
} |
final Set<String> result = new HashSet<>();
final List<String> words = new ArrayList<>();
OStringSerializerHelper.split(words, iKey, 0, -1, separatorChars);
final StringBuilder buffer = new StringBuilder(64);
// FOREACH WORD CREATE THE LINK TO THE CURRENT DOCUMENT
char c;
boolean ignore;
for (String word : words) {
buffer.setLength(0);
for (int i = 0; i < word.length(); ++i) {
c = word.charAt(i);
ignore = false;
for (int k = 0; k < ignoreChars.length(); ++k) {
if (c == ignoreChars.charAt(k)) {
ignore = true;
break;
}
}
if (!ignore) {
buffer.append(c);
}
}
int length = buffer.length();
while (length >= minWordLength) {
buffer.setLength(length);
word = buffer.toString();
// CHECK IF IT'S A STOP WORD
if (!stopWords.contains(word))
// ADD THE WORD TO THE RESULT SET
{
result.add(word);
}
if (indexRadix) {
length--;
} else {
break;
}
}
}
return result;
| /**
* Abstract index implementation that supports multi-values for the same key.
* @author Luca Garulli (l.garulli--(at)--orientdb.com)
*/
public abstract class OIndexMultiValues extends OIndexAbstract {
OIndexMultiValues( OIndexMetadata im, final OStorage storage);
@Deprecated @Override public Collection<ORID> get( Object key);
@Override public Stream<ORID> getRidsIgnoreTx( Object key);
@Override public Stream<ORID> getRids( Object key);
public OIndexMultiValues put( Object key, final OIdentifiable singleValue);
@Override public void doPut( OAbstractPaginatedStorage storage, Object key, ORID rid) throws OInvalidIndexEngineIdException;
@Override public boolean isNativeTxSupported();
private static void doPutV0( final int indexId, final OAbstractPaginatedStorage storage, String valueContainerAlgorithm, String indexName, Object key, ORID identity) throws OInvalidIndexEngineIdException;
private static void doPutV1( OAbstractPaginatedStorage storage, int indexId, Object key, ORID identity) throws OInvalidIndexEngineIdException;
@Override public boolean remove( Object key, final OIdentifiable value);
@Override public boolean doRemove( OAbstractPaginatedStorage storage, Object key, ORID rid) throws OInvalidIndexEngineIdException;
private static boolean doRemoveV0( int indexId, OAbstractPaginatedStorage storage, Object key, OIdentifiable value) throws OInvalidIndexEngineIdException;
private static boolean doRemoveV1( int indexId, OAbstractPaginatedStorage storage, Object key, OIdentifiable value) throws OInvalidIndexEngineIdException;
@Override public Stream<ORawPair<Object,ORID>> streamEntriesBetween( Object fromKey, boolean fromInclusive, Object toKey, boolean toInclusive, boolean ascOrder);
@Override public Stream<ORawPair<Object,ORID>> streamEntriesMajor( Object fromKey, boolean fromInclusive, boolean ascOrder);
@Override public Stream<ORawPair<Object,ORID>> streamEntriesMinor( Object toKey, boolean toInclusive, boolean ascOrder);
@Override public Stream<ORawPair<Object,ORID>> streamEntries( Collection<?> keys, boolean ascSortOrder);
private Stream<ORawPair<Object,ORID>> txStramForKey( final OTransactionIndexChanges indexChanges, Object key);
private Stream<ORawPair<Object,ORID>> streamForKey( Object key);
public static Set<OIdentifiable> calculateTxValue( final Object key, OTransactionIndexChanges indexChanges);
public long size();
@Override public Stream<ORawPair<Object,ORID>> stream();
private Stream<ORawPair<Object,ORID>> mergeTxAndBackedStreams( OTransactionIndexChanges indexChanges, Stream<ORawPair<Object,ORID>> txStream, Stream<ORawPair<Object,ORID>> backedStream, boolean ascOrder);
private ORawPair<Object,ORID> calculateTxIndexEntry( Object key, final ORID backendValue, OTransactionIndexChanges indexChanges);
@Override public Stream<ORawPair<Object,ORID>> descStream();
}
|
final StringBuilder sb = new StringBuilder();
final Set<String> words = new HashSet<>();
for (int i = 0; i < iKey.length(); i++) {
final char c = iKey.charAt(i);
if (separatorChars.indexOf(c) != -1) {
if (sb.length() >= minWordLength) {
words.add(sb.toString());
}
sb.setLength(0);
} else if (ignoreChars.indexOf(c) == -1) {
sb.append(c);
}
}
if (sb.length() >= minWordLength) {
words.add(sb.toString());
}
return words;
| [
"Set<String>"
] | [
"add",
"indexOf",
"toString",
"append",
"setLength",
"charAt",
"length"
] | [
"List<String>",
"Set<String>"
] | [
"add",
"append",
"toString",
"length",
"setLength",
"charAt",
"split",
"contains"
] | {
"methods": [
"add",
"indexOf",
"toString",
"append",
"setLength",
"charAt",
"length"
],
"similar_methods": [
"splitIntoWords"
],
"types": [
"Set<String>"
]
} | /**
* Created by luigidellaquila on 19/02/15.
*/
public class OInsertSetExpression {
protected OIdentifier left;
protected OExpression right;
public void toString( Map<Object,Object> params, StringBuilder builder);
public OInsertSetExpression copy();
public OIdentifier getLeft();
public OExpression getRight();
public boolean isCacheable();
public void toGenericStatement( StringBuilder builder);
}
@Override public boolean add(OIdentifiable e){
preAdd(e);
lazyLoad(true);
return super.add(e);
}
@Override public int indexOf(Object o){
Node item=first;
for (int i=0; i < size; i++) {
if (item.entry.equals(o)) {
return i;
}
item=item.next;
}
return -1;
}
public static String toString(final int version){
return String.valueOf(version);
}
public OTraversePath append(OIdentifiable record){
return new OTraversePath(new RecordPathItem(record,lastPathItem));
}
public void setLong(int parameterIndex,long x) throws SQLException {
params.put(parameterIndex,x);
}
@Test public void charset() throws Exception {
String element=";";
int x=element.charAt(0);
System.out.println("x=" + x);
}
public long length() throws SQLException {
return this.length;
}
public static int[] splitIntArray(final String iInput){
final List<String> items=split(iInput,RECORD_SEPARATOR);
final int[] values=new int[items.size()];
for (int i=0; i < items.size(); ++i) {
values[i]=Integer.parseInt(items.get(i).trim());
}
return values;
}
| public class OInsertSetExpression {
protected OIdentifier left;
protected OExpression right;
public void toString( Map<Object,Object> params, StringBuilder builder);
public OInsertSetExpression copy();
public OIdentifier getLeft();
public OExpression getRight();
public boolean isCacheable();
public void toGenericStatement( StringBuilder builder);
}
@Override public boolean add(OIdentifiable e){
preAdd(e);
lazyLoad(true);
return super.add(e);
}
@Override public int indexOf(Object o){
Node item=first;
for (int i=0; i < size; i++) {
if (item.entry.equals(o)) {
return i;
}
item=item.next;
}
return -1;
}
public static String toString(final int version){
return String.valueOf(version);
}
public OTraversePath append(OIdentifiable record){
return new OTraversePath(new RecordPathItem(record,lastPathItem));
}
public void setLong(int parameterIndex,long x) throws SQLException {
params.put(parameterIndex,x);
}
@Test public void charset() throws Exception {
String element=";";
int x=element.charAt(0);
System.out.println("x=" + x);
}
public long length() throws SQLException {
return this.length;
}
public static int[] splitIntArray(final String iInput){
final List<String> items=split(iInput,RECORD_SEPARATOR);
final int[] values=new int[items.size()];
for (int i=0; i < items.size(); ++i) {
values[i]=Integer.parseInt(items.get(i).trim());
}
return values;
}
| {"types": [{"Set<String>": "OInsertSetExpression"}], "methods": [{"add": "add"}, {"indexOf": "indexOf"}, {"toString": "toString"}, {"append": "append"}, {"setLength": "setLong"}, {"charAt": "charset"}, {"length": "length"}], "similar_methods": [{"splitIntoWords": "splitIntArray"}]} | [{"Set<String>": {"retrieved_name": "OInsertSetExpression", "raw_body": "/** \n * Created by luigidellaquila on 19/02/15. \n */\npublic class OInsertSetExpression {\n protected OIdentifier left;\n protected OExpression right;\n public void toString( Map<Object,Object> params, StringBuilder builder);\n public OInsertSetExpression copy();\n public OIdentifier getLeft();\n public OExpression getRight();\n public boolean isCacheable();\n public void toGenericStatement( StringBuilder builder);\n}\n", "raw_body_no_cmt": "public class OInsertSetExpression {\n protected OIdentifier left;\n protected OExpression right;\n public void toString( Map<Object,Object> params, StringBuilder builder);\n public OInsertSetExpression copy();\n public OIdentifier getLeft();\n public OExpression getRight();\n public boolean isCacheable();\n public void toGenericStatement( StringBuilder builder);\n}\n"}}] | [{"add": {"retrieved_name": "add", "raw_body": "@Override public boolean add(OIdentifiable e){\n preAdd(e);\n lazyLoad(true);\n return super.add(e);\n}\n"}}, {"indexOf": {"retrieved_name": "indexOf", "raw_body": "@Override public int indexOf(Object o){\n Node item=first;\n for (int i=0; i < size; i++) {\n if (item.entry.equals(o)) {\n return i;\n }\n item=item.next;\n }\n return -1;\n}\n"}}, {"toString": {"retrieved_name": "toString", "raw_body": "public static String toString(final int version){\n return String.valueOf(version);\n}\n"}}, {"append": {"retrieved_name": "append", "raw_body": "public OTraversePath append(OIdentifiable record){\n return new OTraversePath(new RecordPathItem(record,lastPathItem));\n}\n"}}, {"setLength": {"retrieved_name": "setLong", "raw_body": "public void setLong(int parameterIndex,long x) throws SQLException {\n params.put(parameterIndex,x);\n}\n"}}, {"charAt": {"retrieved_name": "charset", "raw_body": "@Test public void charset() throws Exception {\n String element=\";\";\n int x=element.charAt(0);\n System.out.println(\"x=\" + x);\n}\n"}}, {"length": {"retrieved_name": "length", "raw_body": "public long length() throws SQLException {\n return this.length;\n}\n"}}] | [{"splitIntoWords": {"retrieved_name": "splitIntArray", "raw_body": "public static int[] splitIntArray(final String iInput){\n final List<String> items=split(iInput,RECORD_SEPARATOR);\n final int[] values=new int[items.size()];\n for (int i=0; i < items.size(); ++i) {\n values[i]=Integer.parseInt(items.get(i).trim());\n }\n return values;\n}\n"}}] |
PlayEdu_PlayEdu | PlayEdu/playedu-common/src/main/java/xyz/playedu/common/service/impl/UserDepartmentServiceImpl.java | UserDepartmentServiceImpl | storeDepIds | class UserDepartmentServiceImpl extends ServiceImpl<UserDepartmentMapper, UserDepartment>
implements UserDepartmentService {
@Override
public List<Integer> getUserIdsByDepIds(List<Integer> depIds) {
return list(query().getWrapper().in("dep_id", depIds)).stream()
.map(UserDepartment::getUserId)
.toList();
}
@Override
public void storeDepIds(Integer userId, Integer[] depIds) {<FILL_FUNCTION_BODY>}
@Override
public void resetStoreDepIds(Integer userId, Integer[] depIds) {
remove(query().getWrapper().eq("user_id", userId));
storeDepIds(userId, depIds);
}
} |
if (depIds == null) {
return;
}
List<UserDepartment> userDepartments = new ArrayList<>();
for (int i = 0; i < depIds.length; i++) {
Integer depId = depIds[i];
userDepartments.add(
new UserDepartment() {
{
setUserId(userId);
setDepId(depId);
}
});
}
saveBatch(userDepartments);
|
remove(query().getWrapper().eq("user_id", userId));
if (ArrayUtil.isNotEmpty(depIds)) {
List<UserDepartment> userDepartments = Arrays.stream(depIds)
.map(depId -> new UserDepartment(userId, depId))
.toList();
saveBatch(userDepartments);
}
| [
"List<UserDepartment>"
] | [
"isNotEmpty",
"getWrapper",
"eq",
"toList",
"map",
"stream"
] | [
"List<UserDepartment>"
] | [
"add"
] | {
"methods": [
"isNotEmpty",
"getWrapper",
"eq",
"toList",
"map",
"stream"
],
"similar_methods": [
"storeDepIds"
],
"types": [
"List<UserDepartment>"
]
} | /**
* @TableName user_department
*/
@TableName(value="user_department") @Data public class UserDepartment implements Serializable {
@JsonProperty("user_id") private Integer userId;
@JsonProperty("dep_id") private Integer depId;
@TableField(exist=false) private static final long serialVersionUID=1L;
@Override public boolean equals( Object that);
@Override public int hashCode();
@Override public String toString();
}
/**
* 判断一个字符串是否为非空串
* @param str String
* @return true=非空串, false=空串
*/
public static boolean isNotEmpty(String str){
return !isEmpty(str);
}
/**
* 获取key的值
* @param key 键
* @return Object
* @author fzr
*/
public static Object get(String key){
key=redisPrefix + key;
return redisTemplate.opsForValue().get(key);
}
@Override public boolean equals(Object that){
if (this == that) {
return true;
}
if (that == null) {
return false;
}
if (getClass() != that.getClass()) {
return false;
}
CourseAttachment other=(CourseAttachment)that;
return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId())) && (this.getCourseId() == null ? other.getCourseId() == null : this.getCourseId().equals(other.getCourseId())) && (this.getSort() == null ? other.getSort() == null : this.getSort().equals(other.getSort()))&& (this.getTitle() == null ? other.getTitle() == null : this.getTitle().equals(other.getTitle()))&& (this.getExt() == null ? other.getExt() == null : this.getExt().equals(other.getExt()))&& (this.getType() == null ? other.getType() == null : this.getType().equals(other.getType()))&& (this.getRid() == null ? other.getRid() == null : this.getRid().equals(other.getRid()))&& (this.getUrl() == null ? other.getUrl() == null : this.getUrl().equals(other.getUrl()))&& (this.getCreatedAt() == null ? other.getCreatedAt() == null : this.getCreatedAt().equals(other.getCreatedAt()));
}
@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(", migration=").append(migration);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
@Override public void saveFromMap(HashMap<String,String> data){
Map<String,AppConfig> configs=list(query().getWrapper().in("key_name",data.keySet())).stream().collect(Collectors.toMap(AppConfig::getKeyName,e -> e));
List<AppConfig> list=new ArrayList<>();
data.forEach((keyNameValue,keyValueValue) -> {
if (keyValueValue == null) {
return;
}
if ("******".equals(keyNameValue)) {
return;
}
AppConfig configItem=configs.get(keyNameValue);
if (configItem == null) {
return;
}
if (keyValueValue.equals(configItem.getKeyValue())) {
return;
}
list.add(new AppConfig(){
{
setId(configItem.getId());
setKeyValue(keyValueValue);
}
}
);
}
);
if (!list.isEmpty()) {
updateBatchById(list);
}
}
@Override public Integer duration(Integer id){
ResourceVideo resourceVideo=resourceVideoService.getOne(resourceVideoService.query().getWrapper().eq("rid",id));
if (resourceVideo == null) {
return null;
}
return resourceVideo.getDuration();
}
void storeDepIds(Integer userId,Integer[] depIds);
| public class UserDepartment implements Serializable {
private Integer userId;
private Integer depId;
private static final long serialVersionUID=1L;
public boolean equals( Object that);
public int hashCode();
public String toString();
}
/**
* 判断一个字符串是否为非空串
* @param str String
* @return true=非空串, false=空串
*/
public static boolean isNotEmpty(String str){
return !isEmpty(str);
}
/**
* 获取key的值
* @param key 键
* @return Object
* @author fzr
*/
public static Object get(String key){
key=redisPrefix + key;
return redisTemplate.opsForValue().get(key);
}
@Override public boolean equals(Object that){
if (this == that) {
return true;
}
if (that == null) {
return false;
}
if (getClass() != that.getClass()) {
return false;
}
CourseAttachment other=(CourseAttachment)that;
return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId())) && (this.getCourseId() == null ? other.getCourseId() == null : this.getCourseId().equals(other.getCourseId())) && (this.getSort() == null ? other.getSort() == null : this.getSort().equals(other.getSort()))&& (this.getTitle() == null ? other.getTitle() == null : this.getTitle().equals(other.getTitle()))&& (this.getExt() == null ? other.getExt() == null : this.getExt().equals(other.getExt()))&& (this.getType() == null ? other.getType() == null : this.getType().equals(other.getType()))&& (this.getRid() == null ? other.getRid() == null : this.getRid().equals(other.getRid()))&& (this.getUrl() == null ? other.getUrl() == null : this.getUrl().equals(other.getUrl()))&& (this.getCreatedAt() == null ? other.getCreatedAt() == null : this.getCreatedAt().equals(other.getCreatedAt()));
}
@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(", migration=").append(migration);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
@Override public void saveFromMap(HashMap<String,String> data){
Map<String,AppConfig> configs=list(query().getWrapper().in("key_name",data.keySet())).stream().collect(Collectors.toMap(AppConfig::getKeyName,e -> e));
List<AppConfig> list=new ArrayList<>();
data.forEach((keyNameValue,keyValueValue) -> {
if (keyValueValue == null) {
return;
}
if ("******".equals(keyNameValue)) {
return;
}
AppConfig configItem=configs.get(keyNameValue);
if (configItem == null) {
return;
}
if (keyValueValue.equals(configItem.getKeyValue())) {
return;
}
list.add(new AppConfig(){
{
setId(configItem.getId());
setKeyValue(keyValueValue);
}
}
);
}
);
if (!list.isEmpty()) {
updateBatchById(list);
}
}
@Override public Integer duration(Integer id){
ResourceVideo resourceVideo=resourceVideoService.getOne(resourceVideoService.query().getWrapper().eq("rid",id));
if (resourceVideo == null) {
return null;
}
return resourceVideo.getDuration();
}
void storeDepIds(Integer userId,Integer[] depIds);
| {"types": [{"List<UserDepartment>": "UserDepartment"}], "methods": [{"isNotEmpty": "isNotEmpty"}, {"getWrapper": "get"}, {"eq": "equals"}, {"toList": "toString"}, {"map": "saveFromMap"}, {"stream": "duration"}], "similar_methods": [{"storeDepIds": "storeDepIds"}]} | [{"List<UserDepartment>": {"retrieved_name": "UserDepartment", "raw_body": "/** \n * @TableName user_department\n */\n@TableName(value=\"user_department\") @Data public class UserDepartment implements Serializable {\n @JsonProperty(\"user_id\") private Integer userId;\n @JsonProperty(\"dep_id\") private Integer depId;\n @TableField(exist=false) private static final long serialVersionUID=1L;\n @Override public boolean equals( Object that);\n @Override public int hashCode();\n @Override public String toString();\n}\n", "raw_body_no_cmt": "public class UserDepartment implements Serializable {\n private Integer userId;\n private Integer depId;\n private static final long serialVersionUID=1L;\n public boolean equals( Object that);\n public int hashCode();\n public String toString();\n}\n"}}] | [{"isNotEmpty": {"retrieved_name": "isNotEmpty", "raw_body": "/** \n * \u5224\u65ad\u4e00\u4e2a\u5b57\u7b26\u4e32\u662f\u5426\u4e3a\u975e\u7a7a\u4e32\n * @param str String\n * @return true=\u975e\u7a7a\u4e32, false=\u7a7a\u4e32\n */\npublic static boolean isNotEmpty(String str){\n return !isEmpty(str);\n}\n"}}, {"getWrapper": {"retrieved_name": "get", "raw_body": "/** \n * \u83b7\u53d6key\u7684\u503c\n * @param key \u952e\n * @return Object\n * @author fzr\n */\npublic static Object get(String key){\n key=redisPrefix + key;\n return redisTemplate.opsForValue().get(key);\n}\n"}}, {"eq": {"retrieved_name": "equals", "raw_body": "@Override public boolean equals(Object that){\n if (this == that) {\n return true;\n }\n if (that == null) {\n return false;\n }\n if (getClass() != that.getClass()) {\n return false;\n }\n CourseAttachment other=(CourseAttachment)that;\n return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId())) && (this.getCourseId() == null ? other.getCourseId() == null : this.getCourseId().equals(other.getCourseId())) && (this.getSort() == null ? other.getSort() == null : this.getSort().equals(other.getSort()))&& (this.getTitle() == null ? other.getTitle() == null : this.getTitle().equals(other.getTitle()))&& (this.getExt() == null ? other.getExt() == null : this.getExt().equals(other.getExt()))&& (this.getType() == null ? other.getType() == null : this.getType().equals(other.getType()))&& (this.getRid() == null ? other.getRid() == null : this.getRid().equals(other.getRid()))&& (this.getUrl() == null ? other.getUrl() == null : this.getUrl().equals(other.getUrl()))&& (this.getCreatedAt() == null ? other.getCreatedAt() == null : this.getCreatedAt().equals(other.getCreatedAt()));\n}\n"}}, {"toList": {"retrieved_name": "toString", "raw_body": "@Override public String toString(){\n StringBuilder sb=new StringBuilder();\n sb.append(getClass().getSimpleName());\n sb.append(\" [\");\n sb.append(\"Hash = \").append(hashCode());\n sb.append(\", id=\").append(id);\n sb.append(\", migration=\").append(migration);\n sb.append(\", serialVersionUID=\").append(serialVersionUID);\n sb.append(\"]\");\n return sb.toString();\n}\n"}}, {"map": {"retrieved_name": "saveFromMap", "raw_body": "@Override public void saveFromMap(HashMap<String,String> data){\n Map<String,AppConfig> configs=list(query().getWrapper().in(\"key_name\",data.keySet())).stream().collect(Collectors.toMap(AppConfig::getKeyName,e -> e));\n List<AppConfig> list=new ArrayList<>();\n data.forEach((keyNameValue,keyValueValue) -> {\n if (keyValueValue == null) {\n return;\n }\n if (\"******\".equals(keyNameValue)) {\n return;\n }\n AppConfig configItem=configs.get(keyNameValue);\n if (configItem == null) {\n return;\n }\n if (keyValueValue.equals(configItem.getKeyValue())) {\n return;\n }\n list.add(new AppConfig(){\n{\n setId(configItem.getId());\n setKeyValue(keyValueValue);\n }\n }\n);\n }\n);\n if (!list.isEmpty()) {\n updateBatchById(list);\n }\n}\n"}}, {"stream": {"retrieved_name": "duration", "raw_body": "@Override public Integer duration(Integer id){\n ResourceVideo resourceVideo=resourceVideoService.getOne(resourceVideoService.query().getWrapper().eq(\"rid\",id));\n if (resourceVideo == null) {\n return null;\n }\n return resourceVideo.getDuration();\n}\n"}}] | [{"storeDepIds": {"retrieved_name": "storeDepIds", "raw_body": "void storeDepIds(Integer userId,Integer[] depIds);\n"}}] |
|
jeecgboot_jeecg-boot | jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/config/mybatis/ThreadLocalDataHelper.java | ThreadLocalDataHelper | get | class ThreadLocalDataHelper {
/**
* 线程的本地变量
*/
private static final ThreadLocal<ConcurrentHashMap> REQUEST_DATA = new ThreadLocal<>();
/**
* 存储本地参数
*/
private static final ConcurrentHashMap DATA_MAP = new ConcurrentHashMap<>();
/**
* 设置请求参数
*
* @param key 参数key
* @param value 参数值
*/
public static void put(String key, Object value) {
if(ObjectUtil.isNotEmpty(value)) {
DATA_MAP.put(key, value);
REQUEST_DATA.set(DATA_MAP);
}
}
/**
* 获取请求参数值
*
* @param key 请求参数
* @return
*/
public static <T> T get(String key) {<FILL_FUNCTION_BODY>}
/**
* 获取请求参数
*
* @return 请求参数 MAP 对象
*/
public static void clear() {
DATA_MAP.clear();
REQUEST_DATA.remove();
}
} |
ConcurrentHashMap dataMap = REQUEST_DATA.get();
if (CollectionUtils.isNotEmpty(dataMap)) {
return (T) dataMap.get(key);
}
return null;
|
return (T) DATA_MAP.get(key);
| [
"ConcurrentHashMap"
] | [
"get"
] | [
"ThreadLocal<ConcurrentHashMap>",
"ConcurrentHashMap"
] | [
"get",
"isNotEmpty"
] | {
"methods": [
"get"
],
"similar_methods": [
"get"
],
"types": [
"ConcurrentHashMap"
]
} | /**
* @Description : 查询过滤器,SQL拼接写法拆成独立工具类
* @author :qinfeng
* @date 20230904
*/
@Slf4j public class SqlConcatUtil {
/**
* 获取单个查询条件的值
* @param rule
* @param field
* @param value
* @param isString
* @return
*/
public static String getSingleSqlByRule( QueryRuleEnum rule, String field, Object value, boolean isString);
/**
* 报表获取查询条件 支持多数据源
* @param field
* @param alias
* @param value
* @param isString
* @param dataBaseType
* @return
*/
public static String getSingleQueryConditionSql( String field, String alias, Object value, boolean isString, String dataBaseType);
/**
* 获取单个查询条件的值
* @param rule
* @param field
* @param value
* @param isString
* @param dataBaseType
* @return
*/
private static String getSingleSqlByRule( QueryRuleEnum rule, String field, Object value, boolean isString, String dataBaseType);
/**
* 获取查询条件的值
* @param value
* @param isString
* @param dataBaseType
* @return
*/
private static String getFieldConditionValue(Object value,boolean isString,String dataBaseType);
private static String getInConditionValue(Object value,boolean isString);
/**
* 先根据值判断 走左模糊还是右模糊 最后如果值不带任何标识(*或者%),则再根据ruleEnum判断
* @param value
* @param ruleEnum
* @return
*/
private static String getLikeConditionValue(Object value,QueryRuleEnum ruleEnum);
/**
* 获取系统数据库类型
*/
private static String getDbType();
}
/**
* 查询Cookie
* @param request
* @param key
*/
private static Cookie get(HttpServletRequest request,String key){
Cookie[] arr_cookie=request.getCookies();
if (arr_cookie != null && arr_cookie.length > 0) {
for ( Cookie cookie : arr_cookie) {
if (cookie.getName().equals(key)) {
return cookie;
}
}
}
return null;
}
/**
* 查询Cookie
* @param request
* @param key
*/
private static Cookie get(HttpServletRequest request,String key){
Cookie[] arr_cookie=request.getCookies();
if (arr_cookie != null && arr_cookie.length > 0) {
for ( Cookie cookie : arr_cookie) {
if (cookie.getName().equals(key)) {
return cookie;
}
}
}
return null;
}
| public class SqlConcatUtil {
public static String getSingleSqlByRule( QueryRuleEnum rule, String field, Object value, boolean isString);
public static String getSingleQueryConditionSql( String field, String alias, Object value, boolean isString, String dataBaseType);
private static String getSingleSqlByRule( QueryRuleEnum rule, String field, Object value, boolean isString, String dataBaseType);
private static String getFieldConditionValue(Object value,boolean isString,String dataBaseType);
private static String getInConditionValue(Object value,boolean isString);
private static String getLikeConditionValue(Object value,QueryRuleEnum ruleEnum);
private static String getDbType();
}
/**
* 查询Cookie
* @param request
* @param key
*/
private static Cookie get(HttpServletRequest request,String key){
Cookie[] arr_cookie=request.getCookies();
if (arr_cookie != null && arr_cookie.length > 0) {
for ( Cookie cookie : arr_cookie) {
if (cookie.getName().equals(key)) {
return cookie;
}
}
}
return null;
}
/**
* 查询Cookie
* @param request
* @param key
*/
private static Cookie get(HttpServletRequest request,String key){
Cookie[] arr_cookie=request.getCookies();
if (arr_cookie != null && arr_cookie.length > 0) {
for ( Cookie cookie : arr_cookie) {
if (cookie.getName().equals(key)) {
return cookie;
}
}
}
return null;
}
| {"types": [{"ConcurrentHashMap": "SqlConcatUtil"}], "methods": [{"get": "get"}], "similar_methods": [{"get": "get"}]} | [{"ConcurrentHashMap": {"retrieved_name": "SqlConcatUtil", "raw_body": "/** \n * @Description : \u67e5\u8be2\u8fc7\u6ee4\u5668\uff0cSQL\u62fc\u63a5\u5199\u6cd5\u62c6\u6210\u72ec\u7acb\u5de5\u5177\u7c7b\n * @author :qinfeng\n * @date 20230904\n */\n@Slf4j public class SqlConcatUtil {\n /** \n * \u83b7\u53d6\u5355\u4e2a\u67e5\u8be2\u6761\u4ef6\u7684\u503c\n * @param rule\n * @param field\n * @param value\n * @param isString\n * @return\n */\n public static String getSingleSqlByRule( QueryRuleEnum rule, String field, Object value, boolean isString);\n /** \n * \u62a5\u8868\u83b7\u53d6\u67e5\u8be2\u6761\u4ef6 \u652f\u6301\u591a\u6570\u636e\u6e90\n * @param field\n * @param alias\n * @param value\n * @param isString\n * @param dataBaseType\n * @return\n */\n public static String getSingleQueryConditionSql( String field, String alias, Object value, boolean isString, String dataBaseType);\n /** \n * \u83b7\u53d6\u5355\u4e2a\u67e5\u8be2\u6761\u4ef6\u7684\u503c\n * @param rule\n * @param field\n * @param value\n * @param isString\n * @param dataBaseType\n * @return\n */\n private static String getSingleSqlByRule( QueryRuleEnum rule, String field, Object value, boolean isString, String dataBaseType);\n/** \n * \u83b7\u53d6\u67e5\u8be2\u6761\u4ef6\u7684\u503c\n * @param value\n * @param isString\n * @param dataBaseType\n * @return\n */\nprivate static String getFieldConditionValue(Object value,boolean isString,String dataBaseType);\nprivate static String getInConditionValue(Object value,boolean isString);\n/** \n * \u5148\u6839\u636e\u503c\u5224\u65ad \u8d70\u5de6\u6a21\u7cca\u8fd8\u662f\u53f3\u6a21\u7cca \u6700\u540e\u5982\u679c\u503c\u4e0d\u5e26\u4efb\u4f55\u6807\u8bc6(*\u6216\u8005%)\uff0c\u5219\u518d\u6839\u636eruleEnum\u5224\u65ad\n * @param value\n * @param ruleEnum\n * @return\n */\nprivate static String getLikeConditionValue(Object value,QueryRuleEnum ruleEnum);\n/** \n * \u83b7\u53d6\u7cfb\u7edf\u6570\u636e\u5e93\u7c7b\u578b\n */\nprivate static String getDbType();\n}\n", "raw_body_no_cmt": "public class SqlConcatUtil {\n public static String getSingleSqlByRule( QueryRuleEnum rule, String field, Object value, boolean isString);\n public static String getSingleQueryConditionSql( String field, String alias, Object value, boolean isString, String dataBaseType);\n private static String getSingleSqlByRule( QueryRuleEnum rule, String field, Object value, boolean isString, String dataBaseType);\nprivate static String getFieldConditionValue(Object value,boolean isString,String dataBaseType);\nprivate static String getInConditionValue(Object value,boolean isString);\nprivate static String getLikeConditionValue(Object value,QueryRuleEnum ruleEnum);\nprivate static String getDbType();\n}\n"}}] | [{"get": {"retrieved_name": "get", "raw_body": "/** \n * \u67e5\u8be2Cookie\n * @param request\n * @param key\n */\nprivate static Cookie get(HttpServletRequest request,String key){\n Cookie[] arr_cookie=request.getCookies();\n if (arr_cookie != null && arr_cookie.length > 0) {\n for ( Cookie cookie : arr_cookie) {\n if (cookie.getName().equals(key)) {\n return cookie;\n }\n }\n }\n return null;\n}\n"}}] | [{"get": {"retrieved_name": "get", "raw_body": "/** \n * \u67e5\u8be2Cookie\n * @param request\n * @param key\n */\nprivate static Cookie get(HttpServletRequest request,String key){\n Cookie[] arr_cookie=request.getCookies();\n if (arr_cookie != null && arr_cookie.length > 0) {\n for ( Cookie cookie : arr_cookie) {\n if (cookie.getName().equals(key)) {\n return cookie;\n }\n }\n }\n return null;\n}\n"}}] |
|
spring-cloud_spring-cloud-gateway | spring-cloud-gateway/spring-cloud-gateway-server-mvc/src/main/java/org/springframework/cloud/gateway/server/mvc/filter/AfterFilterFunctions.java | AfterFilterFunctions | dedupeHeaders | class AfterFilterFunctions {
private AfterFilterFunctions() {
}
public static BiFunction<ServerRequest, ServerResponse, ServerResponse> addResponseHeader(String name,
String... values) {
return (request, response) -> {
String[] expandedValues = MvcUtils.expandMultiple(request, values);
response.headers().addAll(name, Arrays.asList(expandedValues));
return response;
};
}
public static BiFunction<ServerRequest, ServerResponse, ServerResponse> dedupeResponseHeader(String name) {
return dedupeResponseHeader(name, DedupeStrategy.RETAIN_FIRST);
}
public static BiFunction<ServerRequest, ServerResponse, ServerResponse> dedupeResponseHeader(String name,
DedupeStrategy strategy) {
Assert.hasText(name, "name must not be null or empty");
Assert.notNull(strategy, "strategy must not be null");
return (request, response) -> {
dedupeHeaders(response.headers(), name, strategy);
return response;
};
}
private static void dedupeHeaders(HttpHeaders headers, String names, DedupeStrategy strategy) {<FILL_FUNCTION_BODY>}
private static void dedupeHeader(HttpHeaders headers, String name, DedupeStrategy strategy) {
List<String> values = headers.get(name);
if (values == null || values.size() <= 1) {
return;
}
switch (strategy) {
case RETAIN_FIRST:
headers.set(name, values.get(0));
break;
case RETAIN_LAST:
headers.set(name, values.get(values.size() - 1));
break;
case RETAIN_UNIQUE:
headers.put(name, new ArrayList<>(new LinkedHashSet<>(values)));
break;
default:
break;
}
}
public static BiFunction<ServerRequest, ServerResponse, ServerResponse> removeResponseHeader(String name) {
return (request, response) -> {
response.headers().remove(name);
return response;
};
}
public static BiFunction<ServerRequest, ServerResponse, ServerResponse> rewriteLocationResponseHeader() {
return RewriteLocationResponseHeaderFilterFunctions.rewriteLocationResponseHeader(config -> {
});
}
public static BiFunction<ServerRequest, ServerResponse, ServerResponse> rewriteLocationResponseHeader(
Consumer<RewriteLocationResponseHeaderFilterFunctions.RewriteLocationResponseHeaderConfig> configConsumer) {
return RewriteLocationResponseHeaderFilterFunctions.rewriteLocationResponseHeader(configConsumer);
}
public static BiFunction<ServerRequest, ServerResponse, ServerResponse> rewriteResponseHeader(String name,
String regexp, String originalReplacement) {
String replacement = originalReplacement.replace("$\\", "$");
Pattern pattern = Pattern.compile(regexp);
return (request, response) -> {
response.headers().computeIfPresent(name, (key, values) -> {
List<String> rewrittenValues = values.stream()
.map(value -> pattern.matcher(value).replaceAll(replacement)).toList();
return new ArrayList<>(rewrittenValues);
});
return response;
};
}
public static BiFunction<ServerRequest, ServerResponse, ServerResponse> setResponseHeader(String name,
String value) {
return (request, response) -> {
String expandedValue = MvcUtils.expand(request, value);
response.headers().set(name, expandedValue);
return response;
};
}
public static BiFunction<ServerRequest, ServerResponse, ServerResponse> setStatus(int statusCode) {
return setStatus(new HttpStatusHolder(null, statusCode));
}
public static BiFunction<ServerRequest, ServerResponse, ServerResponse> setStatus(String statusCode) {
return setStatus(HttpStatusHolder.valueOf(statusCode));
}
public static BiFunction<ServerRequest, ServerResponse, ServerResponse> setStatus(HttpStatusCode statusCode) {
return setStatus(new HttpStatusHolder(statusCode, null));
}
public static BiFunction<ServerRequest, ServerResponse, ServerResponse> setStatus(HttpStatusHolder statusCode) {
return (request, response) -> {
if (response instanceof GatewayServerResponse res) {
res.setStatusCode(statusCode.resolve());
}
return response;
};
}
public enum DedupeStrategy {
/**
* Default: Retain the first value only.
*/
RETAIN_FIRST,
/**
* Retain the last value only.
*/
RETAIN_LAST,
/**
* Retain all unique values in the order of their first encounter.
*/
RETAIN_UNIQUE
}
} |
if (headers == null || names == null || strategy == null) {
return;
}
String[] tokens = StringUtils.tokenizeToStringArray(names, " ", true, true);
for (String name : tokens) {
dedupeHeader(headers, name.trim(), strategy);
}
|
Arrays.stream(names.split(",")).forEach(name -> dedupeHeader(headers, name, strategy));
| [
"HttpHeaders",
"DedupeStrategy"
] | [
"stream",
"forEach",
"split"
] | [
"DedupeStrategy",
"HttpHeaders"
] | [
"tokenizeToStringArray",
"trim"
] | {
"methods": [
"stream",
"forEach",
"split"
],
"similar_methods": [
"dedupeHeaders"
],
"types": [
"HttpHeaders",
"DedupeStrategy"
]
} | public interface HttpHeadersFilter<TYPE> extends BiFunction<HttpHeaders,TYPE,HttpHeaders> {
interface RequestHttpHeadersFilter extends HttpHeadersFilter<ServerRequest> {
}
interface ResponseHttpHeadersFilter extends HttpHeadersFilter<ServerResponse> {
}
}
/**
* @author Vitaliy Pavlyuk
*/
public class DedupeResponseHeaderGatewayFilterFactory extends AbstractGatewayFilterFactory<DedupeResponseHeaderGatewayFilterFactory.Config> {
/**
* The name of the strategy key.
*/
public static final String STRATEGY_KEY="strategy";
public DedupeResponseHeaderGatewayFilterFactory();
@Override public List<String> shortcutFieldOrder();
@Override public GatewayFilter apply( Config config);
public enum Strategy { /**
* Default: Retain the first value only.
*/
RETAIN_FIRST, /**
* Retain the last value only.
*/
RETAIN_LAST, /**
* Retain all unique values in the order of their first encounter.
*/
RETAIN_UNIQUE}
void dedupe( HttpHeaders headers, Config config);
private void dedupe( HttpHeaders headers, String name, Strategy strategy);
public static class Config extends AbstractGatewayFilterFactory.NameConfig {
private Strategy strategy=Strategy.RETAIN_FIRST;
public Strategy getStrategy();
public Config setStrategy(Strategy strategy);
}
}
/**
* Return a stream of the contained parameters.
* @return a stream of the parameters
*/
Stream<OperationParameter> stream();
public boolean isForEnabled(){
return forEnabled;
}
@Override public DefaultUriBuilder fragment(@Nullable String fragment){
this.uriComponentsBuilder.fragment(fragment);
return this;
}
/**
* A filter that removes duplication on a response header before it is returned to the client by the Gateway.
* @param headerName the header name(s), space separated
* @param strategy RETAIN_FIRST, RETAIN_LAST, or RETAIN_UNIQUE
* @return a {@link GatewayFilterSpec} that can be used to apply additional filters
*/
public GatewayFilterSpec dedupeResponseHeader(String headerName,String strategy){
return filter(getBean(DedupeResponseHeaderGatewayFilterFactory.class).apply(c -> c.setStrategy(Strategy.valueOf(strategy)).setName(headerName)));
}
| public interface HttpHeadersFilter<TYPE> extends BiFunction<HttpHeaders,TYPE,HttpHeaders> {
interface RequestHttpHeadersFilter extends HttpHeadersFilter<ServerRequest> {
}
interface ResponseHttpHeadersFilter extends HttpHeadersFilter<ServerResponse> {
}
}
error/**
* Return a stream of the contained parameters.
* @return a stream of the parameters
*/
Stream<OperationParameter> stream();
public boolean isForEnabled(){
return forEnabled;
}
@Override public DefaultUriBuilder fragment(@Nullable String fragment){
this.uriComponentsBuilder.fragment(fragment);
return this;
}
/**
* A filter that removes duplication on a response header before it is returned to the client by the Gateway.
* @param headerName the header name(s), space separated
* @param strategy RETAIN_FIRST, RETAIN_LAST, or RETAIN_UNIQUE
* @return a {@link GatewayFilterSpec} that can be used to apply additional filters
*/
public GatewayFilterSpec dedupeResponseHeader(String headerName,String strategy){
return filter(getBean(DedupeResponseHeaderGatewayFilterFactory.class).apply(c -> c.setStrategy(Strategy.valueOf(strategy)).setName(headerName)));
}
| {"types": [{"HttpHeaders": "HttpHeadersFilter"}, {"DedupeStrategy": "DedupeResponseHeaderGatewayFilterFactory"}], "methods": [{"stream": "stream"}, {"forEach": "isForEnabled"}, {"split": "fragment"}], "similar_methods": [{"dedupeHeaders": "dedupeResponseHeader"}]} | [{"HttpHeaders": {"retrieved_name": "HttpHeadersFilter", "raw_body": "public interface HttpHeadersFilter<TYPE> extends BiFunction<HttpHeaders,TYPE,HttpHeaders> {\ninterface RequestHttpHeadersFilter extends HttpHeadersFilter<ServerRequest> {\n }\ninterface ResponseHttpHeadersFilter extends HttpHeadersFilter<ServerResponse> {\n }\n}\n", "raw_body_no_cmt": "public interface HttpHeadersFilter<TYPE> extends BiFunction<HttpHeaders,TYPE,HttpHeaders> {\ninterface RequestHttpHeadersFilter extends HttpHeadersFilter<ServerRequest> {\n }\ninterface ResponseHttpHeadersFilter extends HttpHeadersFilter<ServerResponse> {\n }\n}\n"}}, {"DedupeStrategy": {"retrieved_name": "DedupeResponseHeaderGatewayFilterFactory", "raw_body": "/** \n * @author Vitaliy Pavlyuk\n */\npublic class DedupeResponseHeaderGatewayFilterFactory extends AbstractGatewayFilterFactory<DedupeResponseHeaderGatewayFilterFactory.Config> {\n /** \n * The name of the strategy key.\n */\n public static final String STRATEGY_KEY=\"strategy\";\n public DedupeResponseHeaderGatewayFilterFactory();\n @Override public List<String> shortcutFieldOrder();\n @Override public GatewayFilter apply( Config config);\n public enum Strategy { /** \n * Default: Retain the first value only.\n */\n RETAIN_FIRST, /** \n * Retain the last value only.\n */\n RETAIN_LAST, /** \n * Retain all unique values in the order of their first encounter.\n */\n RETAIN_UNIQUE}\n void dedupe( HttpHeaders headers, Config config);\n private void dedupe( HttpHeaders headers, String name, Strategy strategy);\npublic static class Config extends AbstractGatewayFilterFactory.NameConfig {\nprivate Strategy strategy=Strategy.RETAIN_FIRST;\npublic Strategy getStrategy();\npublic Config setStrategy(Strategy strategy);\n}\n}\n", "raw_body_no_cmt": "error"}}] | [{"stream": {"retrieved_name": "stream", "raw_body": "/** \n * Return a stream of the contained parameters.\n * @return a stream of the parameters\n */\nStream<OperationParameter> stream();\n"}}, {"forEach": {"retrieved_name": "isForEnabled", "raw_body": "public boolean isForEnabled(){\n return forEnabled;\n}\n"}}, {"split": {"retrieved_name": "fragment", "raw_body": "@Override public DefaultUriBuilder fragment(@Nullable String fragment){\n this.uriComponentsBuilder.fragment(fragment);\n return this;\n}\n"}}] | [{"dedupeHeaders": {"retrieved_name": "dedupeResponseHeader", "raw_body": "/** \n * A filter that removes duplication on a response header before it is returned to the client by the Gateway.\n * @param headerName the header name(s), space separated\n * @param strategy RETAIN_FIRST, RETAIN_LAST, or RETAIN_UNIQUE\n * @return a {@link GatewayFilterSpec} that can be used to apply additional filters\n */\npublic GatewayFilterSpec dedupeResponseHeader(String headerName,String strategy){\n return filter(getBean(DedupeResponseHeaderGatewayFilterFactory.class).apply(c -> c.setStrategy(Strategy.valueOf(strategy)).setName(headerName)));\n}\n"}}] |
|
logfellow_logstash-logback-encoder | logstash-logback-encoder/src/main/java/net/logstash/logback/marker/SingleFieldAppendingMarker.java | SingleFieldAppendingMarker | hashCode | class SingleFieldAppendingMarker extends LogstashMarker implements StructuredArgument {
public static final String MARKER_NAME_PREFIX = LogstashMarker.MARKER_NAME_PREFIX + "APPEND_";
/**
* Name of the field to append.
*
* Note that the value of the field is provided by subclasses via {@link #writeFieldValue(JsonGenerator)}.
*/
private final String fieldName;
/**
* Pattern to use when appending the field/value in {@link #toString()}.
* <p>
* {@link #getFieldName()} will be substituted in {0}.
* {@link #getFieldValue()} will be substituted in {1}.
*/
private final String messageFormatPattern;
public SingleFieldAppendingMarker(String markerName, String fieldName) {
this(markerName, fieldName, StructuredArguments.DEFAULT_KEY_VALUE_MESSAGE_FORMAT_PATTERN);
}
public SingleFieldAppendingMarker(String markerName, String fieldName, String messageFormatPattern) {
super(markerName);
this.fieldName = Objects.requireNonNull(fieldName, "fieldName must not be null");
this.messageFormatPattern = Objects.requireNonNull(messageFormatPattern, "messageFormatPattern must not be null");
}
public String getFieldName() {
return fieldName;
}
public void writeTo(JsonGenerator generator) throws IOException {
writeFieldName(generator);
writeFieldValue(generator);
}
/**
* Writes the field name to the generator.
*
* @param generator the generator to write JSON
* @throws IOException if an I/O error occurs
*/
protected void writeFieldName(JsonGenerator generator) throws IOException {
generator.writeFieldName(getFieldName());
}
/**
* Writes the field value to the generator.
*
* @param generator the generator to write JSON
* @throws IOException if an I/O error occurs
*/
protected abstract void writeFieldValue(JsonGenerator generator) throws IOException;
@Override
public String toStringSelf() {
final String fieldValueString = StructuredArguments.toString(getFieldValue());
/*
* Optimize for commonly used messageFormatPattern
*/
if (StructuredArguments.VALUE_ONLY_MESSAGE_FORMAT_PATTERN.equals(messageFormatPattern)) {
return fieldValueString;
}
if (StructuredArguments.DEFAULT_KEY_VALUE_MESSAGE_FORMAT_PATTERN.equals(messageFormatPattern)) {
return getFieldName()
+ "="
+ fieldValueString;
}
/*
* Custom messageFormatPattern
*/
return MessageFormatCache.INSTANCE.getMessageFormat(this.messageFormatPattern)
.format(new Object[] {getFieldName(), fieldValueString});
}
/**
* Return the value that should be included in the output of {@link #toString()}.
*
* @return the field value
*/
protected abstract Object getFieldValue();
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!super.equals(obj)) {
return false;
}
if (!(obj instanceof SingleFieldAppendingMarker)) {
return false;
}
SingleFieldAppendingMarker other = (SingleFieldAppendingMarker) obj;
return this.fieldName.equals(other.fieldName);
}
@Override
public int hashCode() {<FILL_FUNCTION_BODY>}
} |
final int prime = 31;
int result = 1;
result = prime * result + super.hashCode();
result = prime * result + this.fieldName.hashCode();
return result;
| /**
* A {@link Marker} that is known and understood by the logstash logback encoder.<p> In particular these markers are used to write data into the logstash json event via {@link #writeTo(JsonGenerator)}.
*/
@SuppressWarnings("serial") public abstract class LogstashMarker extends LogstashBasicMarker implements Iterable<Marker> {
public static final String MARKER_NAME_PREFIX="LS_";
public LogstashMarker( String name);
/**
* Adds the given marker as a reference, and returns this marker. <p> This can be used to chain markers together fluently on a log line. For example: <pre> {@code import static net.logstash.logback.marker.Markers. logger.info(append("name1", "value1).and(append("name2", "value2")), "log message");}</pre>
* @param < T > subtype of LogstashMarker
* @param reference The marker to add
* @return A marker with this marker and the given marker
*/
@SuppressWarnings("unchecked") public <T extends LogstashMarker>T and( Marker reference);
/**
* @param < T > subtype of LogstashMarker
* @param reference The marker to add
* @deprecated Use {@link #and(Marker)} instead
* @see #and(Marker)
* @return A marker with this marker and the given marker
*/
@Deprecated public <T extends LogstashMarker>T with( Marker reference);
/**
* Writes the data associated with this marker to the given {@link JsonGenerator}.
* @param generator the generator to which to write the output of this marker.
* @throws IOException if there was an error writing to the generator
*/
public abstract void writeTo( JsonGenerator generator) throws IOException ;
@Override public void add( Marker reference);
/**
* Returns a String in the form of <pre> self, reference1, reference2, ... </pre> <p>Where <code>self</code> is the value returned by {@link #toStringSelf()}, and <code>reference*</code> are the <code>toString()</code> values of any references.</p> <p>It is recommended that subclasses only override {@link #toStringSelf()}, so that references are automatically included in the value returned from {@link #toString()}.</p>
* @return a string representation of the object, which includes references
*/
@Override public String toString();
/**
* Returns a string representation of this object, without including any references. <p>Subclasses should override {@link #toStringSelf()} instead of {@link #toString()}, since {@link #toString()} will automatically include the {@link #toStringSelf()} and references.</p>
* @return a string representation of this object, without including any references.
*/
protected String toStringSelf();
}
|
return super.hashCode() * 31 + fieldName.hashCode();
| [] | [
"hashCode"
] | [] | [
"hashCode"
] | {
"methods": [
"hashCode"
],
"similar_methods": [
"hashCode"
],
"types": []
} | /**
* {@inheritDoc}
*/
@Override public int hashCode(){
return name.hashCode();
}
/**
* {@inheritDoc}
*/
@Override public int hashCode(){
return name.hashCode();
}
| /**
* {@inheritDoc}
*/
@Override public int hashCode(){
return name.hashCode();
}
/**
* {@inheritDoc}
*/
@Override public int hashCode(){
return name.hashCode();
}
| {"methods": [{"hashCode": "hashCode"}], "similar_methods": [{"hashCode": "hashCode"}]} | [] | [{"hashCode": {"retrieved_name": "hashCode", "raw_body": "/** \n * {@inheritDoc}\n */\n@Override public int hashCode(){\n return name.hashCode();\n}\n"}}] | [{"hashCode": {"retrieved_name": "hashCode", "raw_body": "/** \n * {@inheritDoc}\n */\n@Override public int hashCode(){\n return name.hashCode();\n}\n"}}] |
jeecgboot_jeecg-boot | jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/config/WebSocketConfig.java | WebSocketConfig | getFilterRegistrationBean | class WebSocketConfig {
/**
* 注入ServerEndpointExporter,
* 这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint
*/
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
@Bean
public WebsocketFilter websocketFilter(){
return new WebsocketFilter();
}
@Bean
public FilterRegistrationBean getFilterRegistrationBean(){<FILL_FUNCTION_BODY>}
} |
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(websocketFilter());
//TODO 临时注释掉,测试下线上socket总断的问题
bean.addUrlPatterns("/taskCountSocket/*", "/websocket/*","/eoaSocket/*","/eoaNewChatSocket/*", "/newsWebsocket/*", "/vxeSocket/*");
return bean;
|
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(websocketFilter());
bean.addUrlPatterns("/*");
return bean;
| [
"FilterRegistrationBean"
] | [
"setFilter",
"addUrlPatterns"
] | [
"FilterRegistrationBean"
] | [
"addUrlPatterns",
"setFilter"
] | {
"methods": [
"setFilter",
"addUrlPatterns"
],
"similar_methods": [
"getFilterRegistrationBean"
],
"types": [
"FilterRegistrationBean"
]
} | /**
* 自定义ShiroFilterFactoryBean解决资源中文路径问题
* @author : jeecg-boot
*/
@Slf4j public class CustomShiroFilterFactoryBean extends ShiroFilterFactoryBean {
@Override public Class getObjectType();
@Override protected AbstractShiroFilter createInstance() throws Exception;
private static final class MySpringShiroFilter extends AbstractShiroFilter {
protected MySpringShiroFilter( WebSecurityManager webSecurityManager, FilterChainResolver resolver);
}
}
public void setField(String field){
this.field=field;
}
/**
* 将URL请求参数转换成Map
* @param queryString
*/
public static Map<String,String> getUrlParams(String queryString){
Map<String,String> result=new HashMap<>(16);
if (oConvertUtils.isEmpty(queryString)) {
return result;
}
String param="";
try {
param=URLDecoder.decode(queryString,"utf-8");
}
catch ( UnsupportedEncodingException e) {
e.printStackTrace();
}
String[] params=param.split("&");
for ( String s : params) {
int index=s.indexOf("=");
if (index != -1) {
result.put(s.substring(0,index),s.substring(index + 1));
}
}
return result;
}
@Bean public FilterRegistrationBean reqBodyFilterRegistrationBean(){
FilterRegistrationBean registration=new FilterRegistrationBean();
registration.setFilter(requestBodyReserveFilter());
registration.setName("requestBodyReserveFilter");
String signUrls=jeecgBaseConfig.getSignUrls();
String[] signUrlsArray=null;
if (StringUtils.isNotBlank(signUrls)) {
signUrlsArray=signUrls.split(",");
}
else {
signUrlsArray=PathMatcherUtil.SIGN_URL_LIST;
}
registration.addUrlPatterns(signUrlsArray);
return registration;
}
| public class CustomShiroFilterFactoryBean extends ShiroFilterFactoryBean {
public Class getObjectType();
protected AbstractShiroFilter createInstance() throws Exception;
private static final class MySpringShiroFilter extends AbstractShiroFilter {
protected MySpringShiroFilter( WebSecurityManager webSecurityManager, FilterChainResolver resolver);
}
}
public void setField(String field){
this.field=field;
}
/**
* 将URL请求参数转换成Map
* @param queryString
*/
public static Map<String,String> getUrlParams(String queryString){
Map<String,String> result=new HashMap<>(16);
if (oConvertUtils.isEmpty(queryString)) {
return result;
}
String param="";
try {
param=URLDecoder.decode(queryString,"utf-8");
}
catch ( UnsupportedEncodingException e) {
e.printStackTrace();
}
String[] params=param.split("&");
for ( String s : params) {
int index=s.indexOf("=");
if (index != -1) {
result.put(s.substring(0,index),s.substring(index + 1));
}
}
return result;
}
@Bean public FilterRegistrationBean reqBodyFilterRegistrationBean(){
FilterRegistrationBean registration=new FilterRegistrationBean();
registration.setFilter(requestBodyReserveFilter());
registration.setName("requestBodyReserveFilter");
String signUrls=jeecgBaseConfig.getSignUrls();
String[] signUrlsArray=null;
if (StringUtils.isNotBlank(signUrls)) {
signUrlsArray=signUrls.split(",");
}
else {
signUrlsArray=PathMatcherUtil.SIGN_URL_LIST;
}
registration.addUrlPatterns(signUrlsArray);
return registration;
}
| {"types": [{"FilterRegistrationBean": "CustomShiroFilterFactoryBean"}], "methods": [{"setFilter": "setField"}, {"addUrlPatterns": "getUrlParams"}], "similar_methods": [{"getFilterRegistrationBean": "reqBodyFilterRegistrationBean"}]} | [{"FilterRegistrationBean": {"retrieved_name": "CustomShiroFilterFactoryBean", "raw_body": "/** \n * \u81ea\u5b9a\u4e49ShiroFilterFactoryBean\u89e3\u51b3\u8d44\u6e90\u4e2d\u6587\u8def\u5f84\u95ee\u9898\n * @author : jeecg-boot\n */\n@Slf4j public class CustomShiroFilterFactoryBean extends ShiroFilterFactoryBean {\n @Override public Class getObjectType();\n @Override protected AbstractShiroFilter createInstance() throws Exception;\nprivate static final class MySpringShiroFilter extends AbstractShiroFilter {\n protected MySpringShiroFilter( WebSecurityManager webSecurityManager, FilterChainResolver resolver);\n }\n}\n", "raw_body_no_cmt": "public class CustomShiroFilterFactoryBean extends ShiroFilterFactoryBean {\n public Class getObjectType();\n protected AbstractShiroFilter createInstance() throws Exception;\nprivate static final class MySpringShiroFilter extends AbstractShiroFilter {\n protected MySpringShiroFilter( WebSecurityManager webSecurityManager, FilterChainResolver resolver);\n }\n}\n"}}] | [{"setFilter": {"retrieved_name": "setField", "raw_body": "public void setField(String field){\n this.field=field;\n}\n"}}, {"addUrlPatterns": {"retrieved_name": "getUrlParams", "raw_body": "/** \n * \u5c06URL\u8bf7\u6c42\u53c2\u6570\u8f6c\u6362\u6210Map\n * @param queryString\n */\npublic static Map<String,String> getUrlParams(String queryString){\n Map<String,String> result=new HashMap<>(16);\n if (oConvertUtils.isEmpty(queryString)) {\n return result;\n }\n String param=\"\";\n try {\n param=URLDecoder.decode(queryString,\"utf-8\");\n }\n catch ( UnsupportedEncodingException e) {\n e.printStackTrace();\n }\n String[] params=param.split(\"&\");\n for ( String s : params) {\n int index=s.indexOf(\"=\");\n if (index != -1) {\n result.put(s.substring(0,index),s.substring(index + 1));\n }\n }\n return result;\n}\n"}}] | [{"getFilterRegistrationBean": {"retrieved_name": "reqBodyFilterRegistrationBean", "raw_body": "@Bean public FilterRegistrationBean reqBodyFilterRegistrationBean(){\n FilterRegistrationBean registration=new FilterRegistrationBean();\n registration.setFilter(requestBodyReserveFilter());\n registration.setName(\"requestBodyReserveFilter\");\n String signUrls=jeecgBaseConfig.getSignUrls();\n String[] signUrlsArray=null;\n if (StringUtils.isNotBlank(signUrls)) {\n signUrlsArray=signUrls.split(\",\");\n }\n else {\n signUrlsArray=PathMatcherUtil.SIGN_URL_LIST;\n }\n registration.addUrlPatterns(signUrlsArray);\n return registration;\n}\n"}}] |
|
subhra74_snowflake | snowflake/muon-app/src/main/java/muon/app/ui/components/session/PuttyImporter.java | PuttyImporter | getKeyNames | class PuttyImporter {
private static final String PuttyREGKey = "Software\\SimonTatham\\PuTTY\\Sessions";
public static Map<String, String> getKeyNames() {<FILL_FUNCTION_BODY>}
public static void importSessions(DefaultMutableTreeNode node,
List<String> keys) {
// String[] keys =
// Advapi32Util.registryGetKeys(WinReg.HKEY_CURRENT_USER,
// PuttyREGKey);
for (String key : keys) {
if ("ssh".equals(RegUtil.regGetStr(WinReg.HKEY_CURRENT_USER,
PuttyREGKey + "\\" + key, "Protocol"))) {
String host = RegUtil.regGetStr(WinReg.HKEY_CURRENT_USER,
PuttyREGKey + "\\" + key, "HostName");
int port = RegUtil.regGetInt(WinReg.HKEY_CURRENT_USER,
PuttyREGKey + "\\" + key, "PortNumber");
String user = RegUtil.regGetStr(WinReg.HKEY_CURRENT_USER,
PuttyREGKey + "\\" + key, "UserName");
String keyfile = RegUtil.regGetStr(WinReg.HKEY_CURRENT_USER,
PuttyREGKey + "\\" + key, "PublicKeyFile");
String proxyHost = RegUtil.regGetStr(WinReg.HKEY_CURRENT_USER,
PuttyREGKey + "\\" + key, "ProxyHost");
int proxyPort = RegUtil.regGetInt(WinReg.HKEY_CURRENT_USER,
PuttyREGKey + "\\" + key, "ProxyPort");
String proxyUser = RegUtil.regGetStr(WinReg.HKEY_CURRENT_USER,
PuttyREGKey + "\\" + key, "ProxyUsername");
String proxyPass = RegUtil.regGetStr(WinReg.HKEY_CURRENT_USER,
PuttyREGKey + "\\" + key, "ProxyPassword");
int proxyType = RegUtil.regGetInt(WinReg.HKEY_CURRENT_USER,
PuttyREGKey + "\\" + key, "ProxyMethod");
if (proxyType == 1) {
proxyType = 2;
} else if (proxyType == 2) {
proxyType = 3;
} else if (proxyType == 3) {
proxyType = 1;
} else {
proxyType = 0;
}
SessionInfo info = new SessionInfo();
info.setName(key);
info.setHost(host);
info.setPort(port);
info.setUser(user);
info.setPrivateKeyFile(keyfile);
info.setProxyHost(proxyHost);
info.setProxyPort(proxyPort);
info.setProxyUser(proxyUser);
info.setProxyPassword(proxyPass);
info.setProxyType(proxyType);
DefaultMutableTreeNode node1 = new DefaultMutableTreeNode(info);
node1.setAllowsChildren(false);
node.add(node1);
}
}
}
} |
Map<String, String> map = new HashMap<String, String>();
try {
String[] keys = Advapi32Util
.registryGetKeys(WinReg.HKEY_CURRENT_USER, PuttyREGKey);
for (String key : keys) {
String decodedKey = key.replace("%20", " ");
map.put(key, decodedKey);
}
} catch (Exception e) {
e.printStackTrace();
}
return map;
|
return RegUtil.regGetKeys(WinReg.HKEY_CURRENT_USER, PuttyREGKey);
| [] | [
"regGetKeys"
] | [
"List<String>",
"Exception",
"Map<String,String>"
] | [
"put",
"registryGetKeys",
"printStackTrace",
"replace"
] | {
"methods": [
"regGetKeys"
],
"similar_methods": [
"getKeyNames"
],
"types": []
} | public static String regGetStr(WinReg.HKEY hkey,String key,String value){
try {
return Advapi32Util.registryGetStringValue(hkey,key,value);
}
catch ( Exception e) {
}
return null;
}
public static Map<String,String> getKeyNames(){
Map<String,String> map=new HashMap<String,String>();
try {
String[] keys=Advapi32Util.registryGetKeys(WinReg.HKEY_CURRENT_USER,WinSCPRegKey);
for ( String key : keys) {
String decodedKey=key.replace("%20"," ");
map.put(key,decodedKey);
}
}
catch ( Exception e) {
e.printStackTrace();
}
System.out.println(map);
return map;
}
| public static String regGetStr(WinReg.HKEY hkey,String key,String value){
try {
return Advapi32Util.registryGetStringValue(hkey,key,value);
}
catch ( Exception e) {
}
return null;
}
public static Map<String,String> getKeyNames(){
Map<String,String> map=new HashMap<String,String>();
try {
String[] keys=Advapi32Util.registryGetKeys(WinReg.HKEY_CURRENT_USER,WinSCPRegKey);
for ( String key : keys) {
String decodedKey=key.replace("%20"," ");
map.put(key,decodedKey);
}
}
catch ( Exception e) {
e.printStackTrace();
}
System.out.println(map);
return map;
}
| {"methods": [{"regGetKeys": "regGetStr"}], "similar_methods": [{"getKeyNames": "getKeyNames"}]} | [] | [{"regGetKeys": {"retrieved_name": "regGetStr", "raw_body": "public static String regGetStr(WinReg.HKEY hkey,String key,String value){\n try {\n return Advapi32Util.registryGetStringValue(hkey,key,value);\n }\n catch ( Exception e) {\n }\n return null;\n}\n"}}] | [{"getKeyNames": {"retrieved_name": "getKeyNames", "raw_body": "public static Map<String,String> getKeyNames(){\n Map<String,String> map=new HashMap<String,String>();\n try {\n String[] keys=Advapi32Util.registryGetKeys(WinReg.HKEY_CURRENT_USER,WinSCPRegKey);\n for ( String key : keys) {\n String decodedKey=key.replace(\"%20\",\" \");\n map.put(key,decodedKey);\n }\n }\n catch ( Exception e) {\n e.printStackTrace();\n }\n System.out.println(map);\n return map;\n}\n"}}] |
|
graphhopper_graphhopper | graphhopper/core/src/main/java/com/graphhopper/routing/util/countryrules/europe/SanMarinoCountryRule.java | SanMarinoCountryRule | getToll | class SanMarinoCountryRule implements CountryRule {
@Override
public Toll getToll(ReaderWay readerWay, Toll currentToll) {<FILL_FUNCTION_BODY>}
} |
if (currentToll != Toll.MISSING) {
return currentToll;
}
return Toll.NO;
|
return new Toll(0, 0);
| [
"ReaderWay",
"Toll"
] | [] | [
"Toll",
"ReaderWay"
] | [] | {
"methods": [],
"similar_methods": [
"getToll"
],
"types": [
"ReaderWay",
"Toll"
]
} | /**
* Represents a way received from the reader. <p>
* @author Nop
*/
public class ReaderWay extends ReaderElement {
protected final LongArrayList nodes=new LongArrayList(5);
public ReaderWay( long id);
public LongArrayList getNodes();
@Override public String toString();
}
/**
* This enum defines the toll value like MISSING (default), NO (no toll), HGV (toll for heavy goods vehicles) and ALL (all vehicles)
*/
public enum Toll {MISSING, NO, HGV, ALL; public static final String KEY="toll";
public static EnumEncodedValue<Toll> create(){
return new EnumEncodedValue<>(KEY,Toll.class);
}
@Override public String toString(){
return Helper.toLowerCase(super.toString());
}
}
@Override public Toll getToll(ReaderWay readerWay,Toll currentToll){
if (currentToll != Toll.MISSING) {
return currentToll;
}
return Toll.NO;
}
| public class ReaderWay extends ReaderElement {
protected final LongArrayList nodes=new LongArrayList(5);
public ReaderWay( long id);
public LongArrayList getNodes();
public String toString();
}
/**
* This enum defines the toll value like MISSING (default), NO (no toll), HGV (toll for heavy goods vehicles) and ALL (all vehicles)
*/
public enum Toll {MISSING, NO, HGV, ALL; public static final String KEY="toll";
public static EnumEncodedValue<Toll> create(){
return new EnumEncodedValue<>(KEY,Toll.class);
}
@Override public String toString(){
return Helper.toLowerCase(super.toString());
}
}
@Override public Toll getToll(ReaderWay readerWay,Toll currentToll){
if (currentToll != Toll.MISSING) {
return currentToll;
}
return Toll.NO;
}
| {"types": [{"ReaderWay": "ReaderWay"}, {"Toll": "Toll"}], "similar_methods": [{"getToll": "getToll"}]} | [{"ReaderWay": {"retrieved_name": "ReaderWay", "raw_body": "/** \n * Represents a way received from the reader. <p>\n * @author Nop\n */\npublic class ReaderWay extends ReaderElement {\n protected final LongArrayList nodes=new LongArrayList(5);\n public ReaderWay( long id);\n public LongArrayList getNodes();\n @Override public String toString();\n}\n", "raw_body_no_cmt": "public class ReaderWay extends ReaderElement {\n protected final LongArrayList nodes=new LongArrayList(5);\n public ReaderWay( long id);\n public LongArrayList getNodes();\n public String toString();\n}\n"}}, {"Toll": {"retrieved_name": "Toll", "raw_body": "/** \n * This enum defines the toll value like MISSING (default), NO (no toll), HGV (toll for heavy goods vehicles) and ALL (all vehicles)\n */\npublic enum Toll {MISSING, NO, HGV, ALL; public static final String KEY=\"toll\";\npublic static EnumEncodedValue<Toll> create(){\n return new EnumEncodedValue<>(KEY,Toll.class);\n}\n@Override public String toString(){\n return Helper.toLowerCase(super.toString());\n}\n}\n", "raw_body_no_cmt": "/** \n * This enum defines the toll value like MISSING (default), NO (no toll), HGV (toll for heavy goods vehicles) and ALL (all vehicles)\n */\npublic enum Toll {MISSING, NO, HGV, ALL; public static final String KEY=\"toll\";\npublic static EnumEncodedValue<Toll> create(){\n return new EnumEncodedValue<>(KEY,Toll.class);\n}\n@Override public String toString(){\n return Helper.toLowerCase(super.toString());\n}\n}\n"}}] | [] | [{"getToll": {"retrieved_name": "getToll", "raw_body": "@Override public Toll getToll(ReaderWay readerWay,Toll currentToll){\n if (currentToll != Toll.MISSING) {\n return currentToll;\n }\n return Toll.NO;\n}\n"}}] |
|
jitsi_jitsi | jitsi/modules/plugin/notificationconfiguration/src/main/java/net/java/sip/communicator/plugin/notificationconfiguration/SoundFilter.java | SoundFilter | getDescription | class SoundFilter
extends SipCommFileFilter
{
/**
* All acceptable sound formats. If null, then this sound filter will accept
* all sound formats available in SoundFileUtils.
*/
private String[] soundFormats = null;
/**
* Creates a new sound filter which accepts all sound format available in
* SoundFileUtils.
*/
public SoundFilter()
{
super();
}
/**
* Creates a new sound filter which accepts only sound format corresponding
* to the list given in parameter.
*
* @param soundFormats The list of sound format to accept.
*/
public SoundFilter(String[] soundFormats)
{
super();
if(soundFormats != null)
{
this.soundFormats = new String[soundFormats.length];
System.arraycopy(
soundFormats,
0,
this.soundFormats,
0,
soundFormats.length);
}
}
/**
* Method which describes differents permits extensions and defines which
* file or directory will be displayed in the filechoser.
*
* @param f file for the test
*
* @return boolean true if the File is a Directory or a sound file. And
* return false in the other cases.
*/
@Override
public boolean accept(File f)
{
// Tests if the file passed in argument is a directory.
if (f.isDirectory())
{
return true;
}
// Else, tests if the exension is correct.
else
{
return SoundFileUtils.isSoundFile(f, this.soundFormats);
}
}
/**
* Method which describes, in the file chooser, the text representing the
* permit extension files.
*
* @return String which is displayed in the sound file chooser.
*/
@Override
public String getDescription()
{<FILL_FUNCTION_BODY>}
} |
String desc = "Sound File (";
if(this.soundFormats != null)
{
for(int i = 0; i < this.soundFormats.length; ++i)
{
if(i != 0)
{
desc += ", ";
}
desc += "*." + this.soundFormats[i];
}
}
else
{
desc += "*.au, *.mid, *.mod, *.mp2, *.mp3, *.ogg, *.ram, *.wav, "
+ "*.wma";
}
desc += ")";
return desc;
| /**
* The purpose of this interface is to provide an generic file filter type for the SipCommFileChooser, which is used either as an AWT FileDialog, either as a Swing JFileChooser. Both of these dialogs use their own filter type, FileFilter (class) for JFileChooser and FilenameFilter (interface) for FileDialog. SipCommFileFilter acts as both an implementation and an heritage from these two filters. To use a your own file filter with a SipCommFileChooser, you just have to extend from SipCommFileFilter and redefine at least the method 'public boolean accept(File f)' which is described in the Java FileFilter class. You won't have to redefine 'public boolean accept(File dir, String name)' from the Java FilenameFilter interface since it's done here: the method is transfered toward the accept method of Java FileFilter class.
* @author Valentin Martinet
*/
public abstract class SipCommFileFilter extends FileFilter implements FilenameFilter {
/**
* Avoid to be obliged to implement 'public boolean accept(File dir, String name)' in your own file filter.
* @param dir file's parent directory
* @param name file's name
* @return boolean if the file is accepted or not
*/
public boolean accept( File dir, String name);
}
|
return "Sound files";
| [] | [] | [] | [] | {
"methods": [],
"similar_methods": [
"getDescription"
],
"types": []
} | /**
* Returns the description of the corresponding smack property.
* @return the description of the corresponding smack property
*/
public String getDescription(){
return smackFormField.getDescription();
}
| /**
* Returns the description of the corresponding smack property.
* @return the description of the corresponding smack property
*/
public String getDescription(){
return smackFormField.getDescription();
}
| {"similar_methods": [{"getDescription": "getDescription"}]} | [] | [] | [{"getDescription": {"retrieved_name": "getDescription", "raw_body": "/** \n * Returns the description of the corresponding smack property.\n * @return the description of the corresponding smack property\n */\npublic String getDescription(){\n return smackFormField.getDescription();\n}\n"}}] |
graphhopper_graphhopper | graphhopper/core/src/main/java/com/graphhopper/reader/osm/pbf/PbfDecoder.java | PbfDecoder | processBlobs | class PbfDecoder {
private final PbfStreamSplitter streamSplitter;
private final ExecutorService executorService;
private final int maxPendingBlobs;
private final Sink sink;
private final Lock lock;
private final Condition dataWaitCondition;
private final Queue<PbfBlobResult> blobResults;
private final SkipOptions skipOptions;
/**
* Creates a new instance.
* <p>
*
* @param streamSplitter The PBF stream splitter providing the source of blobs to be decoded.
* @param executorService The executor service managing the thread pool.
* @param maxPendingBlobs The maximum number of blobs to have in progress at any point in time.
* @param sink The sink to send all decoded entities to.
*/
public PbfDecoder(PbfStreamSplitter streamSplitter, ExecutorService executorService, int maxPendingBlobs,
Sink sink, SkipOptions skipOptions) {
this.streamSplitter = streamSplitter;
this.executorService = executorService;
this.maxPendingBlobs = maxPendingBlobs;
this.sink = sink;
this.skipOptions = skipOptions;
// Create the thread synchronisation primitives.
lock = new ReentrantLock();
dataWaitCondition = lock.newCondition();
// Create the queue of blobs being decoded.
blobResults = new LinkedList<>();
}
/**
* Any thread can call this method when they wish to wait until an update has been performed by
* another thread.
*/
private void waitForUpdate() {
try {
dataWaitCondition.await();
} catch (InterruptedException e) {
throw new RuntimeException("Thread was interrupted.", e);
}
}
/**
* Any thread can call this method when they wish to signal another thread that an update has
* occurred.
*/
private void signalUpdate() {
dataWaitCondition.signal();
}
private void sendResultsToSink(int targetQueueSize) {
while (blobResults.size() > targetQueueSize) {
// Get the next result from the queue and wait for it to complete.
PbfBlobResult blobResult = blobResults.remove();
while (!blobResult.isComplete()) {
// The thread hasn't finished processing yet so wait for an
// update from another thread before checking again.
waitForUpdate();
}
if (!blobResult.isSuccess()) {
throw new RuntimeException("A PBF decoding worker thread failed, aborting.", blobResult.getException());
}
// Send the processed entities to the sink. We can release the lock
// for the duration of processing to allow worker threads to post
// their results.
lock.unlock();
try {
for (ReaderElement entity : blobResult.getEntities()) {
sink.process(entity);
}
} finally {
lock.lock();
}
}
}
private void processBlobs() {<FILL_FUNCTION_BODY>}
public void run() {
lock.lock();
try {
processBlobs();
} finally {
lock.unlock();
}
}
} |
// Process until the PBF stream is exhausted.
while (streamSplitter.hasNext()) {
// Obtain the next raw blob from the PBF stream.
PbfRawBlob rawBlob = streamSplitter.next();
// Create the result object to capture the results of the decoded
// blob and add it to the blob results queue.
final PbfBlobResult blobResult = new PbfBlobResult();
blobResults.add(blobResult);
// Create the listener object that will update the blob results
// based on an event fired by the blob decoder.
PbfBlobDecoderListener decoderListener = new PbfBlobDecoderListener() {
@Override
public void error(Exception ex) {
lock.lock();
try {
// System.out.println("ERROR: " + new Date());
blobResult.storeFailureResult(ex);
signalUpdate();
} finally {
lock.unlock();
}
}
@Override
public void complete(List<ReaderElement> decodedEntities) {
lock.lock();
try {
blobResult.storeSuccessResult(decodedEntities);
signalUpdate();
} finally {
lock.unlock();
}
}
};
// Create the blob decoder itself and execute it on a worker thread.
PbfBlobDecoder blobDecoder = new PbfBlobDecoder(rawBlob.getType(), rawBlob.getData(), decoderListener, skipOptions);
executorService.execute(blobDecoder);
// If the number of pending blobs has reached capacity we must begin
// sending results to the sink. This method will block until blob
// decoding is complete.
sendResultsToSink(maxPendingBlobs - 1);
}
// There are no more entities available in the PBF stream, so send all remaining data to the sink.
sendResultsToSink(0);
|
// Process blobs until the stream splitter is exhausted.
while (streamSplitter.hasNext()) {
// Get the next blob from the stream splitter.
PbfBlob blob = streamSplitter.next();
// If the blob is a header blob then skip it.
if (blob.isHeader()) {
continue;
}
// If the blob is a delta blob then skip it.
if (blob.isDelta()) {
continue;
}
// If the blob is a complete blob then skip it.
if (blob.isComplete()) {
continue;
}
// If the blob is a partial blob then skip it.
if (blob.isPartial()) {
continue;
}
// If the blob is a data blob then skip it.
if (blob.isData()) {
continue;
}
// If the blob is a string table blob then skip it.
if (blob.isStringTable()) {
continue;
}
// If the blob is a node blob then skip it.
if (blob.isNode()) {
continue;
}
// If the blob is a way blob then skip it.
if (blob.isWay()) {
continue;
}
// If the blob is a relation blob then skip it.
if (blob.isRelation()) {
continue;
}
// If the blob is a node blob then skip it.
if (blob.isNode()) {
continue;
} | [
"PbfStreamSplitter",
"PbfBlob"
] | [
"isNode",
"isRelation",
"isData",
"isComplete",
"next",
"isDelta",
"isHeader",
"hasNext",
"isStringTable",
"isPartial",
"isWay"
] | [
"PbfBlobDecoder",
"ExecutorService",
"PbfStreamSplitter",
"PbfBlobResult",
"SkipOptions",
"Queue<PbfBlobResult>",
"PbfRawBlob",
"Exception",
"List<ReaderElement>",
"Lock",
"PbfBlobDecoderListener"
] | [
"getData",
"add",
"storeSuccessResult",
"storeFailureResult",
"hasNext",
"lock",
"unlock",
"getType",
"execute",
"next"
] | {
"methods": [
"isNode",
"isRelation",
"isData",
"isComplete",
"next",
"isDelta",
"isHeader",
"hasNext",
"isStringTable",
"isPartial",
"isWay"
],
"similar_methods": [
"processBlobs"
],
"types": [
"PbfStreamSplitter",
"PbfBlob"
]
} | /**
* Parses a PBF data stream and extracts the raw data of each blob in sequence until the end of the stream is reached. <p>
* @author Brett Henderson
*/
public class PbfStreamSplitter implements Iterator<PbfRawBlob> {
private static Logger log=Logger.getLogger(PbfStreamSplitter.class.getName());
private DataInputStream dis;
private int dataBlockCount;
private boolean eof;
private PbfRawBlob nextBlob;
/**
* Creates a new instance. <p>
* @param pbfStream The PBF data stream to be parsed.
*/
public PbfStreamSplitter( DataInputStream pbfStream);
private Fileformat.BlobHeader readHeader( int headerLength) throws IOException;
private byte[] readRawBlob( Fileformat.BlobHeader blobHeader) throws IOException;
private void getNextBlob();
@Override public boolean hasNext();
@Override public PbfRawBlob next();
@Override public void remove();
public void release();
}
/**
* Represents a single piece of raw blob data extracted from the PBF stream. It has not yet been decoded into a PBF blob object. <p>
* @author Brett Henderson
*/
public class PbfRawBlob {
private String type;
private byte[] data;
/**
* Creates a new instance. <p>
* @param type The type of data represented by this blob. This corresponds to the type field inthe blob header.
* @param data The raw contents of the blob in binary undecoded form.
*/
public PbfRawBlob( String type, byte[] data);
/**
* Gets the type of data represented by this blob. This corresponds to the type field in the blob header. <p>
* @return The blob type.
*/
public String getType();
/**
* Gets the raw contents of the blob in binary undecoded form. <p>
* @return The raw blob data.
*/
public byte[] getData();
}
private boolean isVirtualNode(int node){
return node >= routingCHGraph.getNodes();
}
public boolean isMetaRelation(){
if (members != null) for ( Member member : members) {
if (member.getType() == Type.RELATION) {
return true;
}
}
return false;
}
public boolean isFound(){
return found;
}
/**
* Gets the complete flag. <p>
* @return True if complete.
*/
public boolean isComplete(){
return complete;
}
@Override public void next(EdgeIteratorState edge,int index,int prevEdgeId){
for ( PathDetailsBuilder calc : calculators) {
if (calc.isEdgeDifferentToLastEdge(edge)) {
calc.endInterval(lastIndex);
calc.startInterval(lastIndex);
}
}
lastIndex+=edge.fetchWayGeometry(FetchMode.PILLAR_AND_ADJ).size();
}
public boolean isInternal(){
return internal;
}
private static String getHeader(TreeSet<String> keys){
StringBuilder sb=new StringBuilder("#");
for ( String key : keys) {
sb.append(key).append(";");
}
sb.append("\n");
return sb.toString();
}
private boolean hasNext(){
return !dfsStack.isEmpty();
}
public static String isToString(InputStream inputStream) throws IOException {
int size=1024 * 8;
String encoding="UTF-8";
InputStream in=new BufferedInputStream(inputStream,size);
try {
byte[] buffer=new byte[size];
ByteArrayOutputStream output=new ByteArrayOutputStream();
int numRead;
while ((numRead=in.read(buffer)) != -1) {
output.write(buffer,0,numRead);
}
return output.toString(encoding);
}
finally {
in.close();
}
}
public boolean isInternal(){
return internal;
}
public boolean isWay(){
return this.ordinal() == WAY.ordinal();
}
private void processNodes(Osmformat.DenseNodes nodes,PbfFieldDecoder fieldDecoder){
List<Long> idList=nodes.getIdList();
List<Long> latList=nodes.getLatList();
List<Long> lonList=nodes.getLonList();
if (checkData) {
if ((idList.size() != latList.size()) || (idList.size() != lonList.size())) {
throw new RuntimeException("Number of ids (" + idList.size() + "), latitudes ("+ latList.size()+ "), and longitudes ("+ lonList.size()+ ") don't match");
}
}
Iterator<Integer> keysValuesIterator=nodes.getKeysValsList().iterator();
long nodeId=0;
long latitude=0;
long longitude=0;
for (int i=0; i < idList.size(); i++) {
nodeId+=idList.get(i);
latitude+=latList.get(i);
longitude+=lonList.get(i);
Map<String,Object> tags=null;
while (keysValuesIterator.hasNext()) {
int keyIndex=keysValuesIterator.next();
if (keyIndex == 0) {
break;
}
if (checkData) {
if (!keysValuesIterator.hasNext()) {
throw new RuntimeException("The PBF DenseInfo keys/values list contains a key with no corresponding value.");
}
}
int valueIndex=keysValuesIterator.next();
if (tags == null) {
tags=new HashMap<>(Math.max(3,2 * (nodes.getKeysValsList().size() / 2) / idList.size()));
}
tags.put(fieldDecoder.decodeString(keyIndex),fieldDecoder.decodeString(valueIndex));
}
ReaderNode node=new ReaderNode(nodeId,fieldDecoder.decodeLatitude(latitude),fieldDecoder.decodeLongitude(longitude));
node.setTags(tags);
decodedEntities.add(node);
}
}
| public class PbfStreamSplitter implements Iterator<PbfRawBlob> {
private static Logger log=Logger.getLogger(PbfStreamSplitter.class.getName());
private DataInputStream dis;
private int dataBlockCount;
private boolean eof;
private PbfRawBlob nextBlob;
public PbfStreamSplitter( DataInputStream pbfStream);
private Fileformat.BlobHeader readHeader( int headerLength) throws IOException;
private byte[] readRawBlob( Fileformat.BlobHeader blobHeader) throws IOException;
private void getNextBlob();
public boolean hasNext();
public PbfRawBlob next();
public void remove();
public void release();
}
public class PbfRawBlob {
private String type;
private byte[] data;
public PbfRawBlob( String type, byte[] data);
public String getType();
public byte[] getData();
}
private boolean isVirtualNode(int node){
return node >= routingCHGraph.getNodes();
}
public boolean isMetaRelation(){
if (members != null) for ( Member member : members) {
if (member.getType() == Type.RELATION) {
return true;
}
}
return false;
}
public boolean isFound(){
return found;
}
/**
* Gets the complete flag. <p>
* @return True if complete.
*/
public boolean isComplete(){
return complete;
}
@Override public void next(EdgeIteratorState edge,int index,int prevEdgeId){
for ( PathDetailsBuilder calc : calculators) {
if (calc.isEdgeDifferentToLastEdge(edge)) {
calc.endInterval(lastIndex);
calc.startInterval(lastIndex);
}
}
lastIndex+=edge.fetchWayGeometry(FetchMode.PILLAR_AND_ADJ).size();
}
public boolean isInternal(){
return internal;
}
private static String getHeader(TreeSet<String> keys){
StringBuilder sb=new StringBuilder("#");
for ( String key : keys) {
sb.append(key).append(";");
}
sb.append("\n");
return sb.toString();
}
private boolean hasNext(){
return !dfsStack.isEmpty();
}
public static String isToString(InputStream inputStream) throws IOException {
int size=1024 * 8;
String encoding="UTF-8";
InputStream in=new BufferedInputStream(inputStream,size);
try {
byte[] buffer=new byte[size];
ByteArrayOutputStream output=new ByteArrayOutputStream();
int numRead;
while ((numRead=in.read(buffer)) != -1) {
output.write(buffer,0,numRead);
}
return output.toString(encoding);
}
finally {
in.close();
}
}
public boolean isInternal(){
return internal;
}
public boolean isWay(){
return this.ordinal() == WAY.ordinal();
}
private void processNodes(Osmformat.DenseNodes nodes,PbfFieldDecoder fieldDecoder){
List<Long> idList=nodes.getIdList();
List<Long> latList=nodes.getLatList();
List<Long> lonList=nodes.getLonList();
if (checkData) {
if ((idList.size() != latList.size()) || (idList.size() != lonList.size())) {
throw new RuntimeException("Number of ids (" + idList.size() + "), latitudes ("+ latList.size()+ "), and longitudes ("+ lonList.size()+ ") don't match");
}
}
Iterator<Integer> keysValuesIterator=nodes.getKeysValsList().iterator();
long nodeId=0;
long latitude=0;
long longitude=0;
for (int i=0; i < idList.size(); i++) {
nodeId+=idList.get(i);
latitude+=latList.get(i);
longitude+=lonList.get(i);
Map<String,Object> tags=null;
while (keysValuesIterator.hasNext()) {
int keyIndex=keysValuesIterator.next();
if (keyIndex == 0) {
break;
}
if (checkData) {
if (!keysValuesIterator.hasNext()) {
throw new RuntimeException("The PBF DenseInfo keys/values list contains a key with no corresponding value.");
}
}
int valueIndex=keysValuesIterator.next();
if (tags == null) {
tags=new HashMap<>(Math.max(3,2 * (nodes.getKeysValsList().size() / 2) / idList.size()));
}
tags.put(fieldDecoder.decodeString(keyIndex),fieldDecoder.decodeString(valueIndex));
}
ReaderNode node=new ReaderNode(nodeId,fieldDecoder.decodeLatitude(latitude),fieldDecoder.decodeLongitude(longitude));
node.setTags(tags);
decodedEntities.add(node);
}
}
| {"types": [{"PbfStreamSplitter": "PbfStreamSplitter"}, {"PbfBlob": "PbfRawBlob"}], "methods": [{"isNode": "isVirtualNode"}, {"isRelation": "isMetaRelation"}, {"isData": "isFound"}, {"isComplete": "isComplete"}, {"next": "next"}, {"isDelta": "isInternal"}, {"isHeader": "getHeader"}, {"hasNext": "hasNext"}, {"isStringTable": "isToString"}, {"isPartial": "isInternal"}, {"isWay": "isWay"}], "similar_methods": [{"processBlobs": "processNodes"}]} | [{"PbfStreamSplitter": {"retrieved_name": "PbfStreamSplitter", "raw_body": "/** \n * Parses a PBF data stream and extracts the raw data of each blob in sequence until the end of the stream is reached. <p>\n * @author Brett Henderson\n */\npublic class PbfStreamSplitter implements Iterator<PbfRawBlob> {\n private static Logger log=Logger.getLogger(PbfStreamSplitter.class.getName());\n private DataInputStream dis;\n private int dataBlockCount;\n private boolean eof;\n private PbfRawBlob nextBlob;\n /** \n * Creates a new instance. <p>\n * @param pbfStream The PBF data stream to be parsed.\n */\n public PbfStreamSplitter( DataInputStream pbfStream);\n private Fileformat.BlobHeader readHeader( int headerLength) throws IOException;\n private byte[] readRawBlob( Fileformat.BlobHeader blobHeader) throws IOException;\n private void getNextBlob();\n @Override public boolean hasNext();\n @Override public PbfRawBlob next();\n @Override public void remove();\n public void release();\n}\n", "raw_body_no_cmt": "public class PbfStreamSplitter implements Iterator<PbfRawBlob> {\n private static Logger log=Logger.getLogger(PbfStreamSplitter.class.getName());\n private DataInputStream dis;\n private int dataBlockCount;\n private boolean eof;\n private PbfRawBlob nextBlob;\n public PbfStreamSplitter( DataInputStream pbfStream);\n private Fileformat.BlobHeader readHeader( int headerLength) throws IOException;\n private byte[] readRawBlob( Fileformat.BlobHeader blobHeader) throws IOException;\n private void getNextBlob();\n public boolean hasNext();\n public PbfRawBlob next();\n public void remove();\n public void release();\n}\n"}}, {"PbfBlob": {"retrieved_name": "PbfRawBlob", "raw_body": "/** \n * Represents a single piece of raw blob data extracted from the PBF stream. It has not yet been decoded into a PBF blob object. <p>\n * @author Brett Henderson\n */\npublic class PbfRawBlob {\n private String type;\n private byte[] data;\n /** \n * Creates a new instance. <p>\n * @param type The type of data represented by this blob. This corresponds to the type field inthe blob header.\n * @param data The raw contents of the blob in binary undecoded form.\n */\n public PbfRawBlob( String type, byte[] data);\n /** \n * Gets the type of data represented by this blob. This corresponds to the type field in the blob header. <p>\n * @return The blob type.\n */\n public String getType();\n /** \n * Gets the raw contents of the blob in binary undecoded form. <p>\n * @return The raw blob data.\n */\n public byte[] getData();\n}\n", "raw_body_no_cmt": "public class PbfRawBlob {\n private String type;\n private byte[] data;\n public PbfRawBlob( String type, byte[] data);\n public String getType();\n public byte[] getData();\n}\n"}}] | [{"isNode": {"retrieved_name": "isVirtualNode", "raw_body": "private boolean isVirtualNode(int node){\n return node >= routingCHGraph.getNodes();\n}\n"}}, {"isRelation": {"retrieved_name": "isMetaRelation", "raw_body": "public boolean isMetaRelation(){\n if (members != null) for ( Member member : members) {\n if (member.getType() == Type.RELATION) {\n return true;\n }\n }\n return false;\n}\n"}}, {"isData": {"retrieved_name": "isFound", "raw_body": "public boolean isFound(){\n return found;\n}\n"}}, {"isComplete": {"retrieved_name": "isComplete", "raw_body": "/** \n * Gets the complete flag. <p>\n * @return True if complete.\n */\npublic boolean isComplete(){\n return complete;\n}\n"}}, {"next": {"retrieved_name": "next", "raw_body": "@Override public void next(EdgeIteratorState edge,int index,int prevEdgeId){\n for ( PathDetailsBuilder calc : calculators) {\n if (calc.isEdgeDifferentToLastEdge(edge)) {\n calc.endInterval(lastIndex);\n calc.startInterval(lastIndex);\n }\n }\n lastIndex+=edge.fetchWayGeometry(FetchMode.PILLAR_AND_ADJ).size();\n}\n"}}, {"isDelta": {"retrieved_name": "isInternal", "raw_body": "public boolean isInternal(){\n return internal;\n}\n"}}, {"isHeader": {"retrieved_name": "getHeader", "raw_body": "private static String getHeader(TreeSet<String> keys){\n StringBuilder sb=new StringBuilder(\"#\");\n for ( String key : keys) {\n sb.append(key).append(\";\");\n }\n sb.append(\"\\n\");\n return sb.toString();\n}\n"}}, {"hasNext": {"retrieved_name": "hasNext", "raw_body": "private boolean hasNext(){\n return !dfsStack.isEmpty();\n}\n"}}, {"isStringTable": {"retrieved_name": "isToString", "raw_body": "public static String isToString(InputStream inputStream) throws IOException {\n int size=1024 * 8;\n String encoding=\"UTF-8\";\n InputStream in=new BufferedInputStream(inputStream,size);\n try {\n byte[] buffer=new byte[size];\n ByteArrayOutputStream output=new ByteArrayOutputStream();\n int numRead;\n while ((numRead=in.read(buffer)) != -1) {\n output.write(buffer,0,numRead);\n }\n return output.toString(encoding);\n }\n finally {\n in.close();\n }\n}\n"}}, {"isPartial": {"retrieved_name": "isInternal", "raw_body": "public boolean isInternal(){\n return internal;\n}\n"}}, {"isWay": {"retrieved_name": "isWay", "raw_body": "public boolean isWay(){\n return this.ordinal() == WAY.ordinal();\n}\n"}}] | [{"processBlobs": {"retrieved_name": "processNodes", "raw_body": "private void processNodes(Osmformat.DenseNodes nodes,PbfFieldDecoder fieldDecoder){\n List<Long> idList=nodes.getIdList();\n List<Long> latList=nodes.getLatList();\n List<Long> lonList=nodes.getLonList();\n if (checkData) {\n if ((idList.size() != latList.size()) || (idList.size() != lonList.size())) {\n throw new RuntimeException(\"Number of ids (\" + idList.size() + \"), latitudes (\"+ latList.size()+ \"), and longitudes (\"+ lonList.size()+ \") don't match\");\n }\n }\n Iterator<Integer> keysValuesIterator=nodes.getKeysValsList().iterator();\n long nodeId=0;\n long latitude=0;\n long longitude=0;\n for (int i=0; i < idList.size(); i++) {\n nodeId+=idList.get(i);\n latitude+=latList.get(i);\n longitude+=lonList.get(i);\n Map<String,Object> tags=null;\n while (keysValuesIterator.hasNext()) {\n int keyIndex=keysValuesIterator.next();\n if (keyIndex == 0) {\n break;\n }\n if (checkData) {\n if (!keysValuesIterator.hasNext()) {\n throw new RuntimeException(\"The PBF DenseInfo keys/values list contains a key with no corresponding value.\");\n }\n }\n int valueIndex=keysValuesIterator.next();\n if (tags == null) {\n tags=new HashMap<>(Math.max(3,2 * (nodes.getKeysValsList().size() / 2) / idList.size()));\n }\n tags.put(fieldDecoder.decodeString(keyIndex),fieldDecoder.decodeString(valueIndex));\n }\n ReaderNode node=new ReaderNode(nodeId,fieldDecoder.decodeLatitude(latitude),fieldDecoder.decodeLongitude(longitude));\n node.setTags(tags);\n decodedEntities.add(node);\n }\n}\n"}}] |
|
jeecgboot_jeecg-boot | jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/PasswordUtil.java | PasswordUtil | bytesToHexString | class PasswordUtil {
/**
* JAVA6支持以下任意一种算法 PBEWITHMD5ANDDES PBEWITHMD5ANDTRIPLEDES
* PBEWITHSHAANDDESEDE PBEWITHSHA1ANDRC2_40 PBKDF2WITHHMACSHA1
* */
/**
* 定义使用的算法为:PBEWITHMD5andDES算法
* 加密算法
*/
public static final String ALGORITHM = "PBEWithMD5AndDES";
/**
* 定义使用的算法为:PBEWITHMD5andDES算法
* 密钥
*/
public static final String SALT = "63293188";
/**
* 定义迭代次数为1000次
*/
private static final int ITERATIONCOUNT = 1000;
/**
* 获取加密算法中使用的盐值,解密中使用的盐值必须与加密中使用的相同才能完成操作. 盐长度必须为8字节
*
* @return byte[] 盐值
* */
public static byte[] getSalt() throws Exception {
// 实例化安全随机数
SecureRandom random = new SecureRandom();
// 产出盐
return random.generateSeed(8);
}
public static byte[] getStaticSalt() {
// 产出盐
return SALT.getBytes();
}
/**
* 根据PBE密码生成一把密钥
*
* @param password
* 生成密钥时所使用的密码
* @return Key PBE算法密钥
* */
private static Key getPbeKey(String password) {
// 实例化使用的算法
SecretKeyFactory keyFactory;
SecretKey secretKey = null;
try {
keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
// 设置PBE密钥参数
PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());
// 生成密钥
secretKey = keyFactory.generateSecret(keySpec);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return secretKey;
}
/**
* 加密明文字符串
*
* @param plaintext
* 待加密的明文字符串
* @param password
* 生成密钥时所使用的密码
* @param salt
* 盐值
* @return 加密后的密文字符串
* @throws Exception
*/
public static String encrypt(String plaintext, String password, String salt) {
Key key = getPbeKey(password);
byte[] encipheredData = null;
PBEParameterSpec parameterSpec = new PBEParameterSpec(salt.getBytes(), ITERATIONCOUNT);
try {
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, key, parameterSpec);
//update-begin-author:sccott date:20180815 for:中文作为用户名时,加密的密码windows和linux会得到不同的结果 gitee/issues/IZUD7
encipheredData = cipher.doFinal(plaintext.getBytes("utf-8"));
//update-end-author:sccott date:20180815 for:中文作为用户名时,加密的密码windows和linux会得到不同的结果 gitee/issues/IZUD7
} catch (Exception e) {
}
return bytesToHexString(encipheredData);
}
/**
* 解密密文字符串
*
* @param ciphertext
* 待解密的密文字符串
* @param password
* 生成密钥时所使用的密码(如需解密,该参数需要与加密时使用的一致)
* @param salt
* 盐值(如需解密,该参数需要与加密时使用的一致)
* @return 解密后的明文字符串
* @throws Exception
*/
public static String decrypt(String ciphertext, String password, String salt) {
Key key = getPbeKey(password);
byte[] passDec = null;
PBEParameterSpec parameterSpec = new PBEParameterSpec(salt.getBytes(), ITERATIONCOUNT);
try {
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, key, parameterSpec);
passDec = cipher.doFinal(hexStringToBytes(ciphertext));
}
catch (Exception e) {
// TODO: handle exception
}
return new String(passDec);
}
/**
* 将字节数组转换为十六进制字符串
*
* @param src
* 字节数组
* @return
*/
public static String bytesToHexString(byte[] src) {<FILL_FUNCTION_BODY>}
/**
* 将十六进制字符串转换为字节数组
*
* @param hexString
* 十六进制字符串
* @return
*/
public static byte[] hexStringToBytes(String hexString) {
if (hexString == null || "".equals(hexString)) {
return null;
}
hexString = hexString.toUpperCase();
int length = hexString.length() / 2;
char[] hexChars = hexString.toCharArray();
byte[] d = new byte[length];
for (int i = 0; i < length; i++) {
int pos = i * 2;
d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
}
return d;
}
private static byte charToByte(char c) {
return (byte) "0123456789ABCDEF".indexOf(c);
}
} |
StringBuilder stringBuilder = new StringBuilder("");
if (src == null || src.length <= 0) {
return null;
}
for (int i = 0; i < src.length; i++) {
int v = src[i] & 0xFF;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv);
}
return stringBuilder.toString();
|
StringBuilder stringBuilder = new StringBuilder("");
if (src == null || src.length <= 0) {
return null;
}
for (int i = 0; i < src.length; i++) {
int v = src[i] & 0xFF;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv);
}
return stringBuilder.toString();
| [] | [
"append",
"toHexString",
"toString",
"length"
] | [] | [
"toString",
"length",
"toHexString",
"append"
] | {
"methods": [
"append",
"toHexString",
"toString",
"length"
],
"similar_methods": [
"bytesToHexString"
],
"types": []
} | /**
* 单库分表 —— 添加
* @return
*/
@PostMapping(value="/test1") @ApiOperation(value="单库分表插入",notes="单库分表") public Result<?> add(){
log.info("---------------------------------单库分表插入--------------------------------");
int size=10;
for (int i=0; i < size; i++) {
ShardingSysLog shardingSysLog=new ShardingSysLog();
shardingSysLog.setLogContent("jeecg");
shardingSysLog.setLogType(i);
shardingSysLog.setOperateType(i);
shardingSysLogService.save(shardingSysLog);
}
return Result.OK("单库分表插入10条数据完成!");
}
private static String byteToHexString(byte b){
int n=b;
if (n < 0) {
n+=256;
}
int d1=n / 16;
int d2=n % 16;
return HEXDIGITS[d1] + HEXDIGITS[d2];
}
@Override public String toString(){
return "RedisInfo{" + "key='" + key + '\''+ ", value='"+ value+ '\''+ ", desctiption='"+ description+ '\''+ '}';
}
public static long stringToLong(String str){
Long test=new Long(0);
try {
test=Long.valueOf(str);
}
catch ( Exception e) {
}
return test.longValue();
}
/**
* 获得文件头部字符串
* @param src
* @return
*/
private static String bytesToHexString(byte[] src){
StringBuilder stringBuilder=new StringBuilder();
if (src == null || src.length <= 0) {
return null;
}
for (int i=0; i < src.length; i++) {
int v=src[i] & 0xFF;
String hv=Integer.toHexString(v);
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv);
}
return stringBuilder.toString();
}
| /**
* 单库分表 —— 添加
* @return
*/
@PostMapping(value="/test1") @ApiOperation(value="单库分表插入",notes="单库分表") public Result<?> add(){
log.info("---------------------------------单库分表插入--------------------------------");
int size=10;
for (int i=0; i < size; i++) {
ShardingSysLog shardingSysLog=new ShardingSysLog();
shardingSysLog.setLogContent("jeecg");
shardingSysLog.setLogType(i);
shardingSysLog.setOperateType(i);
shardingSysLogService.save(shardingSysLog);
}
return Result.OK("单库分表插入10条数据完成!");
}
private static String byteToHexString(byte b){
int n=b;
if (n < 0) {
n+=256;
}
int d1=n / 16;
int d2=n % 16;
return HEXDIGITS[d1] + HEXDIGITS[d2];
}
@Override public String toString(){
return "RedisInfo{" + "key='" + key + '\''+ ", value='"+ value+ '\''+ ", desctiption='"+ description+ '\''+ '}';
}
public static long stringToLong(String str){
Long test=new Long(0);
try {
test=Long.valueOf(str);
}
catch ( Exception e) {
}
return test.longValue();
}
/**
* 获得文件头部字符串
* @param src
* @return
*/
private static String bytesToHexString(byte[] src){
StringBuilder stringBuilder=new StringBuilder();
if (src == null || src.length <= 0) {
return null;
}
for (int i=0; i < src.length; i++) {
int v=src[i] & 0xFF;
String hv=Integer.toHexString(v);
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv);
}
return stringBuilder.toString();
}
| {"methods": [{"append": "add"}, {"toHexString": "byteToHexString"}, {"toString": "toString"}, {"length": "stringToLong"}], "similar_methods": [{"bytesToHexString": "bytesToHexString"}]} | [] | [{"append": {"retrieved_name": "add", "raw_body": "/** \n * \u5355\u5e93\u5206\u8868 \u2014\u2014 \u6dfb\u52a0\n * @return\n */\n@PostMapping(value=\"/test1\") @ApiOperation(value=\"\u5355\u5e93\u5206\u8868\u63d2\u5165\",notes=\"\u5355\u5e93\u5206\u8868\") public Result<?> add(){\n log.info(\"---------------------------------\u5355\u5e93\u5206\u8868\u63d2\u5165--------------------------------\");\n int size=10;\n for (int i=0; i < size; i++) {\n ShardingSysLog shardingSysLog=new ShardingSysLog();\n shardingSysLog.setLogContent(\"jeecg\");\n shardingSysLog.setLogType(i);\n shardingSysLog.setOperateType(i);\n shardingSysLogService.save(shardingSysLog);\n }\n return Result.OK(\"\u5355\u5e93\u5206\u8868\u63d2\u516510\u6761\u6570\u636e\u5b8c\u6210\uff01\");\n}\n"}}, {"toHexString": {"retrieved_name": "byteToHexString", "raw_body": "private static String byteToHexString(byte b){\n int n=b;\n if (n < 0) {\n n+=256;\n }\n int d1=n / 16;\n int d2=n % 16;\n return HEXDIGITS[d1] + HEXDIGITS[d2];\n}\n"}}, {"toString": {"retrieved_name": "toString", "raw_body": "@Override public String toString(){\n return \"RedisInfo{\" + \"key='\" + key + '\\''+ \", value='\"+ value+ '\\''+ \", desctiption='\"+ description+ '\\''+ '}';\n}\n"}}, {"length": {"retrieved_name": "stringToLong", "raw_body": "public static long stringToLong(String str){\n Long test=new Long(0);\n try {\n test=Long.valueOf(str);\n }\n catch ( Exception e) {\n }\n return test.longValue();\n}\n"}}] | [{"bytesToHexString": {"retrieved_name": "bytesToHexString", "raw_body": "/** \n * \u83b7\u5f97\u6587\u4ef6\u5934\u90e8\u5b57\u7b26\u4e32\n * @param src\n * @return\n */\nprivate static String bytesToHexString(byte[] src){\n StringBuilder stringBuilder=new StringBuilder();\n if (src == null || src.length <= 0) {\n return null;\n }\n for (int i=0; i < src.length; i++) {\n int v=src[i] & 0xFF;\n String hv=Integer.toHexString(v);\n if (hv.length() < 2) {\n stringBuilder.append(0);\n }\n stringBuilder.append(hv);\n }\n return stringBuilder.toString();\n}\n"}}] |
|
joelittlejohn_jsonschema2pojo | jsonschema2pojo/jsonschema2pojo-core/src/main/java/org/jsonschema2pojo/Jackson2Annotator.java | Jackson2Annotator | dateField | class Jackson2Annotator extends AbstractTypeInfoAwareAnnotator {
private final JsonInclude.Include inclusionLevel;
public Jackson2Annotator(GenerationConfig generationConfig) {
super(generationConfig);
switch (generationConfig.getInclusionLevel()) {
case ALWAYS:
inclusionLevel = JsonInclude.Include.ALWAYS;
break;
case NON_ABSENT:
inclusionLevel = JsonInclude.Include.NON_ABSENT;
break;
case NON_DEFAULT:
inclusionLevel = JsonInclude.Include.NON_DEFAULT;
break;
case NON_EMPTY:
inclusionLevel = JsonInclude.Include.NON_EMPTY;
break;
case NON_NULL:
inclusionLevel = JsonInclude.Include.NON_NULL;
break;
case USE_DEFAULTS:
inclusionLevel = JsonInclude.Include.USE_DEFAULTS;
break;
default:
inclusionLevel = JsonInclude.Include.NON_NULL;
break;
}
}
@Override
public void propertyOrder(JDefinedClass clazz, JsonNode propertiesNode) {
JAnnotationArrayMember annotationValue = clazz.annotate(JsonPropertyOrder.class).paramArray("value");
for (Iterator<String> properties = propertiesNode.fieldNames(); properties.hasNext();) {
annotationValue.param(properties.next());
}
}
@Override
public void propertyInclusion(JDefinedClass clazz, JsonNode schema) {
clazz.annotate(JsonInclude.class).param("value", inclusionLevel);
}
@Override
public void propertyField(JFieldVar field, JDefinedClass clazz, String propertyName, JsonNode propertyNode) {
field.annotate(JsonProperty.class).param("value", propertyName);
if (field.type().erasure().equals(field.type().owner().ref(Set.class))) {
field.annotate(JsonDeserialize.class).param("as", LinkedHashSet.class);
}
if (propertyNode.has("javaJsonView")) {
field.annotate(JsonView.class).param(
"value", field.type().owner().ref(propertyNode.get("javaJsonView").asText()));
}
if (propertyNode.has("description")) {
field.annotate(JsonPropertyDescription.class).param("value", propertyNode.get("description").asText());
}
}
@Override
public void propertyGetter(JMethod getter, JDefinedClass clazz, String propertyName) {
getter.annotate(JsonProperty.class).param("value", propertyName);
}
@Override
public void propertySetter(JMethod setter, JDefinedClass clazz, String propertyName) {
setter.annotate(JsonProperty.class).param("value", propertyName);
}
@Override
public void anyGetter(JMethod getter, JDefinedClass clazz) {
getter.annotate(JsonAnyGetter.class);
}
@Override
public void anySetter(JMethod setter, JDefinedClass clazz) {
setter.annotate(JsonAnySetter.class);
}
@Override
public void enumCreatorMethod(JDefinedClass _enum, JMethod creatorMethod) {
creatorMethod.annotate(JsonCreator.class);
}
@Override
public void enumValueMethod(JDefinedClass _enum, JMethod valueMethod) {
valueMethod.annotate(JsonValue.class);
}
@Override
public void enumConstant(JDefinedClass _enum, JEnumConstant constant, String value) {
}
@Override
public boolean isAdditionalPropertiesSupported() {
return true;
}
@Override
public void additionalPropertiesField(JFieldVar field, JDefinedClass clazz, String propertyName) {
field.annotate(JsonIgnore.class);
}
@Override
public void dateField(JFieldVar field, JDefinedClass clazz, JsonNode node) {<FILL_FUNCTION_BODY>}
@Override
public void timeField(JFieldVar field, JDefinedClass clazz, JsonNode node) {
String pattern = null;
if (node.has("customTimePattern")) {
pattern = node.get("customTimePattern").asText();
} else if (node.has("customPattern")) {
pattern = node.get("customPattern").asText();
} else if (isNotEmpty(getGenerationConfig().getCustomTimePattern())) {
pattern = getGenerationConfig().getCustomTimePattern();
} else if (getGenerationConfig().isFormatDates()) {
pattern = FormatRule.ISO_8601_TIME_FORMAT;
}
if (pattern != null && !field.type().fullName().equals("java.lang.String")) {
field.annotate(JsonFormat.class).param("shape", JsonFormat.Shape.STRING).param("pattern", pattern);
}
}
@Override
public void dateTimeField(JFieldVar field, JDefinedClass clazz, JsonNode node) {
String timezone = node.has("customTimezone") ? node.get("customTimezone").asText() : "UTC";
String pattern = null;
if (node.has("customDateTimePattern")) {
pattern = node.get("customDateTimePattern").asText();
} else if (node.has("customPattern")) {
pattern = node.get("customPattern").asText();
} else if (isNotEmpty(getGenerationConfig().getCustomDateTimePattern())) {
pattern = getGenerationConfig().getCustomDateTimePattern();
} else if (getGenerationConfig().isFormatDateTimes()) {
pattern = FormatRule.ISO_8601_DATETIME_FORMAT;
}
if (pattern != null && !field.type().fullName().equals("java.lang.String")) {
field.annotate(JsonFormat.class).param("shape", JsonFormat.Shape.STRING).param("pattern", pattern).param("timezone", timezone);
}
}
protected void addJsonTypeInfoAnnotation(JDefinedClass jclass, String propertyName) {
JAnnotationUse jsonTypeInfo = jclass.annotate(JsonTypeInfo.class);
jsonTypeInfo.param("use", JsonTypeInfo.Id.CLASS);
jsonTypeInfo.param("include", JsonTypeInfo.As.PROPERTY);
// When not provided it will use default provided by "use" attribute
if (StringUtils.isNotBlank(propertyName)) {
jsonTypeInfo.param("property", propertyName);
}
}
} |
String pattern = null;
if (node.has("customDatePattern")) {
pattern = node.get("customDatePattern").asText();
} else if (node.has("customPattern")) {
pattern = node.get("customPattern").asText();
} else if (isNotEmpty(getGenerationConfig().getCustomDatePattern())) {
pattern = getGenerationConfig().getCustomDatePattern();
} else if (getGenerationConfig().isFormatDates()) {
pattern = FormatRule.ISO_8601_DATE_FORMAT;
}
if (pattern != null && !field.type().fullName().equals("java.lang.String")) {
field.annotate(JsonFormat.class).param("shape", JsonFormat.Shape.STRING).param("pattern", pattern);
}
| public abstract class AbstractTypeInfoAwareAnnotator extends AbstractAnnotator {
public AbstractTypeInfoAwareAnnotator( GenerationConfig generationConfig);
@Override public void typeInfo( JDefinedClass clazz, JsonNode node);
@Override public boolean isPolymorphicDeserializationSupported( JsonNode node);
abstract protected void addJsonTypeInfoAnnotation( JDefinedClass clazz, String propertyName);
}
|
String timezone = node.has("customTimezone") ? node.get("customTimezone").asText() : "UTC";
String pattern = null;
if (node.has("customDatePattern")) {
pattern = node.get("customDatePattern").asText();
} else if (node.has("customPattern")) {
pattern = node.get("customPattern").asText();
} else if (isNotEmpty(getGenerationConfig().getCustomDatePattern())) {
pattern = getGenerationConfig().getCustomDatePattern();
} else if (getGenerationConfig().isFormatDates()) {
pattern = FormatRule.ISO_8601_DATE_FORMAT;
}
if (pattern != null && !field.type().fullName().equals("java.lang.String")) {
field.annotate(JsonFormat.class).param("shape", JsonFormat.Shape.STRING).param("pattern", pattern).param("timezone", timezone);
}
| [
"JDefinedClass",
"JFieldVar",
"JsonNode"
] | [
"isFormatDates",
"type",
"getCustomDatePattern",
"get",
"param",
"asText",
"annotate",
"has",
"fullName",
"equals"
] | [
"JDefinedClass",
"JsonNode",
"JFieldVar"
] | [
"equals",
"isFormatDates",
"fullName",
"annotate",
"get",
"param",
"asText",
"getCustomDatePattern",
"type",
"has"
] | {
"methods": [
"isFormatDates",
"type",
"getCustomDatePattern",
"get",
"param",
"asText",
"annotate",
"has",
"fullName",
"equals"
],
"similar_methods": [
"dateField"
],
"types": [
"JDefinedClass",
"JFieldVar",
"JsonNode"
]
} | public class MyJsonViewClass {
}
public class JavaVersion {
private static final Pattern JAVA_VERSION_1_X=Pattern.compile("(^1.\\d+)");
private static final Pattern JAVA_VERSION_X=Pattern.compile("(^\\d+)");
public static String parse( String version);
public static boolean is9OrLater( final String targetVersion);
}
@RunWith(Parameterized.class) public class JsonTypesIT {
@Parameters(name="{0}") public static List<Object[]> data();
@Rule public Jsonschema2PojoRule schemaRule=new Jsonschema2PojoRule();
@Rule public ExpectedException thrown=ExpectedException.none();
private final String format;
private final ObjectMapper objectMapper;
public JsonTypesIT( final String format, final ObjectMapper objectMapper);
private String filePath( String baseName);
@Test public void simpleTypesInExampleAreMappedToCorrectJavaTypes() throws Exception;
@Test public void integerIsMappedToBigInteger() throws Exception;
@Test public void numberIsMappedToBigDecimal() throws Exception;
@Test(expected=ClassNotFoundException.class) public void simpleTypeAtRootProducesNoJavaTypes() throws ClassNotFoundException;
@Test @SuppressWarnings("unchecked") public void complexTypesProduceObjects() throws Exception;
@Test @SuppressWarnings("rawtypes") public void arrayTypePropertiesProduceLists() throws Exception;
@Test public void arrayItemsAreRecursivelyMerged() throws Exception;
@Test public void arrayItemsAreNotRecursivelyMerged() throws Exception;
@Test(expected=ClassNotFoundException.class) public void arrayAtRootWithSimpleTypeProducesNoJavaTypes() throws Exception;
@Test public void propertiesWithSameNameOnDifferentObjects() throws Exception;
}
@Override public boolean isFormatDates(){
return formatDates;
}
public EnumDefinitionExtensionType getType(){
return type;
}
@Override public String getCustomDatePattern(){
return customDatePattern;
}
public static Object getValue(Object instance,String methodName) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
return instance.getClass().getMethod(methodName).invoke(instance);
}
@Parameters(name="{0}") public static Collection<Object[]> parameters(){
JavaCompiler systemJavaCompiler=Compiler.systemJavaCompiler();
JavaCompiler eclipseCompiler=Compiler.eclipseCompiler();
return Arrays.asList(new Object[][]{{"includeAccessorsWithSystemJavaCompiler",systemJavaCompiler,config("includeDynamicAccessors",true,"includeDynamicGetters",true,"includeDynamicSetters",true,"includeDynamicBuilders",true),"/schema/dynamic/parentType.json",Matchers.empty()},{"includeAccessorsWithEclipseCompiler",eclipseCompiler,config("includeDynamicAccessors",true,"includeDynamicGetters",true,"includeDynamicSetters",true,"includeDynamicBuilders",true),"/schema/dynamic/parentType.json",onlyCastExceptions()}});
}
private static Matcher<File> containsText(String searchText){
return new FileSearchMatcher(searchText);
}
private static boolean tryToAnnotate(JDefinedClass jclass,String annotationClassName){
try {
Class.forName(annotationClassName);
JClass annotationClass=jclass.owner().ref(annotationClassName);
JAnnotationUse generated=jclass.annotate(annotationClass);
generated.param("value",GENERATOR_NAME);
return true;
}
catch ( ClassNotFoundException e) {
return false;
}
}
public boolean hasTitle(){
return titleNode != null && !titleNode.isMissingNode();
}
private String createFullFieldName(String nodeName,String prefix,String suffix){
String returnString=nodeName;
if (prefix != null) {
returnString=prefix + returnString;
}
if (suffix != null) {
returnString=returnString + suffix;
}
return returnString;
}
@Override public boolean equals(java.lang.Object other){
if (other == this) {
return true;
}
if ((other instanceof ParentWithEquals) == false) {
return false;
}
return true;
}
@Override public void dateField(JFieldVar field,JDefinedClass clazz,JsonNode node){
String pattern=null;
if (node.has("customDatePattern")) {
pattern=node.get("customDatePattern").asText();
}
else if (node.has("customPattern")) {
pattern=node.get("customPattern").asText();
}
else if (isNotEmpty(getGenerationConfig().getCustomDatePattern())) {
pattern=getGenerationConfig().getCustomDatePattern();
}
else if (getGenerationConfig().isFormatDates()) {
pattern=FormatRule.ISO_8601_DATE_FORMAT;
}
if (!field.type().fullName().equals("java.lang.String")) {
pattern=pattern != null ? pattern : FormatRule.ISO_8601_DATE_FORMAT;
field.annotate(JsonbDateFormat.class).param("value",pattern);
}
}
| public class MyJsonViewClass {
}
public class JavaVersion {
private static final Pattern JAVA_VERSION_1_X=Pattern.compile("(^1.\\d+)");
private static final Pattern JAVA_VERSION_X=Pattern.compile("(^\\d+)");
public static String parse( String version);
public static boolean is9OrLater( final String targetVersion);
}
public class JsonTypesIT {
public static List<Object[]> data();
public Jsonschema2PojoRule schemaRule=new Jsonschema2PojoRule();
public ExpectedException thrown=ExpectedException.none();
private final String format;
private final ObjectMapper objectMapper;
public JsonTypesIT( final String format, final ObjectMapper objectMapper);
private String filePath( String baseName);
public void simpleTypesInExampleAreMappedToCorrectJavaTypes() throws Exception;
public void integerIsMappedToBigInteger() throws Exception;
public void numberIsMappedToBigDecimal() throws Exception;
public void simpleTypeAtRootProducesNoJavaTypes() throws ClassNotFoundException;
public void complexTypesProduceObjects() throws Exception;
public void arrayTypePropertiesProduceLists() throws Exception;
public void arrayItemsAreRecursivelyMerged() throws Exception;
public void arrayItemsAreNotRecursivelyMerged() throws Exception;
public void arrayAtRootWithSimpleTypeProducesNoJavaTypes() throws Exception;
public void propertiesWithSameNameOnDifferentObjects() throws Exception;
}
@Override public boolean isFormatDates(){
return formatDates;
}
public EnumDefinitionExtensionType getType(){
return type;
}
@Override public String getCustomDatePattern(){
return customDatePattern;
}
public static Object getValue(Object instance,String methodName) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
return instance.getClass().getMethod(methodName).invoke(instance);
}
@Parameters(name="{0}") public static Collection<Object[]> parameters(){
JavaCompiler systemJavaCompiler=Compiler.systemJavaCompiler();
JavaCompiler eclipseCompiler=Compiler.eclipseCompiler();
return Arrays.asList(new Object[][]{{"includeAccessorsWithSystemJavaCompiler",systemJavaCompiler,config("includeDynamicAccessors",true,"includeDynamicGetters",true,"includeDynamicSetters",true,"includeDynamicBuilders",true),"/schema/dynamic/parentType.json",Matchers.empty()},{"includeAccessorsWithEclipseCompiler",eclipseCompiler,config("includeDynamicAccessors",true,"includeDynamicGetters",true,"includeDynamicSetters",true,"includeDynamicBuilders",true),"/schema/dynamic/parentType.json",onlyCastExceptions()}});
}
private static Matcher<File> containsText(String searchText){
return new FileSearchMatcher(searchText);
}
private static boolean tryToAnnotate(JDefinedClass jclass,String annotationClassName){
try {
Class.forName(annotationClassName);
JClass annotationClass=jclass.owner().ref(annotationClassName);
JAnnotationUse generated=jclass.annotate(annotationClass);
generated.param("value",GENERATOR_NAME);
return true;
}
catch ( ClassNotFoundException e) {
return false;
}
}
public boolean hasTitle(){
return titleNode != null && !titleNode.isMissingNode();
}
private String createFullFieldName(String nodeName,String prefix,String suffix){
String returnString=nodeName;
if (prefix != null) {
returnString=prefix + returnString;
}
if (suffix != null) {
returnString=returnString + suffix;
}
return returnString;
}
@Override public boolean equals(java.lang.Object other){
if (other == this) {
return true;
}
if ((other instanceof ParentWithEquals) == false) {
return false;
}
return true;
}
@Override public void dateField(JFieldVar field,JDefinedClass clazz,JsonNode node){
String pattern=null;
if (node.has("customDatePattern")) {
pattern=node.get("customDatePattern").asText();
}
else if (node.has("customPattern")) {
pattern=node.get("customPattern").asText();
}
else if (isNotEmpty(getGenerationConfig().getCustomDatePattern())) {
pattern=getGenerationConfig().getCustomDatePattern();
}
else if (getGenerationConfig().isFormatDates()) {
pattern=FormatRule.ISO_8601_DATE_FORMAT;
}
if (!field.type().fullName().equals("java.lang.String")) {
pattern=pattern != null ? pattern : FormatRule.ISO_8601_DATE_FORMAT;
field.annotate(JsonbDateFormat.class).param("value",pattern);
}
}
| {"types": [{"JDefinedClass": "MyJsonViewClass"}, {"JFieldVar": "JavaVersion"}, {"JsonNode": "JsonTypesIT"}], "methods": [{"isFormatDates": "isFormatDates"}, {"type": "getType"}, {"getCustomDatePattern": "getCustomDatePattern"}, {"get": "getValue"}, {"param": "parameters"}, {"asText": "containsText"}, {"annotate": "tryToAnnotate"}, {"has": "hasTitle"}, {"fullName": "createFullFieldName"}, {"equals": "equals"}], "similar_methods": [{"dateField": "dateField"}]} | [{"JDefinedClass": {"retrieved_name": "MyJsonViewClass", "raw_body": "public class MyJsonViewClass {\n}\n", "raw_body_no_cmt": "public class MyJsonViewClass {\n}\n"}}, {"JFieldVar": {"retrieved_name": "JavaVersion", "raw_body": "public class JavaVersion {\n private static final Pattern JAVA_VERSION_1_X=Pattern.compile(\"(^1.\\\\d+)\");\n private static final Pattern JAVA_VERSION_X=Pattern.compile(\"(^\\\\d+)\");\n public static String parse( String version);\n public static boolean is9OrLater( final String targetVersion);\n}\n", "raw_body_no_cmt": "public class JavaVersion {\n private static final Pattern JAVA_VERSION_1_X=Pattern.compile(\"(^1.\\\\d+)\");\n private static final Pattern JAVA_VERSION_X=Pattern.compile(\"(^\\\\d+)\");\n public static String parse( String version);\n public static boolean is9OrLater( final String targetVersion);\n}\n"}}, {"JsonNode": {"retrieved_name": "JsonTypesIT", "raw_body": "@RunWith(Parameterized.class) public class JsonTypesIT {\n @Parameters(name=\"{0}\") public static List<Object[]> data();\n @Rule public Jsonschema2PojoRule schemaRule=new Jsonschema2PojoRule();\n @Rule public ExpectedException thrown=ExpectedException.none();\n private final String format;\n private final ObjectMapper objectMapper;\n public JsonTypesIT( final String format, final ObjectMapper objectMapper);\n private String filePath( String baseName);\n @Test public void simpleTypesInExampleAreMappedToCorrectJavaTypes() throws Exception;\n @Test public void integerIsMappedToBigInteger() throws Exception;\n @Test public void numberIsMappedToBigDecimal() throws Exception;\n @Test(expected=ClassNotFoundException.class) public void simpleTypeAtRootProducesNoJavaTypes() throws ClassNotFoundException;\n @Test @SuppressWarnings(\"unchecked\") public void complexTypesProduceObjects() throws Exception;\n @Test @SuppressWarnings(\"rawtypes\") public void arrayTypePropertiesProduceLists() throws Exception;\n @Test public void arrayItemsAreRecursivelyMerged() throws Exception;\n @Test public void arrayItemsAreNotRecursivelyMerged() throws Exception;\n @Test(expected=ClassNotFoundException.class) public void arrayAtRootWithSimpleTypeProducesNoJavaTypes() throws Exception;\n @Test public void propertiesWithSameNameOnDifferentObjects() throws Exception;\n}\n", "raw_body_no_cmt": "public class JsonTypesIT {\n public static List<Object[]> data();\n public Jsonschema2PojoRule schemaRule=new Jsonschema2PojoRule();\n public ExpectedException thrown=ExpectedException.none();\n private final String format;\n private final ObjectMapper objectMapper;\n public JsonTypesIT( final String format, final ObjectMapper objectMapper);\n private String filePath( String baseName);\n public void simpleTypesInExampleAreMappedToCorrectJavaTypes() throws Exception;\n public void integerIsMappedToBigInteger() throws Exception;\n public void numberIsMappedToBigDecimal() throws Exception;\n public void simpleTypeAtRootProducesNoJavaTypes() throws ClassNotFoundException;\n public void complexTypesProduceObjects() throws Exception;\n public void arrayTypePropertiesProduceLists() throws Exception;\n public void arrayItemsAreRecursivelyMerged() throws Exception;\n public void arrayItemsAreNotRecursivelyMerged() throws Exception;\n public void arrayAtRootWithSimpleTypeProducesNoJavaTypes() throws Exception;\n public void propertiesWithSameNameOnDifferentObjects() throws Exception;\n}\n"}}] | [{"isFormatDates": {"retrieved_name": "isFormatDates", "raw_body": "@Override public boolean isFormatDates(){\n return formatDates;\n}\n"}}, {"type": {"retrieved_name": "getType", "raw_body": "public EnumDefinitionExtensionType getType(){\n return type;\n}\n"}}, {"getCustomDatePattern": {"retrieved_name": "getCustomDatePattern", "raw_body": "@Override public String getCustomDatePattern(){\n return customDatePattern;\n}\n"}}, {"get": {"retrieved_name": "getValue", "raw_body": "public static Object getValue(Object instance,String methodName) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {\n return instance.getClass().getMethod(methodName).invoke(instance);\n}\n"}}, {"param": {"retrieved_name": "parameters", "raw_body": "@Parameters(name=\"{0}\") public static Collection<Object[]> parameters(){\n JavaCompiler systemJavaCompiler=Compiler.systemJavaCompiler();\n JavaCompiler eclipseCompiler=Compiler.eclipseCompiler();\n return Arrays.asList(new Object[][]{{\"includeAccessorsWithSystemJavaCompiler\",systemJavaCompiler,config(\"includeDynamicAccessors\",true,\"includeDynamicGetters\",true,\"includeDynamicSetters\",true,\"includeDynamicBuilders\",true),\"/schema/dynamic/parentType.json\",Matchers.empty()},{\"includeAccessorsWithEclipseCompiler\",eclipseCompiler,config(\"includeDynamicAccessors\",true,\"includeDynamicGetters\",true,\"includeDynamicSetters\",true,\"includeDynamicBuilders\",true),\"/schema/dynamic/parentType.json\",onlyCastExceptions()}});\n}\n"}}, {"asText": {"retrieved_name": "containsText", "raw_body": "private static Matcher<File> containsText(String searchText){\n return new FileSearchMatcher(searchText);\n}\n"}}, {"annotate": {"retrieved_name": "tryToAnnotate", "raw_body": "private static boolean tryToAnnotate(JDefinedClass jclass,String annotationClassName){\n try {\n Class.forName(annotationClassName);\n JClass annotationClass=jclass.owner().ref(annotationClassName);\n JAnnotationUse generated=jclass.annotate(annotationClass);\n generated.param(\"value\",GENERATOR_NAME);\n return true;\n }\n catch ( ClassNotFoundException e) {\n return false;\n }\n}\n"}}, {"has": {"retrieved_name": "hasTitle", "raw_body": "public boolean hasTitle(){\n return titleNode != null && !titleNode.isMissingNode();\n}\n"}}, {"fullName": {"retrieved_name": "createFullFieldName", "raw_body": "private String createFullFieldName(String nodeName,String prefix,String suffix){\n String returnString=nodeName;\n if (prefix != null) {\n returnString=prefix + returnString;\n }\n if (suffix != null) {\n returnString=returnString + suffix;\n }\n return returnString;\n}\n"}}, {"equals": {"retrieved_name": "equals", "raw_body": "@Override public boolean equals(java.lang.Object other){\n if (other == this) {\n return true;\n }\n if ((other instanceof ParentWithEquals) == false) {\n return false;\n }\n return true;\n}\n"}}] | [{"dateField": {"retrieved_name": "dateField", "raw_body": "@Override public void dateField(JFieldVar field,JDefinedClass clazz,JsonNode node){\n String pattern=null;\n if (node.has(\"customDatePattern\")) {\n pattern=node.get(\"customDatePattern\").asText();\n }\n else if (node.has(\"customPattern\")) {\n pattern=node.get(\"customPattern\").asText();\n }\n else if (isNotEmpty(getGenerationConfig().getCustomDatePattern())) {\n pattern=getGenerationConfig().getCustomDatePattern();\n }\n else if (getGenerationConfig().isFormatDates()) {\n pattern=FormatRule.ISO_8601_DATE_FORMAT;\n }\n if (!field.type().fullName().equals(\"java.lang.String\")) {\n pattern=pattern != null ? pattern : FormatRule.ISO_8601_DATE_FORMAT;\n field.annotate(JsonbDateFormat.class).param(\"value\",pattern);\n }\n}\n"}}] |
DerekYRC_mini-spring | mini-spring/src/main/java/org/springframework/core/io/ClassPathResource.java | ClassPathResource | getInputStream | class ClassPathResource implements Resource {
private final String path;
public ClassPathResource(String path) {
this.path = path;
}
@Override
public InputStream getInputStream() throws IOException {<FILL_FUNCTION_BODY>}
} |
InputStream is = this.getClass().getClassLoader().getResourceAsStream(this.path);
if (is == null) {
throw new FileNotFoundException(this.path + " cannot be opened because it does not exist");
}
return is;
|
InputStream is = this.getClass().getClassLoader().getResourceAsStream(this.path);
if (is == null) {
throw new FileNotFoundException(this.path + " cannot be opened because it does not exist");
}
return is;
| [
"InputStream"
] | [
"getResourceAsStream",
"getClassLoader",
"getClass"
] | [
"InputStream"
] | [
"getClass",
"getResourceAsStream",
"getClassLoader"
] | {
"methods": [
"getResourceAsStream",
"getClassLoader",
"getClass"
],
"similar_methods": [
"getInputStream"
],
"types": [
"InputStream"
]
} | /**
* @author derekyi
* @date 2020/11/22
*/
public abstract class AbstractBeanFactory extends DefaultSingletonBeanRegistry implements ConfigurableBeanFactory {
private final List<BeanPostProcessor> beanPostProcessors=new ArrayList<>();
private final Map<String,Object> factoryBeanObjectCache=new HashMap<>();
private final List<StringValueResolver> embeddedValueResolvers=new ArrayList<StringValueResolver>();
private ConversionService conversionService;
@Override public Object getBean( String name) throws BeansException;
/**
* 如果是FactoryBean,从FactoryBean#getObject中创建bean
* @param beanInstance
* @param beanName
* @return
*/
protected Object getObjectForBeanInstance( Object beanInstance, String beanName);
@Override public <T>T getBean( String name, Class<T> requiredType) throws BeansException;
@Override public boolean containsBean( String name);
protected abstract boolean containsBeanDefinition( String beanName);
protected abstract Object createBean( String beanName, BeanDefinition beanDefinition) throws BeansException ;
protected abstract BeanDefinition getBeanDefinition( String beanName) throws BeansException ;
@Override public void addBeanPostProcessor( BeanPostProcessor beanPostProcessor);
public List<BeanPostProcessor> getBeanPostProcessors();
public void addEmbeddedValueResolver( StringValueResolver valueResolver);
public String resolveEmbeddedValue( String value);
@Override public ConversionService getConversionService();
@Override public void setConversionService( ConversionService conversionService);
}
@Override public Resource getResource(String location){
if (location.startsWith(CLASSPATH_URL_PREFIX)) {
return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()));
}
else {
try {
URL url=new URL(location);
return new UrlResource(url);
}
catch ( MalformedURLException ex) {
return new FileSystemResource(location);
}
}
}
ClassFilter getClassFilter();
public Class<?>[] getTargetClass(){
return this.target.getClass().getInterfaces();
}
@Override public InputStream getInputStream() throws IOException {
try {
Path path=new File(this.filePath).toPath();
return Files.newInputStream(path);
}
catch ( NoSuchFileException ex) {
throw new FileNotFoundException(ex.getMessage());
}
}
| public abstract class AbstractBeanFactory extends DefaultSingletonBeanRegistry implements ConfigurableBeanFactory {
private final List<BeanPostProcessor> beanPostProcessors=new ArrayList<>();
private final Map<String,Object> factoryBeanObjectCache=new HashMap<>();
private final List<StringValueResolver> embeddedValueResolvers=new ArrayList<StringValueResolver>();
private ConversionService conversionService;
public Object getBean( String name) throws BeansException;
protected Object getObjectForBeanInstance( Object beanInstance, String beanName);
public <T>T getBean( String name, Class<T> requiredType) throws BeansException;
public boolean containsBean( String name);
protected abstract boolean containsBeanDefinition( String beanName);
protected abstract Object createBean( String beanName, BeanDefinition beanDefinition) throws BeansException ;
protected abstract BeanDefinition getBeanDefinition( String beanName) throws BeansException ;
public void addBeanPostProcessor( BeanPostProcessor beanPostProcessor);
public List<BeanPostProcessor> getBeanPostProcessors();
public void addEmbeddedValueResolver( StringValueResolver valueResolver);
public String resolveEmbeddedValue( String value);
public ConversionService getConversionService();
public void setConversionService( ConversionService conversionService);
}
@Override public Resource getResource(String location){
if (location.startsWith(CLASSPATH_URL_PREFIX)) {
return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()));
}
else {
try {
URL url=new URL(location);
return new UrlResource(url);
}
catch ( MalformedURLException ex) {
return new FileSystemResource(location);
}
}
}
ClassFilter getClassFilter();
public Class<?>[] getTargetClass(){
return this.target.getClass().getInterfaces();
}
@Override public InputStream getInputStream() throws IOException {
try {
Path path=new File(this.filePath).toPath();
return Files.newInputStream(path);
}
catch ( NoSuchFileException ex) {
throw new FileNotFoundException(ex.getMessage());
}
}
| {"types": [{"InputStream": "AbstractBeanFactory"}], "methods": [{"getResourceAsStream": "getResource"}, {"getClassLoader": "getClassFilter"}, {"getClass": "getTargetClass"}], "similar_methods": [{"getInputStream": "getInputStream"}]} | [{"InputStream": {"retrieved_name": "AbstractBeanFactory", "raw_body": "/** \n * @author derekyi\n * @date 2020/11/22\n */\npublic abstract class AbstractBeanFactory extends DefaultSingletonBeanRegistry implements ConfigurableBeanFactory {\n private final List<BeanPostProcessor> beanPostProcessors=new ArrayList<>();\n private final Map<String,Object> factoryBeanObjectCache=new HashMap<>();\n private final List<StringValueResolver> embeddedValueResolvers=new ArrayList<StringValueResolver>();\n private ConversionService conversionService;\n @Override public Object getBean( String name) throws BeansException;\n /** \n * \u5982\u679c\u662fFactoryBean\uff0c\u4eceFactoryBean#getObject\u4e2d\u521b\u5efabean\n * @param beanInstance\n * @param beanName\n * @return\n */\n protected Object getObjectForBeanInstance( Object beanInstance, String beanName);\n @Override public <T>T getBean( String name, Class<T> requiredType) throws BeansException;\n @Override public boolean containsBean( String name);\n protected abstract boolean containsBeanDefinition( String beanName);\n protected abstract Object createBean( String beanName, BeanDefinition beanDefinition) throws BeansException ;\n protected abstract BeanDefinition getBeanDefinition( String beanName) throws BeansException ;\n @Override public void addBeanPostProcessor( BeanPostProcessor beanPostProcessor);\n public List<BeanPostProcessor> getBeanPostProcessors();\n public void addEmbeddedValueResolver( StringValueResolver valueResolver);\n public String resolveEmbeddedValue( String value);\n @Override public ConversionService getConversionService();\n @Override public void setConversionService( ConversionService conversionService);\n}\n", "raw_body_no_cmt": "public abstract class AbstractBeanFactory extends DefaultSingletonBeanRegistry implements ConfigurableBeanFactory {\n private final List<BeanPostProcessor> beanPostProcessors=new ArrayList<>();\n private final Map<String,Object> factoryBeanObjectCache=new HashMap<>();\n private final List<StringValueResolver> embeddedValueResolvers=new ArrayList<StringValueResolver>();\n private ConversionService conversionService;\n public Object getBean( String name) throws BeansException;\n protected Object getObjectForBeanInstance( Object beanInstance, String beanName);\n public <T>T getBean( String name, Class<T> requiredType) throws BeansException;\n public boolean containsBean( String name);\n protected abstract boolean containsBeanDefinition( String beanName);\n protected abstract Object createBean( String beanName, BeanDefinition beanDefinition) throws BeansException ;\n protected abstract BeanDefinition getBeanDefinition( String beanName) throws BeansException ;\n public void addBeanPostProcessor( BeanPostProcessor beanPostProcessor);\n public List<BeanPostProcessor> getBeanPostProcessors();\n public void addEmbeddedValueResolver( StringValueResolver valueResolver);\n public String resolveEmbeddedValue( String value);\n public ConversionService getConversionService();\n public void setConversionService( ConversionService conversionService);\n}\n"}}] | [{"getResourceAsStream": {"retrieved_name": "getResource", "raw_body": "@Override public Resource getResource(String location){\n if (location.startsWith(CLASSPATH_URL_PREFIX)) {\n return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()));\n }\n else {\n try {\n URL url=new URL(location);\n return new UrlResource(url);\n }\n catch ( MalformedURLException ex) {\n return new FileSystemResource(location);\n }\n }\n}\n"}}, {"getClassLoader": {"retrieved_name": "getClassFilter", "raw_body": "ClassFilter getClassFilter();\n"}}, {"getClass": {"retrieved_name": "getTargetClass", "raw_body": "public Class<?>[] getTargetClass(){\n return this.target.getClass().getInterfaces();\n}\n"}}] | [{"getInputStream": {"retrieved_name": "getInputStream", "raw_body": "@Override public InputStream getInputStream() throws IOException {\n try {\n Path path=new File(this.filePath).toPath();\n return Files.newInputStream(path);\n }\n catch ( NoSuchFileException ex) {\n throw new FileNotFoundException(ex.getMessage());\n }\n}\n"}}] |
|
elunez_eladmin | eladmin/eladmin-common/src/main/java/me/zhengjie/config/FileProperties.java | FileProperties | getPath | class FileProperties {
/** 文件大小限制 */
private Long maxSize;
/** 头像大小限制 */
private Long avatarMaxSize;
private ElPath mac;
private ElPath linux;
private ElPath windows;
public ElPath getPath(){<FILL_FUNCTION_BODY>}
@Data
public static class ElPath{
private String path;
private String avatar;
}
} |
String os = System.getProperty("os.name");
if(os.toLowerCase().startsWith(ElConstant.WIN)) {
return windows;
} else if(os.toLowerCase().startsWith(ElConstant.MAC)){
return mac;
}
return linux;
|
String os = System.getProperty("os.name");
if(os.toLowerCase().startsWith("win")){
return windows;
}else if(os.toLowerCase().startsWith("mac")){
return mac;
}
return linux;
| [
"ElPath"
] | [
"getProperty",
"startsWith",
"toLowerCase"
] | [
"ElPath"
] | [
"startsWith",
"toLowerCase",
"getProperty"
] | {
"methods": [
"getProperty",
"startsWith",
"toLowerCase"
],
"similar_methods": [
"getPath"
],
"types": [
"ElPath"
]
} | /**
* 常用静态常量
* @author Zheng Jie
* @date 2018-12-26
*/
public class ElConstant {
/**
* win 系统
*/
public static final String WIN="win";
/**
* mac 系统
*/
public static final String MAC="mac";
}
/**
* 获取SpringBoot 配置信息
* @param property 属性key
* @param defaultValue 默认值
* @param requiredType 返回类型
* @return /
*/
public static <T>T getProperties(String property,T defaultValue,Class<T> requiredType){
T result=defaultValue;
try {
result=getBean(Environment.class).getProperty(property,requiredType);
}
catch ( Exception ignored) {
}
return result;
}
public String getTokenStartWith(){
return tokenStartWith + " ";
}
/**
* 驼峰命名法工具
* @return toCamelCase(" hello_world ") == "helloWorld"toCapitalizeCamelCase("hello_world") == "HelloWorld" toUnderScoreCase("helloWorld") = "hello_world"
*/
static String toUnderScoreCase(String s){
if (s == null) {
return null;
}
StringBuilder sb=new StringBuilder();
boolean upperCase=false;
for (int i=0; i < s.length(); i++) {
char c=s.charAt(i);
boolean nextUpperCase=true;
if (i < (s.length() - 1)) {
nextUpperCase=Character.isUpperCase(s.charAt(i + 1));
}
if ((i > 0) && Character.isUpperCase(c)) {
if (!upperCase || !nextUpperCase) {
sb.append(SEPARATOR);
}
upperCase=true;
}
else {
upperCase=false;
}
sb.append(Character.toLowerCase(c));
}
return sb.toString();
}
public void getFile(String remoteFile,String localTargetDirectory){
Connection conn=new Connection(ip,port);
try {
conn.connect();
boolean isAuthenticated=conn.authenticateWithPassword(username,password);
if (!isAuthenticated) {
System.err.println("authentication failed");
}
SCPClient client=new SCPClient(conn);
client.get(remoteFile,localTargetDirectory);
}
catch ( IOException ex) {
Logger.getLogger(SCPClient.class.getName()).log(Level.SEVERE,null,ex);
}
finally {
conn.close();
}
}
| public class ElConstant {
public static final String WIN="win";
public static final String MAC="mac";
}
/**
* 获取SpringBoot 配置信息
* @param property 属性key
* @param defaultValue 默认值
* @param requiredType 返回类型
* @return /
*/
public static <T>T getProperties(String property,T defaultValue,Class<T> requiredType){
T result=defaultValue;
try {
result=getBean(Environment.class).getProperty(property,requiredType);
}
catch ( Exception ignored) {
}
return result;
}
public String getTokenStartWith(){
return tokenStartWith + " ";
}
/**
* 驼峰命名法工具
* @return toCamelCase(" hello_world ") == "helloWorld"toCapitalizeCamelCase("hello_world") == "HelloWorld" toUnderScoreCase("helloWorld") = "hello_world"
*/
static String toUnderScoreCase(String s){
if (s == null) {
return null;
}
StringBuilder sb=new StringBuilder();
boolean upperCase=false;
for (int i=0; i < s.length(); i++) {
char c=s.charAt(i);
boolean nextUpperCase=true;
if (i < (s.length() - 1)) {
nextUpperCase=Character.isUpperCase(s.charAt(i + 1));
}
if ((i > 0) && Character.isUpperCase(c)) {
if (!upperCase || !nextUpperCase) {
sb.append(SEPARATOR);
}
upperCase=true;
}
else {
upperCase=false;
}
sb.append(Character.toLowerCase(c));
}
return sb.toString();
}
public void getFile(String remoteFile,String localTargetDirectory){
Connection conn=new Connection(ip,port);
try {
conn.connect();
boolean isAuthenticated=conn.authenticateWithPassword(username,password);
if (!isAuthenticated) {
System.err.println("authentication failed");
}
SCPClient client=new SCPClient(conn);
client.get(remoteFile,localTargetDirectory);
}
catch ( IOException ex) {
Logger.getLogger(SCPClient.class.getName()).log(Level.SEVERE,null,ex);
}
finally {
conn.close();
}
}
| {"types": [{"ElPath": "ElConstant"}], "methods": [{"getProperty": "getProperties"}, {"startsWith": "getTokenStartWith"}, {"toLowerCase": "toUnderScoreCase"}], "similar_methods": [{"getPath": "getFile"}]} | [{"ElPath": {"retrieved_name": "ElConstant", "raw_body": "/** \n * \u5e38\u7528\u9759\u6001\u5e38\u91cf\n * @author Zheng Jie\n * @date 2018-12-26\n */\npublic class ElConstant {\n /** \n * win \u7cfb\u7edf\n */\n public static final String WIN=\"win\";\n /** \n * mac \u7cfb\u7edf\n */\n public static final String MAC=\"mac\";\n}\n", "raw_body_no_cmt": "public class ElConstant {\n public static final String WIN=\"win\";\n public static final String MAC=\"mac\";\n}\n"}}] | [{"getProperty": {"retrieved_name": "getProperties", "raw_body": "/** \n * \u83b7\u53d6SpringBoot \u914d\u7f6e\u4fe1\u606f\n * @param property \u5c5e\u6027key\n * @param defaultValue \u9ed8\u8ba4\u503c\n * @param requiredType \u8fd4\u56de\u7c7b\u578b\n * @return /\n */\npublic static <T>T getProperties(String property,T defaultValue,Class<T> requiredType){\n T result=defaultValue;\n try {\n result=getBean(Environment.class).getProperty(property,requiredType);\n }\n catch ( Exception ignored) {\n }\n return result;\n}\n"}}, {"startsWith": {"retrieved_name": "getTokenStartWith", "raw_body": "public String getTokenStartWith(){\n return tokenStartWith + \" \";\n}\n"}}, {"toLowerCase": {"retrieved_name": "toUnderScoreCase", "raw_body": "/** \n * \u9a7c\u5cf0\u547d\u540d\u6cd5\u5de5\u5177\n * @return toCamelCase(\" hello_world \") == \"helloWorld\"toCapitalizeCamelCase(\"hello_world\") == \"HelloWorld\" toUnderScoreCase(\"helloWorld\") = \"hello_world\"\n */\nstatic String toUnderScoreCase(String s){\n if (s == null) {\n return null;\n }\n StringBuilder sb=new StringBuilder();\n boolean upperCase=false;\n for (int i=0; i < s.length(); i++) {\n char c=s.charAt(i);\n boolean nextUpperCase=true;\n if (i < (s.length() - 1)) {\n nextUpperCase=Character.isUpperCase(s.charAt(i + 1));\n }\n if ((i > 0) && Character.isUpperCase(c)) {\n if (!upperCase || !nextUpperCase) {\n sb.append(SEPARATOR);\n }\n upperCase=true;\n }\n else {\n upperCase=false;\n }\n sb.append(Character.toLowerCase(c));\n }\n return sb.toString();\n}\n"}}] | [{"getPath": {"retrieved_name": "getFile", "raw_body": "public void getFile(String remoteFile,String localTargetDirectory){\n Connection conn=new Connection(ip,port);\n try {\n conn.connect();\n boolean isAuthenticated=conn.authenticateWithPassword(username,password);\n if (!isAuthenticated) {\n System.err.println(\"authentication failed\");\n }\n SCPClient client=new SCPClient(conn);\n client.get(remoteFile,localTargetDirectory);\n }\n catch ( IOException ex) {\n Logger.getLogger(SCPClient.class.getName()).log(Level.SEVERE,null,ex);\n }\n finally {\n conn.close();\n }\n}\n"}}] |
|
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-common/src/main/java/com/jarvis/lib/util/StringUtil.java | StringUtil | containsText | class StringUtil {
/**
* Check whether the given {@code CharSequence} contains actual <em>text</em>.
* <p>More specifically, this method returns {@code true} if the
* {@code CharSequence} is not {@code null}, its length is greater than
* 0, and it contains at least one non-whitespace character.
* <p><pre class="code">
* StringUtils.hasText(null) = false
* StringUtils.hasText("") = false
* StringUtils.hasText(" ") = false
* StringUtils.hasText("12345") = true
* StringUtils.hasText(" 12345 ") = true
* </pre>
* @param str the {@code CharSequence} to check (may be {@code null})
* @return {@code true} if the {@code CharSequence} is not {@code null},
* its length is greater than 0, and it does not contain whitespace only
* @see Character#isWhitespace
*/
public static boolean hasText(CharSequence str) {
return (str != null && str.length() > 0 && containsText(str));
}
/**
* Check whether the given {@code String} contains actual <em>text</em>.
* <p>More specifically, this method returns {@code true} if the
* {@code String} is not {@code null}, its length is greater than 0,
* and it contains at least one non-whitespace character.
* @param str the {@code String} to check (may be {@code null})
* @return {@code true} if the {@code String} is not {@code null}, its
* length is greater than 0, and it does not contain whitespace only
* @see #hasText(CharSequence)
*/
public static boolean hasText(String str) {
return (str != null && !str.isEmpty() && containsText(str));
}
private static boolean containsText(CharSequence str) {<FILL_FUNCTION_BODY>}
} |
int strLen = str.length();
for (int i = 0; i < strLen; i++) {
if (!Character.isWhitespace(str.charAt(i))) {
return true;
}
}
return false;
|
int strLen = str.length();
for (int i = 0; i < strLen; i++) {
if (!Character.isWhitespace(str.charAt(i))) {
return true;
}
}
return false;
| [] | [
"isWhitespace",
"charAt",
"length"
] | [] | [
"charAt",
"length",
"isWhitespace"
] | {
"methods": [
"isWhitespace",
"charAt",
"length"
],
"similar_methods": [
"containsText"
],
"types": []
} | public boolean isNamespaceEnable(){
return namespaceEnable;
}
private static byte[] write(Object obj) throws Exception {
byte barray[]=conf.asByteArray(obj);
return barray;
}
static long getLongLE(byte[] memory,int index){
return (long)memory[index] & 0xff | ((long)memory[index + 1] & 0xff) << 8 | ((long)memory[index + 2] & 0xff) << 16 | ((long)memory[index + 3] & 0xff) << 24 | ((long)memory[index + 4] & 0xff) << 32 | ((long)memory[index + 5] & 0xff) << 40 | ((long)memory[index + 6] & 0xff) << 48 | ((long)memory[index + 7] & 0xff) << 56;
}
| public boolean isNamespaceEnable(){
return namespaceEnable;
}
private static byte[] write(Object obj) throws Exception {
byte barray[]=conf.asByteArray(obj);
return barray;
}
static long getLongLE(byte[] memory,int index){
return (long)memory[index] & 0xff | ((long)memory[index + 1] & 0xff) << 8 | ((long)memory[index + 2] & 0xff) << 16 | ((long)memory[index + 3] & 0xff) << 24 | ((long)memory[index + 4] & 0xff) << 32 | ((long)memory[index + 5] & 0xff) << 40 | ((long)memory[index + 6] & 0xff) << 48 | ((long)memory[index + 7] & 0xff) << 56;
}
| {"methods": [{"isWhitespace": "isNamespaceEnable"}, {"charAt": "write"}, {"length": "getLongLE"}], "similar_methods": [{"containsText": ""}]} | [] | [{"isWhitespace": {"retrieved_name": "isNamespaceEnable", "raw_body": "public boolean isNamespaceEnable(){\n return namespaceEnable;\n}\n"}}, {"charAt": {"retrieved_name": "write", "raw_body": "private static byte[] write(Object obj) throws Exception {\n byte barray[]=conf.asByteArray(obj);\n return barray;\n}\n"}}, {"length": {"retrieved_name": "getLongLE", "raw_body": "static long getLongLE(byte[] memory,int index){\n return (long)memory[index] & 0xff | ((long)memory[index + 1] & 0xff) << 8 | ((long)memory[index + 2] & 0xff) << 16 | ((long)memory[index + 3] & 0xff) << 24 | ((long)memory[index + 4] & 0xff) << 32 | ((long)memory[index + 5] & 0xff) << 40 | ((long)memory[index + 6] & 0xff) << 48 | ((long)memory[index + 7] & 0xff) << 56;\n}\n"}}] | [] |
|
subhra74_snowflake | snowflake/muon-app/src/main/java/muon/app/ui/components/session/ImportDlg.java | ImportDlg | importSessionsFromWinScp | class ImportDlg extends JDialog {
// private JComboBox<String> items;
private JList<String> sessionList;
private DefaultListModel<String> model;
public ImportDlg(Window w, int index, DefaultMutableTreeNode node) {
super(w);
setSize(400, 300);
setLocationRelativeTo(w);
setModal(true);
model = new DefaultListModel<>();
sessionList = new JList<>(model);
sessionList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
switch (index) {
case 0:
importFromPutty();
break;
case 1:
importFromWinScp();
break;
}
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(new EmptyBorder(5, 5, 5, 5));
panel.add(new JScrollPane(sessionList));
add(panel);
Box b2 = Box.createHorizontalBox();
b2.setBorder(new EmptyBorder(0, 5, 5, 5));
JButton btnSelect = new JButton("Select all");
btnSelect.addActionListener(e -> {
int arr[] = new int[model.size()];
for (int i = 0; i < model.size(); i++) {
arr[i] = i;
}
sessionList.setSelectedIndices(arr);
});
JButton btnUnSelect = new JButton("Un-select all");
btnUnSelect.addActionListener(e -> {
int arr[] = new int[0];
sessionList.setSelectedIndices(arr);
});
b2.add(btnSelect);
b2.add(Box.createRigidArea(new Dimension(5, 5)));
b2.add(btnUnSelect);
b2.add(Box.createHorizontalGlue());
JButton btnImport = new JButton("Import");
btnImport.addActionListener(e -> {
switch (index) {
case 0:
importSessionsFromPutty(node);
break;
case 1:
importSessionsFromWinScp(node);
break;
}
dispose();
});
b2.add(btnImport);
add(b2, BorderLayout.SOUTH);
//importFromPutty();
}
private void importFromPutty() {
model.clear();
model.addAll(PuttyImporter.getKeyNames().keySet());
}
private void importFromWinScp() {
model.clear();
model.addAll(WinScpImporter.getKeyNames().keySet());
}
private void importSessionsFromPutty(DefaultMutableTreeNode node) {
List<String> list = new ArrayList<String>();
int arr[] = sessionList.getSelectedIndices();
if (arr != null) {
for (int i = 0; i < arr.length; i++) {
list.add(model.get(arr[i]));
}
}
PuttyImporter.importSessions(node, list);
// SessionFolder folder = SessionStore.load().getFolder();
// folder.getItems().addAll(sessions);
// SessionStore.store(folder);
}
private void importSessionsFromWinScp(DefaultMutableTreeNode node) {<FILL_FUNCTION_BODY>}
} |
List<String> list = new ArrayList<String>();
int arr[] = sessionList.getSelectedIndices();
if (arr != null) {
for (int i = 0; i < arr.length; i++) {
list.add(model.get(arr[i]));
}
}
WinScpImporter.importSessions(node, list);
// SessionFolder folder = SessionStore.load().getFolder();
// folder.getItems().addAll(sessions);
// SessionStore.store(folder);
|
List<String> list = new ArrayList<String>();
int arr[] = sessionList.getSelectedIndices();
if (arr != null) {
for (int i = 0; i < arr.length; i++) {
list.add(model.get(arr[i]));
}
}
WinScpImporter.importSessions(node, list);
// SessionFolder folder = SessionStore.load().getFolder();
// folder.getItems().addAll(sessions);
// SessionStore.store(folder);
| [
"JList<String>",
"DefaultListModel<String>",
"DefaultMutableTreeNode",
"List<String>"
] | [
"add",
"get",
"importSessions",
"getSelectedIndices"
] | [
"List<String>",
"DefaultListModel<String>",
"JList<String>",
"DefaultMutableTreeNode"
] | [
"getSelectedIndices",
"add",
"importSessions",
"get"
] | {
"methods": [
"add",
"get",
"importSessions",
"getSelectedIndices"
],
"similar_methods": [
"importSessionsFromWinScp"
],
"types": [
"JList<String>",
"DefaultListModel<String>",
"DefaultMutableTreeNode",
"List<String>"
]
} | public class ProcessListRenderer extends JLabel implements TableCellRenderer {
public ProcessListRenderer();
@Override public Component getTableCellRendererComponent( JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column);
}
public class DefaultSettingsProvider implements SettingsProvider {
@Override public KeyStroke[] getNewSessionKeyStrokes();
@Override public KeyStroke[] getCloseSessionKeyStrokes();
@Override public KeyStroke[] getCopyKeyStrokes();
@Override public KeyStroke[] getPasteKeyStrokes();
@Override public KeyStroke[] getClearBufferKeyStrokes();
@Override public KeyStroke[] getFindKeyStrokes();
@Override public KeyStroke[] getPageUpKeyStrokes();
@Override public KeyStroke[] getPageDownKeyStrokes();
@Override public KeyStroke[] getLineUpKeyStrokes();
@Override public KeyStroke[] getLineDownKeyStrokes();
@Override public ColorPalette getTerminalColorPalette();
@Override public Font getTerminalFont();
@Override public float getTerminalFontSize();
@Override public float getLineSpace();
@Override public TextStyle getDefaultStyle();
@Override public TextStyle getSelectionColor();
@Override public TextStyle getFoundPatternColor();
@Override public TextStyle getHyperlinkColor();
@Override public HyperlinkStyle.HighlightMode getHyperlinkHighlightingMode();
@Override public boolean useInverseSelectionColor();
@Override public boolean copyOnSelect();
@Override public boolean pasteOnMiddleMouseClick();
@Override public boolean emulateX11CopyPaste();
@Override public boolean useAntialiasing();
@Override public int maxRefreshRate();
@Override public boolean audibleBell();
@Override public boolean enableMouseReporting();
@Override public int caretBlinkingMs();
@Override public boolean scrollToBottomOnTyping();
@Override public boolean DECCompatibilityMode();
@Override public boolean forceActionOnMouseReporting();
@Override public int getBufferMaxLinesCount();
@Override public boolean altSendsEscape();
@Override public boolean ambiguousCharsAreDoubleWidth();
}
/**
* @author traff
*/
public class DefaultTabbedSettingsProvider extends DefaultSettingsProvider implements TabbedSettingsProvider {
@Override public boolean shouldCloseTabOnLogout( TtyConnector ttyConnector);
@Override public String tabName( TtyConnector ttyConnector, String sessionName);
@Override public KeyStroke[] getNextTabKeyStrokes();
@Override public KeyStroke[] getPreviousTabKeyStrokes();
}
public class SnippetListRenderer extends JPanel implements ListCellRenderer<SnippetItem> {
private JLabel lblName;
private JLabel lblCommand;
public SnippetListRenderer();
@Override public Component getListCellRendererComponent( JList<? extends SnippetItem> list, SnippetItem value, int index, boolean isSelected, boolean cellHasFocus);
}
public void add(TextEntry entry){
if (!entry.getText().isNul()) {
for ( TextEntry t : myTextEntries) {
if (t.getText().isNul()) {
t.getText().unNullify();
}
}
}
myTextEntries.add(entry);
myLength+=entry.getLength();
}
public ProcessTableEntry get(int index){
return processList.get(index);
}
public static void importSessions(DefaultMutableTreeNode node,List<String> keys){
for ( String key : keys) {
if (RegUtil.regGetInt(WinReg.HKEY_CURRENT_USER,WinSCPRegKey + "\\" + key,"FSProtocol") == 0) {
String host=RegUtil.regGetStr(WinReg.HKEY_CURRENT_USER,WinSCPRegKey + "\\" + key,"HostName");
int port=RegUtil.regGetInt(WinReg.HKEY_CURRENT_USER,WinSCPRegKey + "\\" + key,"PortNumber");
if (port == 0) port=22;
String user=RegUtil.regGetStr(WinReg.HKEY_CURRENT_USER,WinSCPRegKey + "\\" + key,"UserName");
String keyfile=RegUtil.regGetStr(WinReg.HKEY_CURRENT_USER,WinSCPRegKey + "\\" + key,"PublicKeyFile");
String proxyHost=RegUtil.regGetStr(WinReg.HKEY_CURRENT_USER,WinSCPRegKey + "\\" + key,"ProxyHost");
int proxyPort=RegUtil.regGetInt(WinReg.HKEY_CURRENT_USER,WinSCPRegKey + "\\" + key,"ProxyPort");
String proxyUser=RegUtil.regGetStr(WinReg.HKEY_CURRENT_USER,WinSCPRegKey + "\\" + key,"ProxyUsername");
String proxyPass=RegUtil.regGetStr(WinReg.HKEY_CURRENT_USER,WinSCPRegKey + "\\" + key,"ProxyPassword");
int proxyType=RegUtil.regGetInt(WinReg.HKEY_CURRENT_USER,WinSCPRegKey + "\\" + key,"ProxyMethod");
if (proxyType == 1) {
proxyType=2;
}
else if (proxyType == 2) {
proxyType=3;
}
else if (proxyType == 3) {
proxyType=1;
}
else {
proxyType=0;
}
SessionInfo info=new SessionInfo();
info.setHost(host);
info.setPort(port);
info.setUser(user);
try {
if (keyfile != null && keyfile.length() > 0) {
info.setPrivateKeyFile(URLDecoder.decode(keyfile,"utf-8"));
}
}
catch ( UnsupportedEncodingException e) {
e.printStackTrace();
}
info.setProxyHost(proxyHost);
info.setProxyPort(proxyPort);
info.setProxyUser(proxyUser);
info.setProxyPassword(proxyPass);
info.setProxyType(proxyType);
try {
String[] arr=URLDecoder.decode(key,"utf-8").split("/");
info.setName(arr[arr.length - 1]);
DefaultMutableTreeNode parent=node;
if (arr.length > 1) {
for (int i=0; i < arr.length - 1; i++) {
DefaultMutableTreeNode parent2=find(parent,arr[i]);
if (parent2 == null) {
SessionFolder folder=new SessionFolder();
folder.setName(arr[i]);
parent2=new DefaultMutableTreeNode(folder);
parent2.setAllowsChildren(true);
parent.add(parent2);
}
parent=parent2;
}
}
DefaultMutableTreeNode node1=new DefaultMutableTreeNode(info);
node1.setAllowsChildren(false);
parent.add(node1);
}
catch ( Exception e) {
e.printStackTrace();
}
}
}
}
public int getSelectedIndex(){
for (int i=0; i < tabHolder.getComponentCount(); i++) {
JComponent c=(JComponent)tabHolder.getComponent(i);
if (c.getClientProperty("selected") == Boolean.TRUE) {
return i;
}
}
return -1;
}
public static void importSessions(DefaultMutableTreeNode node,List<String> keys){
for ( String key : keys) {
if (RegUtil.regGetInt(WinReg.HKEY_CURRENT_USER,WinSCPRegKey + "\\" + key,"FSProtocol") == 0) {
String host=RegUtil.regGetStr(WinReg.HKEY_CURRENT_USER,WinSCPRegKey + "\\" + key,"HostName");
int port=RegUtil.regGetInt(WinReg.HKEY_CURRENT_USER,WinSCPRegKey + "\\" + key,"PortNumber");
if (port == 0) port=22;
String user=RegUtil.regGetStr(WinReg.HKEY_CURRENT_USER,WinSCPRegKey + "\\" + key,"UserName");
String keyfile=RegUtil.regGetStr(WinReg.HKEY_CURRENT_USER,WinSCPRegKey + "\\" + key,"PublicKeyFile");
String proxyHost=RegUtil.regGetStr(WinReg.HKEY_CURRENT_USER,WinSCPRegKey + "\\" + key,"ProxyHost");
int proxyPort=RegUtil.regGetInt(WinReg.HKEY_CURRENT_USER,WinSCPRegKey + "\\" + key,"ProxyPort");
String proxyUser=RegUtil.regGetStr(WinReg.HKEY_CURRENT_USER,WinSCPRegKey + "\\" + key,"ProxyUsername");
String proxyPass=RegUtil.regGetStr(WinReg.HKEY_CURRENT_USER,WinSCPRegKey + "\\" + key,"ProxyPassword");
int proxyType=RegUtil.regGetInt(WinReg.HKEY_CURRENT_USER,WinSCPRegKey + "\\" + key,"ProxyMethod");
if (proxyType == 1) {
proxyType=2;
}
else if (proxyType == 2) {
proxyType=3;
}
else if (proxyType == 3) {
proxyType=1;
}
else {
proxyType=0;
}
SessionInfo info=new SessionInfo();
info.setHost(host);
info.setPort(port);
info.setUser(user);
try {
if (keyfile != null && keyfile.length() > 0) {
info.setPrivateKeyFile(URLDecoder.decode(keyfile,"utf-8"));
}
}
catch ( UnsupportedEncodingException e) {
e.printStackTrace();
}
info.setProxyHost(proxyHost);
info.setProxyPort(proxyPort);
info.setProxyUser(proxyUser);
info.setProxyPassword(proxyPass);
info.setProxyType(proxyType);
try {
String[] arr=URLDecoder.decode(key,"utf-8").split("/");
info.setName(arr[arr.length - 1]);
DefaultMutableTreeNode parent=node;
if (arr.length > 1) {
for (int i=0; i < arr.length - 1; i++) {
DefaultMutableTreeNode parent2=find(parent,arr[i]);
if (parent2 == null) {
SessionFolder folder=new SessionFolder();
folder.setName(arr[i]);
parent2=new DefaultMutableTreeNode(folder);
parent2.setAllowsChildren(true);
parent.add(parent2);
}
parent=parent2;
}
}
DefaultMutableTreeNode node1=new DefaultMutableTreeNode(info);
node1.setAllowsChildren(false);
parent.add(node1);
}
catch ( Exception e) {
e.printStackTrace();
}
}
}
}
| public class ProcessListRenderer extends JLabel implements TableCellRenderer {
public ProcessListRenderer();
public Component getTableCellRendererComponent( JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column);
}
public class DefaultSettingsProvider implements SettingsProvider {
public KeyStroke[] getNewSessionKeyStrokes();
public KeyStroke[] getCloseSessionKeyStrokes();
public KeyStroke[] getCopyKeyStrokes();
public KeyStroke[] getPasteKeyStrokes();
public KeyStroke[] getClearBufferKeyStrokes();
public KeyStroke[] getFindKeyStrokes();
public KeyStroke[] getPageUpKeyStrokes();
public KeyStroke[] getPageDownKeyStrokes();
public KeyStroke[] getLineUpKeyStrokes();
public KeyStroke[] getLineDownKeyStrokes();
public ColorPalette getTerminalColorPalette();
public Font getTerminalFont();
public float getTerminalFontSize();
public float getLineSpace();
public TextStyle getDefaultStyle();
public TextStyle getSelectionColor();
public TextStyle getFoundPatternColor();
public TextStyle getHyperlinkColor();
public HyperlinkStyle.HighlightMode getHyperlinkHighlightingMode();
public boolean useInverseSelectionColor();
public boolean copyOnSelect();
public boolean pasteOnMiddleMouseClick();
public boolean emulateX11CopyPaste();
public boolean useAntialiasing();
public int maxRefreshRate();
public boolean audibleBell();
public boolean enableMouseReporting();
public int caretBlinkingMs();
public boolean scrollToBottomOnTyping();
public boolean DECCompatibilityMode();
public boolean forceActionOnMouseReporting();
public int getBufferMaxLinesCount();
public boolean altSendsEscape();
public boolean ambiguousCharsAreDoubleWidth();
}
public class DefaultTabbedSettingsProvider extends DefaultSettingsProvider implements TabbedSettingsProvider {
public boolean shouldCloseTabOnLogout( TtyConnector ttyConnector);
public String tabName( TtyConnector ttyConnector, String sessionName);
public KeyStroke[] getNextTabKeyStrokes();
public KeyStroke[] getPreviousTabKeyStrokes();
}
public class SnippetListRenderer extends JPanel implements ListCellRenderer<SnippetItem> {
private JLabel lblName;
private JLabel lblCommand;
public SnippetListRenderer();
public Component getListCellRendererComponent( JList<? extends SnippetItem> list, SnippetItem value, int index, boolean isSelected, boolean cellHasFocus);
}
public void add(TextEntry entry){
if (!entry.getText().isNul()) {
for ( TextEntry t : myTextEntries) {
if (t.getText().isNul()) {
t.getText().unNullify();
}
}
}
myTextEntries.add(entry);
myLength+=entry.getLength();
}
public ProcessTableEntry get(int index){
return processList.get(index);
}
public static void importSessions(DefaultMutableTreeNode node,List<String> keys){
for ( String key : keys) {
if (RegUtil.regGetInt(WinReg.HKEY_CURRENT_USER,WinSCPRegKey + "\\" + key,"FSProtocol") == 0) {
String host=RegUtil.regGetStr(WinReg.HKEY_CURRENT_USER,WinSCPRegKey + "\\" + key,"HostName");
int port=RegUtil.regGetInt(WinReg.HKEY_CURRENT_USER,WinSCPRegKey + "\\" + key,"PortNumber");
if (port == 0) port=22;
String user=RegUtil.regGetStr(WinReg.HKEY_CURRENT_USER,WinSCPRegKey + "\\" + key,"UserName");
String keyfile=RegUtil.regGetStr(WinReg.HKEY_CURRENT_USER,WinSCPRegKey + "\\" + key,"PublicKeyFile");
String proxyHost=RegUtil.regGetStr(WinReg.HKEY_CURRENT_USER,WinSCPRegKey + "\\" + key,"ProxyHost");
int proxyPort=RegUtil.regGetInt(WinReg.HKEY_CURRENT_USER,WinSCPRegKey + "\\" + key,"ProxyPort");
String proxyUser=RegUtil.regGetStr(WinReg.HKEY_CURRENT_USER,WinSCPRegKey + "\\" + key,"ProxyUsername");
String proxyPass=RegUtil.regGetStr(WinReg.HKEY_CURRENT_USER,WinSCPRegKey + "\\" + key,"ProxyPassword");
int proxyType=RegUtil.regGetInt(WinReg.HKEY_CURRENT_USER,WinSCPRegKey + "\\" + key,"ProxyMethod");
if (proxyType == 1) {
proxyType=2;
}
else if (proxyType == 2) {
proxyType=3;
}
else if (proxyType == 3) {
proxyType=1;
}
else {
proxyType=0;
}
SessionInfo info=new SessionInfo();
info.setHost(host);
info.setPort(port);
info.setUser(user);
try {
if (keyfile != null && keyfile.length() > 0) {
info.setPrivateKeyFile(URLDecoder.decode(keyfile,"utf-8"));
}
}
catch ( UnsupportedEncodingException e) {
e.printStackTrace();
}
info.setProxyHost(proxyHost);
info.setProxyPort(proxyPort);
info.setProxyUser(proxyUser);
info.setProxyPassword(proxyPass);
info.setProxyType(proxyType);
try {
String[] arr=URLDecoder.decode(key,"utf-8").split("/");
info.setName(arr[arr.length - 1]);
DefaultMutableTreeNode parent=node;
if (arr.length > 1) {
for (int i=0; i < arr.length - 1; i++) {
DefaultMutableTreeNode parent2=find(parent,arr[i]);
if (parent2 == null) {
SessionFolder folder=new SessionFolder();
folder.setName(arr[i]);
parent2=new DefaultMutableTreeNode(folder);
parent2.setAllowsChildren(true);
parent.add(parent2);
}
parent=parent2;
}
}
DefaultMutableTreeNode node1=new DefaultMutableTreeNode(info);
node1.setAllowsChildren(false);
parent.add(node1);
}
catch ( Exception e) {
e.printStackTrace();
}
}
}
}
public int getSelectedIndex(){
for (int i=0; i < tabHolder.getComponentCount(); i++) {
JComponent c=(JComponent)tabHolder.getComponent(i);
if (c.getClientProperty("selected") == Boolean.TRUE) {
return i;
}
}
return -1;
}
public static void importSessions(DefaultMutableTreeNode node,List<String> keys){
for ( String key : keys) {
if (RegUtil.regGetInt(WinReg.HKEY_CURRENT_USER,WinSCPRegKey + "\\" + key,"FSProtocol") == 0) {
String host=RegUtil.regGetStr(WinReg.HKEY_CURRENT_USER,WinSCPRegKey + "\\" + key,"HostName");
int port=RegUtil.regGetInt(WinReg.HKEY_CURRENT_USER,WinSCPRegKey + "\\" + key,"PortNumber");
if (port == 0) port=22;
String user=RegUtil.regGetStr(WinReg.HKEY_CURRENT_USER,WinSCPRegKey + "\\" + key,"UserName");
String keyfile=RegUtil.regGetStr(WinReg.HKEY_CURRENT_USER,WinSCPRegKey + "\\" + key,"PublicKeyFile");
String proxyHost=RegUtil.regGetStr(WinReg.HKEY_CURRENT_USER,WinSCPRegKey + "\\" + key,"ProxyHost");
int proxyPort=RegUtil.regGetInt(WinReg.HKEY_CURRENT_USER,WinSCPRegKey + "\\" + key,"ProxyPort");
String proxyUser=RegUtil.regGetStr(WinReg.HKEY_CURRENT_USER,WinSCPRegKey + "\\" + key,"ProxyUsername");
String proxyPass=RegUtil.regGetStr(WinReg.HKEY_CURRENT_USER,WinSCPRegKey + "\\" + key,"ProxyPassword");
int proxyType=RegUtil.regGetInt(WinReg.HKEY_CURRENT_USER,WinSCPRegKey + "\\" + key,"ProxyMethod");
if (proxyType == 1) {
proxyType=2;
}
else if (proxyType == 2) {
proxyType=3;
}
else if (proxyType == 3) {
proxyType=1;
}
else {
proxyType=0;
}
SessionInfo info=new SessionInfo();
info.setHost(host);
info.setPort(port);
info.setUser(user);
try {
if (keyfile != null && keyfile.length() > 0) {
info.setPrivateKeyFile(URLDecoder.decode(keyfile,"utf-8"));
}
}
catch ( UnsupportedEncodingException e) {
e.printStackTrace();
}
info.setProxyHost(proxyHost);
info.setProxyPort(proxyPort);
info.setProxyUser(proxyUser);
info.setProxyPassword(proxyPass);
info.setProxyType(proxyType);
try {
String[] arr=URLDecoder.decode(key,"utf-8").split("/");
info.setName(arr[arr.length - 1]);
DefaultMutableTreeNode parent=node;
if (arr.length > 1) {
for (int i=0; i < arr.length - 1; i++) {
DefaultMutableTreeNode parent2=find(parent,arr[i]);
if (parent2 == null) {
SessionFolder folder=new SessionFolder();
folder.setName(arr[i]);
parent2=new DefaultMutableTreeNode(folder);
parent2.setAllowsChildren(true);
parent.add(parent2);
}
parent=parent2;
}
}
DefaultMutableTreeNode node1=new DefaultMutableTreeNode(info);
node1.setAllowsChildren(false);
parent.add(node1);
}
catch ( Exception e) {
e.printStackTrace();
}
}
}
}
| {"types": [{"JList<String>": "ProcessListRenderer"}, {"DefaultListModel<String>": "DefaultSettingsProvider"}, {"DefaultMutableTreeNode": "DefaultTabbedSettingsProvider"}, {"List<String>": "SnippetListRenderer"}], "methods": [{"add": "add"}, {"get": "get"}, {"importSessions": "importSessions"}, {"getSelectedIndices": "getSelectedIndex"}], "similar_methods": [{"importSessionsFromWinScp": "importSessions"}]} | [{"JList<String>": {"retrieved_name": "ProcessListRenderer", "raw_body": "public class ProcessListRenderer extends JLabel implements TableCellRenderer {\n public ProcessListRenderer();\n @Override public Component getTableCellRendererComponent( JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column);\n}\n", "raw_body_no_cmt": "public class ProcessListRenderer extends JLabel implements TableCellRenderer {\n public ProcessListRenderer();\n public Component getTableCellRendererComponent( JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column);\n}\n"}}, {"DefaultListModel<String>": {"retrieved_name": "DefaultSettingsProvider", "raw_body": "public class DefaultSettingsProvider implements SettingsProvider {\n @Override public KeyStroke[] getNewSessionKeyStrokes();\n @Override public KeyStroke[] getCloseSessionKeyStrokes();\n @Override public KeyStroke[] getCopyKeyStrokes();\n @Override public KeyStroke[] getPasteKeyStrokes();\n @Override public KeyStroke[] getClearBufferKeyStrokes();\n @Override public KeyStroke[] getFindKeyStrokes();\n @Override public KeyStroke[] getPageUpKeyStrokes();\n @Override public KeyStroke[] getPageDownKeyStrokes();\n @Override public KeyStroke[] getLineUpKeyStrokes();\n @Override public KeyStroke[] getLineDownKeyStrokes();\n @Override public ColorPalette getTerminalColorPalette();\n @Override public Font getTerminalFont();\n @Override public float getTerminalFontSize();\n @Override public float getLineSpace();\n @Override public TextStyle getDefaultStyle();\n @Override public TextStyle getSelectionColor();\n @Override public TextStyle getFoundPatternColor();\n @Override public TextStyle getHyperlinkColor();\n @Override public HyperlinkStyle.HighlightMode getHyperlinkHighlightingMode();\n @Override public boolean useInverseSelectionColor();\n @Override public boolean copyOnSelect();\n @Override public boolean pasteOnMiddleMouseClick();\n @Override public boolean emulateX11CopyPaste();\n @Override public boolean useAntialiasing();\n @Override public int maxRefreshRate();\n @Override public boolean audibleBell();\n @Override public boolean enableMouseReporting();\n @Override public int caretBlinkingMs();\n @Override public boolean scrollToBottomOnTyping();\n @Override public boolean DECCompatibilityMode();\n @Override public boolean forceActionOnMouseReporting();\n @Override public int getBufferMaxLinesCount();\n @Override public boolean altSendsEscape();\n @Override public boolean ambiguousCharsAreDoubleWidth();\n}\n", "raw_body_no_cmt": "public class DefaultSettingsProvider implements SettingsProvider {\n public KeyStroke[] getNewSessionKeyStrokes();\n public KeyStroke[] getCloseSessionKeyStrokes();\n public KeyStroke[] getCopyKeyStrokes();\n public KeyStroke[] getPasteKeyStrokes();\n public KeyStroke[] getClearBufferKeyStrokes();\n public KeyStroke[] getFindKeyStrokes();\n public KeyStroke[] getPageUpKeyStrokes();\n public KeyStroke[] getPageDownKeyStrokes();\n public KeyStroke[] getLineUpKeyStrokes();\n public KeyStroke[] getLineDownKeyStrokes();\n public ColorPalette getTerminalColorPalette();\n public Font getTerminalFont();\n public float getTerminalFontSize();\n public float getLineSpace();\n public TextStyle getDefaultStyle();\n public TextStyle getSelectionColor();\n public TextStyle getFoundPatternColor();\n public TextStyle getHyperlinkColor();\n public HyperlinkStyle.HighlightMode getHyperlinkHighlightingMode();\n public boolean useInverseSelectionColor();\n public boolean copyOnSelect();\n public boolean pasteOnMiddleMouseClick();\n public boolean emulateX11CopyPaste();\n public boolean useAntialiasing();\n public int maxRefreshRate();\n public boolean audibleBell();\n public boolean enableMouseReporting();\n public int caretBlinkingMs();\n public boolean scrollToBottomOnTyping();\n public boolean DECCompatibilityMode();\n public boolean forceActionOnMouseReporting();\n public int getBufferMaxLinesCount();\n public boolean altSendsEscape();\n public boolean ambiguousCharsAreDoubleWidth();\n}\n"}}, {"DefaultMutableTreeNode": {"retrieved_name": "DefaultTabbedSettingsProvider", "raw_body": "/** \n * @author traff\n */\npublic class DefaultTabbedSettingsProvider extends DefaultSettingsProvider implements TabbedSettingsProvider {\n @Override public boolean shouldCloseTabOnLogout( TtyConnector ttyConnector);\n @Override public String tabName( TtyConnector ttyConnector, String sessionName);\n @Override public KeyStroke[] getNextTabKeyStrokes();\n @Override public KeyStroke[] getPreviousTabKeyStrokes();\n}\n", "raw_body_no_cmt": "public class DefaultTabbedSettingsProvider extends DefaultSettingsProvider implements TabbedSettingsProvider {\n public boolean shouldCloseTabOnLogout( TtyConnector ttyConnector);\n public String tabName( TtyConnector ttyConnector, String sessionName);\n public KeyStroke[] getNextTabKeyStrokes();\n public KeyStroke[] getPreviousTabKeyStrokes();\n}\n"}}, {"List<String>": {"retrieved_name": "SnippetListRenderer", "raw_body": "public class SnippetListRenderer extends JPanel implements ListCellRenderer<SnippetItem> {\n private JLabel lblName;\n private JLabel lblCommand;\n public SnippetListRenderer();\n @Override public Component getListCellRendererComponent( JList<? extends SnippetItem> list, SnippetItem value, int index, boolean isSelected, boolean cellHasFocus);\n}\n", "raw_body_no_cmt": "public class SnippetListRenderer extends JPanel implements ListCellRenderer<SnippetItem> {\n private JLabel lblName;\n private JLabel lblCommand;\n public SnippetListRenderer();\n public Component getListCellRendererComponent( JList<? extends SnippetItem> list, SnippetItem value, int index, boolean isSelected, boolean cellHasFocus);\n}\n"}}] | [{"add": {"retrieved_name": "add", "raw_body": "public void add(TextEntry entry){\n if (!entry.getText().isNul()) {\n for ( TextEntry t : myTextEntries) {\n if (t.getText().isNul()) {\n t.getText().unNullify();\n }\n }\n }\n myTextEntries.add(entry);\n myLength+=entry.getLength();\n}\n"}}, {"get": {"retrieved_name": "get", "raw_body": "public ProcessTableEntry get(int index){\n return processList.get(index);\n}\n"}}, {"importSessions": {"retrieved_name": "importSessions", "raw_body": "public static void importSessions(DefaultMutableTreeNode node,List<String> keys){\n for ( String key : keys) {\n if (RegUtil.regGetInt(WinReg.HKEY_CURRENT_USER,WinSCPRegKey + \"\\\\\" + key,\"FSProtocol\") == 0) {\n String host=RegUtil.regGetStr(WinReg.HKEY_CURRENT_USER,WinSCPRegKey + \"\\\\\" + key,\"HostName\");\n int port=RegUtil.regGetInt(WinReg.HKEY_CURRENT_USER,WinSCPRegKey + \"\\\\\" + key,\"PortNumber\");\n if (port == 0) port=22;\n String user=RegUtil.regGetStr(WinReg.HKEY_CURRENT_USER,WinSCPRegKey + \"\\\\\" + key,\"UserName\");\n String keyfile=RegUtil.regGetStr(WinReg.HKEY_CURRENT_USER,WinSCPRegKey + \"\\\\\" + key,\"PublicKeyFile\");\n String proxyHost=RegUtil.regGetStr(WinReg.HKEY_CURRENT_USER,WinSCPRegKey + \"\\\\\" + key,\"ProxyHost\");\n int proxyPort=RegUtil.regGetInt(WinReg.HKEY_CURRENT_USER,WinSCPRegKey + \"\\\\\" + key,\"ProxyPort\");\n String proxyUser=RegUtil.regGetStr(WinReg.HKEY_CURRENT_USER,WinSCPRegKey + \"\\\\\" + key,\"ProxyUsername\");\n String proxyPass=RegUtil.regGetStr(WinReg.HKEY_CURRENT_USER,WinSCPRegKey + \"\\\\\" + key,\"ProxyPassword\");\n int proxyType=RegUtil.regGetInt(WinReg.HKEY_CURRENT_USER,WinSCPRegKey + \"\\\\\" + key,\"ProxyMethod\");\n if (proxyType == 1) {\n proxyType=2;\n }\n else if (proxyType == 2) {\n proxyType=3;\n }\n else if (proxyType == 3) {\n proxyType=1;\n }\n else {\n proxyType=0;\n }\n SessionInfo info=new SessionInfo();\n info.setHost(host);\n info.setPort(port);\n info.setUser(user);\n try {\n if (keyfile != null && keyfile.length() > 0) {\n info.setPrivateKeyFile(URLDecoder.decode(keyfile,\"utf-8\"));\n }\n }\n catch ( UnsupportedEncodingException e) {\n e.printStackTrace();\n }\n info.setProxyHost(proxyHost);\n info.setProxyPort(proxyPort);\n info.setProxyUser(proxyUser);\n info.setProxyPassword(proxyPass);\n info.setProxyType(proxyType);\n try {\n String[] arr=URLDecoder.decode(key,\"utf-8\").split(\"/\");\n info.setName(arr[arr.length - 1]);\n DefaultMutableTreeNode parent=node;\n if (arr.length > 1) {\n for (int i=0; i < arr.length - 1; i++) {\n DefaultMutableTreeNode parent2=find(parent,arr[i]);\n if (parent2 == null) {\n SessionFolder folder=new SessionFolder();\n folder.setName(arr[i]);\n parent2=new DefaultMutableTreeNode(folder);\n parent2.setAllowsChildren(true);\n parent.add(parent2);\n }\n parent=parent2;\n }\n }\n DefaultMutableTreeNode node1=new DefaultMutableTreeNode(info);\n node1.setAllowsChildren(false);\n parent.add(node1);\n }\n catch ( Exception e) {\n e.printStackTrace();\n }\n }\n }\n}\n"}}, {"getSelectedIndices": {"retrieved_name": "getSelectedIndex", "raw_body": "public int getSelectedIndex(){\n for (int i=0; i < tabHolder.getComponentCount(); i++) {\n JComponent c=(JComponent)tabHolder.getComponent(i);\n if (c.getClientProperty(\"selected\") == Boolean.TRUE) {\n return i;\n }\n }\n return -1;\n}\n"}}] | [{"importSessionsFromWinScp": {"retrieved_name": "importSessions", "raw_body": "public static void importSessions(DefaultMutableTreeNode node,List<String> keys){\n for ( String key : keys) {\n if (RegUtil.regGetInt(WinReg.HKEY_CURRENT_USER,WinSCPRegKey + \"\\\\\" + key,\"FSProtocol\") == 0) {\n String host=RegUtil.regGetStr(WinReg.HKEY_CURRENT_USER,WinSCPRegKey + \"\\\\\" + key,\"HostName\");\n int port=RegUtil.regGetInt(WinReg.HKEY_CURRENT_USER,WinSCPRegKey + \"\\\\\" + key,\"PortNumber\");\n if (port == 0) port=22;\n String user=RegUtil.regGetStr(WinReg.HKEY_CURRENT_USER,WinSCPRegKey + \"\\\\\" + key,\"UserName\");\n String keyfile=RegUtil.regGetStr(WinReg.HKEY_CURRENT_USER,WinSCPRegKey + \"\\\\\" + key,\"PublicKeyFile\");\n String proxyHost=RegUtil.regGetStr(WinReg.HKEY_CURRENT_USER,WinSCPRegKey + \"\\\\\" + key,\"ProxyHost\");\n int proxyPort=RegUtil.regGetInt(WinReg.HKEY_CURRENT_USER,WinSCPRegKey + \"\\\\\" + key,\"ProxyPort\");\n String proxyUser=RegUtil.regGetStr(WinReg.HKEY_CURRENT_USER,WinSCPRegKey + \"\\\\\" + key,\"ProxyUsername\");\n String proxyPass=RegUtil.regGetStr(WinReg.HKEY_CURRENT_USER,WinSCPRegKey + \"\\\\\" + key,\"ProxyPassword\");\n int proxyType=RegUtil.regGetInt(WinReg.HKEY_CURRENT_USER,WinSCPRegKey + \"\\\\\" + key,\"ProxyMethod\");\n if (proxyType == 1) {\n proxyType=2;\n }\n else if (proxyType == 2) {\n proxyType=3;\n }\n else if (proxyType == 3) {\n proxyType=1;\n }\n else {\n proxyType=0;\n }\n SessionInfo info=new SessionInfo();\n info.setHost(host);\n info.setPort(port);\n info.setUser(user);\n try {\n if (keyfile != null && keyfile.length() > 0) {\n info.setPrivateKeyFile(URLDecoder.decode(keyfile,\"utf-8\"));\n }\n }\n catch ( UnsupportedEncodingException e) {\n e.printStackTrace();\n }\n info.setProxyHost(proxyHost);\n info.setProxyPort(proxyPort);\n info.setProxyUser(proxyUser);\n info.setProxyPassword(proxyPass);\n info.setProxyType(proxyType);\n try {\n String[] arr=URLDecoder.decode(key,\"utf-8\").split(\"/\");\n info.setName(arr[arr.length - 1]);\n DefaultMutableTreeNode parent=node;\n if (arr.length > 1) {\n for (int i=0; i < arr.length - 1; i++) {\n DefaultMutableTreeNode parent2=find(parent,arr[i]);\n if (parent2 == null) {\n SessionFolder folder=new SessionFolder();\n folder.setName(arr[i]);\n parent2=new DefaultMutableTreeNode(folder);\n parent2.setAllowsChildren(true);\n parent.add(parent2);\n }\n parent=parent2;\n }\n }\n DefaultMutableTreeNode node1=new DefaultMutableTreeNode(info);\n node1.setAllowsChildren(false);\n parent.add(node1);\n }\n catch ( Exception e) {\n e.printStackTrace();\n }\n }\n }\n}\n"}}] |
|
orientechnologies_orientdb | orientdb/core/src/main/java/com/orientechnologies/orient/core/sql/OSQLScriptEngine.java | OSQLScriptEngine | eval | class OSQLScriptEngine implements ScriptEngine {
public static final String NAME = "sql";
private ScriptEngineFactory factory;
public OSQLScriptEngine(ScriptEngineFactory factory) {
this.factory = factory;
}
@Override
public Object eval(String script, ScriptContext context) throws ScriptException {
return eval(script, (Bindings) null);
}
@Override
public Object eval(Reader reader, ScriptContext context) throws ScriptException {
return eval(reader, (Bindings) null);
}
@Override
public Object eval(String script) throws ScriptException {
return eval(script, (Bindings) null);
}
@Override
public Object eval(Reader reader) throws ScriptException {
return eval(reader, (Bindings) null);
}
@Override
public Object eval(String script, Bindings n) throws ScriptException {<FILL_FUNCTION_BODY>}
@SuppressWarnings("unchecked")
protected Map<Object, Object> convertToParameters(Object... iArgs) {
final Map<Object, Object> params;
if (iArgs.length == 1 && iArgs[0] instanceof Map) {
params = (Map<Object, Object>) iArgs[0];
} else {
if (iArgs.length == 1
&& iArgs[0] != null
&& iArgs[0].getClass().isArray()
&& iArgs[0] instanceof Object[]) iArgs = (Object[]) iArgs[0];
params = new HashMap<Object, Object>(iArgs.length);
for (int i = 0; i < iArgs.length; ++i) {
Object par = iArgs[i];
if (par instanceof OIdentifiable && ((OIdentifiable) par).getIdentity().isValid())
// USE THE RID ONLY
par = ((OIdentifiable) par).getIdentity();
params.put(i, par);
}
}
return params;
}
@Override
public Object eval(Reader reader, Bindings n) throws ScriptException {
final StringBuilder buffer = new StringBuilder();
try {
while (reader.ready()) buffer.append((char) reader.read());
} catch (IOException e) {
throw new ScriptException(e);
}
return new OCommandScript(buffer.toString()).execute(n);
}
@Override
public void put(String key, Object value) {}
@Override
public Object get(String key) {
return null;
}
@Override
public Bindings getBindings(int scope) {
return new SimpleBindings();
}
@Override
public void setBindings(Bindings bindings, int scope) {}
@Override
public Bindings createBindings() {
return new SimpleBindings();
}
@Override
public ScriptContext getContext() {
return null;
}
@Override
public void setContext(ScriptContext context) {}
@Override
public ScriptEngineFactory getFactory() {
return factory;
}
} |
ODatabaseDocumentInternal db = ODatabaseRecordThreadLocal.instance().getIfDefined();
if (db == null) {
throw new OCommandExecutionException("No database available in threadlocal");
}
Map<Object, Object> params = convertToParameters(n);
OResultSet queryResult;
if (params.keySet().stream().anyMatch(x -> !(x instanceof String))) {
queryResult = db.execute("sql", script, params);
} else {
queryResult = db.execute("sql", script, (Map) params);
}
try (OResultSet res = queryResult) {
OLegacyResultSet finalResult = new OBasicLegacyResultSet();
res.stream().forEach(x -> finalResult.add(x));
return finalResult;
}
|
return new OCommandScript(script).execute(n);
| [
"Bindings",
"Reader",
"IOException"
] | [
"append",
"toString",
"execute",
"read",
"ready"
] | [
"Reader",
"Bindings",
"IOException"
] | [
"ready",
"append",
"execute",
"toString",
"read"
] | {
"methods": [
"append",
"toString",
"execute",
"read",
"ready"
],
"similar_methods": [
"eval"
],
"types": [
"Bindings",
"Reader",
"IOException"
]
} | public class Streams {
public static <T>Stream<T> mergeSortedSpliterators( Stream<T> streamOne, Stream<T> streamTwo, Comparator<? super T> comparator);
private static final class SortedStreamSpliterator<T> implements Spliterator<T>, Consumer<T> {
private boolean firstStream;
private final Spliterator<T> firstSpliterator;
private final Spliterator<T> secondSpliterator;
private T firstValue;
private T secondValue;
private final Comparator<? super T> comparator;
private SortedStreamSpliterator( Spliterator<T> firstSpliterator, Spliterator<T> secondSpliterator, Comparator<? super T> comparator);
@Override public boolean tryAdvance( Consumer<? super T> action);
@Override public Spliterator<T> trySplit();
@Override public long estimateSize();
@Override public int characteristics();
@Override public Comparator<? super T> getComparator();
@Override public void accept( T t);
}
private static Runnable composedClose( BaseStream<?,?> a, BaseStream<?,?> b);
}
/**
* @Internal
*/
public interface RecordReader {
ORawBuffer readRecord( OStorage storage, ORecordId rid, String fetchPlan, boolean ignoreCache, final int recordVersion) throws ORecordNotFoundException ;
}
public class OIOException extends OSystemException {
private static final long serialVersionUID=-3003977236203691448L;
public OIOException( OIOException exception);
public OIOException( String string);
}
public OTraversePath append(OIdentifiable record){
return new OTraversePath(new RecordPathItem(record,lastPathItem));
}
@Override public String toString(){
return "OQuarto{" + "one=" + one + ", two="+ two+ ", three="+ three+ ", four="+ four+ '}';
}
/**
* Execute a script in a specified query language. The result set has to be closed after usage <br> <br> Sample usage: <p><code> String script = "INSERT INTO Person SET name = 'foo', surname = ?;"+ "INSERT INTO Person SET name = 'bar', surname = ?;"+ "INSERT INTO Person SET name = 'baz', surname = ?;"; <p> OResultSet rs = db.execute("sql", script, "Surname1", "Surname2", "Surname3"); ... rs.close(); </code>
* @param language
* @param script
* @param args
* @return
*/
default OResultSet execute(String language,String script,Object... args) throws OCommandExecutionException, OCommandScriptException {
throw new UnsupportedOperationException();
}
@Override public void read(OChannelDataInput network,OStorageRemoteSession session) throws IOException {
}
/**
* Creates the databases as follows: - server1: db A, db B - server2: db B, db C
* @throws IOException
*/
@Override protected void prepare(final boolean iCopyDatabaseToNodes,final boolean iCreateDatabase) throws IOException {
serverInstance.remove(2);
ServerRun master=serverInstance.get(0);
OrientDB orientDB=new OrientDB("embedded:" + master.getServerHome() + "/databases/",OrientDBConfig.defaultConfig());
if (iCreateDatabase) {
orientDB.execute("create database ? plocal users(admin identified by 'admin' role admin)",dbA);
orientDB.execute("create database ? plocal users(admin identified by 'admin' role admin)",dbB);
final ODatabaseDocument graph1=orientDB.open(dbA,"admin","admin");
final ODatabaseDocument graph2=orientDB.open(dbB,"admin","admin");
try {
onAfterDatabaseCreation(graph1);
onAfterDatabaseCreation(graph2);
}
finally {
if (!graph1.isClosed()) {
graph1.activateOnCurrentThread();
graph1.close();
}
if (!graph2.isClosed()) {
graph2.activateOnCurrentThread();
graph2.close();
}
orientDB.close();
}
}
if (iCopyDatabaseToNodes) master.copyDatabase(dbB,serverInstance.get(1).getDatabasePath(dbB));
master=serverInstance.get(1);
OrientDB orientDB1=new OrientDB("embedded:" + master.getServerHome() + "/databases/",OrientDBConfig.defaultConfig());
if (iCreateDatabase) {
orientDB1.execute("create database ? plocal users(admin identified by 'admin' role admin)",dbC);
final ODatabaseDocument graph1=orientDB1.open(dbC,"admin","admin");
try {
onAfterDatabaseCreation(graph1);
}
finally {
if (!graph1.isClosed()) {
graph1.close();
}
orientDB1.close();
}
}
}
/**
* Evaluates a SQL expression against current document by passing a context. The expression can refer to the variables contained in the context. Example: <code> OCommandContext context = new OBasicCommandContext().setVariable("vat", 20); long amountPlusVat = doc.eval("amount * (100+$vat) / 100", context); </code>
* @param iExpression SQL expression to evaluate.
* @return The result of expression
* @throws OQueryParsingException in case the expression is not valid
*/
public Object eval(final String iExpression,final OCommandContext iContext){
return new OSQLPredicate(iExpression).evaluate(this,null,iContext);
}
| public class Streams {
public static <T>Stream<T> mergeSortedSpliterators( Stream<T> streamOne, Stream<T> streamTwo, Comparator<? super T> comparator);
private static final class SortedStreamSpliterator<T> implements Spliterator<T>, Consumer<T> {
private boolean firstStream;
private final Spliterator<T> firstSpliterator;
private final Spliterator<T> secondSpliterator;
private T firstValue;
private T secondValue;
private final Comparator<? super T> comparator;
private SortedStreamSpliterator( Spliterator<T> firstSpliterator, Spliterator<T> secondSpliterator, Comparator<? super T> comparator);
public boolean tryAdvance( Consumer<? super T> action);
public Spliterator<T> trySplit();
public long estimateSize();
public int characteristics();
public Comparator<? super T> getComparator();
public void accept( T t);
}
private static Runnable composedClose( BaseStream<?,?> a, BaseStream<?,?> b);
}
public interface RecordReader {
ORawBuffer readRecord( OStorage storage, ORecordId rid, String fetchPlan, boolean ignoreCache, final int recordVersion) throws ORecordNotFoundException ;
}
public class OIOException extends OSystemException {
private static final long serialVersionUID=-3003977236203691448L;
public OIOException( OIOException exception);
public OIOException( String string);
}
public OTraversePath append(OIdentifiable record){
return new OTraversePath(new RecordPathItem(record,lastPathItem));
}
@Override public String toString(){
return "OQuarto{" + "one=" + one + ", two="+ two+ ", three="+ three+ ", four="+ four+ '}';
}
/**
* Execute a script in a specified query language. The result set has to be closed after usage <br> <br> Sample usage: <p><code> String script = "INSERT INTO Person SET name = 'foo', surname = ?;"+ "INSERT INTO Person SET name = 'bar', surname = ?;"+ "INSERT INTO Person SET name = 'baz', surname = ?;"; <p> OResultSet rs = db.execute("sql", script, "Surname1", "Surname2", "Surname3"); ... rs.close(); </code>
* @param language
* @param script
* @param args
* @return
*/
default OResultSet execute(String language,String script,Object... args) throws OCommandExecutionException, OCommandScriptException {
throw new UnsupportedOperationException();
}
@Override public void read(OChannelDataInput network,OStorageRemoteSession session) throws IOException {
}
/**
* Creates the databases as follows: - server1: db A, db B - server2: db B, db C
* @throws IOException
*/
@Override protected void prepare(final boolean iCopyDatabaseToNodes,final boolean iCreateDatabase) throws IOException {
serverInstance.remove(2);
ServerRun master=serverInstance.get(0);
OrientDB orientDB=new OrientDB("embedded:" + master.getServerHome() + "/databases/",OrientDBConfig.defaultConfig());
if (iCreateDatabase) {
orientDB.execute("create database ? plocal users(admin identified by 'admin' role admin)",dbA);
orientDB.execute("create database ? plocal users(admin identified by 'admin' role admin)",dbB);
final ODatabaseDocument graph1=orientDB.open(dbA,"admin","admin");
final ODatabaseDocument graph2=orientDB.open(dbB,"admin","admin");
try {
onAfterDatabaseCreation(graph1);
onAfterDatabaseCreation(graph2);
}
finally {
if (!graph1.isClosed()) {
graph1.activateOnCurrentThread();
graph1.close();
}
if (!graph2.isClosed()) {
graph2.activateOnCurrentThread();
graph2.close();
}
orientDB.close();
}
}
if (iCopyDatabaseToNodes) master.copyDatabase(dbB,serverInstance.get(1).getDatabasePath(dbB));
master=serverInstance.get(1);
OrientDB orientDB1=new OrientDB("embedded:" + master.getServerHome() + "/databases/",OrientDBConfig.defaultConfig());
if (iCreateDatabase) {
orientDB1.execute("create database ? plocal users(admin identified by 'admin' role admin)",dbC);
final ODatabaseDocument graph1=orientDB1.open(dbC,"admin","admin");
try {
onAfterDatabaseCreation(graph1);
}
finally {
if (!graph1.isClosed()) {
graph1.close();
}
orientDB1.close();
}
}
}
/**
* Evaluates a SQL expression against current document by passing a context. The expression can refer to the variables contained in the context. Example: <code> OCommandContext context = new OBasicCommandContext().setVariable("vat", 20); long amountPlusVat = doc.eval("amount * (100+$vat) / 100", context); </code>
* @param iExpression SQL expression to evaluate.
* @return The result of expression
* @throws OQueryParsingException in case the expression is not valid
*/
public Object eval(final String iExpression,final OCommandContext iContext){
return new OSQLPredicate(iExpression).evaluate(this,null,iContext);
}
| {"types": [{"Bindings": "Streams"}, {"Reader": "RecordReader"}, {"IOException": "OIOException"}], "methods": [{"append": "append"}, {"toString": "toString"}, {"execute": "execute"}, {"read": "read"}, {"ready": "prepare"}], "similar_methods": [{"eval": "eval"}]} | [{"Bindings": {"retrieved_name": "Streams", "raw_body": "public class Streams {\n public static <T>Stream<T> mergeSortedSpliterators( Stream<T> streamOne, Stream<T> streamTwo, Comparator<? super T> comparator);\nprivate static final class SortedStreamSpliterator<T> implements Spliterator<T>, Consumer<T> {\n private boolean firstStream;\n private final Spliterator<T> firstSpliterator;\n private final Spliterator<T> secondSpliterator;\n private T firstValue;\n private T secondValue;\n private final Comparator<? super T> comparator;\n private SortedStreamSpliterator( Spliterator<T> firstSpliterator, Spliterator<T> secondSpliterator, Comparator<? super T> comparator);\n @Override public boolean tryAdvance( Consumer<? super T> action);\n @Override public Spliterator<T> trySplit();\n @Override public long estimateSize();\n @Override public int characteristics();\n @Override public Comparator<? super T> getComparator();\n @Override public void accept( T t);\n }\n private static Runnable composedClose( BaseStream<?,?> a, BaseStream<?,?> b);\n}\n", "raw_body_no_cmt": "public class Streams {\n public static <T>Stream<T> mergeSortedSpliterators( Stream<T> streamOne, Stream<T> streamTwo, Comparator<? super T> comparator);\nprivate static final class SortedStreamSpliterator<T> implements Spliterator<T>, Consumer<T> {\n private boolean firstStream;\n private final Spliterator<T> firstSpliterator;\n private final Spliterator<T> secondSpliterator;\n private T firstValue;\n private T secondValue;\n private final Comparator<? super T> comparator;\n private SortedStreamSpliterator( Spliterator<T> firstSpliterator, Spliterator<T> secondSpliterator, Comparator<? super T> comparator);\n public boolean tryAdvance( Consumer<? super T> action);\n public Spliterator<T> trySplit();\n public long estimateSize();\n public int characteristics();\n public Comparator<? super T> getComparator();\n public void accept( T t);\n }\n private static Runnable composedClose( BaseStream<?,?> a, BaseStream<?,?> b);\n}\n"}}, {"Reader": {"retrieved_name": "RecordReader", "raw_body": "/** \n * @Internal \n */\npublic interface RecordReader {\n ORawBuffer readRecord( OStorage storage, ORecordId rid, String fetchPlan, boolean ignoreCache, final int recordVersion) throws ORecordNotFoundException ;\n}\n", "raw_body_no_cmt": "public interface RecordReader {\n ORawBuffer readRecord( OStorage storage, ORecordId rid, String fetchPlan, boolean ignoreCache, final int recordVersion) throws ORecordNotFoundException ;\n}\n"}}, {"IOException": {"retrieved_name": "OIOException", "raw_body": "public class OIOException extends OSystemException {\n private static final long serialVersionUID=-3003977236203691448L;\n public OIOException( OIOException exception);\n public OIOException( String string);\n}\n", "raw_body_no_cmt": "public class OIOException extends OSystemException {\n private static final long serialVersionUID=-3003977236203691448L;\n public OIOException( OIOException exception);\n public OIOException( String string);\n}\n"}}] | [{"append": {"retrieved_name": "append", "raw_body": "public OTraversePath append(OIdentifiable record){\n return new OTraversePath(new RecordPathItem(record,lastPathItem));\n}\n"}}, {"toString": {"retrieved_name": "toString", "raw_body": "@Override public String toString(){\n return \"OQuarto{\" + \"one=\" + one + \", two=\"+ two+ \", three=\"+ three+ \", four=\"+ four+ '}';\n}\n"}}, {"execute": {"retrieved_name": "execute", "raw_body": "/** \n * Execute a script in a specified query language. The result set has to be closed after usage <br> <br> Sample usage: <p><code> String script = \"INSERT INTO Person SET name = 'foo', surname = ?;\"+ \"INSERT INTO Person SET name = 'bar', surname = ?;\"+ \"INSERT INTO Person SET name = 'baz', surname = ?;\"; <p> OResultSet rs = db.execute(\"sql\", script, \"Surname1\", \"Surname2\", \"Surname3\"); ... rs.close(); </code>\n * @param language\n * @param script\n * @param args\n * @return\n */\ndefault OResultSet execute(String language,String script,Object... args) throws OCommandExecutionException, OCommandScriptException {\n throw new UnsupportedOperationException();\n}\n"}}, {"read": {"retrieved_name": "read", "raw_body": "@Override public void read(OChannelDataInput network,OStorageRemoteSession session) throws IOException {\n}\n"}}, {"ready": {"retrieved_name": "prepare", "raw_body": "/** \n * Creates the databases as follows: - server1: db A, db B - server2: db B, db C\n * @throws IOException\n */\n@Override protected void prepare(final boolean iCopyDatabaseToNodes,final boolean iCreateDatabase) throws IOException {\n serverInstance.remove(2);\n ServerRun master=serverInstance.get(0);\n OrientDB orientDB=new OrientDB(\"embedded:\" + master.getServerHome() + \"/databases/\",OrientDBConfig.defaultConfig());\n if (iCreateDatabase) {\n orientDB.execute(\"create database ? plocal users(admin identified by 'admin' role admin)\",dbA);\n orientDB.execute(\"create database ? plocal users(admin identified by 'admin' role admin)\",dbB);\n final ODatabaseDocument graph1=orientDB.open(dbA,\"admin\",\"admin\");\n final ODatabaseDocument graph2=orientDB.open(dbB,\"admin\",\"admin\");\n try {\n onAfterDatabaseCreation(graph1);\n onAfterDatabaseCreation(graph2);\n }\n finally {\n if (!graph1.isClosed()) {\n graph1.activateOnCurrentThread();\n graph1.close();\n }\n if (!graph2.isClosed()) {\n graph2.activateOnCurrentThread();\n graph2.close();\n }\n orientDB.close();\n }\n }\n if (iCopyDatabaseToNodes) master.copyDatabase(dbB,serverInstance.get(1).getDatabasePath(dbB));\n master=serverInstance.get(1);\n OrientDB orientDB1=new OrientDB(\"embedded:\" + master.getServerHome() + \"/databases/\",OrientDBConfig.defaultConfig());\n if (iCreateDatabase) {\n orientDB1.execute(\"create database ? plocal users(admin identified by 'admin' role admin)\",dbC);\n final ODatabaseDocument graph1=orientDB1.open(dbC,\"admin\",\"admin\");\n try {\n onAfterDatabaseCreation(graph1);\n }\n finally {\n if (!graph1.isClosed()) {\n graph1.close();\n }\n orientDB1.close();\n }\n }\n}\n"}}] | [{"eval": {"retrieved_name": "eval", "raw_body": "/** \n * Evaluates a SQL expression against current document by passing a context. The expression can refer to the variables contained in the context. Example: <code> OCommandContext context = new OBasicCommandContext().setVariable(\"vat\", 20); long amountPlusVat = doc.eval(\"amount * (100+$vat) / 100\", context); </code>\n * @param iExpression SQL expression to evaluate.\n * @return The result of expression\n * @throws OQueryParsingException in case the expression is not valid\n */\npublic Object eval(final String iExpression,final OCommandContext iContext){\n return new OSQLPredicate(iExpression).evaluate(this,null,iContext);\n}\n"}}] |
|
orientechnologies_orientdb | orientdb/core/src/main/java/com/orientechnologies/orient/core/sql/parser/SimpleNode.java | SimpleNode | jjtAddChild | class SimpleNode implements Node {
public static final String PARAMETER_PLACEHOLDER = "?";
protected Node parent;
protected Node[] children;
protected int id;
protected Object value;
protected OrientSql parser;
protected Token firstToken;
protected Token lastToken;
public SimpleNode() {
id = -1;
}
public SimpleNode(int i) {
id = i;
}
public SimpleNode(OrientSql p, int i) {
this(i);
parser = p;
}
public void jjtOpen() {}
public void jjtClose() {}
public void jjtSetParent(Node n) {
parent = n;
}
public Node jjtGetParent() {
return parent;
}
public void jjtAddChild(Node n, int i) {<FILL_FUNCTION_BODY>}
public Node jjtGetChild(int i) {
return children[i];
}
public int jjtGetNumChildren() {
return (children == null) ? 0 : children.length;
}
public void jjtSetValue(Object value) {
this.value = value;
}
public Object jjtGetValue() {
return value;
}
public Token jjtGetFirstToken() {
return firstToken;
}
public void jjtSetFirstToken(Token token) {
this.firstToken = token;
}
public Token jjtGetLastToken() {
return lastToken;
}
public void jjtSetLastToken(Token token) {
this.lastToken = token;
}
/*
* You can override these two methods in subclasses of SimpleNode to customize the way the node appears when the tree is dumped.
* If your output uses more than one line you should override toString(String), otherwise overriding toString() is probably all
* you need to do.
*/
public String toString() {
StringBuilder result = new StringBuilder();
toString(null, result);
return result.toString();
}
public String toString(String prefix) {
return prefix + toString();
}
/*
* Override this method if you want to customize how the node dumps out its children.
*/
public void dump(String prefix) {
if (children != null) {
for (int i = 0; i < children.length; ++i) {
SimpleNode n = (SimpleNode) children[i];
if (n != null) {
n.dump(prefix + " ");
}
}
}
}
public static ODatabaseDocumentInternal getDatabase() {
return ODatabaseRecordThreadLocal.instance().get();
}
public abstract void toString(Map<Object, Object> params, StringBuilder builder);
public abstract void toGenericStatement(StringBuilder builder);
public String toGenericStatement() {
StringBuilder builder = new StringBuilder();
toGenericStatement(builder);
return builder.toString();
}
public Object getValue() {
return value;
}
public SimpleNode copy() {
throw new UnsupportedOperationException();
}
} |
if (children == null) {
children = new Node[i + 1];
} else if (i >= children.length) {
Node c[] = new Node[i + 1];
System.arraycopy(children, 0, c, 0, children.length);
children = c;
}
children[i] = n;
|
if (children == null) {
children = new Node[1];
} else {
Node[] a = new Node[children.length + 1];
System.arraycopy(children, 0, a, 0, children.length);
children = a;
}
children[children.length - 1] = n;
if (n != null) {
((SimpleNode) n).jjtSetParent(this);
}
| [
"Node[]",
"SimpleNode"
] | [
"jjtSetParent",
"arraycopy"
] | [
"SimpleNode",
"Node[]",
"Node"
] | [
"arraycopy"
] | {
"methods": [
"jjtSetParent",
"arraycopy"
],
"similar_methods": [
"jjtAddChild"
],
"types": [
"Node[]",
"SimpleNode"
]
} | public final class Node<T> extends AtomicReference<Node<T>> {
static final int BUFFER_SIZE=1024;
private volatile Node<T> prev;
public volatile int deqidx=0;
public final AtomicReferenceArray<T> items=new AtomicReferenceArray<>(BUFFER_SIZE);
public final AtomicInteger enqidx=new AtomicInteger(1);
Node();
Node( T record, Node<T> prev);
public void clearPrev();
public boolean casNext( Node<T> oldNode, Node<T> newNode);
public Node<T> getNext();
public Node<T> getPrev();
@Override public String toString();
}
public class SimpleMultiNodeConnectIT {
private TestSetup setup;
private SetupConfig config;
private String server0, server1, server2;
@Before public void before() throws Exception;
@Test public void testLiveQueryDifferentNode();
@After public void after();
}
/**
* This pair of methods are used to inform the node of its parent.
*/
public void jjtSetParent(Node n);
public static <T>T[] array(final Object iValue,final Class<? extends T> iClass,final OCallable<Object,Object> iCallback){
if (iValue == null) return null;
final T[] result;
if (isMultiValue(iValue)) {
result=(T[])Array.newInstance(iClass,getSize(iValue));
int i=0;
for (Iterator<T> it=(Iterator<T>)getMultiValueIterator(iValue,false); it.hasNext(); ++i) result[i]=(T)convert(it.next(),iCallback);
}
else if (isIterable(iValue)) {
final List<T> temp=new ArrayList<T>();
for (Iterator<T> it=(Iterator<T>)getMultiValueIterator(iValue,false); it.hasNext(); ) temp.add((T)convert(it.next(),iCallback));
if (iClass.equals(Object.class)) result=(T[])temp.toArray();
else result=temp.toArray((T[])Array.newInstance(iClass,getSize(iValue)));
}
else {
result=(T[])Array.newInstance(iClass,1);
result[0]=(T)(T)convert(iValue,iCallback);
}
return result;
}
/**
* This method tells the node to add its argument to the node's list of children.
*/
public void jjtAddChild(Node n,int i);
| public final class Node<T> extends AtomicReference<Node<T>> {
static final int BUFFER_SIZE=1024;
private volatile Node<T> prev;
public volatile int deqidx=0;
public final AtomicReferenceArray<T> items=new AtomicReferenceArray<>(BUFFER_SIZE);
public final AtomicInteger enqidx=new AtomicInteger(1);
Node();
Node( T record, Node<T> prev);
public void clearPrev();
public boolean casNext( Node<T> oldNode, Node<T> newNode);
public Node<T> getNext();
public Node<T> getPrev();
public String toString();
}
public class SimpleMultiNodeConnectIT {
private TestSetup setup;
private SetupConfig config;
private String server0, server1, server2;
public void before() throws Exception;
public void testLiveQueryDifferentNode();
public void after();
}
/**
* This pair of methods are used to inform the node of its parent.
*/
public void jjtSetParent(Node n);
public static <T>T[] array(final Object iValue,final Class<? extends T> iClass,final OCallable<Object,Object> iCallback){
if (iValue == null) return null;
final T[] result;
if (isMultiValue(iValue)) {
result=(T[])Array.newInstance(iClass,getSize(iValue));
int i=0;
for (Iterator<T> it=(Iterator<T>)getMultiValueIterator(iValue,false); it.hasNext(); ++i) result[i]=(T)convert(it.next(),iCallback);
}
else if (isIterable(iValue)) {
final List<T> temp=new ArrayList<T>();
for (Iterator<T> it=(Iterator<T>)getMultiValueIterator(iValue,false); it.hasNext(); ) temp.add((T)convert(it.next(),iCallback));
if (iClass.equals(Object.class)) result=(T[])temp.toArray();
else result=temp.toArray((T[])Array.newInstance(iClass,getSize(iValue)));
}
else {
result=(T[])Array.newInstance(iClass,1);
result[0]=(T)(T)convert(iValue,iCallback);
}
return result;
}
/**
* This method tells the node to add its argument to the node's list of children.
*/
public void jjtAddChild(Node n,int i);
| {"types": [{"Node[]": "Node"}, {"SimpleNode": "SimpleMultiNodeConnectIT"}], "methods": [{"jjtSetParent": "jjtSetParent"}, {"arraycopy": "array"}], "similar_methods": [{"jjtAddChild": "jjtAddChild"}]} | [{"Node[]": {"retrieved_name": "Node", "raw_body": "public final class Node<T> extends AtomicReference<Node<T>> {\n static final int BUFFER_SIZE=1024;\n private volatile Node<T> prev;\n public volatile int deqidx=0;\n public final AtomicReferenceArray<T> items=new AtomicReferenceArray<>(BUFFER_SIZE);\n public final AtomicInteger enqidx=new AtomicInteger(1);\n Node();\n Node( T record, Node<T> prev);\n public void clearPrev();\n public boolean casNext( Node<T> oldNode, Node<T> newNode);\n public Node<T> getNext();\n public Node<T> getPrev();\n @Override public String toString();\n}\n", "raw_body_no_cmt": "public final class Node<T> extends AtomicReference<Node<T>> {\n static final int BUFFER_SIZE=1024;\n private volatile Node<T> prev;\n public volatile int deqidx=0;\n public final AtomicReferenceArray<T> items=new AtomicReferenceArray<>(BUFFER_SIZE);\n public final AtomicInteger enqidx=new AtomicInteger(1);\n Node();\n Node( T record, Node<T> prev);\n public void clearPrev();\n public boolean casNext( Node<T> oldNode, Node<T> newNode);\n public Node<T> getNext();\n public Node<T> getPrev();\n public String toString();\n}\n"}}, {"SimpleNode": {"retrieved_name": "SimpleMultiNodeConnectIT", "raw_body": "public class SimpleMultiNodeConnectIT {\n private TestSetup setup;\n private SetupConfig config;\n private String server0, server1, server2;\n @Before public void before() throws Exception;\n @Test public void testLiveQueryDifferentNode();\n @After public void after();\n}\n", "raw_body_no_cmt": "public class SimpleMultiNodeConnectIT {\n private TestSetup setup;\n private SetupConfig config;\n private String server0, server1, server2;\n public void before() throws Exception;\n public void testLiveQueryDifferentNode();\n public void after();\n}\n"}}] | [{"jjtSetParent": {"retrieved_name": "jjtSetParent", "raw_body": "/** \n * This pair of methods are used to inform the node of its parent. \n */\npublic void jjtSetParent(Node n);\n"}}, {"arraycopy": {"retrieved_name": "array", "raw_body": "public static <T>T[] array(final Object iValue,final Class<? extends T> iClass,final OCallable<Object,Object> iCallback){\n if (iValue == null) return null;\n final T[] result;\n if (isMultiValue(iValue)) {\n result=(T[])Array.newInstance(iClass,getSize(iValue));\n int i=0;\n for (Iterator<T> it=(Iterator<T>)getMultiValueIterator(iValue,false); it.hasNext(); ++i) result[i]=(T)convert(it.next(),iCallback);\n }\n else if (isIterable(iValue)) {\n final List<T> temp=new ArrayList<T>();\n for (Iterator<T> it=(Iterator<T>)getMultiValueIterator(iValue,false); it.hasNext(); ) temp.add((T)convert(it.next(),iCallback));\n if (iClass.equals(Object.class)) result=(T[])temp.toArray();\n else result=temp.toArray((T[])Array.newInstance(iClass,getSize(iValue)));\n }\n else {\n result=(T[])Array.newInstance(iClass,1);\n result[0]=(T)(T)convert(iValue,iCallback);\n }\n return result;\n}\n"}}] | [{"jjtAddChild": {"retrieved_name": "jjtAddChild", "raw_body": "/** \n * This method tells the node to add its argument to the node's list of children. \n */\npublic void jjtAddChild(Node n,int i);\n"}}] |
|
docker-java_docker-java | docker-java/docker-java-core/src/main/java/com/github/dockerjava/core/exec/LogSwarmObjectExec.java | LogSwarmObjectExec | execute0 | class LogSwarmObjectExec extends AbstrAsyncDockerCmdExec<LogSwarmObjectCmd, Frame> implements
LogSwarmObjectCmd.Exec {
private String endpoint = "";
private static final Logger LOGGER = LoggerFactory.getLogger(LogSwarmObjectExec.class);
public LogSwarmObjectExec(com.github.dockerjava.core.WebTarget baseResource, DockerClientConfig dockerClientConfig, String endpoint) {
super(baseResource, dockerClientConfig);
this.endpoint = endpoint;
}
@Override
protected Void execute0(LogSwarmObjectCmd command, ResultCallback<Frame> resultCallback) {<FILL_FUNCTION_BODY>}
} |
WebTarget webTarget = getBaseResource().path("/" + endpoint + "/{id}/logs").resolveTemplate("id", command.getId());
if (command.getTail() != null) {
webTarget = webTarget.queryParam("tail", command.getTail());
} else {
webTarget = webTarget.queryParam("tail", "all");
}
if (command.getSince() != null) {
webTarget = webTarget.queryParam("since", command.getSince());
}
webTarget = booleanQueryParam(webTarget, "timestamps", command.getTimestamps());
webTarget = booleanQueryParam(webTarget, "stdout", command.getStdout());
webTarget = booleanQueryParam(webTarget, "stderr", command.getStderr());
webTarget = booleanQueryParam(webTarget, "follow", command.getFollow());
LOGGER.trace("GET: {}", webTarget);
webTarget.request().get(resultCallback);
return null;
|
WebTarget webResource = getBaseResource().path(endpoint).path(command.getObjectId());
if (command.isFollow()) {
webResource = webResource.queryParam("follow", "1");
}
if (command.isStdout()) {
webResource = webResource.queryParam("stdout", "1");
}
if (command.isStderr()) {
webResource = webResource.queryParam("stderr", "1");
}
if (command.isTimestamps()) {
webResource = webResource.queryParam("timestamps", "1");
}
if (command.isDetails()) {
webResource = webResource.queryParam("details", "1");
}
if (command.isSince() != null) {
webResource = webResource.queryParam("since", command.getSince());
}
if (command.isUntil() != null) {
webResource = webResource.queryParam("until", command.getUntil());
}
if (command.isTail() != null) {
webResource = webResource.queryParam("tail", command.getTail());
}
if (command.isSinceTime() != null) {
webResource = webResource.queryParam("since", command.getSinceTime().toString());
}
if (command.isUntilTime() != null) {
webResource = webResource.queryParam("until", command.getUntilTime().toString());
}
if (command.isTimestamps() != null) {
webResource = webResource.queryParam("timestamps", command.getTimestamps | [
"LogSwarmObjectCmd",
"WebTarget",
"ResultCallback<Frame>"
] | [
"isTimestamps",
"path",
"queryParam",
"isStderr",
"isUntil",
"toString",
"isSince",
"isSinceTime",
"getSince",
"isFollow",
"isStdout",
"isTail",
"isUntilTime",
"getUntil",
"isDetails",
"getTail",
"getObjectId",
"getSinceTime",
"getUntilTime"
] | [
"WebTarget",
"Logger",
"ResultCallback<Frame>",
"LogSwarmObjectCmd"
] | [
"getSince",
"getTimestamps",
"getId",
"trace",
"queryParam",
"getFollow",
"get",
"resolveTemplate",
"getStderr",
"request",
"path",
"getTail",
"getStdout"
] | {
"methods": [
"isTimestamps",
"path",
"queryParam",
"isStderr",
"isUntil",
"toString",
"isSince",
"isSinceTime",
"getSince",
"isFollow",
"isStdout",
"isTail",
"isUntilTime",
"getUntil",
"isDetails",
"getTail",
"getObjectId",
"getSinceTime",
"getUntilTime"
],
"similar_methods": [
"execute0"
],
"types": [
"LogSwarmObjectCmd",
"WebTarget",
"ResultCallback<Frame>"
]
} | /**
* Get docker service/task stdout/stderr logs
*/
public interface LogSwarmObjectCmd extends AsyncDockerCmd<LogSwarmObjectCmd,Frame> {
/**
* @param id ID or name of the service
* @return self
*/
LogSwarmObjectCmd withId( @Nonnull String id);
/**
* @param follow Return the logs as a raw stream.
* @return self
*/
LogSwarmObjectCmd withFollow( Boolean follow);
/**
* @param timestamps Add timestamps to every log line
* @return self
*/
LogSwarmObjectCmd withTimestamps( Boolean timestamps);
/**
* @param stdout Return logs from stdout
* @return self
*/
LogSwarmObjectCmd withStdout( Boolean stdout);
/**
* @param stderr Return logs from stderr
* @return self
*/
LogSwarmObjectCmd withStderr( Boolean stderr);
/**
* @param tail only return this number of log lines from the end of the logs.
* @return self
*/
LogSwarmObjectCmd withTail( Integer tail);
/**
* @param since Only return logs since this time, as a UNIX timestamp
* @return self
*/
LogSwarmObjectCmd withSince( Integer since);
/**
* @param details Show service context and extra details provided to logs.
* @return
*/
LogSwarmObjectCmd withDetails( Boolean details);
@CheckForNull String getId();
@CheckForNull Integer getTail();
@CheckForNull Boolean getFollow();
@CheckForNull Boolean getTimestamps();
@CheckForNull Boolean getStdout();
@CheckForNull Boolean getStderr();
@CheckForNull Integer getSince();
@CheckForNull Boolean getDetails();
/**
* @throws com.github.dockerjava.api.exception.NotFoundException no such service
*/
@Override <T extends ResultCallback<Frame>>T exec( T resultCallback);
interface Exec extends DockerCmdAsyncExec<LogSwarmObjectCmd,Frame> {
}
}
public interface WebTarget {
WebTarget path( String... components);
InvocationBuilder request();
WebTarget resolveTemplate( String name, Object value);
WebTarget queryParam( String name, Object value);
WebTarget queryParamsSet( String name, Set<?> values);
WebTarget queryParamsJsonMap( String name, Map<String,String> values);
}
/**
* Result callback
*/
public interface ResultCallback<A_RES_T> extends Closeable {
class Adapter<A_RES_T> extends ResultCallbackTemplate<Adapter<A_RES_T>,A_RES_T> {
@Override public void onNext( A_RES_T object);
}
/**
* Called when the async processing starts respectively when the response arrives from the server. The passed {@link Closeable} can beused to close/interrupt the processing.
*/
void onStart( Closeable closeable);
/**
* Called when an async result event occurs
*/
void onNext( A_RES_T object);
/**
* Called when an exception occurs while processing
*/
void onError( Throwable throwable);
/**
* Called when processing was finished either by reaching the end or by aborting it
*/
void onComplete();
}
/**
* @param timestamps Add timestamps to every log line
* @return self
*/
LogSwarmObjectCmd withTimestamps(Boolean timestamps);
/**
* @return The value of the {@code path} attribute
*/
@Override public String path(){
return path;
}
public NettyWebTarget queryParam(String name,Object value){
ImmutableMap.Builder<String,String> builder=ImmutableMap.<String,String>builder().putAll(queryParams);
if (value != null) {
builder.put(name,value.toString());
}
return new NettyWebTarget(objectMapper,channelProvider,host,path,builder.build(),queryParamsSet);
}
public Boolean isOpenStderr(){
return openStderr;
}
private boolean isValidUntil(String until){
if (UNTIL_DATETIME_PATTERN.matcher(until).matches()) {
return true;
}
else if (!Strings.isNullOrEmpty(until) && UNTIL_GO_PATTERN.matcher(until).matches()) {
return true;
}
else if (UNTIL_TIMESTAMP_PATTERN.matcher(until).matches()) {
return true;
}
return false;
}
@Override String toString();
/**
* @param since Only return logs since this time, as a UNIX timestamp
* @return self
*/
LogSwarmObjectCmd withSince(Integer since);
/**
* @param since Only return logs since this time, as a UNIX timestamp
* @return self
*/
LogSwarmObjectCmd withSince(Integer since);
@CheckForNull Integer getSince();
public Boolean getFollow(){
return follow;
}
public Boolean isOpenStdout(){
return openStdout;
}
@Override public LogSwarmObjectImpl withTail(Integer tail){
this.tail=tail;
return this;
}
private boolean isValidUntil(String until){
if (UNTIL_DATETIME_PATTERN.matcher(until).matches()) {
return true;
}
else if (!Strings.isNullOrEmpty(until) && UNTIL_GO_PATTERN.matcher(until).matches()) {
return true;
}
else if (UNTIL_TIMESTAMP_PATTERN.matcher(until).matches()) {
return true;
}
return false;
}
@CheckForNull String getUntil();
@Override public LogSwarmObjectCmd withDetails(Boolean details){
this.details=details;
return this;
}
@CheckForNull Integer getTail();
public String getId(){
return id;
}
@CheckForNull Integer getSince();
@CheckForNull String getUntil();
@Override protected Void execute0(BuildImageCmd command,ResultCallback<BuildResponseItem> resultCallback){
WebTarget webTarget=getBaseResource().path("/build");
String dockerFilePath=command.getPathToDockerfile();
if (dockerFilePath != null && command.getRemote() == null && !"Dockerfile".equals(dockerFilePath)) {
webTarget=webTarget.queryParam("dockerfile",dockerFilePath);
}
if (command.getTags() != null && !command.getTags().isEmpty()) {
webTarget=webTarget.queryParamsSet("t",command.getTags());
}
else if (isNotBlank(command.getTag())) {
webTarget=webTarget.queryParam("t",command.getTag());
}
if (command.getCacheFrom() != null && !command.getCacheFrom().isEmpty()) {
webTarget=webTarget.queryParam("cachefrom",jsonEncode(command.getCacheFrom()));
}
if (command.getRemote() != null) {
webTarget=webTarget.queryParam("remote",command.getRemote().toString());
}
webTarget=booleanQueryParam(webTarget,"q",command.isQuiet());
webTarget=booleanQueryParam(webTarget,"nocache",command.hasNoCacheEnabled());
webTarget=booleanQueryParam(webTarget,"pull",command.hasPullEnabled());
webTarget=booleanQueryParam(webTarget,"rm",command.hasRemoveEnabled());
webTarget=booleanQueryParam(webTarget,"forcerm",command.isForcerm());
if (command.hasRemoveEnabled() == null || !command.hasRemoveEnabled()) {
webTarget=webTarget.queryParam("rm","false");
}
if (command.getMemory() != null) {
webTarget=webTarget.queryParam("memory",command.getMemory());
}
if (command.getMemswap() != null) {
webTarget=webTarget.queryParam("memswap",command.getMemswap());
}
if (command.getCpushares() != null) {
webTarget=webTarget.queryParam("cpushares",command.getCpushares());
}
if (command.getCpusetcpus() != null) {
webTarget=webTarget.queryParam("cpusetcpus",command.getCpusetcpus());
}
if (command.getBuildArgs() != null) {
webTarget=webTarget.queryParamsJsonMap("buildargs",command.getBuildArgs());
}
if (command.getShmsize() != null) {
webTarget=webTarget.queryParam("shmsize",command.getShmsize());
}
if (command.getLabels() != null) {
webTarget=webTarget.queryParamsJsonMap("labels",command.getLabels());
}
if (command.getNetworkMode() != null) {
webTarget=webTarget.queryParam("networkmode",command.getNetworkMode());
}
if (command.getPlatform() != null) {
webTarget=webTarget.queryParam("platform",command.getPlatform());
}
if (command.getTarget() != null) {
webTarget=webTarget.queryParam("target",command.getTarget());
}
if (command.getExtraHosts() != null) {
webTarget=webTarget.queryParamsSet("extrahosts",command.getExtraHosts());
}
LOGGER.trace("POST: {}",webTarget);
InvocationBuilder builder=resourceWithOptionalAuthConfig(command,webTarget.request()).accept(MediaType.APPLICATION_JSON).header("Content-Type","application/tar").header("encoding","gzip");
builder.post(new TypeReference<BuildResponseItem>(){
}
,resultCallback,command.getTarInputStream());
return null;
}
| public interface LogSwarmObjectCmd extends AsyncDockerCmd<LogSwarmObjectCmd,Frame> {
LogSwarmObjectCmd withId( String id);
LogSwarmObjectCmd withFollow( Boolean follow);
LogSwarmObjectCmd withTimestamps( Boolean timestamps);
LogSwarmObjectCmd withStdout( Boolean stdout);
LogSwarmObjectCmd withStderr( Boolean stderr);
LogSwarmObjectCmd withTail( Integer tail);
LogSwarmObjectCmd withSince( Integer since);
LogSwarmObjectCmd withDetails( Boolean details);
String getId();
Integer getTail();
Boolean getFollow();
Boolean getTimestamps();
Boolean getStdout();
Boolean getStderr();
Integer getSince();
Boolean getDetails();
<T extends ResultCallback<Frame>>T exec( T resultCallback);
interface Exec extends DockerCmdAsyncExec<LogSwarmObjectCmd,Frame> {
}
}
public interface WebTarget {
WebTarget path( String... components);
InvocationBuilder request();
WebTarget resolveTemplate( String name, Object value);
WebTarget queryParam( String name, Object value);
WebTarget queryParamsSet( String name, Set<?> values);
WebTarget queryParamsJsonMap( String name, Map<String,String> values);
}
public interface ResultCallback<A_RES_T> extends Closeable {
class Adapter<A_RES_T> extends ResultCallbackTemplate<Adapter<A_RES_T>,A_RES_T> {
public void onNext( A_RES_T object);
}
void onStart( Closeable closeable);
void onNext( A_RES_T object);
void onError( Throwable throwable);
void onComplete();
}
/**
* @param timestamps Add timestamps to every log line
* @return self
*/
LogSwarmObjectCmd withTimestamps(Boolean timestamps);
/**
* @return The value of the {@code path} attribute
*/
@Override public String path(){
return path;
}
public NettyWebTarget queryParam(String name,Object value){
ImmutableMap.Builder<String,String> builder=ImmutableMap.<String,String>builder().putAll(queryParams);
if (value != null) {
builder.put(name,value.toString());
}
return new NettyWebTarget(objectMapper,channelProvider,host,path,builder.build(),queryParamsSet);
}
public Boolean isOpenStderr(){
return openStderr;
}
private boolean isValidUntil(String until){
if (UNTIL_DATETIME_PATTERN.matcher(until).matches()) {
return true;
}
else if (!Strings.isNullOrEmpty(until) && UNTIL_GO_PATTERN.matcher(until).matches()) {
return true;
}
else if (UNTIL_TIMESTAMP_PATTERN.matcher(until).matches()) {
return true;
}
return false;
}
@Override String toString();
/**
* @param since Only return logs since this time, as a UNIX timestamp
* @return self
*/
LogSwarmObjectCmd withSince(Integer since);
/**
* @param since Only return logs since this time, as a UNIX timestamp
* @return self
*/
LogSwarmObjectCmd withSince(Integer since);
@CheckForNull Integer getSince();
public Boolean getFollow(){
return follow;
}
public Boolean isOpenStdout(){
return openStdout;
}
@Override public LogSwarmObjectImpl withTail(Integer tail){
this.tail=tail;
return this;
}
private boolean isValidUntil(String until){
if (UNTIL_DATETIME_PATTERN.matcher(until).matches()) {
return true;
}
else if (!Strings.isNullOrEmpty(until) && UNTIL_GO_PATTERN.matcher(until).matches()) {
return true;
}
else if (UNTIL_TIMESTAMP_PATTERN.matcher(until).matches()) {
return true;
}
return false;
}
@CheckForNull String getUntil();
@Override public LogSwarmObjectCmd withDetails(Boolean details){
this.details=details;
return this;
}
@CheckForNull Integer getTail();
public String getId(){
return id;
}
@CheckForNull Integer getSince();
@CheckForNull String getUntil();
@Override protected Void execute0(BuildImageCmd command,ResultCallback<BuildResponseItem> resultCallback){
WebTarget webTarget=getBaseResource().path("/build");
String dockerFilePath=command.getPathToDockerfile();
if (dockerFilePath != null && command.getRemote() == null && !"Dockerfile".equals(dockerFilePath)) {
webTarget=webTarget.queryParam("dockerfile",dockerFilePath);
}
if (command.getTags() != null && !command.getTags().isEmpty()) {
webTarget=webTarget.queryParamsSet("t",command.getTags());
}
else if (isNotBlank(command.getTag())) {
webTarget=webTarget.queryParam("t",command.getTag());
}
if (command.getCacheFrom() != null && !command.getCacheFrom().isEmpty()) {
webTarget=webTarget.queryParam("cachefrom",jsonEncode(command.getCacheFrom()));
}
if (command.getRemote() != null) {
webTarget=webTarget.queryParam("remote",command.getRemote().toString());
}
webTarget=booleanQueryParam(webTarget,"q",command.isQuiet());
webTarget=booleanQueryParam(webTarget,"nocache",command.hasNoCacheEnabled());
webTarget=booleanQueryParam(webTarget,"pull",command.hasPullEnabled());
webTarget=booleanQueryParam(webTarget,"rm",command.hasRemoveEnabled());
webTarget=booleanQueryParam(webTarget,"forcerm",command.isForcerm());
if (command.hasRemoveEnabled() == null || !command.hasRemoveEnabled()) {
webTarget=webTarget.queryParam("rm","false");
}
if (command.getMemory() != null) {
webTarget=webTarget.queryParam("memory",command.getMemory());
}
if (command.getMemswap() != null) {
webTarget=webTarget.queryParam("memswap",command.getMemswap());
}
if (command.getCpushares() != null) {
webTarget=webTarget.queryParam("cpushares",command.getCpushares());
}
if (command.getCpusetcpus() != null) {
webTarget=webTarget.queryParam("cpusetcpus",command.getCpusetcpus());
}
if (command.getBuildArgs() != null) {
webTarget=webTarget.queryParamsJsonMap("buildargs",command.getBuildArgs());
}
if (command.getShmsize() != null) {
webTarget=webTarget.queryParam("shmsize",command.getShmsize());
}
if (command.getLabels() != null) {
webTarget=webTarget.queryParamsJsonMap("labels",command.getLabels());
}
if (command.getNetworkMode() != null) {
webTarget=webTarget.queryParam("networkmode",command.getNetworkMode());
}
if (command.getPlatform() != null) {
webTarget=webTarget.queryParam("platform",command.getPlatform());
}
if (command.getTarget() != null) {
webTarget=webTarget.queryParam("target",command.getTarget());
}
if (command.getExtraHosts() != null) {
webTarget=webTarget.queryParamsSet("extrahosts",command.getExtraHosts());
}
LOGGER.trace("POST: {}",webTarget);
InvocationBuilder builder=resourceWithOptionalAuthConfig(command,webTarget.request()).accept(MediaType.APPLICATION_JSON).header("Content-Type","application/tar").header("encoding","gzip");
builder.post(new TypeReference<BuildResponseItem>(){
}
,resultCallback,command.getTarInputStream());
return null;
}
| {"types": [{"LogSwarmObjectCmd": "LogSwarmObjectCmd"}, {"WebTarget": "WebTarget"}, {"ResultCallback<Frame>": "ResultCallback"}], "methods": [{"isTimestamps": "withTimestamps"}, {"path": "path"}, {"queryParam": "queryParam"}, {"isStderr": "isOpenStderr"}, {"isUntil": "isValidUntil"}, {"toString": "toString"}, {"isSince": "withSince"}, {"isSinceTime": "withSince"}, {"getSince": "getSince"}, {"isFollow": "getFollow"}, {"isStdout": "isOpenStdout"}, {"isTail": "withTail"}, {"isUntilTime": "isValidUntil"}, {"getUntil": "getUntil"}, {"isDetails": "withDetails"}, {"getTail": "getTail"}, {"getObjectId": "getId"}, {"getSinceTime": "getSince"}, {"getUntilTime": "getUntil"}], "similar_methods": [{"execute0": "execute0"}]} | [{"LogSwarmObjectCmd": {"retrieved_name": "LogSwarmObjectCmd", "raw_body": "/** \n * Get docker service/task stdout/stderr logs\n */\npublic interface LogSwarmObjectCmd extends AsyncDockerCmd<LogSwarmObjectCmd,Frame> {\n /** \n * @param id ID or name of the service\n * @return self\n */\n LogSwarmObjectCmd withId( @Nonnull String id);\n /** \n * @param follow Return the logs as a raw stream.\n * @return self\n */\n LogSwarmObjectCmd withFollow( Boolean follow);\n /** \n * @param timestamps Add timestamps to every log line\n * @return self\n */\n LogSwarmObjectCmd withTimestamps( Boolean timestamps);\n /** \n * @param stdout Return logs from stdout\n * @return self\n */\n LogSwarmObjectCmd withStdout( Boolean stdout);\n /** \n * @param stderr Return logs from stderr\n * @return self\n */\n LogSwarmObjectCmd withStderr( Boolean stderr);\n /** \n * @param tail only return this number of log lines from the end of the logs.\n * @return self\n */\n LogSwarmObjectCmd withTail( Integer tail);\n /** \n * @param since Only return logs since this time, as a UNIX timestamp\n * @return self\n */\n LogSwarmObjectCmd withSince( Integer since);\n /** \n * @param details Show service context and extra details provided to logs.\n * @return\n */\n LogSwarmObjectCmd withDetails( Boolean details);\n @CheckForNull String getId();\n @CheckForNull Integer getTail();\n @CheckForNull Boolean getFollow();\n @CheckForNull Boolean getTimestamps();\n @CheckForNull Boolean getStdout();\n @CheckForNull Boolean getStderr();\n @CheckForNull Integer getSince();\n @CheckForNull Boolean getDetails();\n /** \n * @throws com.github.dockerjava.api.exception.NotFoundException no such service\n */\n @Override <T extends ResultCallback<Frame>>T exec( T resultCallback);\ninterface Exec extends DockerCmdAsyncExec<LogSwarmObjectCmd,Frame> {\n }\n}\n", "raw_body_no_cmt": "public interface LogSwarmObjectCmd extends AsyncDockerCmd<LogSwarmObjectCmd,Frame> {\n LogSwarmObjectCmd withId( String id);\n LogSwarmObjectCmd withFollow( Boolean follow);\n LogSwarmObjectCmd withTimestamps( Boolean timestamps);\n LogSwarmObjectCmd withStdout( Boolean stdout);\n LogSwarmObjectCmd withStderr( Boolean stderr);\n LogSwarmObjectCmd withTail( Integer tail);\n LogSwarmObjectCmd withSince( Integer since);\n LogSwarmObjectCmd withDetails( Boolean details);\n String getId();\n Integer getTail();\n Boolean getFollow();\n Boolean getTimestamps();\n Boolean getStdout();\n Boolean getStderr();\n Integer getSince();\n Boolean getDetails();\n <T extends ResultCallback<Frame>>T exec( T resultCallback);\ninterface Exec extends DockerCmdAsyncExec<LogSwarmObjectCmd,Frame> {\n }\n}\n"}}, {"WebTarget": {"retrieved_name": "WebTarget", "raw_body": "public interface WebTarget {\n WebTarget path( String... components);\n InvocationBuilder request();\n WebTarget resolveTemplate( String name, Object value);\n WebTarget queryParam( String name, Object value);\n WebTarget queryParamsSet( String name, Set<?> values);\n WebTarget queryParamsJsonMap( String name, Map<String,String> values);\n}\n", "raw_body_no_cmt": "public interface WebTarget {\n WebTarget path( String... components);\n InvocationBuilder request();\n WebTarget resolveTemplate( String name, Object value);\n WebTarget queryParam( String name, Object value);\n WebTarget queryParamsSet( String name, Set<?> values);\n WebTarget queryParamsJsonMap( String name, Map<String,String> values);\n}\n"}}, {"ResultCallback<Frame>": {"retrieved_name": "ResultCallback", "raw_body": "/** \n * Result callback\n */\npublic interface ResultCallback<A_RES_T> extends Closeable {\nclass Adapter<A_RES_T> extends ResultCallbackTemplate<Adapter<A_RES_T>,A_RES_T> {\n @Override public void onNext( A_RES_T object);\n }\n /** \n * Called when the async processing starts respectively when the response arrives from the server. The passed {@link Closeable} can beused to close/interrupt the processing.\n */\n void onStart( Closeable closeable);\n /** \n * Called when an async result event occurs \n */\n void onNext( A_RES_T object);\n /** \n * Called when an exception occurs while processing \n */\n void onError( Throwable throwable);\n /** \n * Called when processing was finished either by reaching the end or by aborting it \n */\n void onComplete();\n}\n", "raw_body_no_cmt": "public interface ResultCallback<A_RES_T> extends Closeable {\nclass Adapter<A_RES_T> extends ResultCallbackTemplate<Adapter<A_RES_T>,A_RES_T> {\n public void onNext( A_RES_T object);\n }\n void onStart( Closeable closeable);\n void onNext( A_RES_T object);\n void onError( Throwable throwable);\n void onComplete();\n}\n"}}] | [{"isTimestamps": {"retrieved_name": "withTimestamps", "raw_body": "/** \n * @param timestamps Add timestamps to every log line\n * @return self\n */\nLogSwarmObjectCmd withTimestamps(Boolean timestamps);\n"}}, {"path": {"retrieved_name": "path", "raw_body": "/** \n * @return The value of the {@code path} attribute\n */\n@Override public String path(){\n return path;\n}\n"}}, {"queryParam": {"retrieved_name": "queryParam", "raw_body": "public NettyWebTarget queryParam(String name,Object value){\n ImmutableMap.Builder<String,String> builder=ImmutableMap.<String,String>builder().putAll(queryParams);\n if (value != null) {\n builder.put(name,value.toString());\n }\n return new NettyWebTarget(objectMapper,channelProvider,host,path,builder.build(),queryParamsSet);\n}\n"}}, {"isStderr": {"retrieved_name": "isOpenStderr", "raw_body": "public Boolean isOpenStderr(){\n return openStderr;\n}\n"}}, {"isUntil": {"retrieved_name": "isValidUntil", "raw_body": "private boolean isValidUntil(String until){\n if (UNTIL_DATETIME_PATTERN.matcher(until).matches()) {\n return true;\n }\n else if (!Strings.isNullOrEmpty(until) && UNTIL_GO_PATTERN.matcher(until).matches()) {\n return true;\n }\n else if (UNTIL_TIMESTAMP_PATTERN.matcher(until).matches()) {\n return true;\n }\n return false;\n}\n"}}, {"toString": {"retrieved_name": "toString", "raw_body": "@Override String toString();\n"}}, {"isSince": {"retrieved_name": "withSince", "raw_body": "/** \n * @param since Only return logs since this time, as a UNIX timestamp\n * @return self\n */\nLogSwarmObjectCmd withSince(Integer since);\n"}}, {"isSinceTime": {"retrieved_name": "withSince", "raw_body": "/** \n * @param since Only return logs since this time, as a UNIX timestamp\n * @return self\n */\nLogSwarmObjectCmd withSince(Integer since);\n"}}, {"getSince": {"retrieved_name": "getSince", "raw_body": "@CheckForNull Integer getSince();\n"}}, {"isFollow": {"retrieved_name": "getFollow", "raw_body": "public Boolean getFollow(){\n return follow;\n}\n"}}, {"isStdout": {"retrieved_name": "isOpenStdout", "raw_body": "public Boolean isOpenStdout(){\n return openStdout;\n}\n"}}, {"isTail": {"retrieved_name": "withTail", "raw_body": "@Override public LogSwarmObjectImpl withTail(Integer tail){\n this.tail=tail;\n return this;\n}\n"}}, {"isUntilTime": {"retrieved_name": "isValidUntil", "raw_body": "private boolean isValidUntil(String until){\n if (UNTIL_DATETIME_PATTERN.matcher(until).matches()) {\n return true;\n }\n else if (!Strings.isNullOrEmpty(until) && UNTIL_GO_PATTERN.matcher(until).matches()) {\n return true;\n }\n else if (UNTIL_TIMESTAMP_PATTERN.matcher(until).matches()) {\n return true;\n }\n return false;\n}\n"}}, {"getUntil": {"retrieved_name": "getUntil", "raw_body": "@CheckForNull String getUntil();\n"}}, {"isDetails": {"retrieved_name": "withDetails", "raw_body": "@Override public LogSwarmObjectCmd withDetails(Boolean details){\n this.details=details;\n return this;\n}\n"}}, {"getTail": {"retrieved_name": "getTail", "raw_body": "@CheckForNull Integer getTail();\n"}}, {"getObjectId": {"retrieved_name": "getId", "raw_body": "public String getId(){\n return id;\n}\n"}}, {"getSinceTime": {"retrieved_name": "getSince", "raw_body": "@CheckForNull Integer getSince();\n"}}, {"getUntilTime": {"retrieved_name": "getUntil", "raw_body": "@CheckForNull String getUntil();\n"}}] | [{"execute0": {"retrieved_name": "execute0", "raw_body": "@Override protected Void execute0(BuildImageCmd command,ResultCallback<BuildResponseItem> resultCallback){\n WebTarget webTarget=getBaseResource().path(\"/build\");\n String dockerFilePath=command.getPathToDockerfile();\n if (dockerFilePath != null && command.getRemote() == null && !\"Dockerfile\".equals(dockerFilePath)) {\n webTarget=webTarget.queryParam(\"dockerfile\",dockerFilePath);\n }\n if (command.getTags() != null && !command.getTags().isEmpty()) {\n webTarget=webTarget.queryParamsSet(\"t\",command.getTags());\n }\n else if (isNotBlank(command.getTag())) {\n webTarget=webTarget.queryParam(\"t\",command.getTag());\n }\n if (command.getCacheFrom() != null && !command.getCacheFrom().isEmpty()) {\n webTarget=webTarget.queryParam(\"cachefrom\",jsonEncode(command.getCacheFrom()));\n }\n if (command.getRemote() != null) {\n webTarget=webTarget.queryParam(\"remote\",command.getRemote().toString());\n }\n webTarget=booleanQueryParam(webTarget,\"q\",command.isQuiet());\n webTarget=booleanQueryParam(webTarget,\"nocache\",command.hasNoCacheEnabled());\n webTarget=booleanQueryParam(webTarget,\"pull\",command.hasPullEnabled());\n webTarget=booleanQueryParam(webTarget,\"rm\",command.hasRemoveEnabled());\n webTarget=booleanQueryParam(webTarget,\"forcerm\",command.isForcerm());\n if (command.hasRemoveEnabled() == null || !command.hasRemoveEnabled()) {\n webTarget=webTarget.queryParam(\"rm\",\"false\");\n }\n if (command.getMemory() != null) {\n webTarget=webTarget.queryParam(\"memory\",command.getMemory());\n }\n if (command.getMemswap() != null) {\n webTarget=webTarget.queryParam(\"memswap\",command.getMemswap());\n }\n if (command.getCpushares() != null) {\n webTarget=webTarget.queryParam(\"cpushares\",command.getCpushares());\n }\n if (command.getCpusetcpus() != null) {\n webTarget=webTarget.queryParam(\"cpusetcpus\",command.getCpusetcpus());\n }\n if (command.getBuildArgs() != null) {\n webTarget=webTarget.queryParamsJsonMap(\"buildargs\",command.getBuildArgs());\n }\n if (command.getShmsize() != null) {\n webTarget=webTarget.queryParam(\"shmsize\",command.getShmsize());\n }\n if (command.getLabels() != null) {\n webTarget=webTarget.queryParamsJsonMap(\"labels\",command.getLabels());\n }\n if (command.getNetworkMode() != null) {\n webTarget=webTarget.queryParam(\"networkmode\",command.getNetworkMode());\n }\n if (command.getPlatform() != null) {\n webTarget=webTarget.queryParam(\"platform\",command.getPlatform());\n }\n if (command.getTarget() != null) {\n webTarget=webTarget.queryParam(\"target\",command.getTarget());\n }\n if (command.getExtraHosts() != null) {\n webTarget=webTarget.queryParamsSet(\"extrahosts\",command.getExtraHosts());\n }\n LOGGER.trace(\"POST: {}\",webTarget);\n InvocationBuilder builder=resourceWithOptionalAuthConfig(command,webTarget.request()).accept(MediaType.APPLICATION_JSON).header(\"Content-Type\",\"application/tar\").header(\"encoding\",\"gzip\");\n builder.post(new TypeReference<BuildResponseItem>(){\n }\n,resultCallback,command.getTarInputStream());\n return null;\n}\n"}}] |
|
jeecgboot_jeecg-boot | jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/system/util/JeecgDataAutorUtils.java | JeecgDataAutorUtils | installDataSearchConditon | class JeecgDataAutorUtils {
public static final String MENU_DATA_AUTHOR_RULES = "MENU_DATA_AUTHOR_RULES";
public static final String MENU_DATA_AUTHOR_RULE_SQL = "MENU_DATA_AUTHOR_RULE_SQL";
public static final String SYS_USER_INFO = "SYS_USER_INFO";
/**
* 往链接请求里面,传入数据查询条件
*
* @param request
* @param dataRules
*/
public static synchronized void installDataSearchConditon(HttpServletRequest request, List<SysPermissionDataRuleModel> dataRules) {
@SuppressWarnings("unchecked")
// 1.先从request获取MENU_DATA_AUTHOR_RULES,如果存则获取到LIST
List<SysPermissionDataRuleModel> list = (List<SysPermissionDataRuleModel>)loadDataSearchConditon();
if (list==null) {
// 2.如果不存在,则new一个list
list = new ArrayList<SysPermissionDataRuleModel>();
}
for (SysPermissionDataRuleModel tsDataRule : dataRules) {
list.add(tsDataRule);
}
// 3.往list里面增量存指
request.setAttribute(MENU_DATA_AUTHOR_RULES, list);
}
/**
* 获取请求对应的数据权限规则
*
* @return
*/
@SuppressWarnings("unchecked")
public static synchronized List<SysPermissionDataRuleModel> loadDataSearchConditon() {
return (List<SysPermissionDataRuleModel>) SpringContextUtils.getHttpServletRequest().getAttribute(MENU_DATA_AUTHOR_RULES);
}
/**
* 获取请求对应的数据权限SQL
*
* @return
*/
public static synchronized String loadDataSearchConditonSqlString() {
return (String) SpringContextUtils.getHttpServletRequest().getAttribute(MENU_DATA_AUTHOR_RULE_SQL);
}
/**
* 往链接请求里面,传入数据查询条件
*
* @param request
* @param sql
*/
public static synchronized void installDataSearchConditon(HttpServletRequest request, String sql) {<FILL_FUNCTION_BODY>}
/**
* 将用户信息存到request
* @param request
* @param userinfo
*/
public static synchronized void installUserInfo(HttpServletRequest request, SysUserCacheInfo userinfo) {
request.setAttribute(SYS_USER_INFO, userinfo);
}
/**
* 将用户信息存到request
* @param userinfo
*/
public static synchronized void installUserInfo(SysUserCacheInfo userinfo) {
SpringContextUtils.getHttpServletRequest().setAttribute(SYS_USER_INFO, userinfo);
}
/**
* 从request获取用户信息
* @return
*/
public static synchronized SysUserCacheInfo loadUserInfo() {
return (SysUserCacheInfo) SpringContextUtils.getHttpServletRequest().getAttribute(SYS_USER_INFO);
}
} |
String ruleSql = (String) loadDataSearchConditonSqlString();
if (!StringUtils.hasText(ruleSql)) {
request.setAttribute(MENU_DATA_AUTHOR_RULE_SQL,sql);
}
|
request.setAttribute(MENU_DATA_AUTHOR_RULE_SQL, sql);
| [
"HttpServletRequest"
] | [
"setAttribute"
] | [
"HttpServletRequest"
] | [
"setAttribute",
"hasText"
] | {
"methods": [
"setAttribute"
],
"similar_methods": [
"installDataSearchConditon"
],
"types": [
"HttpServletRequest"
]
} | /**
* 保存过滤器里面的流
* @author jeecg
* @date 20210621
*/
public class BodyReaderHttpServletRequestWrapper extends HttpServletRequestWrapper {
private final byte[] body;
public BodyReaderHttpServletRequestWrapper( HttpServletRequest request);
/**
* 获取请求Body
* @param request
* @return
*/
public String getBodyString( final ServletRequest request);
/**
* Description: 复制输入流</br>
* @param inputStream
* @return </br>
*/
public InputStream cloneInputStream( ServletInputStream inputStream);
@Override public BufferedReader getReader();
@Override public ServletInputStream getInputStream();
}
public void setParameter(String parameter){
this.parameter=parameter;
}
| public class BodyReaderHttpServletRequestWrapper extends HttpServletRequestWrapper {
private final byte[] body;
public BodyReaderHttpServletRequestWrapper( HttpServletRequest request);
public String getBodyString( final ServletRequest request);
public InputStream cloneInputStream( ServletInputStream inputStream);
public BufferedReader getReader();
public ServletInputStream getInputStream();
}
public void setParameter(String parameter){
this.parameter=parameter;
}
| {"types": [{"HttpServletRequest": "BodyReaderHttpServletRequestWrapper"}], "methods": [{"setAttribute": "setParameter"}], "similar_methods": [{"installDataSearchConditon": ""}]} | [{"HttpServletRequest": {"retrieved_name": "BodyReaderHttpServletRequestWrapper", "raw_body": "/** \n * \u4fdd\u5b58\u8fc7\u6ee4\u5668\u91cc\u9762\u7684\u6d41\n * @author jeecg\n * @date 20210621\n */\npublic class BodyReaderHttpServletRequestWrapper extends HttpServletRequestWrapper {\n private final byte[] body;\n public BodyReaderHttpServletRequestWrapper( HttpServletRequest request);\n /** \n * \u83b7\u53d6\u8bf7\u6c42Body\n * @param request\n * @return\n */\n public String getBodyString( final ServletRequest request);\n /** \n * Description: \u590d\u5236\u8f93\u5165\u6d41</br>\n * @param inputStream\n * @return </br>\n */\n public InputStream cloneInputStream( ServletInputStream inputStream);\n @Override public BufferedReader getReader();\n @Override public ServletInputStream getInputStream();\n}\n", "raw_body_no_cmt": "public class BodyReaderHttpServletRequestWrapper extends HttpServletRequestWrapper {\n private final byte[] body;\n public BodyReaderHttpServletRequestWrapper( HttpServletRequest request);\n public String getBodyString( final ServletRequest request);\n public InputStream cloneInputStream( ServletInputStream inputStream);\n public BufferedReader getReader();\n public ServletInputStream getInputStream();\n}\n"}}] | [{"setAttribute": {"retrieved_name": "setParameter", "raw_body": "public void setParameter(String parameter){\n this.parameter=parameter;\n}\n"}}] | [] |
|
ainilili_ratel | ratel/landlords-server/src/main/java/org/nico/ratel/landlords/server/event/ServerEventListener_CODE_CLIENT_INFO_SET.java | ServerEventListener_CODE_CLIENT_INFO_SET | call | class ServerEventListener_CODE_CLIENT_INFO_SET implements ServerEventListener {
private static final String DEFAULT_VERSION = "v1.2.8";
@Override
public void call(ClientSide client, String info) {<FILL_FUNCTION_BODY>}
} |
Map<?,?> infos = JsonUtils.fromJson(info, Map.class);
// Get client version
client.setVersion(DEFAULT_VERSION);
if (infos.containsKey("version")){
client.setVersion(String.valueOf(infos.get("version")));
}
|
client.setVersion(info);
| [
"ClientSide"
] | [
"setVersion"
] | [
"ClientSide",
"Map<?,?>"
] | [
"containsKey",
"get",
"setVersion",
"fromJson",
"valueOf"
] | {
"methods": [
"setVersion"
],
"similar_methods": [
"call"
],
"types": [
"ClientSide"
]
} | public class ClientSide {
private int id;
private int roomId;
private int score;
private int scoreInc;
private int round;
private String nickname;
private List<Poker> pokers;
private ClientStatus status;
private ClientRole role;
private ClientType type;
private ClientSide next;
private ClientSide pre;
private transient Channel channel;
private String version;
public ClientSide();
public ClientSide( int id, ClientStatus status, Channel channel);
public void init();
public final void resetRound();
public final int getRound();
public final void addRound();
public final ClientRole getRole();
public final void setRole( ClientRole role);
public final String getNickname();
public final void setNickname( String nickname);
public final Channel getChannel();
public final void setChannel( Channel channel);
public final int getRoomId();
public final void setRoomId( int roomId);
public final List<Poker> getPokers();
public final void setPokers( List<Poker> pokers);
public final int getScore();
public final void setScore( int score);
public final void addScore( int score);
public final void setScoreInc( int scoreInc);
public final int getScoreInc();
public final ClientStatus getStatus();
public final void setStatus( ClientStatus status);
public final ClientType getType();
public final void setType( ClientType type);
public final int getId();
public final void setId( int id);
public final ClientSide getNext();
public final void setNext( ClientSide next);
public final ClientSide getPre();
public final void setPre( ClientSide pre);
public String getVersion();
public void setVersion( String version);
@Override public int hashCode();
@Override public boolean equals( Object obj);
}
public void setVersion(String version){
this.version=version;
}
@Override public void call(Channel channel,String data){
SimplePrinter.printNotice("You have been kicked from the room for being idle.\n");
get(ClientEventCode.CODE_SHOW_OPTIONS).call(channel,data);
}
| public class ClientSide {
private int id;
private int roomId;
private int score;
private int scoreInc;
private int round;
private String nickname;
private List<Poker> pokers;
private ClientStatus status;
private ClientRole role;
private ClientType type;
private ClientSide next;
private ClientSide pre;
private transient Channel channel;
private String version;
public ClientSide();
public ClientSide( int id, ClientStatus status, Channel channel);
public void init();
public final void resetRound();
public final int getRound();
public final void addRound();
public final ClientRole getRole();
public final void setRole( ClientRole role);
public final String getNickname();
public final void setNickname( String nickname);
public final Channel getChannel();
public final void setChannel( Channel channel);
public final int getRoomId();
public final void setRoomId( int roomId);
public final List<Poker> getPokers();
public final void setPokers( List<Poker> pokers);
public final int getScore();
public final void setScore( int score);
public final void addScore( int score);
public final void setScoreInc( int scoreInc);
public final int getScoreInc();
public final ClientStatus getStatus();
public final void setStatus( ClientStatus status);
public final ClientType getType();
public final void setType( ClientType type);
public final int getId();
public final void setId( int id);
public final ClientSide getNext();
public final void setNext( ClientSide next);
public final ClientSide getPre();
public final void setPre( ClientSide pre);
public String getVersion();
public void setVersion( String version);
public int hashCode();
public boolean equals( Object obj);
}
public void setVersion(String version){
this.version=version;
}
@Override public void call(Channel channel,String data){
SimplePrinter.printNotice("You have been kicked from the room for being idle.\n");
get(ClientEventCode.CODE_SHOW_OPTIONS).call(channel,data);
}
| {"types": [{"ClientSide": "ClientSide"}], "methods": [{"setVersion": "setVersion"}], "similar_methods": [{"call": "call"}]} | [{"ClientSide": {"retrieved_name": "ClientSide", "raw_body": "public class ClientSide {\n private int id;\n private int roomId;\n private int score;\n private int scoreInc;\n private int round;\n private String nickname;\n private List<Poker> pokers;\n private ClientStatus status;\n private ClientRole role;\n private ClientType type;\n private ClientSide next;\n private ClientSide pre;\n private transient Channel channel;\n private String version;\n public ClientSide();\n public ClientSide( int id, ClientStatus status, Channel channel);\n public void init();\n public final void resetRound();\n public final int getRound();\n public final void addRound();\n public final ClientRole getRole();\n public final void setRole( ClientRole role);\n public final String getNickname();\n public final void setNickname( String nickname);\n public final Channel getChannel();\n public final void setChannel( Channel channel);\n public final int getRoomId();\n public final void setRoomId( int roomId);\n public final List<Poker> getPokers();\n public final void setPokers( List<Poker> pokers);\n public final int getScore();\n public final void setScore( int score);\n public final void addScore( int score);\n public final void setScoreInc( int scoreInc);\n public final int getScoreInc();\n public final ClientStatus getStatus();\n public final void setStatus( ClientStatus status);\n public final ClientType getType();\n public final void setType( ClientType type);\n public final int getId();\n public final void setId( int id);\n public final ClientSide getNext();\n public final void setNext( ClientSide next);\n public final ClientSide getPre();\n public final void setPre( ClientSide pre);\n public String getVersion();\n public void setVersion( String version);\n @Override public int hashCode();\n @Override public boolean equals( Object obj);\n}\n", "raw_body_no_cmt": "public class ClientSide {\n private int id;\n private int roomId;\n private int score;\n private int scoreInc;\n private int round;\n private String nickname;\n private List<Poker> pokers;\n private ClientStatus status;\n private ClientRole role;\n private ClientType type;\n private ClientSide next;\n private ClientSide pre;\n private transient Channel channel;\n private String version;\n public ClientSide();\n public ClientSide( int id, ClientStatus status, Channel channel);\n public void init();\n public final void resetRound();\n public final int getRound();\n public final void addRound();\n public final ClientRole getRole();\n public final void setRole( ClientRole role);\n public final String getNickname();\n public final void setNickname( String nickname);\n public final Channel getChannel();\n public final void setChannel( Channel channel);\n public final int getRoomId();\n public final void setRoomId( int roomId);\n public final List<Poker> getPokers();\n public final void setPokers( List<Poker> pokers);\n public final int getScore();\n public final void setScore( int score);\n public final void addScore( int score);\n public final void setScoreInc( int scoreInc);\n public final int getScoreInc();\n public final ClientStatus getStatus();\n public final void setStatus( ClientStatus status);\n public final ClientType getType();\n public final void setType( ClientType type);\n public final int getId();\n public final void setId( int id);\n public final ClientSide getNext();\n public final void setNext( ClientSide next);\n public final ClientSide getPre();\n public final void setPre( ClientSide pre);\n public String getVersion();\n public void setVersion( String version);\n public int hashCode();\n public boolean equals( Object obj);\n}\n"}}] | [{"setVersion": {"retrieved_name": "setVersion", "raw_body": "public void setVersion(String version){\n this.version=version;\n}\n"}}] | [{"call": {"retrieved_name": "call", "raw_body": "@Override public void call(Channel channel,String data){\n SimplePrinter.printNotice(\"You have been kicked from the room for being idle.\\n\");\n get(ClientEventCode.CODE_SHOW_OPTIONS).call(channel,data);\n}\n"}}] |
|
pmd_pmd | pmd/pmd-core/src/main/java/net/sourceforge/pmd/internal/Slf4jSimpleConfiguration.java | Slf4jSimpleConfiguration | getDefaultLogLevel | class Slf4jSimpleConfiguration {
private static final String SIMPLE_LOGGER_FACTORY_CLASS = "org.slf4j.impl.SimpleLoggerFactory";
private static final String SIMPLE_LOGGER_CLASS = "org.slf4j.impl.SimpleLogger";
private static final String SIMPLE_LOGGER_CONFIGURATION = "org.slf4j.impl.SimpleLoggerConfiguration";
private static final String PMD_ROOT_LOGGER = "net.sourceforge.pmd";
private Slf4jSimpleConfiguration() { }
public static void reconfigureDefaultLogLevel(Level level) {
if (!isSimpleLogger()) {
// do nothing, not even set system properties, if not Simple Logger is in use
return;
}
if (level != null) {
System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", level.toString());
}
// Call SimpleLogger.init() by reflection.
// Alternatively: move the CLI related classes into an own module, add
// slf4j-simple as a compile dependency and create a PmdSlf4jSimpleFriend class in
// the package org.slf4j.simple to gain access to this package-private init method.
//
// SimpleLogger.init() will reevaluate the configuration from the system properties or
// simplelogger.properties file.
ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory();
ClassLoader classLoader = loggerFactory.getClass().getClassLoader();
try {
Class<?> simpleLoggerClass = classLoader.loadClass(SIMPLE_LOGGER_CLASS);
Method initMethod = simpleLoggerClass.getDeclaredMethod("init");
initMethod.setAccessible(true);
initMethod.invoke(null);
int newDefaultLogLevel = getDefaultLogLevelInt(simpleLoggerClass);
Field currentLogLevelField = simpleLoggerClass.getDeclaredField("currentLogLevel");
currentLogLevelField.setAccessible(true);
Method levelStringMethod = simpleLoggerClass.getDeclaredMethod("recursivelyComputeLevelString");
levelStringMethod.setAccessible(true);
Method stringToLevelMethod = classLoader.loadClass(SIMPLE_LOGGER_CONFIGURATION)
.getDeclaredMethod("stringToLevel", String.class);
stringToLevelMethod.setAccessible(true);
// Change the logging level of loggers that were already created.
// For this we fetch the map of name to logger that is stored in the logger factory,
// then set the log level field of each logger via reflection.
// The new log level is determined similar to the constructor of SimpleLogger, that
// means, configuration params are being considered.
Class<?> loggerFactoryClass = classLoader.loadClass(SIMPLE_LOGGER_FACTORY_CLASS);
Field loggerMapField = loggerFactoryClass.getDeclaredField("loggerMap");
loggerMapField.setAccessible(true);
// we checked previously, that loggerFactory instanceof SimpleLoggerFactory
// see #isSimpleLogger()
@SuppressWarnings("unchecked")
Map<String, Logger> loggerMap = (Map<String, Logger>) loggerMapField.get(loggerFactory);
for (Logger logger : loggerMap.values()) {
if (logger.getName().startsWith(PMD_ROOT_LOGGER)
&& simpleLoggerClass.isAssignableFrom(logger.getClass())) {
String newConfiguredLevel = (String) levelStringMethod.invoke(logger);
int newLogLevel = newDefaultLogLevel;
if (newConfiguredLevel != null) {
newLogLevel = (int) stringToLevelMethod.invoke(null, newConfiguredLevel);
}
currentLogLevelField.set(logger, newLogLevel);
}
}
} catch (ReflectiveOperationException | ClassCastException ex) {
System.err.println("Error while initializing logging: " + ex);
}
}
private static int getDefaultLogLevelInt(Class<?> simpleLoggerClass) throws ReflectiveOperationException {
Field configParamsField = simpleLoggerClass.getDeclaredField("CONFIG_PARAMS");
configParamsField.setAccessible(true);
Object configParams = configParamsField.get(null);
Field defaultLogLevelField = configParams.getClass().getDeclaredField("defaultLogLevel");
defaultLogLevelField.setAccessible(true);
return (int) defaultLogLevelField.get(configParams);
}
public static Level getDefaultLogLevel() {<FILL_FUNCTION_BODY>}
public static void disableLogging(Class<?> clazz) {
if (!isSimpleLogger()) {
// do nothing, not even set system properties, if not Simple Logger is in use
return;
}
System.setProperty("org.slf4j.simpleLogger.log." + clazz.getName(), "off");
}
public static boolean isSimpleLogger() {
try {
ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory();
Class<?> loggerFactoryClass = loggerFactory.getClass().getClassLoader().loadClass(SIMPLE_LOGGER_FACTORY_CLASS);
return loggerFactoryClass.isAssignableFrom(loggerFactory.getClass());
} catch (ClassNotFoundException e) {
// not slf4j simple logger
return false;
}
}
public static void installJulBridge() {
if (!SLF4JBridgeHandler.isInstalled()) {
SLF4JBridgeHandler.removeHandlersForRootLogger(); // removes any existing ConsoleLogger
SLF4JBridgeHandler.install();
}
}
} |
Logger rootLogger = LoggerFactory.getLogger(PMD_ROOT_LOGGER);
// check the lowest log level first
if (rootLogger.isTraceEnabled()) {
return Level.TRACE;
}
if (rootLogger.isDebugEnabled()) {
return Level.DEBUG;
}
if (rootLogger.isInfoEnabled()) {
return Level.INFO;
}
if (rootLogger.isWarnEnabled()) {
return Level.WARN;
}
if (rootLogger.isErrorEnabled()) {
return Level.ERROR;
}
return Level.INFO;
|
if (!isSimpleLogger()) {
// do nothing, not even set system properties, if not Simple Logger is in use
return null;
}
String defaultLogLevel = System.getProperty("org.slf4j.simpleLogger.defaultLogLevel");
if (defaultLogLevel == null) {
return null;
}
return Level.valueOf(defaultLogLevel);
| [] | [
"getProperty",
"valueOf"
] | [
"Logger"
] | [
"isWarnEnabled",
"isErrorEnabled",
"isTraceEnabled",
"isDebugEnabled",
"isInfoEnabled",
"getLogger"
] | {
"methods": [
"getProperty",
"valueOf"
],
"similar_methods": [
"getDefaultLogLevel"
],
"types": []
} | /**
* Get the typed value for the given property. Multi valued properties return immutable lists.
* @param < T > The underlying type of the property descriptor.
* @param propertyDescriptor The property descriptor.
* @return The property value.
*/
<T>T getProperty(PropertyDescriptor<T> propertyDescriptor);
/**
* Get the priority which corresponds to the given number as returned by {@link RulePriority#getPriority()}. If the number is an invalid value, then {@link RulePriority#LOW} will be returned.
* @param priority The numeric priority value.
* @return The priority.
*/
public static RulePriority valueOf(int priority){
try {
return RulePriority.values()[priority - 1];
}
catch ( ArrayIndexOutOfBoundsException e) {
return LOW;
}
}
/**
* Determines the log level, that is used. It is either the called method name itself or - in case java util logging is used, then it is the first argument of the method call (if it exists).
* @param methodCall the method call
* @return the log level or <code>null</code> if it could not be determined
*/
private @Nullable String getLogLevelName(ASTMethodCall methodCall){
String methodName=methodCall.getMethodName();
if (!JAVA_UTIL_LOG_METHOD.equals(methodName)) {
if (isUnguardedAccessOk(methodCall,0)) {
return null;
}
return methodName;
}
if (isUnguardedAccessOk(methodCall,1)) {
return null;
}
return getJutilLogLevelInFirstArg(methodCall);
}
| /**
* Get the typed value for the given property. Multi valued properties return immutable lists.
* @param < T > The underlying type of the property descriptor.
* @param propertyDescriptor The property descriptor.
* @return The property value.
*/
<T>T getProperty(PropertyDescriptor<T> propertyDescriptor);
/**
* Get the priority which corresponds to the given number as returned by {@link RulePriority#getPriority()}. If the number is an invalid value, then {@link RulePriority#LOW} will be returned.
* @param priority The numeric priority value.
* @return The priority.
*/
public static RulePriority valueOf(int priority){
try {
return RulePriority.values()[priority - 1];
}
catch ( ArrayIndexOutOfBoundsException e) {
return LOW;
}
}
/**
* Determines the log level, that is used. It is either the called method name itself or - in case java util logging is used, then it is the first argument of the method call (if it exists).
* @param methodCall the method call
* @return the log level or <code>null</code> if it could not be determined
*/
private @Nullable String getLogLevelName(ASTMethodCall methodCall){
String methodName=methodCall.getMethodName();
if (!JAVA_UTIL_LOG_METHOD.equals(methodName)) {
if (isUnguardedAccessOk(methodCall,0)) {
return null;
}
return methodName;
}
if (isUnguardedAccessOk(methodCall,1)) {
return null;
}
return getJutilLogLevelInFirstArg(methodCall);
}
| {"methods": [{"getProperty": "getProperty"}, {"valueOf": "valueOf"}], "similar_methods": [{"getDefaultLogLevel": "getLogLevelName"}]} | [] | [{"getProperty": {"retrieved_name": "getProperty", "raw_body": "/** \n * Get the typed value for the given property. Multi valued properties return immutable lists.\n * @param < T > The underlying type of the property descriptor.\n * @param propertyDescriptor The property descriptor.\n * @return The property value.\n */\n<T>T getProperty(PropertyDescriptor<T> propertyDescriptor);\n"}}, {"valueOf": {"retrieved_name": "valueOf", "raw_body": "/** \n * Get the priority which corresponds to the given number as returned by {@link RulePriority#getPriority()}. If the number is an invalid value, then {@link RulePriority#LOW} will be returned.\n * @param priority The numeric priority value.\n * @return The priority.\n */\npublic static RulePriority valueOf(int priority){\n try {\n return RulePriority.values()[priority - 1];\n }\n catch ( ArrayIndexOutOfBoundsException e) {\n return LOW;\n }\n}\n"}}] | [{"getDefaultLogLevel": {"retrieved_name": "getLogLevelName", "raw_body": "/** \n * Determines the log level, that is used. It is either the called method name itself or - in case java util logging is used, then it is the first argument of the method call (if it exists).\n * @param methodCall the method call\n * @return the log level or <code>null</code> if it could not be determined\n */\nprivate @Nullable String getLogLevelName(ASTMethodCall methodCall){\n String methodName=methodCall.getMethodName();\n if (!JAVA_UTIL_LOG_METHOD.equals(methodName)) {\n if (isUnguardedAccessOk(methodCall,0)) {\n return null;\n }\n return methodName;\n }\n if (isUnguardedAccessOk(methodCall,1)) {\n return null;\n }\n return getJutilLogLevelInFirstArg(methodCall);\n}\n"}}] |
|
docker-java_docker-java | docker-java/docker-java-core/src/main/java/com/github/dockerjava/core/command/RemoveSwarmNodeCmdImpl.java | RemoveSwarmNodeCmdImpl | withSwarmNodeId | class RemoveSwarmNodeCmdImpl extends AbstrDockerCmd<RemoveSwarmNodeCmd, Void> implements RemoveSwarmNodeCmd {
private String swarmNodeId;
private Boolean force;
public RemoveSwarmNodeCmdImpl(RemoveSwarmNodeCmd.Exec exec, String swarmNodeId) {
super(exec);
withSwarmNodeId(swarmNodeId);
}
@Override
@CheckForNull
public String getSwarmNodeId() {
return swarmNodeId;
}
@Override
@CheckForNull
public Boolean hasForceEnabled() {
return force;
}
@Override
public RemoveSwarmNodeCmd withSwarmNodeId(@Nonnull String swarmNodeId) {<FILL_FUNCTION_BODY>}
@Override
public RemoveSwarmNodeCmd withForce(Boolean force) {
this.force = force;
return this;
}
/**
* @throws NotFoundException No such swarmNode
*/
@Override
public Void exec() throws NotFoundException {
return super.exec();
}
} |
this.swarmNodeId = Objects.requireNonNull(swarmNodeId, "swarmNodeId was not specified");
return this;
|
this.swarmNodeId = swarmNodeId;
return this;
| [] | [] | [] | [
"requireNonNull"
] | {
"methods": [],
"similar_methods": [
"withSwarmNodeId"
],
"types": []
} | @Override public InspectSwarmNodeCmd withSwarmNodeId(String swarmNodeId){
this.swarmNodeId=Objects.requireNonNull(swarmNodeId,"swarmNodeId was not specified");
return this;
}
| @Override public InspectSwarmNodeCmd withSwarmNodeId(String swarmNodeId){
this.swarmNodeId=Objects.requireNonNull(swarmNodeId,"swarmNodeId was not specified");
return this;
}
| {"similar_methods": [{"withSwarmNodeId": "withSwarmNodeId"}]} | [] | [] | [{"withSwarmNodeId": {"retrieved_name": "withSwarmNodeId", "raw_body": "@Override public InspectSwarmNodeCmd withSwarmNodeId(String swarmNodeId){\n this.swarmNodeId=Objects.requireNonNull(swarmNodeId,\"swarmNodeId was not specified\");\n return this;\n}\n"}}] |
|
google_truth | truth/extensions/proto/src/main/java/com/google/common/truth/extensions/proto/FieldNumberTree.java | FieldNumberTree | fromMessage | class FieldNumberTree {
private static final FieldNumberTree EMPTY = new FieldNumberTree();
/** A {@code FieldNumberTree} with no children. */
static FieldNumberTree empty() {
return EMPTY;
}
// Modified only during [factory] construction, never changed afterwards.
private final Map<SubScopeId, FieldNumberTree> children = Maps.newHashMap();
/** Returns whether this {@code FieldNumberTree} has no children. */
boolean isEmpty() {
return children.isEmpty();
}
/**
* Returns the {@code FieldNumberTree} corresponding to this sub-field.
*
* <p>{@code empty()} if there is none.
*/
FieldNumberTree child(SubScopeId subScopeId) {
FieldNumberTree child = children.get(subScopeId);
return child == null ? EMPTY : child;
}
/** Returns whether this tree has a child for this node. */
boolean hasChild(SubScopeId subScopeId) {
return children.containsKey(subScopeId);
}
static FieldNumberTree fromMessage(
Message message, TypeRegistry typeRegistry, ExtensionRegistry extensionRegistry) {<FILL_FUNCTION_BODY>}
static FieldNumberTree fromMessages(
Iterable<? extends Message> messages,
TypeRegistry typeRegistry,
ExtensionRegistry extensionRegistry) {
FieldNumberTree tree = new FieldNumberTree();
for (Message message : messages) {
if (message != null) {
tree.merge(fromMessage(message, typeRegistry, extensionRegistry));
}
}
return tree;
}
private static FieldNumberTree fromUnknownFieldSet(UnknownFieldSet unknownFieldSet) {
FieldNumberTree tree = new FieldNumberTree();
for (int fieldNumber : unknownFieldSet.asMap().keySet()) {
UnknownFieldSet.Field unknownField = unknownFieldSet.asMap().get(fieldNumber);
for (UnknownFieldDescriptor unknownFieldDescriptor :
UnknownFieldDescriptor.descriptors(fieldNumber, unknownField)) {
SubScopeId subScopeId = SubScopeId.of(unknownFieldDescriptor);
FieldNumberTree childTree = new FieldNumberTree();
tree.children.put(subScopeId, childTree);
if (unknownFieldDescriptor.type() == UnknownFieldDescriptor.Type.GROUP) {
for (Object group : unknownFieldDescriptor.type().getValues(unknownField)) {
childTree.merge(fromUnknownFieldSet((UnknownFieldSet) group));
}
}
}
}
return tree;
}
/** Adds the other tree onto this one. May destroy {@code other} in the process. */
private void merge(FieldNumberTree other) {
for (SubScopeId subScopeId : other.children.keySet()) {
FieldNumberTree value = other.children.get(subScopeId);
if (!this.children.containsKey(subScopeId)) {
this.children.put(subScopeId, value);
} else {
this.children.get(subScopeId).merge(value);
}
}
}
} |
FieldNumberTree tree = new FieldNumberTree();
// Known fields.
Map<FieldDescriptor, Object> knownFieldValues = message.getAllFields();
for (FieldDescriptor field : knownFieldValues.keySet()) {
SubScopeId subScopeId = SubScopeId.of(field);
FieldNumberTree childTree = new FieldNumberTree();
tree.children.put(subScopeId, childTree);
if (field.equals(AnyUtils.valueFieldDescriptor())) {
// Handle Any protos specially.
Optional<Message> unpackedAny = AnyUtils.unpack(message, typeRegistry, extensionRegistry);
if (unpackedAny.isPresent()) {
tree.children.put(
SubScopeId.ofUnpackedAnyValueType(unpackedAny.get().getDescriptorForType()),
fromMessage(unpackedAny.get(), typeRegistry, extensionRegistry));
}
} else {
Object fieldValue = knownFieldValues.get(field);
if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) {
if (field.isRepeated()) {
List<?> valueList = (List<?>) fieldValue;
for (Object value : valueList) {
childTree.merge(fromMessage((Message) value, typeRegistry, extensionRegistry));
}
} else {
childTree.merge(fromMessage((Message) fieldValue, typeRegistry, extensionRegistry));
}
}
}
}
// Unknown fields.
tree.merge(fromUnknownFieldSet(message.getUnknownFields()));
return tree;
|
if (message.unknownFields().isEmpty()) {
return empty();
}
return fromUnknownFieldSet(message.unknownFields());
| [
"TypeRegistry",
"ExtensionRegistry",
"Message"
] | [
"isEmpty",
"unknownFields"
] | [
"SubScopeId",
"TypeRegistry",
"FieldNumberTree",
"Message",
"Optional<Message>",
"Map<FieldDescriptor,Object>",
"ExtensionRegistry",
"Map<SubScopeId,FieldNumberTree>",
"List<?>",
"FieldDescriptor"
] | [
"equals",
"isPresent",
"isRepeated",
"unpack",
"merge",
"getJavaType",
"getUnknownFields",
"get",
"getAllFields",
"getDescriptorForType",
"ofUnpackedAnyValueType",
"put",
"valueFieldDescriptor",
"keySet",
"of"
] | {
"methods": [
"isEmpty",
"unknownFields"
],
"similar_methods": [
"fromMessage"
],
"types": [
"TypeRegistry",
"ExtensionRegistry",
"Message"
]
} | /**
* Propositions for {@link Table} subjects.
* @author Kurt Alfred Kluever
*/
public final class TableSubject extends Subject {
private final @Nullable Table<?,?,?> actual;
TableSubject( FailureMetadata metadata, @Nullable Table<?,?,?> table);
/**
* Fails if the table is not empty.
*/
public void isEmpty();
/**
* Fails if the table is empty.
*/
public void isNotEmpty();
/**
* Fails if the table does not have the given size.
*/
public final void hasSize( int expectedSize);
/**
* Fails if the table does not contain a mapping for the given row key and column key.
*/
public void contains( @Nullable Object rowKey, @Nullable Object columnKey);
/**
* Fails if the table contains a mapping for the given row key and column key.
*/
public void doesNotContain( @Nullable Object rowKey, @Nullable Object columnKey);
/**
* Fails if the table does not contain the given cell.
*/
public void containsCell( @Nullable Object rowKey, @Nullable Object colKey, @Nullable Object value);
/**
* Fails if the table does not contain the given cell.
*/
public void containsCell( Cell<?,?,?> cell);
/**
* Fails if the table contains the given cell.
*/
public void doesNotContainCell( @Nullable Object rowKey, @Nullable Object colKey, @Nullable Object value);
/**
* Fails if the table contains the given cell.
*/
public void doesNotContainCell( Cell<?,?,?> cell);
/**
* Fails if the table does not contain the given row key.
*/
public void containsRow( @Nullable Object rowKey);
/**
* Fails if the table does not contain the given column key.
*/
public void containsColumn( @Nullable Object columnKey);
/**
* Fails if the table does not contain the given value.
*/
public void containsValue( @Nullable Object value);
}
/**
* Tests (and effectively sample code) for the Expect verb (implemented as a rule)
* @author David Saff
* @author Christian Gruber (cgruber@israfil.net)
*/
@RunWith(JUnit4.class) @SuppressWarnings({"ExpectedExceptionChecker","deprecation"}) public class ExpectTest {
private final Expect oopsNotARule=Expect.create();
private final Expect expect=Expect.create();
private final ExpectedException thrown=ExpectedException.none();
private final TestRule postTestWait=(base,description) -> new Statement(){
@Override public void evaluate() throws Throwable;
}
;
private final CountDownLatch testMethodComplete=new CountDownLatch(1);
/**
* A task that the main thread will await, to be provided by tests that do work in other threads.
*/
private Future<?> taskToAwait=immediateFuture(null);
@Rule public final TestRule wrapper=(statement,description) -> {
statement=expect.apply(statement,description);
statement=postTestWait.apply(statement,description);
statement=thrown.apply(statement,description);
return statement;
}
;
@Test @SuppressWarnings("TruthSelfEquals") public void expectTrue();
@Test public void singleExpectationFails();
@Test public void expectFail();
@Test public void expectFail10Aligned();
@Test public void expectFail10WrappedAligned();
@Test public void expectFailWithExceptionNoMessage();
@Test public void expectFailWithExceptionWithMessage();
@Test public void expectFailWithExceptionBeforeExpectFailures();
private void throwException();
@Test public void expectFailWithFailuresBeforeAssume();
@Test public void expectSuccessWithFailuresAfterAssume();
@Test @SuppressWarnings("TruthSelfEquals") public void warnWhenExpectIsNotRule();
@Test public void bash() throws Exception;
@Test public void failWhenCallingThatAfterTest();
@Test public void failWhenCallingFailingAssertionMethodAfterTest();
}
/**
* Determines whether an instance of type {@code A} corresponds in some way to an instance of type{@code E} for the purposes of a test assertion. For example, the implementation returned by the{@link #tolerance(double)} factory method implements approximate equality between numeric values,with values being said to correspond if the difference between them does not exceed the given fixed tolerance. The instances of type {@code A} are typically actual values from a collectionreturned by the code under test; the instances of type {@code E} are typically expected valueswith which the actual values are compared by the test. <p>The correspondence is required to be consistent: for any given values {@code actual} and{@code expected}, multiple invocations of {@code compare(actual, expected)} must consistentlyreturn {@code true} or consistently return {@code false} (provided that neither value ismodified). Although {@code A} and {@code E} will often be the same types, they are <i>not</i>required to be the same, and even if they are it is <i>not</i> required that the correspondence should have any of the other properties of an equivalence relation (reflexivity, symmetry, or transitivity). <p>Optionally, instances of this class can also provide functionality to format the difference between values which do not correspond. This results in failure messages including formatted diffs between expected and actual value, where possible. <p>The recommended approach for creating an instance of this class is to use one of the static factory methods. The most general of these is {@link #from}; the other methods are more convenient in specific cases. The optional diff-formatting functionality can be added using {@link #formattingDiffsUsing}. (Alternatively, you can subclass this class yourself, but that is generally not recommended.) <p>Instances of this are typically used via {@link IterableSubject#comparingElementsUsing}, {@link MapSubject#comparingValuesUsing}, or {@link MultimapSubject#comparingValuesUsing}.
* @author Pete Gillin
*/
public abstract class Correspondence<A extends @Nullable Object,E extends @Nullable Object> {
/**
* Constructs a {@link Correspondence} that compares actual and expected elements using the givenbinary predicate. <p>The correspondence does not support formatting of diffs (see {@link #formatDiff}). You can add that behaviour by calling {@link Correspondence#formattingDiffsUsing}. <p>Note that, if the data you are asserting about contains nulls, your predicate may be invoked with null arguments. If this causes it to throw a {@link NullPointerException}, then your test will fail. (See {@link Correspondence#compare} for more detail on how exceptions are handled.)In particular, if your predicate is an instance method reference on the actual value (as in the {@code String::contains} example below), your test will fail if it sees null actual values.<p>Example using an instance method reference: <pre> {@code static final Correspondence<String, String> CONTAINS_SUBSTRING = Correspondence.from(String::contains, "contains");}</pre> <p>Example using a static method reference: <pre> {@code class MyRecordTestHelper static final Correspondence<MyRecord, MyRecord> EQUIVALENCE = Correspondence.from(MyRecordTestHelper::recordsEquivalent, "is equivalent to"); static boolean recordsEquivalent(MyRecord actual, MyRecord expected) // code to check whether records should be considered equivalent for testing purposes}} }</pre> <p>Example using a lambda: <pre> {@code static final Correspondence<Object, Class<?>> INSTANCE_OF = Correspondence.from((obj, clazz) -> clazz.isInstance(obj), "is an instance of");}</pre>
* @param predicate a {@link BinaryPredicate} taking an actual and expected value (in that order)and returning whether the actual value corresponds to the expected value in some way
* @param description should fill the gap in a failure message of the form {@code "not true that<some actual element> is an element that <description> <some expected element>"}, e.g. {@code "contains"}, {@code "is an instance of"}, or {@code "is equivalent to"}
*/
public static <A extends @Nullable Object,E extends @Nullable Object>Correspondence<A,E> from( BinaryPredicate<A,E> predicate, String description);
/**
* A functional interface for a binary predicate, to be used to test whether a pair of objects of types {@code A} and {@code E} satisfy some condition.<p>This interface will normally be implemented using a lambda or a method reference, and the resulting object will normally be passed directly to {@link Correspondence#from}. As a result, you should almost never see {@code BinaryPredicate} used as the type of a field or variable, ora return type.
*/
public interface BinaryPredicate<A extends @Nullable Object,E extends @Nullable Object> {
/**
* Returns whether or not the actual and expected values satisfy the condition defined by this predicate.
*/
boolean apply( A actual, E expected);
}
private static final class FromBinaryPredicate<A extends @Nullable Object,E extends @Nullable Object> extends Correspondence<A,E> {
private final BinaryPredicate<A,E> predicate;
private final String description;
private FromBinaryPredicate( BinaryPredicate<A,E> correspondencePredicate, String description);
@Override public boolean compare( A actual, E expected);
@Override public String toString();
}
/**
* Constructs a {@link Correspondence} that compares elements by transforming the actual elementsusing the given function and testing for equality with the expected elements. If the transformed actual element (i.e. the output of the given function) is null, it will correspond to a null expected element. <p>The correspondence does not support formatting of diffs (see {@link #formatDiff}). You can add that behaviour by calling {@link Correspondence#formattingDiffsUsing}. <p>Note that, if you the data you are asserting about contains null actual values, your function may be invoked with a null argument. If this causes it to throw a {@link NullPointerException}, then your test will fail. (See {@link Correspondence#compare} for moredetail on how exceptions are handled.) In particular, this applies if your function is an instance method reference on the actual value (as in the example below). If you want a null actual element to correspond to a null expected element, you must ensure that your function transforms a null input to a null output. <p>Example: <pre> {@code static final Correspondence<MyRecord, Integer> HAS_ID = Correspondence.transforming(MyRecord::getId, "has an ID of");}</pre> This can be used as follows: <pre> {@code assertThat(myRecords).comparingElementsUsing(HAS_ID).containsExactly(123, 456, 789);}</pre>
* @param actualTransform a {@link Function} taking an actual value and returning a new valuewhich will be compared with an expected value to determine whether they correspond
* @param description should fill the gap in a failure message of the form {@code "not true that<some actual element> is an element that <description> <some expected element>"}, e.g. {@code "has an ID of"}
*/
public static <A extends @Nullable Object,E extends @Nullable Object>Correspondence<A,E> transforming( Function<A,? extends E> actualTransform, String description);
/**
* Constructs a {@link Correspondence} that compares elements by transforming the actual and theexpected elements using the given functions and testing the transformed values for equality. If an actual element is transformed to null, it will correspond to an expected element that is also transformed to null. <p>The correspondence does not support formatting of diffs (see {@link #formatDiff}). You can add that behaviour by calling {@link Correspondence#formattingDiffsUsing}. <p>Note that, if you the data you are asserting about contains null actual or expected values, the appropriate function may be invoked with a null argument. If this causes it to throw a {@link NullPointerException}, then your test will fail. (See {@link Correspondence#compare} formore detail on how exceptions are handled.) In particular, this applies if your function is an instance method reference on the actual or expected value (as in the example below). If you want a null actual element to correspond to a null expected element, you must ensure that your functions both transform a null input to a null output. <p>If you want to apply the same function to both the actual and expected elements, just provide the same argument twice. <p>Example: <pre> {@code static final Correspondence<MyRequest, MyResponse> SAME_IDS = Correspondence.transforming(MyRequest::getId, MyResponse::getId, "has the same ID as");}</pre> This can be used as follows: <pre> {@code assertThat(myResponses).comparingElementsUsing(SAME_IDS).containsExactlyElementsIn(myRequests);}</pre>
* @param actualTransform a {@link Function} taking an actual value and returning a new valuewhich will be compared with a transformed expected value to determine whether they correspond
* @param expectedTransform a {@link Function} taking an expected value and returning a new valuewhich will be compared with a transformed actual value
* @param description should fill the gap in a failure message of the form {@code "not true that<some actual element> is an element that <description> <some expected element>"}, e.g. {@code "has the same ID as"}
*/
public static <A extends @Nullable Object,E extends @Nullable Object>Correspondence<A,E> transforming( Function<A,?> actualTransform, Function<E,?> expectedTransform, String description);
private static final class Transforming<A extends @Nullable Object,E extends @Nullable Object> extends Correspondence<A,E> {
private final Function<? super A,?> actualTransform;
private final Function<? super E,?> expectedTransform;
private final String description;
private Transforming( Function<? super A,?> actualTransform, Function<? super E,?> expectedTransform, String description);
@Override public boolean compare( A actual, E expected);
@Override public String toString();
}
/**
* Returns a {@link Correspondence} between {@link Number} instances that considers instances tocorrespond (i.e. {@link Correspondence#compare(Object,Object)} returns {@code true}) if the double values of each instance (i.e. the result of calling {@link Number#doubleValue()} onthem) are finite values within {@code tolerance} of each other.<ul> <li>It does not consider instances to correspond if either value is infinite or NaN. <li>The conversion to double may result in a loss of precision for some numeric types. <li>The {@link Correspondence#compare(Object,Object)} method throws a {@link NullPointerException} if either {@link Number} instance is null.</ul>
* @param tolerance an inclusive upper bound on the difference between the double values of thetwo {@link Number} instances, which must be a non-negative finite value, i.e. not {@link Double#NaN}, {@link Double#POSITIVE_INFINITY}, or negative, including {@code -0.0}
*/
public static Correspondence<Number,Number> tolerance( double tolerance);
private static final class TolerantNumericEquality extends Correspondence<Number,Number> {
private final double tolerance;
private TolerantNumericEquality( double tolerance);
@Override public boolean compare( Number actual, Number expected);
@Override public String toString();
}
/**
* Returns a correspondence which compares elements using object equality, i.e. giving the same assertions as you would get without a correspondence. This exists so that we can add a diff-formatting functionality to it. See e.g. {@link IterableSubject#formattingDiffsUsing}.
*/
@SuppressWarnings("unchecked") static <T>Correspondence<T,T> equality();
private static final class Equality<T> extends Correspondence<T,T> {
private static final Equality<Object> INSTANCE=new Equality<>();
@Override public boolean compare( T actual, T expected);
@Override public String toString();
@Override boolean isEquality();
}
/**
* Constructor. Creating subclasses (anonymous or otherwise) of this class is <i>not recommended</i>, but is possible via this constructor. The recommended approach is to use the factory methods instead (see {@linkplain Correspondence class-level documentation}).
* @deprecated Construct an instance with the static factory methods instead. The most mechanicalmigration is usually to {@link #from}.
*/
@Deprecated Correspondence();
/**
* Returns a new correspondence which is like this one, except that the given formatter may be used to format the difference between a pair of elements that do not correspond. <p>Note that, if you the data you are asserting about contains null actual or expected values, the formatter may be invoked with a null argument. If this causes it to throw a {@link NullPointerException}, that will be taken to indicate that the values cannot be diffed. (See {@link Correspondence#formatDiff} for more detail on how exceptions are handled.) If you thinknull values are likely, it is slightly cleaner to have the formatter return null in that case instead of throwing. <p>Example: <pre> {@code class MyRecordTestHelper static final Correspondence<MyRecord, MyRecord> EQUIVALENCE = Correspondence.from(MyRecordTestHelper::recordsEquivalent, "is equivalent to") .formattingDiffsUsing(MyRecordTestHelper::formatRecordDiff); static boolean recordsEquivalent(MyRecord actual, MyRecord expected) // code to check whether records should be considered equivalent for testing purposes}static String formatRecordDiff(MyRecord actual, MyRecord expected) // code to format the diff between the records } } }</pre>
*/
public Correspondence<A,E> formattingDiffsUsing( DiffFormatter<? super A,? super E> formatter);
/**
* A functional interface to be used format the diff between a pair of objects of types {@code A}and {@code E}. <p>This interface will normally be implemented using a lambda or a method reference, and the resulting object will normally be passed directly to {@link Correspondence#formattingDiffsUsing}. As a result, you should almost never see {@code DiffFormatter} used as the type of a field or variable, or a return type.
*/
public interface DiffFormatter<A extends @Nullable Object,E extends @Nullable Object> {
/**
* Returns a {@link String} describing the difference between the {@code actual} and {@code expected} values, if possible, or {@code null} if not.
*/
@Nullable String formatDiff( A actual, E expected);
}
private static class FormattingDiffs<A extends @Nullable Object,E extends @Nullable Object> extends Correspondence<A,E> {
private final Correspondence<A,E> delegate;
private final DiffFormatter<? super A,? super E> formatter;
FormattingDiffs( Correspondence<A,E> delegate, DiffFormatter<? super A,? super E> formatter);
@Override public boolean compare( A actual, E expected);
@Override public @Nullable String formatDiff( A actual, E expected);
@Override public String toString();
@Override boolean isEquality();
}
/**
* Returns whether or not the {@code actual} value is said to correspond to the {@code expected}value for the purposes of this test. <h3>Exception handling</h3> <p>Throwing a {@link RuntimeException} from this method indicates that this {@link Correspondence} cannot compare the given values. Any assertion which encounters such anexception during the course of evaluating its condition must not pass. However, an assertion is not required to invoke this method for every pair of values in its input just in order to check for exceptions, if it is able to evaluate its condition without doing so. <h4>Conventions for handling exceptions</h4> <p>(N.B. This section is only really of interest when implementing assertion methods that call {@link Correspondence#compare}, not to users making such assertions in their tests.) <p>The only requirement on an assertion is that, if it encounters an exception from this method, it must not pass. The simplest implementation choice is simply to allow the exception to propagate. However, it is normally more helpful to catch the exception and instead fail with a message which includes more information about the assertion in progress and the nature of the failure. <p>By convention, an assertion may catch and store the exception and continue evaluating the condition as if the method had returned false instead of throwing. If the assertion's condition does not hold with this alternative behaviour, it may choose to fail with a message that gives details about how the condition does not hold, additionally mentioning that assertions were encountered and giving details about one of the stored exceptions. (See the first example below.) If the assertion's condition does hold with this alternative behaviour, the requirement that the assertion must not pass still applies, so it should fail with a message giving details about one of the stored exceptions. (See the second and third examples below.) <p>This behaviour is only a convention and should only be implemented when it makes sense to do so. In particular, in an assertion that has multiple stages, it may be better to only continue evaluation to the end of the current stage, and fail citing a stored exception at the end of the stage, rather than accumulating exceptions through the multiple stages. <h4>Examples of exception handling</h4> <p>Suppose that we have the correspondence <pre> {@code static final Correspondence<String, String> CASE_INSENSITIVE_EQUALITY = Correspondence.from(String::equalsIgnoreCase, "equals ignoring case"}}</pre> whose {@code compare} method throws {@link NullPointerException} if the actual value is null.The assertion <pre> {@code assertThat(asList(null, "xyz", "abc", "def")) .comparingElementsUsing(CASE_INSENSITIVE_EQUALITY) .containsExactly("ABC", "DEF", "GHI", "JKL");}</pre> may fail saying that the actual iterable contains unexpected values {@code null} and {@code xyz} and is missing values corresponding to {@code GHI} and {@code JKL}, which is what it would do if the {@code compare} method returned false instead of throwing, and additionally mentionthe exception. (This is more helpful than allowing the {@link NullPointerException} topropagate to the caller, or than failing with only a description of the exception.) <p>However, the assertions <pre> {@code assertThat(asList(null, "xyz", "abc", "def")) .comparingElementsUsing(CASE_INSENSITIVE_EQUALITY) .doesNotContain("MNO");}</pre> and <pre> {@code assertThat(asList(null, "xyz", "abc", "def")) .comparingElementsUsing(CASE_INSENSITIVE_EQUALITY) .doesNotContain(null);}</pre> must both fail citing the exception, even though they would pass if the {@code compare} methodreturned false. (Note that, in the latter case at least, it is likely that the test author's intention was <i>not</i> for the test to pass with these values.)
*/
public abstract boolean compare( A actual, E expected);
private static class StoredException {
private static final Joiner ARGUMENT_JOINER=Joiner.on(", ").useForNull("null");
private final Exception exception;
private final String methodName;
private final List<@Nullable Object> methodArguments;
StoredException( Exception exception, String methodName, List<@Nullable Object> methodArguments);
/**
* Returns a String describing the exception stored. This includes a stack trace (except under j2cl, where this is not available). It also has a separator at the end, so that when this appears at the end of an {@code AssertionError} message, the stack trace of the storedexception is distinguishable from the stack trace of the {@code AssertionError}.
*/
private String describe();
}
/**
* Helper object to store exceptions encountered while executing a {@link Correspondence} method.
*/
static final class ExceptionStore {
private final String argumentLabel;
private @Nullable StoredException firstCompareException=null;
private @Nullable StoredException firstPairingException=null;
private @Nullable StoredException firstFormatDiffException=null;
static ExceptionStore forIterable();
static ExceptionStore forMapValues();
private ExceptionStore( String argumentLabel);
/**
* Adds an exception that was thrown during a {@code compare} call.
* @param callingClass The class from which the {@code compare} method was called. Whenreporting failures, stack traces will be truncated above elements in this class.
* @param exception The exception encountered
* @param actual The {@code actual} argument to the {@code compare} call during which theexception was encountered
* @param expected The {@code expected} argument to the {@code compare} call during which theexception was encountered
*/
void addCompareException( Class<?> callingClass, Exception exception, @Nullable Object actual, @Nullable Object expected);
/**
* Adds an exception that was thrown during an {@code apply} call on the function used to keyactual elements.
* @param callingClass The class from which the {@code apply} method was called. When reportingfailures, stack traces will be truncated above elements in this class.
* @param exception The exception encountered
* @param actual The {@code actual} argument to the {@code apply} call during which theexception was encountered
*/
void addActualKeyFunctionException( Class<?> callingClass, Exception exception, @Nullable Object actual);
/**
* Adds an exception that was thrown during an {@code apply} call on the function used to keyexpected elements.
* @param callingClass The class from which the {@code apply} method was called. When reportingfailures, stack traces will be truncated above elements in this class.
* @param exception The exception encountered
* @param expected The {@code expected} argument to the {@code apply} call during which theexception was encountered
*/
void addExpectedKeyFunctionException( Class<?> callingClass, Exception exception, @Nullable Object expected);
/**
* Adds an exception that was thrown during a {@code formatDiff} call.
* @param callingClass The class from which the {@code formatDiff} method was called. Whenreporting failures, stack traces will be truncated above elements in this class.
* @param exception The exception encountered
* @param actual The {@code actual} argument to the {@code formatDiff} call during which theexception was encountered
* @param expected The {@code expected} argument to the {@code formatDiff} call during which theexception was encountered
*/
void addFormatDiffException( Class<?> callingClass, Exception exception, @Nullable Object actual, @Nullable Object expected);
/**
* Returns whether any exceptions thrown during {@code compare} calls were stored.
*/
boolean hasCompareException();
/**
* Returns facts to use in a failure message when the exceptions from {@code compare} calls arethe main cause of the failure. At least one exception thrown during a {@code compare} callmust have been stored, and no exceptions from a {@code formatDiff} call. Assertions shoulduse this when exceptions were thrown while comparing elements and no more meaningful failure was discovered by assuming a false return and continuing (see the javadoc for {@link Correspondence#compare}). C.f. {@link #describeAsAdditionalInfo}.
*/
ImmutableList<Fact> describeAsMainCause();
/**
* If any exceptions are stored, returns facts to use in a failure message when the exceptions should be noted as additional info; if empty, returns an empty list. Assertions should use this when exceptions were thrown while comparing elements but more meaningful failures were discovered by assuming a false return and continuing (see the javadoc for {@link Correspondence#compare}), or when exceptions were thrown by other methods while generating the failure message. C.f. {@link #describeAsMainCause}.
*/
ImmutableList<Fact> describeAsAdditionalInfo();
private static void truncateStackTrace( Exception exception, Class<?> callingClass);
}
/**
* Invokes {@link #compare}, catching any exceptions. If the comparison does not throw, returns the result. If it does throw, adds the exception to the given {@link ExceptionStore} andreturns false. This method can help with implementing the exception-handling policy described above, but note that assertions using it <i>must</i> fail later if an exception was stored.
*/
final boolean safeCompare( A actual, E expected, ExceptionStore exceptions);
/**
* Returns a {@link String} describing the difference between the {@code actual} and {@code expected} values, if possible, or {@code null} if not.<p>The implementation on the {@link Correspondence} base class always returns {@code null}. To enable diffing, use {@link #formattingDiffsUsing} (or override this method in a subclass, butfactory methods are recommended over subclassing). <p>Assertions should only invoke this with parameters for which {@link #compare} returns {@code false}. <p>If this throws an exception, that implies that it is not possible to describe the diffs. An assertion will normally only call this method if it has established that its condition does not hold: good practice dictates that, if this method throws, the assertion should catch the exception and continue to describe the original failure as if this method had returned null, mentioning the failure from this method as additional information.
*/
public @Nullable String formatDiff( A actual, E expected);
/**
* Invokes {@link #formatDiff}, catching any exceptions. If the comparison does not throw, returns the result. If it does throw, adds the exception to the given {@link ExceptionStore} andreturns null.
*/
final @Nullable String safeFormatDiff( A actual, E expected, ExceptionStore exceptions);
/**
* Returns a description of the correspondence, suitable to fill the gap in a failure message of the form {@code "<some actual element> is an element that ... <some expected element>"}. Note that this is a fragment of a verb phrase which takes a singular subject. <p>Example 1: For a {@code Correspondence<String, Integer>} that tests whether the actualstring parses to the expected integer, this would return {@code "parses to"} to result in afailure message of the form {@code "<some actual string> is an element that parses to <someexpected integer>"}. <p>Example 2: For the {@code Correspondence<Number, Number>} returns by {@link #tolerance} thisreturns {@code "is a finite number within " + tolerance + " of"} to result in a failure messageof the form {@code "<some actual number> is an element that is a finite number within 0.0001 of<some expected number>"}.
*/
@Override public abstract String toString();
/**
* Returns whether this is an equality correspondence, i.e. one returned by {@link #equality} orone whose {@link #compare} delegates to one returned by {@link #equality}.
*/
boolean isEquality();
/**
* Returns a list of {@link Fact} instance describing how this correspondence compares elements ofan iterable. There will be one "testing whether" fact, unless this {@link #isEquality is anequality correspondence}, in which case the list will be empty.
*/
final ImmutableList<Fact> describeForIterable();
/**
* Returns a list of {@link Fact} instance describing how this correspondence compares values in amap (or multimap). There will be one "testing whether" fact, unless this {@link #isEquality isan equality correspondence}, in which case the list will be empty.
*/
final ImmutableList<Fact> describeForMapValues();
/**
* @throws UnsupportedOperationException always
* @deprecated {@link Object#equals(Object)} is not supported. If you meant to compare objectsusing this {@link Correspondence}, use {@link #compare}.
*/
@Deprecated @Override public final boolean equals( @Nullable Object o);
/**
* @throws UnsupportedOperationException always
* @deprecated {@link Object#hashCode()} is not supported.
*/
@Deprecated @Override public final int hashCode();
}
/**
* Fails if the array is not empty (i.e. {@code array.length > 0}).
*/
public final void isEmpty(){
if (length() > 0) {
failWithActual(simpleFact("expected to be empty"));
}
}
@Override Optional<DiffResult.UnknownFieldSetDiff> unknownFields(){
return unknownFields;
}
/**
* Returns a new instance whose failures will contain the given message. The way for Truth users to set a message is {@code check(...).withMessage(...).that(...)} (for calls from within a{@code Subject}) or {@link Truth#assertWithMessage} (for most other calls).
*/
FailureMetadata withMessage(String format,@Nullable Object[] args){
ImmutableList<LazyMessage> messages=append(this.messages,new LazyMessage(format,args));
return derive(messages,steps);
}
| public final class TableSubject extends Subject {
private final Table<?,?,?> actual;
TableSubject( FailureMetadata metadata, Table<?,?,?> table);
public void isEmpty();
public void isNotEmpty();
public final void hasSize( int expectedSize);
public void contains( Object rowKey, Object columnKey);
public void doesNotContain( Object rowKey, Object columnKey);
public void containsCell( Object rowKey, Object colKey, Object value);
public void containsCell( Cell<?,?,?> cell);
public void doesNotContainCell( Object rowKey, Object colKey, Object value);
public void doesNotContainCell( Cell<?,?,?> cell);
public void containsRow( Object rowKey);
public void containsColumn( Object columnKey);
public void containsValue( Object value);
}
public class ExpectTest {
private final Expect oopsNotARule=Expect.create();
private final Expect expect=Expect.create();
private final ExpectedException thrown=ExpectedException.none();
private final TestRule postTestWait=(base,description) -> new Statement(){
public void evaluate() throws Throwable;
}
;
private final CountDownLatch testMethodComplete=new CountDownLatch(1);
private Future<?> taskToAwait=immediateFuture(null);
public final TestRule wrapper=(statement,description) -> {
statement=expect.apply(statement,description);
statement=postTestWait.apply(statement,description);
statement=thrown.apply(statement,description);
return statement;
}
;
public void expectTrue();
public void singleExpectationFails();
public void expectFail();
public void expectFail10Aligned();
public void expectFail10WrappedAligned();
public void expectFailWithExceptionNoMessage();
public void expectFailWithExceptionWithMessage();
public void expectFailWithExceptionBeforeExpectFailures();
private void throwException();
public void expectFailWithFailuresBeforeAssume();
public void expectSuccessWithFailuresAfterAssume();
public void warnWhenExpectIsNotRule();
public void bash() throws Exception;
public void failWhenCallingThatAfterTest();
public void failWhenCallingFailingAssertionMethodAfterTest();
}
public abstract class Correspondence<A extends Object,E extends Object> {
public static <A extends Object,E extends Object>Correspondence<A,E> from( BinaryPredicate<A,E> predicate, String description);
public interface BinaryPredicate<A extends Object,E extends Object> {
boolean apply( A actual, E expected);
}
private static final class FromBinaryPredicate<A extends Object,E extends Object> extends Correspondence<A,E> {
private final BinaryPredicate<A,E> predicate;
private final String description;
private FromBinaryPredicate( BinaryPredicate<A,E> correspondencePredicate, String description);
public boolean compare( A actual, E expected);
public String toString();
}
public static <A extends Object,E extends Object>Correspondence<A,E> transforming( Function<A,? extends E> actualTransform, String description);
public static <A extends Object,E extends Object>Correspondence<A,E> transforming( Function<A,?> actualTransform, Function<E,?> expectedTransform, String description);
private static final class Transforming<A extends Object,E extends Object> extends Correspondence<A,E> {
private final Function<? super A,?> actualTransform;
private final Function<? super E,?> expectedTransform;
private final String description;
private Transforming( Function<? super A,?> actualTransform, Function<? super E,?> expectedTransform, String description);
public boolean compare( A actual, E expected);
public String toString();
}
public static Correspondence<Number,Number> tolerance( double tolerance);
private static final class TolerantNumericEquality extends Correspondence<Number,Number> {
private final double tolerance;
private TolerantNumericEquality( double tolerance);
public boolean compare( Number actual, Number expected);
public String toString();
}
static <T>Correspondence<T,T> equality();
private static final class Equality<T> extends Correspondence<T,T> {
private static final Equality<Object> INSTANCE=new Equality<>();
public boolean compare( T actual, T expected);
public String toString();
boolean isEquality();
}
Correspondence();
public Correspondence<A,E> formattingDiffsUsing( DiffFormatter<? super A,? super E> formatter);
public interface DiffFormatter<A extends Object,E extends Object> {
String formatDiff( A actual, E expected);
}
private static class FormattingDiffs<A extends Object,E extends Object> extends Correspondence<A,E> {
private final Correspondence<A,E> delegate;
private final DiffFormatter<? super A,? super E> formatter;
FormattingDiffs( Correspondence<A,E> delegate, DiffFormatter<? super A,? super E> formatter);
public boolean compare( A actual, E expected);
public String formatDiff( A actual, E expected);
public String toString();
boolean isEquality();
}
public abstract boolean compare( A actual, E expected);
private static class StoredException {
private static final Joiner ARGUMENT_JOINER=Joiner.on(", ").useForNull("null");
private final Exception exception;
private final String methodName;
private final List<Object> methodArguments;
StoredException( Exception exception, String methodName, List<Object> methodArguments);
private String describe();
}
static final class ExceptionStore {
private final String argumentLabel;
private StoredException firstCompareException=null;
private StoredException firstPairingException=null;
private StoredException firstFormatDiffException=null;
static ExceptionStore forIterable();
static ExceptionStore forMapValues();
private ExceptionStore( String argumentLabel);
void addCompareException( Class<?> callingClass, Exception exception, Object actual, Object expected);
void addActualKeyFunctionException( Class<?> callingClass, Exception exception, Object actual);
void addExpectedKeyFunctionException( Class<?> callingClass, Exception exception, Object expected);
void addFormatDiffException( Class<?> callingClass, Exception exception, Object actual, Object expected);
boolean hasCompareException();
ImmutableList<Fact> describeAsMainCause();
ImmutableList<Fact> describeAsAdditionalInfo();
private static void truncateStackTrace( Exception exception, Class<?> callingClass);
}
final boolean safeCompare( A actual, E expected, ExceptionStore exceptions);
public String formatDiff( A actual, E expected);
final String safeFormatDiff( A actual, E expected, ExceptionStore exceptions);
public abstract String toString();
boolean isEquality();
final ImmutableList<Fact> describeForIterable();
final ImmutableList<Fact> describeForMapValues();
public final boolean equals( Object o);
public final int hashCode();
}
/**
* Fails if the array is not empty (i.e. {@code array.length > 0}).
*/
public final void isEmpty(){
if (length() > 0) {
failWithActual(simpleFact("expected to be empty"));
}
}
@Override Optional<DiffResult.UnknownFieldSetDiff> unknownFields(){
return unknownFields;
}
/**
* Returns a new instance whose failures will contain the given message. The way for Truth users to set a message is {@code check(...).withMessage(...).that(...)} (for calls from within a{@code Subject}) or {@link Truth#assertWithMessage} (for most other calls).
*/
FailureMetadata withMessage(String format,@Nullable Object[] args){
ImmutableList<LazyMessage> messages=append(this.messages,new LazyMessage(format,args));
return derive(messages,steps);
}
| {"types": [{"TypeRegistry": "TableSubject"}, {"ExtensionRegistry": "ExpectTest"}, {"Message": "Correspondence"}], "methods": [{"isEmpty": "isEmpty"}, {"unknownFields": "unknownFields"}], "similar_methods": [{"fromMessage": "withMessage"}]} | [{"TypeRegistry": {"retrieved_name": "TableSubject", "raw_body": "/** \n * Propositions for {@link Table} subjects.\n * @author Kurt Alfred Kluever\n */\npublic final class TableSubject extends Subject {\n private final @Nullable Table<?,?,?> actual;\n TableSubject( FailureMetadata metadata, @Nullable Table<?,?,?> table);\n /** \n * Fails if the table is not empty. \n */\n public void isEmpty();\n /** \n * Fails if the table is empty. \n */\n public void isNotEmpty();\n /** \n * Fails if the table does not have the given size. \n */\n public final void hasSize( int expectedSize);\n /** \n * Fails if the table does not contain a mapping for the given row key and column key. \n */\n public void contains( @Nullable Object rowKey, @Nullable Object columnKey);\n /** \n * Fails if the table contains a mapping for the given row key and column key. \n */\n public void doesNotContain( @Nullable Object rowKey, @Nullable Object columnKey);\n /** \n * Fails if the table does not contain the given cell. \n */\n public void containsCell( @Nullable Object rowKey, @Nullable Object colKey, @Nullable Object value);\n /** \n * Fails if the table does not contain the given cell. \n */\n public void containsCell( Cell<?,?,?> cell);\n /** \n * Fails if the table contains the given cell. \n */\n public void doesNotContainCell( @Nullable Object rowKey, @Nullable Object colKey, @Nullable Object value);\n /** \n * Fails if the table contains the given cell. \n */\n public void doesNotContainCell( Cell<?,?,?> cell);\n /** \n * Fails if the table does not contain the given row key. \n */\n public void containsRow( @Nullable Object rowKey);\n /** \n * Fails if the table does not contain the given column key. \n */\n public void containsColumn( @Nullable Object columnKey);\n /** \n * Fails if the table does not contain the given value. \n */\n public void containsValue( @Nullable Object value);\n}\n", "raw_body_no_cmt": "public final class TableSubject extends Subject {\n private final Table<?,?,?> actual;\n TableSubject( FailureMetadata metadata, Table<?,?,?> table);\n public void isEmpty();\n public void isNotEmpty();\n public final void hasSize( int expectedSize);\n public void contains( Object rowKey, Object columnKey);\n public void doesNotContain( Object rowKey, Object columnKey);\n public void containsCell( Object rowKey, Object colKey, Object value);\n public void containsCell( Cell<?,?,?> cell);\n public void doesNotContainCell( Object rowKey, Object colKey, Object value);\n public void doesNotContainCell( Cell<?,?,?> cell);\n public void containsRow( Object rowKey);\n public void containsColumn( Object columnKey);\n public void containsValue( Object value);\n}\n"}}, {"ExtensionRegistry": {"retrieved_name": "ExpectTest", "raw_body": "/** \n * Tests (and effectively sample code) for the Expect verb (implemented as a rule)\n * @author David Saff\n * @author Christian Gruber (cgruber@israfil.net)\n */\n@RunWith(JUnit4.class) @SuppressWarnings({\"ExpectedExceptionChecker\",\"deprecation\"}) public class ExpectTest {\n private final Expect oopsNotARule=Expect.create();\n private final Expect expect=Expect.create();\n private final ExpectedException thrown=ExpectedException.none();\n private final TestRule postTestWait=(base,description) -> new Statement(){\n @Override public void evaluate() throws Throwable;\n }\n;\n private final CountDownLatch testMethodComplete=new CountDownLatch(1);\n /** \n * A task that the main thread will await, to be provided by tests that do work in other threads.\n */\n private Future<?> taskToAwait=immediateFuture(null);\n @Rule public final TestRule wrapper=(statement,description) -> {\n statement=expect.apply(statement,description);\n statement=postTestWait.apply(statement,description);\n statement=thrown.apply(statement,description);\n return statement;\n }\n;\n @Test @SuppressWarnings(\"TruthSelfEquals\") public void expectTrue();\n @Test public void singleExpectationFails();\n @Test public void expectFail();\n @Test public void expectFail10Aligned();\n @Test public void expectFail10WrappedAligned();\n @Test public void expectFailWithExceptionNoMessage();\n @Test public void expectFailWithExceptionWithMessage();\n @Test public void expectFailWithExceptionBeforeExpectFailures();\n private void throwException();\n @Test public void expectFailWithFailuresBeforeAssume();\n @Test public void expectSuccessWithFailuresAfterAssume();\n @Test @SuppressWarnings(\"TruthSelfEquals\") public void warnWhenExpectIsNotRule();\n @Test public void bash() throws Exception;\n @Test public void failWhenCallingThatAfterTest();\n @Test public void failWhenCallingFailingAssertionMethodAfterTest();\n}\n", "raw_body_no_cmt": "public class ExpectTest {\n private final Expect oopsNotARule=Expect.create();\n private final Expect expect=Expect.create();\n private final ExpectedException thrown=ExpectedException.none();\n private final TestRule postTestWait=(base,description) -> new Statement(){\n public void evaluate() throws Throwable;\n }\n;\n private final CountDownLatch testMethodComplete=new CountDownLatch(1);\n private Future<?> taskToAwait=immediateFuture(null);\n public final TestRule wrapper=(statement,description) -> {\n statement=expect.apply(statement,description);\n statement=postTestWait.apply(statement,description);\n statement=thrown.apply(statement,description);\n return statement;\n }\n;\n public void expectTrue();\n public void singleExpectationFails();\n public void expectFail();\n public void expectFail10Aligned();\n public void expectFail10WrappedAligned();\n public void expectFailWithExceptionNoMessage();\n public void expectFailWithExceptionWithMessage();\n public void expectFailWithExceptionBeforeExpectFailures();\n private void throwException();\n public void expectFailWithFailuresBeforeAssume();\n public void expectSuccessWithFailuresAfterAssume();\n public void warnWhenExpectIsNotRule();\n public void bash() throws Exception;\n public void failWhenCallingThatAfterTest();\n public void failWhenCallingFailingAssertionMethodAfterTest();\n}\n"}}, {"Message": {"retrieved_name": "Correspondence", "raw_body": "/** \n * Determines whether an instance of type {@code A} corresponds in some way to an instance of type{@code E} for the purposes of a test assertion. For example, the implementation returned by the{@link #tolerance(double)} factory method implements approximate equality between numeric values,with values being said to correspond if the difference between them does not exceed the given fixed tolerance. The instances of type {@code A} are typically actual values from a collectionreturned by the code under test; the instances of type {@code E} are typically expected valueswith which the actual values are compared by the test. <p>The correspondence is required to be consistent: for any given values {@code actual} and{@code expected}, multiple invocations of {@code compare(actual, expected)} must consistentlyreturn {@code true} or consistently return {@code false} (provided that neither value ismodified). Although {@code A} and {@code E} will often be the same types, they are <i>not</i>required to be the same, and even if they are it is <i>not</i> required that the correspondence should have any of the other properties of an equivalence relation (reflexivity, symmetry, or transitivity). <p>Optionally, instances of this class can also provide functionality to format the difference between values which do not correspond. This results in failure messages including formatted diffs between expected and actual value, where possible. <p>The recommended approach for creating an instance of this class is to use one of the static factory methods. The most general of these is {@link #from}; the other methods are more convenient in specific cases. The optional diff-formatting functionality can be added using {@link #formattingDiffsUsing}. (Alternatively, you can subclass this class yourself, but that is generally not recommended.) <p>Instances of this are typically used via {@link IterableSubject#comparingElementsUsing}, {@link MapSubject#comparingValuesUsing}, or {@link MultimapSubject#comparingValuesUsing}.\n * @author Pete Gillin\n */\npublic abstract class Correspondence<A extends @Nullable Object,E extends @Nullable Object> {\n /** \n * Constructs a {@link Correspondence} that compares actual and expected elements using the givenbinary predicate. <p>The correspondence does not support formatting of diffs (see {@link #formatDiff}). You can add that behaviour by calling {@link Correspondence#formattingDiffsUsing}. <p>Note that, if the data you are asserting about contains nulls, your predicate may be invoked with null arguments. If this causes it to throw a {@link NullPointerException}, then your test will fail. (See {@link Correspondence#compare} for more detail on how exceptions are handled.)In particular, if your predicate is an instance method reference on the actual value (as in the {@code String::contains} example below), your test will fail if it sees null actual values.<p>Example using an instance method reference: <pre> {@code static final Correspondence<String, String> CONTAINS_SUBSTRING = Correspondence.from(String::contains, \"contains\");}</pre> <p>Example using a static method reference: <pre> {@code class MyRecordTestHelper static final Correspondence<MyRecord, MyRecord> EQUIVALENCE = Correspondence.from(MyRecordTestHelper::recordsEquivalent, \"is equivalent to\"); static boolean recordsEquivalent(MyRecord actual, MyRecord expected) // code to check whether records should be considered equivalent for testing purposes}} }</pre> <p>Example using a lambda: <pre> {@code static final Correspondence<Object, Class<?>> INSTANCE_OF = Correspondence.from((obj, clazz) -> clazz.isInstance(obj), \"is an instance of\");}</pre>\n * @param predicate a {@link BinaryPredicate} taking an actual and expected value (in that order)and returning whether the actual value corresponds to the expected value in some way\n * @param description should fill the gap in a failure message of the form {@code \"not true that<some actual element> is an element that <description> <some expected element>\"}, e.g. {@code \"contains\"}, {@code \"is an instance of\"}, or {@code \"is equivalent to\"}\n */\n public static <A extends @Nullable Object,E extends @Nullable Object>Correspondence<A,E> from( BinaryPredicate<A,E> predicate, String description);\n /** \n * A functional interface for a binary predicate, to be used to test whether a pair of objects of types {@code A} and {@code E} satisfy some condition.<p>This interface will normally be implemented using a lambda or a method reference, and the resulting object will normally be passed directly to {@link Correspondence#from}. As a result, you should almost never see {@code BinaryPredicate} used as the type of a field or variable, ora return type.\n */\npublic interface BinaryPredicate<A extends @Nullable Object,E extends @Nullable Object> {\n /** \n * Returns whether or not the actual and expected values satisfy the condition defined by this predicate.\n */\n boolean apply( A actual, E expected);\n }\nprivate static final class FromBinaryPredicate<A extends @Nullable Object,E extends @Nullable Object> extends Correspondence<A,E> {\n private final BinaryPredicate<A,E> predicate;\n private final String description;\n private FromBinaryPredicate( BinaryPredicate<A,E> correspondencePredicate, String description);\n @Override public boolean compare( A actual, E expected);\n @Override public String toString();\n }\n /** \n * Constructs a {@link Correspondence} that compares elements by transforming the actual elementsusing the given function and testing for equality with the expected elements. If the transformed actual element (i.e. the output of the given function) is null, it will correspond to a null expected element. <p>The correspondence does not support formatting of diffs (see {@link #formatDiff}). You can add that behaviour by calling {@link Correspondence#formattingDiffsUsing}. <p>Note that, if you the data you are asserting about contains null actual values, your function may be invoked with a null argument. If this causes it to throw a {@link NullPointerException}, then your test will fail. (See {@link Correspondence#compare} for moredetail on how exceptions are handled.) In particular, this applies if your function is an instance method reference on the actual value (as in the example below). If you want a null actual element to correspond to a null expected element, you must ensure that your function transforms a null input to a null output. <p>Example: <pre> {@code static final Correspondence<MyRecord, Integer> HAS_ID = Correspondence.transforming(MyRecord::getId, \"has an ID of\");}</pre> This can be used as follows: <pre> {@code assertThat(myRecords).comparingElementsUsing(HAS_ID).containsExactly(123, 456, 789);}</pre>\n * @param actualTransform a {@link Function} taking an actual value and returning a new valuewhich will be compared with an expected value to determine whether they correspond\n * @param description should fill the gap in a failure message of the form {@code \"not true that<some actual element> is an element that <description> <some expected element>\"}, e.g. {@code \"has an ID of\"}\n */\n public static <A extends @Nullable Object,E extends @Nullable Object>Correspondence<A,E> transforming( Function<A,? extends E> actualTransform, String description);\n /** \n * Constructs a {@link Correspondence} that compares elements by transforming the actual and theexpected elements using the given functions and testing the transformed values for equality. If an actual element is transformed to null, it will correspond to an expected element that is also transformed to null. <p>The correspondence does not support formatting of diffs (see {@link #formatDiff}). You can add that behaviour by calling {@link Correspondence#formattingDiffsUsing}. <p>Note that, if you the data you are asserting about contains null actual or expected values, the appropriate function may be invoked with a null argument. If this causes it to throw a {@link NullPointerException}, then your test will fail. (See {@link Correspondence#compare} formore detail on how exceptions are handled.) In particular, this applies if your function is an instance method reference on the actual or expected value (as in the example below). If you want a null actual element to correspond to a null expected element, you must ensure that your functions both transform a null input to a null output. <p>If you want to apply the same function to both the actual and expected elements, just provide the same argument twice. <p>Example: <pre> {@code static final Correspondence<MyRequest, MyResponse> SAME_IDS = Correspondence.transforming(MyRequest::getId, MyResponse::getId, \"has the same ID as\");}</pre> This can be used as follows: <pre> {@code assertThat(myResponses).comparingElementsUsing(SAME_IDS).containsExactlyElementsIn(myRequests);}</pre>\n * @param actualTransform a {@link Function} taking an actual value and returning a new valuewhich will be compared with a transformed expected value to determine whether they correspond\n * @param expectedTransform a {@link Function} taking an expected value and returning a new valuewhich will be compared with a transformed actual value\n * @param description should fill the gap in a failure message of the form {@code \"not true that<some actual element> is an element that <description> <some expected element>\"}, e.g. {@code \"has the same ID as\"}\n */\n public static <A extends @Nullable Object,E extends @Nullable Object>Correspondence<A,E> transforming( Function<A,?> actualTransform, Function<E,?> expectedTransform, String description);\nprivate static final class Transforming<A extends @Nullable Object,E extends @Nullable Object> extends Correspondence<A,E> {\n private final Function<? super A,?> actualTransform;\n private final Function<? super E,?> expectedTransform;\n private final String description;\n private Transforming( Function<? super A,?> actualTransform, Function<? super E,?> expectedTransform, String description);\n @Override public boolean compare( A actual, E expected);\n @Override public String toString();\n }\n /** \n * Returns a {@link Correspondence} between {@link Number} instances that considers instances tocorrespond (i.e. {@link Correspondence#compare(Object,Object)} returns {@code true}) if the double values of each instance (i.e. the result of calling {@link Number#doubleValue()} onthem) are finite values within {@code tolerance} of each other.<ul> <li>It does not consider instances to correspond if either value is infinite or NaN. <li>The conversion to double may result in a loss of precision for some numeric types. <li>The {@link Correspondence#compare(Object,Object)} method throws a {@link NullPointerException} if either {@link Number} instance is null.</ul>\n * @param tolerance an inclusive upper bound on the difference between the double values of thetwo {@link Number} instances, which must be a non-negative finite value, i.e. not {@link Double#NaN}, {@link Double#POSITIVE_INFINITY}, or negative, including {@code -0.0}\n */\n public static Correspondence<Number,Number> tolerance( double tolerance);\nprivate static final class TolerantNumericEquality extends Correspondence<Number,Number> {\n private final double tolerance;\n private TolerantNumericEquality( double tolerance);\n @Override public boolean compare( Number actual, Number expected);\n @Override public String toString();\n }\n /** \n * Returns a correspondence which compares elements using object equality, i.e. giving the same assertions as you would get without a correspondence. This exists so that we can add a diff-formatting functionality to it. See e.g. {@link IterableSubject#formattingDiffsUsing}.\n */\n @SuppressWarnings(\"unchecked\") static <T>Correspondence<T,T> equality();\nprivate static final class Equality<T> extends Correspondence<T,T> {\n private static final Equality<Object> INSTANCE=new Equality<>();\n @Override public boolean compare( T actual, T expected);\n @Override public String toString();\n @Override boolean isEquality();\n }\n /** \n * Constructor. Creating subclasses (anonymous or otherwise) of this class is <i>not recommended</i>, but is possible via this constructor. The recommended approach is to use the factory methods instead (see {@linkplain Correspondence class-level documentation}).\n * @deprecated Construct an instance with the static factory methods instead. The most mechanicalmigration is usually to {@link #from}.\n */\n @Deprecated Correspondence();\n /** \n * Returns a new correspondence which is like this one, except that the given formatter may be used to format the difference between a pair of elements that do not correspond. <p>Note that, if you the data you are asserting about contains null actual or expected values, the formatter may be invoked with a null argument. If this causes it to throw a {@link NullPointerException}, that will be taken to indicate that the values cannot be diffed. (See {@link Correspondence#formatDiff} for more detail on how exceptions are handled.) If you thinknull values are likely, it is slightly cleaner to have the formatter return null in that case instead of throwing. <p>Example: <pre> {@code class MyRecordTestHelper static final Correspondence<MyRecord, MyRecord> EQUIVALENCE = Correspondence.from(MyRecordTestHelper::recordsEquivalent, \"is equivalent to\") .formattingDiffsUsing(MyRecordTestHelper::formatRecordDiff); static boolean recordsEquivalent(MyRecord actual, MyRecord expected) // code to check whether records should be considered equivalent for testing purposes}static String formatRecordDiff(MyRecord actual, MyRecord expected) // code to format the diff between the records } } }</pre>\n */\n public Correspondence<A,E> formattingDiffsUsing( DiffFormatter<? super A,? super E> formatter);\n /** \n * A functional interface to be used format the diff between a pair of objects of types {@code A}and {@code E}. <p>This interface will normally be implemented using a lambda or a method reference, and the resulting object will normally be passed directly to {@link Correspondence#formattingDiffsUsing}. As a result, you should almost never see {@code DiffFormatter} used as the type of a field or variable, or a return type.\n */\npublic interface DiffFormatter<A extends @Nullable Object,E extends @Nullable Object> {\n /** \n * Returns a {@link String} describing the difference between the {@code actual} and {@code expected} values, if possible, or {@code null} if not.\n */\n @Nullable String formatDiff( A actual, E expected);\n }\nprivate static class FormattingDiffs<A extends @Nullable Object,E extends @Nullable Object> extends Correspondence<A,E> {\n private final Correspondence<A,E> delegate;\n private final DiffFormatter<? super A,? super E> formatter;\n FormattingDiffs( Correspondence<A,E> delegate, DiffFormatter<? super A,? super E> formatter);\n @Override public boolean compare( A actual, E expected);\n @Override public @Nullable String formatDiff( A actual, E expected);\n @Override public String toString();\n @Override boolean isEquality();\n }\n /** \n * Returns whether or not the {@code actual} value is said to correspond to the {@code expected}value for the purposes of this test. <h3>Exception handling</h3> <p>Throwing a {@link RuntimeException} from this method indicates that this {@link Correspondence} cannot compare the given values. Any assertion which encounters such anexception during the course of evaluating its condition must not pass. However, an assertion is not required to invoke this method for every pair of values in its input just in order to check for exceptions, if it is able to evaluate its condition without doing so. <h4>Conventions for handling exceptions</h4> <p>(N.B. This section is only really of interest when implementing assertion methods that call {@link Correspondence#compare}, not to users making such assertions in their tests.) <p>The only requirement on an assertion is that, if it encounters an exception from this method, it must not pass. The simplest implementation choice is simply to allow the exception to propagate. However, it is normally more helpful to catch the exception and instead fail with a message which includes more information about the assertion in progress and the nature of the failure. <p>By convention, an assertion may catch and store the exception and continue evaluating the condition as if the method had returned false instead of throwing. If the assertion's condition does not hold with this alternative behaviour, it may choose to fail with a message that gives details about how the condition does not hold, additionally mentioning that assertions were encountered and giving details about one of the stored exceptions. (See the first example below.) If the assertion's condition does hold with this alternative behaviour, the requirement that the assertion must not pass still applies, so it should fail with a message giving details about one of the stored exceptions. (See the second and third examples below.) <p>This behaviour is only a convention and should only be implemented when it makes sense to do so. In particular, in an assertion that has multiple stages, it may be better to only continue evaluation to the end of the current stage, and fail citing a stored exception at the end of the stage, rather than accumulating exceptions through the multiple stages. <h4>Examples of exception handling</h4> <p>Suppose that we have the correspondence <pre> {@code static final Correspondence<String, String> CASE_INSENSITIVE_EQUALITY = Correspondence.from(String::equalsIgnoreCase, \"equals ignoring case\"}}</pre> whose {@code compare} method throws {@link NullPointerException} if the actual value is null.The assertion <pre> {@code assertThat(asList(null, \"xyz\", \"abc\", \"def\")) .comparingElementsUsing(CASE_INSENSITIVE_EQUALITY) .containsExactly(\"ABC\", \"DEF\", \"GHI\", \"JKL\");}</pre> may fail saying that the actual iterable contains unexpected values {@code null} and {@code xyz} and is missing values corresponding to {@code GHI} and {@code JKL}, which is what it would do if the {@code compare} method returned false instead of throwing, and additionally mentionthe exception. (This is more helpful than allowing the {@link NullPointerException} topropagate to the caller, or than failing with only a description of the exception.) <p>However, the assertions <pre> {@code assertThat(asList(null, \"xyz\", \"abc\", \"def\")) .comparingElementsUsing(CASE_INSENSITIVE_EQUALITY) .doesNotContain(\"MNO\");}</pre> and <pre> {@code assertThat(asList(null, \"xyz\", \"abc\", \"def\")) .comparingElementsUsing(CASE_INSENSITIVE_EQUALITY) .doesNotContain(null);}</pre> must both fail citing the exception, even though they would pass if the {@code compare} methodreturned false. (Note that, in the latter case at least, it is likely that the test author's intention was <i>not</i> for the test to pass with these values.)\n */\n public abstract boolean compare( A actual, E expected);\nprivate static class StoredException {\n private static final Joiner ARGUMENT_JOINER=Joiner.on(\", \").useForNull(\"null\");\n private final Exception exception;\n private final String methodName;\n private final List<@Nullable Object> methodArguments;\n StoredException( Exception exception, String methodName, List<@Nullable Object> methodArguments);\n /** \n * Returns a String describing the exception stored. This includes a stack trace (except under j2cl, where this is not available). It also has a separator at the end, so that when this appears at the end of an {@code AssertionError} message, the stack trace of the storedexception is distinguishable from the stack trace of the {@code AssertionError}.\n */\n private String describe();\n }\n /** \n * Helper object to store exceptions encountered while executing a {@link Correspondence} method.\n */\nstatic final class ExceptionStore {\n private final String argumentLabel;\n private @Nullable StoredException firstCompareException=null;\n private @Nullable StoredException firstPairingException=null;\n private @Nullable StoredException firstFormatDiffException=null;\n static ExceptionStore forIterable();\n static ExceptionStore forMapValues();\n private ExceptionStore( String argumentLabel);\n /** \n * Adds an exception that was thrown during a {@code compare} call.\n * @param callingClass The class from which the {@code compare} method was called. Whenreporting failures, stack traces will be truncated above elements in this class.\n * @param exception The exception encountered\n * @param actual The {@code actual} argument to the {@code compare} call during which theexception was encountered\n * @param expected The {@code expected} argument to the {@code compare} call during which theexception was encountered\n */\n void addCompareException( Class<?> callingClass, Exception exception, @Nullable Object actual, @Nullable Object expected);\n /** \n * Adds an exception that was thrown during an {@code apply} call on the function used to keyactual elements.\n * @param callingClass The class from which the {@code apply} method was called. When reportingfailures, stack traces will be truncated above elements in this class.\n * @param exception The exception encountered\n * @param actual The {@code actual} argument to the {@code apply} call during which theexception was encountered\n */\n void addActualKeyFunctionException( Class<?> callingClass, Exception exception, @Nullable Object actual);\n /** \n * Adds an exception that was thrown during an {@code apply} call on the function used to keyexpected elements.\n * @param callingClass The class from which the {@code apply} method was called. When reportingfailures, stack traces will be truncated above elements in this class.\n * @param exception The exception encountered\n * @param expected The {@code expected} argument to the {@code apply} call during which theexception was encountered\n */\n void addExpectedKeyFunctionException( Class<?> callingClass, Exception exception, @Nullable Object expected);\n /** \n * Adds an exception that was thrown during a {@code formatDiff} call.\n * @param callingClass The class from which the {@code formatDiff} method was called. Whenreporting failures, stack traces will be truncated above elements in this class.\n * @param exception The exception encountered\n * @param actual The {@code actual} argument to the {@code formatDiff} call during which theexception was encountered\n * @param expected The {@code expected} argument to the {@code formatDiff} call during which theexception was encountered\n */\n void addFormatDiffException( Class<?> callingClass, Exception exception, @Nullable Object actual, @Nullable Object expected);\n /** \n * Returns whether any exceptions thrown during {@code compare} calls were stored. \n */\n boolean hasCompareException();\n /** \n * Returns facts to use in a failure message when the exceptions from {@code compare} calls arethe main cause of the failure. At least one exception thrown during a {@code compare} callmust have been stored, and no exceptions from a {@code formatDiff} call. Assertions shoulduse this when exceptions were thrown while comparing elements and no more meaningful failure was discovered by assuming a false return and continuing (see the javadoc for {@link Correspondence#compare}). C.f. {@link #describeAsAdditionalInfo}.\n */\n ImmutableList<Fact> describeAsMainCause();\n /** \n * If any exceptions are stored, returns facts to use in a failure message when the exceptions should be noted as additional info; if empty, returns an empty list. Assertions should use this when exceptions were thrown while comparing elements but more meaningful failures were discovered by assuming a false return and continuing (see the javadoc for {@link Correspondence#compare}), or when exceptions were thrown by other methods while generating the failure message. C.f. {@link #describeAsMainCause}.\n */\n ImmutableList<Fact> describeAsAdditionalInfo();\n private static void truncateStackTrace( Exception exception, Class<?> callingClass);\n }\n /** \n * Invokes {@link #compare}, catching any exceptions. If the comparison does not throw, returns the result. If it does throw, adds the exception to the given {@link ExceptionStore} andreturns false. This method can help with implementing the exception-handling policy described above, but note that assertions using it <i>must</i> fail later if an exception was stored.\n */\n final boolean safeCompare( A actual, E expected, ExceptionStore exceptions);\n /** \n * Returns a {@link String} describing the difference between the {@code actual} and {@code expected} values, if possible, or {@code null} if not.<p>The implementation on the {@link Correspondence} base class always returns {@code null}. To enable diffing, use {@link #formattingDiffsUsing} (or override this method in a subclass, butfactory methods are recommended over subclassing). <p>Assertions should only invoke this with parameters for which {@link #compare} returns {@code false}. <p>If this throws an exception, that implies that it is not possible to describe the diffs. An assertion will normally only call this method if it has established that its condition does not hold: good practice dictates that, if this method throws, the assertion should catch the exception and continue to describe the original failure as if this method had returned null, mentioning the failure from this method as additional information.\n */\n public @Nullable String formatDiff( A actual, E expected);\n /** \n * Invokes {@link #formatDiff}, catching any exceptions. If the comparison does not throw, returns the result. If it does throw, adds the exception to the given {@link ExceptionStore} andreturns null.\n */\n final @Nullable String safeFormatDiff( A actual, E expected, ExceptionStore exceptions);\n /** \n * Returns a description of the correspondence, suitable to fill the gap in a failure message of the form {@code \"<some actual element> is an element that ... <some expected element>\"}. Note that this is a fragment of a verb phrase which takes a singular subject. <p>Example 1: For a {@code Correspondence<String, Integer>} that tests whether the actualstring parses to the expected integer, this would return {@code \"parses to\"} to result in afailure message of the form {@code \"<some actual string> is an element that parses to <someexpected integer>\"}. <p>Example 2: For the {@code Correspondence<Number, Number>} returns by {@link #tolerance} thisreturns {@code \"is a finite number within \" + tolerance + \" of\"} to result in a failure messageof the form {@code \"<some actual number> is an element that is a finite number within 0.0001 of<some expected number>\"}.\n */\n @Override public abstract String toString();\n /** \n * Returns whether this is an equality correspondence, i.e. one returned by {@link #equality} orone whose {@link #compare} delegates to one returned by {@link #equality}.\n */\n boolean isEquality();\n /** \n * Returns a list of {@link Fact} instance describing how this correspondence compares elements ofan iterable. There will be one \"testing whether\" fact, unless this {@link #isEquality is anequality correspondence}, in which case the list will be empty.\n */\n final ImmutableList<Fact> describeForIterable();\n /** \n * Returns a list of {@link Fact} instance describing how this correspondence compares values in amap (or multimap). There will be one \"testing whether\" fact, unless this {@link #isEquality isan equality correspondence}, in which case the list will be empty.\n */\n final ImmutableList<Fact> describeForMapValues();\n /** \n * @throws UnsupportedOperationException always\n * @deprecated {@link Object#equals(Object)} is not supported. If you meant to compare objectsusing this {@link Correspondence}, use {@link #compare}.\n */\n @Deprecated @Override public final boolean equals( @Nullable Object o);\n /** \n * @throws UnsupportedOperationException always\n * @deprecated {@link Object#hashCode()} is not supported.\n */\n @Deprecated @Override public final int hashCode();\n}\n", "raw_body_no_cmt": "public abstract class Correspondence<A extends Object,E extends Object> {\n public static <A extends Object,E extends Object>Correspondence<A,E> from( BinaryPredicate<A,E> predicate, String description);\n public interface BinaryPredicate<A extends Object,E extends Object> {\n boolean apply( A actual, E expected);\n }\nprivate static final class FromBinaryPredicate<A extends Object,E extends Object> extends Correspondence<A,E> {\n private final BinaryPredicate<A,E> predicate;\n private final String description;\n private FromBinaryPredicate( BinaryPredicate<A,E> correspondencePredicate, String description);\n public boolean compare( A actual, E expected);\n public String toString();\n }\n public static <A extends Object,E extends Object>Correspondence<A,E> transforming( Function<A,? extends E> actualTransform, String description);\n public static <A extends Object,E extends Object>Correspondence<A,E> transforming( Function<A,?> actualTransform, Function<E,?> expectedTransform, String description);\nprivate static final class Transforming<A extends Object,E extends Object> extends Correspondence<A,E> {\n private final Function<? super A,?> actualTransform;\n private final Function<? super E,?> expectedTransform;\n private final String description;\n private Transforming( Function<? super A,?> actualTransform, Function<? super E,?> expectedTransform, String description);\n public boolean compare( A actual, E expected);\n public String toString();\n }\n public static Correspondence<Number,Number> tolerance( double tolerance);\nprivate static final class TolerantNumericEquality extends Correspondence<Number,Number> {\n private final double tolerance;\n private TolerantNumericEquality( double tolerance);\n public boolean compare( Number actual, Number expected);\n public String toString();\n }\n static <T>Correspondence<T,T> equality();\nprivate static final class Equality<T> extends Correspondence<T,T> {\n private static final Equality<Object> INSTANCE=new Equality<>();\n public boolean compare( T actual, T expected);\n public String toString();\n boolean isEquality();\n }\n Correspondence();\n public Correspondence<A,E> formattingDiffsUsing( DiffFormatter<? super A,? super E> formatter);\n public interface DiffFormatter<A extends Object,E extends Object> {\n String formatDiff( A actual, E expected);\n }\nprivate static class FormattingDiffs<A extends Object,E extends Object> extends Correspondence<A,E> {\n private final Correspondence<A,E> delegate;\n private final DiffFormatter<? super A,? super E> formatter;\n FormattingDiffs( Correspondence<A,E> delegate, DiffFormatter<? super A,? super E> formatter);\n public boolean compare( A actual, E expected);\n public String formatDiff( A actual, E expected);\n public String toString();\n boolean isEquality();\n }\n public abstract boolean compare( A actual, E expected);\nprivate static class StoredException {\n private static final Joiner ARGUMENT_JOINER=Joiner.on(\", \").useForNull(\"null\");\n private final Exception exception;\n private final String methodName;\n private final List<Object> methodArguments;\n StoredException( Exception exception, String methodName, List<Object> methodArguments);\n private String describe();\n }\n static final class ExceptionStore {\n private final String argumentLabel;\n private StoredException firstCompareException=null;\n private StoredException firstPairingException=null;\n private StoredException firstFormatDiffException=null;\n static ExceptionStore forIterable();\n static ExceptionStore forMapValues();\n private ExceptionStore( String argumentLabel);\n void addCompareException( Class<?> callingClass, Exception exception, Object actual, Object expected);\n void addActualKeyFunctionException( Class<?> callingClass, Exception exception, Object actual);\n void addExpectedKeyFunctionException( Class<?> callingClass, Exception exception, Object expected);\n void addFormatDiffException( Class<?> callingClass, Exception exception, Object actual, Object expected);\n boolean hasCompareException();\n ImmutableList<Fact> describeAsMainCause();\n ImmutableList<Fact> describeAsAdditionalInfo();\n private static void truncateStackTrace( Exception exception, Class<?> callingClass);\n }\n final boolean safeCompare( A actual, E expected, ExceptionStore exceptions);\n public String formatDiff( A actual, E expected);\n final String safeFormatDiff( A actual, E expected, ExceptionStore exceptions);\n public abstract String toString();\n boolean isEquality();\n final ImmutableList<Fact> describeForIterable();\n final ImmutableList<Fact> describeForMapValues();\n public final boolean equals( Object o);\n public final int hashCode();\n}\n"}}] | [{"isEmpty": {"retrieved_name": "isEmpty", "raw_body": "/** \n * Fails if the array is not empty (i.e. {@code array.length > 0}). \n */\npublic final void isEmpty(){\n if (length() > 0) {\n failWithActual(simpleFact(\"expected to be empty\"));\n }\n}\n"}}, {"unknownFields": {"retrieved_name": "unknownFields", "raw_body": "@Override Optional<DiffResult.UnknownFieldSetDiff> unknownFields(){\n return unknownFields;\n}\n"}}] | [{"fromMessage": {"retrieved_name": "withMessage", "raw_body": "/** \n * Returns a new instance whose failures will contain the given message. The way for Truth users to set a message is {@code check(...).withMessage(...).that(...)} (for calls from within a{@code Subject}) or {@link Truth#assertWithMessage} (for most other calls).\n */\nFailureMetadata withMessage(String format,@Nullable Object[] args){\n ImmutableList<LazyMessage> messages=append(this.messages,new LazyMessage(format,args));\n return derive(messages,steps);\n}\n"}}] |
|
jitsi_jitsi | jitsi/modules/impl/gui/src/main/java/net/java/sip/communicator/impl/gui/main/chat/menus/ChatRightButtonMenu.java | ChatRightButtonMenu | dispose | class ChatRightButtonMenu
extends SIPCommPopupMenu
implements ActionListener,
Skinnable
{
private ChatConversationPanel chatConvPanel;
private JMenuItem copyMenuItem = new JMenuItem(
GuiActivator.getResources().getI18NString("service.gui.COPY"),
new ImageIcon(ImageLoader.getImage(ImageLoader.COPY_ICON)));
private JMenuItem closeMenuItem = new JMenuItem(
GuiActivator.getResources().getI18NString("service.gui.CLOSE"),
new ImageIcon(ImageLoader.getImage(ImageLoader.CLOSE_ICON)));
/**
* Creates an instance of <tt>ChatRightButtonMenu</tt>.
*
* @param chatConvPanel The conversation panel, where this menu will apear.
*/
public ChatRightButtonMenu(ChatConversationPanel chatConvPanel)
{
super();
this.chatConvPanel = chatConvPanel;
this.init();
}
/**
* Initializes the menu with all menu items.
*/
private void init()
{
this.add(copyMenuItem);
this.addSeparator();
this.add(closeMenuItem);
this.copyMenuItem.setName("copy");
this.closeMenuItem.setName("service.gui.CLOSE");
this.copyMenuItem.addActionListener(this);
this.closeMenuItem.addActionListener(this);
this.copyMenuItem.setMnemonic(
GuiActivator.getResources().getI18nMnemonic("service.gui.COPY"));
this.closeMenuItem.setMnemonic(
GuiActivator.getResources().getI18nMnemonic("service.gui.CLOSE"));
this.copyMenuItem.setAccelerator(
KeyStroke.getKeyStroke(KeyEvent.VK_C,
KeyEvent.CTRL_MASK));
}
/**
* Disables the copy item.
*/
public void disableCopy() {
this.copyMenuItem.setEnabled(false);
}
/**
* Enables the copy item.
*/
public void enableCopy() {
this.copyMenuItem.setEnabled(true);
}
/**
* Handles the <tt>ActionEvent</tt> when one of the menu items is selected.
*
* @param e the <tt>ActionEvent</tt> that notified us
*/
public void actionPerformed(ActionEvent e)
{
JMenuItem menuItem = (JMenuItem) e.getSource();
String itemText = menuItem.getName();
if (itemText.equalsIgnoreCase("copy"))
{
this.chatConvPanel.copyConversation();
}
else if (itemText.equalsIgnoreCase("save"))
{
//TODO: Implement save to file.
}
else if (itemText.equalsIgnoreCase("print"))
{
//TODO: Implement print.
}
else if (itemText.equalsIgnoreCase("service.gui.CLOSE"))
{
Window window = this.chatConvPanel
.getChatContainer().getConversationContainerWindow();
window.setVisible(false);
window.dispose();
}
}
/**
* Reloads menu icons.
*/
public void loadSkin()
{
copyMenuItem.setIcon(new ImageIcon(
ImageLoader.getImage(ImageLoader.COPY_ICON)));
closeMenuItem.setIcon(new ImageIcon(
ImageLoader.getImage(ImageLoader.CLOSE_ICON)));
}
/**
* Clear resources.
*/
public void dispose()
{<FILL_FUNCTION_BODY>}
} |
this.chatConvPanel = null;
copyMenuItem = null;
closeMenuItem = null;
| /**
* A custom popup menu that detects parent focus lost.
* @author Yana Stamcheva
*/
public class SIPCommPopupMenu extends JPopupMenu {
/**
* Serial version UID.
*/
private static final long serialVersionUID=0L;
/**
* Constructor.
*/
public SIPCommPopupMenu();
}
|
this.copyMenuItem = null;
this.closeMenuItem = null;
this.chatConvPanel = null;
| [
"ChatConversationPanel",
"JMenuItem"
] | [] | [
"ChatConversationPanel",
"JMenuItem"
] | [] | {
"methods": [],
"similar_methods": [
"dispose"
],
"types": [
"ChatConversationPanel",
"JMenuItem"
]
} | /**
* The <tt>ChatConversationPanel</tt> is the panel, where all sent and received messages appear. All data is stored in an HTML document. An external CSS file is applied to the document to provide the look&feel. All smileys and link strings are processed and finally replaced by corresponding images and HTML links.
* @author Yana Stamcheva
* @author Lyubomir Marinov
* @author Adam Netocny
* @author Danny van Heumen
*/
public class ChatConversationPanel extends SIPCommScrollPane implements HyperlinkListener, MouseListener, ClipboardOwner, Skinnable {
/**
* The <tt>Logger</tt> used by the <tt>ChatConversationPanel</tt> class and its instances for logging output.
*/
private static final org.slf4j.Logger logger=org.slf4j.LoggerFactory.getLogger(ChatConversationPanel.class);
/**
* The regular expression (in the form of compiled <tt>Pattern</tt>) which matches URLs for the purposed of turning them into links. TODO Current pattern misses tailing '/' (slash) that is sometimes included in URL's. (Danny) TODO Current implementation misses # after ? has been encountered in URL. (Danny)
*/
private static final Pattern URL_PATTERN=Pattern.compile("(" + "(\\bwww\\.[^\\s<>\"]+\\.[^\\s<>\"]+/*[?#]*(\\w+[&=;?]\\w+)*\\b)" + "|"+ "(\\bjitsi\\:[^\\s<>\"]+\\.[^\\s<>\"]*\\b)"+ "|"+ "(\\b\\w+://[^\\s<>\"]+/*[?#]*(\\w+[&=;?]\\w+)*\\b)"+ ")");
/**
* A regular expression that matches a <div> tag and its contents. The opening tag is group 1, and the tag contents is group 2 when a match is found.
*/
private static final Pattern DIV_PATTERN=Pattern.compile("(<div[^>]*>)(.*)(</div>)",Pattern.DOTALL);
/**
* A regular expression for searching all pieces of plain text within a blob of HTML text. <i>This expression assumes that the plain text part is correctly escaped, such that there is no occurrence of the symbols < and >.</i> <pre> In essence this regexp pattern works as follows: 1. Find all the text that isn't the start of a tag. (so all chars != '<') -> This is your actual result: textual content that is not part of a tag. 2. Then, if you find a '<', find as much chars as you can until you find '>' (if it is possible at all to find a closing '>') In depth explanation of 2.: The text between tags consists mainly of 2 parts: A) a piece of text B) some value "between quotes" So everything up to the "quote" is part of a piece of text (A). Then if we encounter a "quote" we consider the rest of the text part of the value (B) until the value section is closed with a closing "quote". (We tend to be rather greedy, so we even swallow '>' along the way looking for the closing "quote".) This subpattern is allowed any number of times, until eventually the closing '>' is encountered. (Or not if the pattern is incomplete.) 3. And consider that 2. is optional, since it could also be that we only find plain text, which would all be captured by 1. </pre> <p>The first group matches any piece of text outside of the < and > brackets that define the start and end of HTML tags.</p>
*/
static final Pattern TEXT_TO_REPLACE_PATTERN=Pattern.compile("([^<]*+)(?:<(?:[^>\"]*(?:\"[^\"]*+\"?)*)*+>?)?",Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
/**
* List for observing text messages.
*/
private Set<ChatLinkClickedListener> chatLinkClickedListeners=new HashSet<ChatLinkClickedListener>();
/**
* The component rendering chat conversation panel text.
*/
private final JTextPane chatTextPane=new MyTextPane();
/**
* The editor kit used by the text component.
*/
private final ChatConversationEditorKit editorKit;
/**
* The document used by the text component.
*/
HTMLDocument document;
/**
* The parent container.
*/
private final ChatConversationContainer chatContainer;
/**
* The menu shown on right button mouse click.
*/
private ChatRightButtonMenu rightButtonMenu;
/**
* The currently shown href.
*/
private String currentHref;
/**
* The currently shown href, is it an img element.
*/
private boolean isCurrentHrefImg=false;
/**
* The copy link item, contained in the right mouse click menu.
*/
private final JMenuItem copyLinkItem;
/**
* The copy link item, contained in the right mouse click menu.
*/
private final JMenuItem configureReplacementItem;
/**
* The configure replacement item separator.
*/
private final JSeparator configureReplacementSeparator=new JSeparator();
/**
* The open link item, contained in the right mouse click menu.
*/
private final JMenuItem openLinkItem;
/**
* The right mouse click menu separator.
*/
private final JSeparator copyLinkSeparator=new JSeparator();
/**
* The timestamp of the last incoming message.
*/
private Date lastIncomingMsgTimestamp=new Date(0);
/**
* The timestamp of the last message.
*/
private Date lastMessageTimestamp=new Date(0);
/**
* Indicates if this component is rendering a history conversation.
*/
private final boolean isHistory;
/**
* The indicator which determines whether an automatic scroll to the bottom of {@link #chatTextPane} is to be performed.
*/
private boolean scrollToBottomIsPending=false;
private String lastMessageUID=null;
private boolean isSimpleTheme=true;
private ShowPreviewDialog showPreview=new ShowPreviewDialog(ChatConversationPanel.this);
/**
* The implementation of the routine which scrolls {@link #chatTextPane} toits bottom.
*/
private final Runnable scrollToBottomRunnable=new Runnable(){
public void run();
}
;
/**
* Creates an instance of <tt>ChatConversationPanel</tt>.
* @param chatContainer The parent <tt>ChatConversationContainer</tt>.
*/
public ChatConversationPanel( ChatConversationContainer chatContainer);
/**
* Overrides Component#setBounds(int, int, int, int) in order to determine whether an automatic scroll of #chatTextPane to its bottom will be necessary at a later time in order to keep its vertical scroll bar to its bottom after the realization of the resize if it is at its bottom before the resize.
*/
@Override public void setBounds( int x, int y, int width, int height);
/**
* Retrieves the contents of the sent message with the given ID.
* @param messageUID The ID of the message to retrieve.
* @return The contents of the message, or null if the message is not found.
*/
public String getMessageContents( String messageUID);
/**
* Processes the message given by the parameters.
* @param chatMessage the message
* @param keyword a substring of <tt>chatMessage</tt> to be highlighted upondisplay of <tt>chatMessage</tt> in the UI
* @return the processed message
*/
public String processMessage( ChatMessage chatMessage, String keyword, ProtocolProviderService protocolProvider, String contactAddress);
/**
* Processes the message given by the parameters.
* @param chatMessage the message.
* @return the formatted message
*/
public String processMessage( ChatMessage chatMessage, ProtocolProviderService protocolProvider, String contactAddress);
/**
* Appends a consecutive message to the document.
* @param chatMessage the message to append
* @param keyword the keywords to highlight
*/
public void appendConsecutiveMessage( final ChatMessage chatMessage, final String keyword);
/**
* Replaces the contents of the message with ID of the corrected message specified in chatMessage, with this message.
* @param chatMessage A <tt>ChatMessage</tt> that contains all the requiredinformation to correct the old message.
*/
public void correctMessage( final ChatMessage chatMessage);
/**
* Appends the given string at the end of the contained in this panel document. Note: Currently, it looks like appendMessageToEnd is only called for messages that are already converted to HTML. So It is quite possible that we can remove the content type without any issues.
* @param original the message string to append
* @param contentType the message's content type
*/
public void appendMessageToEnd( final String original, final String contentType);
/**
* Performs all operations needed in order to finish the adding of the message to the document.
* @param message the message string
*/
private void finishMessageAdd( final String message);
/**
* Formats the given message. Processes the messages and replaces links to video/image sources with their previews or any other substitution. Spawns a separate thread for replacement.
* @param messageID the messageID element.
* @param chatString the message.
*/
void processReplacement( final String messageID, final String chatString);
/**
* Ensures that the document won't become too big. When the document reaches a certain size the first message in the page is removed.
*/
private void ensureDocumentSize();
/**
* Deletes all messages "div"s that are missing their header the table tag. The method calls itself recursively.
*/
private void deleteAllMessagesWithoutHeader();
/**
* Formats the given message. Processes all smiley chars, new lines and links. This method expects <u>only</u> the message's <u>body</u> to be provided.
* @param contentType the content type of the message to be formatted
* @param keyword the word to be highlighted
* @return the formatted message
*/
private String formatMessageAsHTML( final String original, final String contentType, final String keyword);
/**
* Process provided replacers one by one sequentially. The output of the first replacer is then fed as input into the second replacer, and so on. <p> {@link Replacer}s that expect HTML content ( {@link Replacer#expectsPlainText()}) will typically receive the complete message as an argument. {@linkplain Replacer}s that expect plain text content will typically receive small pieces that are found in between HTML tags. The pieces of plain text content cannot be predicted as results change when they are processed by other replacers. </p>
* @param content the original content to process
* @param replacers the replacers to call
* @return returns the final result message content after it has beenprocessed by all replacers
*/
private String processReplacers( final String content, final Replacer... replacers);
/**
* Opens a link in the default browser when clicked and shows link url in a popup on mouseover.
* @param e The HyperlinkEvent.
*/
public void hyperlinkUpdate( HyperlinkEvent e);
/**
* Returns the text pane of this conversation panel.
* @return The text pane of this conversation panel.
*/
public JTextPane getChatTextPane();
/**
* Returns the time of the last received message.
* @return The time of the last received message.
*/
public Date getLastIncomingMsgTimestamp();
/**
* When a right button click is performed in the editor pane, a popup menu is opened. In case of the Scheme being internal, it won't open the Browser but instead it will trigger the forwarded action.
* @param e The MouseEvent.
*/
public void mouseClicked( MouseEvent e);
/**
* Opens this panel context menu at the given point.
* @param p the point where to position the left-top cornet of the contextmenu
*/
private void openContextMenu( Point p);
public void mousePressed( MouseEvent e);
public void mouseReleased( MouseEvent e);
public void mouseEntered( MouseEvent e);
public void mouseExited( MouseEvent e);
public void lostOwnership( Clipboard clipboard, Transferable contents);
/**
* Returns the chat container.
* @return the chat container
*/
public ChatConversationContainer getChatContainer();
/**
* Copies the selected conversation panel content to the clipboard.
*/
public void copyConversation();
/**
* Creates new document and all the messages that will be processed in the future will be appended in it.
*/
public void clear();
/**
* Sets the given document to the editor pane in this panel.
* @param document the document to set
*/
public void setContent( final HTMLDocument document);
/**
* Sets the default document contained in this panel, created on init or when clear is invoked.
*/
public void setDefaultContent();
/**
* Returns the document contained in this panel.
* @return the document contained in this panel
*/
public HTMLDocument getContent();
/**
* Returns the right button popup menu.
* @return the right button popup menu
*/
public ChatRightButtonMenu getRightButtonMenu();
/**
* Returns the date of the first message in the current page.
* @return the date of the first message in the current page
*/
public Date getPageFirstMsgTimestamp();
/**
* Returns the date of the last message in the current page.
* @return the date of the last message in the current page
*/
public Date getPageLastMsgTimestamp();
/**
* Extend Editor pane to add URL tooltips.
*/
private class MyTextPane extends JTextPane {
/**
* Returns the string to be used as the tooltip for <i>event</i>.
* @param event the <tt>MouseEvent</tt>
* @return the string to be used as the tooltip for <i>event</i>.
*/
@Override public String getToolTipText( MouseEvent event);
}
/**
* Adds a custom component at the end of the conversation.
* @param component the component to add at the end of the conversation.
*/
public void addComponent( ChatConversationComponent component);
/**
* Registers a new link click listener.
* @param listener the object that should be notified when an internallink was clicked.
*/
public void addChatLinkClickedListener( ChatLinkClickedListener listener);
/**
* Remove a registered link click listener.
* @param listener a registered click listener to remove
*/
public void removeChatLinkClickedListener( ChatLinkClickedListener listener);
/**
* Reloads images.
*/
@Override public void loadSkin();
/**
* Processes /me command in group chats.
* @param chatMessage the chat message
* @return the newly processed message string
*/
public String processMeCommand( ChatMessage chatMessage);
/**
* Returns the avatar corresponding to the account of the given <tt>protocolProvider</tt>.
* @param protocolProvider the protocol provider service, which accountavatar we're looking for
* @return the avatar corresponding to the account of the given<tt>protocolProvider</tt>
*/
private static String getContactAvatar( ProtocolProviderService protocolProvider, String contactAddress);
/**
* Returns the avatar corresponding to the account of the given <tt>protocolProvider</tt>.
* @param protocolProvider the protocol provider service, which accountavatar we're looking for
* @return the avatar corresponding to the account of the given<tt>protocolProvider</tt>
*/
private static String getContactAvatar( ProtocolProviderService protocolProvider);
/**
* Indicates if this is a consecutive message.
* @param chatMessage the message to verify
* @return <tt>true</tt> if the given message is a consecutive message,<tt>false</tt> - otherwise
*/
private boolean isConsecutiveMessage( ChatMessage chatMessage);
/**
* Releases the resources allocated by this instance throughout its lifetime and prepares it for garbage collection.
*/
@Override public void dispose();
/**
* @param attribute
* @param matchStrings
* @return
*/
private Element findElement( HTML.Attribute attribute, String[] matchStrings);
/**
* Finds the first element with <tt>name</tt>.
* @param name the name to search for.
* @return the first element with <tt>name</tt>.
*/
private Element findFirstElement( String name);
/**
* @param element
* @param attrName
* @param matchStrings
* @return
*/
private Element findFirstElement( Element element, HTML.Attribute attrName, String[] matchStrings);
/**
* Finds the first element with <tt>name</tt> among the child elements of <tt>element</tt>.
* @param element the element to searh for.
* @param name the name to search for.
* @return the first element with <tt>name</tt>.
*/
private Element findFirstElement( Element element, String name);
/**
* @param elementId
* @param message
* @return
*/
private String getElementContent( String elementId, String message);
/**
* Returns the first available advanced configuration form.
* @return the first available advanced configuration form
*/
public static ConfigurationForm getChatConfigForm();
/**
* Extends SIPCommHTMLEditorKit to keeps track of created ImageView for the gif images in order to flush them whenever they are no longer visible
*/
private class ChatConversationEditorKit extends SIPCommHTMLEditorKit implements DocumentListener {
/**
* List of the image views.
*/
private java.util.List<ImageView> imageViews=new ArrayList<ImageView>();
/**
* Constructs.
* @param container
*/
public ChatConversationEditorKit( JComponent container);
/**
* Clears any left img view and removes any listener was added.
*/
public void dispose();
/**
* Inform view creation.
* @param view the newly created view.
*/
protected void viewCreated( ViewFactory factory, View view);
/**
* Not used.
* @param e
*/
@Override public void insertUpdate( DocumentEvent e);
/**
* When something is removed from the current document we will check the stored image views for any element which si no longer visible.
* @param e the event.
*/
@Override public void removeUpdate( DocumentEvent e);
/**
* Not used.
* @param e
*/
@Override public void changedUpdate( DocumentEvent e);
/**
* For debugging purposes, prints the content of the document in the console.
*/
public void debug();
}
/**
* Swing worker used by processReplacement.
*/
private final class ReplacementWorker extends SwingWorker {
/**
* The messageID element.
*/
private final String messageID;
/**
* The message.
*/
private final String chatString;
/**
* Counts links while processing. Used to generate unique href.
*/
private int linkCounter=0;
/**
* Is image replacement enabled.
*/
private final boolean isEnabled;
/**
* Is replacement proposal enabled.
*/
private final boolean isProposalEnabled;
/**
* Constructs worker.
* @param messageID the messageID element.
* @param chatString the messages.
*/
private ReplacementWorker( final String messageID, final String chatString);
/**
* Called on the event dispatching thread (not on the worker thread) after the <code>construct</code> method has returned.
*/
@Override public void finished();
@Override public Object construct() throws Exception;
/**
* Process message for a ReplacementService.
* @param service the service.
* @param msg the message.
* @param buff current accumulated buffer.
*/
private void processReplacementService( final ReplacementService service, final String msg, final StringBuilder buff);
/**
* Process plain text content.
* @param plainText the nodes text.
* @param msgBuff the currently accumulated buffer.
* @param pattern the pattern for current replacement service, createdearlier so we don't create it for every text we check.
* @param rService the replacement service.
* @param isURL whether this content matches the URL pattern
*/
private void processText( final String plainText, final StringBuilder msgBuff, final Pattern pattern, final ReplacementService rService, final boolean isURL);
}
}
/**
* @author Adam Goldstein
*/
public class ContactInfoMenuItem extends AbstractPluginComponent implements ActionListener {
private AbstractButton menuItem=null;
private MetaContact metaContact;
/**
* The button index, for now placed on last position.
*/
private final static int CONTACT_INFO_BUTTON_IX=50;
/**
* Creates a <tt>ContactInfoMenuItem</tt>.
*/
public ContactInfoMenuItem( PluginComponentFactory parentFactory);
/**
* Creates a <tt>ContactInfoMenuItem</tt>.
*/
public ContactInfoMenuItem( Container container, PluginComponentFactory parentFactory);
/**
* Sets the currently selected <tt>MetaContact</tt>.
* @param metaContact the currently selected meta contact
*/
@Override public void setCurrentContact( MetaContact metaContact);
@Override public void setCurrentContact( Contact contact);
/**
* Initializes and shows the contact details dialog.
*/
public void actionPerformed( ActionEvent e);
public Object getComponent();
public String getName();
private AbstractButton getMenuItem();
}
/**
* Remove the newAccountDialog on dispose.
*/
@Override public void dispose(){
if (isCurrentlySigningIn) return;
if (newAccountDialog == this) newAccountDialog=null;
wizardContainer.getModel().removePropertyChangeListener(this);
super.dispose();
}
| public class ChatConversationPanel extends SIPCommScrollPane implements HyperlinkListener, MouseListener, ClipboardOwner, Skinnable {
private static final org.slf4j.Logger logger=org.slf4j.LoggerFactory.getLogger(ChatConversationPanel.class);
private static final Pattern URL_PATTERN=Pattern.compile("(" + "(\\bwww\\.[^\\s<>\"]+\\.[^\\s<>\"]+/*[?#]*(\\w+[&=;?]\\w+)*\\b)" + "|"+ "(\\bjitsi\\:[^\\s<>\"]+\\.[^\\s<>\"]*\\b)"+ "|"+ "(\\b\\w+://[^\\s<>\"]+/*[?#]*(\\w+[&=;?]\\w+)*\\b)"+ ")");
private static final Pattern DIV_PATTERN=Pattern.compile("(<div[^>]*>)(.*)(</div>)",Pattern.DOTALL);
static final Pattern TEXT_TO_REPLACE_PATTERN=Pattern.compile("([^<]*+)(?:<(?:[^>\"]*(?:\"[^\"]*+\"?)*)*+>?)?",Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
private Set<ChatLinkClickedListener> chatLinkClickedListeners=new HashSet<ChatLinkClickedListener>();
private final JTextPane chatTextPane=new MyTextPane();
private final ChatConversationEditorKit editorKit;
HTMLDocument document;
private final ChatConversationContainer chatContainer;
private ChatRightButtonMenu rightButtonMenu;
private String currentHref;
private boolean isCurrentHrefImg=false;
private final JMenuItem copyLinkItem;
private final JMenuItem configureReplacementItem;
private final JSeparator configureReplacementSeparator=new JSeparator();
private final JMenuItem openLinkItem;
private final JSeparator copyLinkSeparator=new JSeparator();
private Date lastIncomingMsgTimestamp=new Date(0);
private Date lastMessageTimestamp=new Date(0);
private final boolean isHistory;
private boolean scrollToBottomIsPending=false;
private String lastMessageUID=null;
private boolean isSimpleTheme=true;
private ShowPreviewDialog showPreview=new ShowPreviewDialog(ChatConversationPanel.this);
private final Runnable scrollToBottomRunnable=new Runnable(){
public void run();
}
;
public ChatConversationPanel( ChatConversationContainer chatContainer);
public void setBounds( int x, int y, int width, int height);
public String getMessageContents( String messageUID);
public String processMessage( ChatMessage chatMessage, String keyword, ProtocolProviderService protocolProvider, String contactAddress);
public String processMessage( ChatMessage chatMessage, ProtocolProviderService protocolProvider, String contactAddress);
public void appendConsecutiveMessage( final ChatMessage chatMessage, final String keyword);
public void correctMessage( final ChatMessage chatMessage);
public void appendMessageToEnd( final String original, final String contentType);
private void finishMessageAdd( final String message);
void processReplacement( final String messageID, final String chatString);
private void ensureDocumentSize();
private void deleteAllMessagesWithoutHeader();
private String formatMessageAsHTML( final String original, final String contentType, final String keyword);
private String processReplacers( final String content, final Replacer... replacers);
public void hyperlinkUpdate( HyperlinkEvent e);
public JTextPane getChatTextPane();
public Date getLastIncomingMsgTimestamp();
public void mouseClicked( MouseEvent e);
private void openContextMenu( Point p);
public void mousePressed( MouseEvent e);
public void mouseReleased( MouseEvent e);
public void mouseEntered( MouseEvent e);
public void mouseExited( MouseEvent e);
public void lostOwnership( Clipboard clipboard, Transferable contents);
public ChatConversationContainer getChatContainer();
public void copyConversation();
public void clear();
public void setContent( final HTMLDocument document);
public void setDefaultContent();
public HTMLDocument getContent();
public ChatRightButtonMenu getRightButtonMenu();
public Date getPageFirstMsgTimestamp();
public Date getPageLastMsgTimestamp();
private class MyTextPane extends JTextPane {
public String getToolTipText( MouseEvent event);
}
public void addComponent( ChatConversationComponent component);
public void addChatLinkClickedListener( ChatLinkClickedListener listener);
public void removeChatLinkClickedListener( ChatLinkClickedListener listener);
public void loadSkin();
public String processMeCommand( ChatMessage chatMessage);
private static String getContactAvatar( ProtocolProviderService protocolProvider, String contactAddress);
private static String getContactAvatar( ProtocolProviderService protocolProvider);
private boolean isConsecutiveMessage( ChatMessage chatMessage);
public void dispose();
private Element findElement( HTML.Attribute attribute, String[] matchStrings);
private Element findFirstElement( String name);
private Element findFirstElement( Element element, HTML.Attribute attrName, String[] matchStrings);
private Element findFirstElement( Element element, String name);
private String getElementContent( String elementId, String message);
public static ConfigurationForm getChatConfigForm();
private class ChatConversationEditorKit extends SIPCommHTMLEditorKit implements DocumentListener {
private java.util.List<ImageView> imageViews=new ArrayList<ImageView>();
public ChatConversationEditorKit( JComponent container);
public void dispose();
protected void viewCreated( ViewFactory factory, View view);
public void insertUpdate( DocumentEvent e);
public void removeUpdate( DocumentEvent e);
public void changedUpdate( DocumentEvent e);
public void debug();
}
private final class ReplacementWorker extends SwingWorker {
private final String messageID;
private final String chatString;
private int linkCounter=0;
private final boolean isEnabled;
private final boolean isProposalEnabled;
private ReplacementWorker( final String messageID, final String chatString);
public void finished();
public Object construct() throws Exception;
private void processReplacementService( final ReplacementService service, final String msg, final StringBuilder buff);
private void processText( final String plainText, final StringBuilder msgBuff, final Pattern pattern, final ReplacementService rService, final boolean isURL);
}
}
public class ContactInfoMenuItem extends AbstractPluginComponent implements ActionListener {
private AbstractButton menuItem=null;
private MetaContact metaContact;
private final static int CONTACT_INFO_BUTTON_IX=50;
public ContactInfoMenuItem( PluginComponentFactory parentFactory);
public ContactInfoMenuItem( Container container, PluginComponentFactory parentFactory);
public void setCurrentContact( MetaContact metaContact);
public void setCurrentContact( Contact contact);
public void actionPerformed( ActionEvent e);
public Object getComponent();
public String getName();
private AbstractButton getMenuItem();
}
/**
* Remove the newAccountDialog on dispose.
*/
@Override public void dispose(){
if (isCurrentlySigningIn) return;
if (newAccountDialog == this) newAccountDialog=null;
wizardContainer.getModel().removePropertyChangeListener(this);
super.dispose();
}
| {"types": [{"ChatConversationPanel": "ChatConversationPanel"}, {"JMenuItem": "ContactInfoMenuItem"}], "similar_methods": [{"dispose": "dispose"}]} | [{"ChatConversationPanel": {"retrieved_name": "ChatConversationPanel", "raw_body": "/** \n * The <tt>ChatConversationPanel</tt> is the panel, where all sent and received messages appear. All data is stored in an HTML document. An external CSS file is applied to the document to provide the look&feel. All smileys and link strings are processed and finally replaced by corresponding images and HTML links.\n * @author Yana Stamcheva\n * @author Lyubomir Marinov\n * @author Adam Netocny\n * @author Danny van Heumen\n */\npublic class ChatConversationPanel extends SIPCommScrollPane implements HyperlinkListener, MouseListener, ClipboardOwner, Skinnable {\n /** \n * The <tt>Logger</tt> used by the <tt>ChatConversationPanel</tt> class and its instances for logging output.\n */\n private static final org.slf4j.Logger logger=org.slf4j.LoggerFactory.getLogger(ChatConversationPanel.class);\n /** \n * The regular expression (in the form of compiled <tt>Pattern</tt>) which matches URLs for the purposed of turning them into links. TODO Current pattern misses tailing '/' (slash) that is sometimes included in URL's. (Danny) TODO Current implementation misses # after ? has been encountered in URL. (Danny)\n */\n private static final Pattern URL_PATTERN=Pattern.compile(\"(\" + \"(\\\\bwww\\\\.[^\\\\s<>\\\"]+\\\\.[^\\\\s<>\\\"]+/*[?#]*(\\\\w+[&=;?]\\\\w+)*\\\\b)\" + \"|\"+ \"(\\\\bjitsi\\\\:[^\\\\s<>\\\"]+\\\\.[^\\\\s<>\\\"]*\\\\b)\"+ \"|\"+ \"(\\\\b\\\\w+://[^\\\\s<>\\\"]+/*[?#]*(\\\\w+[&=;?]\\\\w+)*\\\\b)\"+ \")\");\n /** \n * A regular expression that matches a <div> tag and its contents. The opening tag is group 1, and the tag contents is group 2 when a match is found.\n */\n private static final Pattern DIV_PATTERN=Pattern.compile(\"(<div[^>]*>)(.*)(</div>)\",Pattern.DOTALL);\n /** \n * A regular expression for searching all pieces of plain text within a blob of HTML text. <i>This expression assumes that the plain text part is correctly escaped, such that there is no occurrence of the symbols < and >.</i> <pre> In essence this regexp pattern works as follows: 1. Find all the text that isn't the start of a tag. (so all chars != '<') -> This is your actual result: textual content that is not part of a tag. 2. Then, if you find a '<', find as much chars as you can until you find '>' (if it is possible at all to find a closing '>') In depth explanation of 2.: The text between tags consists mainly of 2 parts: A) a piece of text B) some value \"between quotes\" So everything up to the \"quote\" is part of a piece of text (A). Then if we encounter a \"quote\" we consider the rest of the text part of the value (B) until the value section is closed with a closing \"quote\". (We tend to be rather greedy, so we even swallow '>' along the way looking for the closing \"quote\".) This subpattern is allowed any number of times, until eventually the closing '>' is encountered. (Or not if the pattern is incomplete.) 3. And consider that 2. is optional, since it could also be that we only find plain text, which would all be captured by 1. </pre> <p>The first group matches any piece of text outside of the < and > brackets that define the start and end of HTML tags.</p>\n */\n static final Pattern TEXT_TO_REPLACE_PATTERN=Pattern.compile(\"([^<]*+)(?:<(?:[^>\\\"]*(?:\\\"[^\\\"]*+\\\"?)*)*+>?)?\",Pattern.CASE_INSENSITIVE | Pattern.DOTALL);\n /** \n * List for observing text messages.\n */\n private Set<ChatLinkClickedListener> chatLinkClickedListeners=new HashSet<ChatLinkClickedListener>();\n /** \n * The component rendering chat conversation panel text.\n */\n private final JTextPane chatTextPane=new MyTextPane();\n /** \n * The editor kit used by the text component.\n */\n private final ChatConversationEditorKit editorKit;\n /** \n * The document used by the text component.\n */\n HTMLDocument document;\n /** \n * The parent container.\n */\n private final ChatConversationContainer chatContainer;\n /** \n * The menu shown on right button mouse click.\n */\n private ChatRightButtonMenu rightButtonMenu;\n /** \n * The currently shown href.\n */\n private String currentHref;\n /** \n * The currently shown href, is it an img element.\n */\n private boolean isCurrentHrefImg=false;\n /** \n * The copy link item, contained in the right mouse click menu.\n */\n private final JMenuItem copyLinkItem;\n /** \n * The copy link item, contained in the right mouse click menu.\n */\n private final JMenuItem configureReplacementItem;\n /** \n * The configure replacement item separator.\n */\n private final JSeparator configureReplacementSeparator=new JSeparator();\n /** \n * The open link item, contained in the right mouse click menu.\n */\n private final JMenuItem openLinkItem;\n /** \n * The right mouse click menu separator.\n */\n private final JSeparator copyLinkSeparator=new JSeparator();\n /** \n * The timestamp of the last incoming message.\n */\n private Date lastIncomingMsgTimestamp=new Date(0);\n /** \n * The timestamp of the last message.\n */\n private Date lastMessageTimestamp=new Date(0);\n /** \n * Indicates if this component is rendering a history conversation.\n */\n private final boolean isHistory;\n /** \n * The indicator which determines whether an automatic scroll to the bottom of {@link #chatTextPane} is to be performed.\n */\n private boolean scrollToBottomIsPending=false;\n private String lastMessageUID=null;\n private boolean isSimpleTheme=true;\n private ShowPreviewDialog showPreview=new ShowPreviewDialog(ChatConversationPanel.this);\n /** \n * The implementation of the routine which scrolls {@link #chatTextPane} toits bottom.\n */\n private final Runnable scrollToBottomRunnable=new Runnable(){\n public void run();\n }\n;\n /** \n * Creates an instance of <tt>ChatConversationPanel</tt>.\n * @param chatContainer The parent <tt>ChatConversationContainer</tt>.\n */\n public ChatConversationPanel( ChatConversationContainer chatContainer);\n /** \n * Overrides Component#setBounds(int, int, int, int) in order to determine whether an automatic scroll of #chatTextPane to its bottom will be necessary at a later time in order to keep its vertical scroll bar to its bottom after the realization of the resize if it is at its bottom before the resize.\n */\n @Override public void setBounds( int x, int y, int width, int height);\n /** \n * Retrieves the contents of the sent message with the given ID.\n * @param messageUID The ID of the message to retrieve.\n * @return The contents of the message, or null if the message is not found.\n */\n public String getMessageContents( String messageUID);\n /** \n * Processes the message given by the parameters.\n * @param chatMessage the message\n * @param keyword a substring of <tt>chatMessage</tt> to be highlighted upondisplay of <tt>chatMessage</tt> in the UI\n * @return the processed message\n */\n public String processMessage( ChatMessage chatMessage, String keyword, ProtocolProviderService protocolProvider, String contactAddress);\n /** \n * Processes the message given by the parameters.\n * @param chatMessage the message.\n * @return the formatted message\n */\n public String processMessage( ChatMessage chatMessage, ProtocolProviderService protocolProvider, String contactAddress);\n /** \n * Appends a consecutive message to the document.\n * @param chatMessage the message to append\n * @param keyword the keywords to highlight\n */\n public void appendConsecutiveMessage( final ChatMessage chatMessage, final String keyword);\n /** \n * Replaces the contents of the message with ID of the corrected message specified in chatMessage, with this message.\n * @param chatMessage A <tt>ChatMessage</tt> that contains all the requiredinformation to correct the old message.\n */\n public void correctMessage( final ChatMessage chatMessage);\n /** \n * Appends the given string at the end of the contained in this panel document. Note: Currently, it looks like appendMessageToEnd is only called for messages that are already converted to HTML. So It is quite possible that we can remove the content type without any issues.\n * @param original the message string to append\n * @param contentType the message's content type\n */\n public void appendMessageToEnd( final String original, final String contentType);\n /** \n * Performs all operations needed in order to finish the adding of the message to the document.\n * @param message the message string\n */\n private void finishMessageAdd( final String message);\n /** \n * Formats the given message. Processes the messages and replaces links to video/image sources with their previews or any other substitution. Spawns a separate thread for replacement.\n * @param messageID the messageID element.\n * @param chatString the message.\n */\n void processReplacement( final String messageID, final String chatString);\n /** \n * Ensures that the document won't become too big. When the document reaches a certain size the first message in the page is removed.\n */\n private void ensureDocumentSize();\n /** \n * Deletes all messages \"div\"s that are missing their header the table tag. The method calls itself recursively.\n */\n private void deleteAllMessagesWithoutHeader();\n /** \n * Formats the given message. Processes all smiley chars, new lines and links. This method expects <u>only</u> the message's <u>body</u> to be provided.\n * @param contentType the content type of the message to be formatted\n * @param keyword the word to be highlighted\n * @return the formatted message\n */\n private String formatMessageAsHTML( final String original, final String contentType, final String keyword);\n /** \n * Process provided replacers one by one sequentially. The output of the first replacer is then fed as input into the second replacer, and so on. <p> {@link Replacer}s that expect HTML content ( {@link Replacer#expectsPlainText()}) will typically receive the complete message as an argument. {@linkplain Replacer}s that expect plain text content will typically receive small pieces that are found in between HTML tags. The pieces of plain text content cannot be predicted as results change when they are processed by other replacers. </p>\n * @param content the original content to process\n * @param replacers the replacers to call\n * @return returns the final result message content after it has beenprocessed by all replacers\n */\n private String processReplacers( final String content, final Replacer... replacers);\n /** \n * Opens a link in the default browser when clicked and shows link url in a popup on mouseover.\n * @param e The HyperlinkEvent.\n */\n public void hyperlinkUpdate( HyperlinkEvent e);\n /** \n * Returns the text pane of this conversation panel.\n * @return The text pane of this conversation panel.\n */\n public JTextPane getChatTextPane();\n /** \n * Returns the time of the last received message.\n * @return The time of the last received message.\n */\n public Date getLastIncomingMsgTimestamp();\n /** \n * When a right button click is performed in the editor pane, a popup menu is opened. In case of the Scheme being internal, it won't open the Browser but instead it will trigger the forwarded action.\n * @param e The MouseEvent.\n */\n public void mouseClicked( MouseEvent e);\n /** \n * Opens this panel context menu at the given point.\n * @param p the point where to position the left-top cornet of the contextmenu\n */\n private void openContextMenu( Point p);\n public void mousePressed( MouseEvent e);\n public void mouseReleased( MouseEvent e);\n public void mouseEntered( MouseEvent e);\n public void mouseExited( MouseEvent e);\n public void lostOwnership( Clipboard clipboard, Transferable contents);\n /** \n * Returns the chat container.\n * @return the chat container\n */\n public ChatConversationContainer getChatContainer();\n /** \n * Copies the selected conversation panel content to the clipboard.\n */\n public void copyConversation();\n /** \n * Creates new document and all the messages that will be processed in the future will be appended in it.\n */\n public void clear();\n /** \n * Sets the given document to the editor pane in this panel.\n * @param document the document to set\n */\n public void setContent( final HTMLDocument document);\n /** \n * Sets the default document contained in this panel, created on init or when clear is invoked.\n */\n public void setDefaultContent();\n /** \n * Returns the document contained in this panel.\n * @return the document contained in this panel\n */\n public HTMLDocument getContent();\n /** \n * Returns the right button popup menu.\n * @return the right button popup menu\n */\n public ChatRightButtonMenu getRightButtonMenu();\n /** \n * Returns the date of the first message in the current page.\n * @return the date of the first message in the current page\n */\n public Date getPageFirstMsgTimestamp();\n /** \n * Returns the date of the last message in the current page.\n * @return the date of the last message in the current page\n */\n public Date getPageLastMsgTimestamp();\n /** \n * Extend Editor pane to add URL tooltips.\n */\nprivate class MyTextPane extends JTextPane {\n /** \n * Returns the string to be used as the tooltip for <i>event</i>.\n * @param event the <tt>MouseEvent</tt>\n * @return the string to be used as the tooltip for <i>event</i>.\n */\n @Override public String getToolTipText( MouseEvent event);\n }\n /** \n * Adds a custom component at the end of the conversation.\n * @param component the component to add at the end of the conversation.\n */\n public void addComponent( ChatConversationComponent component);\n /** \n * Registers a new link click listener.\n * @param listener the object that should be notified when an internallink was clicked.\n */\n public void addChatLinkClickedListener( ChatLinkClickedListener listener);\n /** \n * Remove a registered link click listener.\n * @param listener a registered click listener to remove\n */\n public void removeChatLinkClickedListener( ChatLinkClickedListener listener);\n /** \n * Reloads images.\n */\n @Override public void loadSkin();\n /** \n * Processes /me command in group chats.\n * @param chatMessage the chat message\n * @return the newly processed message string\n */\n public String processMeCommand( ChatMessage chatMessage);\n /** \n * Returns the avatar corresponding to the account of the given <tt>protocolProvider</tt>.\n * @param protocolProvider the protocol provider service, which accountavatar we're looking for\n * @return the avatar corresponding to the account of the given<tt>protocolProvider</tt>\n */\n private static String getContactAvatar( ProtocolProviderService protocolProvider, String contactAddress);\n /** \n * Returns the avatar corresponding to the account of the given <tt>protocolProvider</tt>.\n * @param protocolProvider the protocol provider service, which accountavatar we're looking for\n * @return the avatar corresponding to the account of the given<tt>protocolProvider</tt>\n */\n private static String getContactAvatar( ProtocolProviderService protocolProvider);\n /** \n * Indicates if this is a consecutive message.\n * @param chatMessage the message to verify\n * @return <tt>true</tt> if the given message is a consecutive message,<tt>false</tt> - otherwise\n */\n private boolean isConsecutiveMessage( ChatMessage chatMessage);\n /** \n * Releases the resources allocated by this instance throughout its lifetime and prepares it for garbage collection.\n */\n @Override public void dispose();\n /** \n * @param attribute\n * @param matchStrings\n * @return\n */\n private Element findElement( HTML.Attribute attribute, String[] matchStrings);\n /** \n * Finds the first element with <tt>name</tt>.\n * @param name the name to search for.\n * @return the first element with <tt>name</tt>.\n */\n private Element findFirstElement( String name);\n /** \n * @param element\n * @param attrName\n * @param matchStrings\n * @return\n */\n private Element findFirstElement( Element element, HTML.Attribute attrName, String[] matchStrings);\n /** \n * Finds the first element with <tt>name</tt> among the child elements of <tt>element</tt>.\n * @param element the element to searh for.\n * @param name the name to search for.\n * @return the first element with <tt>name</tt>.\n */\n private Element findFirstElement( Element element, String name);\n /** \n * @param elementId\n * @param message\n * @return\n */\n private String getElementContent( String elementId, String message);\n /** \n * Returns the first available advanced configuration form.\n * @return the first available advanced configuration form\n */\n public static ConfigurationForm getChatConfigForm();\n /** \n * Extends SIPCommHTMLEditorKit to keeps track of created ImageView for the gif images in order to flush them whenever they are no longer visible\n */\nprivate class ChatConversationEditorKit extends SIPCommHTMLEditorKit implements DocumentListener {\n /** \n * List of the image views.\n */\n private java.util.List<ImageView> imageViews=new ArrayList<ImageView>();\n /** \n * Constructs.\n * @param container\n */\n public ChatConversationEditorKit( JComponent container);\n /** \n * Clears any left img view and removes any listener was added.\n */\n public void dispose();\n /** \n * Inform view creation.\n * @param view the newly created view.\n */\n protected void viewCreated( ViewFactory factory, View view);\n /** \n * Not used.\n * @param e\n */\n @Override public void insertUpdate( DocumentEvent e);\n /** \n * When something is removed from the current document we will check the stored image views for any element which si no longer visible.\n * @param e the event.\n */\n @Override public void removeUpdate( DocumentEvent e);\n /** \n * Not used.\n * @param e\n */\n @Override public void changedUpdate( DocumentEvent e);\n /** \n * For debugging purposes, prints the content of the document in the console.\n */\n public void debug();\n }\n /** \n * Swing worker used by processReplacement.\n */\nprivate final class ReplacementWorker extends SwingWorker {\n /** \n * The messageID element.\n */\n private final String messageID;\n /** \n * The message.\n */\n private final String chatString;\n /** \n * Counts links while processing. Used to generate unique href.\n */\n private int linkCounter=0;\n /** \n * Is image replacement enabled.\n */\n private final boolean isEnabled;\n /** \n * Is replacement proposal enabled.\n */\n private final boolean isProposalEnabled;\n /** \n * Constructs worker.\n * @param messageID the messageID element.\n * @param chatString the messages.\n */\n private ReplacementWorker( final String messageID, final String chatString);\n /** \n * Called on the event dispatching thread (not on the worker thread) after the <code>construct</code> method has returned.\n */\n @Override public void finished();\n @Override public Object construct() throws Exception;\n /** \n * Process message for a ReplacementService.\n * @param service the service.\n * @param msg the message.\n * @param buff current accumulated buffer.\n */\n private void processReplacementService( final ReplacementService service, final String msg, final StringBuilder buff);\n /** \n * Process plain text content.\n * @param plainText the nodes text.\n * @param msgBuff the currently accumulated buffer.\n * @param pattern the pattern for current replacement service, createdearlier so we don't create it for every text we check.\n * @param rService the replacement service.\n * @param isURL whether this content matches the URL pattern\n */\n private void processText( final String plainText, final StringBuilder msgBuff, final Pattern pattern, final ReplacementService rService, final boolean isURL);\n }\n}\n", "raw_body_no_cmt": "public class ChatConversationPanel extends SIPCommScrollPane implements HyperlinkListener, MouseListener, ClipboardOwner, Skinnable {\n private static final org.slf4j.Logger logger=org.slf4j.LoggerFactory.getLogger(ChatConversationPanel.class);\n private static final Pattern URL_PATTERN=Pattern.compile(\"(\" + \"(\\\\bwww\\\\.[^\\\\s<>\\\"]+\\\\.[^\\\\s<>\\\"]+/*[?#]*(\\\\w+[&=;?]\\\\w+)*\\\\b)\" + \"|\"+ \"(\\\\bjitsi\\\\:[^\\\\s<>\\\"]+\\\\.[^\\\\s<>\\\"]*\\\\b)\"+ \"|\"+ \"(\\\\b\\\\w+://[^\\\\s<>\\\"]+/*[?#]*(\\\\w+[&=;?]\\\\w+)*\\\\b)\"+ \")\");\n private static final Pattern DIV_PATTERN=Pattern.compile(\"(<div[^>]*>)(.*)(</div>)\",Pattern.DOTALL);\n static final Pattern TEXT_TO_REPLACE_PATTERN=Pattern.compile(\"([^<]*+)(?:<(?:[^>\\\"]*(?:\\\"[^\\\"]*+\\\"?)*)*+>?)?\",Pattern.CASE_INSENSITIVE | Pattern.DOTALL);\n private Set<ChatLinkClickedListener> chatLinkClickedListeners=new HashSet<ChatLinkClickedListener>();\n private final JTextPane chatTextPane=new MyTextPane();\n private final ChatConversationEditorKit editorKit;\n HTMLDocument document;\n private final ChatConversationContainer chatContainer;\n private ChatRightButtonMenu rightButtonMenu;\n private String currentHref;\n private boolean isCurrentHrefImg=false;\n private final JMenuItem copyLinkItem;\n private final JMenuItem configureReplacementItem;\n private final JSeparator configureReplacementSeparator=new JSeparator();\n private final JMenuItem openLinkItem;\n private final JSeparator copyLinkSeparator=new JSeparator();\n private Date lastIncomingMsgTimestamp=new Date(0);\n private Date lastMessageTimestamp=new Date(0);\n private final boolean isHistory;\n private boolean scrollToBottomIsPending=false;\n private String lastMessageUID=null;\n private boolean isSimpleTheme=true;\n private ShowPreviewDialog showPreview=new ShowPreviewDialog(ChatConversationPanel.this);\n private final Runnable scrollToBottomRunnable=new Runnable(){\n public void run();\n }\n;\n public ChatConversationPanel( ChatConversationContainer chatContainer);\n public void setBounds( int x, int y, int width, int height);\n public String getMessageContents( String messageUID);\n public String processMessage( ChatMessage chatMessage, String keyword, ProtocolProviderService protocolProvider, String contactAddress);\n public String processMessage( ChatMessage chatMessage, ProtocolProviderService protocolProvider, String contactAddress);\n public void appendConsecutiveMessage( final ChatMessage chatMessage, final String keyword);\n public void correctMessage( final ChatMessage chatMessage);\n public void appendMessageToEnd( final String original, final String contentType);\n private void finishMessageAdd( final String message);\n void processReplacement( final String messageID, final String chatString);\n private void ensureDocumentSize();\n private void deleteAllMessagesWithoutHeader();\n private String formatMessageAsHTML( final String original, final String contentType, final String keyword);\n private String processReplacers( final String content, final Replacer... replacers);\n public void hyperlinkUpdate( HyperlinkEvent e);\n public JTextPane getChatTextPane();\n public Date getLastIncomingMsgTimestamp();\n public void mouseClicked( MouseEvent e);\n private void openContextMenu( Point p);\n public void mousePressed( MouseEvent e);\n public void mouseReleased( MouseEvent e);\n public void mouseEntered( MouseEvent e);\n public void mouseExited( MouseEvent e);\n public void lostOwnership( Clipboard clipboard, Transferable contents);\n public ChatConversationContainer getChatContainer();\n public void copyConversation();\n public void clear();\n public void setContent( final HTMLDocument document);\n public void setDefaultContent();\n public HTMLDocument getContent();\n public ChatRightButtonMenu getRightButtonMenu();\n public Date getPageFirstMsgTimestamp();\n public Date getPageLastMsgTimestamp();\n private class MyTextPane extends JTextPane {\n public String getToolTipText( MouseEvent event);\n }\n public void addComponent( ChatConversationComponent component);\n public void addChatLinkClickedListener( ChatLinkClickedListener listener);\n public void removeChatLinkClickedListener( ChatLinkClickedListener listener);\n public void loadSkin();\n public String processMeCommand( ChatMessage chatMessage);\n private static String getContactAvatar( ProtocolProviderService protocolProvider, String contactAddress);\n private static String getContactAvatar( ProtocolProviderService protocolProvider);\n private boolean isConsecutiveMessage( ChatMessage chatMessage);\n public void dispose();\n private Element findElement( HTML.Attribute attribute, String[] matchStrings);\n private Element findFirstElement( String name);\n private Element findFirstElement( Element element, HTML.Attribute attrName, String[] matchStrings);\n private Element findFirstElement( Element element, String name);\n private String getElementContent( String elementId, String message);\n public static ConfigurationForm getChatConfigForm();\n private class ChatConversationEditorKit extends SIPCommHTMLEditorKit implements DocumentListener {\n private java.util.List<ImageView> imageViews=new ArrayList<ImageView>();\n public ChatConversationEditorKit( JComponent container);\n public void dispose();\n protected void viewCreated( ViewFactory factory, View view);\n public void insertUpdate( DocumentEvent e);\n public void removeUpdate( DocumentEvent e);\n public void changedUpdate( DocumentEvent e);\n public void debug();\n }\n private final class ReplacementWorker extends SwingWorker {\n private final String messageID;\n private final String chatString;\n private int linkCounter=0;\n private final boolean isEnabled;\n private final boolean isProposalEnabled;\n private ReplacementWorker( final String messageID, final String chatString);\n public void finished();\n public Object construct() throws Exception;\n private void processReplacementService( final ReplacementService service, final String msg, final StringBuilder buff);\n private void processText( final String plainText, final StringBuilder msgBuff, final Pattern pattern, final ReplacementService rService, final boolean isURL);\n }\n}\n"}}, {"JMenuItem": {"retrieved_name": "ContactInfoMenuItem", "raw_body": "/** \n * @author Adam Goldstein\n */\npublic class ContactInfoMenuItem extends AbstractPluginComponent implements ActionListener {\n private AbstractButton menuItem=null;\n private MetaContact metaContact;\n /** \n * The button index, for now placed on last position.\n */\n private final static int CONTACT_INFO_BUTTON_IX=50;\n /** \n * Creates a <tt>ContactInfoMenuItem</tt>.\n */\n public ContactInfoMenuItem( PluginComponentFactory parentFactory);\n /** \n * Creates a <tt>ContactInfoMenuItem</tt>.\n */\n public ContactInfoMenuItem( Container container, PluginComponentFactory parentFactory);\n /** \n * Sets the currently selected <tt>MetaContact</tt>.\n * @param metaContact the currently selected meta contact\n */\n @Override public void setCurrentContact( MetaContact metaContact);\n @Override public void setCurrentContact( Contact contact);\n /** \n * Initializes and shows the contact details dialog.\n */\n public void actionPerformed( ActionEvent e);\n public Object getComponent();\n public String getName();\n private AbstractButton getMenuItem();\n}\n", "raw_body_no_cmt": "public class ContactInfoMenuItem extends AbstractPluginComponent implements ActionListener {\n private AbstractButton menuItem=null;\n private MetaContact metaContact;\n private final static int CONTACT_INFO_BUTTON_IX=50;\n public ContactInfoMenuItem( PluginComponentFactory parentFactory);\n public ContactInfoMenuItem( Container container, PluginComponentFactory parentFactory);\n public void setCurrentContact( MetaContact metaContact);\n public void setCurrentContact( Contact contact);\n public void actionPerformed( ActionEvent e);\n public Object getComponent();\n public String getName();\n private AbstractButton getMenuItem();\n}\n"}}] | [] | [{"dispose": {"retrieved_name": "dispose", "raw_body": "/** \n * Remove the newAccountDialog on dispose.\n */\n@Override public void dispose(){\n if (isCurrentlySigningIn) return;\n if (newAccountDialog == this) newAccountDialog=null;\n wizardContainer.getModel().removePropertyChangeListener(this);\n super.dispose();\n}\n"}}] |
pmd_pmd | pmd/pmd-core/src/main/java/net/sourceforge/pmd/renderers/AbstractIncrementingRenderer.java | AbstractIncrementingRenderer | renderFileReport | class AbstractIncrementingRenderer extends AbstractRenderer {
/**
* Accumulated processing errors.
*/
protected List<Report.ProcessingError> errors = new LinkedList<>();
/**
* Accumulated configuration errors.
*/
protected List<Report.ConfigurationError> configErrors = new LinkedList<>();
/**
* Accumulated suppressed violations.
*/
protected List<Report.SuppressedViolation> suppressed = new LinkedList<>();
public AbstractIncrementingRenderer(String name, String description) {
super(name, description);
}
@Override
public void start() throws IOException {
// does nothing - override if necessary
}
@Override
public void startFileAnalysis(TextFile dataSource) {
// does nothing - override if necessary
}
@Override
public void renderFileReport(Report report) throws IOException {<FILL_FUNCTION_BODY>}
/**
* Render a series of {@link RuleViolation}s.
*
* @param violations
* The iterator of violations to render.
* @throws IOException
*/
public abstract void renderFileViolations(Iterator<RuleViolation> violations) throws IOException;
@Override
public void end() throws IOException {
// does nothing - override if necessary
}
} |
Iterator<RuleViolation> violations = report.getViolations().iterator();
if (violations.hasNext()) {
renderFileViolations(violations);
getWriter().flush();
}
errors.addAll(report.getProcessingErrors());
configErrors.addAll(report.getConfigurationErrors());
if (showSuppressedViolations) {
suppressed.addAll(report.getSuppressedViolations());
}
|
// does nothing - override if necessary
| [
"Report"
] | [] | [
"List<Report.SuppressedViolation>",
"Iterator<RuleViolation>",
"List<Report.ProcessingError>",
"List<Report.ConfigurationError>",
"Report"
] | [
"flush",
"addAll",
"getSuppressedViolations",
"hasNext",
"getConfigurationErrors",
"getViolations",
"getProcessingErrors",
"iterator"
] | {
"methods": [],
"similar_methods": [
"renderFileReport"
],
"types": [
"Report"
]
} | /**
* A {@link Report} collects all information during a PMD execution. Thisincludes violations, suppressed violations, metrics, error during processing and configuration errors. <p>A report may be created by a {@link GlobalReportBuilderListener} that youuse as the {@linkplain GlobalAnalysisListener} in {@link PmdAnalysis#performAnalysisAndCollectReport() PMD's entry point}. You can also create one manually with {@link #buildReport(Consumer)}. <p>For special use cases, like filtering the report after PMD analysis and before rendering the report, some transformation operations are provided: <ul> <li> {@link #filterViolations(Predicate)}</li> <li> {@link #union(Report)}</li> </ul> These methods create a new {@link Report} rather than modifying their receiver.
*/
public class Report {
protected final List<RuleViolation> violations=synchronizedList(new ArrayList<>());
protected final List<SuppressedViolation> suppressedRuleViolations=synchronizedList(new ArrayList<>());
protected final List<ProcessingError> errors=synchronizedList(new ArrayList<>());
protected final List<ConfigurationError> configErrors=synchronizedList(new ArrayList<>());
@DeprecatedUntil700 @InternalApi public Report();
/**
* Represents a configuration error.
*/
public static class ConfigurationError {
private final Rule rule;
private final String issue;
/**
* Creates a new configuration error for a specific rule.
* @param theRule the rule which is configured wrongly
* @param theIssue the reason, why the configuration is wrong
*/
public ConfigurationError( Rule theRule, String theIssue);
/**
* Gets the wrongly configured rule
* @return the wrongly configured rule
*/
public Rule rule();
/**
* Gets the reason for the configuration error.
* @return the issue
*/
public String issue();
}
/**
* Represents a processing error, such as a parse error.
*/
public static class ProcessingError {
private final Throwable error;
private final FileId file;
/**
* Creates a new processing error
* @param error the error
* @param file the file during which the error occurred
*/
public ProcessingError( Throwable error, FileId file);
public String getMsg();
public String getDetail();
public FileId getFileId();
public Throwable getError();
public String getFile();
}
/**
* Represents a violation, that has been suppressed.
*/
public static class SuppressedViolation {
private final RuleViolation rv;
private final String userMessage;
private final ViolationSuppressor suppressor;
/**
* Creates a suppressed violation.
* @param rv The violation, that has been suppressed
* @param suppressor The suppressor which suppressed the violation
* @param userMessage Any relevant info given by the suppressor
*/
public SuppressedViolation( RuleViolation rv, ViolationSuppressor suppressor, String userMessage);
public ViolationSuppressor getSuppressor();
public RuleViolation getRuleViolation();
public String getUserMessage();
}
/**
* Adds a new rule violation to the report and notify the listeners.
* @param violation the violation to add
* @deprecated PMD's way of creating a report is internal and may be changed in pmd 7.
*/
@DeprecatedUntil700 @Deprecated @InternalApi public void addRuleViolation( RuleViolation violation);
/**
* Adds a new suppressed violation.
*/
private void addSuppressedViolation( SuppressedViolation sv);
/**
* Adds a new configuration error to the report.
* @param error the error to add
* @deprecated PMD's way of creating a report is internal and may be changed in pmd 7.
*/
@DeprecatedUntil700 @Deprecated @InternalApi public void addConfigError( ConfigurationError error);
/**
* Adds a new processing error to the report.
* @param error the error to add
* @deprecated PMD's way of creating a report is internal and may be changed in pmd 7.
*/
@DeprecatedUntil700 @Deprecated @InternalApi public void addError( ProcessingError error);
/**
* Merges the given report into this report. This might be necessary, if a summary over all violations is needed as PMD creates one report per file by default. <p>This is synchronized on an internal lock (note that other mutation operations are not synchronized, todo for pmd 7).
* @param r the report to be merged into this.
* @see AbstractAccumulatingRenderer
* @deprecated Convert Renderer to use the reports.
*/
@Deprecated public void merge( Report r);
/**
* Returns an unmodifiable list of violations that were suppressed.
*/
public List<SuppressedViolation> getSuppressedViolations();
/**
* Returns an unmodifiable list of violations that have been recorded until now. None of those violations were suppressed. <p>The violations list is sorted with {@link RuleViolation#DEFAULT_COMPARATOR}.
*/
public List<RuleViolation> getViolations();
/**
* Returns an unmodifiable list of processing errors that have been recorded until now.
*/
public List<ProcessingError> getProcessingErrors();
/**
* Returns an unmodifiable list of configuration errors that have been recorded until now.
*/
public List<ConfigurationError> getConfigurationErrors();
/**
* Create a report by making side effects on a {@link FileAnalysisListener}. This wraps a {@link ReportBuilderListener}.
*/
public static Report buildReport( Consumer<? super FileAnalysisListener> lambda);
/**
* A {@link FileAnalysisListener} that accumulates events into a{@link Report}.
*/
public static class ReportBuilderListener extends BaseResultProducingCloseable<Report> implements FileAnalysisListener {
private final Report report;
public ReportBuilderListener();
ReportBuilderListener( Report report);
@Override protected Report getResultImpl();
@Override public void onRuleViolation( net.sourceforge.pmd.reporting.RuleViolation violation);
@Override public void onSuppressedRuleViolation( net.sourceforge.pmd.reporting.Report.SuppressedViolation violation);
@Override public void onError( net.sourceforge.pmd.reporting.Report.ProcessingError error);
@Override public String toString();
}
/**
* A {@link GlobalAnalysisListener} that accumulates the events ofall files into a {@link Report}.
*/
public static class GlobalReportBuilderListener extends BaseResultProducingCloseable<net.sourceforge.pmd.reporting.Report> implements GlobalAnalysisListener {
private final net.sourceforge.pmd.reporting.Report report=new net.sourceforge.pmd.reporting.Report();
@Override public FileAnalysisListener startFileAnalysis( TextFile file);
@Override public void onConfigError( net.sourceforge.pmd.reporting.Report.ConfigurationError error);
@Override protected net.sourceforge.pmd.reporting.Report getResultImpl();
}
/**
* Creates a new report taking all the information from this report, but filtering the violations.
* @param filter when true, the violation will be kept.
* @return copy of this report
*/
@Experimental public Report filterViolations( Predicate<RuleViolation> filter);
/**
* Creates a new report by combining this report with another report. This is similar to {@link #merge(Report)}, but instead a new report is created. The lowest start time and greatest end time are kept in the copy.
* @param other the other report to combine
* @return
*/
@Experimental public Report union( Report other);
@Deprecated public Report filterViolations( net.sourceforge.pmd.util.Predicate<RuleViolation> filter);
}
@Override public void renderFileReport(Report report) throws IOException {
}
| public class Report {
protected final List<RuleViolation> violations=synchronizedList(new ArrayList<>());
protected final List<SuppressedViolation> suppressedRuleViolations=synchronizedList(new ArrayList<>());
protected final List<ProcessingError> errors=synchronizedList(new ArrayList<>());
protected final List<ConfigurationError> configErrors=synchronizedList(new ArrayList<>());
public Report();
public static class ConfigurationError {
private final Rule rule;
private final String issue;
public ConfigurationError( Rule theRule, String theIssue);
public Rule rule();
public String issue();
}
public static class ProcessingError {
private final Throwable error;
private final FileId file;
public ProcessingError( Throwable error, FileId file);
public String getMsg();
public String getDetail();
public FileId getFileId();
public Throwable getError();
public String getFile();
}
public static class SuppressedViolation {
private final RuleViolation rv;
private final String userMessage;
private final ViolationSuppressor suppressor;
public SuppressedViolation( RuleViolation rv, ViolationSuppressor suppressor, String userMessage);
public ViolationSuppressor getSuppressor();
public RuleViolation getRuleViolation();
public String getUserMessage();
}
public void addRuleViolation( RuleViolation violation);
private void addSuppressedViolation( SuppressedViolation sv);
public void addConfigError( ConfigurationError error);
public void addError( ProcessingError error);
public void merge( Report r);
public List<SuppressedViolation> getSuppressedViolations();
public List<RuleViolation> getViolations();
public List<ProcessingError> getProcessingErrors();
public List<ConfigurationError> getConfigurationErrors();
public static Report buildReport( Consumer<? super FileAnalysisListener> lambda);
public static class ReportBuilderListener extends BaseResultProducingCloseable<Report> implements FileAnalysisListener {
private final Report report;
public ReportBuilderListener();
ReportBuilderListener( Report report);
protected Report getResultImpl();
public void onRuleViolation( net.sourceforge.pmd.reporting.RuleViolation violation);
public void onSuppressedRuleViolation( net.sourceforge.pmd.reporting.Report.SuppressedViolation violation);
public void onError( net.sourceforge.pmd.reporting.Report.ProcessingError error);
public String toString();
}
public static class GlobalReportBuilderListener extends BaseResultProducingCloseable<net.sourceforge.pmd.reporting.Report> implements GlobalAnalysisListener {
private final net.sourceforge.pmd.reporting.Report report=new net.sourceforge.pmd.reporting.Report();
public FileAnalysisListener startFileAnalysis( TextFile file);
public void onConfigError( net.sourceforge.pmd.reporting.Report.ConfigurationError error);
protected net.sourceforge.pmd.reporting.Report getResultImpl();
}
public Report filterViolations( Predicate<RuleViolation> filter);
public Report union( Report other);
public Report filterViolations( net.sourceforge.pmd.util.Predicate<RuleViolation> filter);
}
@Override public void renderFileReport(Report report) throws IOException {
}
| {"types": [{"Report": "Report"}], "similar_methods": [{"renderFileReport": "renderFileReport"}]} | [{"Report": {"retrieved_name": "Report", "raw_body": "/** \n * A {@link Report} collects all information during a PMD execution. Thisincludes violations, suppressed violations, metrics, error during processing and configuration errors. <p>A report may be created by a {@link GlobalReportBuilderListener} that youuse as the {@linkplain GlobalAnalysisListener} in {@link PmdAnalysis#performAnalysisAndCollectReport() PMD's entry point}. You can also create one manually with {@link #buildReport(Consumer)}. <p>For special use cases, like filtering the report after PMD analysis and before rendering the report, some transformation operations are provided: <ul> <li> {@link #filterViolations(Predicate)}</li> <li> {@link #union(Report)}</li> </ul> These methods create a new {@link Report} rather than modifying their receiver.\n */\npublic class Report {\n protected final List<RuleViolation> violations=synchronizedList(new ArrayList<>());\n protected final List<SuppressedViolation> suppressedRuleViolations=synchronizedList(new ArrayList<>());\n protected final List<ProcessingError> errors=synchronizedList(new ArrayList<>());\n protected final List<ConfigurationError> configErrors=synchronizedList(new ArrayList<>());\n @DeprecatedUntil700 @InternalApi public Report();\n /** \n * Represents a configuration error.\n */\npublic static class ConfigurationError {\n private final Rule rule;\n private final String issue;\n /** \n * Creates a new configuration error for a specific rule.\n * @param theRule the rule which is configured wrongly\n * @param theIssue the reason, why the configuration is wrong\n */\n public ConfigurationError( Rule theRule, String theIssue);\n /** \n * Gets the wrongly configured rule\n * @return the wrongly configured rule\n */\n public Rule rule();\n /** \n * Gets the reason for the configuration error.\n * @return the issue\n */\n public String issue();\n }\n /** \n * Represents a processing error, such as a parse error.\n */\npublic static class ProcessingError {\n private final Throwable error;\n private final FileId file;\n /** \n * Creates a new processing error\n * @param error the error\n * @param file the file during which the error occurred\n */\n public ProcessingError( Throwable error, FileId file);\n public String getMsg();\n public String getDetail();\n public FileId getFileId();\n public Throwable getError();\n public String getFile();\n }\n /** \n * Represents a violation, that has been suppressed.\n */\npublic static class SuppressedViolation {\n private final RuleViolation rv;\n private final String userMessage;\n private final ViolationSuppressor suppressor;\n /** \n * Creates a suppressed violation.\n * @param rv The violation, that has been suppressed\n * @param suppressor The suppressor which suppressed the violation\n * @param userMessage Any relevant info given by the suppressor\n */\n public SuppressedViolation( RuleViolation rv, ViolationSuppressor suppressor, String userMessage);\n public ViolationSuppressor getSuppressor();\n public RuleViolation getRuleViolation();\n public String getUserMessage();\n }\n /** \n * Adds a new rule violation to the report and notify the listeners.\n * @param violation the violation to add\n * @deprecated PMD's way of creating a report is internal and may be changed in pmd 7.\n */\n @DeprecatedUntil700 @Deprecated @InternalApi public void addRuleViolation( RuleViolation violation);\n /** \n * Adds a new suppressed violation.\n */\n private void addSuppressedViolation( SuppressedViolation sv);\n /** \n * Adds a new configuration error to the report.\n * @param error the error to add\n * @deprecated PMD's way of creating a report is internal and may be changed in pmd 7.\n */\n @DeprecatedUntil700 @Deprecated @InternalApi public void addConfigError( ConfigurationError error);\n /** \n * Adds a new processing error to the report.\n * @param error the error to add\n * @deprecated PMD's way of creating a report is internal and may be changed in pmd 7.\n */\n @DeprecatedUntil700 @Deprecated @InternalApi public void addError( ProcessingError error);\n /** \n * Merges the given report into this report. This might be necessary, if a summary over all violations is needed as PMD creates one report per file by default. <p>This is synchronized on an internal lock (note that other mutation operations are not synchronized, todo for pmd 7).\n * @param r the report to be merged into this.\n * @see AbstractAccumulatingRenderer\n * @deprecated Convert Renderer to use the reports.\n */\n @Deprecated public void merge( Report r);\n /** \n * Returns an unmodifiable list of violations that were suppressed.\n */\n public List<SuppressedViolation> getSuppressedViolations();\n /** \n * Returns an unmodifiable list of violations that have been recorded until now. None of those violations were suppressed. <p>The violations list is sorted with {@link RuleViolation#DEFAULT_COMPARATOR}.\n */\n public List<RuleViolation> getViolations();\n /** \n * Returns an unmodifiable list of processing errors that have been recorded until now.\n */\n public List<ProcessingError> getProcessingErrors();\n /** \n * Returns an unmodifiable list of configuration errors that have been recorded until now.\n */\n public List<ConfigurationError> getConfigurationErrors();\n /** \n * Create a report by making side effects on a {@link FileAnalysisListener}. This wraps a {@link ReportBuilderListener}.\n */\n public static Report buildReport( Consumer<? super FileAnalysisListener> lambda);\n /** \n * A {@link FileAnalysisListener} that accumulates events into a{@link Report}.\n */\npublic static class ReportBuilderListener extends BaseResultProducingCloseable<Report> implements FileAnalysisListener {\n private final Report report;\n public ReportBuilderListener();\n ReportBuilderListener( Report report);\n @Override protected Report getResultImpl();\n @Override public void onRuleViolation( net.sourceforge.pmd.reporting.RuleViolation violation);\n @Override public void onSuppressedRuleViolation( net.sourceforge.pmd.reporting.Report.SuppressedViolation violation);\n @Override public void onError( net.sourceforge.pmd.reporting.Report.ProcessingError error);\n @Override public String toString();\n }\n /** \n * A {@link GlobalAnalysisListener} that accumulates the events ofall files into a {@link Report}.\n */\npublic static class GlobalReportBuilderListener extends BaseResultProducingCloseable<net.sourceforge.pmd.reporting.Report> implements GlobalAnalysisListener {\n private final net.sourceforge.pmd.reporting.Report report=new net.sourceforge.pmd.reporting.Report();\n @Override public FileAnalysisListener startFileAnalysis( TextFile file);\n @Override public void onConfigError( net.sourceforge.pmd.reporting.Report.ConfigurationError error);\n @Override protected net.sourceforge.pmd.reporting.Report getResultImpl();\n }\n /** \n * Creates a new report taking all the information from this report, but filtering the violations.\n * @param filter when true, the violation will be kept.\n * @return copy of this report\n */\n @Experimental public Report filterViolations( Predicate<RuleViolation> filter);\n /** \n * Creates a new report by combining this report with another report. This is similar to {@link #merge(Report)}, but instead a new report is created. The lowest start time and greatest end time are kept in the copy.\n * @param other the other report to combine\n * @return\n */\n @Experimental public Report union( Report other);\n @Deprecated public Report filterViolations( net.sourceforge.pmd.util.Predicate<RuleViolation> filter);\n}\n", "raw_body_no_cmt": "public class Report {\n protected final List<RuleViolation> violations=synchronizedList(new ArrayList<>());\n protected final List<SuppressedViolation> suppressedRuleViolations=synchronizedList(new ArrayList<>());\n protected final List<ProcessingError> errors=synchronizedList(new ArrayList<>());\n protected final List<ConfigurationError> configErrors=synchronizedList(new ArrayList<>());\n public Report();\n public static class ConfigurationError {\n private final Rule rule;\n private final String issue;\n public ConfigurationError( Rule theRule, String theIssue);\n public Rule rule();\n public String issue();\n }\n public static class ProcessingError {\n private final Throwable error;\n private final FileId file;\n public ProcessingError( Throwable error, FileId file);\n public String getMsg();\n public String getDetail();\n public FileId getFileId();\n public Throwable getError();\n public String getFile();\n }\n public static class SuppressedViolation {\n private final RuleViolation rv;\n private final String userMessage;\n private final ViolationSuppressor suppressor;\n public SuppressedViolation( RuleViolation rv, ViolationSuppressor suppressor, String userMessage);\n public ViolationSuppressor getSuppressor();\n public RuleViolation getRuleViolation();\n public String getUserMessage();\n }\n public void addRuleViolation( RuleViolation violation);\n private void addSuppressedViolation( SuppressedViolation sv);\n public void addConfigError( ConfigurationError error);\n public void addError( ProcessingError error);\n public void merge( Report r);\n public List<SuppressedViolation> getSuppressedViolations();\n public List<RuleViolation> getViolations();\n public List<ProcessingError> getProcessingErrors();\n public List<ConfigurationError> getConfigurationErrors();\n public static Report buildReport( Consumer<? super FileAnalysisListener> lambda);\n public static class ReportBuilderListener extends BaseResultProducingCloseable<Report> implements FileAnalysisListener {\n private final Report report;\n public ReportBuilderListener();\n ReportBuilderListener( Report report);\n protected Report getResultImpl();\n public void onRuleViolation( net.sourceforge.pmd.reporting.RuleViolation violation);\n public void onSuppressedRuleViolation( net.sourceforge.pmd.reporting.Report.SuppressedViolation violation);\n public void onError( net.sourceforge.pmd.reporting.Report.ProcessingError error);\n public String toString();\n }\n public static class GlobalReportBuilderListener extends BaseResultProducingCloseable<net.sourceforge.pmd.reporting.Report> implements GlobalAnalysisListener {\n private final net.sourceforge.pmd.reporting.Report report=new net.sourceforge.pmd.reporting.Report();\n public FileAnalysisListener startFileAnalysis( TextFile file);\n public void onConfigError( net.sourceforge.pmd.reporting.Report.ConfigurationError error);\n protected net.sourceforge.pmd.reporting.Report getResultImpl();\n }\n public Report filterViolations( Predicate<RuleViolation> filter);\n public Report union( Report other);\n public Report filterViolations( net.sourceforge.pmd.util.Predicate<RuleViolation> filter);\n}\n"}}] | [] | [{"renderFileReport": {"retrieved_name": "renderFileReport", "raw_body": "@Override public void renderFileReport(Report report) throws IOException {\n}\n"}}] |
|
jitsi_jitsi | jitsi/modules/service/ui-service/src/main/java/net/java/sip/communicator/service/gui/call/CallPeerAdapter.java | CallPeerAdapter | propertyChange | class CallPeerAdapter
extends net.java.sip.communicator.service.protocol.event.CallPeerAdapter
implements CallPeerSecurityListener,
PropertyChangeListener
{
/**
* The <tt>CallPeer</tt> which is depicted by {@link #renderer}.
*/
private final CallPeer peer;
/**
* The <tt>CallPeerRenderer</tt> which is facilitated by this instance.
*/
private final CallPeerRenderer renderer;
/**
* Initializes a new <tt>CallPeerAdapter</tt> instance which is to listen to
* a specific <tt>CallPeer</tt> on behalf of a specific
* <tt>CallPeerRenderer</tt>. The new instance adds itself to the specified
* <tt>CallPeer</tt> as a listener for each of the implemented listener
* types.
*
* @param peer the <tt>CallPeer</tt> which the new instance is to listen to
* on behalf of the specified <tt>renderer</tt>
* @param renderer the <tt>CallPeerRenderer</tt> which is to be facilitated
* by the new instance
*/
public CallPeerAdapter(CallPeer peer, CallPeerRenderer renderer)
{
this.peer = peer;
this.renderer = renderer;
this.peer.addCallPeerListener(this);
this.peer.addCallPeerSecurityListener(this);
this.peer.addPropertyChangeListener(this);
}
/**
* Removes the listeners implemented by this instance from the associated
* <tt>CallPeer</tt> and prepares it for garbage collection.
*/
public void dispose()
{
peer.removeCallPeerListener(this);
peer.removeCallPeerSecurityListener(this);
peer.removePropertyChangeListener(this);
}
/**
* {@inheritDoc}
*/
@Override
public void peerDisplayNameChanged(CallPeerChangeEvent ev)
{
if (peer.equals(ev.getSourceCallPeer()))
renderer.setPeerName((String) ev.getNewValue());
}
/**
* {@inheritDoc}
*/
@Override
public void peerImageChanged(CallPeerChangeEvent ev)
{
if (peer.equals(ev.getSourceCallPeer()))
renderer.setPeerImage((byte[]) ev.getNewValue());
}
/**
* {@inheritDoc}
*/
@Override
public void peerStateChanged(CallPeerChangeEvent ev)
{
CallPeer sourcePeer = ev.getSourceCallPeer();
if (!sourcePeer.equals(peer))
return;
CallPeerState newState = (CallPeerState) ev.getNewValue();
CallPeerState oldState = (CallPeerState) ev.getOldValue();
String newStateString = sourcePeer.getState().getLocalizedStateString();
if (newState == CallPeerState.CONNECTED)
{
if (!CallPeerState.isOnHold(oldState))
{
if (!renderer.getCallRenderer().isCallTimerStarted())
renderer.getCallRenderer().startCallTimer();
}
else
{
renderer.setOnHold(false);
renderer.getCallRenderer().updateHoldButtonState();
}
}
else if (newState == CallPeerState.DISCONNECTED)
{
// The call peer should be already removed from the call
// see CallPeerRemoved
}
else if (newState == CallPeerState.FAILED)
{
// The call peer should be already removed from the call
// see CallPeerRemoved
}
else if (CallPeerState.isOnHold(newState))
{
renderer.setOnHold(true);
renderer.getCallRenderer().updateHoldButtonState();
}
renderer.setPeerState(oldState, newState, newStateString);
String reasonString = ev.getReasonString();
if (reasonString != null)
renderer.setErrorReason(reasonString);
}
/**
* {@inheritDoc}
*/
public void propertyChange(PropertyChangeEvent ev)
{<FILL_FUNCTION_BODY>}
/**
* {@inheritDoc}
*
* <tt>CallPeerAdapter</tt> does nothing.
*/
public void securityMessageRecieved(CallPeerSecurityMessageEvent ev)
{
}
/**
* {@inheritDoc}
*/
public void securityNegotiationStarted(
CallPeerSecurityNegotiationStartedEvent ev)
{
if (peer.equals(ev.getSource()))
renderer.securityNegotiationStarted(ev);
}
/**
* {@inheritDoc}
*/
public void securityOff(CallPeerSecurityOffEvent ev)
{
if (peer.equals(ev.getSource()))
renderer.securityOff(ev);
}
/**
* {@inheritDoc}
*/
public void securityOn(CallPeerSecurityOnEvent ev)
{
if (peer.equals(ev.getSource()))
renderer.securityOn(ev);
}
/**
* {@inheritDoc}
*/
public void securityTimeout(CallPeerSecurityTimeoutEvent ev)
{
if (peer.equals(ev.getSource()))
renderer.securityTimeout(ev);
}
} |
String propertyName = ev.getPropertyName();
if (propertyName.equals(CallPeer.MUTE_PROPERTY_NAME))
{
boolean mute = (Boolean) ev.getNewValue();
renderer.setMute(mute);
}
| /**
* An abstract adapter class for receiving call peer (change) events. This class exists only as a convenience for creating listener objects. <p> Extend this class to create a <tt>CallPeerChangeEvent</tt> listener and override the methods for the events of interest. (If you implement the <tt>CallPeerListener</tt> interface, you have to define all of the methods in it. This abstract class defines null methods for them all, so you only have to define methods for events you care about.) </p>
* @see CallPeerChangeEvent
* @see CallPeerListener
* @author Lubomir Marinov
*/
public abstract class CallPeerAdapter implements CallPeerListener {
/**
* Indicates that a change has occurred in the address of the source <tt>CallPeer</tt>.
* @param evt the <tt>CallPeerChangeEvent</tt> instance containing thesource event as well as its previous and its new address
*/
public void peerAddressChanged( CallPeerChangeEvent evt);
/**
* Indicates that a change has occurred in the display name of the source <tt>CallPeer</tt>.
* @param evt the <tt>CallPeerChangeEvent</tt> instance containing thesource event as well as its previous and its new display names
*/
public void peerDisplayNameChanged( CallPeerChangeEvent evt);
/**
* Indicates that a change has occurred in the image of the source <tt>CallPeer</tt>.
* @param evt the <tt>CallPeerChangeEvent</tt> instance containing thesource event as well as its previous and its new image
*/
public void peerImageChanged( CallPeerChangeEvent evt);
/**
* Indicates that a change has occurred in the status of the source <tt>CallPeer</tt>.
* @param evt the <tt>CallPeerChangeEvent</tt> instance containing thesource event as well as its previous and its new status
*/
public void peerStateChanged( CallPeerChangeEvent evt);
/**
* Indicates that a change has occurred in the transport address that we use to communicate with the source <tt>CallPeer</tt>.
* @param evt the <tt>CallPeerChangeEvent</tt> instance containing thesource event as well as its previous and its new transport address
*/
public void peerTransportAddressChanged( CallPeerChangeEvent evt);
}
|
if (peer.equals(ev.getSource()))
renderer.setPeerProperty(ev.getPropertyName(), ev.getNewValue());
| [
"CallPeerRenderer",
"CallPeer",
"CallPeerSecurityTimeoutEvent"
] | [
"getNewValue",
"getPropertyName",
"getSource",
"equals",
"setPeerProperty"
] | [
"CallPeerRenderer",
"CallPeerSecurityTimeoutEvent"
] | [
"equals",
"getPropertyName",
"setMute",
"getNewValue"
] | {
"methods": [
"getNewValue",
"getPropertyName",
"getSource",
"equals",
"setPeerProperty"
],
"similar_methods": [
"propertyChange"
],
"types": [
"CallPeerRenderer",
"CallPeer",
"CallPeerSecurityTimeoutEvent"
]
} | /**
* The <tt>CallPeerRenderer</tt> interface is meant to be implemented by different renderers of <tt>CallPeer</tt>s. Through this interface they would could be updated in order to reflect the current state of the CallPeer.
* @author Yana Stamcheva
* @author Lyubomir Marinov
*/
public interface CallPeerRenderer {
/**
* Releases the resources (which require explicit disposal) acquired by this <tt>CallPeerRenderer</tt> throughout its lifetime and prepares it for garbage collection.
*/
public void dispose();
/**
* Returns the parent call renderer.
* @return the parent call renderer
*/
public CallRenderer getCallRenderer();
/**
* Indicates if the local video component is currently visible.
* @return <tt>true</tt> if the local video component is currently visible,<tt>false</tt> - otherwise
*/
public boolean isLocalVideoVisible();
/**
* Prints the given DTMG character through this <tt>CallPeerRenderer</tt>.
* @param dtmfChar the DTMF char to print
*/
public void printDTMFTone( char dtmfChar);
/**
* The handler for the security event received. The security event for starting establish a secure connection.
* @param securityStartedEvent the security started event received
*/
public void securityNegotiationStarted( CallPeerSecurityNegotiationStartedEvent securityStartedEvent);
/**
* Indicates that the security is turned off.
* @param evt Details about the event that caused this message.
*/
public void securityOff( CallPeerSecurityOffEvent evt);
/**
* Indicates that the security is turned on.
* @param evt Details about the event that caused this message.
*/
public void securityOn( CallPeerSecurityOnEvent evt);
/**
* Indicates that the security status is pending confirmation.
*/
public void securityPending();
/**
* Indicates that the security is timeouted, is not supported by the other end.
* @param evt Details about the event that caused this message.
*/
public void securityTimeout( CallPeerSecurityTimeoutEvent evt);
/**
* Sets the reason of a call failure if one occurs. The renderer should display this reason to the user.
* @param reason the reason of the error to set
*/
public void setErrorReason( String reason);
/**
* Shows/hides the local video component.
* @param visible <tt>true</tt> to show the local video or <tt>false</tt> tohide it
*/
public void setLocalVideoVisible( boolean visible);
/**
* Sets the mute property value.
* @param mute <tt>true</tt> to mute the <tt>CallPeer</tt> depicted by thisinstance; <tt>false</tt>, otherwise
*/
public void setMute( boolean mute);
/**
* Sets the "on hold" property value.
* @param onHold <tt>true</tt> to put the <tt>CallPeer</tt> depicted by thisinstance on hold; <tt>false</tt>, otherwise
*/
public void setOnHold( boolean onHold);
/**
* Sets the <tt>image</tt> of the peer.
* @param image the image to set
*/
public void setPeerImage( byte[] image);
/**
* Sets the name of the peer.
* @param name the name of the peer
*/
public void setPeerName( String name);
/**
* Sets the state of the contained call peer by specifying the state name.
* @param oldState the previous state of the peer
* @param newState the new state of the peer
* @param stateString the state of the contained call peer
*/
public void setPeerState( CallPeerState oldState, CallPeerState newState, String stateString);
/**
* Shows/hides the security panel.
* @param visible <tt>true</tt> to show the security panel or <tt>false</tt>to hide it
*/
public void setSecurityPanelVisible( boolean visible);
/**
* Enable or disable DTMF tone handle
* @param enabled - if true DTMF tone is enabled and disabled if false
*/
public void setDtmfToneEnabled( boolean enabled);
/**
* @return true if DTMF handling enabled
*/
public boolean isDtmfToneEnabled();
}
/**
* The CallPeer is an interface that represents peers in a call. Users of the UIService need to implement this interface (or one of its default implementations such DefaultCallPeer) in order to be able to register call peer in the user interface. <p>For SIP calls for example, it would be necessary to create a CallPeerSipImpl class that would provide sip specific implementations of various methods (getAddress() for example would return the peer's sip URI).
* @author Emil Ivov
* @author Lyubomir Marinov
* @author Yana Stamcheva
*/
public interface CallPeer {
/**
* The constant indicating that a <tt>CallPeer</tt> has not yet transitioned into a state marking the beginning of a participation in a <tt>Call</tt> or that such a transition may have happened but the time of its occurrence is unknown.
*/
public static final long CALL_DURATION_START_TIME_UNKNOWN=0;
/**
* The mute property name.
*/
public static final String MUTE_PROPERTY_NAME="Mute";
/**
* Adds a specific <tt>CallPeerConferenceListener</tt> to the list of listeners interested in and notified about changes in conference-related information such as this peer acting or not acting as a conference focus and conference membership details.
* @param listener a <tt>CallPeerConferenceListener</tt> to be notified about changes in conference-related information. If the specified listener is already in the list of interested listeners (i.e. it has been previously added), it is not added again.
*/
public void addCallPeerConferenceListener( CallPeerConferenceListener listener);
/**
* Allows the user interface to register a listener interested in changes
* @param listener a listener instance to register with this peer.
*/
public void addCallPeerListener( CallPeerListener listener);
/**
* Allows the user interface to register a listener interested in security status changes.
* @param listener a listener instance to register with this peer
*/
public void addCallPeerSecurityListener( CallPeerSecurityListener listener);
/**
* Adds a specific <tt>SoundLevelListener</tt> to the list of listeners interested in and notified about changes in conference members sound level.
* @param listener the <tt>SoundLevelListener</tt> to add
*/
public void addConferenceMembersSoundLevelListener( ConferenceMembersSoundLevelListener listener);
/**
* Allows the user interface to register a listener interested in property changes.
* @param listener a property change listener instance to register with thispeer.
*/
public void addPropertyChangeListener( PropertyChangeListener listener);
/**
* Adds a specific <tt>SoundLevelListener</tt> to the list of listeners interested in and notified about changes in stream sound level related information.
* @param listener the <tt>SoundLevelListener</tt> to add
*/
public void addStreamSoundLevelListener( SoundLevelListener listener);
/**
* Returns a String locator for that peer. A locator might be a SIP URI, an IP address or a telephone number.
* @return the peer's address or phone number.
*/
public String getAddress();
/**
* Returns a reference to the call that this peer belongs to.
* @return a reference to the call containing this peer.
*/
public Call getCall();
/**
* Gets the time at which this <tt>CallPeer</tt> transitioned into a state (likely {@link CallPeerState#CONNECTED}) marking the start of the duration of the participation in a <tt>Call</tt>.
* @return the time at which this <tt>CallPeer</tt> transitionedinto a state marking the start of the duration of the participation in a <tt>Call</tt> or {@link #CALL_DURATION_START_TIME_UNKNOWN} if such a transitionhas not been performed
*/
long getCallDurationStartTime();
/**
* Returns a URL pointing to a location with call control information or null if such an URL is not available for the current call peer.
* @return a URL link to a location with call information or a call controlweb interface related to this peer or <tt>null</tt> if no such URL is available.
*/
public URL getCallInfoURL();
/**
* Gets the number of <tt>ConferenceMember</tt>s currently known to this peer if it is acting as a conference focus.
* @return the number of <tt>ConferenceMember</tt>s currently known tothis peer if it is acting as a conference focus. If this peer is not acting as a conference focus or it does but there are currently no members in the conference it manages, a value of zero is returned.
*/
public int getConferenceMemberCount();
/**
* Gets the <tt>ConferenceMember</tt>s currently known to this peer if it is acting as a conference focus.
* @return a <tt>List</tt> of <tt>ConferenceMember</tt>s describing themembers of a conference managed by this peer if it is acting as a conference focus. If this peer is not acting as a conference focus or it does but there are currently no members in the conference it manages, an empty <tt>List</tt> is returned.
*/
public List<ConferenceMember> getConferenceMembers();
/**
* Returns the contact corresponding to this peer or null if no particular contact has been associated. <p>
* @return the <tt>Contact</tt> corresponding to this peer or nullif no particular contact has been associated.
*/
public Contact getContact();
/**
* Returns the currently used security settings of this <tt>CallPeer</tt>.
* @return the <tt>CallPeerSecurityStatusEvent</tt> that contains thecurrent security settings.
*/
public CallPeerSecurityStatusEvent getCurrentSecuritySettings();
/**
* Returns a human readable name representing this peer.
* @return a String containing a name for that peer.
*/
public String getDisplayName();
/**
* Returns an alternative IMPP address corresponding to this <tt>CallPeer</tt>.
* @return a string representing an alternative IMPP address correspondingto this <tt>CallPeer</tt>
*/
public String getAlternativeIMPPAddress();
/**
* The method returns an image representation of the call peer (e.g. a photo). Generally, the image representation is acquired from the underlying telephony protocol and is transferred over the network during call negotiation.
* @return byte[] a byte array containing the image or null if no image isavailable.
*/
public byte[] getImage();
/**
* Returns a unique identifier representing this peer. Identifiers returned by this method should remain unique across calls. In other words, if it returned the value of "A" for a given peer it should not return that same value for any other peer and return a different value even if the same person (address) is participating in another call. Values need not remain unique after restarting the program.
* @return an identifier representing this call peer.
*/
public String getPeerID();
/**
* Returns the protocol provider that this peer belongs to.
* @return a reference to the ProtocolProviderService that this peerbelongs to.
*/
public ProtocolProviderService getProtocolProvider();
/**
* Returns an object representing the current state of that peer. CallPeerState may vary among CONNECTING, RINGING, CALLING, BUSY, CONNECTED, and others, and it reflects the state of the connection between us and that peer.
* @return a CallPeerState instance representing the peer'sstate.
*/
public CallPeerState getState();
/**
* Returns full URI of the address. For example sip:user@domain.org or xmpp:user@domain.org.
* @return full URI of the address
*/
public String getURI();
/**
* Determines whether this peer is acting as a conference focus and thus may provide information about <tt>ConferenceMember</tt> such as {@link #getConferenceMembers()} and {@link #getConferenceMemberCount()}.
* @return <tt>true</tt> if this peer is acting as a conferencefocus; <tt>false</tt>, otherwise
*/
public boolean isConferenceFocus();
/**
* Determines whether the audio stream (if any) being sent to this peer is mute.
* @return <tt>true</tt> if an audio stream is being sent to thispeer and it is currently mute; <tt>false</tt>, otherwise
*/
public boolean isMute();
/**
* Removes a specific <tt>CallPeerConferenceListener</tt> from the list of listeners interested in and notified about changes in conference-related information such as this peer acting or not acting as a conference focus and conference membership details.
* @param listener a <tt>CallPeerConferenceListener</tt> to no longer be notified about changes in conference-related information
*/
public void removeCallPeerConferenceListener( CallPeerConferenceListener listener);
/**
* Unregisters the specified listener.
* @param listener the listener to unregister.
*/
public void removeCallPeerListener( CallPeerListener listener);
/**
* Unregisters the specified listener.
* @param listener the listener to unregister
*/
public void removeCallPeerSecurityListener( CallPeerSecurityListener listener);
/**
* Removes a specific <tt>SoundLevelListener</tt> of the list of listeners interested in and notified about changes in conference members sound level.
* @param listener the <tt>SoundLevelListener</tt> toremove
*/
public void removeConferenceMembersSoundLevelListener( ConferenceMembersSoundLevelListener listener);
/**
* Unregisters the specified property change listener.
* @param listener the property change listener to unregister.
*/
public void removePropertyChangeListener( PropertyChangeListener listener);
/**
* Removes a specific <tt>SoundLevelListener</tt> of the list of listeners interested in and notified about changes in stream sound level related information.
* @param listener the <tt>SoundLevelListener</tt> to remove
*/
public void removeStreamSoundLevelListener( SoundLevelListener listener);
/**
* Returns a string representation of the peer in the form of <br> Display Name <address>;status=CallPeerStatus
* @return a string representation of the peer and its state.
*/
public String toString();
}
/**
* The <tt>CallPeerSecurityTimeoutEvent</tt> is triggered whenever a communication with a given peer cannot be established, the peer did not answer our tries to secure the connection.
* @author Damian Minkov
*/
public class CallPeerSecurityTimeoutEvent extends CallPeerSecurityStatusEvent {
/**
* Serial version UID.
*/
private static final long serialVersionUID=0L;
/**
* The event constructor
* @param callPeer the call peer associated with this event
* @param sessionType the type of the session, either{@link CallPeerSecurityStatusEvent#AUDIO_SESSION} or{@link CallPeerSecurityStatusEvent#VIDEO_SESSION}
*/
public CallPeerSecurityTimeoutEvent( CallPeer callPeer, int sessionType);
}
/**
* Gets the new value for the event, expressed as an Object.
* @return The new value for the event, expressed as an Object.
*/
public Object getNewValue(){
return newValue;
}
/**
* Returns the property name of individual replacement sources
* @param source the replacement source name.
* @return the property name of the specified source as will be stored inthe properties file.
*/
public static String getPropertyName(String source){
return "net.java.sip.communicator.service.replacement." + source + ".enable";
}
public Object getSource(){
return getWindow();
}
@Override public boolean equals(Object obj){
if (obj instanceof ChatAttachments) return this.chat.equals(((ChatAttachments)obj).chat);
else return false;
}
/**
* Sets the name of the peer.
* @param name the name of the peer
*/
public void setPeerName(String name){
setParticipantName(name);
}
/**
* {@inheritDoc}Invokes {@link #onEventObject(EventObject)}.
*/
public void propertyChange(PropertyChangeEvent ev){
String propertyName=ev.getPropertyName();
if (propertyName.equals(CallConference.CALLS)) {
onEventObject(ev);
}
else if (propertyName.equals(CallContainer.PROP_FULL_SCREEN)) {
if (ev.getSource().equals(callWindow.getFrame())) {
try {
onEventObject(ev);
}
finally {
callWindowPropertyChange(ev);
}
}
}
}
| public interface CallPeerRenderer {
public void dispose();
public CallRenderer getCallRenderer();
public boolean isLocalVideoVisible();
public void printDTMFTone( char dtmfChar);
public void securityNegotiationStarted( CallPeerSecurityNegotiationStartedEvent securityStartedEvent);
public void securityOff( CallPeerSecurityOffEvent evt);
public void securityOn( CallPeerSecurityOnEvent evt);
public void securityPending();
public void securityTimeout( CallPeerSecurityTimeoutEvent evt);
public void setErrorReason( String reason);
public void setLocalVideoVisible( boolean visible);
public void setMute( boolean mute);
public void setOnHold( boolean onHold);
public void setPeerImage( byte[] image);
public void setPeerName( String name);
public void setPeerState( CallPeerState oldState, CallPeerState newState, String stateString);
public void setSecurityPanelVisible( boolean visible);
public void setDtmfToneEnabled( boolean enabled);
public boolean isDtmfToneEnabled();
}
public interface CallPeer {
public static final long CALL_DURATION_START_TIME_UNKNOWN=0;
public static final String MUTE_PROPERTY_NAME="Mute";
public void addCallPeerConferenceListener( CallPeerConferenceListener listener);
public void addCallPeerListener( CallPeerListener listener);
public void addCallPeerSecurityListener( CallPeerSecurityListener listener);
public void addConferenceMembersSoundLevelListener( ConferenceMembersSoundLevelListener listener);
public void addPropertyChangeListener( PropertyChangeListener listener);
public void addStreamSoundLevelListener( SoundLevelListener listener);
public String getAddress();
public Call getCall();
long getCallDurationStartTime();
public URL getCallInfoURL();
public int getConferenceMemberCount();
public List<ConferenceMember> getConferenceMembers();
public Contact getContact();
public CallPeerSecurityStatusEvent getCurrentSecuritySettings();
public String getDisplayName();
public String getAlternativeIMPPAddress();
public byte[] getImage();
public String getPeerID();
public ProtocolProviderService getProtocolProvider();
public CallPeerState getState();
public String getURI();
public boolean isConferenceFocus();
public boolean isMute();
public void removeCallPeerConferenceListener( CallPeerConferenceListener listener);
public void removeCallPeerListener( CallPeerListener listener);
public void removeCallPeerSecurityListener( CallPeerSecurityListener listener);
public void removeConferenceMembersSoundLevelListener( ConferenceMembersSoundLevelListener listener);
public void removePropertyChangeListener( PropertyChangeListener listener);
public void removeStreamSoundLevelListener( SoundLevelListener listener);
public String toString();
}
public class CallPeerSecurityTimeoutEvent extends CallPeerSecurityStatusEvent {
private static final long serialVersionUID=0L;
public CallPeerSecurityTimeoutEvent( CallPeer callPeer, int sessionType);
}
/**
* Gets the new value for the event, expressed as an Object.
* @return The new value for the event, expressed as an Object.
*/
public Object getNewValue(){
return newValue;
}
/**
* Returns the property name of individual replacement sources
* @param source the replacement source name.
* @return the property name of the specified source as will be stored inthe properties file.
*/
public static String getPropertyName(String source){
return "net.java.sip.communicator.service.replacement." + source + ".enable";
}
public Object getSource(){
return getWindow();
}
@Override public boolean equals(Object obj){
if (obj instanceof ChatAttachments) return this.chat.equals(((ChatAttachments)obj).chat);
else return false;
}
/**
* Sets the name of the peer.
* @param name the name of the peer
*/
public void setPeerName(String name){
setParticipantName(name);
}
/**
* {@inheritDoc}Invokes {@link #onEventObject(EventObject)}.
*/
public void propertyChange(PropertyChangeEvent ev){
String propertyName=ev.getPropertyName();
if (propertyName.equals(CallConference.CALLS)) {
onEventObject(ev);
}
else if (propertyName.equals(CallContainer.PROP_FULL_SCREEN)) {
if (ev.getSource().equals(callWindow.getFrame())) {
try {
onEventObject(ev);
}
finally {
callWindowPropertyChange(ev);
}
}
}
}
| {"types": [{"CallPeerRenderer": "CallPeerRenderer"}, {"CallPeer": "CallPeer"}, {"CallPeerSecurityTimeoutEvent": "CallPeerSecurityTimeoutEvent"}], "methods": [{"getNewValue": "getNewValue"}, {"getPropertyName": "getPropertyName"}, {"getSource": "getSource"}, {"equals": "equals"}, {"setPeerProperty": "setPeerName"}], "similar_methods": [{"propertyChange": "propertyChange"}]} | [{"CallPeerRenderer": {"retrieved_name": "CallPeerRenderer", "raw_body": "/** \n * The <tt>CallPeerRenderer</tt> interface is meant to be implemented by different renderers of <tt>CallPeer</tt>s. Through this interface they would could be updated in order to reflect the current state of the CallPeer.\n * @author Yana Stamcheva\n * @author Lyubomir Marinov\n */\npublic interface CallPeerRenderer {\n /** \n * Releases the resources (which require explicit disposal) acquired by this <tt>CallPeerRenderer</tt> throughout its lifetime and prepares it for garbage collection.\n */\n public void dispose();\n /** \n * Returns the parent call renderer.\n * @return the parent call renderer\n */\n public CallRenderer getCallRenderer();\n /** \n * Indicates if the local video component is currently visible.\n * @return <tt>true</tt> if the local video component is currently visible,<tt>false</tt> - otherwise\n */\n public boolean isLocalVideoVisible();\n /** \n * Prints the given DTMG character through this <tt>CallPeerRenderer</tt>.\n * @param dtmfChar the DTMF char to print\n */\n public void printDTMFTone( char dtmfChar);\n /** \n * The handler for the security event received. The security event for starting establish a secure connection.\n * @param securityStartedEvent the security started event received\n */\n public void securityNegotiationStarted( CallPeerSecurityNegotiationStartedEvent securityStartedEvent);\n /** \n * Indicates that the security is turned off.\n * @param evt Details about the event that caused this message.\n */\n public void securityOff( CallPeerSecurityOffEvent evt);\n /** \n * Indicates that the security is turned on.\n * @param evt Details about the event that caused this message.\n */\n public void securityOn( CallPeerSecurityOnEvent evt);\n /** \n * Indicates that the security status is pending confirmation.\n */\n public void securityPending();\n /** \n * Indicates that the security is timeouted, is not supported by the other end.\n * @param evt Details about the event that caused this message.\n */\n public void securityTimeout( CallPeerSecurityTimeoutEvent evt);\n /** \n * Sets the reason of a call failure if one occurs. The renderer should display this reason to the user.\n * @param reason the reason of the error to set\n */\n public void setErrorReason( String reason);\n /** \n * Shows/hides the local video component.\n * @param visible <tt>true</tt> to show the local video or <tt>false</tt> tohide it\n */\n public void setLocalVideoVisible( boolean visible);\n /** \n * Sets the mute property value.\n * @param mute <tt>true</tt> to mute the <tt>CallPeer</tt> depicted by thisinstance; <tt>false</tt>, otherwise\n */\n public void setMute( boolean mute);\n /** \n * Sets the \"on hold\" property value.\n * @param onHold <tt>true</tt> to put the <tt>CallPeer</tt> depicted by thisinstance on hold; <tt>false</tt>, otherwise\n */\n public void setOnHold( boolean onHold);\n /** \n * Sets the <tt>image</tt> of the peer.\n * @param image the image to set\n */\n public void setPeerImage( byte[] image);\n /** \n * Sets the name of the peer.\n * @param name the name of the peer\n */\n public void setPeerName( String name);\n /** \n * Sets the state of the contained call peer by specifying the state name.\n * @param oldState the previous state of the peer\n * @param newState the new state of the peer\n * @param stateString the state of the contained call peer\n */\n public void setPeerState( CallPeerState oldState, CallPeerState newState, String stateString);\n /** \n * Shows/hides the security panel.\n * @param visible <tt>true</tt> to show the security panel or <tt>false</tt>to hide it\n */\n public void setSecurityPanelVisible( boolean visible);\n /** \n * Enable or disable DTMF tone handle\n * @param enabled - if true DTMF tone is enabled and disabled if false\n */\n public void setDtmfToneEnabled( boolean enabled);\n /** \n * @return true if DTMF handling enabled\n */\n public boolean isDtmfToneEnabled();\n}\n", "raw_body_no_cmt": "public interface CallPeerRenderer {\n public void dispose();\n public CallRenderer getCallRenderer();\n public boolean isLocalVideoVisible();\n public void printDTMFTone( char dtmfChar);\n public void securityNegotiationStarted( CallPeerSecurityNegotiationStartedEvent securityStartedEvent);\n public void securityOff( CallPeerSecurityOffEvent evt);\n public void securityOn( CallPeerSecurityOnEvent evt);\n public void securityPending();\n public void securityTimeout( CallPeerSecurityTimeoutEvent evt);\n public void setErrorReason( String reason);\n public void setLocalVideoVisible( boolean visible);\n public void setMute( boolean mute);\n public void setOnHold( boolean onHold);\n public void setPeerImage( byte[] image);\n public void setPeerName( String name);\n public void setPeerState( CallPeerState oldState, CallPeerState newState, String stateString);\n public void setSecurityPanelVisible( boolean visible);\n public void setDtmfToneEnabled( boolean enabled);\n public boolean isDtmfToneEnabled();\n}\n"}}, {"CallPeer": {"retrieved_name": "CallPeer", "raw_body": "/** \n * The CallPeer is an interface that represents peers in a call. Users of the UIService need to implement this interface (or one of its default implementations such DefaultCallPeer) in order to be able to register call peer in the user interface. <p>For SIP calls for example, it would be necessary to create a CallPeerSipImpl class that would provide sip specific implementations of various methods (getAddress() for example would return the peer's sip URI).\n * @author Emil Ivov\n * @author Lyubomir Marinov\n * @author Yana Stamcheva\n */\npublic interface CallPeer {\n /** \n * The constant indicating that a <tt>CallPeer</tt> has not yet transitioned into a state marking the beginning of a participation in a <tt>Call</tt> or that such a transition may have happened but the time of its occurrence is unknown.\n */\n public static final long CALL_DURATION_START_TIME_UNKNOWN=0;\n /** \n * The mute property name.\n */\n public static final String MUTE_PROPERTY_NAME=\"Mute\";\n /** \n * Adds a specific <tt>CallPeerConferenceListener</tt> to the list of listeners interested in and notified about changes in conference-related information such as this peer acting or not acting as a conference focus and conference membership details.\n * @param listener a <tt>CallPeerConferenceListener</tt> to be notified about changes in conference-related information. If the specified listener is already in the list of interested listeners (i.e. it has been previously added), it is not added again.\n */\n public void addCallPeerConferenceListener( CallPeerConferenceListener listener);\n /** \n * Allows the user interface to register a listener interested in changes\n * @param listener a listener instance to register with this peer.\n */\n public void addCallPeerListener( CallPeerListener listener);\n /** \n * Allows the user interface to register a listener interested in security status changes.\n * @param listener a listener instance to register with this peer\n */\n public void addCallPeerSecurityListener( CallPeerSecurityListener listener);\n /** \n * Adds a specific <tt>SoundLevelListener</tt> to the list of listeners interested in and notified about changes in conference members sound level.\n * @param listener the <tt>SoundLevelListener</tt> to add\n */\n public void addConferenceMembersSoundLevelListener( ConferenceMembersSoundLevelListener listener);\n /** \n * Allows the user interface to register a listener interested in property changes.\n * @param listener a property change listener instance to register with thispeer.\n */\n public void addPropertyChangeListener( PropertyChangeListener listener);\n /** \n * Adds a specific <tt>SoundLevelListener</tt> to the list of listeners interested in and notified about changes in stream sound level related information.\n * @param listener the <tt>SoundLevelListener</tt> to add\n */\n public void addStreamSoundLevelListener( SoundLevelListener listener);\n /** \n * Returns a String locator for that peer. A locator might be a SIP URI, an IP address or a telephone number.\n * @return the peer's address or phone number.\n */\n public String getAddress();\n /** \n * Returns a reference to the call that this peer belongs to.\n * @return a reference to the call containing this peer.\n */\n public Call getCall();\n /** \n * Gets the time at which this <tt>CallPeer</tt> transitioned into a state (likely {@link CallPeerState#CONNECTED}) marking the start of the duration of the participation in a <tt>Call</tt>.\n * @return the time at which this <tt>CallPeer</tt> transitionedinto a state marking the start of the duration of the participation in a <tt>Call</tt> or {@link #CALL_DURATION_START_TIME_UNKNOWN} if such a transitionhas not been performed\n */\n long getCallDurationStartTime();\n /** \n * Returns a URL pointing to a location with call control information or null if such an URL is not available for the current call peer.\n * @return a URL link to a location with call information or a call controlweb interface related to this peer or <tt>null</tt> if no such URL is available.\n */\n public URL getCallInfoURL();\n /** \n * Gets the number of <tt>ConferenceMember</tt>s currently known to this peer if it is acting as a conference focus.\n * @return the number of <tt>ConferenceMember</tt>s currently known tothis peer if it is acting as a conference focus. If this peer is not acting as a conference focus or it does but there are currently no members in the conference it manages, a value of zero is returned.\n */\n public int getConferenceMemberCount();\n /** \n * Gets the <tt>ConferenceMember</tt>s currently known to this peer if it is acting as a conference focus.\n * @return a <tt>List</tt> of <tt>ConferenceMember</tt>s describing themembers of a conference managed by this peer if it is acting as a conference focus. If this peer is not acting as a conference focus or it does but there are currently no members in the conference it manages, an empty <tt>List</tt> is returned.\n */\n public List<ConferenceMember> getConferenceMembers();\n /** \n * Returns the contact corresponding to this peer or null if no particular contact has been associated. <p>\n * @return the <tt>Contact</tt> corresponding to this peer or nullif no particular contact has been associated.\n */\n public Contact getContact();\n /** \n * Returns the currently used security settings of this <tt>CallPeer</tt>.\n * @return the <tt>CallPeerSecurityStatusEvent</tt> that contains thecurrent security settings.\n */\n public CallPeerSecurityStatusEvent getCurrentSecuritySettings();\n /** \n * Returns a human readable name representing this peer.\n * @return a String containing a name for that peer.\n */\n public String getDisplayName();\n /** \n * Returns an alternative IMPP address corresponding to this <tt>CallPeer</tt>.\n * @return a string representing an alternative IMPP address correspondingto this <tt>CallPeer</tt>\n */\n public String getAlternativeIMPPAddress();\n /** \n * The method returns an image representation of the call peer (e.g. a photo). Generally, the image representation is acquired from the underlying telephony protocol and is transferred over the network during call negotiation.\n * @return byte[] a byte array containing the image or null if no image isavailable.\n */\n public byte[] getImage();\n /** \n * Returns a unique identifier representing this peer. Identifiers returned by this method should remain unique across calls. In other words, if it returned the value of \"A\" for a given peer it should not return that same value for any other peer and return a different value even if the same person (address) is participating in another call. Values need not remain unique after restarting the program.\n * @return an identifier representing this call peer.\n */\n public String getPeerID();\n /** \n * Returns the protocol provider that this peer belongs to.\n * @return a reference to the ProtocolProviderService that this peerbelongs to.\n */\n public ProtocolProviderService getProtocolProvider();\n /** \n * Returns an object representing the current state of that peer. CallPeerState may vary among CONNECTING, RINGING, CALLING, BUSY, CONNECTED, and others, and it reflects the state of the connection between us and that peer.\n * @return a CallPeerState instance representing the peer'sstate.\n */\n public CallPeerState getState();\n /** \n * Returns full URI of the address. For example sip:user@domain.org or xmpp:user@domain.org.\n * @return full URI of the address\n */\n public String getURI();\n /** \n * Determines whether this peer is acting as a conference focus and thus may provide information about <tt>ConferenceMember</tt> such as {@link #getConferenceMembers()} and {@link #getConferenceMemberCount()}.\n * @return <tt>true</tt> if this peer is acting as a conferencefocus; <tt>false</tt>, otherwise\n */\n public boolean isConferenceFocus();\n /** \n * Determines whether the audio stream (if any) being sent to this peer is mute.\n * @return <tt>true</tt> if an audio stream is being sent to thispeer and it is currently mute; <tt>false</tt>, otherwise\n */\n public boolean isMute();\n /** \n * Removes a specific <tt>CallPeerConferenceListener</tt> from the list of listeners interested in and notified about changes in conference-related information such as this peer acting or not acting as a conference focus and conference membership details.\n * @param listener a <tt>CallPeerConferenceListener</tt> to no longer be notified about changes in conference-related information\n */\n public void removeCallPeerConferenceListener( CallPeerConferenceListener listener);\n /** \n * Unregisters the specified listener.\n * @param listener the listener to unregister.\n */\n public void removeCallPeerListener( CallPeerListener listener);\n /** \n * Unregisters the specified listener.\n * @param listener the listener to unregister\n */\n public void removeCallPeerSecurityListener( CallPeerSecurityListener listener);\n /** \n * Removes a specific <tt>SoundLevelListener</tt> of the list of listeners interested in and notified about changes in conference members sound level.\n * @param listener the <tt>SoundLevelListener</tt> toremove\n */\n public void removeConferenceMembersSoundLevelListener( ConferenceMembersSoundLevelListener listener);\n /** \n * Unregisters the specified property change listener.\n * @param listener the property change listener to unregister.\n */\n public void removePropertyChangeListener( PropertyChangeListener listener);\n /** \n * Removes a specific <tt>SoundLevelListener</tt> of the list of listeners interested in and notified about changes in stream sound level related information.\n * @param listener the <tt>SoundLevelListener</tt> to remove\n */\n public void removeStreamSoundLevelListener( SoundLevelListener listener);\n /** \n * Returns a string representation of the peer in the form of <br> Display Name <address>;status=CallPeerStatus\n * @return a string representation of the peer and its state.\n */\n public String toString();\n}\n", "raw_body_no_cmt": "public interface CallPeer {\n public static final long CALL_DURATION_START_TIME_UNKNOWN=0;\n public static final String MUTE_PROPERTY_NAME=\"Mute\";\n public void addCallPeerConferenceListener( CallPeerConferenceListener listener);\n public void addCallPeerListener( CallPeerListener listener);\n public void addCallPeerSecurityListener( CallPeerSecurityListener listener);\n public void addConferenceMembersSoundLevelListener( ConferenceMembersSoundLevelListener listener);\n public void addPropertyChangeListener( PropertyChangeListener listener);\n public void addStreamSoundLevelListener( SoundLevelListener listener);\n public String getAddress();\n public Call getCall();\n long getCallDurationStartTime();\n public URL getCallInfoURL();\n public int getConferenceMemberCount();\n public List<ConferenceMember> getConferenceMembers();\n public Contact getContact();\n public CallPeerSecurityStatusEvent getCurrentSecuritySettings();\n public String getDisplayName();\n public String getAlternativeIMPPAddress();\n public byte[] getImage();\n public String getPeerID();\n public ProtocolProviderService getProtocolProvider();\n public CallPeerState getState();\n public String getURI();\n public boolean isConferenceFocus();\n public boolean isMute();\n public void removeCallPeerConferenceListener( CallPeerConferenceListener listener);\n public void removeCallPeerListener( CallPeerListener listener);\n public void removeCallPeerSecurityListener( CallPeerSecurityListener listener);\n public void removeConferenceMembersSoundLevelListener( ConferenceMembersSoundLevelListener listener);\n public void removePropertyChangeListener( PropertyChangeListener listener);\n public void removeStreamSoundLevelListener( SoundLevelListener listener);\n public String toString();\n}\n"}}, {"CallPeerSecurityTimeoutEvent": {"retrieved_name": "CallPeerSecurityTimeoutEvent", "raw_body": "/** \n * The <tt>CallPeerSecurityTimeoutEvent</tt> is triggered whenever a communication with a given peer cannot be established, the peer did not answer our tries to secure the connection.\n * @author Damian Minkov\n */\npublic class CallPeerSecurityTimeoutEvent extends CallPeerSecurityStatusEvent {\n /** \n * Serial version UID.\n */\n private static final long serialVersionUID=0L;\n /** \n * The event constructor\n * @param callPeer the call peer associated with this event\n * @param sessionType the type of the session, either{@link CallPeerSecurityStatusEvent#AUDIO_SESSION} or{@link CallPeerSecurityStatusEvent#VIDEO_SESSION}\n */\n public CallPeerSecurityTimeoutEvent( CallPeer callPeer, int sessionType);\n}\n", "raw_body_no_cmt": "public class CallPeerSecurityTimeoutEvent extends CallPeerSecurityStatusEvent {\n private static final long serialVersionUID=0L;\n public CallPeerSecurityTimeoutEvent( CallPeer callPeer, int sessionType);\n}\n"}}] | [{"getNewValue": {"retrieved_name": "getNewValue", "raw_body": "/** \n * Gets the new value for the event, expressed as an Object.\n * @return The new value for the event, expressed as an Object.\n */\npublic Object getNewValue(){\n return newValue;\n}\n"}}, {"getPropertyName": {"retrieved_name": "getPropertyName", "raw_body": "/** \n * Returns the property name of individual replacement sources\n * @param source the replacement source name.\n * @return the property name of the specified source as will be stored inthe properties file.\n */\npublic static String getPropertyName(String source){\n return \"net.java.sip.communicator.service.replacement.\" + source + \".enable\";\n}\n"}}, {"getSource": {"retrieved_name": "getSource", "raw_body": "public Object getSource(){\n return getWindow();\n}\n"}}, {"equals": {"retrieved_name": "equals", "raw_body": "@Override public boolean equals(Object obj){\n if (obj instanceof ChatAttachments) return this.chat.equals(((ChatAttachments)obj).chat);\n else return false;\n}\n"}}, {"setPeerProperty": {"retrieved_name": "setPeerName", "raw_body": "/** \n * Sets the name of the peer.\n * @param name the name of the peer\n */\npublic void setPeerName(String name){\n setParticipantName(name);\n}\n"}}] | [{"propertyChange": {"retrieved_name": "propertyChange", "raw_body": "/** \n * {@inheritDoc}Invokes {@link #onEventObject(EventObject)}.\n */\npublic void propertyChange(PropertyChangeEvent ev){\n String propertyName=ev.getPropertyName();\n if (propertyName.equals(CallConference.CALLS)) {\n onEventObject(ev);\n }\n else if (propertyName.equals(CallContainer.PROP_FULL_SCREEN)) {\n if (ev.getSource().equals(callWindow.getFrame())) {\n try {\n onEventObject(ev);\n }\n finally {\n callWindowPropertyChange(ev);\n }\n }\n }\n}\n"}}] |
YunaiV_ruoyi-vue-pro | ruoyi-vue-pro/yudao-framework/yudao-spring-boot-starter-mybatis/src/main/java/cn/iocoder/yudao/framework/datasource/core/filter/DruidAdRemoveFilter.java | DruidAdRemoveFilter | doFilterInternal | class DruidAdRemoveFilter extends OncePerRequestFilter {
/**
* common.js 的路径
*/
private static final String COMMON_JS_ILE_PATH = "support/http/resources/js/common.js";
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {<FILL_FUNCTION_BODY>}
} |
chain.doFilter(request, response);
// 重置缓冲区,响应头不会被重置
response.resetBuffer();
// 获取 common.js
String text = Utils.readFromResource(COMMON_JS_ILE_PATH);
// 正则替换 banner, 除去底部的广告信息
text = text.replaceAll("<a.*?banner\"></a><br/>", "");
text = text.replaceAll("powered.*?shrek.wang</a>", "");
response.getWriter().write(text);
|
chain.doFilter(request, response);
String path = request.getRequestURI();
if (path.endsWith(COMMON_JS_ILE_PATH)) {
String content = IOUtils.toString(request.getInputStream(), StandardCharsets.UTF_8);
content = content.replaceAll("<script>", "<script>\n" + "window.ad_remove_filter = true;");
response.setContentType("application/javascript;charset=utf-8");
response.getWriter().write(content);
}
| [
"HttpServletRequest",
"FilterChain",
"HttpServletResponse"
] | [
"endsWith",
"doFilter",
"write",
"getRequestURI",
"toString",
"getInputStream",
"getWriter",
"replaceAll",
"setContentType"
] | [
"FilterChain",
"HttpServletResponse",
"HttpServletRequest"
] | [
"replaceAll",
"doFilter",
"write",
"readFromResource",
"resetBuffer",
"getWriter"
] | {
"methods": [
"endsWith",
"doFilter",
"write",
"getRequestURI",
"toString",
"getInputStream",
"getWriter",
"replaceAll",
"setContentType"
],
"similar_methods": [
"doFilterInternal"
],
"types": [
"HttpServletRequest",
"FilterChain",
"HttpServletResponse"
]
} | /**
* 服务器异常 Exception
*/
@Data @EqualsAndHashCode(callSuper=true) public final class ServerException extends RuntimeException {
/**
* 全局错误码
* @see GlobalErrorCodeConstants
*/
private Integer code;
/**
* 错误提示
*/
private String message;
/**
* 空构造方法,避免反序列化问题
*/
public ServerException();
public ServerException( ErrorCode errorCode);
public ServerException( Integer code, String message);
public Integer getCode();
public ServerException setCode( Integer code);
@Override public String getMessage();
public ServerException setMessage( String message);
}
/**
* Trace 过滤器,打印 traceId 到 header 中返回
* @author 芋道源码
*/
public class TraceFilter extends OncePerRequestFilter {
/**
* Header 名 - 链路追踪编号
*/
private static final String HEADER_NAME_TRACE_ID="trace-id";
@Override protected void doFilterInternal( HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException;
}
/**
* 公众号的自动回复 Service 接口
* @author 芋道源码
*/
public interface MpAutoReplyService {
/**
* 获得公众号自动回复分页
* @param pageVO 分页请求
* @return 自动回复分页结果
*/
PageResult<MpAutoReplyDO> getAutoReplyPage( MpMessagePageReqVO pageVO);
/**
* 获得公众号自动回复
* @param id 编号
* @return 自动回复
*/
MpAutoReplyDO getAutoReply( Long id);
/**
* 创建公众号自动回复
* @param createReqVO 创建请求
* @return 自动回复的编号
*/
Long createAutoReply( MpAutoReplyCreateReqVO createReqVO);
/**
* 更新公众号自动回复
* @param updateReqVO 更新请求
*/
void updateAutoReply( MpAutoReplyUpdateReqVO updateReqVO);
/**
* 删除公众号自动回复
* @param id 自动回复的编号
*/
void deleteAutoReply( Long id);
/**
* 当收到消息时,自动回复
* @param appId 微信公众号 appId
* @param wxMessage 消息
* @return 回复的消息
*/
WxMpXmlOutMessage replyForMessage( String appId, WxMpXmlMessage wxMessage);
/**
* 当粉丝关注时,自动回复
* @param appId 微信公众号 appId
* @param wxMessage 消息
* @return 回复的消息
*/
WxMpXmlOutMessage replyForSubscribe( String appId, WxMpXmlMessage wxMessage);
}
/**
* 获取指定日期所在的月份的最后时间 例如:2023-09-30 23:59:59,999
* @param date 日期
* @return 月份的结束时间
*/
public static LocalDateTime endOfMonth(LocalDateTime date){
return date.with(TemporalAdjusters.lastDayOfMonth()).with(LocalTime.MAX);
}
@Override protected void doFilterInternal(HttpServletRequest request,HttpServletResponse response,FilterChain chain){
ServletUtils.writeJSON(response,CommonResult.error(DEMO_DENY));
}
public static void write(HttpServletResponse response,String text,String contentType){
ServletUtil.write(response,text,contentType);
}
/**
* 获得请求
* @return HttpServletRequest
*/
public static HttpServletRequest getRequest(){
RequestAttributes requestAttributes=RequestContextHolder.getRequestAttributes();
if (!(requestAttributes instanceof ServletRequestAttributes)) {
return null;
}
return ((ServletRequestAttributes)requestAttributes).getRequest();
}
@SneakyThrows public static String toJsonString(Object object){
return objectMapper.writeValueAsString(object);
}
@Override public ServletInputStream getInputStream() throws IOException {
final ByteArrayInputStream inputStream=new ByteArrayInputStream(body);
return new ServletInputStream(){
@Override public int read(){
return inputStream.read();
}
@Override public boolean isFinished(){
return false;
}
@Override public boolean isReady(){
return false;
}
@Override public void setReadListener( ReadListener readListener){
}
@Override public int available(){
return body.length;
}
}
;
}
@Override public MemberUserRespDTO getUser(Long id){
MemberUserDO user=userService.getUser(id);
return MemberUserConvert.INSTANCE.convert2(user);
}
@Override String getReplacer(SliderDesensitize annotation){
return annotation.replacer();
}
public AbstractEngineConfiguration setDatabaseType(String databaseType){
this.databaseType=databaseType;
return this;
}
@Override protected void doFilterInternal(HttpServletRequest request,HttpServletResponse response,FilterChain chain){
ServletUtils.writeJSON(response,CommonResult.error(DEMO_DENY));
}
| public final class ServerException extends RuntimeException {
private Integer code;
private String message;
public ServerException();
public ServerException( ErrorCode errorCode);
public ServerException( Integer code, String message);
public Integer getCode();
public ServerException setCode( Integer code);
public String getMessage();
public ServerException setMessage( String message);
}
public class TraceFilter extends OncePerRequestFilter {
private static final String HEADER_NAME_TRACE_ID="trace-id";
protected void doFilterInternal( HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException;
}
public interface MpAutoReplyService {
PageResult<MpAutoReplyDO> getAutoReplyPage( MpMessagePageReqVO pageVO);
MpAutoReplyDO getAutoReply( Long id);
Long createAutoReply( MpAutoReplyCreateReqVO createReqVO);
void updateAutoReply( MpAutoReplyUpdateReqVO updateReqVO);
void deleteAutoReply( Long id);
WxMpXmlOutMessage replyForMessage( String appId, WxMpXmlMessage wxMessage);
WxMpXmlOutMessage replyForSubscribe( String appId, WxMpXmlMessage wxMessage);
}
/**
* 获取指定日期所在的月份的最后时间 例如:2023-09-30 23:59:59,999
* @param date 日期
* @return 月份的结束时间
*/
public static LocalDateTime endOfMonth(LocalDateTime date){
return date.with(TemporalAdjusters.lastDayOfMonth()).with(LocalTime.MAX);
}
@Override protected void doFilterInternal(HttpServletRequest request,HttpServletResponse response,FilterChain chain){
ServletUtils.writeJSON(response,CommonResult.error(DEMO_DENY));
}
public static void write(HttpServletResponse response,String text,String contentType){
ServletUtil.write(response,text,contentType);
}
/**
* 获得请求
* @return HttpServletRequest
*/
public static HttpServletRequest getRequest(){
RequestAttributes requestAttributes=RequestContextHolder.getRequestAttributes();
if (!(requestAttributes instanceof ServletRequestAttributes)) {
return null;
}
return ((ServletRequestAttributes)requestAttributes).getRequest();
}
@SneakyThrows public static String toJsonString(Object object){
return objectMapper.writeValueAsString(object);
}
@Override public ServletInputStream getInputStream() throws IOException {
final ByteArrayInputStream inputStream=new ByteArrayInputStream(body);
return new ServletInputStream(){
@Override public int read(){
return inputStream.read();
}
@Override public boolean isFinished(){
return false;
}
@Override public boolean isReady(){
return false;
}
@Override public void setReadListener( ReadListener readListener){
}
@Override public int available(){
return body.length;
}
}
;
}
@Override public MemberUserRespDTO getUser(Long id){
MemberUserDO user=userService.getUser(id);
return MemberUserConvert.INSTANCE.convert2(user);
}
@Override String getReplacer(SliderDesensitize annotation){
return annotation.replacer();
}
public AbstractEngineConfiguration setDatabaseType(String databaseType){
this.databaseType=databaseType;
return this;
}
@Override protected void doFilterInternal(HttpServletRequest request,HttpServletResponse response,FilterChain chain){
ServletUtils.writeJSON(response,CommonResult.error(DEMO_DENY));
}
| {"types": [{"HttpServletRequest": "ServerException"}, {"FilterChain": "TraceFilter"}, {"HttpServletResponse": "MpAutoReplyService"}], "methods": [{"endsWith": "endOfMonth"}, {"doFilter": "doFilterInternal"}, {"write": "write"}, {"getRequestURI": "getRequest"}, {"toString": "toJsonString"}, {"getInputStream": "getInputStream"}, {"getWriter": "getUser"}, {"replaceAll": "getReplacer"}, {"setContentType": "setDatabaseType"}], "similar_methods": [{"doFilterInternal": "doFilterInternal"}]} | [{"HttpServletRequest": {"retrieved_name": "ServerException", "raw_body": "/** \n * \u670d\u52a1\u5668\u5f02\u5e38 Exception\n */\n@Data @EqualsAndHashCode(callSuper=true) public final class ServerException extends RuntimeException {\n /** \n * \u5168\u5c40\u9519\u8bef\u7801\n * @see GlobalErrorCodeConstants\n */\n private Integer code;\n /** \n * \u9519\u8bef\u63d0\u793a\n */\n private String message;\n /** \n * \u7a7a\u6784\u9020\u65b9\u6cd5\uff0c\u907f\u514d\u53cd\u5e8f\u5217\u5316\u95ee\u9898\n */\n public ServerException();\n public ServerException( ErrorCode errorCode);\n public ServerException( Integer code, String message);\n public Integer getCode();\n public ServerException setCode( Integer code);\n @Override public String getMessage();\n public ServerException setMessage( String message);\n}\n", "raw_body_no_cmt": "public final class ServerException extends RuntimeException {\n private Integer code;\n private String message;\n public ServerException();\n public ServerException( ErrorCode errorCode);\n public ServerException( Integer code, String message);\n public Integer getCode();\n public ServerException setCode( Integer code);\n public String getMessage();\n public ServerException setMessage( String message);\n}\n"}}, {"FilterChain": {"retrieved_name": "TraceFilter", "raw_body": "/** \n * Trace \u8fc7\u6ee4\u5668\uff0c\u6253\u5370 traceId \u5230 header \u4e2d\u8fd4\u56de\n * @author \u828b\u9053\u6e90\u7801\n */\npublic class TraceFilter extends OncePerRequestFilter {\n /** \n * Header \u540d - \u94fe\u8def\u8ffd\u8e2a\u7f16\u53f7\n */\n private static final String HEADER_NAME_TRACE_ID=\"trace-id\";\n @Override protected void doFilterInternal( HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException;\n}\n", "raw_body_no_cmt": "public class TraceFilter extends OncePerRequestFilter {\n private static final String HEADER_NAME_TRACE_ID=\"trace-id\";\n protected void doFilterInternal( HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException;\n}\n"}}, {"HttpServletResponse": {"retrieved_name": "MpAutoReplyService", "raw_body": "/** \n * \u516c\u4f17\u53f7\u7684\u81ea\u52a8\u56de\u590d Service \u63a5\u53e3\n * @author \u828b\u9053\u6e90\u7801\n */\npublic interface MpAutoReplyService {\n /** \n * \u83b7\u5f97\u516c\u4f17\u53f7\u81ea\u52a8\u56de\u590d\u5206\u9875\n * @param pageVO \u5206\u9875\u8bf7\u6c42\n * @return \u81ea\u52a8\u56de\u590d\u5206\u9875\u7ed3\u679c\n */\n PageResult<MpAutoReplyDO> getAutoReplyPage( MpMessagePageReqVO pageVO);\n /** \n * \u83b7\u5f97\u516c\u4f17\u53f7\u81ea\u52a8\u56de\u590d\n * @param id \u7f16\u53f7\n * @return \u81ea\u52a8\u56de\u590d\n */\n MpAutoReplyDO getAutoReply( Long id);\n /** \n * \u521b\u5efa\u516c\u4f17\u53f7\u81ea\u52a8\u56de\u590d\n * @param createReqVO \u521b\u5efa\u8bf7\u6c42\n * @return \u81ea\u52a8\u56de\u590d\u7684\u7f16\u53f7\n */\n Long createAutoReply( MpAutoReplyCreateReqVO createReqVO);\n /** \n * \u66f4\u65b0\u516c\u4f17\u53f7\u81ea\u52a8\u56de\u590d\n * @param updateReqVO \u66f4\u65b0\u8bf7\u6c42\n */\n void updateAutoReply( MpAutoReplyUpdateReqVO updateReqVO);\n /** \n * \u5220\u9664\u516c\u4f17\u53f7\u81ea\u52a8\u56de\u590d\n * @param id \u81ea\u52a8\u56de\u590d\u7684\u7f16\u53f7\n */\n void deleteAutoReply( Long id);\n /** \n * \u5f53\u6536\u5230\u6d88\u606f\u65f6\uff0c\u81ea\u52a8\u56de\u590d\n * @param appId \u5fae\u4fe1\u516c\u4f17\u53f7 appId\n * @param wxMessage \u6d88\u606f\n * @return \u56de\u590d\u7684\u6d88\u606f\n */\n WxMpXmlOutMessage replyForMessage( String appId, WxMpXmlMessage wxMessage);\n /** \n * \u5f53\u7c89\u4e1d\u5173\u6ce8\u65f6\uff0c\u81ea\u52a8\u56de\u590d\n * @param appId \u5fae\u4fe1\u516c\u4f17\u53f7 appId\n * @param wxMessage \u6d88\u606f\n * @return \u56de\u590d\u7684\u6d88\u606f\n */\n WxMpXmlOutMessage replyForSubscribe( String appId, WxMpXmlMessage wxMessage);\n}\n", "raw_body_no_cmt": "public interface MpAutoReplyService {\n PageResult<MpAutoReplyDO> getAutoReplyPage( MpMessagePageReqVO pageVO);\n MpAutoReplyDO getAutoReply( Long id);\n Long createAutoReply( MpAutoReplyCreateReqVO createReqVO);\n void updateAutoReply( MpAutoReplyUpdateReqVO updateReqVO);\n void deleteAutoReply( Long id);\n WxMpXmlOutMessage replyForMessage( String appId, WxMpXmlMessage wxMessage);\n WxMpXmlOutMessage replyForSubscribe( String appId, WxMpXmlMessage wxMessage);\n}\n"}}] | [{"endsWith": {"retrieved_name": "endOfMonth", "raw_body": "/** \n * \u83b7\u53d6\u6307\u5b9a\u65e5\u671f\u6240\u5728\u7684\u6708\u4efd\u7684\u6700\u540e\u65f6\u95f4 \u4f8b\u5982\uff1a2023-09-30 23:59:59,999\n * @param date \u65e5\u671f\n * @return \u6708\u4efd\u7684\u7ed3\u675f\u65f6\u95f4\n */\npublic static LocalDateTime endOfMonth(LocalDateTime date){\n return date.with(TemporalAdjusters.lastDayOfMonth()).with(LocalTime.MAX);\n}\n"}}, {"doFilter": {"retrieved_name": "doFilterInternal", "raw_body": "@Override protected void doFilterInternal(HttpServletRequest request,HttpServletResponse response,FilterChain chain){\n ServletUtils.writeJSON(response,CommonResult.error(DEMO_DENY));\n}\n"}}, {"write": {"retrieved_name": "write", "raw_body": "public static void write(HttpServletResponse response,String text,String contentType){\n ServletUtil.write(response,text,contentType);\n}\n"}}, {"getRequestURI": {"retrieved_name": "getRequest", "raw_body": "/** \n * \u83b7\u5f97\u8bf7\u6c42\n * @return HttpServletRequest\n */\npublic static HttpServletRequest getRequest(){\n RequestAttributes requestAttributes=RequestContextHolder.getRequestAttributes();\n if (!(requestAttributes instanceof ServletRequestAttributes)) {\n return null;\n }\n return ((ServletRequestAttributes)requestAttributes).getRequest();\n}\n"}}, {"toString": {"retrieved_name": "toJsonString", "raw_body": "@SneakyThrows public static String toJsonString(Object object){\n return objectMapper.writeValueAsString(object);\n}\n"}}, {"getInputStream": {"retrieved_name": "getInputStream", "raw_body": "@Override public ServletInputStream getInputStream() throws IOException {\n final ByteArrayInputStream inputStream=new ByteArrayInputStream(body);\n return new ServletInputStream(){\n @Override public int read(){\n return inputStream.read();\n }\n @Override public boolean isFinished(){\n return false;\n }\n @Override public boolean isReady(){\n return false;\n }\n @Override public void setReadListener( ReadListener readListener){\n }\n @Override public int available(){\n return body.length;\n }\n }\n;\n}\n"}}, {"getWriter": {"retrieved_name": "getUser", "raw_body": "@Override public MemberUserRespDTO getUser(Long id){\n MemberUserDO user=userService.getUser(id);\n return MemberUserConvert.INSTANCE.convert2(user);\n}\n"}}, {"replaceAll": {"retrieved_name": "getReplacer", "raw_body": "@Override String getReplacer(SliderDesensitize annotation){\n return annotation.replacer();\n}\n"}}, {"setContentType": {"retrieved_name": "setDatabaseType", "raw_body": "public AbstractEngineConfiguration setDatabaseType(String databaseType){\n this.databaseType=databaseType;\n return this;\n}\n"}}] | [{"doFilterInternal": {"retrieved_name": "doFilterInternal", "raw_body": "@Override protected void doFilterInternal(HttpServletRequest request,HttpServletResponse response,FilterChain chain){\n ServletUtils.writeJSON(response,CommonResult.error(DEMO_DENY));\n}\n"}}] |
|
mapstruct_mapstruct | mapstruct/processor/src/main/java/org/mapstruct/ap/internal/processor/Jsr330ComponentProcessor.java | Jsr330ComponentProcessor | getTypeAnnotations | class Jsr330ComponentProcessor extends AnnotationBasedComponentModelProcessor {
@Override
protected String getComponentModelIdentifier() {
return MappingConstantsGem.ComponentModelGem.JSR330;
}
@Override
protected List<Annotation> getTypeAnnotations(Mapper mapper) {<FILL_FUNCTION_BODY>}
@Override
protected List<Annotation> getDecoratorAnnotations() {
return Arrays.asList( singleton(), named() );
}
@Override
protected List<Annotation> getDelegatorReferenceAnnotations(Mapper mapper) {
return Arrays.asList( inject(), namedDelegate( mapper ) );
}
@Override
protected List<Annotation> getMapperReferenceAnnotations() {
return Collections.singletonList( inject() );
}
@Override
protected boolean requiresGenerationOfDecoratorClass() {
return true;
}
private Annotation singleton() {
return new Annotation( getType( "Singleton" ) );
}
private Annotation named() {
return new Annotation( getType( "Named" ) );
}
private Annotation namedDelegate(Mapper mapper) {
return new Annotation(
getType( "Named" ),
Collections.singletonList(
new AnnotationElement(
AnnotationElementType.STRING,
Collections.singletonList( mapper.getPackageName() + "." + mapper.getName() )
) )
);
}
private Annotation inject() {
return new Annotation( getType( "Inject" ) );
}
private Type getType(String simpleName) {
if ( getTypeFactory().isTypeAvailable( "javax.inject." + simpleName ) ) {
return getTypeFactory().getType( "javax.inject." + simpleName );
}
if ( getTypeFactory().isTypeAvailable( "jakarta.inject." + simpleName ) ) {
return getTypeFactory().getType( "jakarta.inject." + simpleName );
}
throw new AnnotationProcessingException(
"Couldn't find any of the JSR330 or Jakarta Dependency Inject types." +
" Are you missing a dependency on your classpath?" );
}
} |
if ( mapper.getDecorator() == null ) {
return Arrays.asList( singleton(), named() );
}
else {
return Arrays.asList( singleton(), namedDelegate( mapper ) );
}
| /**
* An {@link ModelElementProcessor} which converts the given {@link Mapper} object into an annotation based componentmodel in case a matching model is selected as target component model for this mapper.
* @author Gunnar Morling
* @author Andreas Gudian
* @author Kevin Grüneberg
*/
public abstract class AnnotationBasedComponentModelProcessor implements ModelElementProcessor<Mapper,Mapper> {
private TypeFactory typeFactory;
@Override public Mapper process( ProcessorContext context, TypeElement mapperTypeElement, Mapper mapper);
protected void adjustDecorator( Mapper mapper, InjectionStrategyGem injectionStrategy);
private List<MapperReference> toMapperReferences( List<Field> fields);
private void buildSetters( Mapper mapper);
private void buildConstructors( Mapper mapper);
private AnnotatedConstructor buildAnnotatedConstructorForMapper( Mapper mapper);
private AnnotatedConstructor buildAnnotatedConstructorForDecorator( Decorator decorator);
/**
* Removes duplicate constructor parameter annotations. If an annotation is already present on the constructor, it does not have be defined on the constructor parameter, too. For example, for CDI, the javax.inject.Inject annotation is on the constructor and does not need to be on the constructor parameters.
* @param annotationMapperReferences annotations to annotate the constructor parameter with
* @param mapperReferenceAnnotations annotations to annotate the constructor with
*/
private void removeDuplicateAnnotations( List<AnnotationMapperReference> annotationMapperReferences, List<Annotation> mapperReferenceAnnotations);
/**
* Extract all annotations from {@code annotations} that do not have a type in {@code annotationTypes}.
* @param annotations the annotations from which we need to extract information
* @param annotationTypes the annotation types to ignore
* @return the annotations that are not in the {@code annotationTypes}
*/
private List<Annotation> extractMissingAnnotations( List<Annotation> annotations, Set<Type> annotationTypes);
protected boolean additionalPublicEmptyConstructor();
protected List<Annotation> getDelegatorReferenceAnnotations( Mapper mapper);
/**
* @param originalReference the reference to be replaced
* @param annotations the list of annotations
* @param injectionStrategy strategy for injection
* @return the mapper reference replacing the original one
*/
protected Field replacementMapperReference( Field originalReference, List<Annotation> annotations, InjectionStrategyGem injectionStrategy);
/**
* @return the component model identifier
*/
protected abstract String getComponentModelIdentifier();
/**
* @param mapper the mapper
* @return the annotation(s) to be added at the mapper type implementation
*/
protected abstract List<Annotation> getTypeAnnotations( Mapper mapper);
/**
* @return the annotation(s) to be added at the decorator of the mapper
*/
protected List<Annotation> getDecoratorAnnotations();
/**
* @return the annotation of the field for the mapper reference
*/
protected abstract List<Annotation> getMapperReferenceAnnotations();
/**
* @return if a decorator (sub-)class needs to be generated or not
*/
protected abstract boolean requiresGenerationOfDecoratorClass();
@Override public int getPriority();
protected TypeFactory getTypeFactory();
}
|
return Arrays.asList( singleton(), named() );
| [
"Mapper"
] | [
"asList"
] | [
"Mapper"
] | [
"asList",
"getDecorator"
] | {
"methods": [
"asList"
],
"similar_methods": [
"getTypeAnnotations"
],
"types": [
"Mapper"
]
} | /**
* Marks an interface or abstract class as a mapper and activates the generation of a implementation of that type via MapStruct. <p> <strong>Example 1:</strong> Creating mapper </p> <pre><code class='java'> @Mapper public interface CarMapper { CarDto toCarDto(Car source); } </code></pre> <p> <strong>Example 2:</strong> Use additional mappers with parameters {@link #uses()}, {@link #componentModel()}and {@link #injectionStrategy()}</p> <pre><code class='java'> // we have MarkMapper (map field "mark" to field "name" to upper case) @Mapper(componentModel = MappingConstants.ComponentModel.SPRING) public class MarkMapper { public String mapMark(String mark) { return mark.toUpperCase(); } } // we have CarMapper @Mapper( componentModel = MappingConstants.ComponentModel.SPRING, uses = MarkMapper.class, injectionStrategy = InjectionStrategy.CONSTRUCTOR) public interface CarMapper { @Mapping(target = "name", source = "mark") CarDto convertMap(CarEntity carEntity); } </code></pre> <pre><code class='java'> // generates @Component public class CarMapperImpl implements CarMapper { private final MarkMapper markMapper; @Autowired public CarMapperImpl(MarkMapper markMapper) { this.markMapper = markMapper; } @Override public CarDto convertMap(CarEntity carEntity) { if ( carEntity == null ) { return null; } CarDto carDto = new CarDto(); carDto.setName( markMapper.mapMark( carEntity.getMark() ) ); return carDto; } } </code></pre>
* @author Gunnar Morling
* @see Javadoc
*/
@Target(ElementType.TYPE) @Retention(RetentionPolicy.CLASS) public @interface Mapper {/**
* Other mapper types used by this mapper. May be hand-written classes or other mappers generated by MapStruct. No cycle between generated mapper classes must be created.
* @return The mapper types used by this mapper.
*/
Class<?>[] uses() default {};
/**
* Additional types for which an import statement is to be added to the generated mapper implementation class. This allows to refer to those types from within mapping expressions given via {@link Mapping#expression()}, {@link Mapping#defaultExpression()} or usingtheir simple name rather than their fully-qualified name.
* @return classes to add in the imports of the generated implementation.
*/
Class<?>[] imports() default {};
/**
* How unmapped properties of the source type of a mapping should be reported. The method overrides an unmappedSourcePolicy set in a central configuration set by {@link #config() }
* @return The reporting policy for unmapped source properties.
* @since 1.3
*/
ReportingPolicy unmappedSourcePolicy() default ReportingPolicy.IGNORE;
/**
* How unmapped properties of the target type of a mapping should be reported. The method overrides an unmappedTargetPolicy set in a central configuration set by {@link #config() }
* @return The reporting policy for unmapped target properties.
*/
ReportingPolicy unmappedTargetPolicy() default ReportingPolicy.WARN;
/**
* How lossy (narrowing) conversion, for instance long to integer should be reported. The method overrides an typeConversionPolicy set in a central configuration set by {@link #config() }
* @since 1.3
* @return The reporting policy for unmapped target properties.
*/
ReportingPolicy typeConversionPolicy() default ReportingPolicy.IGNORE;
/**
* Specifies the component model to which the generated mapper should adhere. Supported values are <ul> <li> {@code default}: the mapper uses no component model, instances are typically retrieved via {@link Mappers#getMapper(Class)}</li> <li> {@code cdi}: the generated mapper is an application-scoped CDI bean and can be retrieved via {@code @Inject}</li> <li> {@code spring}: the generated mapper is a Spring bean and can be retrieved via {@code @Autowired}</li> <li> {@code jsr330}: the generated mapper is annotated with {@code @javax.inject.Named} and{@code @Singleton}, and can be retrieved via {@code @Inject}. The annotations will either be from javax.inject or jakarta.inject, depending on which one is available, with javax.inject having precedence.</li> <li> {@code jakarta}: the generated mapper is annotated with {@code @jakarta.inject.Named} and{@code @Singleton}, and can be retrieved via {@code @Inject}.</li> </ul> The method overrides a componentModel set in a central configuration set by {@link #config() }
* @return The component model for the generated mapper.
*/
String componentModel() default MappingConstants.ComponentModel.DEFAULT;
/**
* Specifies the name of the implementation class. The {@code <CLASS_NAME>} will be replaced by theinterface/abstract class name. <p> Defaults to postfixing the name with {@code Impl}: {@code <CLASS_NAME>Impl}
* @return The implementation name.
* @see #implementationPackage()
*/
String implementationName() default "<CLASS_NAME>Impl";
/**
* Specifies the target package for the generated implementation. The {@code <PACKAGE_NAME>} will be replaced by theinterface's or abstract class' package. <p> Defaults to using the same package as the mapper interface/abstract class
* @return the implementation package.
* @see #implementationName()
*/
String implementationPackage() default "<PACKAGE_NAME>";
/**
* A class annotated with {@link MapperConfig} which should be used as configuration template. Any settings givenvia {@link Mapper} will take precedence over the settings from the referenced configuration source. The list ofreferenced mappers will contain all mappers given via {@link Mapper#uses()} and {@link MapperConfig#uses()}.
* @return A class which should be used as configuration template.
*/
Class<?> config() default void.class;
/**
* The strategy to be applied when propagating the value of collection-typed properties. By default, only JavaBeans accessor methods (setters or getters) will be used, but it is also possible to invoke a corresponding adder method for each element of the source collection (e.g. {@code orderDto.addOrderLine()}). <p> Any setting given for this attribute will take precedence over {@link MapperConfig#collectionMappingStrategy()}, if present.
* @return The strategy applied when propagating the value of collection-typed properties.
*/
CollectionMappingStrategy collectionMappingStrategy() default CollectionMappingStrategy.ACCESSOR_ONLY;
/**
* The strategy to be applied when {@code null} is passed as source argument value to the methods of this mapper.If no strategy is configured, the strategy given via {@link MapperConfig#nullValueMappingStrategy()} will beapplied, using {@link NullValueMappingStrategy#RETURN_NULL} by default.
* @return The strategy to be applied when {@code null} is passed as source value to the methods of this mapper.
*/
NullValueMappingStrategy nullValueMappingStrategy() default NullValueMappingStrategy.RETURN_NULL;
/**
* The strategy to be applied when {@code null} is passed as source argument value to an {@link IterableMapping} ofthis mapper. If unset, the strategy set with {@link #nullValueMappingStrategy()} will be applied. If neitherstrategy is configured, the strategy given via {@link MapperConfig#nullValueIterableMappingStrategy()} will beapplied, using {@link NullValueMappingStrategy#RETURN_NULL} by default.
* @since 1.5
* @return The strategy to be applied when {@code null} is passed as source value to an {@link IterableMapping} ofthis mapper.
*/
NullValueMappingStrategy nullValueIterableMappingStrategy() default NullValueMappingStrategy.RETURN_NULL;
/**
* The strategy to be applied when {@code null} is passed as source argument value to a {@link MapMapping} of thismapper. If unset, the strategy set with {@link #nullValueMappingStrategy()} will be applied. If neither strategyis configured, the strategy given via {@link MapperConfig#nullValueMapMappingStrategy()} will be applied, using{@link NullValueMappingStrategy#RETURN_NULL} by default.
* @since 1.5
* @return The strategy to be applied when {@code null} is passed as source value to a {@link MapMapping} of thismapper.
*/
NullValueMappingStrategy nullValueMapMappingStrategy() default NullValueMappingStrategy.RETURN_NULL;
/**
* The strategy to be applied when a source bean property is {@code null} or not present. If no strategy isconfigured, the strategy given via {@link MapperConfig#nullValuePropertyMappingStrategy()} will be applied,{@link NullValuePropertyMappingStrategy#SET_TO_NULL} will be used by default.
* @since 1.3
* @return The strategy to be applied when {@code null} is passed as source property value or the source propertyis not present.
*/
NullValuePropertyMappingStrategy nullValuePropertyMappingStrategy() default NullValuePropertyMappingStrategy.SET_TO_NULL;
/**
* The strategy to use for applying method-level configuration annotations of prototype methods in the interface specified with {@link #config()}. Annotations that can be inherited are for example {@link Mapping}, {@link IterableMapping}, {@link MapMapping}, or {@link BeanMapping}. <p> If no strategy is configured, the strategy given via {@link MapperConfig#mappingInheritanceStrategy()} will beapplied, using {@link MappingInheritanceStrategy#EXPLICIT} as default.
* @return The strategy to use for applying {@code @Mapping} configurations of prototype methods in the interfacespecified with {@link #config()}.
*/
MappingInheritanceStrategy mappingInheritanceStrategy() default MappingInheritanceStrategy.EXPLICIT;
/**
* Determines when to include a null check on the source property value of a bean mapping. Can be overridden by the one on {@link MapperConfig}, {@link BeanMapping} or {@link Mapping}.
* @return strategy how to do null checking
*/
NullValueCheckStrategy nullValueCheckStrategy() default ON_IMPLICIT_CONVERSION;
/**
* Determines how to handle missing implementation for super classes when using the {@link SubclassMapping}. Can be overridden by the one on {@link BeanMapping}, but overrides {@link MapperConfig}.
* @return strategy to handle missing implementation combined with {@link SubclassMappings}.
* @since 1.5
*/
SubclassExhaustiveStrategy subclassExhaustiveStrategy() default COMPILE_ERROR;
/**
* Determines whether to use field or constructor injection. This is only used on annotated based component models such as CDI, Spring and JSR 330. If no strategy is configured, {@link InjectionStrategy#FIELD} will be used as default.
* @return strategy how to inject
*/
InjectionStrategy injectionStrategy() default InjectionStrategy.FIELD;
/**
* If MapStruct could not find another mapping method or apply an automatic conversion it will try to generate a sub-mapping method between the two beans. If this property is set to {@code true} MapStruct will not try toautomatically generate sub-mapping methods. <p> Can be configured by the {@link MapperConfig#disableSubMappingMethodsGeneration()} as well.<p> Note: If you need to use {@code disableSubMappingMethodsGeneration} please contact the MapStruct team at<a href="https://mapstruct.org">mapstruct.org</a> or <a href="https://github.com/mapstruct/mapstruct">github.com/mapstruct/mapstruct</a> to share what problem you are facing with the automatic sub-mapping generation.
* @return whether the automatic generation of sub-mapping methods is disabled
* @since 1.2
*/
boolean disableSubMappingMethodsGeneration() default false;
/**
* The information that should be used for the builder mappings. This can be used to define custom build methods for the builder strategy that one uses. If no builder is defined the builder given via {@link MapperConfig#builder()} will be applied.<p> NOTE: In case no builder is defined here, in {@link BeanMapping} or {@link MapperConfig} and there is a singlebuild method, then that method would be used. <p> If the builder is defined and there is a single method that does not match the name of the build method then a compile error will occur
* @return the builder information
* @since 1.3
*/
Builder builder() default @Builder;
/**
* Allows detailed control over the mapping process.
* @return the mapping control
* @since 1.4
* @see org.mapstruct.control.DeepClone
* @see org.mapstruct.control.NoComplexMapping
* @see org.mapstruct.control.MappingControl
*/
Class<? extends Annotation> mappingControl() default MappingControl.class;
/**
* Exception that should be thrown by the generated code if no mapping matches for enums. If no exception is configured, the exception given via {@link MapperConfig#unexpectedValueMappingException()}will be used, using {@link IllegalArgumentException} by default.<p> Note: <ul> <li> The defined exception should at least have a constructor with a {@link String} parameter.</li> <li> If the defined exception is a checked exception then the enum mapping methods should have that exception in the throws clause. </li> </ul>
* @return the exception that should be used in the generated code
* @since 1.4
*/
Class<? extends Exception> unexpectedValueMappingException() default IllegalArgumentException.class;
/**
* Flag indicating whether the addition of a time stamp in the {@code @Generated} annotation should be suppressed.i.e. not be added. The method overrides the flag set in a central configuration set by {@link #config()}or through an annotation processor option.
* @return whether the addition of a timestamp should be suppressed
* @since 1.5
*/
boolean suppressTimestampInGenerated() default false;
}
@SuppressWarnings("unchecked") private List<AnnotationValue> getValueAsList(AnnotationValue av){
return (List<AnnotationValue>)av.getValue();
}
@Override protected List<Annotation> getTypeAnnotations(Mapper mapper){
return Collections.singletonList(new Annotation(getType("ApplicationScoped")));
}
| /**
* Marks an interface or abstract class as a mapper and activates the generation of a implementation of that type via MapStruct. <p> <strong>Example 1:</strong> Creating mapper </p> <pre><code class='java'> @Mapper public interface CarMapper { CarDto toCarDto(Car source); } </code></pre> <p> <strong>Example 2:</strong> Use additional mappers with parameters {@link #uses()}, {@link #componentModel()}and {@link #injectionStrategy()}</p> <pre><code class='java'> // we have MarkMapper (map field "mark" to field "name" to upper case) @Mapper(componentModel = MappingConstants.ComponentModel.SPRING) public class MarkMapper { public String mapMark(String mark) { return mark.toUpperCase(); } } // we have CarMapper @Mapper( componentModel = MappingConstants.ComponentModel.SPRING, uses = MarkMapper.class, injectionStrategy = InjectionStrategy.CONSTRUCTOR) public interface CarMapper { @Mapping(target = "name", source = "mark") CarDto convertMap(CarEntity carEntity); } </code></pre> <pre><code class='java'> // generates @Component public class CarMapperImpl implements CarMapper { private final MarkMapper markMapper; @Autowired public CarMapperImpl(MarkMapper markMapper) { this.markMapper = markMapper; } @Override public CarDto convertMap(CarEntity carEntity) { if ( carEntity == null ) { return null; } CarDto carDto = new CarDto(); carDto.setName( markMapper.mapMark( carEntity.getMark() ) ); return carDto; } } </code></pre>
* @author Gunnar Morling
* @see Javadoc
*/
@Target(ElementType.TYPE) @Retention(RetentionPolicy.CLASS) public @interface Mapper {/**
* Other mapper types used by this mapper. May be hand-written classes or other mappers generated by MapStruct. No cycle between generated mapper classes must be created.
* @return The mapper types used by this mapper.
*/
Class<?>[] uses() default {};
/**
* Additional types for which an import statement is to be added to the generated mapper implementation class. This allows to refer to those types from within mapping expressions given via {@link Mapping#expression()}, {@link Mapping#defaultExpression()} or usingtheir simple name rather than their fully-qualified name.
* @return classes to add in the imports of the generated implementation.
*/
Class<?>[] imports() default {};
/**
* How unmapped properties of the source type of a mapping should be reported. The method overrides an unmappedSourcePolicy set in a central configuration set by {@link #config() }
* @return The reporting policy for unmapped source properties.
* @since 1.3
*/
ReportingPolicy unmappedSourcePolicy() default ReportingPolicy.IGNORE;
/**
* How unmapped properties of the target type of a mapping should be reported. The method overrides an unmappedTargetPolicy set in a central configuration set by {@link #config() }
* @return The reporting policy for unmapped target properties.
*/
ReportingPolicy unmappedTargetPolicy() default ReportingPolicy.WARN;
/**
* How lossy (narrowing) conversion, for instance long to integer should be reported. The method overrides an typeConversionPolicy set in a central configuration set by {@link #config() }
* @since 1.3
* @return The reporting policy for unmapped target properties.
*/
ReportingPolicy typeConversionPolicy() default ReportingPolicy.IGNORE;
/**
* Specifies the component model to which the generated mapper should adhere. Supported values are <ul> <li> {@code default}: the mapper uses no component model, instances are typically retrieved via {@link Mappers#getMapper(Class)}</li> <li> {@code cdi}: the generated mapper is an application-scoped CDI bean and can be retrieved via {@code @Inject}</li> <li> {@code spring}: the generated mapper is a Spring bean and can be retrieved via {@code @Autowired}</li> <li> {@code jsr330}: the generated mapper is annotated with {@code @javax.inject.Named} and{@code @Singleton}, and can be retrieved via {@code @Inject}. The annotations will either be from javax.inject or jakarta.inject, depending on which one is available, with javax.inject having precedence.</li> <li> {@code jakarta}: the generated mapper is annotated with {@code @jakarta.inject.Named} and{@code @Singleton}, and can be retrieved via {@code @Inject}.</li> </ul> The method overrides a componentModel set in a central configuration set by {@link #config() }
* @return The component model for the generated mapper.
*/
String componentModel() default MappingConstants.ComponentModel.DEFAULT;
/**
* Specifies the name of the implementation class. The {@code <CLASS_NAME>} will be replaced by theinterface/abstract class name. <p> Defaults to postfixing the name with {@code Impl}: {@code <CLASS_NAME>Impl}
* @return The implementation name.
* @see #implementationPackage()
*/
String implementationName() default "<CLASS_NAME>Impl";
/**
* Specifies the target package for the generated implementation. The {@code <PACKAGE_NAME>} will be replaced by theinterface's or abstract class' package. <p> Defaults to using the same package as the mapper interface/abstract class
* @return the implementation package.
* @see #implementationName()
*/
String implementationPackage() default "<PACKAGE_NAME>";
/**
* A class annotated with {@link MapperConfig} which should be used as configuration template. Any settings givenvia {@link Mapper} will take precedence over the settings from the referenced configuration source. The list ofreferenced mappers will contain all mappers given via {@link Mapper#uses()} and {@link MapperConfig#uses()}.
* @return A class which should be used as configuration template.
*/
Class<?> config() default void.class;
/**
* The strategy to be applied when propagating the value of collection-typed properties. By default, only JavaBeans accessor methods (setters or getters) will be used, but it is also possible to invoke a corresponding adder method for each element of the source collection (e.g. {@code orderDto.addOrderLine()}). <p> Any setting given for this attribute will take precedence over {@link MapperConfig#collectionMappingStrategy()}, if present.
* @return The strategy applied when propagating the value of collection-typed properties.
*/
CollectionMappingStrategy collectionMappingStrategy() default CollectionMappingStrategy.ACCESSOR_ONLY;
/**
* The strategy to be applied when {@code null} is passed as source argument value to the methods of this mapper.If no strategy is configured, the strategy given via {@link MapperConfig#nullValueMappingStrategy()} will beapplied, using {@link NullValueMappingStrategy#RETURN_NULL} by default.
* @return The strategy to be applied when {@code null} is passed as source value to the methods of this mapper.
*/
NullValueMappingStrategy nullValueMappingStrategy() default NullValueMappingStrategy.RETURN_NULL;
/**
* The strategy to be applied when {@code null} is passed as source argument value to an {@link IterableMapping} ofthis mapper. If unset, the strategy set with {@link #nullValueMappingStrategy()} will be applied. If neitherstrategy is configured, the strategy given via {@link MapperConfig#nullValueIterableMappingStrategy()} will beapplied, using {@link NullValueMappingStrategy#RETURN_NULL} by default.
* @since 1.5
* @return The strategy to be applied when {@code null} is passed as source value to an {@link IterableMapping} ofthis mapper.
*/
NullValueMappingStrategy nullValueIterableMappingStrategy() default NullValueMappingStrategy.RETURN_NULL;
/**
* The strategy to be applied when {@code null} is passed as source argument value to a {@link MapMapping} of thismapper. If unset, the strategy set with {@link #nullValueMappingStrategy()} will be applied. If neither strategyis configured, the strategy given via {@link MapperConfig#nullValueMapMappingStrategy()} will be applied, using{@link NullValueMappingStrategy#RETURN_NULL} by default.
* @since 1.5
* @return The strategy to be applied when {@code null} is passed as source value to a {@link MapMapping} of thismapper.
*/
NullValueMappingStrategy nullValueMapMappingStrategy() default NullValueMappingStrategy.RETURN_NULL;
/**
* The strategy to be applied when a source bean property is {@code null} or not present. If no strategy isconfigured, the strategy given via {@link MapperConfig#nullValuePropertyMappingStrategy()} will be applied,{@link NullValuePropertyMappingStrategy#SET_TO_NULL} will be used by default.
* @since 1.3
* @return The strategy to be applied when {@code null} is passed as source property value or the source propertyis not present.
*/
NullValuePropertyMappingStrategy nullValuePropertyMappingStrategy() default NullValuePropertyMappingStrategy.SET_TO_NULL;
/**
* The strategy to use for applying method-level configuration annotations of prototype methods in the interface specified with {@link #config()}. Annotations that can be inherited are for example {@link Mapping}, {@link IterableMapping}, {@link MapMapping}, or {@link BeanMapping}. <p> If no strategy is configured, the strategy given via {@link MapperConfig#mappingInheritanceStrategy()} will beapplied, using {@link MappingInheritanceStrategy#EXPLICIT} as default.
* @return The strategy to use for applying {@code @Mapping} configurations of prototype methods in the interfacespecified with {@link #config()}.
*/
MappingInheritanceStrategy mappingInheritanceStrategy() default MappingInheritanceStrategy.EXPLICIT;
/**
* Determines when to include a null check on the source property value of a bean mapping. Can be overridden by the one on {@link MapperConfig}, {@link BeanMapping} or {@link Mapping}.
* @return strategy how to do null checking
*/
NullValueCheckStrategy nullValueCheckStrategy() default ON_IMPLICIT_CONVERSION;
/**
* Determines how to handle missing implementation for super classes when using the {@link SubclassMapping}. Can be overridden by the one on {@link BeanMapping}, but overrides {@link MapperConfig}.
* @return strategy to handle missing implementation combined with {@link SubclassMappings}.
* @since 1.5
*/
SubclassExhaustiveStrategy subclassExhaustiveStrategy() default COMPILE_ERROR;
/**
* Determines whether to use field or constructor injection. This is only used on annotated based component models such as CDI, Spring and JSR 330. If no strategy is configured, {@link InjectionStrategy#FIELD} will be used as default.
* @return strategy how to inject
*/
InjectionStrategy injectionStrategy() default InjectionStrategy.FIELD;
/**
* If MapStruct could not find another mapping method or apply an automatic conversion it will try to generate a sub-mapping method between the two beans. If this property is set to {@code true} MapStruct will not try toautomatically generate sub-mapping methods. <p> Can be configured by the {@link MapperConfig#disableSubMappingMethodsGeneration()} as well.<p> Note: If you need to use {@code disableSubMappingMethodsGeneration} please contact the MapStruct team at<a href="https://mapstruct.org">mapstruct.org</a> or <a href="https://github.com/mapstruct/mapstruct">github.com/mapstruct/mapstruct</a> to share what problem you are facing with the automatic sub-mapping generation.
* @return whether the automatic generation of sub-mapping methods is disabled
* @since 1.2
*/
boolean disableSubMappingMethodsGeneration() default false;
/**
* The information that should be used for the builder mappings. This can be used to define custom build methods for the builder strategy that one uses. If no builder is defined the builder given via {@link MapperConfig#builder()} will be applied.<p> NOTE: In case no builder is defined here, in {@link BeanMapping} or {@link MapperConfig} and there is a singlebuild method, then that method would be used. <p> If the builder is defined and there is a single method that does not match the name of the build method then a compile error will occur
* @return the builder information
* @since 1.3
*/
Builder builder() default @Builder;
/**
* Allows detailed control over the mapping process.
* @return the mapping control
* @since 1.4
* @see org.mapstruct.control.DeepClone
* @see org.mapstruct.control.NoComplexMapping
* @see org.mapstruct.control.MappingControl
*/
Class<? extends Annotation> mappingControl() default MappingControl.class;
/**
* Exception that should be thrown by the generated code if no mapping matches for enums. If no exception is configured, the exception given via {@link MapperConfig#unexpectedValueMappingException()}will be used, using {@link IllegalArgumentException} by default.<p> Note: <ul> <li> The defined exception should at least have a constructor with a {@link String} parameter.</li> <li> If the defined exception is a checked exception then the enum mapping methods should have that exception in the throws clause. </li> </ul>
* @return the exception that should be used in the generated code
* @since 1.4
*/
Class<? extends Exception> unexpectedValueMappingException() default IllegalArgumentException.class;
/**
* Flag indicating whether the addition of a time stamp in the {@code @Generated} annotation should be suppressed.i.e. not be added. The method overrides the flag set in a central configuration set by {@link #config()}or through an annotation processor option.
* @return whether the addition of a timestamp should be suppressed
* @since 1.5
*/
boolean suppressTimestampInGenerated() default false;
}
@SuppressWarnings("unchecked") private List<AnnotationValue> getValueAsList(AnnotationValue av){
return (List<AnnotationValue>)av.getValue();
}
@Override protected List<Annotation> getTypeAnnotations(Mapper mapper){
return Collections.singletonList(new Annotation(getType("ApplicationScoped")));
}
| {"types": [{"Mapper": "Mapper"}], "methods": [{"asList": "getValueAsList"}], "similar_methods": [{"getTypeAnnotations": "getTypeAnnotations"}]} | [{"Mapper": {"retrieved_name": "Mapper", "raw_body": "/** \n * Marks an interface or abstract class as a mapper and activates the generation of a implementation of that type via MapStruct. <p> <strong>Example 1:</strong> Creating mapper </p> <pre><code class='java'> @Mapper public interface CarMapper { CarDto toCarDto(Car source); } </code></pre> <p> <strong>Example 2:</strong> Use additional mappers with parameters {@link #uses()}, {@link #componentModel()}and {@link #injectionStrategy()}</p> <pre><code class='java'> // we have MarkMapper (map field \"mark\" to field \"name\" to upper case) @Mapper(componentModel = MappingConstants.ComponentModel.SPRING) public class MarkMapper { public String mapMark(String mark) { return mark.toUpperCase(); } } // we have CarMapper @Mapper( componentModel = MappingConstants.ComponentModel.SPRING, uses = MarkMapper.class, injectionStrategy = InjectionStrategy.CONSTRUCTOR) public interface CarMapper { @Mapping(target = \"name\", source = \"mark\") CarDto convertMap(CarEntity carEntity); } </code></pre> <pre><code class='java'> // generates @Component public class CarMapperImpl implements CarMapper { private final MarkMapper markMapper; @Autowired public CarMapperImpl(MarkMapper markMapper) { this.markMapper = markMapper; } @Override public CarDto convertMap(CarEntity carEntity) { if ( carEntity == null ) { return null; } CarDto carDto = new CarDto(); carDto.setName( markMapper.mapMark( carEntity.getMark() ) ); return carDto; } } </code></pre>\n * @author Gunnar Morling\n * @see Javadoc\n */\n@Target(ElementType.TYPE) @Retention(RetentionPolicy.CLASS) public @interface Mapper {/** \n * Other mapper types used by this mapper. May be hand-written classes or other mappers generated by MapStruct. No cycle between generated mapper classes must be created.\n * @return The mapper types used by this mapper.\n */\nClass<?>[] uses() default {};\n/** \n * Additional types for which an import statement is to be added to the generated mapper implementation class. This allows to refer to those types from within mapping expressions given via {@link Mapping#expression()}, {@link Mapping#defaultExpression()} or usingtheir simple name rather than their fully-qualified name.\n * @return classes to add in the imports of the generated implementation.\n */\nClass<?>[] imports() default {};\n/** \n * How unmapped properties of the source type of a mapping should be reported. The method overrides an unmappedSourcePolicy set in a central configuration set by {@link #config() }\n * @return The reporting policy for unmapped source properties.\n * @since 1.3\n */\nReportingPolicy unmappedSourcePolicy() default ReportingPolicy.IGNORE;\n/** \n * How unmapped properties of the target type of a mapping should be reported. The method overrides an unmappedTargetPolicy set in a central configuration set by {@link #config() }\n * @return The reporting policy for unmapped target properties.\n */\nReportingPolicy unmappedTargetPolicy() default ReportingPolicy.WARN;\n/** \n * How lossy (narrowing) conversion, for instance long to integer should be reported. The method overrides an typeConversionPolicy set in a central configuration set by {@link #config() }\n * @since 1.3\n * @return The reporting policy for unmapped target properties.\n */\nReportingPolicy typeConversionPolicy() default ReportingPolicy.IGNORE;\n/** \n * Specifies the component model to which the generated mapper should adhere. Supported values are <ul> <li> {@code default}: the mapper uses no component model, instances are typically retrieved via {@link Mappers#getMapper(Class)}</li> <li> {@code cdi}: the generated mapper is an application-scoped CDI bean and can be retrieved via {@code @Inject}</li> <li> {@code spring}: the generated mapper is a Spring bean and can be retrieved via {@code @Autowired}</li> <li> {@code jsr330}: the generated mapper is annotated with {@code @javax.inject.Named} and{@code @Singleton}, and can be retrieved via {@code @Inject}. The annotations will either be from javax.inject or jakarta.inject, depending on which one is available, with javax.inject having precedence.</li> <li> {@code jakarta}: the generated mapper is annotated with {@code @jakarta.inject.Named} and{@code @Singleton}, and can be retrieved via {@code @Inject}.</li> </ul> The method overrides a componentModel set in a central configuration set by {@link #config() }\n * @return The component model for the generated mapper.\n */\nString componentModel() default MappingConstants.ComponentModel.DEFAULT;\n/** \n * Specifies the name of the implementation class. The {@code <CLASS_NAME>} will be replaced by theinterface/abstract class name. <p> Defaults to postfixing the name with {@code Impl}: {@code <CLASS_NAME>Impl}\n * @return The implementation name.\n * @see #implementationPackage()\n */\nString implementationName() default \"<CLASS_NAME>Impl\";\n/** \n * Specifies the target package for the generated implementation. The {@code <PACKAGE_NAME>} will be replaced by theinterface's or abstract class' package. <p> Defaults to using the same package as the mapper interface/abstract class\n * @return the implementation package.\n * @see #implementationName()\n */\nString implementationPackage() default \"<PACKAGE_NAME>\";\n/** \n * A class annotated with {@link MapperConfig} which should be used as configuration template. Any settings givenvia {@link Mapper} will take precedence over the settings from the referenced configuration source. The list ofreferenced mappers will contain all mappers given via {@link Mapper#uses()} and {@link MapperConfig#uses()}.\n * @return A class which should be used as configuration template.\n */\nClass<?> config() default void.class;\n/** \n * The strategy to be applied when propagating the value of collection-typed properties. By default, only JavaBeans accessor methods (setters or getters) will be used, but it is also possible to invoke a corresponding adder method for each element of the source collection (e.g. {@code orderDto.addOrderLine()}). <p> Any setting given for this attribute will take precedence over {@link MapperConfig#collectionMappingStrategy()}, if present.\n * @return The strategy applied when propagating the value of collection-typed properties.\n */\nCollectionMappingStrategy collectionMappingStrategy() default CollectionMappingStrategy.ACCESSOR_ONLY;\n/** \n * The strategy to be applied when {@code null} is passed as source argument value to the methods of this mapper.If no strategy is configured, the strategy given via {@link MapperConfig#nullValueMappingStrategy()} will beapplied, using {@link NullValueMappingStrategy#RETURN_NULL} by default.\n * @return The strategy to be applied when {@code null} is passed as source value to the methods of this mapper.\n */\nNullValueMappingStrategy nullValueMappingStrategy() default NullValueMappingStrategy.RETURN_NULL;\n/** \n * The strategy to be applied when {@code null} is passed as source argument value to an {@link IterableMapping} ofthis mapper. If unset, the strategy set with {@link #nullValueMappingStrategy()} will be applied. If neitherstrategy is configured, the strategy given via {@link MapperConfig#nullValueIterableMappingStrategy()} will beapplied, using {@link NullValueMappingStrategy#RETURN_NULL} by default.\n * @since 1.5\n * @return The strategy to be applied when {@code null} is passed as source value to an {@link IterableMapping} ofthis mapper.\n */\nNullValueMappingStrategy nullValueIterableMappingStrategy() default NullValueMappingStrategy.RETURN_NULL;\n/** \n * The strategy to be applied when {@code null} is passed as source argument value to a {@link MapMapping} of thismapper. If unset, the strategy set with {@link #nullValueMappingStrategy()} will be applied. If neither strategyis configured, the strategy given via {@link MapperConfig#nullValueMapMappingStrategy()} will be applied, using{@link NullValueMappingStrategy#RETURN_NULL} by default.\n * @since 1.5\n * @return The strategy to be applied when {@code null} is passed as source value to a {@link MapMapping} of thismapper.\n */\nNullValueMappingStrategy nullValueMapMappingStrategy() default NullValueMappingStrategy.RETURN_NULL;\n/** \n * The strategy to be applied when a source bean property is {@code null} or not present. If no strategy isconfigured, the strategy given via {@link MapperConfig#nullValuePropertyMappingStrategy()} will be applied,{@link NullValuePropertyMappingStrategy#SET_TO_NULL} will be used by default.\n * @since 1.3\n * @return The strategy to be applied when {@code null} is passed as source property value or the source propertyis not present.\n */\nNullValuePropertyMappingStrategy nullValuePropertyMappingStrategy() default NullValuePropertyMappingStrategy.SET_TO_NULL;\n/** \n * The strategy to use for applying method-level configuration annotations of prototype methods in the interface specified with {@link #config()}. Annotations that can be inherited are for example {@link Mapping}, {@link IterableMapping}, {@link MapMapping}, or {@link BeanMapping}. <p> If no strategy is configured, the strategy given via {@link MapperConfig#mappingInheritanceStrategy()} will beapplied, using {@link MappingInheritanceStrategy#EXPLICIT} as default.\n * @return The strategy to use for applying {@code @Mapping} configurations of prototype methods in the interfacespecified with {@link #config()}.\n */\nMappingInheritanceStrategy mappingInheritanceStrategy() default MappingInheritanceStrategy.EXPLICIT;\n/** \n * Determines when to include a null check on the source property value of a bean mapping. Can be overridden by the one on {@link MapperConfig}, {@link BeanMapping} or {@link Mapping}.\n * @return strategy how to do null checking\n */\nNullValueCheckStrategy nullValueCheckStrategy() default ON_IMPLICIT_CONVERSION;\n/** \n * Determines how to handle missing implementation for super classes when using the {@link SubclassMapping}. Can be overridden by the one on {@link BeanMapping}, but overrides {@link MapperConfig}.\n * @return strategy to handle missing implementation combined with {@link SubclassMappings}.\n * @since 1.5\n */\nSubclassExhaustiveStrategy subclassExhaustiveStrategy() default COMPILE_ERROR;\n/** \n * Determines whether to use field or constructor injection. This is only used on annotated based component models such as CDI, Spring and JSR 330. If no strategy is configured, {@link InjectionStrategy#FIELD} will be used as default.\n * @return strategy how to inject\n */\nInjectionStrategy injectionStrategy() default InjectionStrategy.FIELD;\n/** \n * If MapStruct could not find another mapping method or apply an automatic conversion it will try to generate a sub-mapping method between the two beans. If this property is set to {@code true} MapStruct will not try toautomatically generate sub-mapping methods. <p> Can be configured by the {@link MapperConfig#disableSubMappingMethodsGeneration()} as well.<p> Note: If you need to use {@code disableSubMappingMethodsGeneration} please contact the MapStruct team at<a href=\"https://mapstruct.org\">mapstruct.org</a> or <a href=\"https://github.com/mapstruct/mapstruct\">github.com/mapstruct/mapstruct</a> to share what problem you are facing with the automatic sub-mapping generation.\n * @return whether the automatic generation of sub-mapping methods is disabled\n * @since 1.2\n */\nboolean disableSubMappingMethodsGeneration() default false;\n/** \n * The information that should be used for the builder mappings. This can be used to define custom build methods for the builder strategy that one uses. If no builder is defined the builder given via {@link MapperConfig#builder()} will be applied.<p> NOTE: In case no builder is defined here, in {@link BeanMapping} or {@link MapperConfig} and there is a singlebuild method, then that method would be used. <p> If the builder is defined and there is a single method that does not match the name of the build method then a compile error will occur\n * @return the builder information\n * @since 1.3\n */\nBuilder builder() default @Builder;\n/** \n * Allows detailed control over the mapping process.\n * @return the mapping control\n * @since 1.4\n * @see org.mapstruct.control.DeepClone\n * @see org.mapstruct.control.NoComplexMapping\n * @see org.mapstruct.control.MappingControl\n */\nClass<? extends Annotation> mappingControl() default MappingControl.class;\n/** \n * Exception that should be thrown by the generated code if no mapping matches for enums. If no exception is configured, the exception given via {@link MapperConfig#unexpectedValueMappingException()}will be used, using {@link IllegalArgumentException} by default.<p> Note: <ul> <li> The defined exception should at least have a constructor with a {@link String} parameter.</li> <li> If the defined exception is a checked exception then the enum mapping methods should have that exception in the throws clause. </li> </ul>\n * @return the exception that should be used in the generated code\n * @since 1.4\n */\nClass<? extends Exception> unexpectedValueMappingException() default IllegalArgumentException.class;\n/** \n * Flag indicating whether the addition of a time stamp in the {@code @Generated} annotation should be suppressed.i.e. not be added. The method overrides the flag set in a central configuration set by {@link #config()}or through an annotation processor option.\n * @return whether the addition of a timestamp should be suppressed\n * @since 1.5\n */\nboolean suppressTimestampInGenerated() default false;\n}\n", "raw_body_no_cmt": "/** \n * Marks an interface or abstract class as a mapper and activates the generation of a implementation of that type via MapStruct. <p> <strong>Example 1:</strong> Creating mapper </p> <pre><code class='java'> @Mapper public interface CarMapper { CarDto toCarDto(Car source); } </code></pre> <p> <strong>Example 2:</strong> Use additional mappers with parameters {@link #uses()}, {@link #componentModel()}and {@link #injectionStrategy()}</p> <pre><code class='java'> // we have MarkMapper (map field \"mark\" to field \"name\" to upper case) @Mapper(componentModel = MappingConstants.ComponentModel.SPRING) public class MarkMapper { public String mapMark(String mark) { return mark.toUpperCase(); } } // we have CarMapper @Mapper( componentModel = MappingConstants.ComponentModel.SPRING, uses = MarkMapper.class, injectionStrategy = InjectionStrategy.CONSTRUCTOR) public interface CarMapper { @Mapping(target = \"name\", source = \"mark\") CarDto convertMap(CarEntity carEntity); } </code></pre> <pre><code class='java'> // generates @Component public class CarMapperImpl implements CarMapper { private final MarkMapper markMapper; @Autowired public CarMapperImpl(MarkMapper markMapper) { this.markMapper = markMapper; } @Override public CarDto convertMap(CarEntity carEntity) { if ( carEntity == null ) { return null; } CarDto carDto = new CarDto(); carDto.setName( markMapper.mapMark( carEntity.getMark() ) ); return carDto; } } </code></pre>\n * @author Gunnar Morling\n * @see Javadoc\n */\n@Target(ElementType.TYPE) @Retention(RetentionPolicy.CLASS) public @interface Mapper {/** \n * Other mapper types used by this mapper. May be hand-written classes or other mappers generated by MapStruct. No cycle between generated mapper classes must be created.\n * @return The mapper types used by this mapper.\n */\nClass<?>[] uses() default {};\n/** \n * Additional types for which an import statement is to be added to the generated mapper implementation class. This allows to refer to those types from within mapping expressions given via {@link Mapping#expression()}, {@link Mapping#defaultExpression()} or usingtheir simple name rather than their fully-qualified name.\n * @return classes to add in the imports of the generated implementation.\n */\nClass<?>[] imports() default {};\n/** \n * How unmapped properties of the source type of a mapping should be reported. The method overrides an unmappedSourcePolicy set in a central configuration set by {@link #config() }\n * @return The reporting policy for unmapped source properties.\n * @since 1.3\n */\nReportingPolicy unmappedSourcePolicy() default ReportingPolicy.IGNORE;\n/** \n * How unmapped properties of the target type of a mapping should be reported. The method overrides an unmappedTargetPolicy set in a central configuration set by {@link #config() }\n * @return The reporting policy for unmapped target properties.\n */\nReportingPolicy unmappedTargetPolicy() default ReportingPolicy.WARN;\n/** \n * How lossy (narrowing) conversion, for instance long to integer should be reported. The method overrides an typeConversionPolicy set in a central configuration set by {@link #config() }\n * @since 1.3\n * @return The reporting policy for unmapped target properties.\n */\nReportingPolicy typeConversionPolicy() default ReportingPolicy.IGNORE;\n/** \n * Specifies the component model to which the generated mapper should adhere. Supported values are <ul> <li> {@code default}: the mapper uses no component model, instances are typically retrieved via {@link Mappers#getMapper(Class)}</li> <li> {@code cdi}: the generated mapper is an application-scoped CDI bean and can be retrieved via {@code @Inject}</li> <li> {@code spring}: the generated mapper is a Spring bean and can be retrieved via {@code @Autowired}</li> <li> {@code jsr330}: the generated mapper is annotated with {@code @javax.inject.Named} and{@code @Singleton}, and can be retrieved via {@code @Inject}. The annotations will either be from javax.inject or jakarta.inject, depending on which one is available, with javax.inject having precedence.</li> <li> {@code jakarta}: the generated mapper is annotated with {@code @jakarta.inject.Named} and{@code @Singleton}, and can be retrieved via {@code @Inject}.</li> </ul> The method overrides a componentModel set in a central configuration set by {@link #config() }\n * @return The component model for the generated mapper.\n */\nString componentModel() default MappingConstants.ComponentModel.DEFAULT;\n/** \n * Specifies the name of the implementation class. The {@code <CLASS_NAME>} will be replaced by theinterface/abstract class name. <p> Defaults to postfixing the name with {@code Impl}: {@code <CLASS_NAME>Impl}\n * @return The implementation name.\n * @see #implementationPackage()\n */\nString implementationName() default \"<CLASS_NAME>Impl\";\n/** \n * Specifies the target package for the generated implementation. The {@code <PACKAGE_NAME>} will be replaced by theinterface's or abstract class' package. <p> Defaults to using the same package as the mapper interface/abstract class\n * @return the implementation package.\n * @see #implementationName()\n */\nString implementationPackage() default \"<PACKAGE_NAME>\";\n/** \n * A class annotated with {@link MapperConfig} which should be used as configuration template. Any settings givenvia {@link Mapper} will take precedence over the settings from the referenced configuration source. The list ofreferenced mappers will contain all mappers given via {@link Mapper#uses()} and {@link MapperConfig#uses()}.\n * @return A class which should be used as configuration template.\n */\nClass<?> config() default void.class;\n/** \n * The strategy to be applied when propagating the value of collection-typed properties. By default, only JavaBeans accessor methods (setters or getters) will be used, but it is also possible to invoke a corresponding adder method for each element of the source collection (e.g. {@code orderDto.addOrderLine()}). <p> Any setting given for this attribute will take precedence over {@link MapperConfig#collectionMappingStrategy()}, if present.\n * @return The strategy applied when propagating the value of collection-typed properties.\n */\nCollectionMappingStrategy collectionMappingStrategy() default CollectionMappingStrategy.ACCESSOR_ONLY;\n/** \n * The strategy to be applied when {@code null} is passed as source argument value to the methods of this mapper.If no strategy is configured, the strategy given via {@link MapperConfig#nullValueMappingStrategy()} will beapplied, using {@link NullValueMappingStrategy#RETURN_NULL} by default.\n * @return The strategy to be applied when {@code null} is passed as source value to the methods of this mapper.\n */\nNullValueMappingStrategy nullValueMappingStrategy() default NullValueMappingStrategy.RETURN_NULL;\n/** \n * The strategy to be applied when {@code null} is passed as source argument value to an {@link IterableMapping} ofthis mapper. If unset, the strategy set with {@link #nullValueMappingStrategy()} will be applied. If neitherstrategy is configured, the strategy given via {@link MapperConfig#nullValueIterableMappingStrategy()} will beapplied, using {@link NullValueMappingStrategy#RETURN_NULL} by default.\n * @since 1.5\n * @return The strategy to be applied when {@code null} is passed as source value to an {@link IterableMapping} ofthis mapper.\n */\nNullValueMappingStrategy nullValueIterableMappingStrategy() default NullValueMappingStrategy.RETURN_NULL;\n/** \n * The strategy to be applied when {@code null} is passed as source argument value to a {@link MapMapping} of thismapper. If unset, the strategy set with {@link #nullValueMappingStrategy()} will be applied. If neither strategyis configured, the strategy given via {@link MapperConfig#nullValueMapMappingStrategy()} will be applied, using{@link NullValueMappingStrategy#RETURN_NULL} by default.\n * @since 1.5\n * @return The strategy to be applied when {@code null} is passed as source value to a {@link MapMapping} of thismapper.\n */\nNullValueMappingStrategy nullValueMapMappingStrategy() default NullValueMappingStrategy.RETURN_NULL;\n/** \n * The strategy to be applied when a source bean property is {@code null} or not present. If no strategy isconfigured, the strategy given via {@link MapperConfig#nullValuePropertyMappingStrategy()} will be applied,{@link NullValuePropertyMappingStrategy#SET_TO_NULL} will be used by default.\n * @since 1.3\n * @return The strategy to be applied when {@code null} is passed as source property value or the source propertyis not present.\n */\nNullValuePropertyMappingStrategy nullValuePropertyMappingStrategy() default NullValuePropertyMappingStrategy.SET_TO_NULL;\n/** \n * The strategy to use for applying method-level configuration annotations of prototype methods in the interface specified with {@link #config()}. Annotations that can be inherited are for example {@link Mapping}, {@link IterableMapping}, {@link MapMapping}, or {@link BeanMapping}. <p> If no strategy is configured, the strategy given via {@link MapperConfig#mappingInheritanceStrategy()} will beapplied, using {@link MappingInheritanceStrategy#EXPLICIT} as default.\n * @return The strategy to use for applying {@code @Mapping} configurations of prototype methods in the interfacespecified with {@link #config()}.\n */\nMappingInheritanceStrategy mappingInheritanceStrategy() default MappingInheritanceStrategy.EXPLICIT;\n/** \n * Determines when to include a null check on the source property value of a bean mapping. Can be overridden by the one on {@link MapperConfig}, {@link BeanMapping} or {@link Mapping}.\n * @return strategy how to do null checking\n */\nNullValueCheckStrategy nullValueCheckStrategy() default ON_IMPLICIT_CONVERSION;\n/** \n * Determines how to handle missing implementation for super classes when using the {@link SubclassMapping}. Can be overridden by the one on {@link BeanMapping}, but overrides {@link MapperConfig}.\n * @return strategy to handle missing implementation combined with {@link SubclassMappings}.\n * @since 1.5\n */\nSubclassExhaustiveStrategy subclassExhaustiveStrategy() default COMPILE_ERROR;\n/** \n * Determines whether to use field or constructor injection. This is only used on annotated based component models such as CDI, Spring and JSR 330. If no strategy is configured, {@link InjectionStrategy#FIELD} will be used as default.\n * @return strategy how to inject\n */\nInjectionStrategy injectionStrategy() default InjectionStrategy.FIELD;\n/** \n * If MapStruct could not find another mapping method or apply an automatic conversion it will try to generate a sub-mapping method between the two beans. If this property is set to {@code true} MapStruct will not try toautomatically generate sub-mapping methods. <p> Can be configured by the {@link MapperConfig#disableSubMappingMethodsGeneration()} as well.<p> Note: If you need to use {@code disableSubMappingMethodsGeneration} please contact the MapStruct team at<a href=\"https://mapstruct.org\">mapstruct.org</a> or <a href=\"https://github.com/mapstruct/mapstruct\">github.com/mapstruct/mapstruct</a> to share what problem you are facing with the automatic sub-mapping generation.\n * @return whether the automatic generation of sub-mapping methods is disabled\n * @since 1.2\n */\nboolean disableSubMappingMethodsGeneration() default false;\n/** \n * The information that should be used for the builder mappings. This can be used to define custom build methods for the builder strategy that one uses. If no builder is defined the builder given via {@link MapperConfig#builder()} will be applied.<p> NOTE: In case no builder is defined here, in {@link BeanMapping} or {@link MapperConfig} and there is a singlebuild method, then that method would be used. <p> If the builder is defined and there is a single method that does not match the name of the build method then a compile error will occur\n * @return the builder information\n * @since 1.3\n */\nBuilder builder() default @Builder;\n/** \n * Allows detailed control over the mapping process.\n * @return the mapping control\n * @since 1.4\n * @see org.mapstruct.control.DeepClone\n * @see org.mapstruct.control.NoComplexMapping\n * @see org.mapstruct.control.MappingControl\n */\nClass<? extends Annotation> mappingControl() default MappingControl.class;\n/** \n * Exception that should be thrown by the generated code if no mapping matches for enums. If no exception is configured, the exception given via {@link MapperConfig#unexpectedValueMappingException()}will be used, using {@link IllegalArgumentException} by default.<p> Note: <ul> <li> The defined exception should at least have a constructor with a {@link String} parameter.</li> <li> If the defined exception is a checked exception then the enum mapping methods should have that exception in the throws clause. </li> </ul>\n * @return the exception that should be used in the generated code\n * @since 1.4\n */\nClass<? extends Exception> unexpectedValueMappingException() default IllegalArgumentException.class;\n/** \n * Flag indicating whether the addition of a time stamp in the {@code @Generated} annotation should be suppressed.i.e. not be added. The method overrides the flag set in a central configuration set by {@link #config()}or through an annotation processor option.\n * @return whether the addition of a timestamp should be suppressed\n * @since 1.5\n */\nboolean suppressTimestampInGenerated() default false;\n}\n"}}] | [{"asList": {"retrieved_name": "getValueAsList", "raw_body": "@SuppressWarnings(\"unchecked\") private List<AnnotationValue> getValueAsList(AnnotationValue av){\n return (List<AnnotationValue>)av.getValue();\n}\n"}}] | [{"getTypeAnnotations": {"retrieved_name": "getTypeAnnotations", "raw_body": "@Override protected List<Annotation> getTypeAnnotations(Mapper mapper){\n return Collections.singletonList(new Annotation(getType(\"ApplicationScoped\")));\n}\n"}}] |
PlayEdu_PlayEdu | PlayEdu/playedu-api/src/main/java/xyz/playedu/api/listener/UserCourseHourFinishedListener.java | UserCourseHourFinishedListener | userCourseProgressUpdate | class UserCourseHourFinishedListener {
@Autowired private UserCourseRecordService userCourseRecordService;
@Autowired private UserCourseHourRecordService userCourseHourRecordService;
@Autowired private CourseHourService hourService;
@EventListener
public void userCourseProgressUpdate(UserCourseHourFinishedEvent evt) {<FILL_FUNCTION_BODY>}
} |
Integer hourCount = hourService.getCountByCourseId(evt.getCourseId());
Integer finishedCount =
userCourseHourRecordService.getFinishedHourCount(
evt.getUserId(), evt.getCourseId());
userCourseRecordService.storeOrUpdate(
evt.getUserId(), evt.getCourseId(), hourCount, finishedCount);
|
UserCourseHourRecord record = evt.getRecord();
UserCourseRecord userCourseRecord = userCourseRecordService.getByUserIdAndCourseId(record.getUserId(), record.getCourseId());
if (userCourseRecord == null) {
userCourseRecord = new UserCourseRecord();
userCourseRecord.setUserId(record.getUserId());
userCourseRecord.setCourseId(record.getCourseId());
userCourseRecord.setCourseHourId(record.getCourseHourId());
userCourseRecord.setCourseHourName(record.getCourseHourName());
userCourseRecord.setCourseHourType(record.getCourseHourType());
userCourseRecord.setCourseHourUrl(record.getCourseHourUrl());
userCourseRecord.setCourseHourStatus(record.getCourseHourStatus());
userCourseRecord.setCourseHourFinishedTime(record.getCourseHourFinishedTime());
userCourseRecord.setCourseHourFinished(true);
userCourseRecord.setCourseHourFinishedTime(new Date());
userCourseRecordService.save(userCourseRecord);
} else {
userCourseRecord.setCourseHourId(record.getCourseHourId());
userCourseRecord.setCourseHourName(record.getCourseHourName());
userCourseRecord.setCourseHourType(record.getCourseHourType());
userCourseRecord.setCourseHourUrl(record.get | [
"UserCourseHourRecord",
"UserCourseRecord",
"UserCourseRecordService",
"UserCourseHourFinishedEvent"
] | [
"save",
"setUserId",
"setCourseId",
"setCourseHourUrl",
"getCourseHourStatus",
"setCourseHourFinishedTime",
"getCourseHourName",
"getCourseHourId",
"setCourseHourType",
"getByUserIdAndCourseId",
"getCourseHourFinishedTime",
"setCourseHourId",
"getCourseHourType",
"setCourseHourStatus",
"getCourseHourUrl",
"setCourseHourName",
"getRecord",
"getCourseId",
"getUserId",
"setCourseHourFinished"
] | [
"CourseHourService",
"UserCourseRecordService",
"UserCourseHourRecordService",
"UserCourseHourFinishedEvent"
] | [
"storeOrUpdate",
"getCountByCourseId",
"getFinishedHourCount",
"getCourseId",
"getUserId"
] | {
"methods": [
"save",
"setUserId",
"setCourseId",
"setCourseHourUrl",
"getCourseHourStatus",
"setCourseHourFinishedTime",
"getCourseHourName",
"getCourseHourId",
"setCourseHourType",
"getByUserIdAndCourseId",
"getCourseHourFinishedTime",
"setCourseHourId",
"getCourseHourType",
"setCourseHourStatus",
"getCourseHourUrl",
"setCourseHourName",
"getRecord",
"getCourseId",
"getUserId",
"setCourseHourFinished"
],
"similar_methods": [
"userCourseProgressUpdate"
],
"types": [
"UserCourseHourRecord",
"UserCourseRecord",
"UserCourseRecordService",
"UserCourseHourFinishedEvent"
]
} | /**
* @TableName user_course_hour_records
*/
@TableName(value="user_course_hour_records") @Data public class UserCourseHourRecord implements Serializable {
/**
*/
@TableId(type=IdType.AUTO) private Integer id;
/**
*/
@JsonProperty("user_id") private Integer userId;
/**
*/
@JsonProperty("course_id") private Integer courseId;
/**
*/
@JsonProperty("hour_id") private Integer hourId;
/**
* 总时长
*/
@JsonProperty("total_duration") private Integer totalDuration;
/**
* 已完成时长
*/
@JsonProperty("finished_duration") private Integer finishedDuration;
/**
* 实际观看时长
*/
@JsonProperty("real_duration") private Integer realDuration;
/**
* 是否看完[1:是,0:否]
*/
@JsonProperty("is_finished") private Integer isFinished;
/**
* 看完时间
*/
@JsonProperty("finished_at") private Date finishedAt;
/**
*/
@JsonProperty("created_at") private Date createdAt;
/**
*/
@JsonProperty("updated_at") private Date updatedAt;
@TableField(exist=false) private static final long serialVersionUID=1L;
@Override public boolean equals( Object that);
@Override public int hashCode();
@Override public String toString();
}
/**
* @TableName user_course_records
*/
@TableName(value="user_course_records") @Data public class UserCourseRecord implements Serializable {
/**
*/
@TableId(type=IdType.AUTO) private Integer id;
/**
*/
@JsonProperty("user_id") private Integer userId;
/**
*/
@JsonProperty("course_id") private Integer courseId;
/**
* 课时数量
*/
@JsonProperty("hour_count") private Integer hourCount;
/**
* 已完成课时数
*/
@JsonProperty("finished_count") private Integer finishedCount;
/**
* 进度
*/
private Integer progress;
/**
* 看完[1:是,0:否]
*/
@JsonProperty("is_finished") private Integer isFinished;
/**
* 看完时间
*/
@JsonProperty("finished_at") private Date finishedAt;
/**
*/
@JsonProperty("created_at") private Date createdAt;
/**
*/
@JsonProperty("updated_at") private Date updatedAt;
@TableField(exist=false) private static final long serialVersionUID=1L;
@Override public boolean equals( Object that);
@Override public int hashCode();
@Override public String toString();
}
/**
* @author tengteng
* @description 针对表【user_course_records】的数据库操作Service
* @createDate 2023-03-20 16:41:04
*/
public interface UserCourseRecordService extends IService<UserCourseRecord> {
UserCourseRecord find( Integer userId, Integer courseId);
void storeOrUpdate( Integer userId, Integer courseId, Integer hourCount, Integer finishedCount);
List<UserCourseRecord> chunk( Integer userId, List<Integer> courseIds);
List<UserCourseRecord> chunk( List<Integer> userId, List<Integer> courseIds);
PaginationResult<UserCourseRecord> paginate( int page, int size, UserCourseRecordPaginateFilter filter);
void destroy( Integer courseId, List<Integer> ids);
void destroy( Integer userId, Integer courseId);
void destroy( Integer userId);
void removeByCourseId( Integer courseId);
List<UserCourseRecord> chunks( List<Integer> ids, List<String> fields);
void updateUserCourseLearnProgress( Integer userId, Integer courseId, int count);
}
/**
* @Author 杭州白书科技有限公司
* @create 2023/3/20 17:32
*/
@Getter @Setter public class UserCourseHourFinishedEvent extends ApplicationEvent {
private Integer userId;
private Integer courseId;
private Integer hourId;
private Date createdAt;
public UserCourseHourFinishedEvent( Object source, Integer userId, Integer courseId, Integer hourId);
}
@BackendPermission(slug=BPermissionConstant.SYSTEM_CONFIG) @PutMapping("") @Log(title="系统配置-保存",businessType=BusinessTypeConstant.UPDATE) public JsonResponse save(@RequestBody AppConfigRequest req){
HashMap<String,String> data=new HashMap<>();
req.getData().forEach((key,value) -> {
if (SystemConstant.CONFIG_MASK.equals(value)) {
return;
}
String saveValue=value;
if (ConfigConstant.LDAP_URL.equals(key) && StringUtil.isNotEmpty(value) && !StringUtil.startsWithIgnoreCase(value,"ldap://")) {
saveValue="ldap://" + saveValue;
}
data.put(key,saveValue);
}
);
configService.saveFromMap(data);
return JsonResponse.data(null);
}
/**
* 用户ID
*/
public void setUserId(Integer userId){
this.userId=userId;
}
/**
*/
public void setId(Integer id){
this.id=id;
}
@Override public List<CourseHour> getHoursByCourseId(Integer courseId){
return list(query().getWrapper().eq("course_id",courseId).orderByAsc("sort"));
}
List<CourseHour> getHoursByCourseId(Integer courseId);
public UserCourseHourFinishedEvent(Object source,Integer userId,Integer courseId,Integer hourId){
super(source);
this.userId=userId;
this.courseId=courseId;
this.hourId=hourId;
this.createdAt=new Date();
}
List<CourseHour> getHoursByCourseId(Integer courseId);
List<CourseHour> getHoursByCourseId(Integer courseId);
@Override public List<CourseHour> getHoursByCourseId(Integer courseId){
return list(query().getWrapper().eq("course_id",courseId).orderByAsc("sort"));
}
List<Integer> getRidsByCourseId(Integer courseId);
public UserCourseHourFinishedEvent(Object source,Integer userId,Integer courseId,Integer hourId){
super(source);
this.userId=userId;
this.courseId=courseId;
this.hourId=hourId;
this.createdAt=new Date();
}
List<CourseHour> getHoursByCourseId(Integer courseId);
List<CourseHour> getHoursByCourseId(Integer courseId);
@Override public List<CourseHour> getHoursByCourseId(Integer courseId){
return list(query().getWrapper().eq("course_id",courseId).orderByAsc("sort"));
}
@Override public List<CourseHour> getHoursByCourseId(Integer courseId){
return list(query().getWrapper().eq("course_id",courseId).orderByAsc("sort"));
}
List<CourseHour> getHoursByCourseId(Integer courseId);
List<UserCourseHourRecord> getRecords(Integer userId,Integer courseId);
List<Integer> getRidsByCourseId(Integer courseId);
/**
* 用户ID
*/
public Integer getUserId(){
return userId;
}
public UserCourseHourFinishedEvent(Object source,Integer userId,Integer courseId,Integer hourId){
super(source);
this.userId=userId;
this.courseId=courseId;
this.hourId=hourId;
this.createdAt=new Date();
}
void updateUserCourseLearnProgress(Integer userId,Integer courseId,int count);
| public class UserCourseHourRecord implements Serializable {
private Integer id;
private Integer userId;
private Integer courseId;
private Integer hourId;
private Integer totalDuration;
private Integer finishedDuration;
private Integer realDuration;
private Integer isFinished;
private Date finishedAt;
private Date createdAt;
private Date updatedAt;
private static final long serialVersionUID=1L;
public boolean equals( Object that);
public int hashCode();
public String toString();
}
public class UserCourseRecord implements Serializable {
private Integer id;
private Integer userId;
private Integer courseId;
private Integer hourCount;
private Integer finishedCount;
private Integer progress;
private Integer isFinished;
private Date finishedAt;
private Date createdAt;
private Date updatedAt;
private static final long serialVersionUID=1L;
public boolean equals( Object that);
public int hashCode();
public String toString();
}
public interface UserCourseRecordService extends IService<UserCourseRecord> {
UserCourseRecord find( Integer userId, Integer courseId);
void storeOrUpdate( Integer userId, Integer courseId, Integer hourCount, Integer finishedCount);
List<UserCourseRecord> chunk( Integer userId, List<Integer> courseIds);
List<UserCourseRecord> chunk( List<Integer> userId, List<Integer> courseIds);
PaginationResult<UserCourseRecord> paginate( int page, int size, UserCourseRecordPaginateFilter filter);
void destroy( Integer courseId, List<Integer> ids);
void destroy( Integer userId, Integer courseId);
void destroy( Integer userId);
void removeByCourseId( Integer courseId);
List<UserCourseRecord> chunks( List<Integer> ids, List<String> fields);
void updateUserCourseLearnProgress( Integer userId, Integer courseId, int count);
}
public class UserCourseHourFinishedEvent extends ApplicationEvent {
private Integer userId;
private Integer courseId;
private Integer hourId;
private Date createdAt;
public UserCourseHourFinishedEvent( Object source, Integer userId, Integer courseId, Integer hourId);
}
@BackendPermission(slug=BPermissionConstant.SYSTEM_CONFIG) @PutMapping("") @Log(title="系统配置-保存",businessType=BusinessTypeConstant.UPDATE) public JsonResponse save(@RequestBody AppConfigRequest req){
HashMap<String,String> data=new HashMap<>();
req.getData().forEach((key,value) -> {
if (SystemConstant.CONFIG_MASK.equals(value)) {
return;
}
String saveValue=value;
if (ConfigConstant.LDAP_URL.equals(key) && StringUtil.isNotEmpty(value) && !StringUtil.startsWithIgnoreCase(value,"ldap://")) {
saveValue="ldap://" + saveValue;
}
data.put(key,saveValue);
}
);
configService.saveFromMap(data);
return JsonResponse.data(null);
}
/**
* 用户ID
*/
public void setUserId(Integer userId){
this.userId=userId;
}
/**
*/
public void setId(Integer id){
this.id=id;
}
@Override public List<CourseHour> getHoursByCourseId(Integer courseId){
return list(query().getWrapper().eq("course_id",courseId).orderByAsc("sort"));
}
List<CourseHour> getHoursByCourseId(Integer courseId);
public UserCourseHourFinishedEvent(Object source,Integer userId,Integer courseId,Integer hourId){
super(source);
this.userId=userId;
this.courseId=courseId;
this.hourId=hourId;
this.createdAt=new Date();
}
List<CourseHour> getHoursByCourseId(Integer courseId);
List<CourseHour> getHoursByCourseId(Integer courseId);
@Override public List<CourseHour> getHoursByCourseId(Integer courseId){
return list(query().getWrapper().eq("course_id",courseId).orderByAsc("sort"));
}
List<Integer> getRidsByCourseId(Integer courseId);
public UserCourseHourFinishedEvent(Object source,Integer userId,Integer courseId,Integer hourId){
super(source);
this.userId=userId;
this.courseId=courseId;
this.hourId=hourId;
this.createdAt=new Date();
}
List<CourseHour> getHoursByCourseId(Integer courseId);
List<CourseHour> getHoursByCourseId(Integer courseId);
@Override public List<CourseHour> getHoursByCourseId(Integer courseId){
return list(query().getWrapper().eq("course_id",courseId).orderByAsc("sort"));
}
@Override public List<CourseHour> getHoursByCourseId(Integer courseId){
return list(query().getWrapper().eq("course_id",courseId).orderByAsc("sort"));
}
List<CourseHour> getHoursByCourseId(Integer courseId);
List<UserCourseHourRecord> getRecords(Integer userId,Integer courseId);
List<Integer> getRidsByCourseId(Integer courseId);
/**
* 用户ID
*/
public Integer getUserId(){
return userId;
}
public UserCourseHourFinishedEvent(Object source,Integer userId,Integer courseId,Integer hourId){
super(source);
this.userId=userId;
this.courseId=courseId;
this.hourId=hourId;
this.createdAt=new Date();
}
void updateUserCourseLearnProgress(Integer userId,Integer courseId,int count);
| {"types": [{"UserCourseHourRecord": "UserCourseHourRecord"}, {"UserCourseRecord": "UserCourseRecord"}, {"UserCourseRecordService": "UserCourseRecordService"}, {"UserCourseHourFinishedEvent": "UserCourseHourFinishedEvent"}], "methods": [{"save": "save"}, {"setUserId": "setUserId"}, {"setCourseId": "setId"}, {"setCourseHourUrl": "getHoursByCourseId"}, {"getCourseHourStatus": "getHoursByCourseId"}, {"setCourseHourFinishedTime": "UserCourseHourFinishedEvent"}, {"getCourseHourName": "getHoursByCourseId"}, {"getCourseHourId": "getHoursByCourseId"}, {"setCourseHourType": "getHoursByCourseId"}, {"getByUserIdAndCourseId": "getRidsByCourseId"}, {"getCourseHourFinishedTime": "UserCourseHourFinishedEvent"}, {"setCourseHourId": "getHoursByCourseId"}, {"getCourseHourType": "getHoursByCourseId"}, {"setCourseHourStatus": "getHoursByCourseId"}, {"getCourseHourUrl": "getHoursByCourseId"}, {"setCourseHourName": "getHoursByCourseId"}, {"getRecord": "getRecords"}, {"getCourseId": "getRidsByCourseId"}, {"getUserId": "getUserId"}, {"setCourseHourFinished": "UserCourseHourFinishedEvent"}], "similar_methods": [{"userCourseProgressUpdate": "updateUserCourseLearnProgress"}]} | [{"UserCourseHourRecord": {"retrieved_name": "UserCourseHourRecord", "raw_body": "/** \n * @TableName user_course_hour_records\n */\n@TableName(value=\"user_course_hour_records\") @Data public class UserCourseHourRecord implements Serializable {\n /** \n */\n @TableId(type=IdType.AUTO) private Integer id;\n /** \n */\n @JsonProperty(\"user_id\") private Integer userId;\n /** \n */\n @JsonProperty(\"course_id\") private Integer courseId;\n /** \n */\n @JsonProperty(\"hour_id\") private Integer hourId;\n /** \n * \u603b\u65f6\u957f \n */\n @JsonProperty(\"total_duration\") private Integer totalDuration;\n /** \n * \u5df2\u5b8c\u6210\u65f6\u957f \n */\n @JsonProperty(\"finished_duration\") private Integer finishedDuration;\n /** \n * \u5b9e\u9645\u89c2\u770b\u65f6\u957f \n */\n @JsonProperty(\"real_duration\") private Integer realDuration;\n /** \n * \u662f\u5426\u770b\u5b8c[1:\u662f,0:\u5426] \n */\n @JsonProperty(\"is_finished\") private Integer isFinished;\n /** \n * \u770b\u5b8c\u65f6\u95f4 \n */\n @JsonProperty(\"finished_at\") private Date finishedAt;\n /** \n */\n @JsonProperty(\"created_at\") private Date createdAt;\n /** \n */\n @JsonProperty(\"updated_at\") private Date updatedAt;\n @TableField(exist=false) private static final long serialVersionUID=1L;\n @Override public boolean equals( Object that);\n @Override public int hashCode();\n @Override public String toString();\n}\n", "raw_body_no_cmt": "public class UserCourseHourRecord implements Serializable {\n private Integer id;\n private Integer userId;\n private Integer courseId;\n private Integer hourId;\n private Integer totalDuration;\n private Integer finishedDuration;\n private Integer realDuration;\n private Integer isFinished;\n private Date finishedAt;\n private Date createdAt;\n private Date updatedAt;\n private static final long serialVersionUID=1L;\n public boolean equals( Object that);\n public int hashCode();\n public String toString();\n}\n"}}, {"UserCourseRecord": {"retrieved_name": "UserCourseRecord", "raw_body": "/** \n * @TableName user_course_records\n */\n@TableName(value=\"user_course_records\") @Data public class UserCourseRecord implements Serializable {\n /** \n */\n @TableId(type=IdType.AUTO) private Integer id;\n /** \n */\n @JsonProperty(\"user_id\") private Integer userId;\n /** \n */\n @JsonProperty(\"course_id\") private Integer courseId;\n /** \n * \u8bfe\u65f6\u6570\u91cf \n */\n @JsonProperty(\"hour_count\") private Integer hourCount;\n /** \n * \u5df2\u5b8c\u6210\u8bfe\u65f6\u6570 \n */\n @JsonProperty(\"finished_count\") private Integer finishedCount;\n /** \n * \u8fdb\u5ea6 \n */\n private Integer progress;\n /** \n * \u770b\u5b8c[1:\u662f,0:\u5426] \n */\n @JsonProperty(\"is_finished\") private Integer isFinished;\n /** \n * \u770b\u5b8c\u65f6\u95f4 \n */\n @JsonProperty(\"finished_at\") private Date finishedAt;\n /** \n */\n @JsonProperty(\"created_at\") private Date createdAt;\n /** \n */\n @JsonProperty(\"updated_at\") private Date updatedAt;\n @TableField(exist=false) private static final long serialVersionUID=1L;\n @Override public boolean equals( Object that);\n @Override public int hashCode();\n @Override public String toString();\n}\n", "raw_body_no_cmt": "public class UserCourseRecord implements Serializable {\n private Integer id;\n private Integer userId;\n private Integer courseId;\n private Integer hourCount;\n private Integer finishedCount;\n private Integer progress;\n private Integer isFinished;\n private Date finishedAt;\n private Date createdAt;\n private Date updatedAt;\n private static final long serialVersionUID=1L;\n public boolean equals( Object that);\n public int hashCode();\n public String toString();\n}\n"}}, {"UserCourseRecordService": {"retrieved_name": "UserCourseRecordService", "raw_body": "/** \n * @author tengteng\n * @description \u9488\u5bf9\u8868\u3010user_course_records\u3011\u7684\u6570\u636e\u5e93\u64cd\u4f5cService\n * @createDate 2023-03-20 16:41:04\n */\npublic interface UserCourseRecordService extends IService<UserCourseRecord> {\n UserCourseRecord find( Integer userId, Integer courseId);\n void storeOrUpdate( Integer userId, Integer courseId, Integer hourCount, Integer finishedCount);\n List<UserCourseRecord> chunk( Integer userId, List<Integer> courseIds);\n List<UserCourseRecord> chunk( List<Integer> userId, List<Integer> courseIds);\n PaginationResult<UserCourseRecord> paginate( int page, int size, UserCourseRecordPaginateFilter filter);\n void destroy( Integer courseId, List<Integer> ids);\n void destroy( Integer userId, Integer courseId);\n void destroy( Integer userId);\n void removeByCourseId( Integer courseId);\n List<UserCourseRecord> chunks( List<Integer> ids, List<String> fields);\n void updateUserCourseLearnProgress( Integer userId, Integer courseId, int count);\n}\n", "raw_body_no_cmt": "public interface UserCourseRecordService extends IService<UserCourseRecord> {\n UserCourseRecord find( Integer userId, Integer courseId);\n void storeOrUpdate( Integer userId, Integer courseId, Integer hourCount, Integer finishedCount);\n List<UserCourseRecord> chunk( Integer userId, List<Integer> courseIds);\n List<UserCourseRecord> chunk( List<Integer> userId, List<Integer> courseIds);\n PaginationResult<UserCourseRecord> paginate( int page, int size, UserCourseRecordPaginateFilter filter);\n void destroy( Integer courseId, List<Integer> ids);\n void destroy( Integer userId, Integer courseId);\n void destroy( Integer userId);\n void removeByCourseId( Integer courseId);\n List<UserCourseRecord> chunks( List<Integer> ids, List<String> fields);\n void updateUserCourseLearnProgress( Integer userId, Integer courseId, int count);\n}\n"}}, {"UserCourseHourFinishedEvent": {"retrieved_name": "UserCourseHourFinishedEvent", "raw_body": "/** \n * @Author \u676d\u5dde\u767d\u4e66\u79d1\u6280\u6709\u9650\u516c\u53f8\n * @create 2023/3/20 17:32\n */\n@Getter @Setter public class UserCourseHourFinishedEvent extends ApplicationEvent {\n private Integer userId;\n private Integer courseId;\n private Integer hourId;\n private Date createdAt;\n public UserCourseHourFinishedEvent( Object source, Integer userId, Integer courseId, Integer hourId);\n}\n", "raw_body_no_cmt": "public class UserCourseHourFinishedEvent extends ApplicationEvent {\n private Integer userId;\n private Integer courseId;\n private Integer hourId;\n private Date createdAt;\n public UserCourseHourFinishedEvent( Object source, Integer userId, Integer courseId, Integer hourId);\n}\n"}}] | [{"save": {"retrieved_name": "save", "raw_body": "@BackendPermission(slug=BPermissionConstant.SYSTEM_CONFIG) @PutMapping(\"\") @Log(title=\"\u7cfb\u7edf\u914d\u7f6e-\u4fdd\u5b58\",businessType=BusinessTypeConstant.UPDATE) public JsonResponse save(@RequestBody AppConfigRequest req){\n HashMap<String,String> data=new HashMap<>();\n req.getData().forEach((key,value) -> {\n if (SystemConstant.CONFIG_MASK.equals(value)) {\n return;\n }\n String saveValue=value;\n if (ConfigConstant.LDAP_URL.equals(key) && StringUtil.isNotEmpty(value) && !StringUtil.startsWithIgnoreCase(value,\"ldap://\")) {\n saveValue=\"ldap://\" + saveValue;\n }\n data.put(key,saveValue);\n }\n);\n configService.saveFromMap(data);\n return JsonResponse.data(null);\n}\n"}}, {"setUserId": {"retrieved_name": "setUserId", "raw_body": "/** \n * \u7528\u6237ID \n */\npublic void setUserId(Integer userId){\n this.userId=userId;\n}\n"}}, {"setCourseId": {"retrieved_name": "setId", "raw_body": "/** \n */\npublic void setId(Integer id){\n this.id=id;\n}\n"}}, {"setCourseHourUrl": {"retrieved_name": "getHoursByCourseId", "raw_body": "@Override public List<CourseHour> getHoursByCourseId(Integer courseId){\n return list(query().getWrapper().eq(\"course_id\",courseId).orderByAsc(\"sort\"));\n}\n"}}, {"getCourseHourStatus": {"retrieved_name": "getHoursByCourseId", "raw_body": "List<CourseHour> getHoursByCourseId(Integer courseId);\n"}}, {"setCourseHourFinishedTime": {"retrieved_name": "UserCourseHourFinishedEvent", "raw_body": "public UserCourseHourFinishedEvent(Object source,Integer userId,Integer courseId,Integer hourId){\n super(source);\n this.userId=userId;\n this.courseId=courseId;\n this.hourId=hourId;\n this.createdAt=new Date();\n}\n"}}, {"getCourseHourName": {"retrieved_name": "getHoursByCourseId", "raw_body": "List<CourseHour> getHoursByCourseId(Integer courseId);\n"}}, {"getCourseHourId": {"retrieved_name": "getHoursByCourseId", "raw_body": "List<CourseHour> getHoursByCourseId(Integer courseId);\n"}}, {"setCourseHourType": {"retrieved_name": "getHoursByCourseId", "raw_body": "@Override public List<CourseHour> getHoursByCourseId(Integer courseId){\n return list(query().getWrapper().eq(\"course_id\",courseId).orderByAsc(\"sort\"));\n}\n"}}, {"getByUserIdAndCourseId": {"retrieved_name": "getRidsByCourseId", "raw_body": "List<Integer> getRidsByCourseId(Integer courseId);\n"}}, {"getCourseHourFinishedTime": {"retrieved_name": "UserCourseHourFinishedEvent", "raw_body": "public UserCourseHourFinishedEvent(Object source,Integer userId,Integer courseId,Integer hourId){\n super(source);\n this.userId=userId;\n this.courseId=courseId;\n this.hourId=hourId;\n this.createdAt=new Date();\n}\n"}}, {"setCourseHourId": {"retrieved_name": "getHoursByCourseId", "raw_body": "List<CourseHour> getHoursByCourseId(Integer courseId);\n"}}, {"getCourseHourType": {"retrieved_name": "getHoursByCourseId", "raw_body": "List<CourseHour> getHoursByCourseId(Integer courseId);\n"}}, {"setCourseHourStatus": {"retrieved_name": "getHoursByCourseId", "raw_body": "@Override public List<CourseHour> getHoursByCourseId(Integer courseId){\n return list(query().getWrapper().eq(\"course_id\",courseId).orderByAsc(\"sort\"));\n}\n"}}, {"getCourseHourUrl": {"retrieved_name": "getHoursByCourseId", "raw_body": "@Override public List<CourseHour> getHoursByCourseId(Integer courseId){\n return list(query().getWrapper().eq(\"course_id\",courseId).orderByAsc(\"sort\"));\n}\n"}}, {"setCourseHourName": {"retrieved_name": "getHoursByCourseId", "raw_body": "List<CourseHour> getHoursByCourseId(Integer courseId);\n"}}, {"getRecord": {"retrieved_name": "getRecords", "raw_body": "List<UserCourseHourRecord> getRecords(Integer userId,Integer courseId);\n"}}, {"getCourseId": {"retrieved_name": "getRidsByCourseId", "raw_body": "List<Integer> getRidsByCourseId(Integer courseId);\n"}}, {"getUserId": {"retrieved_name": "getUserId", "raw_body": "/** \n * \u7528\u6237ID \n */\npublic Integer getUserId(){\n return userId;\n}\n"}}, {"setCourseHourFinished": {"retrieved_name": "UserCourseHourFinishedEvent", "raw_body": "public UserCourseHourFinishedEvent(Object source,Integer userId,Integer courseId,Integer hourId){\n super(source);\n this.userId=userId;\n this.courseId=courseId;\n this.hourId=hourId;\n this.createdAt=new Date();\n}\n"}}] | [{"userCourseProgressUpdate": {"retrieved_name": "updateUserCourseLearnProgress", "raw_body": "void updateUserCourseLearnProgress(Integer userId,Integer courseId,int count);\n"}}] |
|
jitsi_jitsi | jitsi/modules/plugin/desktoputil/src/main/java/net/java/sip/communicator/plugin/desktoputil/ScreenInformation.java | ScreenInformation | getScreenBounds | class ScreenInformation
{
/**
* Calculates the bounding box of all available screens. This method is
* highly inaccurate when screens of different sizes are used or not evenly
* aligned. A correct implementation should generate a polygon.
*
* @return A polygon of the usable screen area.
*/
public static Rectangle getScreenBounds()
{<FILL_FUNCTION_BODY>}
/**
* Checks whether the top edge of the rectangle is contained in any of the
* available screens.
*
* @param window The bounding box of the window.
* @return True when the top edge is in a visible screen area; false
* otherwise
*/
public static boolean isTitleOnScreen(Rectangle window)
{
final GraphicsEnvironment ge = GraphicsEnvironment
.getLocalGraphicsEnvironment();
boolean leftInside = false;
boolean rightInside = false;
Point topLeft = new Point(window.x, window.y);
Point topRight = new Point(window.x + window.width, window.y);
for(GraphicsDevice gd : ge.getScreenDevices())
{
GraphicsConfiguration gc = gd.getDefaultConfiguration();
if(gc.getBounds().contains(topLeft))
leftInside = true;
if(gc.getBounds().contains(topRight))
rightInside = true;
if(leftInside && rightInside)
return true;
}
return leftInside && rightInside;
}
} |
final GraphicsEnvironment ge = GraphicsEnvironment
.getLocalGraphicsEnvironment();
Rectangle bounds = new Rectangle();
for(GraphicsDevice gd : ge.getScreenDevices())
{
GraphicsConfiguration gc = gd.getDefaultConfiguration();
bounds = bounds.union(gc.getBounds());
}
return bounds;
|
final GraphicsEnvironment ge = GraphicsEnvironment
.getLocalGraphicsEnvironment();
Rectangle bounds = new Rectangle();
for(GraphicsDevice gd : ge.getScreenDevices())
{
GraphicsConfiguration gc = gd.getDefaultConfiguration();
bounds = bounds.union(gc.getBounds());
}
return bounds;
| [
"GraphicsDevice",
"Rectangle",
"GraphicsEnvironment",
"GraphicsConfiguration"
] | [
"getBounds",
"getLocalGraphicsEnvironment",
"union",
"getDefaultConfiguration",
"getScreenDevices"
] | [
"Rectangle",
"GraphicsEnvironment",
"GraphicsConfiguration",
"GraphicsDevice"
] | [
"getScreenDevices",
"getDefaultConfiguration",
"getLocalGraphicsEnvironment",
"getBounds",
"union"
] | {
"methods": [
"getBounds",
"getLocalGraphicsEnvironment",
"union",
"getDefaultConfiguration",
"getScreenDevices"
],
"similar_methods": [
"getScreenBounds"
],
"types": [
"GraphicsDevice",
"Rectangle",
"GraphicsEnvironment",
"GraphicsConfiguration"
]
} | /**
* The <tt>GraphicUtils</tt> is an utility class that gives access to some simple graphics operations, like an easy creating of a clipped shape or image, or painting of a border glow. Most of the code in this class is based on advices and examples in the "Java 2D Trickery: Soft Clipping".
* @author Yana Stamcheva
*/
public class GraphicUtils {
/**
* Creates a rounded clipped shape with the given <tt>shapeWidth</tt>, <tt>shapeHeight</tt>, arc width and arc height.
* @param shapeWidth the width of the shape to create
* @param shapeHeight the height of the shape to create
* @param arcW the width of the arc to use to round the corners of thenewly created shape
* @param arcH the height of the arc to use to round the corners of thenewly created shape
* @return the created shape
*/
public static Shape createRoundedClipShape( int shapeWidth, int shapeHeight, int arcW, int arcH);
/**
* Creates a clipped image from the given <tt>shape</tt>.
* @param shape the shape from which to create the image
* @param g the <tt>Graphics</tt> object giving access to the graphicsdevice configuration
* @return the created <tt>BufferedImage</tt>
*/
public static BufferedImage createClipImage( Graphics2D g, Shape shape);
/**
* Paints border glow over the given <tt>clipShape</tt> with the given glow high and low colors and the given <tt>glowWidth</tt>.
* @param g2 the <tt>Graphics</tt> object to use for painting
* @param glowWidth the width of the glow
* @param clipShape the shape where to paint the glow
* @param glowOuterHigh the color which will paint the higher glow
* @param glowOuterLow the color which will paint the lower glow
*/
public static void paintBorderGlow( Graphics2D g2, int glowWidth, Shape clipShape, Color glowOuterHigh, Color glowOuterLow);
/**
* Returns a mixed color from color <tt>c1</tt> and <tt>c2</tt>.
* @param c1 the start color
* @param pct1 the first color coefficient of the mix between 0 and 1
* @param c2 the end color
* @param pct2 the second color coefficient of the mix between 0 and 1
* @return the new mixed color
*/
private static Color getMixedColor( Color c1, float pct1, Color c2, float pct2);
}
/**
* Panel containing a listing of current keybinding mappings. This contains methods that can be overwritten to provide easy editing functionality and display logic. Note that this does not support the manual addition or removal of BindingEntry components. However this is designed to tolerate the changing of entry visibility (including individual fields) and the manual addition and removal of extra components either to this panel or its BindingEntries.<br> This represents a mapping of keystrokes to strings, and hence duplicate shortcuts aren't supported. An exception is made in the case of disabled shortcuts, but to keep mappings unique duplicate actions among disabled entries are not permitted.
* @author Damian Johnson (atagar1@gmail.com)
* @version September 1, 2007
*/
public abstract class BindingPanel extends TransparentPanel {
/**
* Serial version UID.
*/
private static final long serialVersionUID=0L;
private ArrayList<BindingEntry> contents=new ArrayList<BindingEntry>();
/**
* Method called whenever an entry is either added or shifts in the display. For instance, if the second entry is removed then this is called on the third to last elements.
* @param index newly assigned index of entry
* @param entry entry that has been added or shifted
* @param isNew if true the entry is new to the display, false otherwise
*/
protected abstract void onUpdate( int index, BindingEntry entry, boolean isNew);
/**
* Method called upon any mouse clicks within a BindingEntry in the display.
* @param event fired mouse event that triggered method call
* @param entry entry on which the click landed
* @param field field of entry on which the click landed, null if not arecognized field
*/
protected abstract void onClick( MouseEvent event, BindingEntry entry, BindingEntry.Field field);
/**
* Constructor.
*/
public BindingPanel();
/**
* Adds a new key binding mapping to the end of the listing. If this already contains the shortcut then the previous entry is replaced instead (not triggering the onUpdate method). Disabled shortcuts trigger replacement on duplicate actions instead. This uses the normal parameters used to generate key stokes, such as: <pre> bindingPanel.putBinding('Y', 0, "Confirm Selection"); bindingPanel.putBinding(KeyEvent.VK_DELETE, KeyEvent.CTRL_MASK | KeyEvent.ALT_MASK, "Kill Process"); </pre>
* @param keyCode key code of keystroke component of mapping
* @param modifier modifiers of keystroke component of mapping
* @param action string component of mapping
* @return true if contents did not already include shortcut
*/
public boolean putBinding( int keyCode, int modifier, String action);
/**
* Adds a new key binding mapping to the end of the listing. If this already contains the shortcut then the previous entry is replaced instead (not triggering the onUpdate method). Disabled shortcuts trigger replacement on duplicate actions instead.
* @param shortcut keystroke component of mapping
* @param action string component of mapping
* @return true if contents did not already include shortcut
*/
public boolean putBinding( KeyStroke shortcut, String action);
/**
* Adds a new key binding mapping to a particular index of the listing. If this already contains the shortcut then the previous entry is replaced instead (not triggering the onUpdate method). Disabled shortcuts trigger replacement on duplicate actions instead.
* @param shortcut keystroke component of mapping
* @param action string component of mapping
* @param index location in which to insert mapping
* @return true if contents did not already include shortcut
* @throws IndexOutOfBoundsException if index is out of range (index < 0 ||index > getBindingCount()).
*/
public boolean putBinding( KeyStroke shortcut, String action, int index);
/**
* Adds a new key binding mapping to a particular index of the listing. If this already contains the shortcut then the previous entry is replaced instead (not triggering the onUpdate method). Disabled shortcuts trigger replacement on duplicate actions instead.
* @param newEntry entry to add to contents
* @param index location in which to insert mapping
* @return true if contents did not already include shortcut
* @throws IndexOutOfBoundsException if index is out of range (index < 0 ||index > getBindingCount()).
*/
public boolean putBinding( BindingEntry newEntry, int index);
/**
* Adds a collection of new key binding mappings to the end of the listing. If any shortcuts are already contained then the previous entries are replaced (not triggering the onUpdate method). Disabled shortcuts trigger replacement on duplicate actions instead.
* @param bindings mapping between keystrokes and actions to be added
*/
public void putAllBindings( Map<KeyStroke,String> bindings);
/**
* Removes a particular binding from the contents.
* @param entry binding to be removed
* @return true if binding was in the contents, false otherwise
*/
public boolean removeBinding( BindingEntry entry);
/**
* Removes the binding at a particular index of the listing.
* @param index from which to remove entry
* @return the entry that was removed from the contents
* @throws IndexOutOfBoundsException if index is out of range (index < 0 ||index > getBindingCount()).
*/
public BindingEntry removeBinding( int index);
/**
* Removes all bindings from the panel.
*/
public void clearBindings();
/**
* Returns if a keystroke is in the panel's current contents. This provides a preemptive means of checking if adding a non-disabled shortcut would cause a replacement.
* @param shortcut keystroke to be checked against contents
* @return true if contents includes the shortcut, false otherwise
*/
public boolean contains( KeyStroke shortcut);
/**
* Provides number of key bindings currently present.
* @return number of key bindings in the display
*/
public int getBindingCount();
/**
* Provides the index of a particular entry.
* @param entry entry for which the index should be returned
* @return entry index, -1 if not found
*/
public int getBindingIndex( BindingEntry entry);
/**
* Provides a binding at a particular index.
* @param index index from which to retrieve binding.
* @return the entry at the specified position in this list
*/
public BindingEntry getBinding( int index);
/**
* Provides listing of the current keybinding entries.
* @return list of current entry contents
*/
public ArrayList<BindingEntry> getBindings();
/**
* Provides the mapping between keystrokes and actions represented by the contents of the display. Disabled entries aren't included in the mapping.
* @return mapping between contained keystrokes and their associated actions
*/
public LinkedHashMap<KeyStroke,String> getBindingMap();
/**
* Provides an input map associating keystrokes to actions according to the contents of the display. Disabled entries aren't included in the mapping.
* @return input mapping between contained keystrokes and their associatedactions
*/
public InputMap getBindingInputMap();
private class MouseTracker extends MouseInputAdapter {
@Override public void mousePressed( MouseEvent event);
}
}
/**
* The general configuration form.
* @author Yana Stamcheva
*/
public class GeneralConfigurationPanel extends TransparentPanel {
/**
* Serial version UID.
*/
private static final long serialVersionUID=0L;
/**
* The <tt>Logger</tt> used by this <tt>GeneralConfigurationPanel</tt> for logging output.
*/
private final org.slf4j.Logger logger=org.slf4j.LoggerFactory.getLogger(GeneralConfigurationPanel.class);
/**
* Indicates if the Startup configuration panel should be disabled, i.e. not visible to the user.
*/
private static final String STARTUP_CONFIG_DISABLED_PROP="net.java.sip.communicator.plugin.generalconfig.startupconfig.DISABLED";
/**
* Indicates if the Message configuration panel should be disabled, i.e. not visible to the user.
*/
private static final String MESSAGE_CONFIG_DISABLED_PROP="net.java.sip.communicator.plugin.generalconfig.messageconfig.DISABLED";
/**
* Indicates if the AutoAway configuration panel should be disabled, i.e. not visible to the user.
*/
private static final String AUTO_AWAY_CONFIG_DISABLED_PROP="net.java.sip.communicator.plugin.generalconfig.autoawayconfig.DISABLED";
/**
* Indicates if the Notification configuration panel should be disabled, i.e. not visible to the user.
*/
private static final String NOTIFICATION_CONFIG_DISABLED_PROP="net.java.sip.communicator.plugin.generalconfig.notificationconfig.DISABLED";
/**
* Indicates if the Locale configuration panel should be disabled, i.e. not visible to the user.
*/
private static final String LOCALE_CONFIG_DISABLED_PROP="net.java.sip.communicator.plugin.generalconfig.localeconfig.DISABLED";
/**
* Indicates if the systray config panel should be disabled, i.e. not visible to the user.
*/
private static final String SYSTRAY_CONFIG_DISABLED_PROP="net.java.sip.communicator.plugin.generalconfig.systrayconfig.DISABLED";
/**
* Indicates if the Call configuration panel should be disabled, i.e. not visible to the user.
*/
private static final String CALL_CONFIG_DISABLED_PROP="net.java.sip.communicator.plugin.generalconfig.callconfig.DISABLED";
/**
* Creates the general configuration panel.
*/
public GeneralConfigurationPanel();
/**
* Returns the application name.
* @return the application name
*/
private String getApplicationName();
/**
* Initializes the auto start checkbox. Used only on windows.
* @return the created auto start check box
*/
private Component createAutoStartCheckBox();
/**
* Initializes the minimize instead of hide checkbox.
*/
public Component createMinimzeInsteadOfHideCheckBox();
/**
* Creates the message configuration panel.
* @return the created panel
*/
private Component createMessageConfigPanel();
/**
* Initializes the group messages check box.
* @return the created check box
*/
private Component createGroupMessagesCheckbox();
/**
* Initializes the window alert on message check box.
* @return the created check box
*/
private Component createChatAlertsOnMessageCheckbox();
/**
* Initializes the group messages check box.
* @return the created check box
*/
private Component createMultichatCheckbox();
/**
* Initializes the recent messages check box.
* @return the created check box
*/
private Component createRecentMessagesCheckbox();
/**
* Initializes the history panel.
* @return the created history panel
*/
private Component createHistoryPanel();
/**
* Initializes the send message configuration panel.
* @return the created message config panel
*/
private Component createSendMessagePanel();
/**
* Initializes typing notifications panel.
* @return the created check box
*/
private Component createTypingNitificationsCheckBox();
/**
* Initializes the bring to front check box.
* @return the created check box
*/
private Component createBringToFrontCheckBox();
/**
* Initializes the notification configuration panel.
* @return the created panel
*/
private Component createNotificationConfigPanel();
/**
* Model for the language combobox.
*/
private static class LocaleItem implements Comparable<LocaleItem> {
private Locale locale;
private int translated;
public LocaleItem( Locale locale, int translated);
@Override public int compareTo( LocaleItem o);
}
/**
* 3-column layout to show the language in the current locale, the locale of the language itself and the percentage of translation.
*/
@SuppressWarnings("serial") private static class LanguageDropDownRenderer extends JPanel implements ListCellRenderer {
JLabel[] labels=new JLabel[3];
public LanguageDropDownRenderer();
public Component getListCellRendererComponent( JList list, Object value, int index, boolean isSelected, boolean cellHasFocus);
}
/**
* Initializes the local configuration panel.
* @return the created component
*/
private Component createLocaleConfigPanel();
private static class Item {
public String key;
public String value;
public Item( String key, String value);
@Override public String toString();
}
/**
* Initializes the systray configuration panel.
* @return the created component
*/
private Component createSystrayeConfigPanel();
/**
* Creates the call configuration panel.
* @return the call configuration panel
*/
private Component createCallConfigPanel();
/**
* Creates the normalized phone number check box.
* @return the created component
*/
private Component createNormalizeNumberCheckBox();
/**
* Creates the accept phone number with alphabetical character check box.
* @return the created component
*/
private Component createAcceptPhoneNumberWithAlphaCharCheckBox();
/**
* Initializes the startup config panel.
* @return the created component
*/
public Component createStartupConfigPanel();
/**
* Initializes the update check panel.
* @return the created component
*/
public Component createUpdateCheckBox();
/**
* Sets the auto start.
* @param isAutoStart indicates if the auto start property is set to true orfalse
* @throws Exception if something goes wrong when obtaining the canonicalpath or when creating or saving the shortcut
*/
private void setAutostart( boolean isAutoStart) throws Exception;
/**
* Returns the current language configuration.
* @return the current locale
*/
public static Locale getCurrentLanguage();
/**
* Sets the current language configuration.
* @param locale the locale to set
*/
public static void setLanguage( Locale locale);
}
/**
* Returns the preferred width of the receiver.
* @param path the path, which bounds we obtain
* @param placeIn the initial rectangle of the path
* @return the bounds of the path
*/
@Override public Rectangle getBounds(TreePath path,Rectangle placeIn){
Rectangle rect=super.getBounds(path,placeIn);
if (rect != null && parentViewport != null) {
rect.width=parentViewport.getWidth() - 2;
}
return rect;
}
/**
* Gets the visual <tt>Component</tt> which depicts the local video being streamed to a specific <tt>CallPeer</tt>.
* @param peer the <tt>CallPeer</tt> to whom the local video which is to bedepicted by the returned visual <tt>Component</tt> is being streamed
* @return a visual <tt>Component</tt> which depicts the local video beingstreamed to the specified <tt>CallPeer</tt> if this telephony chooses to carry out the creation synchronously; <tt>null</tt> if this telephony chooses to create the requested visual <tt>Component</tt> asynchronously
* @throws OperationFailedException if creating the component fails forwhatever reason.
*/
public Component getLocalVisualComponent(CallPeer peer) throws OperationFailedException ;
/**
* Joins this chat room with the nickname of the local user so that the user would start receiving events and messages for it.
* @throws OperationFailedException with the corresponding code if an erroroccurs while joining the room.
*/
public void join() throws OperationFailedException {
joinAs(null,null);
}
/**
* Provides the value of a particular default field, null if undefined.
* @param field default field to retrieve
* @return value corresponding to default field
*/
public static String getDefault(Default field){
return DEFAULTS.get(field);
}
/**
* Extracts the devices for the current type.
* @return the devices.
*/
private List<CaptureDeviceViewModel> getDevices(){
if (devices != null) {
return devices;
}
AudioSystem audioSystem=deviceConfiguration.getAudioSystem();
if (audioSystem == null) {
return Collections.emptyList();
}
List<? extends CaptureDeviceInfo> infos=audioSystem.getDevices(type);
devices=new ArrayList<>(infos.size() + 1);
infos.forEach(i -> devices.add(new CaptureDeviceViewModel(i)));
devices.sort(Comparator.comparing(CaptureDeviceViewModel::toString));
devices.add(new CaptureDeviceViewModel(null));
return devices;
}
/**
* Returns the preferred width of the receiver.
* @param path the path, which bounds we obtain
* @param placeIn the initial rectangle of the path
* @return the bounds of the path
*/
@Override public Rectangle getBounds(TreePath path,Rectangle placeIn){
Rectangle rect=super.getBounds(path,placeIn);
if (rect != null && parentViewport != null) {
rect.width=parentViewport.getWidth() - 2;
}
return rect;
}
| public class GraphicUtils {
public static Shape createRoundedClipShape( int shapeWidth, int shapeHeight, int arcW, int arcH);
public static BufferedImage createClipImage( Graphics2D g, Shape shape);
public static void paintBorderGlow( Graphics2D g2, int glowWidth, Shape clipShape, Color glowOuterHigh, Color glowOuterLow);
private static Color getMixedColor( Color c1, float pct1, Color c2, float pct2);
}
public abstract class BindingPanel extends TransparentPanel {
private static final long serialVersionUID=0L;
private ArrayList<BindingEntry> contents=new ArrayList<BindingEntry>();
protected abstract void onUpdate( int index, BindingEntry entry, boolean isNew);
protected abstract void onClick( MouseEvent event, BindingEntry entry, BindingEntry.Field field);
public BindingPanel();
public boolean putBinding( int keyCode, int modifier, String action);
public boolean putBinding( KeyStroke shortcut, String action);
public boolean putBinding( KeyStroke shortcut, String action, int index);
public boolean putBinding( BindingEntry newEntry, int index);
public void putAllBindings( Map<KeyStroke,String> bindings);
public boolean removeBinding( BindingEntry entry);
public BindingEntry removeBinding( int index);
public void clearBindings();
public boolean contains( KeyStroke shortcut);
public int getBindingCount();
public int getBindingIndex( BindingEntry entry);
public BindingEntry getBinding( int index);
public ArrayList<BindingEntry> getBindings();
public LinkedHashMap<KeyStroke,String> getBindingMap();
public InputMap getBindingInputMap();
private class MouseTracker extends MouseInputAdapter {
public void mousePressed( MouseEvent event);
}
}
public class GeneralConfigurationPanel extends TransparentPanel {
private static final long serialVersionUID=0L;
private final org.slf4j.Logger logger=org.slf4j.LoggerFactory.getLogger(GeneralConfigurationPanel.class);
private static final String STARTUP_CONFIG_DISABLED_PROP="net.java.sip.communicator.plugin.generalconfig.startupconfig.DISABLED";
private static final String MESSAGE_CONFIG_DISABLED_PROP="net.java.sip.communicator.plugin.generalconfig.messageconfig.DISABLED";
private static final String AUTO_AWAY_CONFIG_DISABLED_PROP="net.java.sip.communicator.plugin.generalconfig.autoawayconfig.DISABLED";
private static final String NOTIFICATION_CONFIG_DISABLED_PROP="net.java.sip.communicator.plugin.generalconfig.notificationconfig.DISABLED";
private static final String LOCALE_CONFIG_DISABLED_PROP="net.java.sip.communicator.plugin.generalconfig.localeconfig.DISABLED";
private static final String SYSTRAY_CONFIG_DISABLED_PROP="net.java.sip.communicator.plugin.generalconfig.systrayconfig.DISABLED";
private static final String CALL_CONFIG_DISABLED_PROP="net.java.sip.communicator.plugin.generalconfig.callconfig.DISABLED";
public GeneralConfigurationPanel();
private String getApplicationName();
private Component createAutoStartCheckBox();
public Component createMinimzeInsteadOfHideCheckBox();
private Component createMessageConfigPanel();
private Component createGroupMessagesCheckbox();
private Component createChatAlertsOnMessageCheckbox();
private Component createMultichatCheckbox();
private Component createRecentMessagesCheckbox();
private Component createHistoryPanel();
private Component createSendMessagePanel();
private Component createTypingNitificationsCheckBox();
private Component createBringToFrontCheckBox();
private Component createNotificationConfigPanel();
private static class LocaleItem implements Comparable<LocaleItem> {
private Locale locale;
private int translated;
public LocaleItem( Locale locale, int translated);
public int compareTo( LocaleItem o);
}
private static class LanguageDropDownRenderer extends JPanel implements ListCellRenderer {
JLabel[] labels=new JLabel[3];
public LanguageDropDownRenderer();
public Component getListCellRendererComponent( JList list, Object value, int index, boolean isSelected, boolean cellHasFocus);
}
private Component createLocaleConfigPanel();
private static class Item {
public String key;
public String value;
public Item( String key, String value);
public String toString();
}
private Component createSystrayeConfigPanel();
private Component createCallConfigPanel();
private Component createNormalizeNumberCheckBox();
private Component createAcceptPhoneNumberWithAlphaCharCheckBox();
public Component createStartupConfigPanel();
public Component createUpdateCheckBox();
private void setAutostart( boolean isAutoStart) throws Exception;
public static Locale getCurrentLanguage();
public static void setLanguage( Locale locale);
}
/**
* Returns the preferred width of the receiver.
* @param path the path, which bounds we obtain
* @param placeIn the initial rectangle of the path
* @return the bounds of the path
*/
@Override public Rectangle getBounds(TreePath path,Rectangle placeIn){
Rectangle rect=super.getBounds(path,placeIn);
if (rect != null && parentViewport != null) {
rect.width=parentViewport.getWidth() - 2;
}
return rect;
}
/**
* Gets the visual <tt>Component</tt> which depicts the local video being streamed to a specific <tt>CallPeer</tt>.
* @param peer the <tt>CallPeer</tt> to whom the local video which is to bedepicted by the returned visual <tt>Component</tt> is being streamed
* @return a visual <tt>Component</tt> which depicts the local video beingstreamed to the specified <tt>CallPeer</tt> if this telephony chooses to carry out the creation synchronously; <tt>null</tt> if this telephony chooses to create the requested visual <tt>Component</tt> asynchronously
* @throws OperationFailedException if creating the component fails forwhatever reason.
*/
public Component getLocalVisualComponent(CallPeer peer) throws OperationFailedException ;
/**
* Joins this chat room with the nickname of the local user so that the user would start receiving events and messages for it.
* @throws OperationFailedException with the corresponding code if an erroroccurs while joining the room.
*/
public void join() throws OperationFailedException {
joinAs(null,null);
}
/**
* Provides the value of a particular default field, null if undefined.
* @param field default field to retrieve
* @return value corresponding to default field
*/
public static String getDefault(Default field){
return DEFAULTS.get(field);
}
/**
* Extracts the devices for the current type.
* @return the devices.
*/
private List<CaptureDeviceViewModel> getDevices(){
if (devices != null) {
return devices;
}
AudioSystem audioSystem=deviceConfiguration.getAudioSystem();
if (audioSystem == null) {
return Collections.emptyList();
}
List<? extends CaptureDeviceInfo> infos=audioSystem.getDevices(type);
devices=new ArrayList<>(infos.size() + 1);
infos.forEach(i -> devices.add(new CaptureDeviceViewModel(i)));
devices.sort(Comparator.comparing(CaptureDeviceViewModel::toString));
devices.add(new CaptureDeviceViewModel(null));
return devices;
}
/**
* Returns the preferred width of the receiver.
* @param path the path, which bounds we obtain
* @param placeIn the initial rectangle of the path
* @return the bounds of the path
*/
@Override public Rectangle getBounds(TreePath path,Rectangle placeIn){
Rectangle rect=super.getBounds(path,placeIn);
if (rect != null && parentViewport != null) {
rect.width=parentViewport.getWidth() - 2;
}
return rect;
}
| {"types": [{"GraphicsDevice": "GraphicUtils"}, {"Rectangle": "BindingPanel"}, {"GraphicsEnvironment": "GraphicUtils"}, {"GraphicsConfiguration": "GeneralConfigurationPanel"}], "methods": [{"getBounds": "getBounds"}, {"getLocalGraphicsEnvironment": "getLocalVisualComponent"}, {"union": "join"}, {"getDefaultConfiguration": "getDefault"}, {"getScreenDevices": "getDevices"}], "similar_methods": [{"getScreenBounds": "getBounds"}]} | [{"GraphicsDevice": {"retrieved_name": "GraphicUtils", "raw_body": "/** \n * The <tt>GraphicUtils</tt> is an utility class that gives access to some simple graphics operations, like an easy creating of a clipped shape or image, or painting of a border glow. Most of the code in this class is based on advices and examples in the \"Java 2D Trickery: Soft Clipping\".\n * @author Yana Stamcheva\n */\npublic class GraphicUtils {\n /** \n * Creates a rounded clipped shape with the given <tt>shapeWidth</tt>, <tt>shapeHeight</tt>, arc width and arc height.\n * @param shapeWidth the width of the shape to create\n * @param shapeHeight the height of the shape to create\n * @param arcW the width of the arc to use to round the corners of thenewly created shape\n * @param arcH the height of the arc to use to round the corners of thenewly created shape\n * @return the created shape\n */\n public static Shape createRoundedClipShape( int shapeWidth, int shapeHeight, int arcW, int arcH);\n /** \n * Creates a clipped image from the given <tt>shape</tt>.\n * @param shape the shape from which to create the image\n * @param g the <tt>Graphics</tt> object giving access to the graphicsdevice configuration\n * @return the created <tt>BufferedImage</tt>\n */\n public static BufferedImage createClipImage( Graphics2D g, Shape shape);\n /** \n * Paints border glow over the given <tt>clipShape</tt> with the given glow high and low colors and the given <tt>glowWidth</tt>.\n * @param g2 the <tt>Graphics</tt> object to use for painting\n * @param glowWidth the width of the glow\n * @param clipShape the shape where to paint the glow\n * @param glowOuterHigh the color which will paint the higher glow\n * @param glowOuterLow the color which will paint the lower glow\n */\n public static void paintBorderGlow( Graphics2D g2, int glowWidth, Shape clipShape, Color glowOuterHigh, Color glowOuterLow);\n /** \n * Returns a mixed color from color <tt>c1</tt> and <tt>c2</tt>.\n * @param c1 the start color\n * @param pct1 the first color coefficient of the mix between 0 and 1\n * @param c2 the end color\n * @param pct2 the second color coefficient of the mix between 0 and 1\n * @return the new mixed color\n */\n private static Color getMixedColor( Color c1, float pct1, Color c2, float pct2);\n}\n", "raw_body_no_cmt": "public class GraphicUtils {\n public static Shape createRoundedClipShape( int shapeWidth, int shapeHeight, int arcW, int arcH);\n public static BufferedImage createClipImage( Graphics2D g, Shape shape);\n public static void paintBorderGlow( Graphics2D g2, int glowWidth, Shape clipShape, Color glowOuterHigh, Color glowOuterLow);\n private static Color getMixedColor( Color c1, float pct1, Color c2, float pct2);\n}\n"}}, {"Rectangle": {"retrieved_name": "BindingPanel", "raw_body": "/** \n * Panel containing a listing of current keybinding mappings. This contains methods that can be overwritten to provide easy editing functionality and display logic. Note that this does not support the manual addition or removal of BindingEntry components. However this is designed to tolerate the changing of entry visibility (including individual fields) and the manual addition and removal of extra components either to this panel or its BindingEntries.<br> This represents a mapping of keystrokes to strings, and hence duplicate shortcuts aren't supported. An exception is made in the case of disabled shortcuts, but to keep mappings unique duplicate actions among disabled entries are not permitted.\n * @author Damian Johnson (atagar1@gmail.com)\n * @version September 1, 2007\n */\npublic abstract class BindingPanel extends TransparentPanel {\n /** \n * Serial version UID.\n */\n private static final long serialVersionUID=0L;\n private ArrayList<BindingEntry> contents=new ArrayList<BindingEntry>();\n /** \n * Method called whenever an entry is either added or shifts in the display. For instance, if the second entry is removed then this is called on the third to last elements.\n * @param index newly assigned index of entry\n * @param entry entry that has been added or shifted\n * @param isNew if true the entry is new to the display, false otherwise\n */\n protected abstract void onUpdate( int index, BindingEntry entry, boolean isNew);\n /** \n * Method called upon any mouse clicks within a BindingEntry in the display.\n * @param event fired mouse event that triggered method call\n * @param entry entry on which the click landed\n * @param field field of entry on which the click landed, null if not arecognized field\n */\n protected abstract void onClick( MouseEvent event, BindingEntry entry, BindingEntry.Field field);\n /** \n * Constructor.\n */\n public BindingPanel();\n /** \n * Adds a new key binding mapping to the end of the listing. If this already contains the shortcut then the previous entry is replaced instead (not triggering the onUpdate method). Disabled shortcuts trigger replacement on duplicate actions instead. This uses the normal parameters used to generate key stokes, such as: <pre> bindingPanel.putBinding('Y', 0, "Confirm Selection"); bindingPanel.putBinding(KeyEvent.VK_DELETE, KeyEvent.CTRL_MASK | KeyEvent.ALT_MASK, "Kill Process"); </pre>\n * @param keyCode key code of keystroke component of mapping\n * @param modifier modifiers of keystroke component of mapping\n * @param action string component of mapping\n * @return true if contents did not already include shortcut\n */\n public boolean putBinding( int keyCode, int modifier, String action);\n /** \n * Adds a new key binding mapping to the end of the listing. If this already contains the shortcut then the previous entry is replaced instead (not triggering the onUpdate method). Disabled shortcuts trigger replacement on duplicate actions instead.\n * @param shortcut keystroke component of mapping\n * @param action string component of mapping\n * @return true if contents did not already include shortcut\n */\n public boolean putBinding( KeyStroke shortcut, String action);\n /** \n * Adds a new key binding mapping to a particular index of the listing. If this already contains the shortcut then the previous entry is replaced instead (not triggering the onUpdate method). Disabled shortcuts trigger replacement on duplicate actions instead.\n * @param shortcut keystroke component of mapping\n * @param action string component of mapping\n * @param index location in which to insert mapping\n * @return true if contents did not already include shortcut\n * @throws IndexOutOfBoundsException if index is out of range (index < 0 ||index > getBindingCount()).\n */\n public boolean putBinding( KeyStroke shortcut, String action, int index);\n /** \n * Adds a new key binding mapping to a particular index of the listing. If this already contains the shortcut then the previous entry is replaced instead (not triggering the onUpdate method). Disabled shortcuts trigger replacement on duplicate actions instead.\n * @param newEntry entry to add to contents\n * @param index location in which to insert mapping\n * @return true if contents did not already include shortcut\n * @throws IndexOutOfBoundsException if index is out of range (index < 0 ||index > getBindingCount()).\n */\n public boolean putBinding( BindingEntry newEntry, int index);\n /** \n * Adds a collection of new key binding mappings to the end of the listing. If any shortcuts are already contained then the previous entries are replaced (not triggering the onUpdate method). Disabled shortcuts trigger replacement on duplicate actions instead.\n * @param bindings mapping between keystrokes and actions to be added\n */\n public void putAllBindings( Map<KeyStroke,String> bindings);\n /** \n * Removes a particular binding from the contents.\n * @param entry binding to be removed\n * @return true if binding was in the contents, false otherwise\n */\n public boolean removeBinding( BindingEntry entry);\n /** \n * Removes the binding at a particular index of the listing.\n * @param index from which to remove entry\n * @return the entry that was removed from the contents\n * @throws IndexOutOfBoundsException if index is out of range (index < 0 ||index > getBindingCount()).\n */\n public BindingEntry removeBinding( int index);\n /** \n * Removes all bindings from the panel.\n */\n public void clearBindings();\n /** \n * Returns if a keystroke is in the panel's current contents. This provides a preemptive means of checking if adding a non-disabled shortcut would cause a replacement.\n * @param shortcut keystroke to be checked against contents\n * @return true if contents includes the shortcut, false otherwise\n */\n public boolean contains( KeyStroke shortcut);\n /** \n * Provides number of key bindings currently present.\n * @return number of key bindings in the display\n */\n public int getBindingCount();\n /** \n * Provides the index of a particular entry.\n * @param entry entry for which the index should be returned\n * @return entry index, -1 if not found\n */\n public int getBindingIndex( BindingEntry entry);\n /** \n * Provides a binding at a particular index.\n * @param index index from which to retrieve binding.\n * @return the entry at the specified position in this list\n */\n public BindingEntry getBinding( int index);\n /** \n * Provides listing of the current keybinding entries.\n * @return list of current entry contents\n */\n public ArrayList<BindingEntry> getBindings();\n /** \n * Provides the mapping between keystrokes and actions represented by the contents of the display. Disabled entries aren't included in the mapping.\n * @return mapping between contained keystrokes and their associated actions\n */\n public LinkedHashMap<KeyStroke,String> getBindingMap();\n /** \n * Provides an input map associating keystrokes to actions according to the contents of the display. Disabled entries aren't included in the mapping.\n * @return input mapping between contained keystrokes and their associatedactions\n */\n public InputMap getBindingInputMap();\nprivate class MouseTracker extends MouseInputAdapter {\n @Override public void mousePressed( MouseEvent event);\n }\n}\n", "raw_body_no_cmt": "public abstract class BindingPanel extends TransparentPanel {\n private static final long serialVersionUID=0L;\n private ArrayList<BindingEntry> contents=new ArrayList<BindingEntry>();\n protected abstract void onUpdate( int index, BindingEntry entry, boolean isNew);\n protected abstract void onClick( MouseEvent event, BindingEntry entry, BindingEntry.Field field);\n public BindingPanel();\n public boolean putBinding( int keyCode, int modifier, String action);\n public boolean putBinding( KeyStroke shortcut, String action);\n public boolean putBinding( KeyStroke shortcut, String action, int index);\n public boolean putBinding( BindingEntry newEntry, int index);\n public void putAllBindings( Map<KeyStroke,String> bindings);\n public boolean removeBinding( BindingEntry entry);\n public BindingEntry removeBinding( int index);\n public void clearBindings();\n public boolean contains( KeyStroke shortcut);\n public int getBindingCount();\n public int getBindingIndex( BindingEntry entry);\n public BindingEntry getBinding( int index);\n public ArrayList<BindingEntry> getBindings();\n public LinkedHashMap<KeyStroke,String> getBindingMap();\n public InputMap getBindingInputMap();\nprivate class MouseTracker extends MouseInputAdapter {\n public void mousePressed( MouseEvent event);\n }\n}\n"}}, {"GraphicsConfiguration": {"retrieved_name": "GeneralConfigurationPanel", "raw_body": "/** \n * The general configuration form.\n * @author Yana Stamcheva\n */\npublic class GeneralConfigurationPanel extends TransparentPanel {\n /** \n * Serial version UID.\n */\n private static final long serialVersionUID=0L;\n /** \n * The <tt>Logger</tt> used by this <tt>GeneralConfigurationPanel</tt> for logging output.\n */\n private final org.slf4j.Logger logger=org.slf4j.LoggerFactory.getLogger(GeneralConfigurationPanel.class);\n /** \n * Indicates if the Startup configuration panel should be disabled, i.e. not visible to the user.\n */\n private static final String STARTUP_CONFIG_DISABLED_PROP=\"net.java.sip.communicator.plugin.generalconfig.startupconfig.DISABLED\";\n /** \n * Indicates if the Message configuration panel should be disabled, i.e. not visible to the user.\n */\n private static final String MESSAGE_CONFIG_DISABLED_PROP=\"net.java.sip.communicator.plugin.generalconfig.messageconfig.DISABLED\";\n /** \n * Indicates if the AutoAway configuration panel should be disabled, i.e. not visible to the user.\n */\n private static final String AUTO_AWAY_CONFIG_DISABLED_PROP=\"net.java.sip.communicator.plugin.generalconfig.autoawayconfig.DISABLED\";\n /** \n * Indicates if the Notification configuration panel should be disabled, i.e. not visible to the user.\n */\n private static final String NOTIFICATION_CONFIG_DISABLED_PROP=\"net.java.sip.communicator.plugin.generalconfig.notificationconfig.DISABLED\";\n /** \n * Indicates if the Locale configuration panel should be disabled, i.e. not visible to the user.\n */\n private static final String LOCALE_CONFIG_DISABLED_PROP=\"net.java.sip.communicator.plugin.generalconfig.localeconfig.DISABLED\";\n /** \n * Indicates if the systray config panel should be disabled, i.e. not visible to the user.\n */\n private static final String SYSTRAY_CONFIG_DISABLED_PROP=\"net.java.sip.communicator.plugin.generalconfig.systrayconfig.DISABLED\";\n /** \n * Indicates if the Call configuration panel should be disabled, i.e. not visible to the user.\n */\n private static final String CALL_CONFIG_DISABLED_PROP=\"net.java.sip.communicator.plugin.generalconfig.callconfig.DISABLED\";\n /** \n * Creates the general configuration panel.\n */\n public GeneralConfigurationPanel();\n /** \n * Returns the application name.\n * @return the application name\n */\n private String getApplicationName();\n /** \n * Initializes the auto start checkbox. Used only on windows.\n * @return the created auto start check box\n */\n private Component createAutoStartCheckBox();\n /** \n * Initializes the minimize instead of hide checkbox.\n */\n public Component createMinimzeInsteadOfHideCheckBox();\n /** \n * Creates the message configuration panel.\n * @return the created panel\n */\n private Component createMessageConfigPanel();\n /** \n * Initializes the group messages check box.\n * @return the created check box\n */\n private Component createGroupMessagesCheckbox();\n /** \n * Initializes the window alert on message check box.\n * @return the created check box\n */\n private Component createChatAlertsOnMessageCheckbox();\n /** \n * Initializes the group messages check box.\n * @return the created check box\n */\n private Component createMultichatCheckbox();\n /** \n * Initializes the recent messages check box.\n * @return the created check box\n */\n private Component createRecentMessagesCheckbox();\n /** \n * Initializes the history panel.\n * @return the created history panel\n */\n private Component createHistoryPanel();\n /** \n * Initializes the send message configuration panel.\n * @return the created message config panel\n */\n private Component createSendMessagePanel();\n /** \n * Initializes typing notifications panel.\n * @return the created check box\n */\n private Component createTypingNitificationsCheckBox();\n /** \n * Initializes the bring to front check box.\n * @return the created check box\n */\n private Component createBringToFrontCheckBox();\n /** \n * Initializes the notification configuration panel.\n * @return the created panel\n */\n private Component createNotificationConfigPanel();\n /** \n * Model for the language combobox.\n */\nprivate static class LocaleItem implements Comparable<LocaleItem> {\n private Locale locale;\n private int translated;\n public LocaleItem( Locale locale, int translated);\n @Override public int compareTo( LocaleItem o);\n }\n /** \n * 3-column layout to show the language in the current locale, the locale of the language itself and the percentage of translation.\n */\n@SuppressWarnings(\"serial\") private static class LanguageDropDownRenderer extends JPanel implements ListCellRenderer {\n JLabel[] labels=new JLabel[3];\n public LanguageDropDownRenderer();\n public Component getListCellRendererComponent( JList list, Object value, int index, boolean isSelected, boolean cellHasFocus);\n }\n /** \n * Initializes the local configuration panel.\n * @return the created component\n */\n private Component createLocaleConfigPanel();\nprivate static class Item {\n public String key;\n public String value;\n public Item( String key, String value);\n @Override public String toString();\n }\n /** \n * Initializes the systray configuration panel.\n * @return the created component\n */\n private Component createSystrayeConfigPanel();\n /** \n * Creates the call configuration panel.\n * @return the call configuration panel\n */\n private Component createCallConfigPanel();\n /** \n * Creates the normalized phone number check box.\n * @return the created component\n */\n private Component createNormalizeNumberCheckBox();\n /** \n * Creates the accept phone number with alphabetical character check box.\n * @return the created component\n */\n private Component createAcceptPhoneNumberWithAlphaCharCheckBox();\n /** \n * Initializes the startup config panel.\n * @return the created component\n */\n public Component createStartupConfigPanel();\n /** \n * Initializes the update check panel.\n * @return the created component\n */\n public Component createUpdateCheckBox();\n /** \n * Sets the auto start.\n * @param isAutoStart indicates if the auto start property is set to true orfalse\n * @throws Exception if something goes wrong when obtaining the canonicalpath or when creating or saving the shortcut\n */\n private void setAutostart( boolean isAutoStart) throws Exception;\n /** \n * Returns the current language configuration.\n * @return the current locale\n */\n public static Locale getCurrentLanguage();\n /** \n * Sets the current language configuration.\n * @param locale the locale to set\n */\n public static void setLanguage( Locale locale);\n}\n", "raw_body_no_cmt": "public class GeneralConfigurationPanel extends TransparentPanel {\n private static final long serialVersionUID=0L;\n private final org.slf4j.Logger logger=org.slf4j.LoggerFactory.getLogger(GeneralConfigurationPanel.class);\n private static final String STARTUP_CONFIG_DISABLED_PROP=\"net.java.sip.communicator.plugin.generalconfig.startupconfig.DISABLED\";\n private static final String MESSAGE_CONFIG_DISABLED_PROP=\"net.java.sip.communicator.plugin.generalconfig.messageconfig.DISABLED\";\n private static final String AUTO_AWAY_CONFIG_DISABLED_PROP=\"net.java.sip.communicator.plugin.generalconfig.autoawayconfig.DISABLED\";\n private static final String NOTIFICATION_CONFIG_DISABLED_PROP=\"net.java.sip.communicator.plugin.generalconfig.notificationconfig.DISABLED\";\n private static final String LOCALE_CONFIG_DISABLED_PROP=\"net.java.sip.communicator.plugin.generalconfig.localeconfig.DISABLED\";\n private static final String SYSTRAY_CONFIG_DISABLED_PROP=\"net.java.sip.communicator.plugin.generalconfig.systrayconfig.DISABLED\";\n private static final String CALL_CONFIG_DISABLED_PROP=\"net.java.sip.communicator.plugin.generalconfig.callconfig.DISABLED\";\n public GeneralConfigurationPanel();\n private String getApplicationName();\n private Component createAutoStartCheckBox();\n public Component createMinimzeInsteadOfHideCheckBox();\n private Component createMessageConfigPanel();\n private Component createGroupMessagesCheckbox();\n private Component createChatAlertsOnMessageCheckbox();\n private Component createMultichatCheckbox();\n private Component createRecentMessagesCheckbox();\n private Component createHistoryPanel();\n private Component createSendMessagePanel();\n private Component createTypingNitificationsCheckBox();\n private Component createBringToFrontCheckBox();\n private Component createNotificationConfigPanel();\n private static class LocaleItem implements Comparable<LocaleItem> {\n private Locale locale;\n private int translated;\n public LocaleItem( Locale locale, int translated);\n public int compareTo( LocaleItem o);\n }\n private static class LanguageDropDownRenderer extends JPanel implements ListCellRenderer {\n JLabel[] labels=new JLabel[3];\n public LanguageDropDownRenderer();\n public Component getListCellRendererComponent( JList list, Object value, int index, boolean isSelected, boolean cellHasFocus);\n }\n private Component createLocaleConfigPanel();\nprivate static class Item {\n public String key;\n public String value;\n public Item( String key, String value);\n public String toString();\n }\n private Component createSystrayeConfigPanel();\n private Component createCallConfigPanel();\n private Component createNormalizeNumberCheckBox();\n private Component createAcceptPhoneNumberWithAlphaCharCheckBox();\n public Component createStartupConfigPanel();\n public Component createUpdateCheckBox();\n private void setAutostart( boolean isAutoStart) throws Exception;\n public static Locale getCurrentLanguage();\n public static void setLanguage( Locale locale);\n}\n"}}] | [{"getBounds": {"retrieved_name": "getBounds", "raw_body": "/** \n * Returns the preferred width of the receiver.\n * @param path the path, which bounds we obtain\n * @param placeIn the initial rectangle of the path\n * @return the bounds of the path\n */\n@Override public Rectangle getBounds(TreePath path,Rectangle placeIn){\n Rectangle rect=super.getBounds(path,placeIn);\n if (rect != null && parentViewport != null) {\n rect.width=parentViewport.getWidth() - 2;\n }\n return rect;\n}\n"}}, {"getLocalGraphicsEnvironment": {"retrieved_name": "getLocalVisualComponent", "raw_body": "/** \n * Gets the visual <tt>Component</tt> which depicts the local video being streamed to a specific <tt>CallPeer</tt>.\n * @param peer the <tt>CallPeer</tt> to whom the local video which is to bedepicted by the returned visual <tt>Component</tt> is being streamed\n * @return a visual <tt>Component</tt> which depicts the local video beingstreamed to the specified <tt>CallPeer</tt> if this telephony chooses to carry out the creation synchronously; <tt>null</tt> if this telephony chooses to create the requested visual <tt>Component</tt> asynchronously\n * @throws OperationFailedException if creating the component fails forwhatever reason.\n */\npublic Component getLocalVisualComponent(CallPeer peer) throws OperationFailedException ;\n"}}, {"union": {"retrieved_name": "join", "raw_body": "/** \n * Joins this chat room with the nickname of the local user so that the user would start receiving events and messages for it.\n * @throws OperationFailedException with the corresponding code if an erroroccurs while joining the room.\n */\npublic void join() throws OperationFailedException {\n joinAs(null,null);\n}\n"}}, {"getDefaultConfiguration": {"retrieved_name": "getDefault", "raw_body": "/** \n * Provides the value of a particular default field, null if undefined.\n * @param field default field to retrieve\n * @return value corresponding to default field\n */\npublic static String getDefault(Default field){\n return DEFAULTS.get(field);\n}\n"}}, {"getScreenDevices": {"retrieved_name": "getDevices", "raw_body": "/** \n * Extracts the devices for the current type.\n * @return the devices.\n */\nprivate List<CaptureDeviceViewModel> getDevices(){\n if (devices != null) {\n return devices;\n }\n AudioSystem audioSystem=deviceConfiguration.getAudioSystem();\n if (audioSystem == null) {\n return Collections.emptyList();\n }\n List<? extends CaptureDeviceInfo> infos=audioSystem.getDevices(type);\n devices=new ArrayList<>(infos.size() + 1);\n infos.forEach(i -> devices.add(new CaptureDeviceViewModel(i)));\n devices.sort(Comparator.comparing(CaptureDeviceViewModel::toString));\n devices.add(new CaptureDeviceViewModel(null));\n return devices;\n}\n"}}] | [{"getScreenBounds": {"retrieved_name": "getBounds", "raw_body": "/** \n * Returns the preferred width of the receiver.\n * @param path the path, which bounds we obtain\n * @param placeIn the initial rectangle of the path\n * @return the bounds of the path\n */\n@Override public Rectangle getBounds(TreePath path,Rectangle placeIn){\n Rectangle rect=super.getBounds(path,placeIn);\n if (rect != null && parentViewport != null) {\n rect.width=parentViewport.getWidth() - 2;\n }\n return rect;\n}\n"}}] |
|
graphhopper_graphhopper | graphhopper/core/src/main/java/com/graphhopper/routing/ch/NodeBasedWitnessPathSearcher.java | NodeBasedWitnessPathSearcher | findUpperBound | class NodeBasedWitnessPathSearcher {
private final PrepareGraphEdgeExplorer outEdgeExplorer;
private final double[] weights;
private final IntArrayList changedNodes;
private final IntFloatBinaryHeap heap;
private int ignoreNode = -1;
private int settledNodes = 0;
public NodeBasedWitnessPathSearcher(CHPreparationGraph graph) {
outEdgeExplorer = graph.createOutEdgeExplorer();
weights = new double[graph.getNodes()];
Arrays.fill(weights, Double.POSITIVE_INFINITY);
heap = new IntFloatBinaryHeap(1000);
changedNodes = new IntArrayList();
}
/**
* Sets up a search for given start node and an ignored node. The shortest path tree will be re-used for different
* target nodes until this method is called again.
*/
public void init(int startNode, int ignoreNode) {
reset();
this.ignoreNode = ignoreNode;
weights[startNode] = 0;
changedNodes.add(startNode);
heap.insert(0, startNode);
}
/**
* Runs or continues a Dijkstra search starting at the startNode and ignoring the ignoreNode given in init().
* If the shortest path is found we return its weight. However, this method also returns early if any path was
* found for which the weight is below or equal to the given acceptedWeight, or the given maximum number of settled
* nodes is exceeded. In these cases the returned weight can be larger than the actual weight of the shortest path.
* In any case we get an upper bound for the real shortest path weight.
*
* @param targetNode the target of the search. if this node is settled we return the weight of the shortest path
* @param acceptedWeight once we find a path with weight smaller than or equal to this we return the weight. the
* returned weight might be larger than the weight of the real shortest path. if there is
* no path with weight smaller than or equal to this we stop the search and return the best
* path we found.
* @param maxSettledNodes once the number of settled nodes exceeds this number we return the currently found best
* weight path. in this case we might not have found a path at all.
* @return the weight of the found path or {@link Double#POSITIVE_INFINITY} if no path was found
*/
public double findUpperBound(int targetNode, double acceptedWeight, int maxSettledNodes) {<FILL_FUNCTION_BODY>}
public int getSettledNodes() {
return settledNodes;
}
private void reset() {
for (IntCursor c : changedNodes)
weights[c.value] = Double.POSITIVE_INFINITY;
changedNodes.elementsCount = 0;
heap.clear();
ignoreNode = -1;
settledNodes = 0;
}
/**
* @return currently used memory in MB (approximately)
*/
public String getMemoryUsageAsString() {
return (8L * weights.length
+ changedNodes.buffer.length * 4L
+ heap.getMemoryUsage()
) / Helper.MB + "MB";
}
} |
// todo: for historic reasons we count the number of settled nodes for each call of this method
// *not* the total number of settled nodes since starting the search (which corresponds
// to the size of the settled part of the shortest path tree). it's probably worthwhile
// to change this in the future.
while (!heap.isEmpty() && settledNodes < maxSettledNodes && heap.peekKey() <= acceptedWeight) {
if (weights[targetNode] <= acceptedWeight)
// we found *a* path to the target node (not necessarily the shortest), and the weight is acceptable, so we stop
return weights[targetNode];
int node = heap.poll();
PrepareGraphEdgeIterator iter = outEdgeExplorer.setBaseNode(node);
while (iter.next()) {
int adjNode = iter.getAdjNode();
if (adjNode == ignoreNode)
continue;
double weight = weights[node] + iter.getWeight();
if (Double.isInfinite(weight))
continue;
double adjWeight = weights[adjNode];
if (adjWeight == Double.POSITIVE_INFINITY) {
weights[adjNode] = weight;
heap.insert(weight, adjNode);
changedNodes.add(adjNode);
} else if (weight < adjWeight) {
weights[adjNode] = weight;
heap.update(weight, adjNode);
}
}
settledNodes++;
if (node == targetNode)
// we have settled the target node, we now know the exact weight of the shortest path and return
return weights[node];
}
return weights[targetNode];
|
while (heap.size() > 0) {
int currentNode = heap.extractMin();
if (currentNode == targetNode)
return weights[currentNode];
if (weights[currentNode] > acceptedWeight)
return weights[currentNode];
if (settledNodes >= maxSettledNodes)
return weights[currentNode];
settledNodes++;
for (PrepareGraphEdge edge : outEdgeExplorer.getOutEdges(currentNode)) {
int nextNode = edge.getTarget();
if (nextNode == ignoreNode)
continue;
double newWeight = weights[currentNode] + edge.getWeight();
if (newWeight < weights[nextNode]) {
weights[nextNode] = newWeight;
changedNodes.add(nextNode);
heap.insert(newWeight, nextNode);
}
}
}
return Double.POSITIVE_INFINITY;
| [
"IntArrayList",
"IntFloatBinaryHeap",
"PrepareGraphEdgeExplorer",
"PrepareGraphEdge"
] | [
"add",
"size",
"getTarget",
"extractMin",
"insert",
"getOutEdges",
"getWeight"
] | [
"PrepareGraphEdgeIterator",
"IntFloatBinaryHeap",
"PrepareGraphEdgeExplorer",
"IntArrayList"
] | [
"add",
"getWeight",
"isEmpty",
"insert",
"setBaseNode",
"update",
"isInfinite",
"poll",
"peekKey",
"getAdjNode",
"next"
] | {
"methods": [
"add",
"size",
"getTarget",
"extractMin",
"insert",
"getOutEdges",
"getWeight"
],
"similar_methods": [
"findUpperBound"
],
"types": [
"IntArrayList",
"IntFloatBinaryHeap",
"PrepareGraphEdgeExplorer",
"PrepareGraphEdge"
]
} | public class LineIntIndex {
static final int START_POINTER=1;
final DataAccess dataAccess;
private final BBox bounds;
private int minResolutionInMeter=300;
private int size;
private int leafs;
private int checksum;
private IndexStructureInfo indexStructureInfo;
private int[] entries;
private byte[] shifts;
private boolean initialized=false;
private SpatialKeyAlgo keyAlgo;
public LineIntIndex( BBox bBox, Directory dir, String name);
public LineIntIndex( BBox bBox, Directory dir, String name, DAType daType);
public boolean loadExisting();
public void store( InMemConstructionIndex inMem);
private int store( InMemConstructionIndex.InMemEntry entry, int intPointer);
private void fillIDs( long keyPart, IntConsumer consumer);
public void query( BBox queryShape, final LocationIndex.Visitor function);
public void query( LocationIndex.TileFilter tileFilter, final LocationIndex.Visitor function);
private void query( int intPointer, LocationIndex.TileFilter tileFilter, double minLat, double minLon, double deltaLatPerDepth, double deltaLonPerDepth, LocationIndex.Visitor function, int depth);
/**
* This method collects edge ids from the neighborhood of a point and puts them into foundEntries. <p> If it is called with iteration = 0, it just looks in the tile the query point is in. If it is called with iteration = 0,1,2,.., it will look in additional tiles further and further from the start tile. (In a square that grows by one pixel in all four directions per iteration). <p> See discussion at issue #221. <p>
*/
public void findEdgeIdsInNeighborhood( double queryLat, double queryLon, int iteration, IntConsumer foundEntries);
public int getChecksum();
public int getMinResolutionInMeter();
public void setMinResolutionInMeter( int minResolutionInMeter);
public void flush();
public void close();
public boolean isClosed();
public long getCapacity();
public void setChecksum( int checksum);
public int getSize();
public int getLeafs();
}
/**
* This class is a partial copy of the class org.apache.commons.collections.BinaryHeap for just the min heap and primitive, sorted float keys and associated int elements. <p> The library can be found here: https://commons.apache.org/proper/commons-collections/
*/
public class IntFloatBinaryHeap {
private static final int GROW_FACTOR=2;
private int size;
private int[] elements;
private float[] keys;
public IntFloatBinaryHeap();
public IntFloatBinaryHeap( int initialCapacity);
private boolean isFull();
public void update( double key, int element);
public void insert( double key, int element);
public int peekElement();
public float peekKey();
public int poll();
/**
* Percolates element down heap from the array position given by the index.
*/
final void percolateDownMinHeap( final int index);
final void percolateUpMinHeap( final int index);
public boolean isEmpty();
public int getSize();
public void clear();
void trimTo( int toSize);
public void ensureCapacity( int capacity);
public long getCapacity();
public long getMemoryUsage();
}
public interface PrepareGraphEdgeExplorer {
PrepareGraphEdgeIterator setBaseNode( int node);
}
public void add(PointAccess nodeAccess,int index){
if (is3D) add(nodeAccess.getLat(index),nodeAccess.getLon(index),nodeAccess.getEle(index));
else add(nodeAccess.getLat(index),nodeAccess.getLon(index));
}
@Override public int size(){
return 0;
}
public <T>T getObject(String key,T _default){
Object object=map.get(key);
return object == null ? _default : (T)object;
}
public static void extractMeter(int edgeId,EdgeIntAccess edgeIntAccess,ReaderWay way,DecimalEncodedValue valueEncoder,List<String> keys){
final String rawValue=way.getFirstValue(keys);
double value=stringToMeter(rawValue);
if (Double.isNaN(value)) value=Double.POSITIVE_INFINITY;
valueEncoder.setDecimal(false,edgeId,edgeIntAccess,value);
}
public void insert(double key,int element){
if (isFull()) {
ensureCapacity(elements.length * GROW_FACTOR);
}
size++;
elements[size]=element;
keys[size]=(float)key;
percolateUpMinHeap(size);
}
List<Edge> getOutEdges(Point p){
List<Edge> result=outEdgesByNextPoint.get(p);
return result == null ? Collections.emptyList() : result;
}
/**
* This weight will be updated during the algorithm. The initial value is maximum double.
*/
public double getWeight(){
return weight;
}
public BBox getBounds(){
return bounds;
}
| public class LineIntIndex {
static final int START_POINTER=1;
final DataAccess dataAccess;
private final BBox bounds;
private int minResolutionInMeter=300;
private int size;
private int leafs;
private int checksum;
private IndexStructureInfo indexStructureInfo;
private int[] entries;
private byte[] shifts;
private boolean initialized=false;
private SpatialKeyAlgo keyAlgo;
public LineIntIndex( BBox bBox, Directory dir, String name);
public LineIntIndex( BBox bBox, Directory dir, String name, DAType daType);
public boolean loadExisting();
public void store( InMemConstructionIndex inMem);
private int store( InMemConstructionIndex.InMemEntry entry, int intPointer);
private void fillIDs( long keyPart, IntConsumer consumer);
public void query( BBox queryShape, final LocationIndex.Visitor function);
public void query( LocationIndex.TileFilter tileFilter, final LocationIndex.Visitor function);
private void query( int intPointer, LocationIndex.TileFilter tileFilter, double minLat, double minLon, double deltaLatPerDepth, double deltaLonPerDepth, LocationIndex.Visitor function, int depth);
public void findEdgeIdsInNeighborhood( double queryLat, double queryLon, int iteration, IntConsumer foundEntries);
public int getChecksum();
public int getMinResolutionInMeter();
public void setMinResolutionInMeter( int minResolutionInMeter);
public void flush();
public void close();
public boolean isClosed();
public long getCapacity();
public void setChecksum( int checksum);
public int getSize();
public int getLeafs();
}
public class IntFloatBinaryHeap {
private static final int GROW_FACTOR=2;
private int size;
private int[] elements;
private float[] keys;
public IntFloatBinaryHeap();
public IntFloatBinaryHeap( int initialCapacity);
private boolean isFull();
public void update( double key, int element);
public void insert( double key, int element);
public int peekElement();
public float peekKey();
public int poll();
final void percolateDownMinHeap( final int index);
final void percolateUpMinHeap( final int index);
public boolean isEmpty();
public int getSize();
public void clear();
void trimTo( int toSize);
public void ensureCapacity( int capacity);
public long getCapacity();
public long getMemoryUsage();
}
public interface PrepareGraphEdgeExplorer {
PrepareGraphEdgeIterator setBaseNode( int node);
}
public void add(PointAccess nodeAccess,int index){
if (is3D) add(nodeAccess.getLat(index),nodeAccess.getLon(index),nodeAccess.getEle(index));
else add(nodeAccess.getLat(index),nodeAccess.getLon(index));
}
@Override public int size(){
return 0;
}
public <T>T getObject(String key,T _default){
Object object=map.get(key);
return object == null ? _default : (T)object;
}
public static void extractMeter(int edgeId,EdgeIntAccess edgeIntAccess,ReaderWay way,DecimalEncodedValue valueEncoder,List<String> keys){
final String rawValue=way.getFirstValue(keys);
double value=stringToMeter(rawValue);
if (Double.isNaN(value)) value=Double.POSITIVE_INFINITY;
valueEncoder.setDecimal(false,edgeId,edgeIntAccess,value);
}
public void insert(double key,int element){
if (isFull()) {
ensureCapacity(elements.length * GROW_FACTOR);
}
size++;
elements[size]=element;
keys[size]=(float)key;
percolateUpMinHeap(size);
}
List<Edge> getOutEdges(Point p){
List<Edge> result=outEdgesByNextPoint.get(p);
return result == null ? Collections.emptyList() : result;
}
/**
* This weight will be updated during the algorithm. The initial value is maximum double.
*/
public double getWeight(){
return weight;
}
public BBox getBounds(){
return bounds;
}
| {"types": [{"IntArrayList": "LineIntIndex"}, {"IntFloatBinaryHeap": "IntFloatBinaryHeap"}, {"PrepareGraphEdgeExplorer": "PrepareGraphEdgeExplorer"}, {"PrepareGraphEdge": "PrepareGraphEdgeExplorer"}], "methods": [{"add": "add"}, {"size": "size"}, {"getTarget": "getObject"}, {"extractMin": "extractMeter"}, {"insert": "insert"}, {"getOutEdges": "getOutEdges"}, {"getWeight": "getWeight"}], "similar_methods": [{"findUpperBound": "getBounds"}]} | [{"IntArrayList": {"retrieved_name": "LineIntIndex", "raw_body": "public class LineIntIndex {\n static final int START_POINTER=1;\n final DataAccess dataAccess;\n private final BBox bounds;\n private int minResolutionInMeter=300;\n private int size;\n private int leafs;\n private int checksum;\n private IndexStructureInfo indexStructureInfo;\n private int[] entries;\n private byte[] shifts;\n private boolean initialized=false;\n private SpatialKeyAlgo keyAlgo;\n public LineIntIndex( BBox bBox, Directory dir, String name);\n public LineIntIndex( BBox bBox, Directory dir, String name, DAType daType);\n public boolean loadExisting();\n public void store( InMemConstructionIndex inMem);\n private int store( InMemConstructionIndex.InMemEntry entry, int intPointer);\n private void fillIDs( long keyPart, IntConsumer consumer);\n public void query( BBox queryShape, final LocationIndex.Visitor function);\n public void query( LocationIndex.TileFilter tileFilter, final LocationIndex.Visitor function);\n private void query( int intPointer, LocationIndex.TileFilter tileFilter, double minLat, double minLon, double deltaLatPerDepth, double deltaLonPerDepth, LocationIndex.Visitor function, int depth);\n /** \n * This method collects edge ids from the neighborhood of a point and puts them into foundEntries. <p> If it is called with iteration = 0, it just looks in the tile the query point is in. If it is called with iteration = 0,1,2,.., it will look in additional tiles further and further from the start tile. (In a square that grows by one pixel in all four directions per iteration). <p> See discussion at issue #221. <p>\n */\n public void findEdgeIdsInNeighborhood( double queryLat, double queryLon, int iteration, IntConsumer foundEntries);\n public int getChecksum();\n public int getMinResolutionInMeter();\n public void setMinResolutionInMeter( int minResolutionInMeter);\n public void flush();\n public void close();\n public boolean isClosed();\n public long getCapacity();\n public void setChecksum( int checksum);\n public int getSize();\n public int getLeafs();\n}\n", "raw_body_no_cmt": "public class LineIntIndex {\n static final int START_POINTER=1;\n final DataAccess dataAccess;\n private final BBox bounds;\n private int minResolutionInMeter=300;\n private int size;\n private int leafs;\n private int checksum;\n private IndexStructureInfo indexStructureInfo;\n private int[] entries;\n private byte[] shifts;\n private boolean initialized=false;\n private SpatialKeyAlgo keyAlgo;\n public LineIntIndex( BBox bBox, Directory dir, String name);\n public LineIntIndex( BBox bBox, Directory dir, String name, DAType daType);\n public boolean loadExisting();\n public void store( InMemConstructionIndex inMem);\n private int store( InMemConstructionIndex.InMemEntry entry, int intPointer);\n private void fillIDs( long keyPart, IntConsumer consumer);\n public void query( BBox queryShape, final LocationIndex.Visitor function);\n public void query( LocationIndex.TileFilter tileFilter, final LocationIndex.Visitor function);\n private void query( int intPointer, LocationIndex.TileFilter tileFilter, double minLat, double minLon, double deltaLatPerDepth, double deltaLonPerDepth, LocationIndex.Visitor function, int depth);\n public void findEdgeIdsInNeighborhood( double queryLat, double queryLon, int iteration, IntConsumer foundEntries);\n public int getChecksum();\n public int getMinResolutionInMeter();\n public void setMinResolutionInMeter( int minResolutionInMeter);\n public void flush();\n public void close();\n public boolean isClosed();\n public long getCapacity();\n public void setChecksum( int checksum);\n public int getSize();\n public int getLeafs();\n}\n"}}, {"IntFloatBinaryHeap": {"retrieved_name": "IntFloatBinaryHeap", "raw_body": "/** \n * This class is a partial copy of the class org.apache.commons.collections.BinaryHeap for just the min heap and primitive, sorted float keys and associated int elements. <p> The library can be found here: https://commons.apache.org/proper/commons-collections/\n */\npublic class IntFloatBinaryHeap {\n private static final int GROW_FACTOR=2;\n private int size;\n private int[] elements;\n private float[] keys;\n public IntFloatBinaryHeap();\n public IntFloatBinaryHeap( int initialCapacity);\n private boolean isFull();\n public void update( double key, int element);\n public void insert( double key, int element);\n public int peekElement();\n public float peekKey();\n public int poll();\n /** \n * Percolates element down heap from the array position given by the index.\n */\n final void percolateDownMinHeap( final int index);\n final void percolateUpMinHeap( final int index);\n public boolean isEmpty();\n public int getSize();\n public void clear();\n void trimTo( int toSize);\n public void ensureCapacity( int capacity);\n public long getCapacity();\n public long getMemoryUsage();\n}\n", "raw_body_no_cmt": "public class IntFloatBinaryHeap {\n private static final int GROW_FACTOR=2;\n private int size;\n private int[] elements;\n private float[] keys;\n public IntFloatBinaryHeap();\n public IntFloatBinaryHeap( int initialCapacity);\n private boolean isFull();\n public void update( double key, int element);\n public void insert( double key, int element);\n public int peekElement();\n public float peekKey();\n public int poll();\n final void percolateDownMinHeap( final int index);\n final void percolateUpMinHeap( final int index);\n public boolean isEmpty();\n public int getSize();\n public void clear();\n void trimTo( int toSize);\n public void ensureCapacity( int capacity);\n public long getCapacity();\n public long getMemoryUsage();\n}\n"}}, {"PrepareGraphEdgeExplorer": {"retrieved_name": "PrepareGraphEdgeExplorer", "raw_body": "public interface PrepareGraphEdgeExplorer {\n PrepareGraphEdgeIterator setBaseNode( int node);\n}\n", "raw_body_no_cmt": "public interface PrepareGraphEdgeExplorer {\n PrepareGraphEdgeIterator setBaseNode( int node);\n}\n"}}] | [{"add": {"retrieved_name": "add", "raw_body": "public void add(PointAccess nodeAccess,int index){\n if (is3D) add(nodeAccess.getLat(index),nodeAccess.getLon(index),nodeAccess.getEle(index));\n else add(nodeAccess.getLat(index),nodeAccess.getLon(index));\n}\n"}}, {"size": {"retrieved_name": "size", "raw_body": "@Override public int size(){\n return 0;\n}\n"}}, {"getTarget": {"retrieved_name": "getObject", "raw_body": "public <T>T getObject(String key,T _default){\n Object object=map.get(key);\n return object == null ? _default : (T)object;\n}\n"}}, {"extractMin": {"retrieved_name": "extractMeter", "raw_body": "public static void extractMeter(int edgeId,EdgeIntAccess edgeIntAccess,ReaderWay way,DecimalEncodedValue valueEncoder,List<String> keys){\n final String rawValue=way.getFirstValue(keys);\n double value=stringToMeter(rawValue);\n if (Double.isNaN(value)) value=Double.POSITIVE_INFINITY;\n valueEncoder.setDecimal(false,edgeId,edgeIntAccess,value);\n}\n"}}, {"insert": {"retrieved_name": "insert", "raw_body": "public void insert(double key,int element){\n if (isFull()) {\n ensureCapacity(elements.length * GROW_FACTOR);\n }\n size++;\n elements[size]=element;\n keys[size]=(float)key;\n percolateUpMinHeap(size);\n}\n"}}, {"getOutEdges": {"retrieved_name": "getOutEdges", "raw_body": "List<Edge> getOutEdges(Point p){\n List<Edge> result=outEdgesByNextPoint.get(p);\n return result == null ? Collections.emptyList() : result;\n}\n"}}, {"getWeight": {"retrieved_name": "getWeight", "raw_body": "/** \n * This weight will be updated during the algorithm. The initial value is maximum double.\n */\npublic double getWeight(){\n return weight;\n}\n"}}] | [{"findUpperBound": {"retrieved_name": "getBounds", "raw_body": "public BBox getBounds(){\n return bounds;\n}\n"}}] |
|
obsidiandynamics_kafdrop | kafdrop/src/main/java/kafdrop/config/KafkaConfiguration.java | KafkaConfiguration | applyCommon | class KafkaConfiguration {
private static final Logger LOG = LoggerFactory.getLogger(KafkaConfiguration.class);
private String brokerConnect;
private String saslMechanism;
private String securityProtocol;
private String truststoreFile;
private String propertiesFile;
private String keystoreFile;
public void applyCommon(Properties properties) {<FILL_FUNCTION_BODY>}
} |
properties.setProperty(CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG, brokerConnect);
if (securityProtocol.equals("SSL")) {
properties.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, securityProtocol);
}
LOG.info("Checking truststore file {}", truststoreFile);
if (new File(truststoreFile).isFile()) {
LOG.info("Assigning truststore location to {}", truststoreFile);
properties.put("ssl.truststore.location", truststoreFile);
}
LOG.info("Checking keystore file {}", keystoreFile);
if (new File(keystoreFile).isFile()) {
LOG.info("Assigning keystore location to {}", keystoreFile);
properties.put("ssl.keystore.location", keystoreFile);
}
LOG.info("Checking properties file {}", propertiesFile);
final var propertiesFile = new File(this.propertiesFile);
if (propertiesFile.isFile()) {
LOG.info("Loading properties from {}", this.propertiesFile);
final var propertyOverrides = new Properties();
try (var propsReader = new BufferedReader(new FileReader(propertiesFile))) {
propertyOverrides.load(propsReader);
} catch (IOException e) {
throw new KafkaConfigurationException(e);
}
properties.putAll(propertyOverrides);
}
|
properties.put(CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG, brokerConnect);
properties.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, securityProtocol);
properties.put(CommonClientConfigs.SASL_MECHANISM, saslMechanism);
properties.put(CommonClientConfigs.SASL_JAAS_CONFIG, getJaasConfig());
| [
"Properties"
] | [
"put"
] | [
"var",
"Logger",
"IOException",
"Properties"
] | [
"equals",
"putAll",
"isFile",
"setProperty",
"put",
"load",
"info"
] | {
"methods": [
"put"
],
"similar_methods": [
"applyCommon"
],
"types": [
"Properties"
]
} | /**
* Protobuf type {@code kafdrop.Person}
*/
public final class Person extends com.google.protobuf.GeneratedMessage implements PersonOrBuilder {
private static final long serialVersionUID=0L;
private Person( com.google.protobuf.GeneratedMessage.Builder<?> builder);
private Person();
@java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused);
@java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields();
private Person( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException;
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor();
@java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable();
/**
* Protobuf enum {@code kafdrop.Person.Contact}
*/
public enum Contact implements com.google.protobuf.ProtocolMessageEnum {/**
* <code>TELEPHONE = 0;</code>
*/
TELEPHONE(0), /**
* <code>MOBILE = 1;</code>
*/
MOBILE(1), UNRECOGNIZED(-1); /**
* <code>TELEPHONE = 0;</code>
*/
public static final int TELEPHONE_VALUE=0;
/**
* <code>MOBILE = 1;</code>
*/
public static final int MOBILE_VALUE=1;
public final int getNumber();
/**
* @param value The numeric wire value of the corresponding enum entry.
* @return The enum associated with the given numeric wire value.
* @deprecated Use {@link #forNumber(int)} instead.
*/
@java.lang.Deprecated public static Contact valueOf(int value);
/**
* @param value The numeric wire value of the corresponding enum entry.
* @return The enum associated with the given numeric wire value.
*/
public static Contact forNumber(int value);
public static com.google.protobuf.Internal.EnumLiteMap<Contact> internalGetValueMap();
private static final com.google.protobuf.Internal.EnumLiteMap<Contact> internalValueMap=new com.google.protobuf.Internal.EnumLiteMap<Contact>(){
public Contact findValueByNumber(int number){
return Contact.forNumber(number);
}
}
;
public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor();
public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType();
public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor();
private static final Contact[] VALUES=values();
public static Contact valueOf(com.google.protobuf.Descriptors.EnumValueDescriptor desc);
private final int value;
private Contact(int value);
}
public static final int NAME_FIELD_NUMBER=1;
private volatile java.lang.Object name_;
/**
* <code>string name = 1;</code>
* @return The name.
*/
@java.lang.Override public java.lang.String getName();
/**
* <code>string name = 1;</code>
* @return The bytes for name.
*/
@java.lang.Override public com.google.protobuf.ByteString getNameBytes();
public static final int ID_FIELD_NUMBER=2;
private int id_;
/**
* <code>int32 id = 2;</code>
* @return The id.
*/
@java.lang.Override public int getId();
public static final int EMAIL_FIELD_NUMBER=3;
private volatile java.lang.Object email_;
/**
* <code>string email = 3;</code>
* @return The email.
*/
@java.lang.Override public java.lang.String getEmail();
/**
* <code>string email = 3;</code>
* @return The bytes for email.
*/
@java.lang.Override public com.google.protobuf.ByteString getEmailBytes();
public static final int CONTACT_FIELD_NUMBER=4;
private int contact_;
/**
* <code>.kafdrop.Person.Contact contact = 4;</code>
* @return The enum numeric value on the wire for contact.
*/
@java.lang.Override public int getContactValue();
/**
* <code>.kafdrop.Person.Contact contact = 4;</code>
* @return The contact.
*/
@java.lang.Override public kafdrop.protos.Person.Contact getContact();
public static final int DATA_FIELD_NUMBER=5;
private com.google.protobuf.LazyStringList data_;
/**
* <code>repeated string data = 5;</code>
* @return A list containing the data.
*/
public com.google.protobuf.ProtocolStringList getDataList();
/**
* <code>repeated string data = 5;</code>
* @return The count of data.
*/
public int getDataCount();
/**
* <code>repeated string data = 5;</code>
* @param index The index of the element to return.
* @return The data at the given index.
*/
public java.lang.String getData(int index);
/**
* <code>repeated string data = 5;</code>
* @param index The index of the value to return.
* @return The bytes of the data at the given index.
*/
public com.google.protobuf.ByteString getDataBytes(int index);
private byte memoizedIsInitialized=-1;
@java.lang.Override public final boolean isInitialized();
@java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException;
@java.lang.Override public int getSerializedSize();
@java.lang.Override public boolean equals(final java.lang.Object obj);
@java.lang.Override public int hashCode();
public static kafdrop.protos.Person parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException;
public static kafdrop.protos.Person parseFrom(java.nio.ByteBuffer data,com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException;
public static kafdrop.protos.Person parseFrom(com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException;
public static kafdrop.protos.Person parseFrom(com.google.protobuf.ByteString data,com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException;
public static kafdrop.protos.Person parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException;
public static kafdrop.protos.Person parseFrom(byte[] data,com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException;
public static kafdrop.protos.Person parseFrom(java.io.InputStream input) throws java.io.IOException;
public static kafdrop.protos.Person parseFrom(java.io.InputStream input,com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException;
public static kafdrop.protos.Person parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException;
public static kafdrop.protos.Person parseDelimitedFrom(java.io.InputStream input,com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException;
public static kafdrop.protos.Person parseFrom(com.google.protobuf.CodedInputStream input) throws java.io.IOException;
public static kafdrop.protos.Person parseFrom(com.google.protobuf.CodedInputStream input,com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException;
@java.lang.Override public Builder newBuilderForType();
public static Builder newBuilder();
public static Builder newBuilder(kafdrop.protos.Person prototype);
@java.lang.Override public Builder toBuilder();
@java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessage.BuilderParent parent);
/**
* Protobuf type {@code kafdrop.Person}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder<Builder> implements kafdrop.protos.PersonOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor();
@java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable();
private Builder();
private Builder(com.google.protobuf.GeneratedMessage.BuilderParent parent);
private void maybeForceBuilderInitialization();
@java.lang.Override public Builder clear();
@java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType();
@java.lang.Override public kafdrop.protos.Person getDefaultInstanceForType();
@java.lang.Override public kafdrop.protos.Person build();
@java.lang.Override public kafdrop.protos.Person buildPartial();
@java.lang.Override public Builder clone();
@java.lang.Override public Builder setField(com.google.protobuf.Descriptors.FieldDescriptor field,java.lang.Object value);
@java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field);
@java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof);
@java.lang.Override public Builder setRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field,int index,java.lang.Object value);
@java.lang.Override public Builder addRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field,java.lang.Object value);
@java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other);
public Builder mergeFrom(kafdrop.protos.Person other);
@java.lang.Override public final boolean isInitialized();
@java.lang.Override public Builder mergeFrom(com.google.protobuf.CodedInputStream input,com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException;
private int bitField0_;
private java.lang.Object name_="";
/**
* <code>string name = 1;</code>
* @return The name.
*/
public java.lang.String getName();
/**
* <code>string name = 1;</code>
* @return The bytes for name.
*/
public com.google.protobuf.ByteString getNameBytes();
/**
* <code>string name = 1;</code>
* @param value The name to set.
* @return This builder for chaining.
*/
public Builder setName(java.lang.String value);
/**
* <code>string name = 1;</code>
* @return This builder for chaining.
*/
public Builder clearName();
/**
* <code>string name = 1;</code>
* @param value The bytes for name to set.
* @return This builder for chaining.
*/
public Builder setNameBytes(com.google.protobuf.ByteString value);
private int id_;
/**
* <code>int32 id = 2;</code>
* @return The id.
*/
@java.lang.Override public int getId();
/**
* <code>int32 id = 2;</code>
* @param value The id to set.
* @return This builder for chaining.
*/
public Builder setId(int value);
/**
* <code>int32 id = 2;</code>
* @return This builder for chaining.
*/
public Builder clearId();
private java.lang.Object email_="";
/**
* <code>string email = 3;</code>
* @return The email.
*/
public java.lang.String getEmail();
/**
* <code>string email = 3;</code>
* @return The bytes for email.
*/
public com.google.protobuf.ByteString getEmailBytes();
/**
* <code>string email = 3;</code>
* @param value The email to set.
* @return This builder for chaining.
*/
public Builder setEmail(java.lang.String value);
/**
* <code>string email = 3;</code>
* @return This builder for chaining.
*/
public Builder clearEmail();
/**
* <code>string email = 3;</code>
* @param value The bytes for email to set.
* @return This builder for chaining.
*/
public Builder setEmailBytes(com.google.protobuf.ByteString value);
private int contact_=0;
/**
* <code>.kafdrop.Person.Contact contact = 4;</code>
* @return The enum numeric value on the wire for contact.
*/
@java.lang.Override public int getContactValue();
/**
* <code>.kafdrop.Person.Contact contact = 4;</code>
* @param value The enum numeric value on the wire for contact to set.
* @return This builder for chaining.
*/
public Builder setContactValue(int value);
/**
* <code>.kafdrop.Person.Contact contact = 4;</code>
* @return The contact.
*/
@java.lang.Override public kafdrop.protos.Person.Contact getContact();
/**
* <code>.kafdrop.Person.Contact contact = 4;</code>
* @param value The contact to set.
* @return This builder for chaining.
*/
public Builder setContact(kafdrop.protos.Person.Contact value);
/**
* <code>.kafdrop.Person.Contact contact = 4;</code>
* @return This builder for chaining.
*/
public Builder clearContact();
private com.google.protobuf.LazyStringList data_=com.google.protobuf.LazyStringArrayList.EMPTY;
private void ensureDataIsMutable();
/**
* <code>repeated string data = 5;</code>
* @return A list containing the data.
*/
public com.google.protobuf.ProtocolStringList getDataList();
/**
* <code>repeated string data = 5;</code>
* @return The count of data.
*/
public int getDataCount();
/**
* <code>repeated string data = 5;</code>
* @param index The index of the element to return.
* @return The data at the given index.
*/
public java.lang.String getData(int index);
/**
* <code>repeated string data = 5;</code>
* @param index The index of the value to return.
* @return The bytes of the data at the given index.
*/
public com.google.protobuf.ByteString getDataBytes(int index);
/**
* <code>repeated string data = 5;</code>
* @param index The index to set the value at.
* @param value The data to set.
* @return This builder for chaining.
*/
public Builder setData(int index,java.lang.String value);
/**
* <code>repeated string data = 5;</code>
* @param value The data to add.
* @return This builder for chaining.
*/
public Builder addData(java.lang.String value);
/**
* <code>repeated string data = 5;</code>
* @param values The data to add.
* @return This builder for chaining.
*/
public Builder addAllData(java.lang.Iterable<java.lang.String> values);
/**
* <code>repeated string data = 5;</code>
* @return This builder for chaining.
*/
public Builder clearData();
/**
* <code>repeated string data = 5;</code>
* @param value The bytes of the data to add.
* @return This builder for chaining.
*/
public Builder addDataBytes(com.google.protobuf.ByteString value);
@java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields);
@java.lang.Override public final Builder mergeUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields);
}
private static final kafdrop.protos.Person DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE=new kafdrop.protos.Person();
}
public static kafdrop.protos.Person getDefaultInstance();
private static final com.google.protobuf.Parser<Person> PARSER=new com.google.protobuf.AbstractParser<Person>(){
@java.lang.Override public Person parsePartialFrom(com.google.protobuf.CodedInputStream input,com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException {
return new Person(input,extensionRegistry);
}
}
;
public static com.google.protobuf.Parser<Person> parser();
@java.lang.Override public com.google.protobuf.Parser<Person> getParserForType();
@java.lang.Override public kafdrop.protos.Person getDefaultInstanceForType();
}
public void setPartition(Integer partition){
this.partition=partition;
}
public static SpringApplicationBuilder createApplicationBuilder(){
return new SpringApplicationBuilder(Kafdrop.class).bannerMode(Mode.OFF).listeners(new EnvironmentSetupListener(),new LoggingConfigurationListener());
}
| public final class Person extends com.google.protobuf.GeneratedMessage implements PersonOrBuilder {
private static final long serialVersionUID=0L;
private Person( com.google.protobuf.GeneratedMessage.Builder<?> builder);
private Person();
protected java.lang.Object newInstance( UnusedPrivateParameter unused);
public final com.google.protobuf.UnknownFieldSet getUnknownFields();
private Person( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException;
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor();
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable();
public enum Contact implements com.google.protobuf.ProtocolMessageEnum {/**
* <code>TELEPHONE = 0;</code>
*/
TELEPHONE(0), /**
* <code>MOBILE = 1;</code>
*/
MOBILE(1), UNRECOGNIZED(-1); public static final int TELEPHONE_VALUE=0;
public static final int MOBILE_VALUE=1;
public final int getNumber();
public static Contact valueOf(int value);
public static Contact forNumber(int value);
public static com.google.protobuf.Internal.EnumLiteMap<Contact> internalGetValueMap();
private static final com.google.protobuf.Internal.EnumLiteMap<Contact> internalValueMap=new com.google.protobuf.Internal.EnumLiteMap<Contact>(){
public Contact findValueByNumber(int number){
return Contact.forNumber(number);
}
}
;
public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor();
public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType();
public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor();
private static final Contact[] VALUES=values();
public static Contact valueOf(com.google.protobuf.Descriptors.EnumValueDescriptor desc);
private final int value;
private Contact(int value);
}
public static final int NAME_FIELD_NUMBER=1;
private volatile java.lang.Object name_;
public java.lang.String getName();
public com.google.protobuf.ByteString getNameBytes();
public static final int ID_FIELD_NUMBER=2;
private int id_;
public int getId();
public static final int EMAIL_FIELD_NUMBER=3;
private volatile java.lang.Object email_;
public java.lang.String getEmail();
public com.google.protobuf.ByteString getEmailBytes();
public static final int CONTACT_FIELD_NUMBER=4;
private int contact_;
public int getContactValue();
public kafdrop.protos.Person.Contact getContact();
public static final int DATA_FIELD_NUMBER=5;
private com.google.protobuf.LazyStringList data_;
public com.google.protobuf.ProtocolStringList getDataList();
public int getDataCount();
public java.lang.String getData(int index);
public com.google.protobuf.ByteString getDataBytes(int index);
private byte memoizedIsInitialized=-1;
public final boolean isInitialized();
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException;
public int getSerializedSize();
public boolean equals(final java.lang.Object obj);
public int hashCode();
public static kafdrop.protos.Person parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException;
public static kafdrop.protos.Person parseFrom(java.nio.ByteBuffer data,com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException;
public static kafdrop.protos.Person parseFrom(com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException;
public static kafdrop.protos.Person parseFrom(com.google.protobuf.ByteString data,com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException;
public static kafdrop.protos.Person parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException;
public static kafdrop.protos.Person parseFrom(byte[] data,com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException;
public static kafdrop.protos.Person parseFrom(java.io.InputStream input) throws java.io.IOException;
public static kafdrop.protos.Person parseFrom(java.io.InputStream input,com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException;
public static kafdrop.protos.Person parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException;
public static kafdrop.protos.Person parseDelimitedFrom(java.io.InputStream input,com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException;
public static kafdrop.protos.Person parseFrom(com.google.protobuf.CodedInputStream input) throws java.io.IOException;
public static kafdrop.protos.Person parseFrom(com.google.protobuf.CodedInputStream input,com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException;
public Builder newBuilderForType();
public static Builder newBuilder();
public static Builder newBuilder(kafdrop.protos.Person prototype);
public Builder toBuilder();
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessage.BuilderParent parent);
public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder<Builder> implements kafdrop.protos.PersonOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor();
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable();
private Builder();
private Builder(com.google.protobuf.GeneratedMessage.BuilderParent parent);
private void maybeForceBuilderInitialization();
public Builder clear();
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType();
public kafdrop.protos.Person getDefaultInstanceForType();
public kafdrop.protos.Person build();
public kafdrop.protos.Person buildPartial();
public Builder clone();
public Builder setField(com.google.protobuf.Descriptors.FieldDescriptor field,java.lang.Object value);
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field);
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof);
public Builder setRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field,int index,java.lang.Object value);
public Builder addRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field,java.lang.Object value);
public Builder mergeFrom(com.google.protobuf.Message other);
public Builder mergeFrom(kafdrop.protos.Person other);
public final boolean isInitialized();
public Builder mergeFrom(com.google.protobuf.CodedInputStream input,com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException;
private int bitField0_;
private java.lang.Object name_="";
public java.lang.String getName();
public com.google.protobuf.ByteString getNameBytes();
public Builder setName(java.lang.String value);
public Builder clearName();
public Builder setNameBytes(com.google.protobuf.ByteString value);
private int id_;
public int getId();
public Builder setId(int value);
public Builder clearId();
private java.lang.Object email_="";
public java.lang.String getEmail();
public com.google.protobuf.ByteString getEmailBytes();
public Builder setEmail(java.lang.String value);
public Builder clearEmail();
public Builder setEmailBytes(com.google.protobuf.ByteString value);
private int contact_=0;
public int getContactValue();
public Builder setContactValue(int value);
public kafdrop.protos.Person.Contact getContact();
public Builder setContact(kafdrop.protos.Person.Contact value);
public Builder clearContact();
private com.google.protobuf.LazyStringList data_=com.google.protobuf.LazyStringArrayList.EMPTY;
private void ensureDataIsMutable();
public com.google.protobuf.ProtocolStringList getDataList();
public int getDataCount();
public java.lang.String getData(int index);
public com.google.protobuf.ByteString getDataBytes(int index);
public Builder setData(int index,java.lang.String value);
public Builder addData(java.lang.String value);
public Builder addAllData(java.lang.Iterable<java.lang.String> values);
public Builder clearData();
public Builder addDataBytes(com.google.protobuf.ByteString value);
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields);
public final Builder mergeUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields);
}
private static final kafdrop.protos.Person DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE=new kafdrop.protos.Person();
}
public static kafdrop.protos.Person getDefaultInstance();
private static final com.google.protobuf.Parser<Person> PARSER=new com.google.protobuf.AbstractParser<Person>(){
@java.lang.Override public Person parsePartialFrom(com.google.protobuf.CodedInputStream input,com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException {
return new Person(input,extensionRegistry);
}
}
;
public static com.google.protobuf.Parser<Person> parser();
public com.google.protobuf.Parser<Person> getParserForType();
public kafdrop.protos.Person getDefaultInstanceForType();
}
public void setPartition(Integer partition){
this.partition=partition;
}
public static SpringApplicationBuilder createApplicationBuilder(){
return new SpringApplicationBuilder(Kafdrop.class).bannerMode(Mode.OFF).listeners(new EnvironmentSetupListener(),new LoggingConfigurationListener());
}
| {"types": [{"Properties": "Person"}], "methods": [{"put": "setPartition"}], "similar_methods": [{"applyCommon": "createApplicationBuilder"}]} | [{"Properties": {"retrieved_name": "Person", "raw_body": "/** \n * Protobuf type {@code kafdrop.Person}\n */\npublic final class Person extends com.google.protobuf.GeneratedMessage implements PersonOrBuilder {\n private static final long serialVersionUID=0L;\n private Person( com.google.protobuf.GeneratedMessage.Builder<?> builder);\n private Person();\n @java.lang.Override @SuppressWarnings({\"unused\"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused);\n @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields();\n private Person( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException;\npublic static final com.google.protobuf.Descriptors.Descriptor getDescriptor();\n@java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable();\n/** \n * Protobuf enum {@code kafdrop.Person.Contact}\n */\npublic enum Contact implements com.google.protobuf.ProtocolMessageEnum {/** \n * <code>TELEPHONE = 0;</code>\n */\nTELEPHONE(0), /** \n * <code>MOBILE = 1;</code>\n */\nMOBILE(1), UNRECOGNIZED(-1); /** \n * <code>TELEPHONE = 0;</code>\n */\npublic static final int TELEPHONE_VALUE=0;\n/** \n * <code>MOBILE = 1;</code>\n */\npublic static final int MOBILE_VALUE=1;\npublic final int getNumber();\n/** \n * @param value The numeric wire value of the corresponding enum entry.\n * @return The enum associated with the given numeric wire value.\n * @deprecated Use {@link #forNumber(int)} instead.\n */\n@java.lang.Deprecated public static Contact valueOf(int value);\n/** \n * @param value The numeric wire value of the corresponding enum entry.\n * @return The enum associated with the given numeric wire value.\n */\npublic static Contact forNumber(int value);\npublic static com.google.protobuf.Internal.EnumLiteMap<Contact> internalGetValueMap();\nprivate static final com.google.protobuf.Internal.EnumLiteMap<Contact> internalValueMap=new com.google.protobuf.Internal.EnumLiteMap<Contact>(){\npublic Contact findValueByNumber(int number){\nreturn Contact.forNumber(number);\n}\n}\n;\npublic final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor();\npublic final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType();\npublic static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor();\nprivate static final Contact[] VALUES=values();\npublic static Contact valueOf(com.google.protobuf.Descriptors.EnumValueDescriptor desc);\nprivate final int value;\nprivate Contact(int value);\n}\npublic static final int NAME_FIELD_NUMBER=1;\nprivate volatile java.lang.Object name_;\n/** \n * <code>string name = 1;</code>\n * @return The name.\n */\n@java.lang.Override public java.lang.String getName();\n/** \n * <code>string name = 1;</code>\n * @return The bytes for name.\n */\n@java.lang.Override public com.google.protobuf.ByteString getNameBytes();\npublic static final int ID_FIELD_NUMBER=2;\nprivate int id_;\n/** \n * <code>int32 id = 2;</code>\n * @return The id.\n */\n@java.lang.Override public int getId();\npublic static final int EMAIL_FIELD_NUMBER=3;\nprivate volatile java.lang.Object email_;\n/** \n * <code>string email = 3;</code>\n * @return The email.\n */\n@java.lang.Override public java.lang.String getEmail();\n/** \n * <code>string email = 3;</code>\n * @return The bytes for email.\n */\n@java.lang.Override public com.google.protobuf.ByteString getEmailBytes();\npublic static final int CONTACT_FIELD_NUMBER=4;\nprivate int contact_;\n/** \n * <code>.kafdrop.Person.Contact contact = 4;</code>\n * @return The enum numeric value on the wire for contact.\n */\n@java.lang.Override public int getContactValue();\n/** \n * <code>.kafdrop.Person.Contact contact = 4;</code>\n * @return The contact.\n */\n@java.lang.Override public kafdrop.protos.Person.Contact getContact();\npublic static final int DATA_FIELD_NUMBER=5;\nprivate com.google.protobuf.LazyStringList data_;\n/** \n * <code>repeated string data = 5;</code>\n * @return A list containing the data.\n */\npublic com.google.protobuf.ProtocolStringList getDataList();\n/** \n * <code>repeated string data = 5;</code>\n * @return The count of data.\n */\npublic int getDataCount();\n/** \n * <code>repeated string data = 5;</code>\n * @param index The index of the element to return.\n * @return The data at the given index.\n */\npublic java.lang.String getData(int index);\n/** \n * <code>repeated string data = 5;</code>\n * @param index The index of the value to return.\n * @return The bytes of the data at the given index.\n */\npublic com.google.protobuf.ByteString getDataBytes(int index);\nprivate byte memoizedIsInitialized=-1;\n@java.lang.Override public final boolean isInitialized();\n@java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException;\n@java.lang.Override public int getSerializedSize();\n@java.lang.Override public boolean equals(final java.lang.Object obj);\n@java.lang.Override public int hashCode();\npublic static kafdrop.protos.Person parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException;\npublic static kafdrop.protos.Person parseFrom(java.nio.ByteBuffer data,com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException;\npublic static kafdrop.protos.Person parseFrom(com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException;\npublic static kafdrop.protos.Person parseFrom(com.google.protobuf.ByteString data,com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException;\npublic static kafdrop.protos.Person parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException;\npublic static kafdrop.protos.Person parseFrom(byte[] data,com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException;\npublic static kafdrop.protos.Person parseFrom(java.io.InputStream input) throws java.io.IOException;\npublic static kafdrop.protos.Person parseFrom(java.io.InputStream input,com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException;\npublic static kafdrop.protos.Person parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException;\npublic static kafdrop.protos.Person parseDelimitedFrom(java.io.InputStream input,com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException;\npublic static kafdrop.protos.Person parseFrom(com.google.protobuf.CodedInputStream input) throws java.io.IOException;\npublic static kafdrop.protos.Person parseFrom(com.google.protobuf.CodedInputStream input,com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException;\n@java.lang.Override public Builder newBuilderForType();\npublic static Builder newBuilder();\npublic static Builder newBuilder(kafdrop.protos.Person prototype);\n@java.lang.Override public Builder toBuilder();\n@java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessage.BuilderParent parent);\n/** \n * Protobuf type {@code kafdrop.Person}\n */\npublic static final class Builder extends com.google.protobuf.GeneratedMessage.Builder<Builder> implements kafdrop.protos.PersonOrBuilder {\npublic static final com.google.protobuf.Descriptors.Descriptor getDescriptor();\n@java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable();\nprivate Builder();\nprivate Builder(com.google.protobuf.GeneratedMessage.BuilderParent parent);\nprivate void maybeForceBuilderInitialization();\n@java.lang.Override public Builder clear();\n@java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType();\n@java.lang.Override public kafdrop.protos.Person getDefaultInstanceForType();\n@java.lang.Override public kafdrop.protos.Person build();\n@java.lang.Override public kafdrop.protos.Person buildPartial();\n@java.lang.Override public Builder clone();\n@java.lang.Override public Builder setField(com.google.protobuf.Descriptors.FieldDescriptor field,java.lang.Object value);\n@java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field);\n@java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof);\n@java.lang.Override public Builder setRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field,int index,java.lang.Object value);\n@java.lang.Override public Builder addRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field,java.lang.Object value);\n@java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other);\npublic Builder mergeFrom(kafdrop.protos.Person other);\n@java.lang.Override public final boolean isInitialized();\n@java.lang.Override public Builder mergeFrom(com.google.protobuf.CodedInputStream input,com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException;\nprivate int bitField0_;\nprivate java.lang.Object name_=\"\";\n/** \n * <code>string name = 1;</code>\n * @return The name.\n */\npublic java.lang.String getName();\n/** \n * <code>string name = 1;</code>\n * @return The bytes for name.\n */\npublic com.google.protobuf.ByteString getNameBytes();\n/** \n * <code>string name = 1;</code>\n * @param value The name to set.\n * @return This builder for chaining.\n */\npublic Builder setName(java.lang.String value);\n/** \n * <code>string name = 1;</code>\n * @return This builder for chaining.\n */\npublic Builder clearName();\n/** \n * <code>string name = 1;</code>\n * @param value The bytes for name to set.\n * @return This builder for chaining.\n */\npublic Builder setNameBytes(com.google.protobuf.ByteString value);\nprivate int id_;\n/** \n * <code>int32 id = 2;</code>\n * @return The id.\n */\n@java.lang.Override public int getId();\n/** \n * <code>int32 id = 2;</code>\n * @param value The id to set.\n * @return This builder for chaining.\n */\npublic Builder setId(int value);\n/** \n * <code>int32 id = 2;</code>\n * @return This builder for chaining.\n */\npublic Builder clearId();\nprivate java.lang.Object email_=\"\";\n/** \n * <code>string email = 3;</code>\n * @return The email.\n */\npublic java.lang.String getEmail();\n/** \n * <code>string email = 3;</code>\n * @return The bytes for email.\n */\npublic com.google.protobuf.ByteString getEmailBytes();\n/** \n * <code>string email = 3;</code>\n * @param value The email to set.\n * @return This builder for chaining.\n */\npublic Builder setEmail(java.lang.String value);\n/** \n * <code>string email = 3;</code>\n * @return This builder for chaining.\n */\npublic Builder clearEmail();\n/** \n * <code>string email = 3;</code>\n * @param value The bytes for email to set.\n * @return This builder for chaining.\n */\npublic Builder setEmailBytes(com.google.protobuf.ByteString value);\nprivate int contact_=0;\n/** \n * <code>.kafdrop.Person.Contact contact = 4;</code>\n * @return The enum numeric value on the wire for contact.\n */\n@java.lang.Override public int getContactValue();\n/** \n * <code>.kafdrop.Person.Contact contact = 4;</code>\n * @param value The enum numeric value on the wire for contact to set.\n * @return This builder for chaining.\n */\npublic Builder setContactValue(int value);\n/** \n * <code>.kafdrop.Person.Contact contact = 4;</code>\n * @return The contact.\n */\n@java.lang.Override public kafdrop.protos.Person.Contact getContact();\n/** \n * <code>.kafdrop.Person.Contact contact = 4;</code>\n * @param value The contact to set.\n * @return This builder for chaining.\n */\npublic Builder setContact(kafdrop.protos.Person.Contact value);\n/** \n * <code>.kafdrop.Person.Contact contact = 4;</code>\n * @return This builder for chaining.\n */\npublic Builder clearContact();\nprivate com.google.protobuf.LazyStringList data_=com.google.protobuf.LazyStringArrayList.EMPTY;\nprivate void ensureDataIsMutable();\n/** \n * <code>repeated string data = 5;</code>\n * @return A list containing the data.\n */\npublic com.google.protobuf.ProtocolStringList getDataList();\n/** \n * <code>repeated string data = 5;</code>\n * @return The count of data.\n */\npublic int getDataCount();\n/** \n * <code>repeated string data = 5;</code>\n * @param index The index of the element to return.\n * @return The data at the given index.\n */\npublic java.lang.String getData(int index);\n/** \n * <code>repeated string data = 5;</code>\n * @param index The index of the value to return.\n * @return The bytes of the data at the given index.\n */\npublic com.google.protobuf.ByteString getDataBytes(int index);\n/** \n * <code>repeated string data = 5;</code>\n * @param index The index to set the value at.\n * @param value The data to set.\n * @return This builder for chaining.\n */\npublic Builder setData(int index,java.lang.String value);\n/** \n * <code>repeated string data = 5;</code>\n * @param value The data to add.\n * @return This builder for chaining.\n */\npublic Builder addData(java.lang.String value);\n/** \n * <code>repeated string data = 5;</code>\n * @param values The data to add.\n * @return This builder for chaining.\n */\npublic Builder addAllData(java.lang.Iterable<java.lang.String> values);\n/** \n * <code>repeated string data = 5;</code>\n * @return This builder for chaining.\n */\npublic Builder clearData();\n/** \n * <code>repeated string data = 5;</code>\n * @param value The bytes of the data to add.\n * @return This builder for chaining.\n */\npublic Builder addDataBytes(com.google.protobuf.ByteString value);\n@java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields);\n@java.lang.Override public final Builder mergeUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields);\n}\nprivate static final kafdrop.protos.Person DEFAULT_INSTANCE;\nstatic {\nDEFAULT_INSTANCE=new kafdrop.protos.Person();\n}\npublic static kafdrop.protos.Person getDefaultInstance();\nprivate static final com.google.protobuf.Parser<Person> PARSER=new com.google.protobuf.AbstractParser<Person>(){\n@java.lang.Override public Person parsePartialFrom(com.google.protobuf.CodedInputStream input,com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException {\nreturn new Person(input,extensionRegistry);\n}\n}\n;\npublic static com.google.protobuf.Parser<Person> parser();\n@java.lang.Override public com.google.protobuf.Parser<Person> getParserForType();\n@java.lang.Override public kafdrop.protos.Person getDefaultInstanceForType();\n}\n", "raw_body_no_cmt": "public final class Person extends com.google.protobuf.GeneratedMessage implements PersonOrBuilder {\n private static final long serialVersionUID=0L;\n private Person( com.google.protobuf.GeneratedMessage.Builder<?> builder);\n private Person();\n protected java.lang.Object newInstance( UnusedPrivateParameter unused);\n public final com.google.protobuf.UnknownFieldSet getUnknownFields();\n private Person( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException;\npublic static final com.google.protobuf.Descriptors.Descriptor getDescriptor();\nprotected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable();\npublic enum Contact implements com.google.protobuf.ProtocolMessageEnum {/** \n * <code>TELEPHONE = 0;</code>\n */\nTELEPHONE(0), /** \n * <code>MOBILE = 1;</code>\n */\nMOBILE(1), UNRECOGNIZED(-1); public static final int TELEPHONE_VALUE=0;\npublic static final int MOBILE_VALUE=1;\npublic final int getNumber();\npublic static Contact valueOf(int value);\npublic static Contact forNumber(int value);\npublic static com.google.protobuf.Internal.EnumLiteMap<Contact> internalGetValueMap();\nprivate static final com.google.protobuf.Internal.EnumLiteMap<Contact> internalValueMap=new com.google.protobuf.Internal.EnumLiteMap<Contact>(){\npublic Contact findValueByNumber(int number){\nreturn Contact.forNumber(number);\n}\n}\n;\npublic final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor();\npublic final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType();\npublic static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor();\nprivate static final Contact[] VALUES=values();\npublic static Contact valueOf(com.google.protobuf.Descriptors.EnumValueDescriptor desc);\nprivate final int value;\nprivate Contact(int value);\n}\npublic static final int NAME_FIELD_NUMBER=1;\nprivate volatile java.lang.Object name_;\npublic java.lang.String getName();\npublic com.google.protobuf.ByteString getNameBytes();\npublic static final int ID_FIELD_NUMBER=2;\nprivate int id_;\npublic int getId();\npublic static final int EMAIL_FIELD_NUMBER=3;\nprivate volatile java.lang.Object email_;\npublic java.lang.String getEmail();\npublic com.google.protobuf.ByteString getEmailBytes();\npublic static final int CONTACT_FIELD_NUMBER=4;\nprivate int contact_;\npublic int getContactValue();\npublic kafdrop.protos.Person.Contact getContact();\npublic static final int DATA_FIELD_NUMBER=5;\nprivate com.google.protobuf.LazyStringList data_;\npublic com.google.protobuf.ProtocolStringList getDataList();\npublic int getDataCount();\npublic java.lang.String getData(int index);\npublic com.google.protobuf.ByteString getDataBytes(int index);\nprivate byte memoizedIsInitialized=-1;\npublic final boolean isInitialized();\npublic void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException;\npublic int getSerializedSize();\npublic boolean equals(final java.lang.Object obj);\npublic int hashCode();\npublic static kafdrop.protos.Person parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException;\npublic static kafdrop.protos.Person parseFrom(java.nio.ByteBuffer data,com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException;\npublic static kafdrop.protos.Person parseFrom(com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException;\npublic static kafdrop.protos.Person parseFrom(com.google.protobuf.ByteString data,com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException;\npublic static kafdrop.protos.Person parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException;\npublic static kafdrop.protos.Person parseFrom(byte[] data,com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException;\npublic static kafdrop.protos.Person parseFrom(java.io.InputStream input) throws java.io.IOException;\npublic static kafdrop.protos.Person parseFrom(java.io.InputStream input,com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException;\npublic static kafdrop.protos.Person parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException;\npublic static kafdrop.protos.Person parseDelimitedFrom(java.io.InputStream input,com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException;\npublic static kafdrop.protos.Person parseFrom(com.google.protobuf.CodedInputStream input) throws java.io.IOException;\npublic static kafdrop.protos.Person parseFrom(com.google.protobuf.CodedInputStream input,com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException;\npublic Builder newBuilderForType();\npublic static Builder newBuilder();\npublic static Builder newBuilder(kafdrop.protos.Person prototype);\npublic Builder toBuilder();\nprotected Builder newBuilderForType(com.google.protobuf.GeneratedMessage.BuilderParent parent);\npublic static final class Builder extends com.google.protobuf.GeneratedMessage.Builder<Builder> implements kafdrop.protos.PersonOrBuilder {\npublic static final com.google.protobuf.Descriptors.Descriptor getDescriptor();\nprotected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable();\nprivate Builder();\nprivate Builder(com.google.protobuf.GeneratedMessage.BuilderParent parent);\nprivate void maybeForceBuilderInitialization();\npublic Builder clear();\npublic com.google.protobuf.Descriptors.Descriptor getDescriptorForType();\npublic kafdrop.protos.Person getDefaultInstanceForType();\npublic kafdrop.protos.Person build();\npublic kafdrop.protos.Person buildPartial();\npublic Builder clone();\npublic Builder setField(com.google.protobuf.Descriptors.FieldDescriptor field,java.lang.Object value);\npublic Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field);\npublic Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof);\npublic Builder setRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field,int index,java.lang.Object value);\npublic Builder addRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field,java.lang.Object value);\npublic Builder mergeFrom(com.google.protobuf.Message other);\npublic Builder mergeFrom(kafdrop.protos.Person other);\npublic final boolean isInitialized();\npublic Builder mergeFrom(com.google.protobuf.CodedInputStream input,com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException;\nprivate int bitField0_;\nprivate java.lang.Object name_=\"\";\npublic java.lang.String getName();\npublic com.google.protobuf.ByteString getNameBytes();\npublic Builder setName(java.lang.String value);\npublic Builder clearName();\npublic Builder setNameBytes(com.google.protobuf.ByteString value);\nprivate int id_;\npublic int getId();\npublic Builder setId(int value);\npublic Builder clearId();\nprivate java.lang.Object email_=\"\";\npublic java.lang.String getEmail();\npublic com.google.protobuf.ByteString getEmailBytes();\npublic Builder setEmail(java.lang.String value);\npublic Builder clearEmail();\npublic Builder setEmailBytes(com.google.protobuf.ByteString value);\nprivate int contact_=0;\npublic int getContactValue();\npublic Builder setContactValue(int value);\npublic kafdrop.protos.Person.Contact getContact();\npublic Builder setContact(kafdrop.protos.Person.Contact value);\npublic Builder clearContact();\nprivate com.google.protobuf.LazyStringList data_=com.google.protobuf.LazyStringArrayList.EMPTY;\nprivate void ensureDataIsMutable();\npublic com.google.protobuf.ProtocolStringList getDataList();\npublic int getDataCount();\npublic java.lang.String getData(int index);\npublic com.google.protobuf.ByteString getDataBytes(int index);\npublic Builder setData(int index,java.lang.String value);\npublic Builder addData(java.lang.String value);\npublic Builder addAllData(java.lang.Iterable<java.lang.String> values);\npublic Builder clearData();\npublic Builder addDataBytes(com.google.protobuf.ByteString value);\npublic final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields);\npublic final Builder mergeUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields);\n}\nprivate static final kafdrop.protos.Person DEFAULT_INSTANCE;\nstatic {\nDEFAULT_INSTANCE=new kafdrop.protos.Person();\n}\npublic static kafdrop.protos.Person getDefaultInstance();\nprivate static final com.google.protobuf.Parser<Person> PARSER=new com.google.protobuf.AbstractParser<Person>(){\n@java.lang.Override public Person parsePartialFrom(com.google.protobuf.CodedInputStream input,com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException {\nreturn new Person(input,extensionRegistry);\n}\n}\n;\npublic static com.google.protobuf.Parser<Person> parser();\npublic com.google.protobuf.Parser<Person> getParserForType();\npublic kafdrop.protos.Person getDefaultInstanceForType();\n}\n"}}] | [{"put": {"retrieved_name": "setPartition", "raw_body": "public void setPartition(Integer partition){\n this.partition=partition;\n}\n"}}] | [{"applyCommon": {"retrieved_name": "createApplicationBuilder", "raw_body": "public static SpringApplicationBuilder createApplicationBuilder(){\n return new SpringApplicationBuilder(Kafdrop.class).bannerMode(Mode.OFF).listeners(new EnvironmentSetupListener(),new LoggingConfigurationListener());\n}\n"}}] |
|
eirslett_frontend-maven-plugin | frontend-maven-plugin/frontend-maven-plugin/src/main/java/com/github/eirslett/maven/plugins/frontend/mojo/BunMojo.java | BunMojo | getProxyConfig | class BunMojo extends AbstractFrontendMojo {
private static final String NPM_REGISTRY_URL = "npmRegistryURL";
/**
* bun arguments. Default is "install".
*/
@Parameter(defaultValue = "", property = "frontend.bun.arguments", required = false)
private String arguments;
@Parameter(property = "frontend.bun.bunInheritsProxyConfigFromMaven", required = false,
defaultValue = "true")
private boolean bunInheritsProxyConfigFromMaven;
/**
* Registry override, passed as the registry option during npm install if set.
*/
@Parameter(property = NPM_REGISTRY_URL, required = false, defaultValue = "")
private String npmRegistryURL;
@Parameter(property = "session", defaultValue = "${session}", readonly = true)
private MavenSession session;
@Component
private BuildContext buildContext;
@Component(role = SettingsDecrypter.class)
private SettingsDecrypter decrypter;
/**
* Skips execution of this mojo.
*/
@Parameter(property = "skip.bun", defaultValue = "${skip.bun}")
private boolean skip;
@Override
protected boolean skipExecution() {
return this.skip;
}
@Override
public synchronized void execute(FrontendPluginFactory factory) throws TaskRunnerException {
File packageJson = new File(this.workingDirectory, "package.json");
if (this.buildContext == null || this.buildContext.hasDelta(packageJson)
|| !this.buildContext.isIncremental()) {
ProxyConfig proxyConfig = getProxyConfig();
factory.getBunRunner(proxyConfig, getRegistryUrl()).execute(this.arguments,
this.environmentVariables);
} else {
getLog().info("Skipping bun install as package.json unchanged");
}
}
private ProxyConfig getProxyConfig() {<FILL_FUNCTION_BODY>}
private String getRegistryUrl() {
// check to see if overridden via `-D`, otherwise fallback to pom value
return System.getProperty(NPM_REGISTRY_URL, this.npmRegistryURL);
}
} |
if (this.bunInheritsProxyConfigFromMaven) {
return MojoUtils.getProxyConfig(this.session, this.decrypter);
} else {
getLog().info("bun not inheriting proxy config from Maven");
return new ProxyConfig(Collections.<ProxyConfig.Proxy>emptyList());
}
| public abstract class AbstractFrontendMojo extends AbstractMojo {
@Component protected MojoExecution execution;
/**
* Whether you should skip while running in the test phase (default is false)
*/
@Parameter(property="skipTests",required=false,defaultValue="false") protected Boolean skipTests;
/**
* Set this to true to ignore a failure during testing. Its use is NOT RECOMMENDED, but quite convenient on occasion.
* @since 1.4
*/
@Parameter(property="maven.test.failure.ignore",defaultValue="false") protected boolean testFailureIgnore;
/**
* The base directory for running all Node commands. (Usually the directory that contains package.json)
*/
@Parameter(defaultValue="${basedir}",property="workingDirectory",required=false) protected File workingDirectory;
/**
* The base directory for installing node and npm.
*/
@Parameter(property="installDirectory",required=false) protected File installDirectory;
/**
* Additional environment variables to pass to the build.
*/
@Parameter protected Map<String,String> environmentVariables;
@Parameter(defaultValue="${project}",readonly=true) private MavenProject project;
@Parameter(defaultValue="${repositorySystemSession}",readonly=true) private RepositorySystemSession repositorySystemSession;
/**
* Determines if this execution should be skipped.
*/
private boolean skipTestPhase();
/**
* Determines if the current execution is during a testing phase (e.g., "test" or "integration-test").
*/
private boolean isTestingPhase();
protected abstract void execute( FrontendPluginFactory factory) throws FrontendException ;
/**
* Implemented by children to determine if this execution should be skipped.
*/
protected abstract boolean skipExecution();
@Override public void execute() throws MojoFailureException;
}
|
if (this.bunInheritsProxyConfigFromMaven) {
return this.session.getProxyConfig();
}
return ProxyConfig.EMPTY;
| [
"MavenSession"
] | [
"getProxyConfig"
] | [
"SettingsDecrypter",
"MavenSession"
] | [
"info",
"getProxyConfig"
] | {
"methods": [
"getProxyConfig"
],
"similar_methods": [
"getProxyConfig"
],
"types": [
"MavenSession"
]
} | final class ProcessExecutionException extends Exception {
private static final long serialVersionUID=1L;
public ProcessExecutionException( String message);
public ProcessExecutionException( Throwable cause);
}
private ProxyConfig getProxyConfig(){
if (bowerInheritsProxyConfigFromMaven) {
return MojoUtils.getProxyConfig(session,decrypter);
}
else {
getLog().info("bower not inheriting proxy config from Maven");
return new ProxyConfig(Collections.<ProxyConfig.Proxy>emptyList());
}
}
private ProxyConfig getProxyConfig(){
if (bowerInheritsProxyConfigFromMaven) {
return MojoUtils.getProxyConfig(session,decrypter);
}
else {
getLog().info("bower not inheriting proxy config from Maven");
return new ProxyConfig(Collections.<ProxyConfig.Proxy>emptyList());
}
}
| final class ProcessExecutionException extends Exception {
private static final long serialVersionUID=1L;
public ProcessExecutionException( String message);
public ProcessExecutionException( Throwable cause);
}
private ProxyConfig getProxyConfig(){
if (bowerInheritsProxyConfigFromMaven) {
return MojoUtils.getProxyConfig(session,decrypter);
}
else {
getLog().info("bower not inheriting proxy config from Maven");
return new ProxyConfig(Collections.<ProxyConfig.Proxy>emptyList());
}
}
private ProxyConfig getProxyConfig(){
if (bowerInheritsProxyConfigFromMaven) {
return MojoUtils.getProxyConfig(session,decrypter);
}
else {
getLog().info("bower not inheriting proxy config from Maven");
return new ProxyConfig(Collections.<ProxyConfig.Proxy>emptyList());
}
}
| {"types": [{"MavenSession": "ProcessExecutionException"}], "methods": [{"getProxyConfig": "getProxyConfig"}], "similar_methods": [{"getProxyConfig": "getProxyConfig"}]} | [{"MavenSession": {"retrieved_name": "ProcessExecutionException", "raw_body": "final class ProcessExecutionException extends Exception {\n private static final long serialVersionUID=1L;\n public ProcessExecutionException( String message);\n public ProcessExecutionException( Throwable cause);\n}\n", "raw_body_no_cmt": "final class ProcessExecutionException extends Exception {\n private static final long serialVersionUID=1L;\n public ProcessExecutionException( String message);\n public ProcessExecutionException( Throwable cause);\n}\n"}}] | [{"getProxyConfig": {"retrieved_name": "getProxyConfig", "raw_body": "private ProxyConfig getProxyConfig(){\n if (bowerInheritsProxyConfigFromMaven) {\n return MojoUtils.getProxyConfig(session,decrypter);\n }\n else {\n getLog().info(\"bower not inheriting proxy config from Maven\");\n return new ProxyConfig(Collections.<ProxyConfig.Proxy>emptyList());\n }\n}\n"}}] | [{"getProxyConfig": {"retrieved_name": "getProxyConfig", "raw_body": "private ProxyConfig getProxyConfig(){\n if (bowerInheritsProxyConfigFromMaven) {\n return MojoUtils.getProxyConfig(session,decrypter);\n }\n else {\n getLog().info(\"bower not inheriting proxy config from Maven\");\n return new ProxyConfig(Collections.<ProxyConfig.Proxy>emptyList());\n }\n}\n"}}] |
elunez_eladmin | eladmin/eladmin-system/src/main/java/me/zhengjie/AppRun.java | AppRun | main | class AppRun {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
@Bean
public SpringContextHolder springContextHolder() {
return new SpringContextHolder();
}
/**
* 访问首页提示
*
* @return /
*/
@AnonymousGetMapping("/")
public String index() {
return "Backend service started successfully";
}
} |
SpringApplication springApplication = new SpringApplication(AppRun.class);
// 监控应用的PID,启动时可指定PID路径:--spring.pid.file=/home/eladmin/app.pid
// 或者在 application.yml 添加文件路径,方便 kill,kill `cat /home/eladmin/app.pid`
springApplication.addListeners(new ApplicationPidFileWriter());
springApplication.run(args);
|
SpringApplication.run(AppRun.class, args);
| [] | [
"run"
] | [
"SpringApplication"
] | [
"run",
"addListeners"
] | {
"methods": [
"run"
],
"similar_methods": [
"main"
],
"types": []
} | public void run(){
log.info("run 执行成功");
}
public static void main(String[] args){
}
| public void run(){
log.info("run 执行成功");
}
public static void main(String[] args){
}
| {"methods": [{"run": "run"}], "similar_methods": [{"main": "main"}]} | [] | [{"run": {"retrieved_name": "run", "raw_body": "public void run(){\n log.info(\"run \u6267\u884c\u6210\u529f\");\n}\n"}}] | [{"main": {"retrieved_name": "main", "raw_body": "public static void main(String[] args){\n}\n"}}] |
|
pmd_pmd | pmd/pmd-compat6/src/main/java/net/sourceforge/pmd/util/filter/OrFilter.java | OrFilter | filter | class OrFilter<T> extends AbstractCompoundFilter<T> {
public OrFilter() {
super();
}
public OrFilter(Filter<T>... filters) {
super(filters);
}
@Override
public boolean filter(T obj) {<FILL_FUNCTION_BODY>}
@Override
protected String getOperator() {
return "or";
}
} |
boolean match = false;
for (Filter<T> filter : filters) {
if (filter.filter(obj)) {
match = true;
break;
}
}
return match;
|
for (Filter<T> filter : filters) {
if (filter.filter(obj)) {
return true;
}
}
return false;
| [
"Filter<T>",
"T"
] | [
"filter"
] | [
"T",
"Filter<T>"
] | [
"filter"
] | {
"methods": [
"filter"
],
"similar_methods": [
"filter"
],
"types": [
"Filter<T>",
"T"
]
} | /**
* Utility class for working with Filters. Contains builder style methods, apply methods, as well as mechanisms for adapting Filters and FilenameFilters.
* @deprecated Internal API, see {@link Filter}
*/
@Deprecated @InternalApi public final class Filters {
private Filters();
/**
* Filter a given Collection.
* @param < T > Type of the Collection.
* @param filter A Filter upon the Type of objects in the Collection.
* @param collection The Collection to filter.
* @return A List containing only those objects for which the Filterreturned <code>true</code>.
*/
public static <T>List<T> filter( Filter<T> filter, Collection<T> collection);
/**
* Get a File Filter for files with the given extensions, ignoring case.
* @param extensions The extensions to filter.
* @return A File Filter.
*/
public static Filter<File> getFileExtensionFilter( String... extensions);
/**
* Get a File Filter for directories.
* @return A File Filter.
*/
public static Filter<File> getDirectoryFilter();
/**
* Get a File Filter for directories or for files with the given extensions, ignoring case.
* @param extensions The extensions to filter.
* @return A File Filter.
*/
public static Filter<File> getFileExtensionOrDirectoryFilter( String... extensions);
/**
* Given a String Filter, expose as a File Filter. The File paths are normalized to a standard pattern using <code>/</code> as a path separator which can be used cross platform easily in a regular expression based String Filter.
* @param filter A String Filter.
* @return A File Filter.
*/
public static Filter<File> toNormalizedFileFilter( final Filter<String> filter);
/**
* Given a String Filter, expose as a Filter on another type. The <code>toString()</code> method is called on the objects of the other type and delegated to the String Filter.
* @param < T > The desired type.
* @param filter The existing String Filter.
* @return A Filter on the desired type.
*/
public static <T>Filter<T> fromStringFilter( final Filter<String> filter);
/**
* Given a File Filter, expose as a FilenameFilter.
* @param filter The File Filter.
* @return A FilenameFilter.
*/
public static FilenameFilter toFilenameFilter( final Filter<File> filter);
/**
* Given a FilenameFilter, expose as a File Filter.
* @param filter The FilenameFilter.
* @return A File Filter.
*/
public static Filter<File> toFileFilter( final FilenameFilter filter);
/**
* Construct a String Filter using set of include and exclude regular expressions. If there are no include regular expressions provide, then a regular expression is added which matches every String by default. A String is included as long as it matches an include regular expression and does not match an exclude regular expression. <p> In other words, exclude patterns override include patterns.
* @param includeRegexes The include regular expressions. May be <code>null</code>.
* @param excludeRegexes The exclude regular expressions. May be <code>null</code>.
* @return A String Filter.
*/
public static Filter<String> buildRegexFilterExcludeOverInclude( List<String> includeRegexes, List<String> excludeRegexes);
/**
* Construct a String Filter using set of include and exclude regular expressions. If there are no include regular expressions provide, then a regular expression is added which matches every String by default. A String is included as long as the case that there is an include which matches or there is not an exclude which matches. <p> In other words, include patterns override exclude patterns.
* @param includeRegexes The include regular expressions. May be <code>null</code>.
* @param excludeRegexes The exclude regular expressions. May be <code>null</code>.
* @return A String Filter.
*/
public static Filter<String> buildRegexFilterIncludeOverExclude( List<String> includeRegexes, List<String> excludeRegexes);
}
public class C {
private C();
public class IC {
}
public static class ISC {
}
public static final String V="";
}
@Override public NodeStream<T> filter(Predicate<? super T> predicate){
return predicate.test(node) ? this : NodeStream.empty();
}
@Override public NodeStream<T> filter(Predicate<? super T> predicate){
return predicate.test(node) ? this : NodeStream.empty();
}
| public final class Filters {
private Filters();
public static <T>List<T> filter( Filter<T> filter, Collection<T> collection);
public static Filter<File> getFileExtensionFilter( String... extensions);
public static Filter<File> getDirectoryFilter();
public static Filter<File> getFileExtensionOrDirectoryFilter( String... extensions);
public static Filter<File> toNormalizedFileFilter( final Filter<String> filter);
public static <T>Filter<T> fromStringFilter( final Filter<String> filter);
public static FilenameFilter toFilenameFilter( final Filter<File> filter);
public static Filter<File> toFileFilter( final FilenameFilter filter);
public static Filter<String> buildRegexFilterExcludeOverInclude( List<String> includeRegexes, List<String> excludeRegexes);
public static Filter<String> buildRegexFilterIncludeOverExclude( List<String> includeRegexes, List<String> excludeRegexes);
}
public class C {
private C();
public class IC {
}
public static class ISC {
}
public static final String V="";
}
@Override public NodeStream<T> filter(Predicate<? super T> predicate){
return predicate.test(node) ? this : NodeStream.empty();
}
@Override public NodeStream<T> filter(Predicate<? super T> predicate){
return predicate.test(node) ? this : NodeStream.empty();
}
| {"types": [{"Filter<T>": "Filters"}, {"T": "C"}], "methods": [{"filter": "filter"}], "similar_methods": [{"filter": "filter"}]} | [{"Filter<T>": {"retrieved_name": "Filters", "raw_body": "/** \n * Utility class for working with Filters. Contains builder style methods, apply methods, as well as mechanisms for adapting Filters and FilenameFilters.\n * @deprecated Internal API, see {@link Filter}\n */\n@Deprecated @InternalApi public final class Filters {\n private Filters();\n /** \n * Filter a given Collection.\n * @param < T > Type of the Collection.\n * @param filter A Filter upon the Type of objects in the Collection.\n * @param collection The Collection to filter.\n * @return A List containing only those objects for which the Filterreturned <code>true</code>.\n */\n public static <T>List<T> filter( Filter<T> filter, Collection<T> collection);\n /** \n * Get a File Filter for files with the given extensions, ignoring case.\n * @param extensions The extensions to filter.\n * @return A File Filter.\n */\n public static Filter<File> getFileExtensionFilter( String... extensions);\n /** \n * Get a File Filter for directories.\n * @return A File Filter.\n */\n public static Filter<File> getDirectoryFilter();\n /** \n * Get a File Filter for directories or for files with the given extensions, ignoring case.\n * @param extensions The extensions to filter.\n * @return A File Filter.\n */\n public static Filter<File> getFileExtensionOrDirectoryFilter( String... extensions);\n /** \n * Given a String Filter, expose as a File Filter. The File paths are normalized to a standard pattern using <code>/</code> as a path separator which can be used cross platform easily in a regular expression based String Filter.\n * @param filter A String Filter.\n * @return A File Filter.\n */\n public static Filter<File> toNormalizedFileFilter( final Filter<String> filter);\n /** \n * Given a String Filter, expose as a Filter on another type. The <code>toString()</code> method is called on the objects of the other type and delegated to the String Filter.\n * @param < T > The desired type.\n * @param filter The existing String Filter.\n * @return A Filter on the desired type.\n */\n public static <T>Filter<T> fromStringFilter( final Filter<String> filter);\n /** \n * Given a File Filter, expose as a FilenameFilter.\n * @param filter The File Filter.\n * @return A FilenameFilter.\n */\n public static FilenameFilter toFilenameFilter( final Filter<File> filter);\n /** \n * Given a FilenameFilter, expose as a File Filter.\n * @param filter The FilenameFilter.\n * @return A File Filter.\n */\n public static Filter<File> toFileFilter( final FilenameFilter filter);\n /** \n * Construct a String Filter using set of include and exclude regular expressions. If there are no include regular expressions provide, then a regular expression is added which matches every String by default. A String is included as long as it matches an include regular expression and does not match an exclude regular expression. <p> In other words, exclude patterns override include patterns.\n * @param includeRegexes The include regular expressions. May be <code>null</code>.\n * @param excludeRegexes The exclude regular expressions. May be <code>null</code>.\n * @return A String Filter.\n */\n public static Filter<String> buildRegexFilterExcludeOverInclude( List<String> includeRegexes, List<String> excludeRegexes);\n /** \n * Construct a String Filter using set of include and exclude regular expressions. If there are no include regular expressions provide, then a regular expression is added which matches every String by default. A String is included as long as the case that there is an include which matches or there is not an exclude which matches. <p> In other words, include patterns override exclude patterns.\n * @param includeRegexes The include regular expressions. May be <code>null</code>.\n * @param excludeRegexes The exclude regular expressions. May be <code>null</code>.\n * @return A String Filter.\n */\n public static Filter<String> buildRegexFilterIncludeOverExclude( List<String> includeRegexes, List<String> excludeRegexes);\n}\n", "raw_body_no_cmt": "public final class Filters {\n private Filters();\n public static <T>List<T> filter( Filter<T> filter, Collection<T> collection);\n public static Filter<File> getFileExtensionFilter( String... extensions);\n public static Filter<File> getDirectoryFilter();\n public static Filter<File> getFileExtensionOrDirectoryFilter( String... extensions);\n public static Filter<File> toNormalizedFileFilter( final Filter<String> filter);\n public static <T>Filter<T> fromStringFilter( final Filter<String> filter);\n public static FilenameFilter toFilenameFilter( final Filter<File> filter);\n public static Filter<File> toFileFilter( final FilenameFilter filter);\n public static Filter<String> buildRegexFilterExcludeOverInclude( List<String> includeRegexes, List<String> excludeRegexes);\n public static Filter<String> buildRegexFilterIncludeOverExclude( List<String> includeRegexes, List<String> excludeRegexes);\n}\n"}}, {"T": {"retrieved_name": "C", "raw_body": "public class C {\n private C();\npublic class IC {\n }\npublic static class ISC {\n }\n public static final String V=\"\";\n}\n", "raw_body_no_cmt": "public class C {\n private C();\npublic class IC {\n }\npublic static class ISC {\n }\n public static final String V=\"\";\n}\n"}}] | [{"filter": {"retrieved_name": "filter", "raw_body": "@Override public NodeStream<T> filter(Predicate<? super T> predicate){\n return predicate.test(node) ? this : NodeStream.empty();\n}\n"}}] | [{"filter": {"retrieved_name": "filter", "raw_body": "@Override public NodeStream<T> filter(Predicate<? super T> predicate){\n return predicate.test(node) ? this : NodeStream.empty();\n}\n"}}] |
|
orientechnologies_orientdb | orientdb/distributed/src/main/java/com/orientechnologies/orient/server/distributed/impl/OSynchronizedTaskWrapper.java | OSynchronizedTaskWrapper | execute | class OSynchronizedTaskWrapper extends OAbstractRemoteTask {
private boolean usesDatabase;
private CountDownLatch latch;
private ORemoteTask task;
public OSynchronizedTaskWrapper(
final CountDownLatch iLatch, final String iNodeName, final ORemoteTask iTask) {
this.latch = iLatch;
this.task = iTask;
this.task.setNodeSource(iNodeName);
this.usesDatabase = true;
}
public OSynchronizedTaskWrapper(final CountDownLatch iLatch) {
latch = iLatch;
usesDatabase = false;
}
@Override
public String getName() {
return null;
}
@Override
public OCommandDistributedReplicateRequest.QUORUM_TYPE getQuorumType() {
return null;
}
@Override
public Object execute(
ODistributedRequestId requestId,
OServer iServer,
ODistributedServerManager iManager,
ODatabaseDocumentInternal database)
throws Exception {<FILL_FUNCTION_BODY>}
@Override
public int getFactoryId() {
return 0;
}
@Override
public String toString() {
return "(" + (task != null ? task.toString() : "-") + ")";
}
@Override
public boolean isUsingDatabase() {
return usesDatabase;
}
@Override
public boolean hasResponse() {
if (task == null) return super.hasResponse();
else return task.hasResponse();
}
} |
try {
if (task != null) return task.execute(requestId, iServer, iManager, database);
return null;
} finally {
// RELEASE ALL PENDING WORKERS
latch.countDown();
}
| /**
* Base class for Tasks to be executed remotely.
* @author Luca Garulli (l.garulli--at--orientdb.com)
*/
public abstract class OAbstractRemoteTask implements ORemoteTask {
protected transient String nodeSource;
/**
* Constructor used from unmarshalling.
*/
public OAbstractRemoteTask();
@Override public long getDistributedTimeout();
@Override public long getSynchronousTimeout( final int iSynchNodes);
@Override public long getTotalTimeout( final int iTotalNodes);
@Override public boolean hasResponse();
@Override public RESULT_STRATEGY getResultStrategy();
@Override public String toString();
@Override public String getNodeSource();
@Override public void setNodeSource( String nodeSource);
@Override public boolean isIdempotent();
@Override public boolean isNodeOnlineRequired();
@Override public boolean isUsingDatabase();
@Override public void toStream( DataOutput out) throws IOException;
@Override public void fromStream( DataInput in, ORemoteTaskFactory factory) throws IOException;
}
|
try {
if (task != null) {
return task.execute(requestId, iServer, iManager, database);
} else {
latch.countDown();
return null;
}
} finally {
if (task != null) {
task.release();
}
}
| [
"CountDownLatch",
"ODatabaseDocumentInternal",
"OServer",
"ORemoteTask",
"ODistributedRequestId",
"ODistributedServerManager"
] | [
"countDown",
"execute",
"release"
] | [
"ORemoteTask",
"ODatabaseDocumentInternal",
"ODistributedRequestId",
"CountDownLatch",
"OServer",
"ODistributedServerManager"
] | [
"countDown",
"execute"
] | {
"methods": [
"countDown",
"execute",
"release"
],
"similar_methods": [
"execute"
],
"types": [
"CountDownLatch",
"ODatabaseDocumentInternal",
"OServer",
"ORemoteTask",
"ODistributedRequestId",
"ODistributedServerManager"
]
} | /**
* Counts the records from the previous steps. Returns a record with a single property, called "count" containing the count of records received from pervious steps
* @author Luigi Dell'Aquila (l.dellaquila-(at)-orientdb.com)
*/
public class CountStep extends AbstractExecutionStep {
/**
* @param ctx the query context
* @param profilingEnabled true to enable the profiling of the execution (for SQL PROFILE)
*/
public CountStep( OCommandContext ctx, boolean profilingEnabled);
@Override public OExecutionStream internalStart( OCommandContext ctx) throws OTimeoutException;
@Override public String prettyPrint( int depth, int indent);
@Override public boolean canBeCached();
@Override public OExecutionStep copy( OCommandContext ctx);
}
public interface ODatabaseDocumentInternal extends ODatabaseSession, ODatabaseInternal<ORecord> {
/**
* Internal. Returns the factory that defines a set of components that current database should use to be compatible to current version of storage. So if you open a database create with old version of OrientDB it defines a components that should be used to provide backward compatibility with that version of database.
*/
OCurrentStorageComponentsFactory getStorageVersions();
/**
* Internal. Gets an instance of sb-tree collection manager for current database.
*/
OSBTreeCollectionManager getSbTreeCollectionManager();
/**
* @return the factory of binary serializers.
*/
OBinarySerializerFactory getSerializerFactory();
/**
* @return serializer which is used for document serialization.
*/
ORecordSerializer getSerializer();
void setSerializer( ORecordSerializer serializer);
int assignAndCheckCluster( ORecord record, String iClusterName);
<RET extends ORecord>RET loadIfVersionIsNotLatest( final ORID rid, final int recordVersion, String fetchPlan, boolean ignoreCache) throws ORecordNotFoundException ;
void reloadUser();
void afterReadOperations( final OIdentifiable identifiable);
/**
* @param identifiable
* @return true if the record should be skipped
*/
boolean beforeReadOperations( final OIdentifiable identifiable);
/**
* @param id
* @param iClusterName
* @return null if nothing changed the instance if has been modified or replaced
*/
OIdentifiable beforeCreateOperations( final OIdentifiable id, String iClusterName);
/**
* @param id
* @param iClusterName
* @return null if nothing changed the instance if has been modified or replaced
*/
OIdentifiable beforeUpdateOperations( final OIdentifiable id, String iClusterName);
void beforeDeleteOperations( final OIdentifiable id, String iClusterName);
void afterUpdateOperations( final OIdentifiable id);
void afterCreateOperations( final OIdentifiable id);
void afterDeleteOperations( final OIdentifiable id);
ORecordHook.RESULT callbackHooks( final ORecordHook.TYPE type, final OIdentifiable id);
<RET extends ORecord>RET executeReadRecord( final ORecordId rid, ORecord iRecord, final int recordVersion, final String fetchPlan, final boolean ignoreCache, final boolean iUpdateCache, final boolean loadTombstones, final OStorage.LOCKING_STRATEGY lockingStrategy, RecordReader recordReader);
void executeDeleteRecord( OIdentifiable record, final int iVersion, final boolean iRequired, final OPERATION_MODE iMode, boolean prohibitTombstones);
void setDefaultTransactionMode( Map<ORID,OTransactionAbstract.LockedRecordMetadata> noTxLocks);
@Override OMetadataInternal getMetadata();
ODatabaseDocumentInternal copy();
void recycle( ORecord record);
void checkIfActive();
void callOnOpenListeners();
void callOnCloseListeners();
void callOnDropListeners();
<DB extends ODatabase>DB setCustom( final String name, final Object iValue);
void setPrefetchRecords( boolean prefetchRecords);
boolean isPrefetchRecords();
void checkForClusterPermissions( String name);
void rawBegin( OTransaction transaction);
default OResultSet getActiveQuery( String id);
default Map<String,OQueryDatabaseState> getActiveQueries();
boolean isUseLightweightEdges();
OEdge newLightweightEdge( String iClassName, OVertex from, OVertex to);
OEdge newRegularEdge( String iClassName, OVertex from, OVertex to);
void setUseLightweightEdges( boolean b);
ODatabaseDocumentInternal cleanOutRecord( ORID rid, int version);
default void realClose();
default void reuse();
/**
* synchronizes current database instance with the rest of the cluster (if in distributed mode).
* @return true if the database was synchronized, false otherwise
*/
default boolean sync( boolean forceDeployment, boolean tryWithDelta);
default Map<String,Object> getHaStatus( boolean servers, boolean db, boolean latency, boolean messages);
default boolean removeHaServer( String serverName);
/**
* sends an execution plan to a remote node for a remote query execution
* @param nodeName the node name
* @param executionPlan the execution plan
* @param inputParameters the input parameters for execution
* @return an OResultSet to fetch the results of the query execution
*/
default OResultSet queryOnNode( String nodeName, OExecutionPlan executionPlan, Map<Object,Object> inputParameters);
/**
* Executed the commit on the storage hiding away storage concepts from the transaction
* @param transaction
*/
void internalCommit( OTransactionInternal transaction);
boolean isClusterVertex( int cluster);
boolean isClusterEdge( int cluster);
boolean isClusterView( int cluster);
default OTransaction swapTx( OTransaction newTx);
void internalClose( boolean recycle);
ORecord saveAll( ORecord iRecord, String iClusterName, OPERATION_MODE iMode, boolean iForceCreate, ORecordCallback<? extends Number> iRecordCreatedCallback, ORecordCallback<Integer> iRecordUpdatedCallback);
String getClusterName( final ORecord record);
default OResultSet indexQuery( String indexName, String query, Object... args);
OView getViewFromCluster( int cluster);
void internalLockRecord( OIdentifiable iRecord, OStorage.LOCKING_STRATEGY lockingStrategy);
void internalUnlockRecord( OIdentifiable iRecord);
<T>T sendSequenceAction( OSequenceAction action) throws ExecutionException, InterruptedException ;
default boolean isDistributed();
default boolean isRemote();
Map<UUID,OBonsaiCollectionPointer> getCollectionsChanges();
default void syncCommit( OTransactionData data);
default boolean isLocalEnv();
boolean dropClusterInternal( int clusterId);
default String getStorageId();
long[] getClusterDataRange( int currentClusterId);
void setDefaultClusterId( int addCluster);
long getLastClusterPosition( int clusterId);
String getClusterRecordConflictStrategy( int clusterId);
int[] getClustersIds( Set<String> filterClusters);
default void startEsclusiveMetadataChange();
default void endEsclusiveMetadataChange();
default void queryStartUsingViewCluster( int cluster);
default void queryStartUsingViewIndex( String index);
public void truncateClass( String name);
public long truncateClass( String name, boolean polimorfic);
public long truncateClusterInternal( String name);
}
public class OServer {
private static final String ROOT_PASSWORD_VAR="ORIENTDB_ROOT_PASSWORD";
private static ThreadGroup threadGroup;
private static final Map<String,OServer> distributedServers=new ConcurrentHashMap<String,OServer>();
private CountDownLatch startupLatch;
private CountDownLatch shutdownLatch;
private final boolean shutdownEngineOnExit;
protected ReentrantLock lock=new ReentrantLock();
protected volatile boolean running=false;
protected volatile boolean rejectRequests=true;
protected OServerConfigurationManager serverCfg;
protected OContextConfiguration contextConfiguration;
protected OServerShutdownHook shutdownHook;
protected Map<String,Class<? extends ONetworkProtocol>> networkProtocols=new HashMap<String,Class<? extends ONetworkProtocol>>();
protected Map<String,OServerSocketFactory> networkSocketFactories=new HashMap<String,OServerSocketFactory>();
protected List<OServerNetworkListener> networkListeners=new ArrayList<OServerNetworkListener>();
protected List<OServerLifecycleListener> lifecycleListeners=new ArrayList<OServerLifecycleListener>();
protected OServerPluginManager pluginManager;
protected OConfigurableHooksManager hookManager;
protected ODistributedServerManager distributedManager;
private final Map<String,Object> variables=new HashMap<String,Object>();
private String serverRootDirectory;
private String databaseDirectory;
private OClientConnectionManager clientConnectionManager;
private OHttpSessionManager httpSessionManager;
private OPushManager pushManager;
private ClassLoader extensionClassLoader;
private OTokenHandler tokenHandler;
private OrientDB context;
private OrientDBInternal databases;
protected Date startedOn=new Date();
public OServer();
public OServer( boolean shutdownEngineOnExit);
public static OServer startFromFileConfig( String config) throws ClassNotFoundException, InstantiationException, IOException, IllegalAccessException;
public static OServer startFromClasspathConfig( String config) throws ClassNotFoundException, InstantiationException, IOException, IllegalAccessException;
public static OServer startFromStreamConfig( InputStream config) throws ClassNotFoundException, InstantiationException, IOException, IllegalAccessException;
public static OServer getInstance( final String iServerId);
public static OServer getInstanceByPath( final String iPath);
public static void registerServerInstance( final String iServerId, final OServer iServer);
public static void unregisterServerInstance( final String iServerId);
/**
* Set the preferred {@link ClassLoader} used to load extensions.
* @since 2.1
*/
public void setExtensionClassLoader( final ClassLoader extensionClassLoader);
/**
* Get the preferred {@link ClassLoader} used to load extensions.
* @since 2.1
*/
public ClassLoader getExtensionClassLoader();
public OSecuritySystem getSecurity();
public boolean isActive();
public OClientConnectionManager getClientConnectionManager();
public OHttpSessionManager getHttpSessionManager();
public OPushManager getPushManager();
public void saveConfiguration() throws IOException;
public void restart() throws ClassNotFoundException, InvocationTargetException, InstantiationException, NoSuchMethodException, IllegalAccessException, IOException;
public OSystemDatabase getSystemDatabase();
public String getServerId();
/**
* Load an extension class by name.
*/
private Class<?> loadClass( final String name) throws ClassNotFoundException;
/**
* Attempt to load a class from givenstar class-loader.
*/
private Class<?> tryLoadClass( final ClassLoader classLoader, final String name);
public OServer startup() throws OConfigurationException;
public OServer startup( final File iConfigurationFile) throws OConfigurationException;
public OServer startup( final String iConfiguration) throws IOException;
public OServer startup( final InputStream iInputStream) throws IOException;
public OServer startup( final OServerConfiguration iConfiguration) throws IllegalArgumentException, SecurityException, IOException;
public OServer startupFromConfiguration() throws IOException;
@SuppressWarnings("unchecked") public OServer activate() throws ClassNotFoundException, InstantiationException, IllegalAccessException;
public void removeShutdownHook();
public boolean shutdown();
protected boolean deinit();
public boolean rejectRequests();
public void waitForShutdown();
public Map<String,String> getAvailableStorageNames();
/**
* Opens all the available server's databases.
*/
protected void loadDatabases();
private boolean askForEncryptionKey( final String iDatabaseName);
public String getDatabaseDirectory();
public ThreadGroup getServerThreadGroup();
/**
* Authenticate a server user.
* @param iUserName Username to authenticate
* @param iPassword Password in clear
* @return true if authentication is ok, otherwise false
*/
public boolean authenticate( final String iUserName, final String iPassword, final String iResourceToCheck);
public OSecurityUser authenticateUser( final String iUserName, final String iPassword, final String iResourceToCheck);
public boolean existsStoragePath( final String iURL);
public OServerConfiguration getConfiguration();
public Map<String,Class<? extends ONetworkProtocol>> getNetworkProtocols();
public List<OServerNetworkListener> getNetworkListeners();
@SuppressWarnings("unchecked") public <RET extends OServerNetworkListener>RET getListenerByProtocol( final Class<? extends ONetworkProtocol> iProtocolClass);
public Collection<OServerPluginInfo> getPlugins();
public OContextConfiguration getContextConfiguration();
@SuppressWarnings("unchecked") public <RET extends OServerPlugin>RET getPluginByClass( final Class<RET> iPluginClass);
@SuppressWarnings("unchecked") public <RET extends OServerPlugin>RET getPlugin( final String iName);
public Object getVariable( final String iName);
public OServer setVariable( final String iName, final Object iValue);
public void addTemporaryUser( final String iName, final String iPassword, final String iPermissions);
public OServer registerLifecycleListener( final OServerLifecycleListener iListener);
public OServer unregisterLifecycleListener( final OServerLifecycleListener iListener);
public ODatabaseDocumentInternal openDatabase( final String iDbUrl, final OParsedToken iToken);
public ODatabaseDocumentInternal openDatabase( final String iDbUrl, final String user, final String password);
public ODatabaseDocumentInternal openDatabase( final String iDbUrl, final String user, final String password, ONetworkProtocolData data);
public ODatabaseDocumentInternal openDatabase( String database);
public ODistributedServerManager getDistributedManager();
public void setServerRootDirectory( final String rootDirectory);
protected void initFromConfiguration();
public OConfigurableHooksManager getHookManager();
protected void loadUsers() throws IOException;
/**
* Load configured storages.
*/
protected void loadStorages();
protected void createDefaultServerUsers() throws IOException;
private boolean existsSystemUser( String user);
public OServerPluginManager getPluginManager();
protected void registerPlugins() throws InstantiationException, IllegalAccessException, ClassNotFoundException;
protected void defaultSettings();
public OTokenHandler getTokenHandler();
public ThreadGroup getThreadGroup();
private void initSystemDatabase();
public OrientDBInternal getDatabases();
public OrientDB getContext();
public void dropDatabase( String databaseName);
public boolean existsDatabase( String databaseName);
public void createDatabase( String databaseName, ODatabaseType type, OrientDBConfig config);
public Set<String> listDatabases();
public void restore( String name, String path);
public Date getStartedOn();
}
/**
* Remote Task interface.
* @author Luca Garulli (l.garulli--(at)--orientdb.com)
*/
public interface ORemoteTask {
boolean hasResponse();
default void received( ODistributedRequest request, ODistributedDatabase distributedDatabase);
enum RESULT_STRATEGY { ANY, UNION}
String getName();
OCommandDistributedReplicateRequest.QUORUM_TYPE getQuorumType();
Object execute( ODistributedRequestId requestId, OServer iServer, ODistributedServerManager iManager, ODatabaseDocumentInternal database) throws Exception ;
long getDistributedTimeout();
long getSynchronousTimeout( final int iSynchNodes);
long getTotalTimeout( final int iTotalNodes);
OAbstractRemoteTask.RESULT_STRATEGY getResultStrategy();
String getNodeSource();
void setNodeSource( String nodeSource);
boolean isIdempotent();
boolean isNodeOnlineRequired();
boolean isUsingDatabase();
int getFactoryId();
void toStream( DataOutput out) throws IOException ;
void fromStream( DataInput in, ORemoteTaskFactory factory) throws IOException ;
default void finished( ODistributedDatabase distributedDatabase);
}
/**
* Immutable object representing the distributed request id.
* @author Luca Garulli (l.garulli--(at)--orientdb.com)
*/
public class ODistributedRequestId implements Comparable, OStreamable, Externalizable {
private int nodeId;
private long messageId;
public ODistributedRequestId();
public ODistributedRequestId( final int iNodeId, final long iMessageId);
public long getMessageId();
public int getNodeId();
@Override public boolean equals( final Object obj);
@Override public int compareTo( final Object obj);
@Override public int hashCode();
public void toStream( final DataOutput out) throws IOException;
public void fromStream( final DataInput in) throws IOException;
@Override public void writeExternal( final ObjectOutput out) throws IOException;
@Override public void readExternal( final ObjectInput in) throws IOException, ClassNotFoundException;
@Override public String toString();
}
/**
* Server cluster interface to abstract cluster behavior.
* @author Luca Garulli (l.garulli--at--orientdb.com)
*/
public interface ODistributedServerManager {
String FILE_DISTRIBUTED_DB_CONFIG="distributed-config.json";
/**
* Server status.
*/
enum NODE_STATUS { /**
* The server was never started or the shutdown is complete.
*/
OFFLINE, /**
* The server is STARTING.
*/
STARTING, /**
* The server is ONLINE.
*/
ONLINE, /**
* The server starts to merge to another cluster.
*/
MERGING, /**
* The server is shutting down.
*/
SHUTTINGDOWN}
/**
* Database status.
*/
enum DB_STATUS { /**
* The database is not installed. In this status the server does not receive any request.
*/
NOT_AVAILABLE, /**
* The database has been put in OFFLINE status. In this status the server does not receive any request.
*/
OFFLINE, /**
* The database is in synchronization status. This status is set when a synchronization (full or delta) is requested. The node tha accepts the synchronization, is in SYNCHRONIZING mode too. During this status the server receive requests that will be enqueue until the database is ready. Server in SYNCHRONIZING status do not concur in the quorum.
*/
SYNCHRONIZING, /**
* The database is ONLINE as fully operative. During this status the server is considered in the quorum (if the server's role is MASTER)
*/
ONLINE, /**
* The database is ONLINE, but is not involved in the quorum.
*/
BACKUP}
/**
* Checks the node status if it's one of the statuses received as argument.
* @param iNodeName Node name
* @param iDatabaseName Database name
* @param statuses vararg of statuses
* @return true if the node's status is equals to one of the passed statuses, otherwise false
*/
boolean isNodeStatusEqualsTo( String iNodeName, String iDatabaseName, DB_STATUS... statuses);
boolean isNodeAvailable( String iNodeName);
Set<String> getAvailableNodeNames( String databaseName);
Set<String> getAvailableNodeNotLocalNames( String databaseName);
@Deprecated String getCoordinatorServer();
void waitUntilNodeOnline() throws InterruptedException ;
void waitUntilNodeOnline( String nodeName, String databaseName) throws InterruptedException ;
OServer getServerInstance();
boolean isEnabled();
ODistributedServerManager registerLifecycleListener( ODistributedLifecycleListener iListener);
ODistributedServerManager unregisterLifecycleListener( ODistributedLifecycleListener iListener);
Object executeOnLocalNode( ODistributedRequestId reqId, ORemoteTask task, ODatabaseDocumentInternal database);
void executeOnLocalNodeFromRemote( ODistributedRequest request);
ORemoteServerController getRemoteServer( String nodeName) throws IOException ;
long getLastClusterChangeOn();
NODE_STATUS getNodeStatus();
void setNodeStatus( NODE_STATUS iStatus);
boolean checkNodeStatus( NODE_STATUS status);
void removeServer( String nodeLeftName, boolean removeOnlyDynamicServers);
DB_STATUS getDatabaseStatus( String iNode, String iDatabaseName);
void setDatabaseStatus( String iNode, String iDatabaseName, DB_STATUS iStatus);
int getNodesWithStatus( Collection<String> iNodes, String databaseName, DB_STATUS... statuses);
ODistributedMessageService getMessageService();
ODistributedDatabase getDatabase( String name);
ODistributedStrategy getDistributedStrategy();
void setDistributedStrategy( ODistributedStrategy streatgy);
boolean updateCachedDatabaseConfiguration( String iDatabaseName, OModifiableDistributedConfiguration cfg);
void publishDistributedConfiguration( String iDatabaseName, ODistributedConfiguration cfg);
long getNextMessageIdCounter();
String getNodeUuidByName( String name);
void updateLastClusterChange();
void reassignClustersOwnership( String iNode, String databaseName, OModifiableDistributedConfiguration cfg, boolean canCreateNewClusters);
/**
* Available means not OFFLINE, so ONLINE or SYNCHRONIZING.
*/
boolean isNodeAvailable( String iNodeName, String databaseName);
/**
* Returns true if the node status is ONLINE.
*/
boolean isNodeOnline( String iNodeName, String databaseName);
int getTotalNodes( String iDatabaseName);
int getAvailableNodes( String iDatabaseName);
int getAvailableNodes( Collection<String> iNodes, String databaseName);
boolean isOffline();
int getLocalNodeId();
String getLocalNodeName();
ODocument getClusterConfiguration();
String getNodeNameById( int id);
int getNodeIdByName( String node);
ODocument getNodeConfigurationByUuid( String iNode, boolean useCache);
ODocument getLocalNodeConfiguration();
ODistributedConfiguration getDatabaseConfiguration( String iDatabaseName);
/**
* Sends a distributed request against multiple servers.
* @param iDatabaseName
* @param iTargetNodeNames
* @param iTask
* @return
*/
ODistributedResponse sendRequest( String iDatabaseName, Collection<String> iTargetNodeNames, ORemoteTask iTask);
/**
* Sends a distributed request against multiple servers.
* @param iDatabaseName
* @param node
* @param iTask
* @return
*/
ODistributedResponse sendSingleRequest( String iDatabaseName, String node, ORemoteTask iTask);
ODistributedResponse sendRequest( String iDatabaseName, Collection<String> iTargetNodeNames, ORemoteTask iTask, long messageId, Object localResult, ODistributedResponseManagerFactory responseManagerFactory);
ODocument getStats();
Throwable convertException( Throwable original);
List<String> getOnlineNodes( String iDatabaseName);
List<String> getOnlineNodesNotLocal( String iDatabaseName);
boolean installDatabase( boolean iStartup, String databaseName, boolean forceDeployment, boolean tryWithDeltaFirst);
/**
* Returns the task factory manager. During first connect the minor version of the protocol is used.
*/
ORemoteTaskFactoryManager getTaskFactoryManager();
Set<String> getActiveServers();
Set<String> getActiveServerNotLocal();
/**
* Returns the cluster-wide time in milliseconds. <p>Cluster tries to keep a cluster-wide time which might be different than the member's own system time. Cluster-wide time is -almost- the same on all members of the cluster.
*/
long getClusterTime();
File getDefaultDatabaseConfigFile();
ODistributedLockManager getLockManagerRequester();
ODistributedLockManager getLockManagerExecutor();
/**
* Executes an operation protected by a distributed lock (one per database).
* @param < T > Return type
* @param databaseName Database name
* @param timeoutLocking
* @param iCallback Operation @return The operation's result of type T
*/
<T>T executeInDistributedDatabaseLock( String databaseName, long timeoutLocking, OModifiableDistributedConfiguration lastCfg, OCallable<T,OModifiableDistributedConfiguration> iCallback);
/**
* Returns true if the quorum is present in terms of number of available nodes for full replication only. With sharding, instead, the quorum may depend on the involved clusters.
* @return
*/
boolean isWriteQuorumPresent( String databaseName);
void notifyClients( String databaseName);
default void messageReceived( ODistributedRequest request);
default void messagePartitionCalculate( ODistributedRequest request, Set<Integer> involvedWorkerQueues);
default void messageBeforeOp( String op, ODistributedRequestId requestId);
default void messageAfterOp( String op, ODistributedRequestId requestId);
default void messageCurrentPayload( ODistributedRequestId requestId, Object responsePayload);
default void messageProcessStart( ODistributedRequest message);
default void messageProcessEnd( ODistributedRequest iRequest, Object responsePayload);
ODocument getOnlineDatabaseConfiguration( String databaseName);
}
@After public void tearDown() throws Exception {
graph.shutdown();
}
@Override public OBinaryResponse execute(OBinaryRequestExecutor executor){
return executor.executeReadRecord(this);
}
/**
* Allows to execute write-related commands on DB. Called after {@link #freeze()} command.
* @see #freeze()
*/
void release();
/**
* Execute a script in a specified query language. The result set has to be closed after usage <br> <br> Sample usage: <p><code> String script = "INSERT INTO Person SET name = 'foo', surname = ?;"+ "INSERT INTO Person SET name = 'bar', surname = ?;"+ "INSERT INTO Person SET name = 'baz', surname = ?;"; <p> OResultSet rs = db.execute("sql", script, "Surname1", "Surname2", "Surname3"); ... rs.close(); </code>
* @param language
* @param script
* @param args
* @return
*/
default OResultSet execute(String language,String script,Object... args) throws OCommandExecutionException, OCommandScriptException {
throw new UnsupportedOperationException();
}
| public class CountStep extends AbstractExecutionStep {
public CountStep( OCommandContext ctx, boolean profilingEnabled);
public OExecutionStream internalStart( OCommandContext ctx) throws OTimeoutException;
public String prettyPrint( int depth, int indent);
public boolean canBeCached();
public OExecutionStep copy( OCommandContext ctx);
}
public interface ODatabaseDocumentInternal extends ODatabaseSession, ODatabaseInternal<ORecord> {
OCurrentStorageComponentsFactory getStorageVersions();
OSBTreeCollectionManager getSbTreeCollectionManager();
OBinarySerializerFactory getSerializerFactory();
ORecordSerializer getSerializer();
void setSerializer( ORecordSerializer serializer);
int assignAndCheckCluster( ORecord record, String iClusterName);
<RET extends ORecord>RET loadIfVersionIsNotLatest( final ORID rid, final int recordVersion, String fetchPlan, boolean ignoreCache) throws ORecordNotFoundException ;
void reloadUser();
void afterReadOperations( final OIdentifiable identifiable);
boolean beforeReadOperations( final OIdentifiable identifiable);
OIdentifiable beforeCreateOperations( final OIdentifiable id, String iClusterName);
OIdentifiable beforeUpdateOperations( final OIdentifiable id, String iClusterName);
void beforeDeleteOperations( final OIdentifiable id, String iClusterName);
void afterUpdateOperations( final OIdentifiable id);
void afterCreateOperations( final OIdentifiable id);
void afterDeleteOperations( final OIdentifiable id);
ORecordHook.RESULT callbackHooks( final ORecordHook.TYPE type, final OIdentifiable id);
<RET extends ORecord>RET executeReadRecord( final ORecordId rid, ORecord iRecord, final int recordVersion, final String fetchPlan, final boolean ignoreCache, final boolean iUpdateCache, final boolean loadTombstones, final OStorage.LOCKING_STRATEGY lockingStrategy, RecordReader recordReader);
void executeDeleteRecord( OIdentifiable record, final int iVersion, final boolean iRequired, final OPERATION_MODE iMode, boolean prohibitTombstones);
void setDefaultTransactionMode( Map<ORID,OTransactionAbstract.LockedRecordMetadata> noTxLocks);
OMetadataInternal getMetadata();
ODatabaseDocumentInternal copy();
void recycle( ORecord record);
void checkIfActive();
void callOnOpenListeners();
void callOnCloseListeners();
void callOnDropListeners();
<DB extends ODatabase>DB setCustom( final String name, final Object iValue);
void setPrefetchRecords( boolean prefetchRecords);
boolean isPrefetchRecords();
void checkForClusterPermissions( String name);
void rawBegin( OTransaction transaction);
default OResultSet getActiveQuery( String id);
default Map<String,OQueryDatabaseState> getActiveQueries();
boolean isUseLightweightEdges();
OEdge newLightweightEdge( String iClassName, OVertex from, OVertex to);
OEdge newRegularEdge( String iClassName, OVertex from, OVertex to);
void setUseLightweightEdges( boolean b);
ODatabaseDocumentInternal cleanOutRecord( ORID rid, int version);
default void realClose();
default void reuse();
default boolean sync( boolean forceDeployment, boolean tryWithDelta);
default Map<String,Object> getHaStatus( boolean servers, boolean db, boolean latency, boolean messages);
default boolean removeHaServer( String serverName);
default OResultSet queryOnNode( String nodeName, OExecutionPlan executionPlan, Map<Object,Object> inputParameters);
void internalCommit( OTransactionInternal transaction);
boolean isClusterVertex( int cluster);
boolean isClusterEdge( int cluster);
boolean isClusterView( int cluster);
default OTransaction swapTx( OTransaction newTx);
void internalClose( boolean recycle);
ORecord saveAll( ORecord iRecord, String iClusterName, OPERATION_MODE iMode, boolean iForceCreate, ORecordCallback<? extends Number> iRecordCreatedCallback, ORecordCallback<Integer> iRecordUpdatedCallback);
String getClusterName( final ORecord record);
default OResultSet indexQuery( String indexName, String query, Object... args);
OView getViewFromCluster( int cluster);
void internalLockRecord( OIdentifiable iRecord, OStorage.LOCKING_STRATEGY lockingStrategy);
void internalUnlockRecord( OIdentifiable iRecord);
<T>T sendSequenceAction( OSequenceAction action) throws ExecutionException, InterruptedException ;
default boolean isDistributed();
default boolean isRemote();
Map<UUID,OBonsaiCollectionPointer> getCollectionsChanges();
default void syncCommit( OTransactionData data);
default boolean isLocalEnv();
boolean dropClusterInternal( int clusterId);
default String getStorageId();
long[] getClusterDataRange( int currentClusterId);
void setDefaultClusterId( int addCluster);
long getLastClusterPosition( int clusterId);
String getClusterRecordConflictStrategy( int clusterId);
int[] getClustersIds( Set<String> filterClusters);
default void startEsclusiveMetadataChange();
default void endEsclusiveMetadataChange();
default void queryStartUsingViewCluster( int cluster);
default void queryStartUsingViewIndex( String index);
public void truncateClass( String name);
public long truncateClass( String name, boolean polimorfic);
public long truncateClusterInternal( String name);
}
public class OServer {
private static final String ROOT_PASSWORD_VAR="ORIENTDB_ROOT_PASSWORD";
private static ThreadGroup threadGroup;
private static final Map<String,OServer> distributedServers=new ConcurrentHashMap<String,OServer>();
private CountDownLatch startupLatch;
private CountDownLatch shutdownLatch;
private final boolean shutdownEngineOnExit;
protected ReentrantLock lock=new ReentrantLock();
protected volatile boolean running=false;
protected volatile boolean rejectRequests=true;
protected OServerConfigurationManager serverCfg;
protected OContextConfiguration contextConfiguration;
protected OServerShutdownHook shutdownHook;
protected Map<String,Class<? extends ONetworkProtocol>> networkProtocols=new HashMap<String,Class<? extends ONetworkProtocol>>();
protected Map<String,OServerSocketFactory> networkSocketFactories=new HashMap<String,OServerSocketFactory>();
protected List<OServerNetworkListener> networkListeners=new ArrayList<OServerNetworkListener>();
protected List<OServerLifecycleListener> lifecycleListeners=new ArrayList<OServerLifecycleListener>();
protected OServerPluginManager pluginManager;
protected OConfigurableHooksManager hookManager;
protected ODistributedServerManager distributedManager;
private final Map<String,Object> variables=new HashMap<String,Object>();
private String serverRootDirectory;
private String databaseDirectory;
private OClientConnectionManager clientConnectionManager;
private OHttpSessionManager httpSessionManager;
private OPushManager pushManager;
private ClassLoader extensionClassLoader;
private OTokenHandler tokenHandler;
private OrientDB context;
private OrientDBInternal databases;
protected Date startedOn=new Date();
public OServer();
public OServer( boolean shutdownEngineOnExit);
public static OServer startFromFileConfig( String config) throws ClassNotFoundException, InstantiationException, IOException, IllegalAccessException;
public static OServer startFromClasspathConfig( String config) throws ClassNotFoundException, InstantiationException, IOException, IllegalAccessException;
public static OServer startFromStreamConfig( InputStream config) throws ClassNotFoundException, InstantiationException, IOException, IllegalAccessException;
public static OServer getInstance( final String iServerId);
public static OServer getInstanceByPath( final String iPath);
public static void registerServerInstance( final String iServerId, final OServer iServer);
public static void unregisterServerInstance( final String iServerId);
public void setExtensionClassLoader( final ClassLoader extensionClassLoader);
public ClassLoader getExtensionClassLoader();
public OSecuritySystem getSecurity();
public boolean isActive();
public OClientConnectionManager getClientConnectionManager();
public OHttpSessionManager getHttpSessionManager();
public OPushManager getPushManager();
public void saveConfiguration() throws IOException;
public void restart() throws ClassNotFoundException, InvocationTargetException, InstantiationException, NoSuchMethodException, IllegalAccessException, IOException;
public OSystemDatabase getSystemDatabase();
public String getServerId();
private Class<?> loadClass( final String name) throws ClassNotFoundException;
private Class<?> tryLoadClass( final ClassLoader classLoader, final String name);
public OServer startup() throws OConfigurationException;
public OServer startup( final File iConfigurationFile) throws OConfigurationException;
public OServer startup( final String iConfiguration) throws IOException;
public OServer startup( final InputStream iInputStream) throws IOException;
public OServer startup( final OServerConfiguration iConfiguration) throws IllegalArgumentException, SecurityException, IOException;
public OServer startupFromConfiguration() throws IOException;
public OServer activate() throws ClassNotFoundException, InstantiationException, IllegalAccessException;
public void removeShutdownHook();
public boolean shutdown();
protected boolean deinit();
public boolean rejectRequests();
public void waitForShutdown();
public Map<String,String> getAvailableStorageNames();
protected void loadDatabases();
private boolean askForEncryptionKey( final String iDatabaseName);
public String getDatabaseDirectory();
public ThreadGroup getServerThreadGroup();
public boolean authenticate( final String iUserName, final String iPassword, final String iResourceToCheck);
public OSecurityUser authenticateUser( final String iUserName, final String iPassword, final String iResourceToCheck);
public boolean existsStoragePath( final String iURL);
public OServerConfiguration getConfiguration();
public Map<String,Class<? extends ONetworkProtocol>> getNetworkProtocols();
public List<OServerNetworkListener> getNetworkListeners();
public <RET extends OServerNetworkListener>RET getListenerByProtocol( final Class<? extends ONetworkProtocol> iProtocolClass);
public Collection<OServerPluginInfo> getPlugins();
public OContextConfiguration getContextConfiguration();
public <RET extends OServerPlugin>RET getPluginByClass( final Class<RET> iPluginClass);
public <RET extends OServerPlugin>RET getPlugin( final String iName);
public Object getVariable( final String iName);
public OServer setVariable( final String iName, final Object iValue);
public void addTemporaryUser( final String iName, final String iPassword, final String iPermissions);
public OServer registerLifecycleListener( final OServerLifecycleListener iListener);
public OServer unregisterLifecycleListener( final OServerLifecycleListener iListener);
public ODatabaseDocumentInternal openDatabase( final String iDbUrl, final OParsedToken iToken);
public ODatabaseDocumentInternal openDatabase( final String iDbUrl, final String user, final String password);
public ODatabaseDocumentInternal openDatabase( final String iDbUrl, final String user, final String password, ONetworkProtocolData data);
public ODatabaseDocumentInternal openDatabase( String database);
public ODistributedServerManager getDistributedManager();
public void setServerRootDirectory( final String rootDirectory);
protected void initFromConfiguration();
public OConfigurableHooksManager getHookManager();
protected void loadUsers() throws IOException;
protected void loadStorages();
protected void createDefaultServerUsers() throws IOException;
private boolean existsSystemUser( String user);
public OServerPluginManager getPluginManager();
protected void registerPlugins() throws InstantiationException, IllegalAccessException, ClassNotFoundException;
protected void defaultSettings();
public OTokenHandler getTokenHandler();
public ThreadGroup getThreadGroup();
private void initSystemDatabase();
public OrientDBInternal getDatabases();
public OrientDB getContext();
public void dropDatabase( String databaseName);
public boolean existsDatabase( String databaseName);
public void createDatabase( String databaseName, ODatabaseType type, OrientDBConfig config);
public Set<String> listDatabases();
public void restore( String name, String path);
public Date getStartedOn();
}
public interface ORemoteTask {
boolean hasResponse();
default void received( ODistributedRequest request, ODistributedDatabase distributedDatabase);
enum RESULT_STRATEGY { ANY, UNION}
String getName();
OCommandDistributedReplicateRequest.QUORUM_TYPE getQuorumType();
Object execute( ODistributedRequestId requestId, OServer iServer, ODistributedServerManager iManager, ODatabaseDocumentInternal database) throws Exception ;
long getDistributedTimeout();
long getSynchronousTimeout( final int iSynchNodes);
long getTotalTimeout( final int iTotalNodes);
OAbstractRemoteTask.RESULT_STRATEGY getResultStrategy();
String getNodeSource();
void setNodeSource( String nodeSource);
boolean isIdempotent();
boolean isNodeOnlineRequired();
boolean isUsingDatabase();
int getFactoryId();
void toStream( DataOutput out) throws IOException ;
void fromStream( DataInput in, ORemoteTaskFactory factory) throws IOException ;
default void finished( ODistributedDatabase distributedDatabase);
}
public class ODistributedRequestId implements Comparable, OStreamable, Externalizable {
private int nodeId;
private long messageId;
public ODistributedRequestId();
public ODistributedRequestId( final int iNodeId, final long iMessageId);
public long getMessageId();
public int getNodeId();
public boolean equals( final Object obj);
public int compareTo( final Object obj);
public int hashCode();
public void toStream( final DataOutput out) throws IOException;
public void fromStream( final DataInput in) throws IOException;
public void writeExternal( final ObjectOutput out) throws IOException;
public void readExternal( final ObjectInput in) throws IOException, ClassNotFoundException;
public String toString();
}
public interface ODistributedServerManager {
String FILE_DISTRIBUTED_DB_CONFIG="distributed-config.json";
enum NODE_STATUS { /**
* The server was never started or the shutdown is complete.
*/
OFFLINE, /**
* The server is STARTING.
*/
STARTING, /**
* The server is ONLINE.
*/
ONLINE, /**
* The server starts to merge to another cluster.
*/
MERGING, /**
* The server is shutting down.
*/
SHUTTINGDOWN}
enum DB_STATUS { /**
* The database is not installed. In this status the server does not receive any request.
*/
NOT_AVAILABLE, /**
* The database has been put in OFFLINE status. In this status the server does not receive any request.
*/
OFFLINE, /**
* The database is in synchronization status. This status is set when a synchronization (full or delta) is requested. The node tha accepts the synchronization, is in SYNCHRONIZING mode too. During this status the server receive requests that will be enqueue until the database is ready. Server in SYNCHRONIZING status do not concur in the quorum.
*/
SYNCHRONIZING, /**
* The database is ONLINE as fully operative. During this status the server is considered in the quorum (if the server's role is MASTER)
*/
ONLINE, /**
* The database is ONLINE, but is not involved in the quorum.
*/
BACKUP}
boolean isNodeStatusEqualsTo( String iNodeName, String iDatabaseName, DB_STATUS... statuses);
boolean isNodeAvailable( String iNodeName);
Set<String> getAvailableNodeNames( String databaseName);
Set<String> getAvailableNodeNotLocalNames( String databaseName);
String getCoordinatorServer();
void waitUntilNodeOnline() throws InterruptedException ;
void waitUntilNodeOnline( String nodeName, String databaseName) throws InterruptedException ;
OServer getServerInstance();
boolean isEnabled();
ODistributedServerManager registerLifecycleListener( ODistributedLifecycleListener iListener);
ODistributedServerManager unregisterLifecycleListener( ODistributedLifecycleListener iListener);
Object executeOnLocalNode( ODistributedRequestId reqId, ORemoteTask task, ODatabaseDocumentInternal database);
void executeOnLocalNodeFromRemote( ODistributedRequest request);
ORemoteServerController getRemoteServer( String nodeName) throws IOException ;
long getLastClusterChangeOn();
NODE_STATUS getNodeStatus();
void setNodeStatus( NODE_STATUS iStatus);
boolean checkNodeStatus( NODE_STATUS status);
void removeServer( String nodeLeftName, boolean removeOnlyDynamicServers);
DB_STATUS getDatabaseStatus( String iNode, String iDatabaseName);
void setDatabaseStatus( String iNode, String iDatabaseName, DB_STATUS iStatus);
int getNodesWithStatus( Collection<String> iNodes, String databaseName, DB_STATUS... statuses);
ODistributedMessageService getMessageService();
ODistributedDatabase getDatabase( String name);
ODistributedStrategy getDistributedStrategy();
void setDistributedStrategy( ODistributedStrategy streatgy);
boolean updateCachedDatabaseConfiguration( String iDatabaseName, OModifiableDistributedConfiguration cfg);
void publishDistributedConfiguration( String iDatabaseName, ODistributedConfiguration cfg);
long getNextMessageIdCounter();
String getNodeUuidByName( String name);
void updateLastClusterChange();
void reassignClustersOwnership( String iNode, String databaseName, OModifiableDistributedConfiguration cfg, boolean canCreateNewClusters);
boolean isNodeAvailable( String iNodeName, String databaseName);
boolean isNodeOnline( String iNodeName, String databaseName);
int getTotalNodes( String iDatabaseName);
int getAvailableNodes( String iDatabaseName);
int getAvailableNodes( Collection<String> iNodes, String databaseName);
boolean isOffline();
int getLocalNodeId();
String getLocalNodeName();
ODocument getClusterConfiguration();
String getNodeNameById( int id);
int getNodeIdByName( String node);
ODocument getNodeConfigurationByUuid( String iNode, boolean useCache);
ODocument getLocalNodeConfiguration();
ODistributedConfiguration getDatabaseConfiguration( String iDatabaseName);
ODistributedResponse sendRequest( String iDatabaseName, Collection<String> iTargetNodeNames, ORemoteTask iTask);
ODistributedResponse sendSingleRequest( String iDatabaseName, String node, ORemoteTask iTask);
ODistributedResponse sendRequest( String iDatabaseName, Collection<String> iTargetNodeNames, ORemoteTask iTask, long messageId, Object localResult, ODistributedResponseManagerFactory responseManagerFactory);
ODocument getStats();
Throwable convertException( Throwable original);
List<String> getOnlineNodes( String iDatabaseName);
List<String> getOnlineNodesNotLocal( String iDatabaseName);
boolean installDatabase( boolean iStartup, String databaseName, boolean forceDeployment, boolean tryWithDeltaFirst);
ORemoteTaskFactoryManager getTaskFactoryManager();
Set<String> getActiveServers();
Set<String> getActiveServerNotLocal();
long getClusterTime();
File getDefaultDatabaseConfigFile();
ODistributedLockManager getLockManagerRequester();
ODistributedLockManager getLockManagerExecutor();
<T>T executeInDistributedDatabaseLock( String databaseName, long timeoutLocking, OModifiableDistributedConfiguration lastCfg, OCallable<T,OModifiableDistributedConfiguration> iCallback);
boolean isWriteQuorumPresent( String databaseName);
void notifyClients( String databaseName);
default void messageReceived( ODistributedRequest request);
default void messagePartitionCalculate( ODistributedRequest request, Set<Integer> involvedWorkerQueues);
default void messageBeforeOp( String op, ODistributedRequestId requestId);
default void messageAfterOp( String op, ODistributedRequestId requestId);
default void messageCurrentPayload( ODistributedRequestId requestId, Object responsePayload);
default void messageProcessStart( ODistributedRequest message);
default void messageProcessEnd( ODistributedRequest iRequest, Object responsePayload);
ODocument getOnlineDatabaseConfiguration( String databaseName);
}
@After public void tearDown() throws Exception {
graph.shutdown();
}
@Override public OBinaryResponse execute(OBinaryRequestExecutor executor){
return executor.executeReadRecord(this);
}
/**
* Allows to execute write-related commands on DB. Called after {@link #freeze()} command.
* @see #freeze()
*/
void release();
/**
* Execute a script in a specified query language. The result set has to be closed after usage <br> <br> Sample usage: <p><code> String script = "INSERT INTO Person SET name = 'foo', surname = ?;"+ "INSERT INTO Person SET name = 'bar', surname = ?;"+ "INSERT INTO Person SET name = 'baz', surname = ?;"; <p> OResultSet rs = db.execute("sql", script, "Surname1", "Surname2", "Surname3"); ... rs.close(); </code>
* @param language
* @param script
* @param args
* @return
*/
default OResultSet execute(String language,String script,Object... args) throws OCommandExecutionException, OCommandScriptException {
throw new UnsupportedOperationException();
}
| {"types": [{"CountDownLatch": "CountStep"}, {"ODatabaseDocumentInternal": "ODatabaseDocumentInternal"}, {"OServer": "OServer"}, {"ORemoteTask": "ORemoteTask"}, {"ODistributedRequestId": "ODistributedRequestId"}, {"ODistributedServerManager": "ODistributedServerManager"}], "methods": [{"countDown": "tearDown"}, {"execute": "execute"}, {"release": "release"}], "similar_methods": [{"execute": "execute"}]} | [{"CountDownLatch": {"retrieved_name": "CountStep", "raw_body": "/** \n * Counts the records from the previous steps. Returns a record with a single property, called \"count\" containing the count of records received from pervious steps\n * @author Luigi Dell'Aquila (l.dellaquila-(at)-orientdb.com)\n */\npublic class CountStep extends AbstractExecutionStep {\n /** \n * @param ctx the query context\n * @param profilingEnabled true to enable the profiling of the execution (for SQL PROFILE)\n */\n public CountStep( OCommandContext ctx, boolean profilingEnabled);\n @Override public OExecutionStream internalStart( OCommandContext ctx) throws OTimeoutException;\n @Override public String prettyPrint( int depth, int indent);\n @Override public boolean canBeCached();\n @Override public OExecutionStep copy( OCommandContext ctx);\n}\n", "raw_body_no_cmt": "public class CountStep extends AbstractExecutionStep {\n public CountStep( OCommandContext ctx, boolean profilingEnabled);\n public OExecutionStream internalStart( OCommandContext ctx) throws OTimeoutException;\n public String prettyPrint( int depth, int indent);\n public boolean canBeCached();\n public OExecutionStep copy( OCommandContext ctx);\n}\n"}}, {"ODatabaseDocumentInternal": {"retrieved_name": "ODatabaseDocumentInternal", "raw_body": "public interface ODatabaseDocumentInternal extends ODatabaseSession, ODatabaseInternal<ORecord> {\n /** \n * Internal. Returns the factory that defines a set of components that current database should use to be compatible to current version of storage. So if you open a database create with old version of OrientDB it defines a components that should be used to provide backward compatibility with that version of database.\n */\n OCurrentStorageComponentsFactory getStorageVersions();\n /** \n * Internal. Gets an instance of sb-tree collection manager for current database. \n */\n OSBTreeCollectionManager getSbTreeCollectionManager();\n /** \n * @return the factory of binary serializers. \n */\n OBinarySerializerFactory getSerializerFactory();\n /** \n * @return serializer which is used for document serialization. \n */\n ORecordSerializer getSerializer();\n void setSerializer( ORecordSerializer serializer);\n int assignAndCheckCluster( ORecord record, String iClusterName);\n <RET extends ORecord>RET loadIfVersionIsNotLatest( final ORID rid, final int recordVersion, String fetchPlan, boolean ignoreCache) throws ORecordNotFoundException ;\n void reloadUser();\n void afterReadOperations( final OIdentifiable identifiable);\n /** \n * @param identifiable\n * @return true if the record should be skipped\n */\n boolean beforeReadOperations( final OIdentifiable identifiable);\n /** \n * @param id\n * @param iClusterName\n * @return null if nothing changed the instance if has been modified or replaced\n */\n OIdentifiable beforeCreateOperations( final OIdentifiable id, String iClusterName);\n /** \n * @param id\n * @param iClusterName\n * @return null if nothing changed the instance if has been modified or replaced\n */\n OIdentifiable beforeUpdateOperations( final OIdentifiable id, String iClusterName);\n void beforeDeleteOperations( final OIdentifiable id, String iClusterName);\n void afterUpdateOperations( final OIdentifiable id);\n void afterCreateOperations( final OIdentifiable id);\n void afterDeleteOperations( final OIdentifiable id);\n ORecordHook.RESULT callbackHooks( final ORecordHook.TYPE type, final OIdentifiable id);\n <RET extends ORecord>RET executeReadRecord( final ORecordId rid, ORecord iRecord, final int recordVersion, final String fetchPlan, final boolean ignoreCache, final boolean iUpdateCache, final boolean loadTombstones, final OStorage.LOCKING_STRATEGY lockingStrategy, RecordReader recordReader);\n void executeDeleteRecord( OIdentifiable record, final int iVersion, final boolean iRequired, final OPERATION_MODE iMode, boolean prohibitTombstones);\n void setDefaultTransactionMode( Map<ORID,OTransactionAbstract.LockedRecordMetadata> noTxLocks);\n @Override OMetadataInternal getMetadata();\n ODatabaseDocumentInternal copy();\n void recycle( ORecord record);\n void checkIfActive();\n void callOnOpenListeners();\n void callOnCloseListeners();\n void callOnDropListeners();\n <DB extends ODatabase>DB setCustom( final String name, final Object iValue);\n void setPrefetchRecords( boolean prefetchRecords);\n boolean isPrefetchRecords();\n void checkForClusterPermissions( String name);\n void rawBegin( OTransaction transaction);\n default OResultSet getActiveQuery( String id);\n default Map<String,OQueryDatabaseState> getActiveQueries();\n boolean isUseLightweightEdges();\n OEdge newLightweightEdge( String iClassName, OVertex from, OVertex to);\n OEdge newRegularEdge( String iClassName, OVertex from, OVertex to);\n void setUseLightweightEdges( boolean b);\n ODatabaseDocumentInternal cleanOutRecord( ORID rid, int version);\n default void realClose();\n default void reuse();\n /** \n * synchronizes current database instance with the rest of the cluster (if in distributed mode).\n * @return true if the database was synchronized, false otherwise\n */\n default boolean sync( boolean forceDeployment, boolean tryWithDelta);\n default Map<String,Object> getHaStatus( boolean servers, boolean db, boolean latency, boolean messages);\n default boolean removeHaServer( String serverName);\n /** \n * sends an execution plan to a remote node for a remote query execution\n * @param nodeName the node name\n * @param executionPlan the execution plan\n * @param inputParameters the input parameters for execution\n * @return an OResultSet to fetch the results of the query execution\n */\n default OResultSet queryOnNode( String nodeName, OExecutionPlan executionPlan, Map<Object,Object> inputParameters);\n /** \n * Executed the commit on the storage hiding away storage concepts from the transaction\n * @param transaction\n */\n void internalCommit( OTransactionInternal transaction);\n boolean isClusterVertex( int cluster);\n boolean isClusterEdge( int cluster);\n boolean isClusterView( int cluster);\n default OTransaction swapTx( OTransaction newTx);\n void internalClose( boolean recycle);\n ORecord saveAll( ORecord iRecord, String iClusterName, OPERATION_MODE iMode, boolean iForceCreate, ORecordCallback<? extends Number> iRecordCreatedCallback, ORecordCallback<Integer> iRecordUpdatedCallback);\n String getClusterName( final ORecord record);\n default OResultSet indexQuery( String indexName, String query, Object... args);\n OView getViewFromCluster( int cluster);\n void internalLockRecord( OIdentifiable iRecord, OStorage.LOCKING_STRATEGY lockingStrategy);\n void internalUnlockRecord( OIdentifiable iRecord);\n <T>T sendSequenceAction( OSequenceAction action) throws ExecutionException, InterruptedException ;\n default boolean isDistributed();\n default boolean isRemote();\n Map<UUID,OBonsaiCollectionPointer> getCollectionsChanges();\n default void syncCommit( OTransactionData data);\n default boolean isLocalEnv();\n boolean dropClusterInternal( int clusterId);\n default String getStorageId();\n long[] getClusterDataRange( int currentClusterId);\n void setDefaultClusterId( int addCluster);\n long getLastClusterPosition( int clusterId);\n String getClusterRecordConflictStrategy( int clusterId);\n int[] getClustersIds( Set<String> filterClusters);\n default void startEsclusiveMetadataChange();\n default void endEsclusiveMetadataChange();\n default void queryStartUsingViewCluster( int cluster);\n default void queryStartUsingViewIndex( String index);\n public void truncateClass( String name);\n public long truncateClass( String name, boolean polimorfic);\n public long truncateClusterInternal( String name);\n}\n", "raw_body_no_cmt": "public interface ODatabaseDocumentInternal extends ODatabaseSession, ODatabaseInternal<ORecord> {\n OCurrentStorageComponentsFactory getStorageVersions();\n OSBTreeCollectionManager getSbTreeCollectionManager();\n OBinarySerializerFactory getSerializerFactory();\n ORecordSerializer getSerializer();\n void setSerializer( ORecordSerializer serializer);\n int assignAndCheckCluster( ORecord record, String iClusterName);\n <RET extends ORecord>RET loadIfVersionIsNotLatest( final ORID rid, final int recordVersion, String fetchPlan, boolean ignoreCache) throws ORecordNotFoundException ;\n void reloadUser();\n void afterReadOperations( final OIdentifiable identifiable);\n boolean beforeReadOperations( final OIdentifiable identifiable);\n OIdentifiable beforeCreateOperations( final OIdentifiable id, String iClusterName);\n OIdentifiable beforeUpdateOperations( final OIdentifiable id, String iClusterName);\n void beforeDeleteOperations( final OIdentifiable id, String iClusterName);\n void afterUpdateOperations( final OIdentifiable id);\n void afterCreateOperations( final OIdentifiable id);\n void afterDeleteOperations( final OIdentifiable id);\n ORecordHook.RESULT callbackHooks( final ORecordHook.TYPE type, final OIdentifiable id);\n <RET extends ORecord>RET executeReadRecord( final ORecordId rid, ORecord iRecord, final int recordVersion, final String fetchPlan, final boolean ignoreCache, final boolean iUpdateCache, final boolean loadTombstones, final OStorage.LOCKING_STRATEGY lockingStrategy, RecordReader recordReader);\n void executeDeleteRecord( OIdentifiable record, final int iVersion, final boolean iRequired, final OPERATION_MODE iMode, boolean prohibitTombstones);\n void setDefaultTransactionMode( Map<ORID,OTransactionAbstract.LockedRecordMetadata> noTxLocks);\n OMetadataInternal getMetadata();\n ODatabaseDocumentInternal copy();\n void recycle( ORecord record);\n void checkIfActive();\n void callOnOpenListeners();\n void callOnCloseListeners();\n void callOnDropListeners();\n <DB extends ODatabase>DB setCustom( final String name, final Object iValue);\n void setPrefetchRecords( boolean prefetchRecords);\n boolean isPrefetchRecords();\n void checkForClusterPermissions( String name);\n void rawBegin( OTransaction transaction);\n default OResultSet getActiveQuery( String id);\n default Map<String,OQueryDatabaseState> getActiveQueries();\n boolean isUseLightweightEdges();\n OEdge newLightweightEdge( String iClassName, OVertex from, OVertex to);\n OEdge newRegularEdge( String iClassName, OVertex from, OVertex to);\n void setUseLightweightEdges( boolean b);\n ODatabaseDocumentInternal cleanOutRecord( ORID rid, int version);\n default void realClose();\n default void reuse();\n default boolean sync( boolean forceDeployment, boolean tryWithDelta);\n default Map<String,Object> getHaStatus( boolean servers, boolean db, boolean latency, boolean messages);\n default boolean removeHaServer( String serverName);\n default OResultSet queryOnNode( String nodeName, OExecutionPlan executionPlan, Map<Object,Object> inputParameters);\n void internalCommit( OTransactionInternal transaction);\n boolean isClusterVertex( int cluster);\n boolean isClusterEdge( int cluster);\n boolean isClusterView( int cluster);\n default OTransaction swapTx( OTransaction newTx);\n void internalClose( boolean recycle);\n ORecord saveAll( ORecord iRecord, String iClusterName, OPERATION_MODE iMode, boolean iForceCreate, ORecordCallback<? extends Number> iRecordCreatedCallback, ORecordCallback<Integer> iRecordUpdatedCallback);\n String getClusterName( final ORecord record);\n default OResultSet indexQuery( String indexName, String query, Object... args);\n OView getViewFromCluster( int cluster);\n void internalLockRecord( OIdentifiable iRecord, OStorage.LOCKING_STRATEGY lockingStrategy);\n void internalUnlockRecord( OIdentifiable iRecord);\n <T>T sendSequenceAction( OSequenceAction action) throws ExecutionException, InterruptedException ;\n default boolean isDistributed();\n default boolean isRemote();\n Map<UUID,OBonsaiCollectionPointer> getCollectionsChanges();\n default void syncCommit( OTransactionData data);\n default boolean isLocalEnv();\n boolean dropClusterInternal( int clusterId);\n default String getStorageId();\n long[] getClusterDataRange( int currentClusterId);\n void setDefaultClusterId( int addCluster);\n long getLastClusterPosition( int clusterId);\n String getClusterRecordConflictStrategy( int clusterId);\n int[] getClustersIds( Set<String> filterClusters);\n default void startEsclusiveMetadataChange();\n default void endEsclusiveMetadataChange();\n default void queryStartUsingViewCluster( int cluster);\n default void queryStartUsingViewIndex( String index);\n public void truncateClass( String name);\n public long truncateClass( String name, boolean polimorfic);\n public long truncateClusterInternal( String name);\n}\n"}}, {"OServer": {"retrieved_name": "OServer", "raw_body": "public class OServer {\n private static final String ROOT_PASSWORD_VAR=\"ORIENTDB_ROOT_PASSWORD\";\n private static ThreadGroup threadGroup;\n private static final Map<String,OServer> distributedServers=new ConcurrentHashMap<String,OServer>();\n private CountDownLatch startupLatch;\n private CountDownLatch shutdownLatch;\n private final boolean shutdownEngineOnExit;\n protected ReentrantLock lock=new ReentrantLock();\n protected volatile boolean running=false;\n protected volatile boolean rejectRequests=true;\n protected OServerConfigurationManager serverCfg;\n protected OContextConfiguration contextConfiguration;\n protected OServerShutdownHook shutdownHook;\n protected Map<String,Class<? extends ONetworkProtocol>> networkProtocols=new HashMap<String,Class<? extends ONetworkProtocol>>();\n protected Map<String,OServerSocketFactory> networkSocketFactories=new HashMap<String,OServerSocketFactory>();\n protected List<OServerNetworkListener> networkListeners=new ArrayList<OServerNetworkListener>();\n protected List<OServerLifecycleListener> lifecycleListeners=new ArrayList<OServerLifecycleListener>();\n protected OServerPluginManager pluginManager;\n protected OConfigurableHooksManager hookManager;\n protected ODistributedServerManager distributedManager;\n private final Map<String,Object> variables=new HashMap<String,Object>();\n private String serverRootDirectory;\n private String databaseDirectory;\n private OClientConnectionManager clientConnectionManager;\n private OHttpSessionManager httpSessionManager;\n private OPushManager pushManager;\n private ClassLoader extensionClassLoader;\n private OTokenHandler tokenHandler;\n private OrientDB context;\n private OrientDBInternal databases;\n protected Date startedOn=new Date();\n public OServer();\n public OServer( boolean shutdownEngineOnExit);\n public static OServer startFromFileConfig( String config) throws ClassNotFoundException, InstantiationException, IOException, IllegalAccessException;\n public static OServer startFromClasspathConfig( String config) throws ClassNotFoundException, InstantiationException, IOException, IllegalAccessException;\n public static OServer startFromStreamConfig( InputStream config) throws ClassNotFoundException, InstantiationException, IOException, IllegalAccessException;\n public static OServer getInstance( final String iServerId);\n public static OServer getInstanceByPath( final String iPath);\n public static void registerServerInstance( final String iServerId, final OServer iServer);\n public static void unregisterServerInstance( final String iServerId);\n /** \n * Set the preferred {@link ClassLoader} used to load extensions.\n * @since 2.1\n */\n public void setExtensionClassLoader( final ClassLoader extensionClassLoader);\n /** \n * Get the preferred {@link ClassLoader} used to load extensions.\n * @since 2.1\n */\n public ClassLoader getExtensionClassLoader();\n public OSecuritySystem getSecurity();\n public boolean isActive();\n public OClientConnectionManager getClientConnectionManager();\n public OHttpSessionManager getHttpSessionManager();\n public OPushManager getPushManager();\n public void saveConfiguration() throws IOException;\n public void restart() throws ClassNotFoundException, InvocationTargetException, InstantiationException, NoSuchMethodException, IllegalAccessException, IOException;\n public OSystemDatabase getSystemDatabase();\n public String getServerId();\n /** \n * Load an extension class by name. \n */\n private Class<?> loadClass( final String name) throws ClassNotFoundException;\n /** \n * Attempt to load a class from givenstar class-loader. \n */\n private Class<?> tryLoadClass( final ClassLoader classLoader, final String name);\n public OServer startup() throws OConfigurationException;\n public OServer startup( final File iConfigurationFile) throws OConfigurationException;\n public OServer startup( final String iConfiguration) throws IOException;\n public OServer startup( final InputStream iInputStream) throws IOException;\n public OServer startup( final OServerConfiguration iConfiguration) throws IllegalArgumentException, SecurityException, IOException;\n public OServer startupFromConfiguration() throws IOException;\n @SuppressWarnings(\"unchecked\") public OServer activate() throws ClassNotFoundException, InstantiationException, IllegalAccessException;\n public void removeShutdownHook();\n public boolean shutdown();\n protected boolean deinit();\n public boolean rejectRequests();\n public void waitForShutdown();\n public Map<String,String> getAvailableStorageNames();\n /** \n * Opens all the available server's databases. \n */\n protected void loadDatabases();\n private boolean askForEncryptionKey( final String iDatabaseName);\n public String getDatabaseDirectory();\n public ThreadGroup getServerThreadGroup();\n /** \n * Authenticate a server user.\n * @param iUserName Username to authenticate\n * @param iPassword Password in clear\n * @return true if authentication is ok, otherwise false\n */\n public boolean authenticate( final String iUserName, final String iPassword, final String iResourceToCheck);\n public OSecurityUser authenticateUser( final String iUserName, final String iPassword, final String iResourceToCheck);\n public boolean existsStoragePath( final String iURL);\n public OServerConfiguration getConfiguration();\n public Map<String,Class<? extends ONetworkProtocol>> getNetworkProtocols();\n public List<OServerNetworkListener> getNetworkListeners();\n @SuppressWarnings(\"unchecked\") public <RET extends OServerNetworkListener>RET getListenerByProtocol( final Class<? extends ONetworkProtocol> iProtocolClass);\n public Collection<OServerPluginInfo> getPlugins();\n public OContextConfiguration getContextConfiguration();\n @SuppressWarnings(\"unchecked\") public <RET extends OServerPlugin>RET getPluginByClass( final Class<RET> iPluginClass);\n @SuppressWarnings(\"unchecked\") public <RET extends OServerPlugin>RET getPlugin( final String iName);\n public Object getVariable( final String iName);\n public OServer setVariable( final String iName, final Object iValue);\n public void addTemporaryUser( final String iName, final String iPassword, final String iPermissions);\n public OServer registerLifecycleListener( final OServerLifecycleListener iListener);\n public OServer unregisterLifecycleListener( final OServerLifecycleListener iListener);\n public ODatabaseDocumentInternal openDatabase( final String iDbUrl, final OParsedToken iToken);\n public ODatabaseDocumentInternal openDatabase( final String iDbUrl, final String user, final String password);\n public ODatabaseDocumentInternal openDatabase( final String iDbUrl, final String user, final String password, ONetworkProtocolData data);\n public ODatabaseDocumentInternal openDatabase( String database);\n public ODistributedServerManager getDistributedManager();\n public void setServerRootDirectory( final String rootDirectory);\n protected void initFromConfiguration();\n public OConfigurableHooksManager getHookManager();\n protected void loadUsers() throws IOException;\n /** \n * Load configured storages. \n */\n protected void loadStorages();\n protected void createDefaultServerUsers() throws IOException;\n private boolean existsSystemUser( String user);\n public OServerPluginManager getPluginManager();\n protected void registerPlugins() throws InstantiationException, IllegalAccessException, ClassNotFoundException;\n protected void defaultSettings();\n public OTokenHandler getTokenHandler();\n public ThreadGroup getThreadGroup();\n private void initSystemDatabase();\n public OrientDBInternal getDatabases();\n public OrientDB getContext();\n public void dropDatabase( String databaseName);\n public boolean existsDatabase( String databaseName);\n public void createDatabase( String databaseName, ODatabaseType type, OrientDBConfig config);\n public Set<String> listDatabases();\n public void restore( String name, String path);\n public Date getStartedOn();\n}\n", "raw_body_no_cmt": "public class OServer {\n private static final String ROOT_PASSWORD_VAR=\"ORIENTDB_ROOT_PASSWORD\";\n private static ThreadGroup threadGroup;\n private static final Map<String,OServer> distributedServers=new ConcurrentHashMap<String,OServer>();\n private CountDownLatch startupLatch;\n private CountDownLatch shutdownLatch;\n private final boolean shutdownEngineOnExit;\n protected ReentrantLock lock=new ReentrantLock();\n protected volatile boolean running=false;\n protected volatile boolean rejectRequests=true;\n protected OServerConfigurationManager serverCfg;\n protected OContextConfiguration contextConfiguration;\n protected OServerShutdownHook shutdownHook;\n protected Map<String,Class<? extends ONetworkProtocol>> networkProtocols=new HashMap<String,Class<? extends ONetworkProtocol>>();\n protected Map<String,OServerSocketFactory> networkSocketFactories=new HashMap<String,OServerSocketFactory>();\n protected List<OServerNetworkListener> networkListeners=new ArrayList<OServerNetworkListener>();\n protected List<OServerLifecycleListener> lifecycleListeners=new ArrayList<OServerLifecycleListener>();\n protected OServerPluginManager pluginManager;\n protected OConfigurableHooksManager hookManager;\n protected ODistributedServerManager distributedManager;\n private final Map<String,Object> variables=new HashMap<String,Object>();\n private String serverRootDirectory;\n private String databaseDirectory;\n private OClientConnectionManager clientConnectionManager;\n private OHttpSessionManager httpSessionManager;\n private OPushManager pushManager;\n private ClassLoader extensionClassLoader;\n private OTokenHandler tokenHandler;\n private OrientDB context;\n private OrientDBInternal databases;\n protected Date startedOn=new Date();\n public OServer();\n public OServer( boolean shutdownEngineOnExit);\n public static OServer startFromFileConfig( String config) throws ClassNotFoundException, InstantiationException, IOException, IllegalAccessException;\n public static OServer startFromClasspathConfig( String config) throws ClassNotFoundException, InstantiationException, IOException, IllegalAccessException;\n public static OServer startFromStreamConfig( InputStream config) throws ClassNotFoundException, InstantiationException, IOException, IllegalAccessException;\n public static OServer getInstance( final String iServerId);\n public static OServer getInstanceByPath( final String iPath);\n public static void registerServerInstance( final String iServerId, final OServer iServer);\n public static void unregisterServerInstance( final String iServerId);\n public void setExtensionClassLoader( final ClassLoader extensionClassLoader);\n public ClassLoader getExtensionClassLoader();\n public OSecuritySystem getSecurity();\n public boolean isActive();\n public OClientConnectionManager getClientConnectionManager();\n public OHttpSessionManager getHttpSessionManager();\n public OPushManager getPushManager();\n public void saveConfiguration() throws IOException;\n public void restart() throws ClassNotFoundException, InvocationTargetException, InstantiationException, NoSuchMethodException, IllegalAccessException, IOException;\n public OSystemDatabase getSystemDatabase();\n public String getServerId();\n private Class<?> loadClass( final String name) throws ClassNotFoundException;\n private Class<?> tryLoadClass( final ClassLoader classLoader, final String name);\n public OServer startup() throws OConfigurationException;\n public OServer startup( final File iConfigurationFile) throws OConfigurationException;\n public OServer startup( final String iConfiguration) throws IOException;\n public OServer startup( final InputStream iInputStream) throws IOException;\n public OServer startup( final OServerConfiguration iConfiguration) throws IllegalArgumentException, SecurityException, IOException;\n public OServer startupFromConfiguration() throws IOException;\n public OServer activate() throws ClassNotFoundException, InstantiationException, IllegalAccessException;\n public void removeShutdownHook();\n public boolean shutdown();\n protected boolean deinit();\n public boolean rejectRequests();\n public void waitForShutdown();\n public Map<String,String> getAvailableStorageNames();\n protected void loadDatabases();\n private boolean askForEncryptionKey( final String iDatabaseName);\n public String getDatabaseDirectory();\n public ThreadGroup getServerThreadGroup();\n public boolean authenticate( final String iUserName, final String iPassword, final String iResourceToCheck);\n public OSecurityUser authenticateUser( final String iUserName, final String iPassword, final String iResourceToCheck);\n public boolean existsStoragePath( final String iURL);\n public OServerConfiguration getConfiguration();\n public Map<String,Class<? extends ONetworkProtocol>> getNetworkProtocols();\n public List<OServerNetworkListener> getNetworkListeners();\n public <RET extends OServerNetworkListener>RET getListenerByProtocol( final Class<? extends ONetworkProtocol> iProtocolClass);\n public Collection<OServerPluginInfo> getPlugins();\n public OContextConfiguration getContextConfiguration();\n public <RET extends OServerPlugin>RET getPluginByClass( final Class<RET> iPluginClass);\n public <RET extends OServerPlugin>RET getPlugin( final String iName);\n public Object getVariable( final String iName);\n public OServer setVariable( final String iName, final Object iValue);\n public void addTemporaryUser( final String iName, final String iPassword, final String iPermissions);\n public OServer registerLifecycleListener( final OServerLifecycleListener iListener);\n public OServer unregisterLifecycleListener( final OServerLifecycleListener iListener);\n public ODatabaseDocumentInternal openDatabase( final String iDbUrl, final OParsedToken iToken);\n public ODatabaseDocumentInternal openDatabase( final String iDbUrl, final String user, final String password);\n public ODatabaseDocumentInternal openDatabase( final String iDbUrl, final String user, final String password, ONetworkProtocolData data);\n public ODatabaseDocumentInternal openDatabase( String database);\n public ODistributedServerManager getDistributedManager();\n public void setServerRootDirectory( final String rootDirectory);\n protected void initFromConfiguration();\n public OConfigurableHooksManager getHookManager();\n protected void loadUsers() throws IOException;\n protected void loadStorages();\n protected void createDefaultServerUsers() throws IOException;\n private boolean existsSystemUser( String user);\n public OServerPluginManager getPluginManager();\n protected void registerPlugins() throws InstantiationException, IllegalAccessException, ClassNotFoundException;\n protected void defaultSettings();\n public OTokenHandler getTokenHandler();\n public ThreadGroup getThreadGroup();\n private void initSystemDatabase();\n public OrientDBInternal getDatabases();\n public OrientDB getContext();\n public void dropDatabase( String databaseName);\n public boolean existsDatabase( String databaseName);\n public void createDatabase( String databaseName, ODatabaseType type, OrientDBConfig config);\n public Set<String> listDatabases();\n public void restore( String name, String path);\n public Date getStartedOn();\n}\n"}}, {"ORemoteTask": {"retrieved_name": "ORemoteTask", "raw_body": "/** \n * Remote Task interface.\n * @author Luca Garulli (l.garulli--(at)--orientdb.com)\n */\npublic interface ORemoteTask {\n boolean hasResponse();\n default void received( ODistributedRequest request, ODistributedDatabase distributedDatabase);\n enum RESULT_STRATEGY { ANY, UNION}\n String getName();\n OCommandDistributedReplicateRequest.QUORUM_TYPE getQuorumType();\n Object execute( ODistributedRequestId requestId, OServer iServer, ODistributedServerManager iManager, ODatabaseDocumentInternal database) throws Exception ;\n long getDistributedTimeout();\n long getSynchronousTimeout( final int iSynchNodes);\n long getTotalTimeout( final int iTotalNodes);\n OAbstractRemoteTask.RESULT_STRATEGY getResultStrategy();\n String getNodeSource();\n void setNodeSource( String nodeSource);\n boolean isIdempotent();\n boolean isNodeOnlineRequired();\n boolean isUsingDatabase();\n int getFactoryId();\n void toStream( DataOutput out) throws IOException ;\n void fromStream( DataInput in, ORemoteTaskFactory factory) throws IOException ;\n default void finished( ODistributedDatabase distributedDatabase);\n}\n", "raw_body_no_cmt": "public interface ORemoteTask {\n boolean hasResponse();\n default void received( ODistributedRequest request, ODistributedDatabase distributedDatabase);\n enum RESULT_STRATEGY { ANY, UNION}\n String getName();\n OCommandDistributedReplicateRequest.QUORUM_TYPE getQuorumType();\n Object execute( ODistributedRequestId requestId, OServer iServer, ODistributedServerManager iManager, ODatabaseDocumentInternal database) throws Exception ;\n long getDistributedTimeout();\n long getSynchronousTimeout( final int iSynchNodes);\n long getTotalTimeout( final int iTotalNodes);\n OAbstractRemoteTask.RESULT_STRATEGY getResultStrategy();\n String getNodeSource();\n void setNodeSource( String nodeSource);\n boolean isIdempotent();\n boolean isNodeOnlineRequired();\n boolean isUsingDatabase();\n int getFactoryId();\n void toStream( DataOutput out) throws IOException ;\n void fromStream( DataInput in, ORemoteTaskFactory factory) throws IOException ;\n default void finished( ODistributedDatabase distributedDatabase);\n}\n"}}, {"ODistributedRequestId": {"retrieved_name": "ODistributedRequestId", "raw_body": "/** \n * Immutable object representing the distributed request id.\n * @author Luca Garulli (l.garulli--(at)--orientdb.com)\n */\npublic class ODistributedRequestId implements Comparable, OStreamable, Externalizable {\n private int nodeId;\n private long messageId;\n public ODistributedRequestId();\n public ODistributedRequestId( final int iNodeId, final long iMessageId);\n public long getMessageId();\n public int getNodeId();\n @Override public boolean equals( final Object obj);\n @Override public int compareTo( final Object obj);\n @Override public int hashCode();\n public void toStream( final DataOutput out) throws IOException;\n public void fromStream( final DataInput in) throws IOException;\n @Override public void writeExternal( final ObjectOutput out) throws IOException;\n @Override public void readExternal( final ObjectInput in) throws IOException, ClassNotFoundException;\n @Override public String toString();\n}\n", "raw_body_no_cmt": "public class ODistributedRequestId implements Comparable, OStreamable, Externalizable {\n private int nodeId;\n private long messageId;\n public ODistributedRequestId();\n public ODistributedRequestId( final int iNodeId, final long iMessageId);\n public long getMessageId();\n public int getNodeId();\n public boolean equals( final Object obj);\n public int compareTo( final Object obj);\n public int hashCode();\n public void toStream( final DataOutput out) throws IOException;\n public void fromStream( final DataInput in) throws IOException;\n public void writeExternal( final ObjectOutput out) throws IOException;\n public void readExternal( final ObjectInput in) throws IOException, ClassNotFoundException;\n public String toString();\n}\n"}}, {"ODistributedServerManager": {"retrieved_name": "ODistributedServerManager", "raw_body": "/** \n * Server cluster interface to abstract cluster behavior.\n * @author Luca Garulli (l.garulli--at--orientdb.com)\n */\npublic interface ODistributedServerManager {\n String FILE_DISTRIBUTED_DB_CONFIG=\"distributed-config.json\";\n /** \n * Server status. \n */\n enum NODE_STATUS { /** \n * The server was never started or the shutdown is complete. \n */\n OFFLINE, /** \n * The server is STARTING. \n */\n STARTING, /** \n * The server is ONLINE. \n */\n ONLINE, /** \n * The server starts to merge to another cluster. \n */\n MERGING, /** \n * The server is shutting down. \n */\n SHUTTINGDOWN}\n /** \n * Database status. \n */\n enum DB_STATUS { /** \n * The database is not installed. In this status the server does not receive any request. \n */\n NOT_AVAILABLE, /** \n * The database has been put in OFFLINE status. In this status the server does not receive any request.\n */\n OFFLINE, /** \n * The database is in synchronization status. This status is set when a synchronization (full or delta) is requested. The node tha accepts the synchronization, is in SYNCHRONIZING mode too. During this status the server receive requests that will be enqueue until the database is ready. Server in SYNCHRONIZING status do not concur in the quorum.\n */\n SYNCHRONIZING, /** \n * The database is ONLINE as fully operative. During this status the server is considered in the quorum (if the server's role is MASTER)\n */\n ONLINE, /** \n * The database is ONLINE, but is not involved in the quorum. \n */\n BACKUP}\n /** \n * Checks the node status if it's one of the statuses received as argument.\n * @param iNodeName Node name\n * @param iDatabaseName Database name\n * @param statuses vararg of statuses\n * @return true if the node's status is equals to one of the passed statuses, otherwise false\n */\n boolean isNodeStatusEqualsTo( String iNodeName, String iDatabaseName, DB_STATUS... statuses);\n boolean isNodeAvailable( String iNodeName);\n Set<String> getAvailableNodeNames( String databaseName);\n Set<String> getAvailableNodeNotLocalNames( String databaseName);\n @Deprecated String getCoordinatorServer();\n void waitUntilNodeOnline() throws InterruptedException ;\n void waitUntilNodeOnline( String nodeName, String databaseName) throws InterruptedException ;\n OServer getServerInstance();\n boolean isEnabled();\n ODistributedServerManager registerLifecycleListener( ODistributedLifecycleListener iListener);\n ODistributedServerManager unregisterLifecycleListener( ODistributedLifecycleListener iListener);\n Object executeOnLocalNode( ODistributedRequestId reqId, ORemoteTask task, ODatabaseDocumentInternal database);\n void executeOnLocalNodeFromRemote( ODistributedRequest request);\n ORemoteServerController getRemoteServer( String nodeName) throws IOException ;\n long getLastClusterChangeOn();\n NODE_STATUS getNodeStatus();\n void setNodeStatus( NODE_STATUS iStatus);\n boolean checkNodeStatus( NODE_STATUS status);\n void removeServer( String nodeLeftName, boolean removeOnlyDynamicServers);\n DB_STATUS getDatabaseStatus( String iNode, String iDatabaseName);\n void setDatabaseStatus( String iNode, String iDatabaseName, DB_STATUS iStatus);\n int getNodesWithStatus( Collection<String> iNodes, String databaseName, DB_STATUS... statuses);\n ODistributedMessageService getMessageService();\n ODistributedDatabase getDatabase( String name);\n ODistributedStrategy getDistributedStrategy();\n void setDistributedStrategy( ODistributedStrategy streatgy);\n boolean updateCachedDatabaseConfiguration( String iDatabaseName, OModifiableDistributedConfiguration cfg);\n void publishDistributedConfiguration( String iDatabaseName, ODistributedConfiguration cfg);\n long getNextMessageIdCounter();\n String getNodeUuidByName( String name);\n void updateLastClusterChange();\n void reassignClustersOwnership( String iNode, String databaseName, OModifiableDistributedConfiguration cfg, boolean canCreateNewClusters);\n /** \n * Available means not OFFLINE, so ONLINE or SYNCHRONIZING. \n */\n boolean isNodeAvailable( String iNodeName, String databaseName);\n /** \n * Returns true if the node status is ONLINE. \n */\n boolean isNodeOnline( String iNodeName, String databaseName);\n int getTotalNodes( String iDatabaseName);\n int getAvailableNodes( String iDatabaseName);\n int getAvailableNodes( Collection<String> iNodes, String databaseName);\n boolean isOffline();\n int getLocalNodeId();\n String getLocalNodeName();\n ODocument getClusterConfiguration();\n String getNodeNameById( int id);\n int getNodeIdByName( String node);\n ODocument getNodeConfigurationByUuid( String iNode, boolean useCache);\n ODocument getLocalNodeConfiguration();\n ODistributedConfiguration getDatabaseConfiguration( String iDatabaseName);\n /** \n * Sends a distributed request against multiple servers.\n * @param iDatabaseName\n * @param iTargetNodeNames\n * @param iTask\n * @return\n */\n ODistributedResponse sendRequest( String iDatabaseName, Collection<String> iTargetNodeNames, ORemoteTask iTask);\n /** \n * Sends a distributed request against multiple servers.\n * @param iDatabaseName\n * @param node\n * @param iTask\n * @return\n */\n ODistributedResponse sendSingleRequest( String iDatabaseName, String node, ORemoteTask iTask);\n ODistributedResponse sendRequest( String iDatabaseName, Collection<String> iTargetNodeNames, ORemoteTask iTask, long messageId, Object localResult, ODistributedResponseManagerFactory responseManagerFactory);\n ODocument getStats();\n Throwable convertException( Throwable original);\n List<String> getOnlineNodes( String iDatabaseName);\n List<String> getOnlineNodesNotLocal( String iDatabaseName);\n boolean installDatabase( boolean iStartup, String databaseName, boolean forceDeployment, boolean tryWithDeltaFirst);\n /** \n * Returns the task factory manager. During first connect the minor version of the protocol is used.\n */\n ORemoteTaskFactoryManager getTaskFactoryManager();\n Set<String> getActiveServers();\n Set<String> getActiveServerNotLocal();\n /** \n * Returns the cluster-wide time in milliseconds. <p>Cluster tries to keep a cluster-wide time which might be different than the member's own system time. Cluster-wide time is -almost- the same on all members of the cluster.\n */\n long getClusterTime();\n File getDefaultDatabaseConfigFile();\n ODistributedLockManager getLockManagerRequester();\n ODistributedLockManager getLockManagerExecutor();\n /** \n * Executes an operation protected by a distributed lock (one per database).\n * @param < T > Return type\n * @param databaseName Database name\n * @param timeoutLocking\n * @param iCallback Operation @return The operation's result of type T\n */\n <T>T executeInDistributedDatabaseLock( String databaseName, long timeoutLocking, OModifiableDistributedConfiguration lastCfg, OCallable<T,OModifiableDistributedConfiguration> iCallback);\n /** \n * Returns true if the quorum is present in terms of number of available nodes for full replication only. With sharding, instead, the quorum may depend on the involved clusters.\n * @return\n */\n boolean isWriteQuorumPresent( String databaseName);\n void notifyClients( String databaseName);\n default void messageReceived( ODistributedRequest request);\n default void messagePartitionCalculate( ODistributedRequest request, Set<Integer> involvedWorkerQueues);\n default void messageBeforeOp( String op, ODistributedRequestId requestId);\n default void messageAfterOp( String op, ODistributedRequestId requestId);\n default void messageCurrentPayload( ODistributedRequestId requestId, Object responsePayload);\n default void messageProcessStart( ODistributedRequest message);\n default void messageProcessEnd( ODistributedRequest iRequest, Object responsePayload);\n ODocument getOnlineDatabaseConfiguration( String databaseName);\n}\n", "raw_body_no_cmt": "public interface ODistributedServerManager {\n String FILE_DISTRIBUTED_DB_CONFIG=\"distributed-config.json\";\n enum NODE_STATUS { /** \n * The server was never started or the shutdown is complete. \n */\n OFFLINE, /** \n * The server is STARTING. \n */\n STARTING, /** \n * The server is ONLINE. \n */\n ONLINE, /** \n * The server starts to merge to another cluster. \n */\n MERGING, /** \n * The server is shutting down. \n */\n SHUTTINGDOWN}\n enum DB_STATUS { /** \n * The database is not installed. In this status the server does not receive any request. \n */\n NOT_AVAILABLE, /** \n * The database has been put in OFFLINE status. In this status the server does not receive any request.\n */\n OFFLINE, /** \n * The database is in synchronization status. This status is set when a synchronization (full or delta) is requested. The node tha accepts the synchronization, is in SYNCHRONIZING mode too. During this status the server receive requests that will be enqueue until the database is ready. Server in SYNCHRONIZING status do not concur in the quorum.\n */\n SYNCHRONIZING, /** \n * The database is ONLINE as fully operative. During this status the server is considered in the quorum (if the server's role is MASTER)\n */\n ONLINE, /** \n * The database is ONLINE, but is not involved in the quorum. \n */\n BACKUP}\n boolean isNodeStatusEqualsTo( String iNodeName, String iDatabaseName, DB_STATUS... statuses);\n boolean isNodeAvailable( String iNodeName);\n Set<String> getAvailableNodeNames( String databaseName);\n Set<String> getAvailableNodeNotLocalNames( String databaseName);\n String getCoordinatorServer();\n void waitUntilNodeOnline() throws InterruptedException ;\n void waitUntilNodeOnline( String nodeName, String databaseName) throws InterruptedException ;\n OServer getServerInstance();\n boolean isEnabled();\n ODistributedServerManager registerLifecycleListener( ODistributedLifecycleListener iListener);\n ODistributedServerManager unregisterLifecycleListener( ODistributedLifecycleListener iListener);\n Object executeOnLocalNode( ODistributedRequestId reqId, ORemoteTask task, ODatabaseDocumentInternal database);\n void executeOnLocalNodeFromRemote( ODistributedRequest request);\n ORemoteServerController getRemoteServer( String nodeName) throws IOException ;\n long getLastClusterChangeOn();\n NODE_STATUS getNodeStatus();\n void setNodeStatus( NODE_STATUS iStatus);\n boolean checkNodeStatus( NODE_STATUS status);\n void removeServer( String nodeLeftName, boolean removeOnlyDynamicServers);\n DB_STATUS getDatabaseStatus( String iNode, String iDatabaseName);\n void setDatabaseStatus( String iNode, String iDatabaseName, DB_STATUS iStatus);\n int getNodesWithStatus( Collection<String> iNodes, String databaseName, DB_STATUS... statuses);\n ODistributedMessageService getMessageService();\n ODistributedDatabase getDatabase( String name);\n ODistributedStrategy getDistributedStrategy();\n void setDistributedStrategy( ODistributedStrategy streatgy);\n boolean updateCachedDatabaseConfiguration( String iDatabaseName, OModifiableDistributedConfiguration cfg);\n void publishDistributedConfiguration( String iDatabaseName, ODistributedConfiguration cfg);\n long getNextMessageIdCounter();\n String getNodeUuidByName( String name);\n void updateLastClusterChange();\n void reassignClustersOwnership( String iNode, String databaseName, OModifiableDistributedConfiguration cfg, boolean canCreateNewClusters);\n boolean isNodeAvailable( String iNodeName, String databaseName);\n boolean isNodeOnline( String iNodeName, String databaseName);\n int getTotalNodes( String iDatabaseName);\n int getAvailableNodes( String iDatabaseName);\n int getAvailableNodes( Collection<String> iNodes, String databaseName);\n boolean isOffline();\n int getLocalNodeId();\n String getLocalNodeName();\n ODocument getClusterConfiguration();\n String getNodeNameById( int id);\n int getNodeIdByName( String node);\n ODocument getNodeConfigurationByUuid( String iNode, boolean useCache);\n ODocument getLocalNodeConfiguration();\n ODistributedConfiguration getDatabaseConfiguration( String iDatabaseName);\n ODistributedResponse sendRequest( String iDatabaseName, Collection<String> iTargetNodeNames, ORemoteTask iTask);\n ODistributedResponse sendSingleRequest( String iDatabaseName, String node, ORemoteTask iTask);\n ODistributedResponse sendRequest( String iDatabaseName, Collection<String> iTargetNodeNames, ORemoteTask iTask, long messageId, Object localResult, ODistributedResponseManagerFactory responseManagerFactory);\n ODocument getStats();\n Throwable convertException( Throwable original);\n List<String> getOnlineNodes( String iDatabaseName);\n List<String> getOnlineNodesNotLocal( String iDatabaseName);\n boolean installDatabase( boolean iStartup, String databaseName, boolean forceDeployment, boolean tryWithDeltaFirst);\n ORemoteTaskFactoryManager getTaskFactoryManager();\n Set<String> getActiveServers();\n Set<String> getActiveServerNotLocal();\n long getClusterTime();\n File getDefaultDatabaseConfigFile();\n ODistributedLockManager getLockManagerRequester();\n ODistributedLockManager getLockManagerExecutor();\n <T>T executeInDistributedDatabaseLock( String databaseName, long timeoutLocking, OModifiableDistributedConfiguration lastCfg, OCallable<T,OModifiableDistributedConfiguration> iCallback);\n boolean isWriteQuorumPresent( String databaseName);\n void notifyClients( String databaseName);\n default void messageReceived( ODistributedRequest request);\n default void messagePartitionCalculate( ODistributedRequest request, Set<Integer> involvedWorkerQueues);\n default void messageBeforeOp( String op, ODistributedRequestId requestId);\n default void messageAfterOp( String op, ODistributedRequestId requestId);\n default void messageCurrentPayload( ODistributedRequestId requestId, Object responsePayload);\n default void messageProcessStart( ODistributedRequest message);\n default void messageProcessEnd( ODistributedRequest iRequest, Object responsePayload);\n ODocument getOnlineDatabaseConfiguration( String databaseName);\n}\n"}}] | [{"countDown": {"retrieved_name": "tearDown", "raw_body": "@After public void tearDown() throws Exception {\n graph.shutdown();\n}\n"}}, {"execute": {"retrieved_name": "execute", "raw_body": "@Override public OBinaryResponse execute(OBinaryRequestExecutor executor){\n return executor.executeReadRecord(this);\n}\n"}}, {"release": {"retrieved_name": "release", "raw_body": "/** \n * Allows to execute write-related commands on DB. Called after {@link #freeze()} command.\n * @see #freeze()\n */\nvoid release();\n"}}] | [{"execute": {"retrieved_name": "execute", "raw_body": "/** \n * Execute a script in a specified query language. The result set has to be closed after usage <br> <br> Sample usage: <p><code> String script = \"INSERT INTO Person SET name = 'foo', surname = ?;\"+ \"INSERT INTO Person SET name = 'bar', surname = ?;\"+ \"INSERT INTO Person SET name = 'baz', surname = ?;\"; <p> OResultSet rs = db.execute(\"sql\", script, \"Surname1\", \"Surname2\", \"Surname3\"); ... rs.close(); </code>\n * @param language\n * @param script\n * @param args\n * @return\n */\ndefault OResultSet execute(String language,String script,Object... args) throws OCommandExecutionException, OCommandScriptException {\n throw new UnsupportedOperationException();\n}\n"}}] |
google_truth | truth/core/src/main/java/com/google/common/truth/LazyMessage.java | LazyMessage | evaluateAll | class LazyMessage {
private final String format;
private final @Nullable Object[] args;
LazyMessage(String format, @Nullable Object... args) {
this.format = format;
this.args = args;
int placeholders = countPlaceholders(format);
checkArgument(
placeholders == args.length,
"Incorrect number of args (%s) for the given placeholders (%s) in string template:\"%s\"",
args.length,
placeholders,
format);
}
@Override
public String toString() {
return lenientFormat(format, args);
}
@VisibleForTesting
static int countPlaceholders(String template) {
int index = 0;
int count = 0;
while (true) {
index = template.indexOf("%s", index);
if (index == -1) {
break;
}
index++;
count++;
}
return count;
}
static ImmutableList<String> evaluateAll(ImmutableList<LazyMessage> messages) {<FILL_FUNCTION_BODY>}
} |
ImmutableList.Builder<String> result = ImmutableList.builder();
for (LazyMessage message : messages) {
result.add(message.toString());
}
return result.build();
|
ImmutableList.Builder<String> builder = ImmutableList.builder();
for (LazyMessage message : messages) {
builder.add(message.toString());
}
return builder.build();
| [
"ImmutableList.Builder<String>",
"LazyMessage",
"ImmutableList<LazyMessage>"
] | [
"toString",
"add",
"builder",
"build"
] | [
"ImmutableList<LazyMessage>",
"ImmutableList.Builder<String>",
"LazyMessage"
] | [
"add",
"builder",
"build",
"toString"
] | {
"methods": [
"toString",
"add",
"builder",
"build"
],
"similar_methods": [
"evaluateAll"
],
"types": [
"ImmutableList.Builder<String>",
"LazyMessage",
"ImmutableList<LazyMessage>"
]
} | /**
* Propositions for {@link Iterable} subjects.<p><b>Note:</b> <ul> <li>Assertions may iterate through the given {@link Iterable} more than once. If you have anunusual implementation of {@link Iterable} which does not support multiple iterations(sometimes known as a "one-shot iterable"), you must copy your iterable into a collection which does (e.g. {@code ImmutableList.copyOf(iterable)} or, if your iterable may containnull, {@code newArrayList(iterable)}). If you don't, you may see surprising failures. <li>Assertions may also require that the elements in the given {@link Iterable} implement{@link Object#hashCode} correctly.</ul>
* @author Kurt Alfred Kluever
* @author Pete Gillin
*/
public class IterableSubject extends Subject {
private final @Nullable Iterable<?> actual;
/**
* Constructor for use by subclasses. If you want to create an instance of this class itself, call {@link Subject#check(String,Object...) check(...)}{@code .that(actual)}.
*/
protected IterableSubject( FailureMetadata metadata, @Nullable Iterable<?> iterable);
/**
* Constructor for use by package-private callers.
*/
IterableSubject( FailureMetadata metadata, @Nullable Iterable<?> iterable, @Nullable String typeDescriptionOverride);
@Override protected String actualCustomStringRepresentation();
@Override public void isEqualTo( @Nullable Object expected);
/**
* Fails if the subject is not empty.
*/
public final void isEmpty();
/**
* Fails if the subject is empty.
*/
public final void isNotEmpty();
/**
* Fails if the subject does not have the given size.
*/
public final void hasSize( int expectedSize);
/**
* Checks (with a side-effect failure) that the subject contains the supplied item.
*/
public final void contains( @Nullable Object element);
/**
* Checks (with a side-effect failure) that the subject does not contain the supplied item.
*/
public final void doesNotContain( @Nullable Object element);
/**
* Checks that the subject does not contain duplicate elements.
*/
public final void containsNoDuplicates();
/**
* Checks that the subject contains at least one of the provided objects or fails.
*/
public final void containsAnyOf( @Nullable Object first, @Nullable Object second, @Nullable Object @Nullable ... rest);
/**
* Checks that the subject contains at least one of the objects contained in the provided collection or fails.
*/
public final void containsAnyIn( @Nullable Iterable<?> expected);
/**
* Checks that the subject contains at least one of the objects contained in the provided array or fails.
*/
@SuppressWarnings("AvoidObjectArrays") public final void containsAnyIn( @Nullable Object[] expected);
/**
* Checks that the actual iterable contains at least all of the expected elements or fails. If an element appears more than once in the expected elements to this call then it must appear at least that number of times in the actual elements. <p>To also test that the contents appear in the given order, make a call to {@code inOrder()}on the object returned by this method. The expected elements must appear in the given order within the actual elements, but they are not required to be consecutive.
*/
@CanIgnoreReturnValue public final Ordered containsAtLeast( @Nullable Object firstExpected, @Nullable Object secondExpected, @Nullable Object @Nullable ... restOfExpected);
/**
* Checks that the actual iterable contains at least all of the expected elements or fails. If an element appears more than once in the expected elements then it must appear at least that number of times in the actual elements. <p>To also test that the contents appear in the given order, make a call to {@code inOrder()}on the object returned by this method. The expected elements must appear in the given order within the actual elements, but they are not required to be consecutive.
*/
@CanIgnoreReturnValue public final Ordered containsAtLeastElementsIn( Iterable<?> expectedIterable);
/**
* Checks that the actual iterable contains at least all of the expected elements or fails. If an element appears more than once in the expected elements then it must appear at least that number of times in the actual elements. <p>To also test that the contents appear in the given order, make a call to {@code inOrder()}on the object returned by this method. The expected elements must appear in the given order within the actual elements, but they are not required to be consecutive.
*/
@CanIgnoreReturnValue @SuppressWarnings("AvoidObjectArrays") public final Ordered containsAtLeastElementsIn( @Nullable Object[] expected);
private Ordered failAtLeast( Collection<?> expected, Collection<?> missingRawObjects);
/**
* Removes at most the given number of available elements from the input list and adds them to the given output collection.
*/
private static void moveElements( List<?> input, Collection<@Nullable Object> output, int maxElements);
/**
* Checks that a subject contains exactly the provided objects or fails. <p>Multiplicity is respected. For example, an object duplicated exactly 3 times in the parameters asserts that the object must likewise be duplicated exactly 3 times in the subject. <p>To also test that the contents appear in the given order, make a call to {@code inOrder()}on the object returned by this method. <p>To test that the iterable contains the same elements as an array, prefer {@link #containsExactlyElementsIn(Object[])}. It makes clear that the given array is a list of elements, not an element itself. This helps human readers and avoids a compiler warning.
*/
@CanIgnoreReturnValue public final Ordered containsExactly( @Nullable Object @Nullable ... varargs);
/**
* Checks that a subject contains exactly the provided objects or fails. <p>Multiplicity is respected. For example, an object duplicated exactly 3 times in the {@code Iterable} parameter asserts that the object must likewise be duplicated exactly 3 times in thesubject. <p>To also test that the contents appear in the given order, make a call to {@code inOrder()}on the object returned by this method.
*/
@CanIgnoreReturnValue public final Ordered containsExactlyElementsIn( @Nullable Iterable<?> expected);
/**
* Checks that a subject contains exactly the provided objects or fails. <p>Multiplicity is respected. For example, an object duplicated exactly 3 times in the array parameter asserts that the object must likewise be duplicated exactly 3 times in the subject. <p>To also test that the contents appear in the given order, make a call to {@code inOrder()}on the object returned by this method.
*/
@CanIgnoreReturnValue @SuppressWarnings({"AvoidObjectArrays","ContainsExactlyElementsInUnnecessaryWrapperAroundArray","ContainsExactlyElementsInWithVarArgsToExactly"}) public final Ordered containsExactlyElementsIn( @Nullable Object @Nullable [] expected);
private Ordered containsExactlyElementsIn( @Nullable Iterable<?> required, boolean addElementsInWarning);
private Ordered failExactly( Iterable<?> required, boolean addElementsInWarning, Collection<?> missingRawObjects, Collection<?> extraRawObjects);
private static ImmutableList<Fact> makeElementFactsForBoth( String firstKey, Collection<?> firstCollection, String secondKey, Collection<?> secondCollection);
/**
* Returns a list of facts (zero, one, or many, depending on the number of elements and the grouping policy) describing the given missing, unexpected, or near-miss elements.
*/
private static ImmutableList<Fact> makeElementFacts( String label, DuplicateGroupedAndTyped elements, ElementFactGrouping grouping);
private static String keyToGoWithElementsString( String label, DuplicateGroupedAndTyped elements);
private static String keyToServeAsHeader( String label, DuplicateGroupedAndTyped elements);
private static String numberString( int n, int count);
private static ElementFactGrouping pickGrouping( Iterable<Multiset.Entry<?>> first, Iterable<Multiset.Entry<?>> second);
private static boolean anyContainsCommaOrNewline( Iterable<Multiset.Entry<?>>... lists);
private static boolean hasMultiple( Iterable<Multiset.Entry<?>> entries);
private static boolean containsEmptyOrLong( Iterable<Multiset.Entry<?>> entries);
/**
* Whether to output each missing/unexpected item as its own {@link Fact} or to group all thoseitems together into a single {@code Fact}.
*/
enum ElementFactGrouping { ALL_IN_ONE_FACT, FACT_PER_ELEMENT}
/**
* Checks that a actual iterable contains none of the excluded objects or fails. (Duplicates are irrelevant to this test, which fails if any of the actual elements equal any of the excluded.)
*/
public final void containsNoneOf( @Nullable Object firstExcluded, @Nullable Object secondExcluded, @Nullable Object @Nullable ... restOfExcluded);
/**
* Checks that the actual iterable contains none of the elements contained in the excluded iterable or fails. (Duplicates are irrelevant to this test, which fails if any of the actual elements equal any of the excluded.)
*/
public final void containsNoneIn( Iterable<?> excluded);
/**
* Checks that the actual iterable contains none of the elements contained in the excluded array or fails. (Duplicates are irrelevant to this test, which fails if any of the actual elements equal any of the excluded.)
*/
@SuppressWarnings("AvoidObjectArrays") public final void containsNoneIn( @Nullable Object[] excluded);
/**
* Ordered implementation that does nothing because it's already known to be true.
*/
private static final Ordered IN_ORDER=() -> {
}
;
/**
* Ordered implementation that does nothing because an earlier check already caused a failure.
*/
private static final Ordered ALREADY_FAILED=() -> {
}
;
/**
* Fails if the iterable is not strictly ordered, according to the natural ordering of its elements. Strictly ordered means that each element in the iterable is <i>strictly</i> greater than the element that preceded it.
* @throws ClassCastException if any pair of elements is not mutually Comparable
* @throws NullPointerException if any element is null
*/
public void isInStrictOrder();
/**
* Fails if the iterable is not strictly ordered, according to the given comparator. Strictly ordered means that each element in the iterable is <i>strictly</i> greater than the element that preceded it.
* @throws ClassCastException if any pair of elements is not mutually Comparable
*/
@SuppressWarnings({"unchecked"}) public final void isInStrictOrder( Comparator<?> comparator);
/**
* Fails if the iterable is not ordered, according to the natural ordering of its elements. Ordered means that each element in the iterable is greater than or equal to the element that preceded it.
* @throws ClassCastException if any pair of elements is not mutually Comparable
* @throws NullPointerException if any element is null
*/
public void isInOrder();
/**
* Fails if the iterable is not ordered, according to the given comparator. Ordered means that each element in the iterable is greater than or equal to the element that preceded it.
* @throws ClassCastException if any pair of elements is not mutually Comparable
*/
@SuppressWarnings({"unchecked"}) public final void isInOrder( Comparator<?> comparator);
private interface PairwiseChecker {
boolean check( @Nullable Object prev, @Nullable Object next);
}
private void pairwiseCheck( String expectedFact, PairwiseChecker checker);
/**
* @deprecated You probably meant to call {@link #containsNoneOf} instead.
*/
@Override @Deprecated public void isNoneOf( @Nullable Object first, @Nullable Object second, @Nullable Object @Nullable ... rest);
/**
* @deprecated You probably meant to call {@link #containsNoneIn} instead.
*/
@Override @Deprecated public void isNotIn( @Nullable Iterable<?> iterable);
private Fact fullContents();
/**
* Starts a method chain for a check in which the actual elements (i.e. the elements of the {@link Iterable} under test) are compared to expected elements using the given {@link Correspondence}. The actual elements must be of type {@code A}, the expected elements must be of type {@code E}. The check is actually executed by continuing the method chain. For example: <pre> {@code assertThat(actualIterable).comparingElementsUsing(correspondence).contains(expected);}</pre> where {@code actualIterable} is an {@code Iterable<A>} (or, more generally, an {@code Iterable<? extends A>}), {@code correspondence} is a {@code Correspondence<A, E>}, and {@code expected} is an {@code E}. <p>Any of the methods on the returned object may throw {@link ClassCastException} if theyencounter an actual element that is not of type {@code A}.
*/
public <A extends @Nullable Object,E extends @Nullable Object>UsingCorrespondence<A,E> comparingElementsUsing( Correspondence<? super A,? super E> correspondence);
/**
* Starts a method chain for a check in which failure messages may use the given {@link DiffFormatter} to describe the difference between an actual elements (i.e. an element of the{@link Iterable} under test) and the element it is expected to be equal to, but isn't. Theactual and expected elements must be of type {@code T}. The check is actually executed by continuing the method chain. You may well want to use {@link UsingCorrespondence#displayingDiffsPairedBy} to specify how the elements should be paired upfor diffing. For example: <pre> {@code assertThat(actualFoos) .formattingDiffsUsing(FooTestHelper::formatDiff) .displayingDiffsPairedBy(Foo::getId) .containsExactly(foo1, foo2, foo3);}</pre> where {@code actualFoos} is an {@code Iterable<Foo>}, {@code FooTestHelper.formatDiff} is astatic method taking two {@code Foo} arguments and returning a {@link String}, {@code Foo.getId} is a no-arg instance method returning some kind of ID, and {@code foo1}, {code foo2}, and {@code foo3} are {@code Foo} instances.<p>Unlike when using {@link #comparingElementsUsing}, the elements are still compared using object equality, so this method does not affect whether a test passes or fails. <p>Any of the methods on the returned object may throw {@link ClassCastException} if theyencounter an actual element that is not of type {@code T}.
* @since 1.1
*/
public <T>UsingCorrespondence<T,T> formattingDiffsUsing( DiffFormatter<? super T,? super T> formatter);
/**
* A partially specified check in which the actual elements (normally the elements of the {@link Iterable} under test) are compared to expected elements using a {@link Correspondence}. The expected elements are of type {@code E}. Call methods on this object to actually execute the check.
*/
public static class UsingCorrespondence<A extends @Nullable Object,E extends @Nullable Object> {
private final IterableSubject subject;
private final Correspondence<? super A,? super E> correspondence;
private final Optional<Pairer> pairer;
UsingCorrespondence( IterableSubject subject, Correspondence<? super A,? super E> correspondence);
UsingCorrespondence( IterableSubject subject, Correspondence<? super A,? super E> correspondence, Pairer pairer);
/**
* @throws UnsupportedOperationException always
* @deprecated {@link Object#equals(Object)} is not supported on Truth subjects or intermediateclasses. If you are writing a test assertion (actual vs. expected), use methods liks {@link #containsExactlyElementsIn(Iterable)} instead.
*/
@DoNotCall("UsingCorrespondence.equals() is not supported. Did you mean to call" + " containsExactlyElementsIn(expected) instead of equals(expected)?") @Deprecated @Override public final boolean equals( @Nullable Object o);
/**
* @throws UnsupportedOperationException always
* @deprecated {@link Object#hashCode()} is not supported on Truth types.
*/
@DoNotCall("UsingCorrespondence.hashCode() is not supported.") @Deprecated @Override public final int hashCode();
/**
* @throws UnsupportedOperationException always
* @deprecated {@link Object#toString()} is not supported on Truth subjects.
*/
@Deprecated @DoNotCall("UsingCorrespondence.toString() is not supported.") @Override public final String toString();
/**
* Specifies a way to pair up unexpected and missing elements in the message when an assertion fails. For example: <pre> {@code assertThat(actualRecords) .comparingElementsUsing(RECORD_CORRESPONDENCE) .displayingDiffsPairedBy(MyRecord::getId) .containsExactlyElementsIn(expectedRecords);}</pre> <p><b>Important</b>: The {code keyFunction} function must be able to accept both the actual and the unexpected elements, i.e. it must satisfy {@code Function<? super A, ?>} as well as{@code Function<? super E, ?>}. If that constraint is not met then a subsequent method may throw {@link ClassCastException}. Use the two-parameter overload if you need to specify different key functions for the actual and expected elements. <p>On assertions where it makes sense to do so, the elements are paired as follows: they are keyed by {@code keyFunction}, and if an unexpected element and a missing element have the same non-null key then the they are paired up. (Elements with null keys are not paired.) The failure message will show paired elements together, and a diff will be shown if the {@link Correspondence#formatDiff} method returns non-null.<p>The expected elements given in the assertion should be uniquely keyed by {@code keyFunction}. If multiple missing elements have the same key then the pairing will be skipped. <p>Useful key functions will have the property that key equality is less strict than the correspondence, i.e. given {@code actual} and {@code expected} values with keys {@code actualKey} and {@code expectedKey}, if {@code correspondence.compare(actual, expected)} istrue then it is guaranteed that {@code actualKey} is equal to {@code expectedKey}, but there are cases where {@code actualKey} is equal to {@code expectedKey} but {@code correspondence.compare(actual, expected)} is false.<p>If the {@code apply} method on the key function throws an exception then the element willbe treated as if it had a null key and not paired. (The first such exception will be noted in the failure message.) <p>Note that calling this method makes no difference to whether a test passes or fails, it just improves the message if it fails.
*/
public UsingCorrespondence<A,E> displayingDiffsPairedBy( Function<? super E,?> keyFunction);
/**
* Specifies a way to pair up unexpected and missing elements in the message when an assertion fails. For example: <pre> {@code assertThat(actualFoos) .comparingElementsUsing(FOO_BAR_CORRESPONDENCE) .displayingDiffsPairedBy(Foo::getId, Bar::getFooId) .containsExactlyElementsIn(expectedBar);}</pre> <p>On assertions where it makes sense to do so, the elements are paired as follows: the unexpected elements are keyed by {@code actualKeyFunction}, the missing elements are keyed by {@code expectedKeyFunction}, and if an unexpected element and a missing element have the same non-null key then the they are paired up. (Elements with null keys are not paired.) The failure message will show paired elements together, and a diff will be shown if the {@link Correspondence#formatDiff} method returns non-null.<p>The expected elements given in the assertion should be uniquely keyed by {@code expectedKeyFunction}. If multiple missing elements have the same key then the pairing will be skipped. <p>Useful key functions will have the property that key equality is less strict than the correspondence, i.e. given {@code actual} and {@code expected} values with keys {@code actualKey} and {@code expectedKey}, if {@code correspondence.compare(actual, expected)} istrue then it is guaranteed that {@code actualKey} is equal to {@code expectedKey}, but there are cases where {@code actualKey} is equal to {@code expectedKey} but {@code correspondence.compare(actual, expected)} is false.<p>If the {@code apply} method on either of the key functions throws an exception then theelement will be treated as if it had a null key and not paired. (The first such exception will be noted in the failure message.) <p>Note that calling this method makes no difference to whether a test passes or fails, it just improves the message if it fails.
*/
public UsingCorrespondence<A,E> displayingDiffsPairedBy( Function<? super A,?> actualKeyFunction, Function<? super E,?> expectedKeyFunction);
/**
* Checks that the subject contains at least one element that corresponds to the given expected element.
*/
public void contains( E expected);
/**
* Checks that none of the actual elements correspond to the given element.
*/
public void doesNotContain( E excluded);
/**
* Checks that subject contains exactly elements that correspond to the expected elements, i.e. that there is a 1:1 mapping between the actual elements and the expected elements where each pair of elements correspond. <p>To also test that the contents appear in the given order, make a call to {@code inOrder()}on the object returned by this method. <p>To test that the iterable contains the elements corresponding to those in an array, prefer {@link #containsExactlyElementsIn(Object[])}. It makes clear that the given array is a list of elements, not an element itself. This helps human readers and avoids a compiler warning.
*/
@SafeVarargs @CanIgnoreReturnValue public final Ordered containsExactly( @Nullable E @Nullable ... expected);
/**
* Checks that subject contains exactly elements that correspond to the expected elements, i.e. that there is a 1:1 mapping between the actual elements and the expected elements where each pair of elements correspond. <p>To also test that the contents appear in the given order, make a call to {@code inOrder()}on the object returned by this method.
*/
@CanIgnoreReturnValue public Ordered containsExactlyElementsIn( @Nullable Iterable<? extends E> expected);
/**
* Checks that subject contains exactly elements that correspond to the expected elements, i.e. that there is a 1:1 mapping between the actual elements and the expected elements where each pair of elements correspond. <p>To also test that the contents appear in the given order, make a call to {@code inOrder()}on the object returned by this method.
*/
@CanIgnoreReturnValue @SuppressWarnings("AvoidObjectArrays") public Ordered containsExactlyElementsIn( E @Nullable [] expected);
/**
* Returns whether the actual and expected iterators have the same number of elements and, when iterated pairwise, every pair of actual and expected values satisfies the correspondence. Returns false if any comparison threw an exception.
*/
private boolean correspondInOrderExactly( Iterator<? extends A> actual, Iterator<? extends E> expected);
/**
* Given a list of actual elements and a list of expected elements, finds a many:many mapping between actual and expected elements where a pair of elements maps if it satisfies the correspondence. Returns this mapping as a multimap where the keys are indexes into the actual list and the values are indexes into the expected list. Any exceptions are treated as if the elements did not correspond, and the exception added to the store.
*/
private ImmutableSetMultimap<Integer,Integer> findCandidateMapping( List<? extends A> actual, List<? extends E> expected, Correspondence.ExceptionStore exceptions);
/**
* Given a list of actual elements, a list of expected elements, and a many:many mapping between actual and expected elements specified as a multimap of indexes into the actual list to indexes into the expected list, checks that every actual element maps to at least one expected element and vice versa, and fails if this is not the case. Returns whether the assertion failed.
*/
private boolean failIfCandidateMappingHasMissingOrExtra( List<? extends A> actual, List<? extends E> expected, ImmutableSetMultimap<Integer,Integer> mapping, Correspondence.ExceptionStore exceptions);
/**
* Given a list of missing elements and a list of extra elements, at least one of which must be non-empty, returns facts describing them. Exceptions from calling {@link Correspondence#formatDiff} are stored in {@code exceptions}.
*/
private ImmutableList<Fact> describeMissingOrExtra( List<? extends E> missing, List<? extends A> extra, Correspondence.ExceptionStore exceptions);
private ImmutableList<Fact> describeMissingOrExtraWithoutPairing( List<? extends E> missing, List<? extends A> extra);
private ImmutableList<Fact> describeMissingOrExtraWithPairing( Pairing pairing, Correspondence.ExceptionStore exceptions);
private ImmutableList<Fact> formatExtras( String label, E missing, List<? extends A> extras, Correspondence.ExceptionStore exceptions);
/**
* Returns all the elements of the given list other than those with the given indexes. Assumes that all the given indexes really are valid indexes into the list.
*/
private <T extends @Nullable Object>List<T> findNotIndexed( List<T> list, Set<Integer> indexes);
/**
* Given a many:many mapping between actual elements and expected elements, finds a 1:1 mapping which is the subset of that many:many mapping which includes the largest possible number of elements. The input and output mappings are each described as a map or multimap where the keys are indexes into the actual list and the values are indexes into the expected list. If there are multiple possible output mappings tying for the largest possible, this returns an arbitrary one.
*/
private ImmutableBiMap<Integer,Integer> findMaximalOneToOneMapping( ImmutableMultimap<Integer,Integer> edges);
/**
* Given a list of actual elements, a list of expected elements, and a 1:1 mapping between actual and expected elements specified as a bimap of indexes into the actual list to indexes into the expected list, checks that every actual element maps to an expected element and vice versa, and fails if this is not the case. Returns whether the assertion failed.
*/
private boolean failIfOneToOneMappingHasMissingOrExtra( List<? extends A> actual, List<? extends E> expected, BiMap<Integer,Integer> mapping, Correspondence.ExceptionStore exceptions);
/**
* Checks that the subject contains elements that corresponds to all of the expected elements, i.e. that there is a 1:1 mapping between any subset of the actual elements and the expected elements where each pair of elements correspond. <p>To also test that the contents appear in the given order, make a call to {@code inOrder()}on the object returned by this method. The elements must appear in the given order within the subject, but they are not required to be consecutive.
*/
@SafeVarargs @CanIgnoreReturnValue public final Ordered containsAtLeast( E first, E second, E @Nullable ... rest);
/**
* Checks that the subject contains elements that corresponds to all of the expected elements, i.e. that there is a 1:1 mapping between any subset of the actual elements and the expected elements where each pair of elements correspond. <p>To also test that the contents appear in the given order, make a call to {@code inOrder()}on the object returned by this method. The elements must appear in the given order within the subject, but they are not required to be consecutive.
*/
@CanIgnoreReturnValue public Ordered containsAtLeastElementsIn( Iterable<? extends E> expected);
/**
* Checks that the subject contains elements that corresponds to all of the expected elements, i.e. that there is a 1:1 mapping between any subset of the actual elements and the expected elements where each pair of elements correspond. <p>To also test that the contents appear in the given order, make a call to {@code inOrder()}on the object returned by this method. The elements must appear in the given order within the subject, but they are not required to be consecutive.
*/
@CanIgnoreReturnValue @SuppressWarnings("AvoidObjectArrays") public Ordered containsAtLeastElementsIn( E[] expected);
/**
* Returns whether all the elements of the expected iterator and any subset of the elements of the actual iterator can be paired up in order, such that every pair of actual and expected elements satisfies the correspondence. Returns false if any comparison threw an exception.
*/
private boolean correspondInOrderAllIn( Iterator<? extends A> actual, Iterator<? extends E> expected);
/**
* Advances the actual iterator looking for an element which corresponds to the expected element. Returns whether or not it finds one.
*/
private boolean findCorresponding( Iterator<? extends A> actual, E expectedElement, Correspondence.ExceptionStore exceptions);
/**
* Given a list of actual elements, a list of expected elements, and a many:many mapping between actual and expected elements specified as a multimap of indexes into an actual list to indexes into the expected list, checks that every expected element maps to at least one actual element, and fails if this is not the case. Actual elements which do not map to any expected elements are ignored.
*/
private boolean failIfCandidateMappingHasMissing( List<? extends A> actual, List<? extends E> expected, ImmutableSetMultimap<Integer,Integer> mapping, Correspondence.ExceptionStore exceptions);
/**
* Given a list of missing elements, which must be non-empty, and a list of extra elements, returns a list of facts describing the missing elements, diffing against the extra ones where appropriate.
*/
private ImmutableList<Fact> describeMissing( List<? extends E> missing, List<? extends A> extra, Correspondence.ExceptionStore exceptions);
private ImmutableList<Fact> describeMissingWithoutPairing( List<? extends E> missing);
private ImmutableList<Fact> describeMissingWithPairing( Pairing pairing, Correspondence.ExceptionStore exceptions);
/**
* Given a list of expected elements, and a 1:1 mapping between actual and expected elements specified as a bimap of indexes into an actual list to indexes into the expected list, checks that every expected element maps to an actual element. Actual elements which do not map to any expected elements are ignored.
*/
private boolean failIfOneToOneMappingHasMissing( List<? extends A> actual, List<? extends E> expected, BiMap<Integer,Integer> mapping, Correspondence.ExceptionStore exceptions);
/**
* Checks that the subject contains at least one element that corresponds to at least one of the expected elements.
*/
@SafeVarargs public final void containsAnyOf( E first, E second, E @Nullable ... rest);
/**
* Checks that the subject contains at least one element that corresponds to at least one of the expected elements.
*/
public void containsAnyIn( Iterable<? extends E> expected);
/**
* Checks that the subject contains at least one element that corresponds to at least one of the expected elements.
*/
@SuppressWarnings("AvoidObjectArrays") public void containsAnyIn( E[] expected);
private ImmutableList<Fact> describeAnyMatchesByKey( Pairing pairing, Correspondence.ExceptionStore exceptions);
/**
* Checks that the subject contains no elements that correspond to any of the given elements. (Duplicates are irrelevant to this test, which fails if any of the subject elements correspond to any of the given elements.)
*/
@SafeVarargs public final void containsNoneOf( E firstExcluded, E secondExcluded, E @Nullable ... restOfExcluded);
/**
* Checks that the subject contains no elements that correspond to any of the given elements. (Duplicates are irrelevant to this test, which fails if any of the subject elements correspond to any of the given elements.)
*/
public void containsNoneIn( Iterable<? extends E> excluded);
/**
* Checks that the subject contains no elements that correspond to any of the given elements. (Duplicates are irrelevant to this test, which fails if any of the subject elements correspond to any of the given elements.)
*/
@SuppressWarnings("AvoidObjectArrays") public void containsNoneIn( E[] excluded);
@SuppressWarnings("unchecked") private Iterable<A> getCastActual();
/**
* A class which knows how to pair the actual and expected elements (see {@link #displayingDiffsPairedBy}).
*/
private final class Pairer {
private final Function<? super A,?> actualKeyFunction;
private final Function<? super E,?> expectedKeyFunction;
Pairer( Function<? super A,?> actualKeyFunction, Function<? super E,?> expectedKeyFunction);
/**
* Returns a {@link Pairing} of the given expected and actual values, or {@code null} if theexpected values are not uniquely keyed.
*/
@Nullable Pairing pair( List<? extends E> expectedValues, List<? extends A> actualValues, Correspondence.ExceptionStore exceptions);
List<A> pairOne( E expectedValue, Iterable<? extends A> actualValues, Correspondence.ExceptionStore exceptions);
private @Nullable Object actualKey( A actual, Correspondence.ExceptionStore exceptions);
private @Nullable Object expectedKey( E expected, Correspondence.ExceptionStore exceptions);
}
/**
* A description of a pairing between expected and actual values. N.B. This is mutable.
*/
private final class Pairing {
/**
* Map from keys used in the pairing to the expected value with that key. Iterates in the order the expected values appear in the input. Will never contain null keys.
*/
private final Map<Object,E> pairedKeysToExpectedValues=new LinkedHashMap<>();
/**
* Multimap from keys used in the pairing to the actual values with that key. Keys iterate in the order they first appear in the actual values in the input, and values for each key iterate in the order they appear too. Will never contain null keys.
*/
private final ListMultimap<Object,A> pairedKeysToActualValues=LinkedListMultimap.create();
/**
* List of the expected values not used in the pairing. Iterates in the order they appear in the input.
*/
private final List<E> unpairedExpectedValues=newArrayList();
/**
* List of the actual values not used in the pairing. Iterates in the order they appear in the input.
*/
private final List<A> unpairedActualValues=newArrayList();
}
}
}
final class LazyMessage {
private final String format;
private final Object[] args;
LazyMessage( String format, Object... args);
@Override public String toString();
@VisibleForTesting static int countPlaceholders( String template);
static ImmutableList<String> evaluateAll( ImmutableList<LazyMessage> messages);
}
@Override public final String toString(){
return description();
}
void add(E element){
contents.add(EQUALITY_WITHOUT_USING_HASH_CODE.wrap(element));
}
static Builder builder(String name){
return new AutoValue_ActualValueInference_Invocation.Builder().setName(name);
}
@Override FluentEqualityConfig build(){
if (set$0 != 7 || this.ignoreFieldAbsenceScope == null || this.ignoreRepeatedFieldOrderScope == null || this.ignoreExtraRepeatedFieldElementsScope == null || this.doubleCorrespondenceMap == null || this.floatCorrespondenceMap == null || this.compareFieldsScope == null || this.useTypeRegistry == null || this.useExtensionRegistry == null || this.usingCorrespondenceStringFunction == null) {
StringBuilder missing=new StringBuilder();
if (this.ignoreFieldAbsenceScope == null) {
missing.append(" ignoreFieldAbsenceScope");
}
if (this.ignoreRepeatedFieldOrderScope == null) {
missing.append(" ignoreRepeatedFieldOrderScope");
}
if (this.ignoreExtraRepeatedFieldElementsScope == null) {
missing.append(" ignoreExtraRepeatedFieldElementsScope");
}
if (this.doubleCorrespondenceMap == null) {
missing.append(" doubleCorrespondenceMap");
}
if (this.floatCorrespondenceMap == null) {
missing.append(" floatCorrespondenceMap");
}
if ((set$0 & 1) == 0) {
missing.append(" compareExpectedFieldsOnly");
}
if ((set$0 & 2) == 0) {
missing.append(" hasExpectedMessages");
}
if (this.compareFieldsScope == null) {
missing.append(" compareFieldsScope");
}
if ((set$0 & 4) == 0) {
missing.append(" reportMismatchesOnly");
}
if (this.useTypeRegistry == null) {
missing.append(" useTypeRegistry");
}
if (this.useExtensionRegistry == null) {
missing.append(" useExtensionRegistry");
}
if (this.usingCorrespondenceStringFunction == null) {
missing.append(" usingCorrespondenceStringFunction");
}
throw new IllegalStateException("Missing required properties:" + missing);
}
return new AutoValue_FluentEqualityConfig(this.ignoreFieldAbsenceScope,this.ignoreRepeatedFieldOrderScope,this.ignoreExtraRepeatedFieldElementsScope,this.doubleCorrespondenceMap,this.floatCorrespondenceMap,this.compareExpectedFieldsOnly,this.hasExpectedMessages,this.compareFieldsScope,this.reportMismatchesOnly,this.useTypeRegistry,this.useExtensionRegistry,this.usingCorrespondenceStringFunction);
}
static ImmutableList<String> evaluateAll(ImmutableList<LazyMessage> messages){
ImmutableList.Builder<String> result=ImmutableList.builder();
for ( LazyMessage message : messages) {
result.add(message.toString());
}
return result.build();
}
| public class IterableSubject extends Subject {
private final Iterable<?> actual;
protected IterableSubject( FailureMetadata metadata, Iterable<?> iterable);
IterableSubject( FailureMetadata metadata, Iterable<?> iterable, String typeDescriptionOverride);
protected String actualCustomStringRepresentation();
public void isEqualTo( Object expected);
public final void isEmpty();
public final void isNotEmpty();
public final void hasSize( int expectedSize);
public final void contains( Object element);
public final void doesNotContain( Object element);
public final void containsNoDuplicates();
public final void containsAnyOf( Object first, Object second, Object... rest);
public final void containsAnyIn( Iterable<?> expected);
public final void containsAnyIn( Object[] expected);
public final Ordered containsAtLeast( Object firstExpected, Object secondExpected, Object... restOfExpected);
public final Ordered containsAtLeastElementsIn( Iterable<?> expectedIterable);
public final Ordered containsAtLeastElementsIn( Object[] expected);
private Ordered failAtLeast( Collection<?> expected, Collection<?> missingRawObjects);
private static void moveElements( List<?> input, Collection<Object> output, int maxElements);
public final Ordered containsExactly( Object... varargs);
public final Ordered containsExactlyElementsIn( Iterable<?> expected);
/**
* Checks that a subject contains exactly the provided objects or fails. <p>Multiplicity is respected. For example, an object duplicated exactly 3 times in the array parameter asserts that the object must likewise be duplicated exactly 3 times in the subject. <p>To also test that the contents appear in the given order, make a call to {@code inOrder()}on the object returned by this method.
*/
public final Ordered containsExactlyElementsIn( Object[] expected);
private Ordered containsExactlyElementsIn( Iterable<?> required, boolean addElementsInWarning);
private Ordered failExactly( Iterable<?> required, boolean addElementsInWarning, Collection<?> missingRawObjects, Collection<?> extraRawObjects);
private static ImmutableList<Fact> makeElementFactsForBoth( String firstKey, Collection<?> firstCollection, String secondKey, Collection<?> secondCollection);
private static ImmutableList<Fact> makeElementFacts( String label, DuplicateGroupedAndTyped elements, ElementFactGrouping grouping);
private static String keyToGoWithElementsString( String label, DuplicateGroupedAndTyped elements);
private static String keyToServeAsHeader( String label, DuplicateGroupedAndTyped elements);
private static String numberString( int n, int count);
private static ElementFactGrouping pickGrouping( Iterable<Multiset.Entry<?>> first, Iterable<Multiset.Entry<?>> second);
private static boolean anyContainsCommaOrNewline( Iterable<Multiset.Entry<?>>... lists);
private static boolean hasMultiple( Iterable<Multiset.Entry<?>> entries);
private static boolean containsEmptyOrLong( Iterable<Multiset.Entry<?>> entries);
enum ElementFactGrouping { ALL_IN_ONE_FACT, FACT_PER_ELEMENT}
public final void containsNoneOf( Object firstExcluded, Object secondExcluded, Object... restOfExcluded);
public final void containsNoneIn( Iterable<?> excluded);
public final void containsNoneIn( Object[] excluded);
private static final Ordered IN_ORDER=() -> {
}
;
private static final Ordered ALREADY_FAILED=() -> {
}
;
public void isInStrictOrder();
/**
* Fails if the iterable is not strictly ordered, according to the given comparator. Strictly ordered means that each element in the iterable is <i>strictly</i> greater than the element that preceded it.
* @throws ClassCastException if any pair of elements is not mutually Comparable
*/
public final void isInStrictOrder( Comparator<?> comparator);
public void isInOrder();
/**
* Fails if the iterable is not ordered, according to the given comparator. Ordered means that each element in the iterable is greater than or equal to the element that preceded it.
* @throws ClassCastException if any pair of elements is not mutually Comparable
*/
public final void isInOrder( Comparator<?> comparator);
private interface PairwiseChecker {
boolean check( Object prev, Object next);
}
private void pairwiseCheck( String expectedFact, PairwiseChecker checker);
public void isNoneOf( Object first, Object second, Object... rest);
public void isNotIn( Iterable<?> iterable);
private Fact fullContents();
public <A extends Object,E extends Object>UsingCorrespondence<A,E> comparingElementsUsing( Correspondence<? super A,? super E> correspondence);
public <T>UsingCorrespondence<T,T> formattingDiffsUsing( DiffFormatter<? super T,? super T> formatter);
public static class UsingCorrespondence<A extends Object,E extends Object> {
private final IterableSubject subject;
private final Correspondence<? super A,? super E> correspondence;
private final Optional<Pairer> pairer;
UsingCorrespondence( IterableSubject subject, Correspondence<? super A,? super E> correspondence);
UsingCorrespondence( IterableSubject subject, Correspondence<? super A,? super E> correspondence, Pairer pairer);
public final boolean equals( Object o);
public final int hashCode();
public final String toString();
public UsingCorrespondence<A,E> displayingDiffsPairedBy( Function<? super E,?> keyFunction);
public UsingCorrespondence<A,E> displayingDiffsPairedBy( Function<? super A,?> actualKeyFunction, Function<? super E,?> expectedKeyFunction);
public void contains( E expected);
public void doesNotContain( E excluded);
public final Ordered containsExactly( E... expected);
public Ordered containsExactlyElementsIn( Iterable<? extends E> expected);
public Ordered containsExactlyElementsIn( E[] expected);
private boolean correspondInOrderExactly( Iterator<? extends A> actual, Iterator<? extends E> expected);
private ImmutableSetMultimap<Integer,Integer> findCandidateMapping( List<? extends A> actual, List<? extends E> expected, Correspondence.ExceptionStore exceptions);
private boolean failIfCandidateMappingHasMissingOrExtra( List<? extends A> actual, List<? extends E> expected, ImmutableSetMultimap<Integer,Integer> mapping, Correspondence.ExceptionStore exceptions);
private ImmutableList<Fact> describeMissingOrExtra( List<? extends E> missing, List<? extends A> extra, Correspondence.ExceptionStore exceptions);
private ImmutableList<Fact> describeMissingOrExtraWithoutPairing( List<? extends E> missing, List<? extends A> extra);
private ImmutableList<Fact> describeMissingOrExtraWithPairing( Pairing pairing, Correspondence.ExceptionStore exceptions);
private ImmutableList<Fact> formatExtras( String label, E missing, List<? extends A> extras, Correspondence.ExceptionStore exceptions);
private <T extends Object>List<T> findNotIndexed( List<T> list, Set<Integer> indexes);
private ImmutableBiMap<Integer,Integer> findMaximalOneToOneMapping( ImmutableMultimap<Integer,Integer> edges);
private boolean failIfOneToOneMappingHasMissingOrExtra( List<? extends A> actual, List<? extends E> expected, BiMap<Integer,Integer> mapping, Correspondence.ExceptionStore exceptions);
public final Ordered containsAtLeast( E first, E second, E... rest);
public Ordered containsAtLeastElementsIn( Iterable<? extends E> expected);
public Ordered containsAtLeastElementsIn( E[] expected);
private boolean correspondInOrderAllIn( Iterator<? extends A> actual, Iterator<? extends E> expected);
private boolean findCorresponding( Iterator<? extends A> actual, E expectedElement, Correspondence.ExceptionStore exceptions);
private boolean failIfCandidateMappingHasMissing( List<? extends A> actual, List<? extends E> expected, ImmutableSetMultimap<Integer,Integer> mapping, Correspondence.ExceptionStore exceptions);
private ImmutableList<Fact> describeMissing( List<? extends E> missing, List<? extends A> extra, Correspondence.ExceptionStore exceptions);
private ImmutableList<Fact> describeMissingWithoutPairing( List<? extends E> missing);
private ImmutableList<Fact> describeMissingWithPairing( Pairing pairing, Correspondence.ExceptionStore exceptions);
private boolean failIfOneToOneMappingHasMissing( List<? extends A> actual, List<? extends E> expected, BiMap<Integer,Integer> mapping, Correspondence.ExceptionStore exceptions);
public final void containsAnyOf( E first, E second, E... rest);
public void containsAnyIn( Iterable<? extends E> expected);
public void containsAnyIn( E[] expected);
private ImmutableList<Fact> describeAnyMatchesByKey( Pairing pairing, Correspondence.ExceptionStore exceptions);
public final void containsNoneOf( E firstExcluded, E secondExcluded, E... restOfExcluded);
public void containsNoneIn( Iterable<? extends E> excluded);
public void containsNoneIn( E[] excluded);
private Iterable<A> getCastActual();
private final class Pairer {
private final Function<? super A,?> actualKeyFunction;
private final Function<? super E,?> expectedKeyFunction;
Pairer( Function<? super A,?> actualKeyFunction, Function<? super E,?> expectedKeyFunction);
Pairing pair( List<? extends E> expectedValues, List<? extends A> actualValues, Correspondence.ExceptionStore exceptions);
List<A> pairOne( E expectedValue, Iterable<? extends A> actualValues, Correspondence.ExceptionStore exceptions);
private Object actualKey( A actual, Correspondence.ExceptionStore exceptions);
private Object expectedKey( E expected, Correspondence.ExceptionStore exceptions);
}
private final class Pairing {
private final Map<Object,E> pairedKeysToExpectedValues=new LinkedHashMap<>();
private final ListMultimap<Object,A> pairedKeysToActualValues=LinkedListMultimap.create();
private final List<E> unpairedExpectedValues=newArrayList();
private final List<A> unpairedActualValues=newArrayList();
}
}
}
final class LazyMessage {
private final String format;
private final Object[] args;
LazyMessage( String format, Object... args);
public String toString();
static int countPlaceholders( String template);
static ImmutableList<String> evaluateAll( ImmutableList<LazyMessage> messages);
}
@Override public final String toString(){
return description();
}
void add(E element){
contents.add(EQUALITY_WITHOUT_USING_HASH_CODE.wrap(element));
}
static Builder builder(String name){
return new AutoValue_ActualValueInference_Invocation.Builder().setName(name);
}
@Override FluentEqualityConfig build(){
if (set$0 != 7 || this.ignoreFieldAbsenceScope == null || this.ignoreRepeatedFieldOrderScope == null || this.ignoreExtraRepeatedFieldElementsScope == null || this.doubleCorrespondenceMap == null || this.floatCorrespondenceMap == null || this.compareFieldsScope == null || this.useTypeRegistry == null || this.useExtensionRegistry == null || this.usingCorrespondenceStringFunction == null) {
StringBuilder missing=new StringBuilder();
if (this.ignoreFieldAbsenceScope == null) {
missing.append(" ignoreFieldAbsenceScope");
}
if (this.ignoreRepeatedFieldOrderScope == null) {
missing.append(" ignoreRepeatedFieldOrderScope");
}
if (this.ignoreExtraRepeatedFieldElementsScope == null) {
missing.append(" ignoreExtraRepeatedFieldElementsScope");
}
if (this.doubleCorrespondenceMap == null) {
missing.append(" doubleCorrespondenceMap");
}
if (this.floatCorrespondenceMap == null) {
missing.append(" floatCorrespondenceMap");
}
if ((set$0 & 1) == 0) {
missing.append(" compareExpectedFieldsOnly");
}
if ((set$0 & 2) == 0) {
missing.append(" hasExpectedMessages");
}
if (this.compareFieldsScope == null) {
missing.append(" compareFieldsScope");
}
if ((set$0 & 4) == 0) {
missing.append(" reportMismatchesOnly");
}
if (this.useTypeRegistry == null) {
missing.append(" useTypeRegistry");
}
if (this.useExtensionRegistry == null) {
missing.append(" useExtensionRegistry");
}
if (this.usingCorrespondenceStringFunction == null) {
missing.append(" usingCorrespondenceStringFunction");
}
throw new IllegalStateException("Missing required properties:" + missing);
}
return new AutoValue_FluentEqualityConfig(this.ignoreFieldAbsenceScope,this.ignoreRepeatedFieldOrderScope,this.ignoreExtraRepeatedFieldElementsScope,this.doubleCorrespondenceMap,this.floatCorrespondenceMap,this.compareExpectedFieldsOnly,this.hasExpectedMessages,this.compareFieldsScope,this.reportMismatchesOnly,this.useTypeRegistry,this.useExtensionRegistry,this.usingCorrespondenceStringFunction);
}
static ImmutableList<String> evaluateAll(ImmutableList<LazyMessage> messages){
ImmutableList.Builder<String> result=ImmutableList.builder();
for ( LazyMessage message : messages) {
result.add(message.toString());
}
return result.build();
}
| {"types": [{"ImmutableList.Builder<String>": "IterableSubject"}, {"LazyMessage": "LazyMessage"}, {"ImmutableList<LazyMessage>": "LazyMessage"}], "methods": [{"toString": "toString"}, {"add": "add"}, {"builder": "builder"}, {"build": "build"}], "similar_methods": [{"evaluateAll": "evaluateAll"}]} | [{"ImmutableList.Builder<String>": {"retrieved_name": "IterableSubject", "raw_body": "/** \n * Propositions for {@link Iterable} subjects.<p><b>Note:</b> <ul> <li>Assertions may iterate through the given {@link Iterable} more than once. If you have anunusual implementation of {@link Iterable} which does not support multiple iterations(sometimes known as a \"one-shot iterable\"), you must copy your iterable into a collection which does (e.g. {@code ImmutableList.copyOf(iterable)} or, if your iterable may containnull, {@code newArrayList(iterable)}). If you don't, you may see surprising failures. <li>Assertions may also require that the elements in the given {@link Iterable} implement{@link Object#hashCode} correctly.</ul>\n * @author Kurt Alfred Kluever\n * @author Pete Gillin\n */\npublic class IterableSubject extends Subject {\n private final @Nullable Iterable<?> actual;\n /** \n * Constructor for use by subclasses. If you want to create an instance of this class itself, call {@link Subject#check(String,Object...) check(...)}{@code .that(actual)}.\n */\n protected IterableSubject( FailureMetadata metadata, @Nullable Iterable<?> iterable);\n /** \n * Constructor for use by package-private callers. \n */\n IterableSubject( FailureMetadata metadata, @Nullable Iterable<?> iterable, @Nullable String typeDescriptionOverride);\n @Override protected String actualCustomStringRepresentation();\n @Override public void isEqualTo( @Nullable Object expected);\n /** \n * Fails if the subject is not empty. \n */\n public final void isEmpty();\n /** \n * Fails if the subject is empty. \n */\n public final void isNotEmpty();\n /** \n * Fails if the subject does not have the given size. \n */\n public final void hasSize( int expectedSize);\n /** \n * Checks (with a side-effect failure) that the subject contains the supplied item. \n */\n public final void contains( @Nullable Object element);\n /** \n * Checks (with a side-effect failure) that the subject does not contain the supplied item. \n */\n public final void doesNotContain( @Nullable Object element);\n /** \n * Checks that the subject does not contain duplicate elements. \n */\n public final void containsNoDuplicates();\n /** \n * Checks that the subject contains at least one of the provided objects or fails. \n */\n public final void containsAnyOf( @Nullable Object first, @Nullable Object second, @Nullable Object @Nullable ... rest);\n /** \n * Checks that the subject contains at least one of the objects contained in the provided collection or fails.\n */\n public final void containsAnyIn( @Nullable Iterable<?> expected);\n /** \n * Checks that the subject contains at least one of the objects contained in the provided array or fails.\n */\n @SuppressWarnings(\"AvoidObjectArrays\") public final void containsAnyIn( @Nullable Object[] expected);\n /** \n * Checks that the actual iterable contains at least all of the expected elements or fails. If an element appears more than once in the expected elements to this call then it must appear at least that number of times in the actual elements. <p>To also test that the contents appear in the given order, make a call to {@code inOrder()}on the object returned by this method. The expected elements must appear in the given order within the actual elements, but they are not required to be consecutive.\n */\n @CanIgnoreReturnValue public final Ordered containsAtLeast( @Nullable Object firstExpected, @Nullable Object secondExpected, @Nullable Object @Nullable ... restOfExpected);\n /** \n * Checks that the actual iterable contains at least all of the expected elements or fails. If an element appears more than once in the expected elements then it must appear at least that number of times in the actual elements. <p>To also test that the contents appear in the given order, make a call to {@code inOrder()}on the object returned by this method. The expected elements must appear in the given order within the actual elements, but they are not required to be consecutive.\n */\n @CanIgnoreReturnValue public final Ordered containsAtLeastElementsIn( Iterable<?> expectedIterable);\n /** \n * Checks that the actual iterable contains at least all of the expected elements or fails. If an element appears more than once in the expected elements then it must appear at least that number of times in the actual elements. <p>To also test that the contents appear in the given order, make a call to {@code inOrder()}on the object returned by this method. The expected elements must appear in the given order within the actual elements, but they are not required to be consecutive.\n */\n @CanIgnoreReturnValue @SuppressWarnings(\"AvoidObjectArrays\") public final Ordered containsAtLeastElementsIn( @Nullable Object[] expected);\n private Ordered failAtLeast( Collection<?> expected, Collection<?> missingRawObjects);\n /** \n * Removes at most the given number of available elements from the input list and adds them to the given output collection.\n */\n private static void moveElements( List<?> input, Collection<@Nullable Object> output, int maxElements);\n /** \n * Checks that a subject contains exactly the provided objects or fails. <p>Multiplicity is respected. For example, an object duplicated exactly 3 times in the parameters asserts that the object must likewise be duplicated exactly 3 times in the subject. <p>To also test that the contents appear in the given order, make a call to {@code inOrder()}on the object returned by this method. <p>To test that the iterable contains the same elements as an array, prefer {@link #containsExactlyElementsIn(Object[])}. It makes clear that the given array is a list of elements, not an element itself. This helps human readers and avoids a compiler warning.\n */\n @CanIgnoreReturnValue public final Ordered containsExactly( @Nullable Object @Nullable ... varargs);\n /** \n * Checks that a subject contains exactly the provided objects or fails. <p>Multiplicity is respected. For example, an object duplicated exactly 3 times in the {@code Iterable} parameter asserts that the object must likewise be duplicated exactly 3 times in thesubject. <p>To also test that the contents appear in the given order, make a call to {@code inOrder()}on the object returned by this method.\n */\n @CanIgnoreReturnValue public final Ordered containsExactlyElementsIn( @Nullable Iterable<?> expected);\n /** \n * Checks that a subject contains exactly the provided objects or fails. <p>Multiplicity is respected. For example, an object duplicated exactly 3 times in the array parameter asserts that the object must likewise be duplicated exactly 3 times in the subject. <p>To also test that the contents appear in the given order, make a call to {@code inOrder()}on the object returned by this method.\n */\n @CanIgnoreReturnValue @SuppressWarnings({\"AvoidObjectArrays\",\"ContainsExactlyElementsInUnnecessaryWrapperAroundArray\",\"ContainsExactlyElementsInWithVarArgsToExactly\"}) public final Ordered containsExactlyElementsIn( @Nullable Object @Nullable [] expected);\n private Ordered containsExactlyElementsIn( @Nullable Iterable<?> required, boolean addElementsInWarning);\n private Ordered failExactly( Iterable<?> required, boolean addElementsInWarning, Collection<?> missingRawObjects, Collection<?> extraRawObjects);\n private static ImmutableList<Fact> makeElementFactsForBoth( String firstKey, Collection<?> firstCollection, String secondKey, Collection<?> secondCollection);\n /** \n * Returns a list of facts (zero, one, or many, depending on the number of elements and the grouping policy) describing the given missing, unexpected, or near-miss elements.\n */\n private static ImmutableList<Fact> makeElementFacts( String label, DuplicateGroupedAndTyped elements, ElementFactGrouping grouping);\n private static String keyToGoWithElementsString( String label, DuplicateGroupedAndTyped elements);\n private static String keyToServeAsHeader( String label, DuplicateGroupedAndTyped elements);\n private static String numberString( int n, int count);\n private static ElementFactGrouping pickGrouping( Iterable<Multiset.Entry<?>> first, Iterable<Multiset.Entry<?>> second);\n private static boolean anyContainsCommaOrNewline( Iterable<Multiset.Entry<?>>... lists);\n private static boolean hasMultiple( Iterable<Multiset.Entry<?>> entries);\n private static boolean containsEmptyOrLong( Iterable<Multiset.Entry<?>> entries);\n /** \n * Whether to output each missing/unexpected item as its own {@link Fact} or to group all thoseitems together into a single {@code Fact}.\n */\n enum ElementFactGrouping { ALL_IN_ONE_FACT, FACT_PER_ELEMENT}\n /** \n * Checks that a actual iterable contains none of the excluded objects or fails. (Duplicates are irrelevant to this test, which fails if any of the actual elements equal any of the excluded.)\n */\n public final void containsNoneOf( @Nullable Object firstExcluded, @Nullable Object secondExcluded, @Nullable Object @Nullable ... restOfExcluded);\n /** \n * Checks that the actual iterable contains none of the elements contained in the excluded iterable or fails. (Duplicates are irrelevant to this test, which fails if any of the actual elements equal any of the excluded.)\n */\n public final void containsNoneIn( Iterable<?> excluded);\n /** \n * Checks that the actual iterable contains none of the elements contained in the excluded array or fails. (Duplicates are irrelevant to this test, which fails if any of the actual elements equal any of the excluded.)\n */\n @SuppressWarnings(\"AvoidObjectArrays\") public final void containsNoneIn( @Nullable Object[] excluded);\n /** \n * Ordered implementation that does nothing because it's already known to be true. \n */\n private static final Ordered IN_ORDER=() -> {\n }\n;\n /** \n * Ordered implementation that does nothing because an earlier check already caused a failure. \n */\n private static final Ordered ALREADY_FAILED=() -> {\n }\n;\n /** \n * Fails if the iterable is not strictly ordered, according to the natural ordering of its elements. Strictly ordered means that each element in the iterable is <i>strictly</i> greater than the element that preceded it.\n * @throws ClassCastException if any pair of elements is not mutually Comparable\n * @throws NullPointerException if any element is null\n */\n public void isInStrictOrder();\n /** \n * Fails if the iterable is not strictly ordered, according to the given comparator. Strictly ordered means that each element in the iterable is <i>strictly</i> greater than the element that preceded it.\n * @throws ClassCastException if any pair of elements is not mutually Comparable\n */\n @SuppressWarnings({\"unchecked\"}) public final void isInStrictOrder( Comparator<?> comparator);\n /** \n * Fails if the iterable is not ordered, according to the natural ordering of its elements. Ordered means that each element in the iterable is greater than or equal to the element that preceded it.\n * @throws ClassCastException if any pair of elements is not mutually Comparable\n * @throws NullPointerException if any element is null\n */\n public void isInOrder();\n /** \n * Fails if the iterable is not ordered, according to the given comparator. Ordered means that each element in the iterable is greater than or equal to the element that preceded it.\n * @throws ClassCastException if any pair of elements is not mutually Comparable\n */\n @SuppressWarnings({\"unchecked\"}) public final void isInOrder( Comparator<?> comparator);\nprivate interface PairwiseChecker {\n boolean check( @Nullable Object prev, @Nullable Object next);\n }\n private void pairwiseCheck( String expectedFact, PairwiseChecker checker);\n /** \n * @deprecated You probably meant to call {@link #containsNoneOf} instead.\n */\n @Override @Deprecated public void isNoneOf( @Nullable Object first, @Nullable Object second, @Nullable Object @Nullable ... rest);\n /** \n * @deprecated You probably meant to call {@link #containsNoneIn} instead.\n */\n @Override @Deprecated public void isNotIn( @Nullable Iterable<?> iterable);\n private Fact fullContents();\n /** \n * Starts a method chain for a check in which the actual elements (i.e. the elements of the {@link Iterable} under test) are compared to expected elements using the given {@link Correspondence}. The actual elements must be of type {@code A}, the expected elements must be of type {@code E}. The check is actually executed by continuing the method chain. For example: <pre> {@code assertThat(actualIterable).comparingElementsUsing(correspondence).contains(expected);}</pre> where {@code actualIterable} is an {@code Iterable<A>} (or, more generally, an {@code Iterable<? extends A>}), {@code correspondence} is a {@code Correspondence<A, E>}, and {@code expected} is an {@code E}. <p>Any of the methods on the returned object may throw {@link ClassCastException} if theyencounter an actual element that is not of type {@code A}.\n */\n public <A extends @Nullable Object,E extends @Nullable Object>UsingCorrespondence<A,E> comparingElementsUsing( Correspondence<? super A,? super E> correspondence);\n /** \n * Starts a method chain for a check in which failure messages may use the given {@link DiffFormatter} to describe the difference between an actual elements (i.e. an element of the{@link Iterable} under test) and the element it is expected to be equal to, but isn't. Theactual and expected elements must be of type {@code T}. The check is actually executed by continuing the method chain. You may well want to use {@link UsingCorrespondence#displayingDiffsPairedBy} to specify how the elements should be paired upfor diffing. For example: <pre> {@code assertThat(actualFoos) .formattingDiffsUsing(FooTestHelper::formatDiff) .displayingDiffsPairedBy(Foo::getId) .containsExactly(foo1, foo2, foo3);}</pre> where {@code actualFoos} is an {@code Iterable<Foo>}, {@code FooTestHelper.formatDiff} is astatic method taking two {@code Foo} arguments and returning a {@link String}, {@code Foo.getId} is a no-arg instance method returning some kind of ID, and {@code foo1}, {code foo2}, and {@code foo3} are {@code Foo} instances.<p>Unlike when using {@link #comparingElementsUsing}, the elements are still compared using object equality, so this method does not affect whether a test passes or fails. <p>Any of the methods on the returned object may throw {@link ClassCastException} if theyencounter an actual element that is not of type {@code T}.\n * @since 1.1\n */\n public <T>UsingCorrespondence<T,T> formattingDiffsUsing( DiffFormatter<? super T,? super T> formatter);\n /** \n * A partially specified check in which the actual elements (normally the elements of the {@link Iterable} under test) are compared to expected elements using a {@link Correspondence}. The expected elements are of type {@code E}. Call methods on this object to actually execute the check.\n */\npublic static class UsingCorrespondence<A extends @Nullable Object,E extends @Nullable Object> {\n private final IterableSubject subject;\n private final Correspondence<? super A,? super E> correspondence;\n private final Optional<Pairer> pairer;\n UsingCorrespondence( IterableSubject subject, Correspondence<? super A,? super E> correspondence);\n UsingCorrespondence( IterableSubject subject, Correspondence<? super A,? super E> correspondence, Pairer pairer);\n /** \n * @throws UnsupportedOperationException always\n * @deprecated {@link Object#equals(Object)} is not supported on Truth subjects or intermediateclasses. If you are writing a test assertion (actual vs. expected), use methods liks {@link #containsExactlyElementsIn(Iterable)} instead.\n */\n @DoNotCall(\"UsingCorrespondence.equals() is not supported. Did you mean to call\" + \" containsExactlyElementsIn(expected) instead of equals(expected)?\") @Deprecated @Override public final boolean equals( @Nullable Object o);\n /** \n * @throws UnsupportedOperationException always\n * @deprecated {@link Object#hashCode()} is not supported on Truth types.\n */\n @DoNotCall(\"UsingCorrespondence.hashCode() is not supported.\") @Deprecated @Override public final int hashCode();\n /** \n * @throws UnsupportedOperationException always\n * @deprecated {@link Object#toString()} is not supported on Truth subjects.\n */\n @Deprecated @DoNotCall(\"UsingCorrespondence.toString() is not supported.\") @Override public final String toString();\n /** \n * Specifies a way to pair up unexpected and missing elements in the message when an assertion fails. For example: <pre> {@code assertThat(actualRecords) .comparingElementsUsing(RECORD_CORRESPONDENCE) .displayingDiffsPairedBy(MyRecord::getId) .containsExactlyElementsIn(expectedRecords);}</pre> <p><b>Important</b>: The {code keyFunction} function must be able to accept both the actual and the unexpected elements, i.e. it must satisfy {@code Function<? super A, ?>} as well as{@code Function<? super E, ?>}. If that constraint is not met then a subsequent method may throw {@link ClassCastException}. Use the two-parameter overload if you need to specify different key functions for the actual and expected elements. <p>On assertions where it makes sense to do so, the elements are paired as follows: they are keyed by {@code keyFunction}, and if an unexpected element and a missing element have the same non-null key then the they are paired up. (Elements with null keys are not paired.) The failure message will show paired elements together, and a diff will be shown if the {@link Correspondence#formatDiff} method returns non-null.<p>The expected elements given in the assertion should be uniquely keyed by {@code keyFunction}. If multiple missing elements have the same key then the pairing will be skipped. <p>Useful key functions will have the property that key equality is less strict than the correspondence, i.e. given {@code actual} and {@code expected} values with keys {@code actualKey} and {@code expectedKey}, if {@code correspondence.compare(actual, expected)} istrue then it is guaranteed that {@code actualKey} is equal to {@code expectedKey}, but there are cases where {@code actualKey} is equal to {@code expectedKey} but {@code correspondence.compare(actual, expected)} is false.<p>If the {@code apply} method on the key function throws an exception then the element willbe treated as if it had a null key and not paired. (The first such exception will be noted in the failure message.) <p>Note that calling this method makes no difference to whether a test passes or fails, it just improves the message if it fails.\n */\n public UsingCorrespondence<A,E> displayingDiffsPairedBy( Function<? super E,?> keyFunction);\n /** \n * Specifies a way to pair up unexpected and missing elements in the message when an assertion fails. For example: <pre> {@code assertThat(actualFoos) .comparingElementsUsing(FOO_BAR_CORRESPONDENCE) .displayingDiffsPairedBy(Foo::getId, Bar::getFooId) .containsExactlyElementsIn(expectedBar);}</pre> <p>On assertions where it makes sense to do so, the elements are paired as follows: the unexpected elements are keyed by {@code actualKeyFunction}, the missing elements are keyed by {@code expectedKeyFunction}, and if an unexpected element and a missing element have the same non-null key then the they are paired up. (Elements with null keys are not paired.) The failure message will show paired elements together, and a diff will be shown if the {@link Correspondence#formatDiff} method returns non-null.<p>The expected elements given in the assertion should be uniquely keyed by {@code expectedKeyFunction}. If multiple missing elements have the same key then the pairing will be skipped. <p>Useful key functions will have the property that key equality is less strict than the correspondence, i.e. given {@code actual} and {@code expected} values with keys {@code actualKey} and {@code expectedKey}, if {@code correspondence.compare(actual, expected)} istrue then it is guaranteed that {@code actualKey} is equal to {@code expectedKey}, but there are cases where {@code actualKey} is equal to {@code expectedKey} but {@code correspondence.compare(actual, expected)} is false.<p>If the {@code apply} method on either of the key functions throws an exception then theelement will be treated as if it had a null key and not paired. (The first such exception will be noted in the failure message.) <p>Note that calling this method makes no difference to whether a test passes or fails, it just improves the message if it fails.\n */\n public UsingCorrespondence<A,E> displayingDiffsPairedBy( Function<? super A,?> actualKeyFunction, Function<? super E,?> expectedKeyFunction);\n /** \n * Checks that the subject contains at least one element that corresponds to the given expected element.\n */\n public void contains( E expected);\n /** \n * Checks that none of the actual elements correspond to the given element. \n */\n public void doesNotContain( E excluded);\n /** \n * Checks that subject contains exactly elements that correspond to the expected elements, i.e. that there is a 1:1 mapping between the actual elements and the expected elements where each pair of elements correspond. <p>To also test that the contents appear in the given order, make a call to {@code inOrder()}on the object returned by this method. <p>To test that the iterable contains the elements corresponding to those in an array, prefer {@link #containsExactlyElementsIn(Object[])}. It makes clear that the given array is a list of elements, not an element itself. This helps human readers and avoids a compiler warning.\n */\n @SafeVarargs @CanIgnoreReturnValue public final Ordered containsExactly( @Nullable E @Nullable ... expected);\n /** \n * Checks that subject contains exactly elements that correspond to the expected elements, i.e. that there is a 1:1 mapping between the actual elements and the expected elements where each pair of elements correspond. <p>To also test that the contents appear in the given order, make a call to {@code inOrder()}on the object returned by this method.\n */\n @CanIgnoreReturnValue public Ordered containsExactlyElementsIn( @Nullable Iterable<? extends E> expected);\n /** \n * Checks that subject contains exactly elements that correspond to the expected elements, i.e. that there is a 1:1 mapping between the actual elements and the expected elements where each pair of elements correspond. <p>To also test that the contents appear in the given order, make a call to {@code inOrder()}on the object returned by this method.\n */\n @CanIgnoreReturnValue @SuppressWarnings(\"AvoidObjectArrays\") public Ordered containsExactlyElementsIn( E @Nullable [] expected);\n /** \n * Returns whether the actual and expected iterators have the same number of elements and, when iterated pairwise, every pair of actual and expected values satisfies the correspondence. Returns false if any comparison threw an exception.\n */\n private boolean correspondInOrderExactly( Iterator<? extends A> actual, Iterator<? extends E> expected);\n /** \n * Given a list of actual elements and a list of expected elements, finds a many:many mapping between actual and expected elements where a pair of elements maps if it satisfies the correspondence. Returns this mapping as a multimap where the keys are indexes into the actual list and the values are indexes into the expected list. Any exceptions are treated as if the elements did not correspond, and the exception added to the store.\n */\n private ImmutableSetMultimap<Integer,Integer> findCandidateMapping( List<? extends A> actual, List<? extends E> expected, Correspondence.ExceptionStore exceptions);\n /** \n * Given a list of actual elements, a list of expected elements, and a many:many mapping between actual and expected elements specified as a multimap of indexes into the actual list to indexes into the expected list, checks that every actual element maps to at least one expected element and vice versa, and fails if this is not the case. Returns whether the assertion failed.\n */\n private boolean failIfCandidateMappingHasMissingOrExtra( List<? extends A> actual, List<? extends E> expected, ImmutableSetMultimap<Integer,Integer> mapping, Correspondence.ExceptionStore exceptions);\n /** \n * Given a list of missing elements and a list of extra elements, at least one of which must be non-empty, returns facts describing them. Exceptions from calling {@link Correspondence#formatDiff} are stored in {@code exceptions}.\n */\n private ImmutableList<Fact> describeMissingOrExtra( List<? extends E> missing, List<? extends A> extra, Correspondence.ExceptionStore exceptions);\n private ImmutableList<Fact> describeMissingOrExtraWithoutPairing( List<? extends E> missing, List<? extends A> extra);\n private ImmutableList<Fact> describeMissingOrExtraWithPairing( Pairing pairing, Correspondence.ExceptionStore exceptions);\n private ImmutableList<Fact> formatExtras( String label, E missing, List<? extends A> extras, Correspondence.ExceptionStore exceptions);\n /** \n * Returns all the elements of the given list other than those with the given indexes. Assumes that all the given indexes really are valid indexes into the list.\n */\n private <T extends @Nullable Object>List<T> findNotIndexed( List<T> list, Set<Integer> indexes);\n /** \n * Given a many:many mapping between actual elements and expected elements, finds a 1:1 mapping which is the subset of that many:many mapping which includes the largest possible number of elements. The input and output mappings are each described as a map or multimap where the keys are indexes into the actual list and the values are indexes into the expected list. If there are multiple possible output mappings tying for the largest possible, this returns an arbitrary one.\n */\n private ImmutableBiMap<Integer,Integer> findMaximalOneToOneMapping( ImmutableMultimap<Integer,Integer> edges);\n /** \n * Given a list of actual elements, a list of expected elements, and a 1:1 mapping between actual and expected elements specified as a bimap of indexes into the actual list to indexes into the expected list, checks that every actual element maps to an expected element and vice versa, and fails if this is not the case. Returns whether the assertion failed.\n */\n private boolean failIfOneToOneMappingHasMissingOrExtra( List<? extends A> actual, List<? extends E> expected, BiMap<Integer,Integer> mapping, Correspondence.ExceptionStore exceptions);\n /** \n * Checks that the subject contains elements that corresponds to all of the expected elements, i.e. that there is a 1:1 mapping between any subset of the actual elements and the expected elements where each pair of elements correspond. <p>To also test that the contents appear in the given order, make a call to {@code inOrder()}on the object returned by this method. The elements must appear in the given order within the subject, but they are not required to be consecutive.\n */\n @SafeVarargs @CanIgnoreReturnValue public final Ordered containsAtLeast( E first, E second, E @Nullable ... rest);\n /** \n * Checks that the subject contains elements that corresponds to all of the expected elements, i.e. that there is a 1:1 mapping between any subset of the actual elements and the expected elements where each pair of elements correspond. <p>To also test that the contents appear in the given order, make a call to {@code inOrder()}on the object returned by this method. The elements must appear in the given order within the subject, but they are not required to be consecutive.\n */\n @CanIgnoreReturnValue public Ordered containsAtLeastElementsIn( Iterable<? extends E> expected);\n /** \n * Checks that the subject contains elements that corresponds to all of the expected elements, i.e. that there is a 1:1 mapping between any subset of the actual elements and the expected elements where each pair of elements correspond. <p>To also test that the contents appear in the given order, make a call to {@code inOrder()}on the object returned by this method. The elements must appear in the given order within the subject, but they are not required to be consecutive.\n */\n @CanIgnoreReturnValue @SuppressWarnings(\"AvoidObjectArrays\") public Ordered containsAtLeastElementsIn( E[] expected);\n /** \n * Returns whether all the elements of the expected iterator and any subset of the elements of the actual iterator can be paired up in order, such that every pair of actual and expected elements satisfies the correspondence. Returns false if any comparison threw an exception.\n */\n private boolean correspondInOrderAllIn( Iterator<? extends A> actual, Iterator<? extends E> expected);\n /** \n * Advances the actual iterator looking for an element which corresponds to the expected element. Returns whether or not it finds one.\n */\n private boolean findCorresponding( Iterator<? extends A> actual, E expectedElement, Correspondence.ExceptionStore exceptions);\n /** \n * Given a list of actual elements, a list of expected elements, and a many:many mapping between actual and expected elements specified as a multimap of indexes into an actual list to indexes into the expected list, checks that every expected element maps to at least one actual element, and fails if this is not the case. Actual elements which do not map to any expected elements are ignored.\n */\n private boolean failIfCandidateMappingHasMissing( List<? extends A> actual, List<? extends E> expected, ImmutableSetMultimap<Integer,Integer> mapping, Correspondence.ExceptionStore exceptions);\n /** \n * Given a list of missing elements, which must be non-empty, and a list of extra elements, returns a list of facts describing the missing elements, diffing against the extra ones where appropriate.\n */\n private ImmutableList<Fact> describeMissing( List<? extends E> missing, List<? extends A> extra, Correspondence.ExceptionStore exceptions);\n private ImmutableList<Fact> describeMissingWithoutPairing( List<? extends E> missing);\n private ImmutableList<Fact> describeMissingWithPairing( Pairing pairing, Correspondence.ExceptionStore exceptions);\n /** \n * Given a list of expected elements, and a 1:1 mapping between actual and expected elements specified as a bimap of indexes into an actual list to indexes into the expected list, checks that every expected element maps to an actual element. Actual elements which do not map to any expected elements are ignored.\n */\n private boolean failIfOneToOneMappingHasMissing( List<? extends A> actual, List<? extends E> expected, BiMap<Integer,Integer> mapping, Correspondence.ExceptionStore exceptions);\n /** \n * Checks that the subject contains at least one element that corresponds to at least one of the expected elements.\n */\n @SafeVarargs public final void containsAnyOf( E first, E second, E @Nullable ... rest);\n /** \n * Checks that the subject contains at least one element that corresponds to at least one of the expected elements.\n */\n public void containsAnyIn( Iterable<? extends E> expected);\n /** \n * Checks that the subject contains at least one element that corresponds to at least one of the expected elements.\n */\n @SuppressWarnings(\"AvoidObjectArrays\") public void containsAnyIn( E[] expected);\n private ImmutableList<Fact> describeAnyMatchesByKey( Pairing pairing, Correspondence.ExceptionStore exceptions);\n /** \n * Checks that the subject contains no elements that correspond to any of the given elements. (Duplicates are irrelevant to this test, which fails if any of the subject elements correspond to any of the given elements.)\n */\n @SafeVarargs public final void containsNoneOf( E firstExcluded, E secondExcluded, E @Nullable ... restOfExcluded);\n /** \n * Checks that the subject contains no elements that correspond to any of the given elements. (Duplicates are irrelevant to this test, which fails if any of the subject elements correspond to any of the given elements.)\n */\n public void containsNoneIn( Iterable<? extends E> excluded);\n /** \n * Checks that the subject contains no elements that correspond to any of the given elements. (Duplicates are irrelevant to this test, which fails if any of the subject elements correspond to any of the given elements.)\n */\n @SuppressWarnings(\"AvoidObjectArrays\") public void containsNoneIn( E[] excluded);\n @SuppressWarnings(\"unchecked\") private Iterable<A> getCastActual();\n /** \n * A class which knows how to pair the actual and expected elements (see {@link #displayingDiffsPairedBy}).\n */\nprivate final class Pairer {\n private final Function<? super A,?> actualKeyFunction;\n private final Function<? super E,?> expectedKeyFunction;\n Pairer( Function<? super A,?> actualKeyFunction, Function<? super E,?> expectedKeyFunction);\n /** \n * Returns a {@link Pairing} of the given expected and actual values, or {@code null} if theexpected values are not uniquely keyed.\n */\n @Nullable Pairing pair( List<? extends E> expectedValues, List<? extends A> actualValues, Correspondence.ExceptionStore exceptions);\n List<A> pairOne( E expectedValue, Iterable<? extends A> actualValues, Correspondence.ExceptionStore exceptions);\n private @Nullable Object actualKey( A actual, Correspondence.ExceptionStore exceptions);\n private @Nullable Object expectedKey( E expected, Correspondence.ExceptionStore exceptions);\n }\n /** \n * A description of a pairing between expected and actual values. N.B. This is mutable. \n */\nprivate final class Pairing {\n /** \n * Map from keys used in the pairing to the expected value with that key. Iterates in the order the expected values appear in the input. Will never contain null keys.\n */\n private final Map<Object,E> pairedKeysToExpectedValues=new LinkedHashMap<>();\n /** \n * Multimap from keys used in the pairing to the actual values with that key. Keys iterate in the order they first appear in the actual values in the input, and values for each key iterate in the order they appear too. Will never contain null keys.\n */\n private final ListMultimap<Object,A> pairedKeysToActualValues=LinkedListMultimap.create();\n /** \n * List of the expected values not used in the pairing. Iterates in the order they appear in the input.\n */\n private final List<E> unpairedExpectedValues=newArrayList();\n /** \n * List of the actual values not used in the pairing. Iterates in the order they appear in the input.\n */\n private final List<A> unpairedActualValues=newArrayList();\n }\n }\n}\n", "raw_body_no_cmt": "public class IterableSubject extends Subject {\n private final Iterable<?> actual;\n protected IterableSubject( FailureMetadata metadata, Iterable<?> iterable);\n IterableSubject( FailureMetadata metadata, Iterable<?> iterable, String typeDescriptionOverride);\n protected String actualCustomStringRepresentation();\n public void isEqualTo( Object expected);\n public final void isEmpty();\n public final void isNotEmpty();\n public final void hasSize( int expectedSize);\n public final void contains( Object element);\n public final void doesNotContain( Object element);\n public final void containsNoDuplicates();\n public final void containsAnyOf( Object first, Object second, Object... rest);\n public final void containsAnyIn( Iterable<?> expected);\n public final void containsAnyIn( Object[] expected);\n public final Ordered containsAtLeast( Object firstExpected, Object secondExpected, Object... restOfExpected);\n public final Ordered containsAtLeastElementsIn( Iterable<?> expectedIterable);\n public final Ordered containsAtLeastElementsIn( Object[] expected);\n private Ordered failAtLeast( Collection<?> expected, Collection<?> missingRawObjects);\n private static void moveElements( List<?> input, Collection<Object> output, int maxElements);\n public final Ordered containsExactly( Object... varargs);\n public final Ordered containsExactlyElementsIn( Iterable<?> expected);\n /** \n * Checks that a subject contains exactly the provided objects or fails. <p>Multiplicity is respected. For example, an object duplicated exactly 3 times in the array parameter asserts that the object must likewise be duplicated exactly 3 times in the subject. <p>To also test that the contents appear in the given order, make a call to {@code inOrder()}on the object returned by this method.\n */\n public final Ordered containsExactlyElementsIn( Object[] expected);\n private Ordered containsExactlyElementsIn( Iterable<?> required, boolean addElementsInWarning);\n private Ordered failExactly( Iterable<?> required, boolean addElementsInWarning, Collection<?> missingRawObjects, Collection<?> extraRawObjects);\n private static ImmutableList<Fact> makeElementFactsForBoth( String firstKey, Collection<?> firstCollection, String secondKey, Collection<?> secondCollection);\n private static ImmutableList<Fact> makeElementFacts( String label, DuplicateGroupedAndTyped elements, ElementFactGrouping grouping);\n private static String keyToGoWithElementsString( String label, DuplicateGroupedAndTyped elements);\n private static String keyToServeAsHeader( String label, DuplicateGroupedAndTyped elements);\n private static String numberString( int n, int count);\n private static ElementFactGrouping pickGrouping( Iterable<Multiset.Entry<?>> first, Iterable<Multiset.Entry<?>> second);\n private static boolean anyContainsCommaOrNewline( Iterable<Multiset.Entry<?>>... lists);\n private static boolean hasMultiple( Iterable<Multiset.Entry<?>> entries);\n private static boolean containsEmptyOrLong( Iterable<Multiset.Entry<?>> entries);\n enum ElementFactGrouping { ALL_IN_ONE_FACT, FACT_PER_ELEMENT}\n public final void containsNoneOf( Object firstExcluded, Object secondExcluded, Object... restOfExcluded);\n public final void containsNoneIn( Iterable<?> excluded);\n public final void containsNoneIn( Object[] excluded);\n private static final Ordered IN_ORDER=() -> {\n }\n;\n private static final Ordered ALREADY_FAILED=() -> {\n }\n;\n public void isInStrictOrder();\n /** \n * Fails if the iterable is not strictly ordered, according to the given comparator. Strictly ordered means that each element in the iterable is <i>strictly</i> greater than the element that preceded it.\n * @throws ClassCastException if any pair of elements is not mutually Comparable\n */\n public final void isInStrictOrder( Comparator<?> comparator);\n public void isInOrder();\n /** \n * Fails if the iterable is not ordered, according to the given comparator. Ordered means that each element in the iterable is greater than or equal to the element that preceded it.\n * @throws ClassCastException if any pair of elements is not mutually Comparable\n */\n public final void isInOrder( Comparator<?> comparator);\nprivate interface PairwiseChecker {\n boolean check( Object prev, Object next);\n }\n private void pairwiseCheck( String expectedFact, PairwiseChecker checker);\n public void isNoneOf( Object first, Object second, Object... rest);\n public void isNotIn( Iterable<?> iterable);\n private Fact fullContents();\n public <A extends Object,E extends Object>UsingCorrespondence<A,E> comparingElementsUsing( Correspondence<? super A,? super E> correspondence);\n public <T>UsingCorrespondence<T,T> formattingDiffsUsing( DiffFormatter<? super T,? super T> formatter);\n public static class UsingCorrespondence<A extends Object,E extends Object> {\n private final IterableSubject subject;\n private final Correspondence<? super A,? super E> correspondence;\n private final Optional<Pairer> pairer;\n UsingCorrespondence( IterableSubject subject, Correspondence<? super A,? super E> correspondence);\n UsingCorrespondence( IterableSubject subject, Correspondence<? super A,? super E> correspondence, Pairer pairer);\n public final boolean equals( Object o);\n public final int hashCode();\n public final String toString();\n public UsingCorrespondence<A,E> displayingDiffsPairedBy( Function<? super E,?> keyFunction);\n public UsingCorrespondence<A,E> displayingDiffsPairedBy( Function<? super A,?> actualKeyFunction, Function<? super E,?> expectedKeyFunction);\n public void contains( E expected);\n public void doesNotContain( E excluded);\n public final Ordered containsExactly( E... expected);\n public Ordered containsExactlyElementsIn( Iterable<? extends E> expected);\n public Ordered containsExactlyElementsIn( E[] expected);\n private boolean correspondInOrderExactly( Iterator<? extends A> actual, Iterator<? extends E> expected);\n private ImmutableSetMultimap<Integer,Integer> findCandidateMapping( List<? extends A> actual, List<? extends E> expected, Correspondence.ExceptionStore exceptions);\n private boolean failIfCandidateMappingHasMissingOrExtra( List<? extends A> actual, List<? extends E> expected, ImmutableSetMultimap<Integer,Integer> mapping, Correspondence.ExceptionStore exceptions);\n private ImmutableList<Fact> describeMissingOrExtra( List<? extends E> missing, List<? extends A> extra, Correspondence.ExceptionStore exceptions);\n private ImmutableList<Fact> describeMissingOrExtraWithoutPairing( List<? extends E> missing, List<? extends A> extra);\n private ImmutableList<Fact> describeMissingOrExtraWithPairing( Pairing pairing, Correspondence.ExceptionStore exceptions);\n private ImmutableList<Fact> formatExtras( String label, E missing, List<? extends A> extras, Correspondence.ExceptionStore exceptions);\n private <T extends Object>List<T> findNotIndexed( List<T> list, Set<Integer> indexes);\n private ImmutableBiMap<Integer,Integer> findMaximalOneToOneMapping( ImmutableMultimap<Integer,Integer> edges);\n private boolean failIfOneToOneMappingHasMissingOrExtra( List<? extends A> actual, List<? extends E> expected, BiMap<Integer,Integer> mapping, Correspondence.ExceptionStore exceptions);\n public final Ordered containsAtLeast( E first, E second, E... rest);\n public Ordered containsAtLeastElementsIn( Iterable<? extends E> expected);\n public Ordered containsAtLeastElementsIn( E[] expected);\n private boolean correspondInOrderAllIn( Iterator<? extends A> actual, Iterator<? extends E> expected);\n private boolean findCorresponding( Iterator<? extends A> actual, E expectedElement, Correspondence.ExceptionStore exceptions);\n private boolean failIfCandidateMappingHasMissing( List<? extends A> actual, List<? extends E> expected, ImmutableSetMultimap<Integer,Integer> mapping, Correspondence.ExceptionStore exceptions);\n private ImmutableList<Fact> describeMissing( List<? extends E> missing, List<? extends A> extra, Correspondence.ExceptionStore exceptions);\n private ImmutableList<Fact> describeMissingWithoutPairing( List<? extends E> missing);\n private ImmutableList<Fact> describeMissingWithPairing( Pairing pairing, Correspondence.ExceptionStore exceptions);\n private boolean failIfOneToOneMappingHasMissing( List<? extends A> actual, List<? extends E> expected, BiMap<Integer,Integer> mapping, Correspondence.ExceptionStore exceptions);\n public final void containsAnyOf( E first, E second, E... rest);\n public void containsAnyIn( Iterable<? extends E> expected);\n public void containsAnyIn( E[] expected);\n private ImmutableList<Fact> describeAnyMatchesByKey( Pairing pairing, Correspondence.ExceptionStore exceptions);\n public final void containsNoneOf( E firstExcluded, E secondExcluded, E... restOfExcluded);\n public void containsNoneIn( Iterable<? extends E> excluded);\n public void containsNoneIn( E[] excluded);\n private Iterable<A> getCastActual();\n private final class Pairer {\n private final Function<? super A,?> actualKeyFunction;\n private final Function<? super E,?> expectedKeyFunction;\n Pairer( Function<? super A,?> actualKeyFunction, Function<? super E,?> expectedKeyFunction);\n Pairing pair( List<? extends E> expectedValues, List<? extends A> actualValues, Correspondence.ExceptionStore exceptions);\n List<A> pairOne( E expectedValue, Iterable<? extends A> actualValues, Correspondence.ExceptionStore exceptions);\n private Object actualKey( A actual, Correspondence.ExceptionStore exceptions);\n private Object expectedKey( E expected, Correspondence.ExceptionStore exceptions);\n }\n private final class Pairing {\n private final Map<Object,E> pairedKeysToExpectedValues=new LinkedHashMap<>();\n private final ListMultimap<Object,A> pairedKeysToActualValues=LinkedListMultimap.create();\n private final List<E> unpairedExpectedValues=newArrayList();\n private final List<A> unpairedActualValues=newArrayList();\n }\n }\n}\n"}}, {"LazyMessage": {"retrieved_name": "LazyMessage", "raw_body": "final class LazyMessage {\n private final String format;\n private final Object[] args;\n LazyMessage( String format, Object... args);\n @Override public String toString();\n @VisibleForTesting static int countPlaceholders( String template);\n static ImmutableList<String> evaluateAll( ImmutableList<LazyMessage> messages);\n}\n", "raw_body_no_cmt": "final class LazyMessage {\n private final String format;\n private final Object[] args;\n LazyMessage( String format, Object... args);\n public String toString();\n static int countPlaceholders( String template);\n static ImmutableList<String> evaluateAll( ImmutableList<LazyMessage> messages);\n}\n"}}] | [{"toString": {"retrieved_name": "toString", "raw_body": "@Override public final String toString(){\n return description();\n}\n"}}, {"add": {"retrieved_name": "add", "raw_body": "void add(E element){\n contents.add(EQUALITY_WITHOUT_USING_HASH_CODE.wrap(element));\n}\n"}}, {"builder": {"retrieved_name": "builder", "raw_body": "static Builder builder(String name){\n return new AutoValue_ActualValueInference_Invocation.Builder().setName(name);\n}\n"}}, {"build": {"retrieved_name": "build", "raw_body": "@Override FluentEqualityConfig build(){\n if (set$0 != 7 || this.ignoreFieldAbsenceScope == null || this.ignoreRepeatedFieldOrderScope == null || this.ignoreExtraRepeatedFieldElementsScope == null || this.doubleCorrespondenceMap == null || this.floatCorrespondenceMap == null || this.compareFieldsScope == null || this.useTypeRegistry == null || this.useExtensionRegistry == null || this.usingCorrespondenceStringFunction == null) {\n StringBuilder missing=new StringBuilder();\n if (this.ignoreFieldAbsenceScope == null) {\n missing.append(\" ignoreFieldAbsenceScope\");\n }\n if (this.ignoreRepeatedFieldOrderScope == null) {\n missing.append(\" ignoreRepeatedFieldOrderScope\");\n }\n if (this.ignoreExtraRepeatedFieldElementsScope == null) {\n missing.append(\" ignoreExtraRepeatedFieldElementsScope\");\n }\n if (this.doubleCorrespondenceMap == null) {\n missing.append(\" doubleCorrespondenceMap\");\n }\n if (this.floatCorrespondenceMap == null) {\n missing.append(\" floatCorrespondenceMap\");\n }\n if ((set$0 & 1) == 0) {\n missing.append(\" compareExpectedFieldsOnly\");\n }\n if ((set$0 & 2) == 0) {\n missing.append(\" hasExpectedMessages\");\n }\n if (this.compareFieldsScope == null) {\n missing.append(\" compareFieldsScope\");\n }\n if ((set$0 & 4) == 0) {\n missing.append(\" reportMismatchesOnly\");\n }\n if (this.useTypeRegistry == null) {\n missing.append(\" useTypeRegistry\");\n }\n if (this.useExtensionRegistry == null) {\n missing.append(\" useExtensionRegistry\");\n }\n if (this.usingCorrespondenceStringFunction == null) {\n missing.append(\" usingCorrespondenceStringFunction\");\n }\n throw new IllegalStateException(\"Missing required properties:\" + missing);\n }\n return new AutoValue_FluentEqualityConfig(this.ignoreFieldAbsenceScope,this.ignoreRepeatedFieldOrderScope,this.ignoreExtraRepeatedFieldElementsScope,this.doubleCorrespondenceMap,this.floatCorrespondenceMap,this.compareExpectedFieldsOnly,this.hasExpectedMessages,this.compareFieldsScope,this.reportMismatchesOnly,this.useTypeRegistry,this.useExtensionRegistry,this.usingCorrespondenceStringFunction);\n}\n"}}] | [{"evaluateAll": {"retrieved_name": "evaluateAll", "raw_body": "static ImmutableList<String> evaluateAll(ImmutableList<LazyMessage> messages){\n ImmutableList.Builder<String> result=ImmutableList.builder();\n for ( LazyMessage message : messages) {\n result.add(message.toString());\n }\n return result.build();\n}\n"}}] |
|
mapstruct_mapstruct | mapstruct/processor/src/main/java/org/mapstruct/ap/internal/model/assignment/WrapperForCollectionsAndMaps.java | WrapperForCollectionsAndMaps | getThrownTypes | class WrapperForCollectionsAndMaps extends AssignmentWrapper {
private final List<Type> thrownTypesToExclude;
private final String nullCheckLocalVarName;
private final Type nullCheckLocalVarType;
public WrapperForCollectionsAndMaps(Assignment rhs,
List<Type> thrownTypesToExclude,
Type targetType,
boolean fieldAssignment) {
super( rhs, fieldAssignment );
this.thrownTypesToExclude = thrownTypesToExclude;
if ( rhs.getType() == AssignmentType.DIRECT && rhs.getSourceType() != null ) {
this.nullCheckLocalVarType = rhs.getSourceType();
}
else {
this.nullCheckLocalVarType = targetType;
}
this.nullCheckLocalVarName = rhs.createUniqueVarName( nullCheckLocalVarType.getName() );
}
@Override
public List<Type> getThrownTypes() {<FILL_FUNCTION_BODY>}
public String getNullCheckLocalVarName() {
return nullCheckLocalVarName;
}
public Type getNullCheckLocalVarType() {
return nullCheckLocalVarType;
}
} |
List<Type> parentThrownTypes = super.getThrownTypes();
List<Type> result = new ArrayList<>( parentThrownTypes );
for ( Type thrownTypeToExclude : thrownTypesToExclude ) {
for ( Type parentThrownType : parentThrownTypes ) {
if ( parentThrownType.isAssignableTo( thrownTypeToExclude ) ) {
result.remove( parentThrownType );
}
}
}
return result;
| /**
* Base class for decorators (wrappers). Decorator pattern is used to decorate assignments.
* @author Sjaak Derksen
*/
public abstract class AssignmentWrapper extends ModelElement implements Assignment {
private final Assignment decoratedAssignment;
protected final boolean fieldAssignment;
public AssignmentWrapper( Assignment decoratedAssignment, boolean fieldAssignment);
@Override public Set<Type> getImportTypes();
@Override public List<Type> getThrownTypes();
@Override public void setAssignment( Assignment assignment);
public Assignment getAssignment();
@Override public String getSourceReference();
@Override public boolean isSourceReferenceParameter();
@Override public PresenceCheck getSourcePresenceCheckerReference();
@Override public Type getSourceType();
@Override public String getSourceLocalVarName();
@Override public void setSourceLocalVarName( String sourceLocalVarName);
@Override public String getSourceLoopVarName();
@Override public void setSourceLoopVarName( String sourceLoopVarName);
@Override public String getSourceParameterName();
@Override public AssignmentType getType();
@Override public boolean isCallingUpdateMethod();
@Override public String createUniqueVarName( String desiredName);
/**
* @return {@code true} if the wrapper is for field assignment
*/
public boolean isFieldAssignment();
}
|
return thrownTypesToExclude;
| [
"List<Type>"
] | [] | [
"List<Type>",
"Type"
] | [
"remove",
"isAssignableTo"
] | {
"methods": [],
"similar_methods": [
"getThrownTypes"
],
"types": [
"List<Type>"
]
} | public class List {
}
public List<Type> getThrownTypes(){
return thrownTypes;
}
| public class List {
}
public List<Type> getThrownTypes(){
return thrownTypes;
}
| {"types": [{"List<Type>": "List"}], "similar_methods": [{"getThrownTypes": "getThrownTypes"}]} | [{"List<Type>": {"retrieved_name": "List", "raw_body": "public class List {\n}\n", "raw_body_no_cmt": "public class List {\n}\n"}}] | [] | [{"getThrownTypes": {"retrieved_name": "getThrownTypes", "raw_body": "public List<Type> getThrownTypes(){\n return thrownTypes;\n}\n"}}] |
elunez_eladmin | eladmin/eladmin-system/src/main/java/me/zhengjie/modules/mnt/service/impl/DeployHistoryServiceImpl.java | DeployHistoryServiceImpl | download | class DeployHistoryServiceImpl implements DeployHistoryService {
private final DeployHistoryRepository deployhistoryRepository;
private final DeployHistoryMapper deployhistoryMapper;
@Override
public PageResult<DeployHistoryDto> queryAll(DeployHistoryQueryCriteria criteria, Pageable pageable){
Page<DeployHistory> page = deployhistoryRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
return PageUtil.toPage(page.map(deployhistoryMapper::toDto));
}
@Override
public List<DeployHistoryDto> queryAll(DeployHistoryQueryCriteria criteria){
return deployhistoryMapper.toDto(deployhistoryRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
}
@Override
public DeployHistoryDto findById(String id) {
DeployHistory deployhistory = deployhistoryRepository.findById(id).orElseGet(DeployHistory::new);
ValidationUtil.isNull(deployhistory.getId(),"DeployHistory","id",id);
return deployhistoryMapper.toDto(deployhistory);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void create(DeployHistory resources) {
resources.setId(IdUtil.simpleUUID());
deployhistoryRepository.save(resources);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void delete(Set<String> ids) {
for (String id : ids) {
deployhistoryRepository.deleteById(id);
}
}
@Override
public void download(List<DeployHistoryDto> queryAll, HttpServletResponse response) throws IOException {<FILL_FUNCTION_BODY>}
} |
List<Map<String, Object>> list = new ArrayList<>();
for (DeployHistoryDto deployHistoryDto : queryAll) {
Map<String,Object> map = new LinkedHashMap<>();
map.put("部署编号", deployHistoryDto.getDeployId());
map.put("应用名称", deployHistoryDto.getAppName());
map.put("部署IP", deployHistoryDto.getIp());
map.put("部署时间", deployHistoryDto.getDeployDate());
map.put("部署人员", deployHistoryDto.getDeployUser());
list.add(map);
}
FileUtil.downloadExcel(list, response);
|
List<Map<String, Object>> list = new ArrayList<>();
for (DeployHistoryDto deployhistory : queryAll) {
Map<String,Object> map = new LinkedHashMap<>();
map.put("部署编号", deployhistory.getId());
map.put("部署时间", deployhistory.getDeployTime());
map.put("部署人", deployhistory.getUsername());
map.put("部署地址", deployhistory.getAddress());
map.put("部署内容", deployhistory.getDeployDesc());
list.add(map);
}
FileUtil.downloadExcel(list, response);
| [
"List<DeployHistoryDto>",
"DeployHistoryDto",
"HttpServletResponse",
"Map<String,Object>",
"List<Map<String,Object>>"
] | [
"add",
"put",
"getId",
"getDeployDesc",
"getAddress",
"getDeployTime",
"getUsername",
"downloadExcel"
] | [
"HttpServletResponse",
"List<DeployHistoryDto>",
"List<Map<String,Object>>",
"Map<String,Object>",
"DeployHistoryDto"
] | [
"getDeployId",
"add",
"getIp",
"getDeployUser",
"getAppName",
"downloadExcel",
"put",
"getDeployDate"
] | {
"methods": [
"add",
"put",
"getId",
"getDeployDesc",
"getAddress",
"getDeployTime",
"getUsername",
"downloadExcel"
],
"similar_methods": [
"download"
],
"types": [
"List<DeployHistoryDto>",
"DeployHistoryDto",
"HttpServletResponse",
"Map<String,Object>",
"List<Map<String,Object>>"
]
} | /**
* @author zhanghouying
* @date 2019-08-24
*/
@Data public class DeployHistoryDto implements Serializable {
/**
* 编号
*/
private String id;
/**
* 应用名称
*/
private String appName;
/**
* 部署IP
*/
private String ip;
/**
* 部署时间
*/
private Timestamp deployDate;
/**
* 部署人员
*/
private String deployUser;
/**
* 部署编号
*/
private Long deployId;
}
/**
* @author ZhangHouYing
* @date 2019-08-10 15:46
*/
@ServerEndpoint("/webSocket/{sid}") @Slf4j @Component public class WebSocketServer {
/**
* concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
*/
private static final CopyOnWriteArraySet<WebSocketServer> webSocketSet=new CopyOnWriteArraySet<WebSocketServer>();
/**
* 与某个客户端的连接会话,需要通过它来给客户端发送数据
*/
private Session session;
/**
* 接收sid
*/
private String sid="";
/**
* 连接建立成功调用的方法
*/
@OnOpen public void onOpen( Session session, @PathParam("sid") String sid);
/**
* 连接关闭调用的方法
*/
@OnClose public void onClose();
/**
* 收到客户端消息后调用的方法
* @param message 客户端发送过来的消息
*/
@OnMessage public void onMessage( String message, Session session);
@OnError public void onError( Session session, Throwable error);
/**
* 实现服务器主动推送
*/
private void sendMessage( String message) throws IOException;
/**
* 群发自定义消息
*/
public static void sendInfo( SocketMsg socketMsg, @PathParam("sid") String sid) throws IOException;
@Override public boolean equals( Object o);
@Override public int hashCode();
}
/**
* @author Zheng Jie
* @date 2019-04-10
*/
@Mapper(componentModel="spring",unmappedTargetPolicy=ReportingPolicy.IGNORE) public interface DictMapper extends BaseMapper<DictDto,Dict> {
}
/**
* 针对 某些初始化方法,在SpringContextHolder 未初始化时 提交回调方法。 在SpringContextHolder 初始化后,进行回调使用
* @param callBack 回调函数
*/
public synchronized static void addCallBacks(CallBack callBack){
if (addCallback) {
SpringContextHolder.CALL_BACKS.add(callBack);
}
else {
log.warn("CallBack:{} 已无法添加!立即执行",callBack.getCallBackName());
callBack.executor();
}
}
public void putFile(String localFile,String remoteFileName,String remoteTargetDirectory){
putFile(localFile,remoteFileName,remoteTargetDirectory,null);
}
/**
* 获取ip地址
*/
public static String getIp(HttpServletRequest request){
String ip=request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip=request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip=request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip=request.getRemoteAddr();
}
String comma=",";
String localhost="127.0.0.1";
if (ip.contains(comma)) {
ip=ip.split(",")[0];
}
if (localhost.equals(ip)) {
try {
ip=InetAddress.getLocalHost().getHostAddress();
}
catch ( UnknownHostException e) {
log.error(e.getMessage(),e);
}
}
return ip;
}
public String getDesc(){
return desc;
}
/**
* 获取ip地址
*/
public static String getIp(HttpServletRequest request){
String ip=request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip=request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip=request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip=request.getRemoteAddr();
}
String comma=",";
String localhost="127.0.0.1";
if (ip.contains(comma)) {
ip=ip.split(",")[0];
}
if (localhost.equals(ip)) {
try {
ip=InetAddress.getLocalHost().getHostAddress();
}
catch ( UnknownHostException e) {
log.error(e.getMessage(),e);
}
}
return ip;
}
/**
* 部署文件到服务器
* @param fileSavePath 文件路径
* @param appId 应用ID
*/
void deploy(String fileSavePath,Long appId);
public String getUsername(){
try {
return SecurityUtils.getCurrentUsername();
}
catch ( Exception e) {
return "";
}
}
/**
* 导出excel
*/
public static void downloadExcel(List<Map<String,Object>> list,HttpServletResponse response) throws IOException {
String tempPath=SYS_TEM_DIR + IdUtil.fastSimpleUUID() + ".xlsx";
File file=new File(tempPath);
BigExcelWriter writer=ExcelUtil.getBigWriter(file);
writer.write(list,true);
SXSSFSheet sheet=(SXSSFSheet)writer.getSheet();
sheet.trackAllColumnsForAutoSizing();
writer.autoSizeColumnAll();
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
response.setHeader("Content-Disposition","attachment;filename=file.xlsx");
ServletOutputStream out=response.getOutputStream();
file.deleteOnExit();
writer.flush(out,true);
IoUtil.close(out);
}
@Override public void download(List<AppDto> queryAll,HttpServletResponse response) throws IOException {
List<Map<String,Object>> list=new ArrayList<>();
for ( AppDto appDto : queryAll) {
Map<String,Object> map=new LinkedHashMap<>();
map.put("应用名称",appDto.getName());
map.put("端口",appDto.getPort());
map.put("上传目录",appDto.getUploadPath());
map.put("部署目录",appDto.getDeployPath());
map.put("备份目录",appDto.getBackupPath());
map.put("启动脚本",appDto.getStartScript());
map.put("部署脚本",appDto.getDeployScript());
map.put("创建日期",appDto.getCreateTime());
list.add(map);
}
FileUtil.downloadExcel(list,response);
}
| public class DeployHistoryDto implements Serializable {
private String id;
private String appName;
private String ip;
private Timestamp deployDate;
private String deployUser;
private Long deployId;
}
public class WebSocketServer {
private static final CopyOnWriteArraySet<WebSocketServer> webSocketSet=new CopyOnWriteArraySet<WebSocketServer>();
private Session session;
private String sid="";
public void onOpen( Session session, String sid);
public void onClose();
public void onMessage( String message, Session session);
public void onError( Session session, Throwable error);
private void sendMessage( String message) throws IOException;
public static void sendInfo( SocketMsg socketMsg, String sid) throws IOException;
public boolean equals( Object o);
public int hashCode();
}
public interface DictMapper extends BaseMapper<DictDto,Dict> {
}
/**
* 针对 某些初始化方法,在SpringContextHolder 未初始化时 提交回调方法。 在SpringContextHolder 初始化后,进行回调使用
* @param callBack 回调函数
*/
public synchronized static void addCallBacks(CallBack callBack){
if (addCallback) {
SpringContextHolder.CALL_BACKS.add(callBack);
}
else {
log.warn("CallBack:{} 已无法添加!立即执行",callBack.getCallBackName());
callBack.executor();
}
}
public void putFile(String localFile,String remoteFileName,String remoteTargetDirectory){
putFile(localFile,remoteFileName,remoteTargetDirectory,null);
}
/**
* 获取ip地址
*/
public static String getIp(HttpServletRequest request){
String ip=request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip=request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip=request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip=request.getRemoteAddr();
}
String comma=",";
String localhost="127.0.0.1";
if (ip.contains(comma)) {
ip=ip.split(",")[0];
}
if (localhost.equals(ip)) {
try {
ip=InetAddress.getLocalHost().getHostAddress();
}
catch ( UnknownHostException e) {
log.error(e.getMessage(),e);
}
}
return ip;
}
public String getDesc(){
return desc;
}
/**
* 获取ip地址
*/
public static String getIp(HttpServletRequest request){
String ip=request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip=request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip=request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip=request.getRemoteAddr();
}
String comma=",";
String localhost="127.0.0.1";
if (ip.contains(comma)) {
ip=ip.split(",")[0];
}
if (localhost.equals(ip)) {
try {
ip=InetAddress.getLocalHost().getHostAddress();
}
catch ( UnknownHostException e) {
log.error(e.getMessage(),e);
}
}
return ip;
}
/**
* 部署文件到服务器
* @param fileSavePath 文件路径
* @param appId 应用ID
*/
void deploy(String fileSavePath,Long appId);
public String getUsername(){
try {
return SecurityUtils.getCurrentUsername();
}
catch ( Exception e) {
return "";
}
}
/**
* 导出excel
*/
public static void downloadExcel(List<Map<String,Object>> list,HttpServletResponse response) throws IOException {
String tempPath=SYS_TEM_DIR + IdUtil.fastSimpleUUID() + ".xlsx";
File file=new File(tempPath);
BigExcelWriter writer=ExcelUtil.getBigWriter(file);
writer.write(list,true);
SXSSFSheet sheet=(SXSSFSheet)writer.getSheet();
sheet.trackAllColumnsForAutoSizing();
writer.autoSizeColumnAll();
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
response.setHeader("Content-Disposition","attachment;filename=file.xlsx");
ServletOutputStream out=response.getOutputStream();
file.deleteOnExit();
writer.flush(out,true);
IoUtil.close(out);
}
@Override public void download(List<AppDto> queryAll,HttpServletResponse response) throws IOException {
List<Map<String,Object>> list=new ArrayList<>();
for ( AppDto appDto : queryAll) {
Map<String,Object> map=new LinkedHashMap<>();
map.put("应用名称",appDto.getName());
map.put("端口",appDto.getPort());
map.put("上传目录",appDto.getUploadPath());
map.put("部署目录",appDto.getDeployPath());
map.put("备份目录",appDto.getBackupPath());
map.put("启动脚本",appDto.getStartScript());
map.put("部署脚本",appDto.getDeployScript());
map.put("创建日期",appDto.getCreateTime());
list.add(map);
}
FileUtil.downloadExcel(list,response);
}
| {"types": [{"List<DeployHistoryDto>": "DeployHistoryDto"}, {"DeployHistoryDto": "DeployHistoryDto"}, {"HttpServletResponse": "WebSocketServer"}, {"Map<String,Object>": "DictMapper"}, {"List<Map<String,Object>>": "DictMapper"}], "methods": [{"add": "addCallBacks"}, {"put": "putFile"}, {"getId": "getIp"}, {"getDeployDesc": "getDesc"}, {"getAddress": "getIp"}, {"getDeployTime": "deploy"}, {"getUsername": "getUsername"}, {"downloadExcel": "downloadExcel"}], "similar_methods": [{"download": "download"}]} | [{"List<DeployHistoryDto>": {"retrieved_name": "DeployHistoryDto", "raw_body": "/** \n * @author zhanghouying\n * @date 2019-08-24\n */\n@Data public class DeployHistoryDto implements Serializable {\n /** \n * \u7f16\u53f7\n */\n private String id;\n /** \n * \u5e94\u7528\u540d\u79f0\n */\n private String appName;\n /** \n * \u90e8\u7f72IP\n */\n private String ip;\n /** \n * \u90e8\u7f72\u65f6\u95f4\n */\n private Timestamp deployDate;\n /** \n * \u90e8\u7f72\u4eba\u5458\n */\n private String deployUser;\n /** \n * \u90e8\u7f72\u7f16\u53f7\n */\n private Long deployId;\n}\n", "raw_body_no_cmt": "public class DeployHistoryDto implements Serializable {\n private String id;\n private String appName;\n private String ip;\n private Timestamp deployDate;\n private String deployUser;\n private Long deployId;\n}\n"}}, {"HttpServletResponse": {"retrieved_name": "WebSocketServer", "raw_body": "/** \n * @author ZhangHouYing\n * @date 2019-08-10 15:46\n */\n@ServerEndpoint(\"/webSocket/{sid}\") @Slf4j @Component public class WebSocketServer {\n /** \n * concurrent\u5305\u7684\u7ebf\u7a0b\u5b89\u5168Set\uff0c\u7528\u6765\u5b58\u653e\u6bcf\u4e2a\u5ba2\u6237\u7aef\u5bf9\u5e94\u7684MyWebSocket\u5bf9\u8c61\u3002\n */\n private static final CopyOnWriteArraySet<WebSocketServer> webSocketSet=new CopyOnWriteArraySet<WebSocketServer>();\n /** \n * \u4e0e\u67d0\u4e2a\u5ba2\u6237\u7aef\u7684\u8fde\u63a5\u4f1a\u8bdd\uff0c\u9700\u8981\u901a\u8fc7\u5b83\u6765\u7ed9\u5ba2\u6237\u7aef\u53d1\u9001\u6570\u636e\n */\n private Session session;\n /** \n * \u63a5\u6536sid\n */\n private String sid=\"\";\n /** \n * \u8fde\u63a5\u5efa\u7acb\u6210\u529f\u8c03\u7528\u7684\u65b9\u6cd5\n */\n @OnOpen public void onOpen( Session session, @PathParam(\"sid\") String sid);\n /** \n * \u8fde\u63a5\u5173\u95ed\u8c03\u7528\u7684\u65b9\u6cd5\n */\n @OnClose public void onClose();\n /** \n * \u6536\u5230\u5ba2\u6237\u7aef\u6d88\u606f\u540e\u8c03\u7528\u7684\u65b9\u6cd5\n * @param message \u5ba2\u6237\u7aef\u53d1\u9001\u8fc7\u6765\u7684\u6d88\u606f\n */\n @OnMessage public void onMessage( String message, Session session);\n @OnError public void onError( Session session, Throwable error);\n /** \n * \u5b9e\u73b0\u670d\u52a1\u5668\u4e3b\u52a8\u63a8\u9001\n */\n private void sendMessage( String message) throws IOException;\n /** \n * \u7fa4\u53d1\u81ea\u5b9a\u4e49\u6d88\u606f\n */\n public static void sendInfo( SocketMsg socketMsg, @PathParam(\"sid\") String sid) throws IOException;\n @Override public boolean equals( Object o);\n @Override public int hashCode();\n}\n", "raw_body_no_cmt": "public class WebSocketServer {\n private static final CopyOnWriteArraySet<WebSocketServer> webSocketSet=new CopyOnWriteArraySet<WebSocketServer>();\n private Session session;\n private String sid=\"\";\n public void onOpen( Session session, String sid);\n public void onClose();\n public void onMessage( String message, Session session);\n public void onError( Session session, Throwable error);\n private void sendMessage( String message) throws IOException;\n public static void sendInfo( SocketMsg socketMsg, String sid) throws IOException;\n public boolean equals( Object o);\n public int hashCode();\n}\n"}}, {"Map<String,Object>": {"retrieved_name": "DictMapper", "raw_body": "/** \n * @author Zheng Jie\n * @date 2019-04-10\n */\n@Mapper(componentModel=\"spring\",unmappedTargetPolicy=ReportingPolicy.IGNORE) public interface DictMapper extends BaseMapper<DictDto,Dict> {\n}\n", "raw_body_no_cmt": "public interface DictMapper extends BaseMapper<DictDto,Dict> {\n}\n"}}] | [{"add": {"retrieved_name": "addCallBacks", "raw_body": "/** \n * \u9488\u5bf9 \u67d0\u4e9b\u521d\u59cb\u5316\u65b9\u6cd5\uff0c\u5728SpringContextHolder \u672a\u521d\u59cb\u5316\u65f6 \u63d0\u4ea4\u56de\u8c03\u65b9\u6cd5\u3002 \u5728SpringContextHolder \u521d\u59cb\u5316\u540e\uff0c\u8fdb\u884c\u56de\u8c03\u4f7f\u7528\n * @param callBack \u56de\u8c03\u51fd\u6570\n */\npublic synchronized static void addCallBacks(CallBack callBack){\n if (addCallback) {\n SpringContextHolder.CALL_BACKS.add(callBack);\n }\n else {\n log.warn(\"CallBack\uff1a{} \u5df2\u65e0\u6cd5\u6dfb\u52a0\uff01\u7acb\u5373\u6267\u884c\",callBack.getCallBackName());\n callBack.executor();\n }\n}\n"}}, {"put": {"retrieved_name": "putFile", "raw_body": "public void putFile(String localFile,String remoteFileName,String remoteTargetDirectory){\n putFile(localFile,remoteFileName,remoteTargetDirectory,null);\n}\n"}}, {"getId": {"retrieved_name": "getIp", "raw_body": "/** \n * \u83b7\u53d6ip\u5730\u5740\n */\npublic static String getIp(HttpServletRequest request){\n String ip=request.getHeader(\"x-forwarded-for\");\n if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {\n ip=request.getHeader(\"Proxy-Client-IP\");\n }\n if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {\n ip=request.getHeader(\"WL-Proxy-Client-IP\");\n }\n if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {\n ip=request.getRemoteAddr();\n }\n String comma=\",\";\n String localhost=\"127.0.0.1\";\n if (ip.contains(comma)) {\n ip=ip.split(\",\")[0];\n }\n if (localhost.equals(ip)) {\n try {\n ip=InetAddress.getLocalHost().getHostAddress();\n }\n catch ( UnknownHostException e) {\n log.error(e.getMessage(),e);\n }\n }\n return ip;\n}\n"}}, {"getDeployDesc": {"retrieved_name": "getDesc", "raw_body": "public String getDesc(){\n return desc;\n}\n"}}, {"getAddress": {"retrieved_name": "getIp", "raw_body": "/** \n * \u83b7\u53d6ip\u5730\u5740\n */\npublic static String getIp(HttpServletRequest request){\n String ip=request.getHeader(\"x-forwarded-for\");\n if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {\n ip=request.getHeader(\"Proxy-Client-IP\");\n }\n if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {\n ip=request.getHeader(\"WL-Proxy-Client-IP\");\n }\n if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {\n ip=request.getRemoteAddr();\n }\n String comma=\",\";\n String localhost=\"127.0.0.1\";\n if (ip.contains(comma)) {\n ip=ip.split(\",\")[0];\n }\n if (localhost.equals(ip)) {\n try {\n ip=InetAddress.getLocalHost().getHostAddress();\n }\n catch ( UnknownHostException e) {\n log.error(e.getMessage(),e);\n }\n }\n return ip;\n}\n"}}, {"getDeployTime": {"retrieved_name": "deploy", "raw_body": "/** \n * \u90e8\u7f72\u6587\u4ef6\u5230\u670d\u52a1\u5668\n * @param fileSavePath \u6587\u4ef6\u8def\u5f84\n * @param appId \u5e94\u7528ID\n */\nvoid deploy(String fileSavePath,Long appId);\n"}}, {"getUsername": {"retrieved_name": "getUsername", "raw_body": "public String getUsername(){\n try {\n return SecurityUtils.getCurrentUsername();\n }\n catch ( Exception e) {\n return \"\";\n }\n}\n"}}, {"downloadExcel": {"retrieved_name": "downloadExcel", "raw_body": "/** \n * \u5bfc\u51faexcel\n */\npublic static void downloadExcel(List<Map<String,Object>> list,HttpServletResponse response) throws IOException {\n String tempPath=SYS_TEM_DIR + IdUtil.fastSimpleUUID() + \".xlsx\";\n File file=new File(tempPath);\n BigExcelWriter writer=ExcelUtil.getBigWriter(file);\n writer.write(list,true);\n SXSSFSheet sheet=(SXSSFSheet)writer.getSheet();\n sheet.trackAllColumnsForAutoSizing();\n writer.autoSizeColumnAll();\n response.setContentType(\"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8\");\n response.setHeader(\"Content-Disposition\",\"attachment;filename=file.xlsx\");\n ServletOutputStream out=response.getOutputStream();\n file.deleteOnExit();\n writer.flush(out,true);\n IoUtil.close(out);\n}\n"}}] | [{"download": {"retrieved_name": "download", "raw_body": "@Override public void download(List<AppDto> queryAll,HttpServletResponse response) throws IOException {\n List<Map<String,Object>> list=new ArrayList<>();\n for ( AppDto appDto : queryAll) {\n Map<String,Object> map=new LinkedHashMap<>();\n map.put(\"\u5e94\u7528\u540d\u79f0\",appDto.getName());\n map.put(\"\u7aef\u53e3\",appDto.getPort());\n map.put(\"\u4e0a\u4f20\u76ee\u5f55\",appDto.getUploadPath());\n map.put(\"\u90e8\u7f72\u76ee\u5f55\",appDto.getDeployPath());\n map.put(\"\u5907\u4efd\u76ee\u5f55\",appDto.getBackupPath());\n map.put(\"\u542f\u52a8\u811a\u672c\",appDto.getStartScript());\n map.put(\"\u90e8\u7f72\u811a\u672c\",appDto.getDeployScript());\n map.put(\"\u521b\u5efa\u65e5\u671f\",appDto.getCreateTime());\n list.add(map);\n }\n FileUtil.downloadExcel(list,response);\n}\n"}}] |
|
orientechnologies_orientdb | orientdb/core/src/main/java/com/orientechnologies/orient/core/sql/executor/OIfExecutionPlan.java | OIfExecutionPlan | toResult | class OIfExecutionPlan implements OInternalExecutionPlan {
private String location;
private final OCommandContext ctx;
@Override
public OCommandContext getContext() {
return ctx;
}
protected IfStep step;
public OIfExecutionPlan(OCommandContext ctx) {
this.ctx = ctx;
}
@Override
public void reset(OCommandContext ctx) {
// TODO
throw new UnsupportedOperationException();
}
@Override
public void close() {
step.close();
}
@Override
public OExecutionStream start() {
return step.start(ctx);
}
@Override
public String prettyPrint(int depth, int indent) {
StringBuilder result = new StringBuilder();
result.append(step.prettyPrint(depth, indent));
return result.toString();
}
public void chain(IfStep step) {
this.step = step;
}
@Override
public List<OExecutionStep> getSteps() {
// TODO do a copy of the steps
return Collections.singletonList(step);
}
public void setSteps(List<OExecutionStepInternal> steps) {
this.step = (IfStep) steps.get(0);
}
@Override
public OResult toResult() {<FILL_FUNCTION_BODY>}
@Override
public long getCost() {
return 0l;
}
@Override
public boolean canBeCached() {
return false;
}
public OExecutionStepInternal executeUntilReturn() {
OScriptExecutionPlan plan = step.producePlan(ctx);
if (plan != null) {
return plan.executeUntilReturn();
} else {
return null;
}
}
public boolean containsReturn() {
return step.containsReturn();
}
} |
OResultInternal result = new OResultInternal();
result.setProperty("type", "IfExecutionPlan");
result.setProperty("javaType", getClass().getName());
result.setProperty("cost", getCost());
result.setProperty("prettyPrint", prettyPrint(0, 2));
result.setProperty("steps", Collections.singletonList(step.toResult()));
return result;
|
return new OResult(step.getResult());
| [
"IfStep"
] | [
"getResult"
] | [
"List<OExecutionStepInternal>",
"OResultInternal",
"IfStep"
] | [
"getName",
"singletonList",
"setProperty",
"toResult"
] | {
"methods": [
"getResult"
],
"similar_methods": [
"toResult"
],
"types": [
"IfStep"
]
} | /**
* Created by luigidellaquila on 19/09/16.
*/
public class IfStep extends AbstractExecutionStep {
protected OBooleanExpression condition;
public List<OStatement> positiveStatements;
public List<OStatement> negativeStatements;
public IfStep( OCommandContext ctx, boolean profilingEnabled);
@Override public OExecutionStream internalStart( OCommandContext ctx) throws OTimeoutException;
public OScriptExecutionPlan producePlan( OCommandContext ctx);
public OScriptExecutionPlan initPositivePlan( OCommandContext ctx);
public OScriptExecutionPlan initNegativePlan( OCommandContext ctx);
public OBooleanExpression getCondition();
public void setCondition( OBooleanExpression condition);
public boolean containsReturn();
private boolean containsReturn( OStatement stm);
}
public RET getResult(){
return result;
}
protected Object toResult(OIdentifiable nextElement){
return new OResultInternal(nextElement);
}
| public class IfStep extends AbstractExecutionStep {
protected OBooleanExpression condition;
public List<OStatement> positiveStatements;
public List<OStatement> negativeStatements;
public IfStep( OCommandContext ctx, boolean profilingEnabled);
public OExecutionStream internalStart( OCommandContext ctx) throws OTimeoutException;
public OScriptExecutionPlan producePlan( OCommandContext ctx);
public OScriptExecutionPlan initPositivePlan( OCommandContext ctx);
public OScriptExecutionPlan initNegativePlan( OCommandContext ctx);
public OBooleanExpression getCondition();
public void setCondition( OBooleanExpression condition);
public boolean containsReturn();
private boolean containsReturn( OStatement stm);
}
public RET getResult(){
return result;
}
protected Object toResult(OIdentifiable nextElement){
return new OResultInternal(nextElement);
}
| {"types": [{"IfStep": "IfStep"}], "methods": [{"getResult": "getResult"}], "similar_methods": [{"toResult": "toResult"}]} | [{"IfStep": {"retrieved_name": "IfStep", "raw_body": "/** \n * Created by luigidellaquila on 19/09/16. \n */\npublic class IfStep extends AbstractExecutionStep {\n protected OBooleanExpression condition;\n public List<OStatement> positiveStatements;\n public List<OStatement> negativeStatements;\n public IfStep( OCommandContext ctx, boolean profilingEnabled);\n @Override public OExecutionStream internalStart( OCommandContext ctx) throws OTimeoutException;\n public OScriptExecutionPlan producePlan( OCommandContext ctx);\n public OScriptExecutionPlan initPositivePlan( OCommandContext ctx);\n public OScriptExecutionPlan initNegativePlan( OCommandContext ctx);\n public OBooleanExpression getCondition();\n public void setCondition( OBooleanExpression condition);\n public boolean containsReturn();\n private boolean containsReturn( OStatement stm);\n}\n", "raw_body_no_cmt": "public class IfStep extends AbstractExecutionStep {\n protected OBooleanExpression condition;\n public List<OStatement> positiveStatements;\n public List<OStatement> negativeStatements;\n public IfStep( OCommandContext ctx, boolean profilingEnabled);\n public OExecutionStream internalStart( OCommandContext ctx) throws OTimeoutException;\n public OScriptExecutionPlan producePlan( OCommandContext ctx);\n public OScriptExecutionPlan initPositivePlan( OCommandContext ctx);\n public OScriptExecutionPlan initNegativePlan( OCommandContext ctx);\n public OBooleanExpression getCondition();\n public void setCondition( OBooleanExpression condition);\n public boolean containsReturn();\n private boolean containsReturn( OStatement stm);\n}\n"}}] | [{"getResult": {"retrieved_name": "getResult", "raw_body": "public RET getResult(){\n return result;\n}\n"}}] | [{"toResult": {"retrieved_name": "toResult", "raw_body": "protected Object toResult(OIdentifiable nextElement){\n return new OResultInternal(nextElement);\n}\n"}}] |
|
pmd_pmd | pmd/pmd-kotlin/src/main/java/net/sourceforge/pmd/lang/kotlin/ast/KotlinInnerNode.java | KotlinInnerNode | acceptVisitor | class KotlinInnerNode extends BaseAntlrInnerNode<KotlinNode> implements KotlinNode {
KotlinInnerNode(ParserRuleContext parent, int invokingStateNumber) {
super(parent, invokingStateNumber);
}
@Override
public <P, R> R acceptVisitor(AstVisitor<? super P, ? extends R> visitor, P data) {<FILL_FUNCTION_BODY>}
@Override // override to make visible in package
protected PmdAsAntlrInnerNode<KotlinNode> asAntlrNode() {
return super.asAntlrNode();
}
@Override
public String getXPathNodeName() {
return KotlinParser.DICO.getXPathNameOfRule(getRuleIndex());
}
} |
if (visitor instanceof KotlinVisitor) {
// some of the generated antlr nodes have no accept method...
return ((KotlinVisitor<? super P, ? extends R>) visitor).visitKotlinNode(this, data);
}
return visitor.visitNode(this, data);
|
return visitor.visit(this, data);
| [
"P",
"AstVisitor<? super P,? extends R>"
] | [
"visit"
] | [
"P",
"AstVisitor<? super P,? extends R>"
] | [
"visitKotlinNode",
"visitNode"
] | {
"methods": [
"visit"
],
"similar_methods": [
"acceptVisitor"
],
"types": [
"P",
"AstVisitor<? super P,? extends R>"
]
} | public class C {
private C();
public class IC {
}
public static class ISC {
}
public static final String V="";
}
/**
* Root interface for AST visitors. Language modules publish a subinterface with one separate visit method for each type of node in the language, eg JavaVisitor. <p>Usually you never want to call {@code visit} methods manually, insteadcalling {@link Node#acceptVisitor(AstVisitor,Object) Node::acceptVisitor}, which then dispatches to the most specific method of the visitor instance. <p>Use {@link Void} as a type parameter if you don't want a parameter typeor a return type.
* @param < P > Parameter type of the visit method
* @param < R > Return type of the visit method
*/
public interface AstVisitor<P,R> {
/**
* Called by a node when it detects that the visitor is not of the language it is used to visiting. If a visitor wants to visit nodes for several languages, it should provide a useful implementation of this method. The default implementation throws
* @param node Node calling back this method
* @param param Parameter of the visit
* @return A value (or may throw)
*/
default R cannotVisit( Node node, P param);
/**
* Visit a node. This method is dispatched statically, you should use {@link Node#acceptVisitor(AstVisitor,Object)} if you wantto call the most specific method instead.
* @param node Node to visit
* @param param Parameter
* @return Some result
*/
R visitNode( Node node, P param);
}
default R visit(ASTWhenClause node,P data){
return visitModelicaNode(node,data);
}
@Override public <P,R>R acceptVisitor(AstVisitor<? super P,? extends R> visitor,P data){
if (visitor instanceof KotlinVisitor) return ((KotlinVisitor<? super P,? extends R>)visitor).visitKotlinFile(this,data);
else return super.acceptVisitor(visitor,data);
}
| public class C {
private C();
public class IC {
}
public static class ISC {
}
public static final String V="";
}
public interface AstVisitor<P,R> {
default R cannotVisit( Node node, P param);
R visitNode( Node node, P param);
}
default R visit(ASTWhenClause node,P data){
return visitModelicaNode(node,data);
}
@Override public <P,R>R acceptVisitor(AstVisitor<? super P,? extends R> visitor,P data){
if (visitor instanceof KotlinVisitor) return ((KotlinVisitor<? super P,? extends R>)visitor).visitKotlinFile(this,data);
else return super.acceptVisitor(visitor,data);
}
| {"types": [{"P": "C"}, {"AstVisitor<? super P,? extends R>": "AstVisitor"}], "methods": [{"visit": "visit"}], "similar_methods": [{"acceptVisitor": "acceptVisitor"}]} | [{"P": {"retrieved_name": "C", "raw_body": "public class C {\n private C();\npublic class IC {\n }\npublic static class ISC {\n }\n public static final String V=\"\";\n}\n", "raw_body_no_cmt": "public class C {\n private C();\npublic class IC {\n }\npublic static class ISC {\n }\n public static final String V=\"\";\n}\n"}}, {"AstVisitor<? super P,? extends R>": {"retrieved_name": "AstVisitor", "raw_body": "/** \n * Root interface for AST visitors. Language modules publish a subinterface with one separate visit method for each type of node in the language, eg JavaVisitor. <p>Usually you never want to call {@code visit} methods manually, insteadcalling {@link Node#acceptVisitor(AstVisitor,Object) Node::acceptVisitor}, which then dispatches to the most specific method of the visitor instance. <p>Use {@link Void} as a type parameter if you don't want a parameter typeor a return type.\n * @param < P > Parameter type of the visit method\n * @param < R > Return type of the visit method\n */\npublic interface AstVisitor<P,R> {\n /** \n * Called by a node when it detects that the visitor is not of the language it is used to visiting. If a visitor wants to visit nodes for several languages, it should provide a useful implementation of this method. The default implementation throws\n * @param node Node calling back this method\n * @param param Parameter of the visit\n * @return A value (or may throw)\n */\n default R cannotVisit( Node node, P param);\n /** \n * Visit a node. This method is dispatched statically, you should use {@link Node#acceptVisitor(AstVisitor,Object)} if you wantto call the most specific method instead.\n * @param node Node to visit\n * @param param Parameter\n * @return Some result\n */\n R visitNode( Node node, P param);\n}\n", "raw_body_no_cmt": "public interface AstVisitor<P,R> {\n default R cannotVisit( Node node, P param);\n R visitNode( Node node, P param);\n}\n"}}] | [{"visit": {"retrieved_name": "visit", "raw_body": "default R visit(ASTWhenClause node,P data){\n return visitModelicaNode(node,data);\n}\n"}}] | [{"acceptVisitor": {"retrieved_name": "acceptVisitor", "raw_body": "@Override public <P,R>R acceptVisitor(AstVisitor<? super P,? extends R> visitor,P data){\n if (visitor instanceof KotlinVisitor) return ((KotlinVisitor<? super P,? extends R>)visitor).visitKotlinFile(this,data);\n else return super.acceptVisitor(visitor,data);\n}\n"}}] |
|
pmd_pmd | pmd/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/internal/infer/ast/BaseFunctionalMirror.java | BaseFunctionalMirror | setFunctionalMethod | class BaseFunctionalMirror<N extends FunctionalExpression> extends BasePolyMirror<N> implements FunctionalExprMirror {
private JMethodSig inferredMethod;
BaseFunctionalMirror(JavaExprMirrors mirrors, N myNode, @Nullable ExprMirror parent, MirrorMaker subexprMaker) {
super(mirrors, myNode, parent, subexprMaker);
}
@Override
public void setFunctionalMethod(JMethodSig methodType) {<FILL_FUNCTION_BODY>}
protected JMethodSig getInferredMethod() {
return inferredMethod;
}
} |
this.inferredMethod = methodType;
if (mayMutateAst()) {
InternalApiBridge.setFunctionalMethod(myNode, methodType);
}
|
inferredMethod = methodType;
| [
"JMethodSig"
] | [] | [
"N",
"JMethodSig"
] | [
"setFunctionalMethod"
] | {
"methods": [],
"similar_methods": [
"setFunctionalMethod"
],
"types": [
"JMethodSig"
]
} | /**
* Represents the signature of methods and constructors. An instance of this interface is a {@link JMethodSymbol} viewed under a particularsubstitution. <p>All the types returned by {@link #getFormalParameters()}, {@link #getReturnType()}, {@link #getTypeParameters()} and{@link #getThrownExceptions()} can mention type parameters of the method,of its {@linkplain #getDeclaringType() declaring type} and all its enclosingtypes. <p>Typically the output of type inference is a method symbol whose type parameters have been given a specific instantiation. But If a signature is produced by type inference, it may not match its symbol exactly (ie, not just be a substitution applied to the symbol's type parameters), to account for special cases depending on context information. For example, the actual return type of a method whose applicability required an unchecked conversion is the erasure of the return type of the declaration.
*/
public interface JMethodSig extends JTypeVisitable {
/**
* Return the type system with which this method was created.
*/
TypeSystem getTypeSystem();
/**
* Return the symbol of the method or constructor.
*/
JExecutableSymbol getSymbol();
/**
* Return the name of the method. If this is a constructor, returns {@link JConstructorSymbol#CTOR_NAME}.
*/
default String getName();
/**
* Return whether this is a constructor.
*/
default boolean isConstructor();
/**
* Return method modifiers as decodable by {@link java.lang.reflect.Modifier}.
*/
default int getModifiers();
/**
* Return the type that declares this method. May be an array type, a class type. If this is a constructor for a generic class, returns the generic type declaration of the constructor.
*/
JTypeMirror getDeclaringType();
/**
* Return the type of {@code this} in the body of the method. Thisis the declaring type with
*/
JTypeMirror getAnnotatedReceiverType();
/**
* Return the result type of the method. If this is a constructor, returns the type of the instance produced by the constructor. In particular, for a diamond constructor call, returns the inferred type. For example for {@code List<String> l = new ArrayList<>()}, returns {@code ArrayList<String>}.
*/
JTypeMirror getReturnType();
/**
* The erasure of a method is a new, non-generic method, whose parameters, owner, and return type, are erased. For example: <pre> {@code <N extends Number, U> U fun(N, Supplier<U>, U);}</pre> erases to <pre> Object fun(Number, Supplier, Object); </pre>
*/
JMethodSig getErasure();
/**
* Return the types of the formal parameters. If this is a varargs method, the last parameter should have an array type. For generic methods that have been inferred, these are substituted with the inferred type parameters. For example for {@code Arrays.asList("a", "b")}, returns a singleton list containing {@code String[]}.
*/
List<JTypeMirror> getFormalParameters();
/**
* Number of formal parameters. A varargs parameter counts as one.
*/
default int getArity();
/**
* Return the type parameters of the method. After type inference, occurrences of these type parameters are replaced by their instantiation in formals, return type and thrown exceptions (but not type parameter bounds). If instantiation failed, some variables might have been substituted with {@link TypeSystem#ERROR}.
*/
List<JTypeVar> getTypeParameters();
/**
* Return the list of thrown exception types. Exception types may be type variables of the method or of an enclosing context, that extend Throwable.
*/
List<JTypeMirror> getThrownExceptions();
/**
* Return true if this method is abstract.
*/
default boolean isAbstract();
/**
* Return true if this method is static.
*/
default boolean isStatic();
/**
* Return true if this method has a varargs parameter.
*/
default boolean isVarargs();
/**
* Return true if this method signature declares type parameters.
*/
default boolean isGeneric();
@Override JMethodSig subst( Function<? super SubstVar,? extends @NonNull JTypeMirror> subst);
@Override default <T,P>T acceptVisitor( JTypeVisitor<T,P> visitor, P p);
}
void setFunctionalMethod(@Nullable JMethodSig functionalMethod){
this.functionalMethod=functionalMethod;
}
| public interface JMethodSig extends JTypeVisitable {
TypeSystem getTypeSystem();
JExecutableSymbol getSymbol();
default String getName();
default boolean isConstructor();
default int getModifiers();
JTypeMirror getDeclaringType();
JTypeMirror getAnnotatedReceiverType();
JTypeMirror getReturnType();
JMethodSig getErasure();
List<JTypeMirror> getFormalParameters();
default int getArity();
List<JTypeVar> getTypeParameters();
List<JTypeMirror> getThrownExceptions();
default boolean isAbstract();
default boolean isStatic();
default boolean isVarargs();
default boolean isGeneric();
JMethodSig subst( Function<? super SubstVar,? extends JTypeMirror> subst);
default <T,P>T acceptVisitor( JTypeVisitor<T,P> visitor, P p);
}
void setFunctionalMethod(@Nullable JMethodSig functionalMethod){
this.functionalMethod=functionalMethod;
}
| {"types": [{"JMethodSig": "JMethodSig"}], "similar_methods": [{"setFunctionalMethod": "setFunctionalMethod"}]} | [{"JMethodSig": {"retrieved_name": "JMethodSig", "raw_body": "/** \n * Represents the signature of methods and constructors. An instance of this interface is a {@link JMethodSymbol} viewed under a particularsubstitution. <p>All the types returned by {@link #getFormalParameters()}, {@link #getReturnType()}, {@link #getTypeParameters()} and{@link #getThrownExceptions()} can mention type parameters of the method,of its {@linkplain #getDeclaringType() declaring type} and all its enclosingtypes. <p>Typically the output of type inference is a method symbol whose type parameters have been given a specific instantiation. But If a signature is produced by type inference, it may not match its symbol exactly (ie, not just be a substitution applied to the symbol's type parameters), to account for special cases depending on context information. For example, the actual return type of a method whose applicability required an unchecked conversion is the erasure of the return type of the declaration.\n */\npublic interface JMethodSig extends JTypeVisitable {\n /** \n * Return the type system with which this method was created. \n */\n TypeSystem getTypeSystem();\n /** \n * Return the symbol of the method or constructor. \n */\n JExecutableSymbol getSymbol();\n /** \n * Return the name of the method. If this is a constructor, returns {@link JConstructorSymbol#CTOR_NAME}.\n */\n default String getName();\n /** \n * Return whether this is a constructor. \n */\n default boolean isConstructor();\n /** \n * Return method modifiers as decodable by {@link java.lang.reflect.Modifier}. \n */\n default int getModifiers();\n /** \n * Return the type that declares this method. May be an array type, a class type. If this is a constructor for a generic class, returns the generic type declaration of the constructor.\n */\n JTypeMirror getDeclaringType();\n /** \n * Return the type of {@code this} in the body of the method. Thisis the declaring type with\n */\n JTypeMirror getAnnotatedReceiverType();\n /** \n * Return the result type of the method. If this is a constructor, returns the type of the instance produced by the constructor. In particular, for a diamond constructor call, returns the inferred type. For example for {@code List<String> l = new ArrayList<>()}, returns {@code ArrayList<String>}.\n */\n JTypeMirror getReturnType();\n /** \n * The erasure of a method is a new, non-generic method, whose parameters, owner, and return type, are erased. For example: <pre> {@code <N extends Number, U> U fun(N, Supplier<U>, U);}</pre> erases to <pre> Object fun(Number, Supplier, Object); </pre>\n */\n JMethodSig getErasure();\n /** \n * Return the types of the formal parameters. If this is a varargs method, the last parameter should have an array type. For generic methods that have been inferred, these are substituted with the inferred type parameters. For example for {@code Arrays.asList(\"a\", \"b\")}, returns a singleton list containing {@code String[]}.\n */\n List<JTypeMirror> getFormalParameters();\n /** \n * Number of formal parameters. A varargs parameter counts as one.\n */\n default int getArity();\n /** \n * Return the type parameters of the method. After type inference, occurrences of these type parameters are replaced by their instantiation in formals, return type and thrown exceptions (but not type parameter bounds). If instantiation failed, some variables might have been substituted with {@link TypeSystem#ERROR}.\n */\n List<JTypeVar> getTypeParameters();\n /** \n * Return the list of thrown exception types. Exception types may be type variables of the method or of an enclosing context, that extend Throwable.\n */\n List<JTypeMirror> getThrownExceptions();\n /** \n * Return true if this method is abstract. \n */\n default boolean isAbstract();\n /** \n * Return true if this method is static. \n */\n default boolean isStatic();\n /** \n * Return true if this method has a varargs parameter. \n */\n default boolean isVarargs();\n /** \n * Return true if this method signature declares type parameters.\n */\n default boolean isGeneric();\n @Override JMethodSig subst( Function<? super SubstVar,? extends @NonNull JTypeMirror> subst);\n @Override default <T,P>T acceptVisitor( JTypeVisitor<T,P> visitor, P p);\n}\n", "raw_body_no_cmt": "public interface JMethodSig extends JTypeVisitable {\n TypeSystem getTypeSystem();\n JExecutableSymbol getSymbol();\n default String getName();\n default boolean isConstructor();\n default int getModifiers();\n JTypeMirror getDeclaringType();\n JTypeMirror getAnnotatedReceiverType();\n JTypeMirror getReturnType();\n JMethodSig getErasure();\n List<JTypeMirror> getFormalParameters();\n default int getArity();\n List<JTypeVar> getTypeParameters();\n List<JTypeMirror> getThrownExceptions();\n default boolean isAbstract();\n default boolean isStatic();\n default boolean isVarargs();\n default boolean isGeneric();\n JMethodSig subst( Function<? super SubstVar,? extends JTypeMirror> subst);\n default <T,P>T acceptVisitor( JTypeVisitor<T,P> visitor, P p);\n}\n"}}] | [] | [{"setFunctionalMethod": {"retrieved_name": "setFunctionalMethod", "raw_body": "void setFunctionalMethod(@Nullable JMethodSig functionalMethod){\n this.functionalMethod=functionalMethod;\n}\n"}}] |
|
javamelody_javamelody | javamelody/javamelody-core/src/main/java/net/bull/javamelody/internal/model/TomcatInformations.java | TomcatInformations | buildTomcatInformationsList | class TomcatInformations implements Serializable {
// cette classe utilise la même technique avec les MBeans Tomcat que la webapp manager de Tomcat
// http://svn.apache.org/repos/asf/tomcat/trunk/java/org/apache/catalina/manager/StatusManagerServlet.java
// http://svn.apache.org/repos/asf/tomcat/trunk/java/org/apache/catalina/manager/StatusTransformer.java
// http://svn.apache.org/repos/asf/tomcat/trunk/webapps/manager/xform.xsl
private static final boolean TOMCAT_USED = System.getProperty("catalina.home") != null;
private static final long serialVersionUID = -6145865427461051370L;
@SuppressWarnings("all")
private static final List<ObjectName> THREAD_POOLS = new ArrayList<>();
@SuppressWarnings("all")
private static final List<ObjectName> GLOBAL_REQUEST_PROCESSORS = new ArrayList<>();
private static int mbeansInitAttemps;
private final String name;
private final int maxThreads;
private final int currentThreadCount;
private final int currentThreadsBusy;
private final long bytesReceived;
private final long bytesSent;
private final int requestCount;
private final int errorCount;
private final long processingTime;
private final long maxTime;
private TomcatInformations(ObjectName threadPool) throws JMException {
super();
name = threadPool.getKeyProperty("name");
maxThreads = MBeansAccessor.getAttribute(threadPool, "maxThreads");
currentThreadCount = MBeansAccessor.getAttribute(threadPool, "currentThreadCount");
currentThreadsBusy = MBeansAccessor.getAttribute(threadPool, "currentThreadsBusy");
ObjectName grp = null;
for (final ObjectName globalRequestProcessor : GLOBAL_REQUEST_PROCESSORS) {
if (name.equals(globalRequestProcessor.getKeyProperty("name"))) {
grp = globalRequestProcessor;
break;
}
}
if (grp != null) {
bytesReceived = MBeansAccessor.getAttribute(grp, "bytesReceived");
bytesSent = MBeansAccessor.getAttribute(grp, "bytesSent");
requestCount = MBeansAccessor.getAttribute(grp, "requestCount");
errorCount = MBeansAccessor.getAttribute(grp, "errorCount");
processingTime = MBeansAccessor.getAttribute(grp, "processingTime");
maxTime = MBeansAccessor.getAttribute(grp, "maxTime");
} else {
bytesReceived = 0;
bytesSent = 0;
requestCount = 0;
errorCount = 0;
processingTime = 0;
maxTime = 0;
}
}
static List<TomcatInformations> buildTomcatInformationsList() {<FILL_FUNCTION_BODY>}
// visibilité package pour réinitialisation en test unitaire
public static void initMBeans() {
// rq: en général, il y a 2 connecteurs (http et ajp 1.3) définis dans server.xml et donc
// 2 threadPools et 2 globalRequestProcessors de même nom : http-8080 et jk-8009 (ajp13)
THREAD_POOLS.clear();
GLOBAL_REQUEST_PROCESSORS.clear();
THREAD_POOLS.addAll(MBeansAccessor.getTomcatThreadPools());
GLOBAL_REQUEST_PROCESSORS.addAll(MBeansAccessor.getTomcatGlobalRequestProcessors());
}
public String getName() {
return name;
}
public int getMaxThreads() {
return maxThreads;
}
int getCurrentThreadCount() {
return currentThreadCount;
}
public int getCurrentThreadsBusy() {
return currentThreadsBusy;
}
public long getBytesReceived() {
return bytesReceived;
}
public long getBytesSent() {
return bytesSent;
}
public int getRequestCount() {
return requestCount;
}
public int getErrorCount() {
return errorCount;
}
public long getProcessingTime() {
return processingTime;
}
public long getMaxTime() {
return maxTime;
}
/** {@inheritDoc} */
@Override
public String toString() {
return getClass().getSimpleName() + "[name=" + getName() + ", maxThreads=" + getMaxThreads()
+ ", currentThreadCount=" + getCurrentThreadCount() + ", currentThreadsBusy="
+ getCurrentThreadsBusy() + ", bytesReceived=" + getBytesReceived() + ", bytesSent="
+ getBytesSent() + ", requestCount=" + getRequestCount() + ", errorCount="
+ getErrorCount() + ", processingTime=" + getProcessingTime() + ", maxTime="
+ getMaxTime() + ']';
}
} |
if (!TOMCAT_USED) {
return Collections.emptyList();
}
try {
synchronized (THREAD_POOLS) {
if ((THREAD_POOLS.isEmpty() || GLOBAL_REQUEST_PROCESSORS.isEmpty())
&& mbeansInitAttemps < 10) {
// lors du premier appel dans Tomcat lors du déploiement de la webapp,
// ce initMBeans ne fonctionne pas car les MBeans n'existent pas encore,
// donc il faut réessayer plus tard
initMBeans();
// issue 406, Tomcat mbeans never found in jboss eap 6.2,
// we must stop initMBeans at some point
mbeansInitAttemps++;
}
}
final List<TomcatInformations> tomcatInformationsList = new ArrayList<>(
THREAD_POOLS.size());
// rq: le processor correspondant au threadPool peut se retrouver selon
// threadPool.getKeyProperty("name").equals(globalRequestProcessor.getKeyProperty("name"))
for (final ObjectName threadPool : THREAD_POOLS) {
tomcatInformationsList.add(new TomcatInformations(threadPool));
}
return tomcatInformationsList;
} catch (final InstanceNotFoundException | AttributeNotFoundException e) {
// catch InstanceNotFoundException nécessaire pour JBoss 6.0 quand appelé depuis MonitoringFilter.destroy via
// writeHtmlToLastShutdownFile
// issue 220 and end of issue 133:
// AttributeNotFoundException: No attribute called maxThreads (in some JBossAS or JBossWeb)
return Collections.emptyList();
} catch (final JMException e) {
// n'est pas censé arriver
throw new IllegalStateException(e);
}
|
if (TOMCAT_USED) {
try {
if (THREAD_POOLS.isEmpty() && GLOBAL_REQUEST_PROCESSORS.isEmpty()) {
initMBeans();
}
final List<TomcatInformations> result = new ArrayList<>();
for (final ObjectName threadPool : THREAD_POOLS) {
result.add(new TomcatInformations(threadPool));
}
return result;
} catch (final JMException e) {
LOGGER.error("Erreur lors de la récupération des informations de Tomcat", e);
return Collections.emptyList();
}
} else {
return Collections.emptyList();
}
| [
"JMException",
"List<ObjectName>",
"List<TomcatInformations>"
] | [
"isEmpty",
"add",
"error",
"emptyList"
] | [
"List<ObjectName>",
"JMException",
"List<TomcatInformations>"
] | [
"add",
"emptyList",
"isEmpty",
"size"
] | {
"methods": [
"isEmpty",
"add",
"error",
"emptyList"
],
"similar_methods": [
"buildTomcatInformationsList"
],
"types": [
"JMException",
"List<ObjectName>",
"List<TomcatInformations>"
]
} | /**
* Informations sur un cache de données JCache (JSR107). L'état d'une instance est initialisé à son instanciation et non mutable; il est donc de fait thread-safe. Cet état est celui d'un cache à un instant t. Les instances sont sérialisables pour pouvoir être transmises au serveur de collecte.
* @author James Pether Sörling
* @author Emeric Vernat
*/
public class JCacheInformations implements Serializable {
private static final long serialVersionUID=-3025833425994923286L;
private static final MBeanServer MBEAN_SERVER=MBeans.getPlatformMBeanServer();
private static final boolean JCACHE_AVAILABLE=isJCacheAvailable();
private final String name;
private final long cacheHits;
private final long cacheMisses;
private boolean availableByApi;
private List<?> cacheKeys;
JCacheInformations( ObjectName cache);
JCacheInformations( String cacheName);
private static Long getValue( ObjectName cache, String attribute);
static List<JCacheInformations> buildJCacheInformationsList();
public static JCacheInformations buildJCacheInformationsWithKeys( String cacheId);
private static Set<ObjectName> getJsr107CacheStatistics();
private static boolean isJCacheAvailable();
public String getName();
public long getCacheHits();
public long getCacheMisses();
public int getHitsRatio();
public boolean isAvailableByApi();
public List<?> getCacheKeys();
/**
* {@inheritDoc}
*/
@Override public String toString();
}
/**
* Composant Table typé servant de base à MTable.
* @param < T > Type des valeurs de la liste
* @author Emeric Vernat
*/
public class MListTable<T> extends MBasicTable {
private static final long serialVersionUID=1L;
/**
* Constructeur.
* @param dataModel Modèle pour les données (par exemple, MTableModel)
*/
public MListTable( final MListTableModel<T> dataModel);
/**
* {@inheritDoc}
*/
@Override public void setModel( final TableModel tableModel);
/**
* Retourne la valeur de la propriété listTableModel.
* @return MListTableModel
*/
@SuppressWarnings("unchecked") protected MListTableModel<T> getListTableModel();
/**
* Retourne la valeur de la propriété list.
* @return List
* @see #setList
*/
public List<T> getList();
/**
* Définit la valeur de la propriété list. <BR> Cette méthode adaptent automatiquement les largeurs des colonnes selon les données.
* @param newList List
* @see #getList
*/
public void setList( final List<T> newList);
/**
* Retourne la liste d'objets sélectionnés.
* @return List
* @see #setSelectedList
*/
public List<T> getSelectedList();
/**
* Retourne l'objet sélectionné.
* @return TypeValue
* @see #setSelectedObject
*/
public T getSelectedObject();
/**
* Définit la liste d'objets sélectionnés.
* @param newSelectedList List
* @see #getSelectedList
*/
public void setSelectedList( final List<T> newSelectedList);
/**
* Définit l'objet sélectionné. L'objet peut être null pour ne rien sélectionné.
* @param newSelectedObject TypeValue
* @see #getSelectedObject
*/
public void setSelectedObject( final T newSelectedObject);
/**
* Renvoie l'objet à la position demandée. Attention rowIndex est l'index vu de la JTable avec les index, et non pas vu du ListTableModel.
* @return Object
* @param rowIndex int
*/
T getObjectAt( final int rowIndex);
}
/**
* Test unitaire de la classe TomcatInformations.
* @author Emeric Vernat
*/
public class TestTomcatInformations {
/**
* Implémentation du MBean ThreadPool.
* @author Emeric Vernat
*/
public static class ThreadPool implements ThreadPoolMBean {
/**
* {@inheritDoc}
*/
@Override public int getmaxThreads();
/**
* {@inheritDoc}
*/
@Override public int getcurrentThreadsBusy();
/**
* {@inheritDoc}
*/
@Override public int getcurrentThreadCount();
/**
* {@inheritDoc}
*/
@Override public String[] getdummy();
/**
* {@inheritDoc}
*/
@Override public Map<Object,Object> getmemoryUsage();
/**
* {@inheritDoc}
*/
@Override public Object gettoStringException();
/**
* {@inheritDoc}
*/
@Override public int[] getintArrayAsInJRockit();
/**
* {@inheritDoc}
*/
@Override public double[] getdoubleArrayAsInJRockit();
}
/**
* Interface du MBean ThreadPool.
* @author Emeric Vernat
*/
public interface ThreadPoolMBean {
/**
* attribut maxThreads.
* @return int
*/
int getmaxThreads();
/**
* attribut memoryUsage.
* @return MemoryUsage
*/
Map<Object,Object> getmemoryUsage();
/**
* attribut currentThreadsBusy.
* @return int
*/
int getcurrentThreadsBusy();
/**
* attribut currentThreadCount.
* @return int
*/
int getcurrentThreadCount();
/**
* attribut dummy.
* @return String[]
*/
String[] getdummy();
/**
* attribut toStringException.
* @return Object
*/
Object gettoStringException();
/**
* @return int[]
*/
int[] getintArrayAsInJRockit();
/**
* @return double[]
*/
double[] getdoubleArrayAsInJRockit();
}
/**
* Implémentation du MBean GlobalRequestProcessor.
* @author Emeric Vernat
*/
public static class GlobalRequestProcessor implements GlobalRequestProcessorMBean {
private int requestCount=100;
/**
* {@inheritDoc}
*/
@Override public long getbytesReceived();
/**
* {@inheritDoc}
*/
@Override public long getbytesSent();
/**
* {@inheritDoc}
*/
@Override public int getrequestCount();
/**
* setter.
* @param count int
*/
public void setrequestCount( int count);
/**
* {@inheritDoc}
*/
@Override public int geterrorCount();
/**
* {@inheritDoc}
*/
@Override public long getprocessingTime();
/**
* {@inheritDoc}
*/
@Override public long getmaxTime();
}
/**
* Interface du MBean GlobalRequestProcessor.
* @author Emeric Vernat
*/
public interface GlobalRequestProcessorMBean {
/**
* attribut bytesReceived.
* @return int
*/
long getbytesReceived();
/**
* attribut bytesSent.
* @return int
*/
long getbytesSent();
/**
* attribut requestCount.
* @return int
*/
int getrequestCount();
/**
* attribut errorCount.
* @return int
*/
int geterrorCount();
/**
* attribut processingTime.
* @return int
*/
long getprocessingTime();
/**
* attribut maxTime.
* @return int
*/
long getmaxTime();
}
/**
* Test.
*/
@Before public void setUp();
/**
* Test.
* @throws JMException e
*/
@Test public void testTomcatInformations() throws JMException;
}
boolean isEmpty(){
return properties.isEmpty();
}
private static int add(int t1,int t2){
if (t1 < 0 && t2 > 0) {
return t2;
}
else if (t1 > 0 && t2 < 0) {
return t1;
}
return t1 + t2;
}
private void writeError(CounterError error,boolean displayUser,boolean displayHttpRequest) throws IOException {
write("<td align='right'>");
write(dateTimeFormat.format(error.getDate()));
if (displayHttpRequest) {
write("</td><td class='wrappedText'>");
if (error.getHttpRequest() == null) {
write(" ");
}
else {
writeDirectly(htmlEncode(error.getHttpRequest()));
}
}
if (displayUser) {
write("</td><td class='wrappedText'>");
if (error.getRemoteUser() == null) {
write(" ");
}
else {
writeDirectly(htmlEncode(error.getRemoteUser()));
}
}
if (error.getStackTrace() != null) {
write("</td><td>");
writeln("<div class='tooltip'>");
writeln("<em>");
writeStackTrace(error);
writeln("</em>");
writeDirectly(htmlEncode(error.getMessage()));
writeln("</div>");
}
else {
write("</td><td class='wrappedText'>");
writeDirectly(htmlEncode(error.getMessage()));
}
write("</td>");
}
boolean isEmpty(){
return properties.isEmpty();
}
public List<TomcatInformations> getTomcatInformationsList(){
return tomcatInformationsList;
}
| public class JCacheInformations implements Serializable {
private static final long serialVersionUID=-3025833425994923286L;
private static final MBeanServer MBEAN_SERVER=MBeans.getPlatformMBeanServer();
private static final boolean JCACHE_AVAILABLE=isJCacheAvailable();
private final String name;
private final long cacheHits;
private final long cacheMisses;
private boolean availableByApi;
private List<?> cacheKeys;
JCacheInformations( ObjectName cache);
JCacheInformations( String cacheName);
private static Long getValue( ObjectName cache, String attribute);
static List<JCacheInformations> buildJCacheInformationsList();
public static JCacheInformations buildJCacheInformationsWithKeys( String cacheId);
private static Set<ObjectName> getJsr107CacheStatistics();
private static boolean isJCacheAvailable();
public String getName();
public long getCacheHits();
public long getCacheMisses();
public int getHitsRatio();
public boolean isAvailableByApi();
public List<?> getCacheKeys();
public String toString();
}
public class MListTable<T> extends MBasicTable {
private static final long serialVersionUID=1L;
public MListTable( final MListTableModel<T> dataModel);
public void setModel( final TableModel tableModel);
protected MListTableModel<T> getListTableModel();
public List<T> getList();
public void setList( final List<T> newList);
public List<T> getSelectedList();
public T getSelectedObject();
public void setSelectedList( final List<T> newSelectedList);
public void setSelectedObject( final T newSelectedObject);
T getObjectAt( final int rowIndex);
}
public class TestTomcatInformations {
public static class ThreadPool implements ThreadPoolMBean {
public int getmaxThreads();
public int getcurrentThreadsBusy();
public int getcurrentThreadCount();
public String[] getdummy();
public Map<Object,Object> getmemoryUsage();
public Object gettoStringException();
public int[] getintArrayAsInJRockit();
public double[] getdoubleArrayAsInJRockit();
}
public interface ThreadPoolMBean {
int getmaxThreads();
Map<Object,Object> getmemoryUsage();
int getcurrentThreadsBusy();
int getcurrentThreadCount();
String[] getdummy();
Object gettoStringException();
int[] getintArrayAsInJRockit();
double[] getdoubleArrayAsInJRockit();
}
public static class GlobalRequestProcessor implements GlobalRequestProcessorMBean {
private int requestCount=100;
public long getbytesReceived();
public long getbytesSent();
public int getrequestCount();
public void setrequestCount( int count);
public int geterrorCount();
public long getprocessingTime();
public long getmaxTime();
}
public interface GlobalRequestProcessorMBean {
long getbytesReceived();
long getbytesSent();
int getrequestCount();
int geterrorCount();
long getprocessingTime();
long getmaxTime();
}
public void setUp();
public void testTomcatInformations() throws JMException;
}
boolean isEmpty(){
return properties.isEmpty();
}
private static int add(int t1,int t2){
if (t1 < 0 && t2 > 0) {
return t2;
}
else if (t1 > 0 && t2 < 0) {
return t1;
}
return t1 + t2;
}
private void writeError(CounterError error,boolean displayUser,boolean displayHttpRequest) throws IOException {
write("<td align='right'>");
write(dateTimeFormat.format(error.getDate()));
if (displayHttpRequest) {
write("</td><td class='wrappedText'>");
if (error.getHttpRequest() == null) {
write(" ");
}
else {
writeDirectly(htmlEncode(error.getHttpRequest()));
}
}
if (displayUser) {
write("</td><td class='wrappedText'>");
if (error.getRemoteUser() == null) {
write(" ");
}
else {
writeDirectly(htmlEncode(error.getRemoteUser()));
}
}
if (error.getStackTrace() != null) {
write("</td><td>");
writeln("<div class='tooltip'>");
writeln("<em>");
writeStackTrace(error);
writeln("</em>");
writeDirectly(htmlEncode(error.getMessage()));
writeln("</div>");
}
else {
write("</td><td class='wrappedText'>");
writeDirectly(htmlEncode(error.getMessage()));
}
write("</td>");
}
boolean isEmpty(){
return properties.isEmpty();
}
public List<TomcatInformations> getTomcatInformationsList(){
return tomcatInformationsList;
}
| {"types": [{"JMException": "JCacheInformations"}, {"List<ObjectName>": "MListTable"}, {"List<TomcatInformations>": "TestTomcatInformations"}], "methods": [{"isEmpty": "isEmpty"}, {"add": "add"}, {"error": "writeError"}, {"emptyList": "isEmpty"}], "similar_methods": [{"buildTomcatInformationsList": "getTomcatInformationsList"}]} | [{"JMException": {"retrieved_name": "JCacheInformations", "raw_body": "/** \n * Informations sur un cache de donn\u00e9es JCache (JSR107). L'\u00e9tat d'une instance est initialis\u00e9 \u00e0 son instanciation et non mutable; il est donc de fait thread-safe. Cet \u00e9tat est celui d'un cache \u00e0 un instant t. Les instances sont s\u00e9rialisables pour pouvoir \u00eatre transmises au serveur de collecte.\n * @author James Pether S\u00f6rling\n * @author Emeric Vernat\n */\npublic class JCacheInformations implements Serializable {\n private static final long serialVersionUID=-3025833425994923286L;\n private static final MBeanServer MBEAN_SERVER=MBeans.getPlatformMBeanServer();\n private static final boolean JCACHE_AVAILABLE=isJCacheAvailable();\n private final String name;\n private final long cacheHits;\n private final long cacheMisses;\n private boolean availableByApi;\n private List<?> cacheKeys;\n JCacheInformations( ObjectName cache);\n JCacheInformations( String cacheName);\n private static Long getValue( ObjectName cache, String attribute);\n static List<JCacheInformations> buildJCacheInformationsList();\n public static JCacheInformations buildJCacheInformationsWithKeys( String cacheId);\n private static Set<ObjectName> getJsr107CacheStatistics();\n private static boolean isJCacheAvailable();\n public String getName();\n public long getCacheHits();\n public long getCacheMisses();\n public int getHitsRatio();\n public boolean isAvailableByApi();\n public List<?> getCacheKeys();\n /** \n * {@inheritDoc} \n */\n @Override public String toString();\n}\n", "raw_body_no_cmt": "public class JCacheInformations implements Serializable {\n private static final long serialVersionUID=-3025833425994923286L;\n private static final MBeanServer MBEAN_SERVER=MBeans.getPlatformMBeanServer();\n private static final boolean JCACHE_AVAILABLE=isJCacheAvailable();\n private final String name;\n private final long cacheHits;\n private final long cacheMisses;\n private boolean availableByApi;\n private List<?> cacheKeys;\n JCacheInformations( ObjectName cache);\n JCacheInformations( String cacheName);\n private static Long getValue( ObjectName cache, String attribute);\n static List<JCacheInformations> buildJCacheInformationsList();\n public static JCacheInformations buildJCacheInformationsWithKeys( String cacheId);\n private static Set<ObjectName> getJsr107CacheStatistics();\n private static boolean isJCacheAvailable();\n public String getName();\n public long getCacheHits();\n public long getCacheMisses();\n public int getHitsRatio();\n public boolean isAvailableByApi();\n public List<?> getCacheKeys();\n public String toString();\n}\n"}}, {"List<ObjectName>": {"retrieved_name": "MListTable", "raw_body": "/** \n * Composant Table typ\u00e9 servant de base \u00e0 MTable.\n * @param < T > Type des valeurs de la liste\n * @author Emeric Vernat\n */\npublic class MListTable<T> extends MBasicTable {\n private static final long serialVersionUID=1L;\n /** \n * Constructeur.\n * @param dataModel Mod\u00e8le pour les donn\u00e9es (par exemple, MTableModel)\n */\n public MListTable( final MListTableModel<T> dataModel);\n /** \n * {@inheritDoc} \n */\n @Override public void setModel( final TableModel tableModel);\n /** \n * Retourne la valeur de la propri\u00e9t\u00e9 listTableModel.\n * @return MListTableModel\n */\n @SuppressWarnings(\"unchecked\") protected MListTableModel<T> getListTableModel();\n /** \n * Retourne la valeur de la propri\u00e9t\u00e9 list.\n * @return List\n * @see #setList\n */\n public List<T> getList();\n /** \n * D\u00e9finit la valeur de la propri\u00e9t\u00e9 list. <BR> Cette m\u00e9thode adaptent automatiquement les largeurs des colonnes selon les donn\u00e9es.\n * @param newList List\n * @see #getList\n */\n public void setList( final List<T> newList);\n /** \n * Retourne la liste d'objets s\u00e9lectionn\u00e9s.\n * @return List\n * @see #setSelectedList\n */\n public List<T> getSelectedList();\n /** \n * Retourne l'objet s\u00e9lectionn\u00e9.\n * @return TypeValue\n * @see #setSelectedObject\n */\n public T getSelectedObject();\n /** \n * D\u00e9finit la liste d'objets s\u00e9lectionn\u00e9s.\n * @param newSelectedList List\n * @see #getSelectedList\n */\n public void setSelectedList( final List<T> newSelectedList);\n /** \n * D\u00e9finit l'objet s\u00e9lectionn\u00e9. L'objet peut \u00eatre null pour ne rien s\u00e9lectionn\u00e9.\n * @param newSelectedObject TypeValue\n * @see #getSelectedObject\n */\n public void setSelectedObject( final T newSelectedObject);\n /** \n * Renvoie l'objet \u00e0 la position demand\u00e9e. Attention rowIndex est l'index vu de la JTable avec les index, et non pas vu du ListTableModel.\n * @return Object\n * @param rowIndex int\n */\n T getObjectAt( final int rowIndex);\n}\n", "raw_body_no_cmt": "public class MListTable<T> extends MBasicTable {\n private static final long serialVersionUID=1L;\n public MListTable( final MListTableModel<T> dataModel);\n public void setModel( final TableModel tableModel);\n protected MListTableModel<T> getListTableModel();\n public List<T> getList();\n public void setList( final List<T> newList);\n public List<T> getSelectedList();\n public T getSelectedObject();\n public void setSelectedList( final List<T> newSelectedList);\n public void setSelectedObject( final T newSelectedObject);\n T getObjectAt( final int rowIndex);\n}\n"}}, {"List<TomcatInformations>": {"retrieved_name": "TestTomcatInformations", "raw_body": "/** \n * Test unitaire de la classe TomcatInformations.\n * @author Emeric Vernat\n */\npublic class TestTomcatInformations {\n /** \n * Impl\u00e9mentation du MBean ThreadPool.\n * @author Emeric Vernat\n */\npublic static class ThreadPool implements ThreadPoolMBean {\n /** \n * {@inheritDoc} \n */\n @Override public int getmaxThreads();\n /** \n * {@inheritDoc} \n */\n @Override public int getcurrentThreadsBusy();\n /** \n * {@inheritDoc} \n */\n @Override public int getcurrentThreadCount();\n /** \n * {@inheritDoc} \n */\n @Override public String[] getdummy();\n /** \n * {@inheritDoc} \n */\n @Override public Map<Object,Object> getmemoryUsage();\n /** \n * {@inheritDoc} \n */\n @Override public Object gettoStringException();\n /** \n * {@inheritDoc} \n */\n @Override public int[] getintArrayAsInJRockit();\n /** \n * {@inheritDoc} \n */\n @Override public double[] getdoubleArrayAsInJRockit();\n }\n /** \n * Interface du MBean ThreadPool.\n * @author Emeric Vernat\n */\npublic interface ThreadPoolMBean {\n /** \n * attribut maxThreads.\n * @return int\n */\n int getmaxThreads();\n /** \n * attribut memoryUsage.\n * @return MemoryUsage\n */\n Map<Object,Object> getmemoryUsage();\n /** \n * attribut currentThreadsBusy.\n * @return int\n */\n int getcurrentThreadsBusy();\n /** \n * attribut currentThreadCount.\n * @return int\n */\n int getcurrentThreadCount();\n /** \n * attribut dummy.\n * @return String[]\n */\n String[] getdummy();\n /** \n * attribut toStringException.\n * @return Object\n */\n Object gettoStringException();\n /** \n * @return int[]\n */\n int[] getintArrayAsInJRockit();\n /** \n * @return double[]\n */\n double[] getdoubleArrayAsInJRockit();\n }\n /** \n * Impl\u00e9mentation du MBean GlobalRequestProcessor.\n * @author Emeric Vernat\n */\npublic static class GlobalRequestProcessor implements GlobalRequestProcessorMBean {\n private int requestCount=100;\n /** \n * {@inheritDoc} \n */\n @Override public long getbytesReceived();\n /** \n * {@inheritDoc} \n */\n @Override public long getbytesSent();\n /** \n * {@inheritDoc} \n */\n @Override public int getrequestCount();\n /** \n * setter.\n * @param count int\n */\n public void setrequestCount( int count);\n /** \n * {@inheritDoc} \n */\n @Override public int geterrorCount();\n /** \n * {@inheritDoc} \n */\n @Override public long getprocessingTime();\n /** \n * {@inheritDoc} \n */\n @Override public long getmaxTime();\n }\n /** \n * Interface du MBean GlobalRequestProcessor.\n * @author Emeric Vernat\n */\npublic interface GlobalRequestProcessorMBean {\n /** \n * attribut bytesReceived.\n * @return int\n */\n long getbytesReceived();\n /** \n * attribut bytesSent.\n * @return int\n */\n long getbytesSent();\n /** \n * attribut requestCount.\n * @return int\n */\n int getrequestCount();\n /** \n * attribut errorCount.\n * @return int\n */\n int geterrorCount();\n /** \n * attribut processingTime.\n * @return int\n */\n long getprocessingTime();\n /** \n * attribut maxTime.\n * @return int\n */\n long getmaxTime();\n }\n /** \n * Test. \n */\n @Before public void setUp();\n /** \n * Test.\n * @throws JMException e \n */\n @Test public void testTomcatInformations() throws JMException;\n}\n", "raw_body_no_cmt": "public class TestTomcatInformations {\n public static class ThreadPool implements ThreadPoolMBean {\n public int getmaxThreads();\n public int getcurrentThreadsBusy();\n public int getcurrentThreadCount();\n public String[] getdummy();\n public Map<Object,Object> getmemoryUsage();\n public Object gettoStringException();\n public int[] getintArrayAsInJRockit();\n public double[] getdoubleArrayAsInJRockit();\n }\n public interface ThreadPoolMBean {\n int getmaxThreads();\n Map<Object,Object> getmemoryUsage();\n int getcurrentThreadsBusy();\n int getcurrentThreadCount();\n String[] getdummy();\n Object gettoStringException();\n int[] getintArrayAsInJRockit();\n double[] getdoubleArrayAsInJRockit();\n }\n public static class GlobalRequestProcessor implements GlobalRequestProcessorMBean {\n private int requestCount=100;\n public long getbytesReceived();\n public long getbytesSent();\n public int getrequestCount();\n public void setrequestCount( int count);\n public int geterrorCount();\n public long getprocessingTime();\n public long getmaxTime();\n }\n public interface GlobalRequestProcessorMBean {\n long getbytesReceived();\n long getbytesSent();\n int getrequestCount();\n int geterrorCount();\n long getprocessingTime();\n long getmaxTime();\n }\n public void setUp();\n public void testTomcatInformations() throws JMException;\n}\n"}}] | [{"isEmpty": {"retrieved_name": "isEmpty", "raw_body": "boolean isEmpty(){\n return properties.isEmpty();\n}\n"}}, {"add": {"retrieved_name": "add", "raw_body": "private static int add(int t1,int t2){\n if (t1 < 0 && t2 > 0) {\n return t2;\n }\n else if (t1 > 0 && t2 < 0) {\n return t1;\n }\n return t1 + t2;\n}\n"}}, {"error": {"retrieved_name": "writeError", "raw_body": "private void writeError(CounterError error,boolean displayUser,boolean displayHttpRequest) throws IOException {\n write(\"<td align='right'>\");\n write(dateTimeFormat.format(error.getDate()));\n if (displayHttpRequest) {\n write(\"</td><td class='wrappedText'>\");\n if (error.getHttpRequest() == null) {\n write(\" \");\n }\n else {\n writeDirectly(htmlEncode(error.getHttpRequest()));\n }\n }\n if (displayUser) {\n write(\"</td><td class='wrappedText'>\");\n if (error.getRemoteUser() == null) {\n write(\" \");\n }\n else {\n writeDirectly(htmlEncode(error.getRemoteUser()));\n }\n }\n if (error.getStackTrace() != null) {\n write(\"</td><td>\");\n writeln(\"<div class='tooltip'>\");\n writeln(\"<em>\");\n writeStackTrace(error);\n writeln(\"</em>\");\n writeDirectly(htmlEncode(error.getMessage()));\n writeln(\"</div>\");\n }\n else {\n write(\"</td><td class='wrappedText'>\");\n writeDirectly(htmlEncode(error.getMessage()));\n }\n write(\"</td>\");\n}\n"}}, {"emptyList": {"retrieved_name": "isEmpty", "raw_body": "boolean isEmpty(){\n return properties.isEmpty();\n}\n"}}] | [{"buildTomcatInformationsList": {"retrieved_name": "getTomcatInformationsList", "raw_body": "public List<TomcatInformations> getTomcatInformationsList(){\n return tomcatInformationsList;\n}\n"}}] |
|
PlayEdu_PlayEdu | PlayEdu/playedu-api/src/main/java/xyz/playedu/api/controller/frontend/CourseController.java | CourseController | detail | class CourseController {
@Autowired private CourseService courseService;
@Autowired private CourseChapterService chapterService;
@Autowired private CourseHourService hourService;
@Autowired private CourseAttachmentService attachmentService;
@Autowired private ResourceService resourceService;
@Autowired private UserCourseRecordService userCourseRecordService;
@Autowired private UserCourseHourRecordService userCourseHourRecordService;
@Autowired private CourseAttachmentDownloadLogService courseAttachmentDownloadLogService;
@GetMapping("/{id}")
@SneakyThrows
public JsonResponse detail(@PathVariable(name = "id") Integer id) {<FILL_FUNCTION_BODY>}
@GetMapping("/{courseId}/attach/{id}/download")
@SneakyThrows
public JsonResponse attachmentDownload(
@PathVariable(name = "courseId") Integer courseId,
@PathVariable(name = "id") Integer id) {
CourseAttachment attachment = attachmentService.findOrFail(id, courseId);
Resource resource = resourceService.findOrFail(attachment.getRid());
HashMap<String, Object> data = new HashMap<>();
data.put("download_url", resource.getUrl());
courseAttachmentDownloadLogService.save(
new CourseAttachmentDownloadLog() {
{
setUserId(FCtx.getId());
setCourseId(attachment.getCourseId());
setCourserAttachmentId(attachment.getId());
setRid(resource.getId());
setTitle(attachment.getTitle());
setIp(IpUtil.getIpAddress());
setCreatedAt(new Date());
}
});
return JsonResponse.data(data);
}
} |
Course course = courseService.findOrFail(id);
List<CourseHour> courseHours = hourService.getHoursByCourseId(course.getId());
List<CourseAttachment> attachments =
attachmentService.getAttachmentsByCourseId(course.getId());
if (null != attachments && !attachments.isEmpty()) {
Map<Integer, Resource> resourceMap =
resourceService
.chunks(attachments.stream().map(CourseAttachment::getRid).toList())
.stream()
.collect(Collectors.toMap(Resource::getId, Function.identity()));
attachments.forEach(
courseAttachment -> {
Resource resource = resourceMap.get(courseAttachment.getRid());
if (null != resource) {
courseAttachment.setExt(resource.getExtension());
}
});
}
HashMap<String, Object> data = new HashMap<>();
data.put("course", course);
data.put("chapters", chapterService.getChaptersByCourseId(course.getId()));
data.put(
"hours",
courseHours.stream().collect(Collectors.groupingBy(CourseHour::getChapterId)));
data.put("learn_record", userCourseRecordService.find(FCtx.getId(), course.getId()));
data.put(
"learn_hour_records",
userCourseHourRecordService.getRecords(FCtx.getId(), course.getId()).stream()
.collect(Collectors.toMap(UserCourseHourRecord::getHourId, e -> e)));
data.put("attachments", attachments);
return JsonResponse.data(data);
|
Course course = courseService.findOrFail(id);
List<CourseChapter> chapters = chapterService.findByCourseId(id);
List<CourseHour> hours = hourService.findByCourseId(id);
List<CourseAttachment> attachments = attachmentService.findByCourseId(id);
HashMap<String, Object> data = new HashMap<>();
data.put("course", course);
data.put("chapters", chapters);
data.put("hours", hours);
data.put("attachments", attachments);
return JsonResponse.data(data);
| [
"CourseAttachmentService",
"List<CourseAttachment>",
"CourseService",
"CourseHourService",
"List<CourseHour>",
"List<CourseChapter>",
"CourseChapterService",
"HashMap<String,Object>",
"Course"
] | [
"data",
"findOrFail",
"put",
"findByCourseId"
] | [
"CourseAttachmentService",
"UserCourseRecordService",
"CourseHourService",
"List<CourseAttachment>",
"ResourceService",
"Map<Integer,Resource>",
"CourseChapterService",
"Resource",
"CourseService",
"HashMap<String,Object>",
"Course",
"UserCourseHourRecordService",
"List<CourseHour>"
] | [
"getId",
"getRid",
"getExtension",
"get",
"getHoursByCourseId",
"map",
"data",
"isEmpty",
"forEach",
"identity",
"groupingBy",
"findOrFail",
"getAttachmentsByCourseId",
"toMap",
"chunks",
"setExt",
"find",
"collect",
"toList",
"put",
"getRecords",
"getChaptersByCourseId",
"stream"
] | {
"methods": [
"data",
"findOrFail",
"put",
"findByCourseId"
],
"similar_methods": [
"detail"
],
"types": [
"CourseAttachmentService",
"List<CourseAttachment>",
"CourseService",
"CourseHourService",
"List<CourseHour>",
"List<CourseChapter>",
"CourseChapterService",
"HashMap<String,Object>",
"Course"
]
} | public interface CourseAttachmentService extends IService<CourseAttachment> {
CourseAttachment findOrFail( Integer id, Integer courseId) throws NotFoundException ;
void update( CourseAttachment courseAttachment, Integer sort, String title);
List<CourseAttachment> getAttachmentsByCourseId( Integer courseId);
CourseAttachment create( Integer courseId, Integer sort, String title, String type, Integer rid);
Integer getCountByCourseId( Integer courseId);
void remove( Integer courseId);
void updateSort( List<Integer> ids, Integer cid);
List<Integer> getRidsByCourseId( Integer courseId);
List<CourseAttachment> chunk( List<Integer> attachmentIds);
}
/**
* @TableName course_attachment
*/
@TableName(value="course_attachment") @Data public class CourseAttachment implements Serializable {
/**
*/
@TableId(type=IdType.AUTO) private Integer id;
/**
* 课程ID
*/
@JsonProperty("course_id") private Integer courseId;
/**
* 升序
*/
private Integer sort;
/**
* 附件名
*/
private String title;
/**
* 类型
*/
private String type;
/**
* 资源id
*/
private Integer rid;
/**
* 资源url
*/
@TableField(exist=false) private String url;
/**
* 资源类型
*/
@TableField(exist=false) private String ext;
/**
*/
@JsonIgnore private Date createdAt;
@TableField(exist=false) private static final long serialVersionUID=1L;
@Override public boolean equals( Object that);
@Override public int hashCode();
@Override public String toString();
}
/**
* @author tengteng
* @description 针对表【courses】的数据库操作Service
* @createDate 2023-02-24 14:14:01
*/
public interface CourseService extends IService<Course> {
PaginationResult<Course> paginate( int page, int size, CoursePaginateFiler filter);
Course createWithCategoryIdsAndDepIds( String title, String thumb, String shortDesc, Integer isRequired, Integer isShow, Integer[] categoryIds, Integer[] depIds, Integer adminId);
void updateWithCategoryIdsAndDepIds( Course course, String title, String thumb, String shortDesc, Integer isRequired, Integer isShow, Date publishedAt, Integer[] categoryIds, Integer[] depIds);
void relateDepartments( Course course, Integer[] depIds);
void resetRelateDepartments( Course course, Integer[] depIds);
void relateCategories( Course course, Integer[] categoryIds);
void resetRelateCategories( Course course, Integer[] categoryIds);
Course findOrFail( Integer id) throws NotFoundException ;
List<Integer> getDepIdsByCourseId( Integer courseId);
List<Integer> getCategoryIdsByCourseId( Integer courseId);
void updateClassHour( Integer courseId, Integer classHour);
void removeCategoryIdRelate( Integer categoryId);
List<Course> chunks( List<Integer> ids, List<String> fields);
List<Course> chunks( List<Integer> ids);
List<Course> getOpenCoursesAndShow( Integer limit);
List<Course> getOpenCoursesAndShow( Integer limit, Integer categoryId);
List<Course> getDepCoursesAndShow( List<Integer> depIds);
List<Course> getDepCoursesAndShow( List<Integer> depIds, Integer categoryId);
Map<Integer,List<Integer>> getCategoryIdsGroup( List<Integer> courseIds);
Map<Integer,List<Integer>> getDepIdsGroup( List<Integer> courseIds);
Long total();
}
/**
* @author tengteng
* @description 针对表【course_hour】的数据库操作Service
* @createDate 2023-03-15 10:16:45
*/
public interface CourseHourService extends IService<CourseHour> {
CourseHour findOrFail( Integer id, Integer courseId) throws NotFoundException ;
void update( CourseHour courseHour, Integer chapterId, Integer sort, String title, Integer duration);
List<CourseHour> getHoursByCourseId( Integer courseId);
CourseHour create( Integer courseId, Integer chapterId, Integer sort, String title, String type, Integer rid, Integer duration);
Integer getCountByCourseId( Integer courseId);
Integer getCountByChapterId( Integer chapterId);
void remove( Integer courseId, Integer chapterId);
void updateSort( List<Integer> ids, Integer cid);
List<Integer> getRidsByCourseId( Integer courseId, String type);
List<CourseHour> chunk( List<Integer> hourIds);
}
/**
* @TableName course_hour
*/
@TableName(value="course_hour") @Data public class CourseHour implements Serializable {
/**
*/
@TableId(type=IdType.AUTO) private Integer id;
/**
* 课程ID
*/
@JsonProperty("course_id") private Integer courseId;
/**
* 章节ID
*/
@JsonProperty("chapter_id") private Integer chapterId;
/**
* 升序
*/
private Integer sort;
/**
* 课时名
*/
private String title;
/**
* 课时类型
*/
private String type;
/**
* 资源id
*/
private Integer rid;
/**
* 时长[s]
*/
private Integer duration;
/**
*/
@JsonIgnore private Date createdAt;
@TableField(exist=false) private static final long serialVersionUID=1L;
@Override public boolean equals( Object that);
@Override public int hashCode();
@Override public String toString();
}
/**
* @TableName course_chapters
*/
@TableName(value="course_chapters") @Data public class CourseChapter implements Serializable {
/**
*/
@TableId(type=IdType.AUTO) private Integer id;
/**
* 课程ID
*/
@JsonProperty("course_id") private Integer courseId;
/**
* 章节名
*/
private String name;
/**
* 升序
*/
private Integer sort;
@JsonProperty("created_at") private Date createdAt;
@JsonProperty("updated_at") private Date updatedAt;
@TableField(exist=false) private static final long serialVersionUID=1L;
@Override public boolean equals( Object that);
@Override public int hashCode();
@Override public String toString();
}
/**
* @author tengteng
* @description 针对表【course_chapters】的数据库操作Service
* @createDate 2023-02-26 17:30:19
*/
public interface CourseChapterService extends IService<CourseChapter> {
List<CourseChapter> getChaptersByCourseId( Integer courseId);
void create( Integer courseId, String name, Integer sort);
void update( CourseChapter chapter, String name, Integer sort);
CourseChapter findOrFail( Integer id) throws NotFoundException ;
CourseChapter findOrFail( Integer id, Integer courseId) throws NotFoundException ;
void updateSort( List<Integer> ids, Integer cid);
}
/**
* 字符串工具类
*/
public class StringUtil extends org.apache.commons.lang3.StringUtils {
/**
* 空字符串
*/
private static final String NULL_STR="";
/**
* 下划线
*/
private static final char SEPARATOR='_';
/**
* 获取参数不为空值
* @param value defaultValue 要判断的value
* @return value 返回值
*/
public static <T>T nvl( T value, T defaultValue);
/**
* 判断一个Collection是否为空,包含List, Set, Queue
* @param coll 要判断的Collection
* @return true=为空, false=非空
*/
public static boolean isEmpty( Collection<?> coll);
/**
* 判断一个Collection是否非空,包含List, Set, Queue
* @param coll 要判断的Collection
* @return true=非空, false=空
*/
public static boolean isNotEmpty( Collection<?> coll);
/**
* 判断一个对象数组是否为空
* @param objects 要判断的对象数组
* @return true=为空, false=非空
*/
public static boolean isEmpty( Object[] objects);
/**
* 判断一个对象数组是否非空
* @param objects 要判断的对象数组
* @return true=非空, false=空
*/
public static boolean isNotEmpty( Object[] objects);
/**
* 判断一个Map是否为空
* @param map 要判断的Map
* @return true=为空, false=非空
*/
public static boolean isEmpty( Map<?,?> map);
/**
* 判断一个Map是否为空
* @param map 要判断的Map
* @return true=非空, false=空
*/
public static boolean isNotEmpty( Map<?,?> map);
/**
* 判断一个字符串是否为空串
* @param str String
* @return true=为空, false=非空
*/
public static boolean isEmpty( String str);
/**
* 判断一个字符串是否为非空串
* @param str String
* @return true=非空串, false=空串
*/
public static boolean isNotEmpty( String str);
/**
* 判断一个对象是否为空
* @param object Object
* @return true=为空, false=非空
*/
public static boolean isNull( Object object);
/**
* 判断一个对象是否非空
* @param object Object
* @return true=非空, false=空
*/
public static boolean isNotNull( Object object);
/**
* 判断一个对象是否是数组类型(Java基本型别的数组)
* @param object 对象
* @return true=是数组, false=不是数组
*/
public static boolean isArray( Object object);
/**
* 去空格
*/
public static String trim( String str);
/**
* 截取字符串
* @param str 字符串
* @param start 开始
* @return 结果
*/
public static String substring( final String str, int start);
/**
* 截取字符串
* @param str 字符串
* @param start 开始
* @param end 结束
* @return 结果
*/
public static String substring( final String str, int start, int end);
/**
* 字符串转set
* @param str 字符串
* @param sep 分隔符
* @return set集合
*/
public static Set<String> str2Set( String str, String sep);
/**
* 字符串转list
* @param str 字符串
* @param sep 分隔符
* @param filterBlank 过滤纯空白
* @param trim 去掉首尾空白
* @return list集合
*/
public static List<String> str2List( String str, String sep, boolean filterBlank, boolean trim);
/**
* 查找指定字符串是否包含指定字符串列表中的任意一个字符串同时串忽略大小写
* @param cs 指定字符串
* @param searchCharSequences 需要检查的字符串数组
* @return 是否包含任意一个字符串
*/
public static boolean containsAnyIgnoreCase( CharSequence cs, CharSequence... searchCharSequences);
/**
* 驼峰转下划线命名
*/
public static String toUnderScoreCase( String str);
/**
* 是否包含字符串
* @param str 验证字符串
* @param strArr 字符串组
* @return 包含返回true
*/
public static boolean inStringIgnoreCase( String str, String... strArr);
/**
* 将下划线大写方式命名的字符串转换为驼峰式。 如果转换前的下划线大写方式命名的字符串为空, 则返回空字符串。 例如:HELLO_WORLD->HelloWorld
* @param name 转换前的下划线大写方式命名的字符串
* @return 转换后的驼峰式命名的字符串
*/
public static String convertToCamelCase( String name);
/**
* 驼峰式命名法 例如:user_name->userName
* @param s 字符串
* @return 驼峰字符串
*/
public static String toCamelCase( String s);
/**
* 查找指定字符串是否匹配指定字符串列表中的任意一个字符串
* @param str 指定字符串
* @param strArr 需要检查的字符串数组
* @return 是否匹配
*/
public static boolean matches( String str, List<String> strArr);
/**
* 判断url是否与规则配置: ? 表示单个字符; * 表示一层路径内的任意字符串,不可跨层级; ** 表示任意层路径;
* @param pattern 匹配规则
* @param url 需要匹配的url
* @return boolean
*/
public static boolean isMatch( String pattern, String url);
/**
* 数字左边补齐0,使之达到指定长度。 注意,如果数字转换为字符串后,长度大于size,则只保留 最后size个字符。
* @param num 数字对象
* @param size 字符串指定长度
* @return 返回数字的字符串格式,该字符串为指定长度。
*/
public static String padL( final Number num, final int size);
/**
* 字符串左补齐 如果原始字符串s长度大于size,则只保留最后size个字符。
* @param s 原始字符串
* @param size 字符串指定长度
* @param c 用于补齐的字符
* @return 返回指定长度的字符串,由原字符串左补齐或截取得到。
*/
public static String padL( final String s, final int size, final char c);
/**
* 格式化文本, {} 表示占位符<br> 此方法只是简单将占位符 {} 按照顺序替换为参数<br> 如果想输出 {} 使用 \\转义 { 即可,如果想输出 {} 之前的 \ 使用双转义符 \\\\ 即可<br> 例:<br> 通常使用:format("this is {} for {}", "a", "b") -> this is a for b<br> 转义{}: format("this is \\{} for {}", "a", "b") -> this is \{} for a<br> 转义\: format("this is \\\\{} for {}", "a", "b") -> this is \a for b<br>
* @param strPattern 文本模板,被替换的部分用 {} 表示
* @param argArray 参数值
* @return 格式化后的文本
*/
public static String format( String strPattern, Object... argArray);
public static String arrayToString( Object[] array);
}
/**
* @TableName courses
*/
@TableName(value="courses") @Data public class Course implements Serializable {
/**
*/
@TableId(type=IdType.AUTO) private Integer id;
/**
* 课程标题
*/
private String title;
/**
* 课程封面
*/
private String thumb;
/**
* 课程价格(分)
*/
private Integer charge;
/**
* 课程简介
*/
@JsonProperty("short_desc") private String shortDesc;
/**
* 1:必修,0:选修
*/
@JsonProperty("is_required") private Integer isRequired;
/**
* 课时数
*/
@JsonProperty("class_hour") private Integer classHour;
/**
* 显示[1:是,0:否]
*/
@JsonProperty("is_show") private Integer isShow;
@JsonProperty("published_at") private Date publishedAt;
@JsonProperty("created_at") private Date createdAt;
@JsonProperty("admin_id") private Integer adminId;
@JsonIgnore private Date updatedAt;
@JsonIgnore private Date deletedAt;
@Serial @TableField(exist=false) private static final long serialVersionUID=1L;
}
public static JsonResponse data(Object data){
return new JsonResponse(0,"",data);
}
CourseChapter findOrFail(Integer id) throws NotFoundException ;
private static void put(String key,Object val){
LinkedHashMap<String,Object> hashMap=THREAD_LOCAL.get();
if (hashMap == null) {
hashMap=new LinkedHashMap<>();
}
hashMap.put(key,val);
THREAD_LOCAL.set(hashMap);
}
@Override public List<Integer> getRidsByCourseId(Integer courseId){
return list(query().getWrapper().eq("course_id",courseId)).stream().map(CourseAttachment::getRid).toList();
}
@GetMapping("/detail") @Log(title="管理员-详情",businessType=BusinessTypeConstant.GET) public JsonResponse detail(){
AdminUser user=BCtx.getAdminUser();
HashMap<String,Boolean> permissions=backendBus.adminUserPermissions(user.getId());
HashMap<String,Object> data=new HashMap<>();
data.put("user",user);
data.put("permissions",permissions);
return JsonResponse.data(data);
}
| public interface CourseAttachmentService extends IService<CourseAttachment> {
CourseAttachment findOrFail( Integer id, Integer courseId) throws NotFoundException ;
void update( CourseAttachment courseAttachment, Integer sort, String title);
List<CourseAttachment> getAttachmentsByCourseId( Integer courseId);
CourseAttachment create( Integer courseId, Integer sort, String title, String type, Integer rid);
Integer getCountByCourseId( Integer courseId);
void remove( Integer courseId);
void updateSort( List<Integer> ids, Integer cid);
List<Integer> getRidsByCourseId( Integer courseId);
List<CourseAttachment> chunk( List<Integer> attachmentIds);
}
public class CourseAttachment implements Serializable {
private Integer id;
private Integer courseId;
private Integer sort;
private String title;
private String type;
private Integer rid;
private String url;
private String ext;
private Date createdAt;
private static final long serialVersionUID=1L;
public boolean equals( Object that);
public int hashCode();
public String toString();
}
public interface CourseService extends IService<Course> {
PaginationResult<Course> paginate( int page, int size, CoursePaginateFiler filter);
Course createWithCategoryIdsAndDepIds( String title, String thumb, String shortDesc, Integer isRequired, Integer isShow, Integer[] categoryIds, Integer[] depIds, Integer adminId);
void updateWithCategoryIdsAndDepIds( Course course, String title, String thumb, String shortDesc, Integer isRequired, Integer isShow, Date publishedAt, Integer[] categoryIds, Integer[] depIds);
void relateDepartments( Course course, Integer[] depIds);
void resetRelateDepartments( Course course, Integer[] depIds);
void relateCategories( Course course, Integer[] categoryIds);
void resetRelateCategories( Course course, Integer[] categoryIds);
Course findOrFail( Integer id) throws NotFoundException ;
List<Integer> getDepIdsByCourseId( Integer courseId);
List<Integer> getCategoryIdsByCourseId( Integer courseId);
void updateClassHour( Integer courseId, Integer classHour);
void removeCategoryIdRelate( Integer categoryId);
List<Course> chunks( List<Integer> ids, List<String> fields);
List<Course> chunks( List<Integer> ids);
List<Course> getOpenCoursesAndShow( Integer limit);
List<Course> getOpenCoursesAndShow( Integer limit, Integer categoryId);
List<Course> getDepCoursesAndShow( List<Integer> depIds);
List<Course> getDepCoursesAndShow( List<Integer> depIds, Integer categoryId);
Map<Integer,List<Integer>> getCategoryIdsGroup( List<Integer> courseIds);
Map<Integer,List<Integer>> getDepIdsGroup( List<Integer> courseIds);
Long total();
}
public interface CourseHourService extends IService<CourseHour> {
CourseHour findOrFail( Integer id, Integer courseId) throws NotFoundException ;
void update( CourseHour courseHour, Integer chapterId, Integer sort, String title, Integer duration);
List<CourseHour> getHoursByCourseId( Integer courseId);
CourseHour create( Integer courseId, Integer chapterId, Integer sort, String title, String type, Integer rid, Integer duration);
Integer getCountByCourseId( Integer courseId);
Integer getCountByChapterId( Integer chapterId);
void remove( Integer courseId, Integer chapterId);
void updateSort( List<Integer> ids, Integer cid);
List<Integer> getRidsByCourseId( Integer courseId, String type);
List<CourseHour> chunk( List<Integer> hourIds);
}
public class CourseHour implements Serializable {
private Integer id;
private Integer courseId;
private Integer chapterId;
private Integer sort;
private String title;
private String type;
private Integer rid;
private Integer duration;
private Date createdAt;
private static final long serialVersionUID=1L;
public boolean equals( Object that);
public int hashCode();
public String toString();
}
public class CourseChapter implements Serializable {
private Integer id;
private Integer courseId;
private String name;
private Integer sort;
private Date createdAt;
private Date updatedAt;
private static final long serialVersionUID=1L;
public boolean equals( Object that);
public int hashCode();
public String toString();
}
public interface CourseChapterService extends IService<CourseChapter> {
List<CourseChapter> getChaptersByCourseId( Integer courseId);
void create( Integer courseId, String name, Integer sort);
void update( CourseChapter chapter, String name, Integer sort);
CourseChapter findOrFail( Integer id) throws NotFoundException ;
CourseChapter findOrFail( Integer id, Integer courseId) throws NotFoundException ;
void updateSort( List<Integer> ids, Integer cid);
}
public class StringUtil extends org.apache.commons.lang3.StringUtils {
private static final String NULL_STR="";
private static final char SEPARATOR='_';
public static <T>T nvl( T value, T defaultValue);
public static boolean isEmpty( Collection<?> coll);
public static boolean isNotEmpty( Collection<?> coll);
public static boolean isEmpty( Object[] objects);
public static boolean isNotEmpty( Object[] objects);
public static boolean isEmpty( Map<?,?> map);
public static boolean isNotEmpty( Map<?,?> map);
public static boolean isEmpty( String str);
public static boolean isNotEmpty( String str);
public static boolean isNull( Object object);
public static boolean isNotNull( Object object);
public static boolean isArray( Object object);
public static String trim( String str);
public static String substring( final String str, int start);
public static String substring( final String str, int start, int end);
public static Set<String> str2Set( String str, String sep);
public static List<String> str2List( String str, String sep, boolean filterBlank, boolean trim);
public static boolean containsAnyIgnoreCase( CharSequence cs, CharSequence... searchCharSequences);
public static String toUnderScoreCase( String str);
public static boolean inStringIgnoreCase( String str, String... strArr);
public static String convertToCamelCase( String name);
public static String toCamelCase( String s);
public static boolean matches( String str, List<String> strArr);
public static boolean isMatch( String pattern, String url);
public static String padL( final Number num, final int size);
public static String padL( final String s, final int size, final char c);
public static String format( String strPattern, Object... argArray);
public static String arrayToString( Object[] array);
}
public class Course implements Serializable {
private Integer id;
private String title;
private String thumb;
private Integer charge;
private String shortDesc;
private Integer isRequired;
private Integer classHour;
private Integer isShow;
private Date publishedAt;
private Date createdAt;
private Integer adminId;
private Date updatedAt;
private Date deletedAt;
private static final long serialVersionUID=1L;
}
public static JsonResponse data(Object data){
return new JsonResponse(0,"",data);
}
CourseChapter findOrFail(Integer id) throws NotFoundException ;
private static void put(String key,Object val){
LinkedHashMap<String,Object> hashMap=THREAD_LOCAL.get();
if (hashMap == null) {
hashMap=new LinkedHashMap<>();
}
hashMap.put(key,val);
THREAD_LOCAL.set(hashMap);
}
@Override public List<Integer> getRidsByCourseId(Integer courseId){
return list(query().getWrapper().eq("course_id",courseId)).stream().map(CourseAttachment::getRid).toList();
}
@GetMapping("/detail") @Log(title="管理员-详情",businessType=BusinessTypeConstant.GET) public JsonResponse detail(){
AdminUser user=BCtx.getAdminUser();
HashMap<String,Boolean> permissions=backendBus.adminUserPermissions(user.getId());
HashMap<String,Object> data=new HashMap<>();
data.put("user",user);
data.put("permissions",permissions);
return JsonResponse.data(data);
}
| {"types": [{"CourseAttachmentService": "CourseAttachmentService"}, {"List<CourseAttachment>": "CourseAttachment"}, {"CourseService": "CourseService"}, {"CourseHourService": "CourseHourService"}, {"List<CourseHour>": "CourseHour"}, {"List<CourseChapter>": "CourseChapter"}, {"CourseChapterService": "CourseChapterService"}, {"HashMap<String,Object>": "StringUtil"}, {"Course": "Course"}], "methods": [{"data": "data"}, {"findOrFail": "findOrFail"}, {"put": "put"}, {"findByCourseId": "getRidsByCourseId"}], "similar_methods": [{"detail": "detail"}]} | [{"CourseAttachmentService": {"retrieved_name": "CourseAttachmentService", "raw_body": "public interface CourseAttachmentService extends IService<CourseAttachment> {\n CourseAttachment findOrFail( Integer id, Integer courseId) throws NotFoundException ;\n void update( CourseAttachment courseAttachment, Integer sort, String title);\n List<CourseAttachment> getAttachmentsByCourseId( Integer courseId);\n CourseAttachment create( Integer courseId, Integer sort, String title, String type, Integer rid);\n Integer getCountByCourseId( Integer courseId);\n void remove( Integer courseId);\n void updateSort( List<Integer> ids, Integer cid);\n List<Integer> getRidsByCourseId( Integer courseId);\n List<CourseAttachment> chunk( List<Integer> attachmentIds);\n}\n", "raw_body_no_cmt": "public interface CourseAttachmentService extends IService<CourseAttachment> {\n CourseAttachment findOrFail( Integer id, Integer courseId) throws NotFoundException ;\n void update( CourseAttachment courseAttachment, Integer sort, String title);\n List<CourseAttachment> getAttachmentsByCourseId( Integer courseId);\n CourseAttachment create( Integer courseId, Integer sort, String title, String type, Integer rid);\n Integer getCountByCourseId( Integer courseId);\n void remove( Integer courseId);\n void updateSort( List<Integer> ids, Integer cid);\n List<Integer> getRidsByCourseId( Integer courseId);\n List<CourseAttachment> chunk( List<Integer> attachmentIds);\n}\n"}}, {"List<CourseAttachment>": {"retrieved_name": "CourseAttachment", "raw_body": "/** \n * @TableName course_attachment\n */\n@TableName(value=\"course_attachment\") @Data public class CourseAttachment implements Serializable {\n /** \n */\n @TableId(type=IdType.AUTO) private Integer id;\n /** \n * \u8bfe\u7a0bID \n */\n @JsonProperty(\"course_id\") private Integer courseId;\n /** \n * \u5347\u5e8f \n */\n private Integer sort;\n /** \n * \u9644\u4ef6\u540d \n */\n private String title;\n /** \n * \u7c7b\u578b \n */\n private String type;\n /** \n * \u8d44\u6e90id \n */\n private Integer rid;\n /** \n * \u8d44\u6e90url \n */\n @TableField(exist=false) private String url;\n /** \n * \u8d44\u6e90\u7c7b\u578b \n */\n @TableField(exist=false) private String ext;\n /** \n */\n @JsonIgnore private Date createdAt;\n @TableField(exist=false) private static final long serialVersionUID=1L;\n @Override public boolean equals( Object that);\n @Override public int hashCode();\n @Override public String toString();\n}\n", "raw_body_no_cmt": "public class CourseAttachment implements Serializable {\n private Integer id;\n private Integer courseId;\n private Integer sort;\n private String title;\n private String type;\n private Integer rid;\n private String url;\n private String ext;\n private Date createdAt;\n private static final long serialVersionUID=1L;\n public boolean equals( Object that);\n public int hashCode();\n public String toString();\n}\n"}}, {"CourseService": {"retrieved_name": "CourseService", "raw_body": "/** \n * @author tengteng\n * @description \u9488\u5bf9\u8868\u3010courses\u3011\u7684\u6570\u636e\u5e93\u64cd\u4f5cService\n * @createDate 2023-02-24 14:14:01\n */\npublic interface CourseService extends IService<Course> {\n PaginationResult<Course> paginate( int page, int size, CoursePaginateFiler filter);\n Course createWithCategoryIdsAndDepIds( String title, String thumb, String shortDesc, Integer isRequired, Integer isShow, Integer[] categoryIds, Integer[] depIds, Integer adminId);\n void updateWithCategoryIdsAndDepIds( Course course, String title, String thumb, String shortDesc, Integer isRequired, Integer isShow, Date publishedAt, Integer[] categoryIds, Integer[] depIds);\n void relateDepartments( Course course, Integer[] depIds);\n void resetRelateDepartments( Course course, Integer[] depIds);\n void relateCategories( Course course, Integer[] categoryIds);\n void resetRelateCategories( Course course, Integer[] categoryIds);\n Course findOrFail( Integer id) throws NotFoundException ;\n List<Integer> getDepIdsByCourseId( Integer courseId);\n List<Integer> getCategoryIdsByCourseId( Integer courseId);\n void updateClassHour( Integer courseId, Integer classHour);\n void removeCategoryIdRelate( Integer categoryId);\n List<Course> chunks( List<Integer> ids, List<String> fields);\n List<Course> chunks( List<Integer> ids);\n List<Course> getOpenCoursesAndShow( Integer limit);\n List<Course> getOpenCoursesAndShow( Integer limit, Integer categoryId);\n List<Course> getDepCoursesAndShow( List<Integer> depIds);\n List<Course> getDepCoursesAndShow( List<Integer> depIds, Integer categoryId);\n Map<Integer,List<Integer>> getCategoryIdsGroup( List<Integer> courseIds);\n Map<Integer,List<Integer>> getDepIdsGroup( List<Integer> courseIds);\n Long total();\n}\n", "raw_body_no_cmt": "public interface CourseService extends IService<Course> {\n PaginationResult<Course> paginate( int page, int size, CoursePaginateFiler filter);\n Course createWithCategoryIdsAndDepIds( String title, String thumb, String shortDesc, Integer isRequired, Integer isShow, Integer[] categoryIds, Integer[] depIds, Integer adminId);\n void updateWithCategoryIdsAndDepIds( Course course, String title, String thumb, String shortDesc, Integer isRequired, Integer isShow, Date publishedAt, Integer[] categoryIds, Integer[] depIds);\n void relateDepartments( Course course, Integer[] depIds);\n void resetRelateDepartments( Course course, Integer[] depIds);\n void relateCategories( Course course, Integer[] categoryIds);\n void resetRelateCategories( Course course, Integer[] categoryIds);\n Course findOrFail( Integer id) throws NotFoundException ;\n List<Integer> getDepIdsByCourseId( Integer courseId);\n List<Integer> getCategoryIdsByCourseId( Integer courseId);\n void updateClassHour( Integer courseId, Integer classHour);\n void removeCategoryIdRelate( Integer categoryId);\n List<Course> chunks( List<Integer> ids, List<String> fields);\n List<Course> chunks( List<Integer> ids);\n List<Course> getOpenCoursesAndShow( Integer limit);\n List<Course> getOpenCoursesAndShow( Integer limit, Integer categoryId);\n List<Course> getDepCoursesAndShow( List<Integer> depIds);\n List<Course> getDepCoursesAndShow( List<Integer> depIds, Integer categoryId);\n Map<Integer,List<Integer>> getCategoryIdsGroup( List<Integer> courseIds);\n Map<Integer,List<Integer>> getDepIdsGroup( List<Integer> courseIds);\n Long total();\n}\n"}}, {"CourseHourService": {"retrieved_name": "CourseHourService", "raw_body": "/** \n * @author tengteng\n * @description \u9488\u5bf9\u8868\u3010course_hour\u3011\u7684\u6570\u636e\u5e93\u64cd\u4f5cService\n * @createDate 2023-03-15 10:16:45\n */\npublic interface CourseHourService extends IService<CourseHour> {\n CourseHour findOrFail( Integer id, Integer courseId) throws NotFoundException ;\n void update( CourseHour courseHour, Integer chapterId, Integer sort, String title, Integer duration);\n List<CourseHour> getHoursByCourseId( Integer courseId);\n CourseHour create( Integer courseId, Integer chapterId, Integer sort, String title, String type, Integer rid, Integer duration);\n Integer getCountByCourseId( Integer courseId);\n Integer getCountByChapterId( Integer chapterId);\n void remove( Integer courseId, Integer chapterId);\n void updateSort( List<Integer> ids, Integer cid);\n List<Integer> getRidsByCourseId( Integer courseId, String type);\n List<CourseHour> chunk( List<Integer> hourIds);\n}\n", "raw_body_no_cmt": "public interface CourseHourService extends IService<CourseHour> {\n CourseHour findOrFail( Integer id, Integer courseId) throws NotFoundException ;\n void update( CourseHour courseHour, Integer chapterId, Integer sort, String title, Integer duration);\n List<CourseHour> getHoursByCourseId( Integer courseId);\n CourseHour create( Integer courseId, Integer chapterId, Integer sort, String title, String type, Integer rid, Integer duration);\n Integer getCountByCourseId( Integer courseId);\n Integer getCountByChapterId( Integer chapterId);\n void remove( Integer courseId, Integer chapterId);\n void updateSort( List<Integer> ids, Integer cid);\n List<Integer> getRidsByCourseId( Integer courseId, String type);\n List<CourseHour> chunk( List<Integer> hourIds);\n}\n"}}, {"List<CourseHour>": {"retrieved_name": "CourseHour", "raw_body": "/** \n * @TableName course_hour\n */\n@TableName(value=\"course_hour\") @Data public class CourseHour implements Serializable {\n /** \n */\n @TableId(type=IdType.AUTO) private Integer id;\n /** \n * \u8bfe\u7a0bID \n */\n @JsonProperty(\"course_id\") private Integer courseId;\n /** \n * \u7ae0\u8282ID \n */\n @JsonProperty(\"chapter_id\") private Integer chapterId;\n /** \n * \u5347\u5e8f \n */\n private Integer sort;\n /** \n * \u8bfe\u65f6\u540d \n */\n private String title;\n /** \n * \u8bfe\u65f6\u7c7b\u578b \n */\n private String type;\n /** \n * \u8d44\u6e90id \n */\n private Integer rid;\n /** \n * \u65f6\u957f[s] \n */\n private Integer duration;\n /** \n */\n @JsonIgnore private Date createdAt;\n @TableField(exist=false) private static final long serialVersionUID=1L;\n @Override public boolean equals( Object that);\n @Override public int hashCode();\n @Override public String toString();\n}\n", "raw_body_no_cmt": "public class CourseHour implements Serializable {\n private Integer id;\n private Integer courseId;\n private Integer chapterId;\n private Integer sort;\n private String title;\n private String type;\n private Integer rid;\n private Integer duration;\n private Date createdAt;\n private static final long serialVersionUID=1L;\n public boolean equals( Object that);\n public int hashCode();\n public String toString();\n}\n"}}, {"List<CourseChapter>": {"retrieved_name": "CourseChapter", "raw_body": "/** \n * @TableName course_chapters\n */\n@TableName(value=\"course_chapters\") @Data public class CourseChapter implements Serializable {\n /** \n */\n @TableId(type=IdType.AUTO) private Integer id;\n /** \n * \u8bfe\u7a0bID \n */\n @JsonProperty(\"course_id\") private Integer courseId;\n /** \n * \u7ae0\u8282\u540d \n */\n private String name;\n /** \n * \u5347\u5e8f \n */\n private Integer sort;\n @JsonProperty(\"created_at\") private Date createdAt;\n @JsonProperty(\"updated_at\") private Date updatedAt;\n @TableField(exist=false) private static final long serialVersionUID=1L;\n @Override public boolean equals( Object that);\n @Override public int hashCode();\n @Override public String toString();\n}\n", "raw_body_no_cmt": "public class CourseChapter implements Serializable {\n private Integer id;\n private Integer courseId;\n private String name;\n private Integer sort;\n private Date createdAt;\n private Date updatedAt;\n private static final long serialVersionUID=1L;\n public boolean equals( Object that);\n public int hashCode();\n public String toString();\n}\n"}}, {"CourseChapterService": {"retrieved_name": "CourseChapterService", "raw_body": "/** \n * @author tengteng\n * @description \u9488\u5bf9\u8868\u3010course_chapters\u3011\u7684\u6570\u636e\u5e93\u64cd\u4f5cService\n * @createDate 2023-02-26 17:30:19\n */\npublic interface CourseChapterService extends IService<CourseChapter> {\n List<CourseChapter> getChaptersByCourseId( Integer courseId);\n void create( Integer courseId, String name, Integer sort);\n void update( CourseChapter chapter, String name, Integer sort);\n CourseChapter findOrFail( Integer id) throws NotFoundException ;\n CourseChapter findOrFail( Integer id, Integer courseId) throws NotFoundException ;\n void updateSort( List<Integer> ids, Integer cid);\n}\n", "raw_body_no_cmt": "public interface CourseChapterService extends IService<CourseChapter> {\n List<CourseChapter> getChaptersByCourseId( Integer courseId);\n void create( Integer courseId, String name, Integer sort);\n void update( CourseChapter chapter, String name, Integer sort);\n CourseChapter findOrFail( Integer id) throws NotFoundException ;\n CourseChapter findOrFail( Integer id, Integer courseId) throws NotFoundException ;\n void updateSort( List<Integer> ids, Integer cid);\n}\n"}}, {"HashMap<String,Object>": {"retrieved_name": "StringUtil", "raw_body": "/** \n * \u5b57\u7b26\u4e32\u5de5\u5177\u7c7b \n */\npublic class StringUtil extends org.apache.commons.lang3.StringUtils {\n /** \n * \u7a7a\u5b57\u7b26\u4e32 \n */\n private static final String NULL_STR=\"\";\n /** \n * \u4e0b\u5212\u7ebf \n */\n private static final char SEPARATOR='_';\n /** \n * \u83b7\u53d6\u53c2\u6570\u4e0d\u4e3a\u7a7a\u503c\n * @param value defaultValue \u8981\u5224\u65ad\u7684value\n * @return value \u8fd4\u56de\u503c\n */\n public static <T>T nvl( T value, T defaultValue);\n /** \n * \u5224\u65ad\u4e00\u4e2aCollection\u662f\u5426\u4e3a\u7a7a,\u5305\u542bList, Set, Queue\n * @param coll \u8981\u5224\u65ad\u7684Collection\n * @return true=\u4e3a\u7a7a, false=\u975e\u7a7a\n */\n public static boolean isEmpty( Collection<?> coll);\n /** \n * \u5224\u65ad\u4e00\u4e2aCollection\u662f\u5426\u975e\u7a7a,\u5305\u542bList, Set, Queue\n * @param coll \u8981\u5224\u65ad\u7684Collection\n * @return true=\u975e\u7a7a, false=\u7a7a\n */\n public static boolean isNotEmpty( Collection<?> coll);\n /** \n * \u5224\u65ad\u4e00\u4e2a\u5bf9\u8c61\u6570\u7ec4\u662f\u5426\u4e3a\u7a7a\n * @param objects \u8981\u5224\u65ad\u7684\u5bf9\u8c61\u6570\u7ec4\n * @return true=\u4e3a\u7a7a, false=\u975e\u7a7a\n */\n public static boolean isEmpty( Object[] objects);\n /** \n * \u5224\u65ad\u4e00\u4e2a\u5bf9\u8c61\u6570\u7ec4\u662f\u5426\u975e\u7a7a\n * @param objects \u8981\u5224\u65ad\u7684\u5bf9\u8c61\u6570\u7ec4\n * @return true=\u975e\u7a7a, false=\u7a7a\n */\n public static boolean isNotEmpty( Object[] objects);\n /** \n * \u5224\u65ad\u4e00\u4e2aMap\u662f\u5426\u4e3a\u7a7a\n * @param map \u8981\u5224\u65ad\u7684Map\n * @return true=\u4e3a\u7a7a, false=\u975e\u7a7a\n */\n public static boolean isEmpty( Map<?,?> map);\n /** \n * \u5224\u65ad\u4e00\u4e2aMap\u662f\u5426\u4e3a\u7a7a\n * @param map \u8981\u5224\u65ad\u7684Map\n * @return true=\u975e\u7a7a, false=\u7a7a\n */\n public static boolean isNotEmpty( Map<?,?> map);\n /** \n * \u5224\u65ad\u4e00\u4e2a\u5b57\u7b26\u4e32\u662f\u5426\u4e3a\u7a7a\u4e32\n * @param str String\n * @return true=\u4e3a\u7a7a, false=\u975e\u7a7a\n */\n public static boolean isEmpty( String str);\n /** \n * \u5224\u65ad\u4e00\u4e2a\u5b57\u7b26\u4e32\u662f\u5426\u4e3a\u975e\u7a7a\u4e32\n * @param str String\n * @return true=\u975e\u7a7a\u4e32, false=\u7a7a\u4e32\n */\n public static boolean isNotEmpty( String str);\n /** \n * \u5224\u65ad\u4e00\u4e2a\u5bf9\u8c61\u662f\u5426\u4e3a\u7a7a\n * @param object Object\n * @return true=\u4e3a\u7a7a, false=\u975e\u7a7a\n */\n public static boolean isNull( Object object);\n /** \n * \u5224\u65ad\u4e00\u4e2a\u5bf9\u8c61\u662f\u5426\u975e\u7a7a\n * @param object Object\n * @return true=\u975e\u7a7a, false=\u7a7a\n */\n public static boolean isNotNull( Object object);\n /** \n * \u5224\u65ad\u4e00\u4e2a\u5bf9\u8c61\u662f\u5426\u662f\u6570\u7ec4\u7c7b\u578b\uff08Java\u57fa\u672c\u578b\u522b\u7684\u6570\u7ec4\uff09\n * @param object \u5bf9\u8c61\n * @return true=\u662f\u6570\u7ec4, false=\u4e0d\u662f\u6570\u7ec4\n */\n public static boolean isArray( Object object);\n /** \n * \u53bb\u7a7a\u683c \n */\n public static String trim( String str);\n /** \n * \u622a\u53d6\u5b57\u7b26\u4e32\n * @param str \u5b57\u7b26\u4e32\n * @param start \u5f00\u59cb\n * @return \u7ed3\u679c\n */\n public static String substring( final String str, int start);\n /** \n * \u622a\u53d6\u5b57\u7b26\u4e32\n * @param str \u5b57\u7b26\u4e32\n * @param start \u5f00\u59cb\n * @param end \u7ed3\u675f\n * @return \u7ed3\u679c\n */\n public static String substring( final String str, int start, int end);\n /** \n * \u5b57\u7b26\u4e32\u8f6cset\n * @param str \u5b57\u7b26\u4e32\n * @param sep \u5206\u9694\u7b26\n * @return set\u96c6\u5408\n */\n public static Set<String> str2Set( String str, String sep);\n /** \n * \u5b57\u7b26\u4e32\u8f6clist\n * @param str \u5b57\u7b26\u4e32\n * @param sep \u5206\u9694\u7b26\n * @param filterBlank \u8fc7\u6ee4\u7eaf\u7a7a\u767d\n * @param trim \u53bb\u6389\u9996\u5c3e\u7a7a\u767d\n * @return list\u96c6\u5408\n */\n public static List<String> str2List( String str, String sep, boolean filterBlank, boolean trim);\n /** \n * \u67e5\u627e\u6307\u5b9a\u5b57\u7b26\u4e32\u662f\u5426\u5305\u542b\u6307\u5b9a\u5b57\u7b26\u4e32\u5217\u8868\u4e2d\u7684\u4efb\u610f\u4e00\u4e2a\u5b57\u7b26\u4e32\u540c\u65f6\u4e32\u5ffd\u7565\u5927\u5c0f\u5199\n * @param cs \u6307\u5b9a\u5b57\u7b26\u4e32\n * @param searchCharSequences \u9700\u8981\u68c0\u67e5\u7684\u5b57\u7b26\u4e32\u6570\u7ec4\n * @return \u662f\u5426\u5305\u542b\u4efb\u610f\u4e00\u4e2a\u5b57\u7b26\u4e32\n */\n public static boolean containsAnyIgnoreCase( CharSequence cs, CharSequence... searchCharSequences);\n /** \n * \u9a7c\u5cf0\u8f6c\u4e0b\u5212\u7ebf\u547d\u540d \n */\n public static String toUnderScoreCase( String str);\n /** \n * \u662f\u5426\u5305\u542b\u5b57\u7b26\u4e32\n * @param str \u9a8c\u8bc1\u5b57\u7b26\u4e32\n * @param strArr \u5b57\u7b26\u4e32\u7ec4\n * @return \u5305\u542b\u8fd4\u56detrue\n */\n public static boolean inStringIgnoreCase( String str, String... strArr);\n /** \n * \u5c06\u4e0b\u5212\u7ebf\u5927\u5199\u65b9\u5f0f\u547d\u540d\u7684\u5b57\u7b26\u4e32\u8f6c\u6362\u4e3a\u9a7c\u5cf0\u5f0f\u3002 \u5982\u679c\u8f6c\u6362\u524d\u7684\u4e0b\u5212\u7ebf\u5927\u5199\u65b9\u5f0f\u547d\u540d\u7684\u5b57\u7b26\u4e32\u4e3a\u7a7a, \u5219\u8fd4\u56de\u7a7a\u5b57\u7b26\u4e32\u3002 \u4f8b\u5982\uff1aHELLO_WORLD->HelloWorld\n * @param name \u8f6c\u6362\u524d\u7684\u4e0b\u5212\u7ebf\u5927\u5199\u65b9\u5f0f\u547d\u540d\u7684\u5b57\u7b26\u4e32\n * @return \u8f6c\u6362\u540e\u7684\u9a7c\u5cf0\u5f0f\u547d\u540d\u7684\u5b57\u7b26\u4e32\n */\n public static String convertToCamelCase( String name);\n /** \n * \u9a7c\u5cf0\u5f0f\u547d\u540d\u6cd5 \u4f8b\u5982\uff1auser_name->userName\n * @param s \u5b57\u7b26\u4e32\n * @return \u9a7c\u5cf0\u5b57\u7b26\u4e32\n */\n public static String toCamelCase( String s);\n /** \n * \u67e5\u627e\u6307\u5b9a\u5b57\u7b26\u4e32\u662f\u5426\u5339\u914d\u6307\u5b9a\u5b57\u7b26\u4e32\u5217\u8868\u4e2d\u7684\u4efb\u610f\u4e00\u4e2a\u5b57\u7b26\u4e32\n * @param str \u6307\u5b9a\u5b57\u7b26\u4e32\n * @param strArr \u9700\u8981\u68c0\u67e5\u7684\u5b57\u7b26\u4e32\u6570\u7ec4\n * @return \u662f\u5426\u5339\u914d\n */\n public static boolean matches( String str, List<String> strArr);\n /** \n * \u5224\u65adurl\u662f\u5426\u4e0e\u89c4\u5219\u914d\u7f6e: ? \u8868\u793a\u5355\u4e2a\u5b57\u7b26; * \u8868\u793a\u4e00\u5c42\u8def\u5f84\u5185\u7684\u4efb\u610f\u5b57\u7b26\u4e32\uff0c\u4e0d\u53ef\u8de8\u5c42\u7ea7; ** \u8868\u793a\u4efb\u610f\u5c42\u8def\u5f84;\n * @param pattern \u5339\u914d\u89c4\u5219\n * @param url \u9700\u8981\u5339\u914d\u7684url\n * @return boolean\n */\n public static boolean isMatch( String pattern, String url);\n /** \n * \u6570\u5b57\u5de6\u8fb9\u8865\u9f500,\u4f7f\u4e4b\u8fbe\u5230\u6307\u5b9a\u957f\u5ea6\u3002 \u6ce8\u610f\uff0c\u5982\u679c\u6570\u5b57\u8f6c\u6362\u4e3a\u5b57\u7b26\u4e32\u540e,\u957f\u5ea6\u5927\u4e8esize,\u5219\u53ea\u4fdd\u7559 \u6700\u540esize\u4e2a\u5b57\u7b26\u3002\n * @param num \u6570\u5b57\u5bf9\u8c61\n * @param size \u5b57\u7b26\u4e32\u6307\u5b9a\u957f\u5ea6\n * @return \u8fd4\u56de\u6570\u5b57\u7684\u5b57\u7b26\u4e32\u683c\u5f0f\uff0c\u8be5\u5b57\u7b26\u4e32\u4e3a\u6307\u5b9a\u957f\u5ea6\u3002\n */\n public static String padL( final Number num, final int size);\n /** \n * \u5b57\u7b26\u4e32\u5de6\u8865\u9f50 \u5982\u679c\u539f\u59cb\u5b57\u7b26\u4e32s\u957f\u5ea6\u5927\u4e8esize,\u5219\u53ea\u4fdd\u7559\u6700\u540esize\u4e2a\u5b57\u7b26\u3002\n * @param s \u539f\u59cb\u5b57\u7b26\u4e32\n * @param size \u5b57\u7b26\u4e32\u6307\u5b9a\u957f\u5ea6\n * @param c \u7528\u4e8e\u8865\u9f50\u7684\u5b57\u7b26\n * @return \u8fd4\u56de\u6307\u5b9a\u957f\u5ea6\u7684\u5b57\u7b26\u4e32\uff0c\u7531\u539f\u5b57\u7b26\u4e32\u5de6\u8865\u9f50\u6216\u622a\u53d6\u5f97\u5230\u3002\n */\n public static String padL( final String s, final int size, final char c);\n /** \n * \u683c\u5f0f\u5316\u6587\u672c, {} \u8868\u793a\u5360\u4f4d\u7b26<br> \u6b64\u65b9\u6cd5\u53ea\u662f\u7b80\u5355\u5c06\u5360\u4f4d\u7b26 {} \u6309\u7167\u987a\u5e8f\u66ff\u6362\u4e3a\u53c2\u6570<br> \u5982\u679c\u60f3\u8f93\u51fa {} \u4f7f\u7528 \\\\\u8f6c\u4e49 { \u5373\u53ef\uff0c\u5982\u679c\u60f3\u8f93\u51fa {} \u4e4b\u524d\u7684 \\ \u4f7f\u7528\u53cc\u8f6c\u4e49\u7b26 \\\\\\\\ \u5373\u53ef<br> \u4f8b\uff1a<br> \u901a\u5e38\u4f7f\u7528\uff1aformat(\"this is {} for {}\", \"a\", \"b\") -> this is a for b<br> \u8f6c\u4e49{}\uff1a format(\"this is \\\\{} for {}\", \"a\", \"b\") -> this is \\{} for a<br> \u8f6c\u4e49\\\uff1a format(\"this is \\\\\\\\{} for {}\", \"a\", \"b\") -> this is \\a for b<br>\n * @param strPattern \u6587\u672c\u6a21\u677f\uff0c\u88ab\u66ff\u6362\u7684\u90e8\u5206\u7528 {} \u8868\u793a\n * @param argArray \u53c2\u6570\u503c\n * @return \u683c\u5f0f\u5316\u540e\u7684\u6587\u672c\n */\n public static String format( String strPattern, Object... argArray);\n public static String arrayToString( Object[] array);\n}\n", "raw_body_no_cmt": "public class StringUtil extends org.apache.commons.lang3.StringUtils {\n private static final String NULL_STR=\"\";\n private static final char SEPARATOR='_';\n public static <T>T nvl( T value, T defaultValue);\n public static boolean isEmpty( Collection<?> coll);\n public static boolean isNotEmpty( Collection<?> coll);\n public static boolean isEmpty( Object[] objects);\n public static boolean isNotEmpty( Object[] objects);\n public static boolean isEmpty( Map<?,?> map);\n public static boolean isNotEmpty( Map<?,?> map);\n public static boolean isEmpty( String str);\n public static boolean isNotEmpty( String str);\n public static boolean isNull( Object object);\n public static boolean isNotNull( Object object);\n public static boolean isArray( Object object);\n public static String trim( String str);\n public static String substring( final String str, int start);\n public static String substring( final String str, int start, int end);\n public static Set<String> str2Set( String str, String sep);\n public static List<String> str2List( String str, String sep, boolean filterBlank, boolean trim);\n public static boolean containsAnyIgnoreCase( CharSequence cs, CharSequence... searchCharSequences);\n public static String toUnderScoreCase( String str);\n public static boolean inStringIgnoreCase( String str, String... strArr);\n public static String convertToCamelCase( String name);\n public static String toCamelCase( String s);\n public static boolean matches( String str, List<String> strArr);\n public static boolean isMatch( String pattern, String url);\n public static String padL( final Number num, final int size);\n public static String padL( final String s, final int size, final char c);\n public static String format( String strPattern, Object... argArray);\n public static String arrayToString( Object[] array);\n}\n"}}, {"Course": {"retrieved_name": "Course", "raw_body": "/** \n * @TableName courses\n */\n@TableName(value=\"courses\") @Data public class Course implements Serializable {\n /** \n */\n @TableId(type=IdType.AUTO) private Integer id;\n /** \n * \u8bfe\u7a0b\u6807\u9898 \n */\n private String title;\n /** \n * \u8bfe\u7a0b\u5c01\u9762 \n */\n private String thumb;\n /** \n * \u8bfe\u7a0b\u4ef7\u683c(\u5206) \n */\n private Integer charge;\n /** \n * \u8bfe\u7a0b\u7b80\u4ecb \n */\n @JsonProperty(\"short_desc\") private String shortDesc;\n /** \n * 1:\u5fc5\u4fee,0:\u9009\u4fee \n */\n @JsonProperty(\"is_required\") private Integer isRequired;\n /** \n * \u8bfe\u65f6\u6570 \n */\n @JsonProperty(\"class_hour\") private Integer classHour;\n /** \n * \u663e\u793a[1:\u662f,0:\u5426] \n */\n @JsonProperty(\"is_show\") private Integer isShow;\n @JsonProperty(\"published_at\") private Date publishedAt;\n @JsonProperty(\"created_at\") private Date createdAt;\n @JsonProperty(\"admin_id\") private Integer adminId;\n @JsonIgnore private Date updatedAt;\n @JsonIgnore private Date deletedAt;\n @Serial @TableField(exist=false) private static final long serialVersionUID=1L;\n}\n", "raw_body_no_cmt": "public class Course implements Serializable {\n private Integer id;\n private String title;\n private String thumb;\n private Integer charge;\n private String shortDesc;\n private Integer isRequired;\n private Integer classHour;\n private Integer isShow;\n private Date publishedAt;\n private Date createdAt;\n private Integer adminId;\n private Date updatedAt;\n private Date deletedAt;\n private static final long serialVersionUID=1L;\n}\n"}}] | [{"data": {"retrieved_name": "data", "raw_body": "public static JsonResponse data(Object data){\n return new JsonResponse(0,\"\",data);\n}\n"}}, {"findOrFail": {"retrieved_name": "findOrFail", "raw_body": "CourseChapter findOrFail(Integer id) throws NotFoundException ;\n"}}, {"put": {"retrieved_name": "put", "raw_body": "private static void put(String key,Object val){\n LinkedHashMap<String,Object> hashMap=THREAD_LOCAL.get();\n if (hashMap == null) {\n hashMap=new LinkedHashMap<>();\n }\n hashMap.put(key,val);\n THREAD_LOCAL.set(hashMap);\n}\n"}}, {"findByCourseId": {"retrieved_name": "getRidsByCourseId", "raw_body": "@Override public List<Integer> getRidsByCourseId(Integer courseId){\n return list(query().getWrapper().eq(\"course_id\",courseId)).stream().map(CourseAttachment::getRid).toList();\n}\n"}}] | [{"detail": {"retrieved_name": "detail", "raw_body": "@GetMapping(\"/detail\") @Log(title=\"\u7ba1\u7406\u5458-\u8be6\u60c5\",businessType=BusinessTypeConstant.GET) public JsonResponse detail(){\n AdminUser user=BCtx.getAdminUser();\n HashMap<String,Boolean> permissions=backendBus.adminUserPermissions(user.getId());\n HashMap<String,Object> data=new HashMap<>();\n data.put(\"user\",user);\n data.put(\"permissions\",permissions);\n return JsonResponse.data(data);\n}\n"}}] |
|
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-spring-boot-starter/src/main/java/com/jarvis/cache/interceptor/CacheDeleteInterceptor.java | CacheDeleteInterceptor | invoke | class CacheDeleteInterceptor implements MethodInterceptor {
private static final Logger logger = LoggerFactory.getLogger(CacheDeleteInterceptor.class);
private final CacheHandler cacheHandler;
private final AutoloadCacheProperties config;
public CacheDeleteInterceptor(CacheHandler cacheHandler, AutoloadCacheProperties config) {
this.cacheHandler = cacheHandler;
this.config = config;
}
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {<FILL_FUNCTION_BODY>}
} |
if (!this.config.isEnable()) {
return invocation.proceed();
}
Method method = invocation.getMethod();
// if (method.getDeclaringClass().isInterface()) {
Class<?> cls = AopUtil.getTargetClass(invocation.getThis());
if (!cls.equals(invocation.getThis().getClass())) {
if (logger.isDebugEnabled()) {
logger.debug(invocation.getThis().getClass() + "-->" + cls);
}
return invocation.proceed();
}
// }
Object result = invocation.proceed();
if (method.isAnnotationPresent(CacheDelete.class)) {
CacheDelete cacheDelete = method.getAnnotation(CacheDelete.class);
if (logger.isDebugEnabled()) {
logger.debug(invocation.getThis().getClass().getName() + "." + method.getName() + "-->@CacheDelete");
}
cacheHandler.deleteCache(new DeleteCacheAopProxy(invocation), cacheDelete, result);
} else {
Method specificMethod = AopUtils.getMostSpecificMethod(method, invocation.getThis().getClass());
if (specificMethod.isAnnotationPresent(CacheDelete.class)) {
CacheDelete cacheDelete = specificMethod.getAnnotation(CacheDelete.class);
if (logger.isDebugEnabled()) {
logger.debug(invocation.getThis().getClass().getName() + "." + specificMethod.getName()
+ "-->@CacheDelete");
}
cacheHandler.deleteCache(new DeleteCacheAopProxy(invocation), cacheDelete, result);
}
}
return result;
|
Object result = invocation.proceed();
if (config.isEnabled()) {
cacheHandler.delete(invocation.getMethod(), invocation.getArguments());
}
return result;
| [
"CacheHandler",
"MethodInvocation",
"AutoloadCacheProperties"
] | [
"getArguments",
"proceed",
"getMethod",
"delete",
"isEnabled"
] | [
"Class<?>",
"Method",
"CacheDelete",
"MethodInvocation",
"Logger",
"CacheHandler",
"AutoloadCacheProperties"
] | [
"getThis",
"equals",
"deleteCache",
"getMostSpecificMethod",
"getClass",
"isDebugEnabled",
"isEnable",
"proceed",
"isAnnotationPresent",
"getAnnotation",
"debug",
"getName",
"getTargetClass",
"getMethod"
] | {
"methods": [
"getArguments",
"proceed",
"getMethod",
"delete",
"isEnabled"
],
"similar_methods": [
"invoke"
],
"types": [
"CacheHandler",
"MethodInvocation",
"AutoloadCacheProperties"
]
} | /**
* 处理AOP
*/
public class CacheHandler {
/**
* 正在处理中的请求
*/
public final ConcurrentHashMap<CacheKeyTO,ProcessingTO> processing;
private final ICacheManager cacheManager;
private final AutoLoadConfig config;
private final ICloner cloner;
private final AutoLoadHandler autoLoadHandler;
private static final Logger log=LoggerFactory.getLogger(CacheHandler.class);
/**
* 表达式解析器
*/
private final AbstractScriptParser scriptParser;
private final RefreshHandler refreshHandler;
/**
* 分布式锁
*/
private ILock lock;
private ChangeListener changeListener;
public CacheHandler( ICacheManager cacheManager, AbstractScriptParser scriptParser, AutoLoadConfig config, ICloner cloner) throws IllegalArgumentException;
/**
* 从数据源中获取最新数据,并写入缓存。注意:这里不使用“拿来主义”机制,是因为当前可能是更新数据的方法。
* @param pjp CacheAopProxyChain
* @param cache Cache注解
* @return 最新数据
* @throws Throwable 异常
*/
private Object writeOnly( CacheAopProxyChain pjp, Cache cache) throws Throwable;
/**
* 获取CacheOpType,从三个地方获取:<br> 1. Cache注解中获取;<br> 2. 从ThreadLocal中获取;<br> 3. 从参数中获取;<br> 上面三者的优先级:从低到高。
* @param cache 注解
* @param arguments 参数
* @return CacheOpType
*/
private CacheOpType getCacheOpType( Cache cache, Object[] arguments);
/**
* 处理@Cache 拦截
* @param pjp 切面
* @param cache 注解
* @return T 返回值
* @throws Exception 异常
*/
public Object proceed( CacheAopProxyChain pjp, Cache cache) throws Throwable;
/**
* 处理@CacheDelete 拦截
* @param jp 切点
* @param cacheDelete 拦截到的注解
* @param retVal 返回值
* @throws Throwable 异常
*/
public void deleteCache( DeleteCacheAopProxyChain jp, CacheDelete cacheDelete, Object retVal) throws Throwable;
/**
* 用于处理事务下,事务处理完后才删除缓存,避免因事务失败造成缓存中的数据不一致问题。
* @param pjp 切面
* @param cacheDeleteTransactional 注解
* @return Object 返回值
* @throws Throwable 异常
*/
public Object proceedDeleteCacheTransactional( DeleteCacheTransactionalAopProxyChain pjp, CacheDeleteTransactional cacheDeleteTransactional) throws Throwable;
private void clearCache() throws Throwable;
/**
* 直接加载数据(加载后的数据不往缓存放)
* @param pjp CacheAopProxyChain
* @return Object
* @throws Throwable 异常
*/
private Object getData( CacheAopProxyChain pjp) throws Throwable;
public Object getData( CacheAopProxyChain pjp, Object[] arguments) throws Throwable;
public void writeCache( CacheAopProxyChain pjp, Object[] arguments, Cache cache, CacheKeyTO cacheKey, CacheWrapper<Object> cacheWrapper) throws Exception;
public void destroy();
/**
* 生成缓存KeyTO
* @param target 类名
* @param methodName 方法名
* @param arguments 参数
* @param keyExpression key表达式
* @param hfieldExpression hfield表达式
* @param result 执行实际方法的返回值
* @param hasRetVal 是否有返回值
* @return CacheKeyTO
*/
public CacheKeyTO getCacheKey( Object target, String methodName, Object[] arguments, String keyExpression, String hfieldExpression, Object result, boolean hasRetVal);
/**
* 生成缓存 Key
* @param pjp
* @param cache
* @return String 缓存Key
*/
private CacheKeyTO getCacheKey( CacheAopProxyChain pjp, Cache cache);
/**
* 生成缓存 Key
* @param pjp
* @param cache
* @param result 执行结果值
* @return 缓存Key
*/
private CacheKeyTO getCacheKey( CacheAopProxyChain pjp, Cache cache, Object result);
/**
* 生成缓存 Key
* @param pjp
* @param arguments
* @param exCache
* @param result 执行结果值
* @return 缓存Key
*/
private CacheKeyTO getCacheKey( CacheAopProxyChain pjp, Object[] arguments, ExCache exCache, Object result);
public AutoLoadHandler getAutoLoadHandler();
public AbstractScriptParser getScriptParser();
private void registerFunction( Map<String,String> funcs);
public ILock getLock();
public void setLock( ILock lock);
public void setCache( CacheKeyTO cacheKey, CacheWrapper<Object> result, Method method) throws CacheCenterConnectionException;
public Map<CacheKeyTO,CacheWrapper<Object>> mget( Method method, final Type returnType, Set<CacheKeyTO> keySet) throws CacheCenterConnectionException;
public void mset( final Method method, final Collection<MSetParam> params) throws CacheCenterConnectionException;
public CacheWrapper<Object> get( CacheKeyTO key, Method method) throws CacheCenterConnectionException;
public void delete( Set<CacheKeyTO> keys) throws CacheCenterConnectionException;
public ICloner getCloner();
public AutoLoadConfig getAutoLoadConfig();
public ChangeListener getChangeListener();
public void setChangeListener( ChangeListener changeListener);
}
/**
* Copyright 2016 Anders Granau Høfft Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. END OF NOTICE
* @author Anders Granau Høfft
*/
enum MethodParameter {BOOLEAN(boolean.class), CHAR(char.class), SHORT(short.class), BYTE(byte.class), INT(int.class), FLOAT(float.class), LONG(long.class), DOUBLE(double.class), OBJECT(Object.class); private Class<?> type;
private MethodParameter(Class<?> type){
this.type=type;
}
Class<?> getType(){
return type;
}
String getTypeAsSourceCodeString(){
return getType().getSimpleName();
}
}
/**
*/
@ConfigurationProperties(prefix=AutoloadCacheProperties.PREFIX) public class AutoloadCacheProperties {
public static final String PREFIX="autoload.cache";
private AutoLoadConfig config=new AutoLoadConfig();
private JedisCacheManagerConfig jedis=new JedisCacheManagerConfig();
@Autowired private Environment env;
private boolean namespaceEnable=true;
private boolean proxyTargetClass=true;
private boolean enable=true;
/**
* @Cache 注解是否生效, 默认值为true
*/
private boolean enableReadAndWrite=true;
/**
* @DeleteCache 和 @DeleteCacheTransactional 注解是否生效, 默认值为true
*/
private boolean enableDelete=true;
/**
* @Cache 注解AOP执行顺序
*/
private int cacheOrder=Integer.MAX_VALUE;
/**
* @DeleteCache 注解AOP执行顺序
*/
private int deleteCacheOrder=Integer.MAX_VALUE;
/**
* @DeleteCacheTransactionalAspect 注解AOP执行顺序
*/
private int deleteCacheTransactionalOrder=0;
private String adminUserName="admin";
private String adminPassword="admin";
public AutoLoadConfig getConfig();
public void setConfig( AutoLoadConfig config);
public JedisCacheManagerConfig getJedis();
public void setJedis( JedisCacheManagerConfig jedis);
public Environment getEnv();
public void setEnv( Environment env);
public boolean isNamespaceEnable();
public void setNamespaceEnable( boolean namespaceEnable);
public boolean isProxyTargetClass();
public void setProxyTargetClass( boolean proxyTargetClass);
public boolean isEnable();
public void setEnable( boolean enable);
public boolean isEnableReadAndWrite();
public void setEnableReadAndWrite( boolean enableReadAndWrite);
public boolean isEnableDelete();
public void setEnableDelete( boolean enableDelete);
public int getCacheOrder();
public void setCacheOrder( int cacheOrder);
public int getDeleteCacheOrder();
public void setDeleteCacheOrder( int deleteCacheOrder);
public int getDeleteCacheTransactionalOrder();
public void setDeleteCacheTransactionalOrder( int deleteCacheTransactionalOrder);
public String getAdminUserName();
public void setAdminUserName( String adminUserName);
public String getAdminPassword();
public void setAdminPassword( String adminPassword);
@PostConstruct public void init();
/**
* 对JedisClusterCacheManager 进行配置
*/
static class JedisCacheManagerConfig {
/**
* Hash的缓存时长:等于0时永久缓存;大于0时,主要是为了防止一些已经不用的缓存占用内存;hashExpire小于0时,则使用@Cache中设置的expire值(默认值为-1)。
*/
private int hashExpire=-1;
public int getHashExpire();
public void setHashExpire( int hashExpire);
}
}
@Override public Object[] getArgs(){
return jp.getArgs();
}
public Object proceed(ProceedingJoinPoint aopProxyChain,Cache cache) throws Throwable {
return cacheHandler.proceed(new AspectjCacheAopProxyChain(aopProxyChain),cache);
}
/**
* 获取方法
* @return 方法
*/
Method getMethod();
/**
* 缓存删除
* @param keys 缓存Key
*/
void delete(Set<CacheKeyTO> keys);
public boolean isEnable(){
return enable;
}
@Override public Object invoke(MethodInvocation invocation) throws Throwable {
if (!this.config.isEnable()) {
return invocation.proceed();
}
Method method=invocation.getMethod();
Class<?> cls=AopUtil.getTargetClass(invocation.getThis());
if (!cls.equals(invocation.getThis().getClass())) {
if (logger.isDebugEnabled()) {
logger.debug(invocation.getThis().getClass() + "-->" + cls);
}
return invocation.proceed();
}
if (logger.isDebugEnabled()) {
logger.debug(invocation.toString());
}
if (method.isAnnotationPresent(CacheDeleteTransactional.class)) {
CacheDeleteTransactional cacheDeleteTransactional=method.getAnnotation(CacheDeleteTransactional.class);
if (logger.isDebugEnabled()) {
logger.debug(invocation.getThis().getClass().getName() + "." + method.getName()+ "-->@CacheDeleteTransactional");
}
return cacheHandler.proceedDeleteCacheTransactional(new DeleteCacheTransactionalAopProxy(invocation),cacheDeleteTransactional);
}
else {
Method specificMethod=AopUtils.getMostSpecificMethod(method,invocation.getThis().getClass());
if (specificMethod.isAnnotationPresent(CacheDeleteTransactional.class)) {
CacheDeleteTransactional cacheDeleteTransactional=specificMethod.getAnnotation(CacheDeleteTransactional.class);
if (logger.isDebugEnabled()) {
logger.debug(invocation.getThis().getClass().getName() + "." + specificMethod.getName()+ "-->@CacheDeleteTransactional");
}
return cacheHandler.proceedDeleteCacheTransactional(new DeleteCacheTransactionalAopProxy(invocation),cacheDeleteTransactional);
}
}
return invocation.proceed();
}
| public class CacheHandler {
public final ConcurrentHashMap<CacheKeyTO,ProcessingTO> processing;
private final ICacheManager cacheManager;
private final AutoLoadConfig config;
private final ICloner cloner;
private final AutoLoadHandler autoLoadHandler;
private static final Logger log=LoggerFactory.getLogger(CacheHandler.class);
private final AbstractScriptParser scriptParser;
private final RefreshHandler refreshHandler;
private ILock lock;
private ChangeListener changeListener;
public CacheHandler( ICacheManager cacheManager, AbstractScriptParser scriptParser, AutoLoadConfig config, ICloner cloner) throws IllegalArgumentException;
private Object writeOnly( CacheAopProxyChain pjp, Cache cache) throws Throwable;
private CacheOpType getCacheOpType( Cache cache, Object[] arguments);
public Object proceed( CacheAopProxyChain pjp, Cache cache) throws Throwable;
public void deleteCache( DeleteCacheAopProxyChain jp, CacheDelete cacheDelete, Object retVal) throws Throwable;
public Object proceedDeleteCacheTransactional( DeleteCacheTransactionalAopProxyChain pjp, CacheDeleteTransactional cacheDeleteTransactional) throws Throwable;
private void clearCache() throws Throwable;
private Object getData( CacheAopProxyChain pjp) throws Throwable;
public Object getData( CacheAopProxyChain pjp, Object[] arguments) throws Throwable;
public void writeCache( CacheAopProxyChain pjp, Object[] arguments, Cache cache, CacheKeyTO cacheKey, CacheWrapper<Object> cacheWrapper) throws Exception;
public void destroy();
public CacheKeyTO getCacheKey( Object target, String methodName, Object[] arguments, String keyExpression, String hfieldExpression, Object result, boolean hasRetVal);
private CacheKeyTO getCacheKey( CacheAopProxyChain pjp, Cache cache);
private CacheKeyTO getCacheKey( CacheAopProxyChain pjp, Cache cache, Object result);
private CacheKeyTO getCacheKey( CacheAopProxyChain pjp, Object[] arguments, ExCache exCache, Object result);
public AutoLoadHandler getAutoLoadHandler();
public AbstractScriptParser getScriptParser();
private void registerFunction( Map<String,String> funcs);
public ILock getLock();
public void setLock( ILock lock);
public void setCache( CacheKeyTO cacheKey, CacheWrapper<Object> result, Method method) throws CacheCenterConnectionException;
public Map<CacheKeyTO,CacheWrapper<Object>> mget( Method method, final Type returnType, Set<CacheKeyTO> keySet) throws CacheCenterConnectionException;
public void mset( final Method method, final Collection<MSetParam> params) throws CacheCenterConnectionException;
public CacheWrapper<Object> get( CacheKeyTO key, Method method) throws CacheCenterConnectionException;
public void delete( Set<CacheKeyTO> keys) throws CacheCenterConnectionException;
public ICloner getCloner();
public AutoLoadConfig getAutoLoadConfig();
public ChangeListener getChangeListener();
public void setChangeListener( ChangeListener changeListener);
}
/**
* Copyright 2016 Anders Granau Høfft Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. END OF NOTICE
* @author Anders Granau Høfft
*/
enum MethodParameter {BOOLEAN(boolean.class), CHAR(char.class), SHORT(short.class), BYTE(byte.class), INT(int.class), FLOAT(float.class), LONG(long.class), DOUBLE(double.class), OBJECT(Object.class); private Class<?> type;
private MethodParameter(Class<?> type){
this.type=type;
}
Class<?> getType(){
return type;
}
String getTypeAsSourceCodeString(){
return getType().getSimpleName();
}
}
public class AutoloadCacheProperties {
public static final String PREFIX="autoload.cache";
private AutoLoadConfig config=new AutoLoadConfig();
private JedisCacheManagerConfig jedis=new JedisCacheManagerConfig();
private Environment env;
private boolean namespaceEnable=true;
private boolean proxyTargetClass=true;
private boolean enable=true;
private boolean enableReadAndWrite=true;
private boolean enableDelete=true;
private int cacheOrder=Integer.MAX_VALUE;
private int deleteCacheOrder=Integer.MAX_VALUE;
private int deleteCacheTransactionalOrder=0;
private String adminUserName="admin";
private String adminPassword="admin";
public AutoLoadConfig getConfig();
public void setConfig( AutoLoadConfig config);
public JedisCacheManagerConfig getJedis();
public void setJedis( JedisCacheManagerConfig jedis);
public Environment getEnv();
public void setEnv( Environment env);
public boolean isNamespaceEnable();
public void setNamespaceEnable( boolean namespaceEnable);
public boolean isProxyTargetClass();
public void setProxyTargetClass( boolean proxyTargetClass);
public boolean isEnable();
public void setEnable( boolean enable);
public boolean isEnableReadAndWrite();
public void setEnableReadAndWrite( boolean enableReadAndWrite);
public boolean isEnableDelete();
public void setEnableDelete( boolean enableDelete);
public int getCacheOrder();
public void setCacheOrder( int cacheOrder);
public int getDeleteCacheOrder();
public void setDeleteCacheOrder( int deleteCacheOrder);
public int getDeleteCacheTransactionalOrder();
public void setDeleteCacheTransactionalOrder( int deleteCacheTransactionalOrder);
public String getAdminUserName();
public void setAdminUserName( String adminUserName);
public String getAdminPassword();
public void setAdminPassword( String adminPassword);
public void init();
static class JedisCacheManagerConfig {
private int hashExpire=-1;
public int getHashExpire();
public void setHashExpire( int hashExpire);
}
}
@Override public Object[] getArgs(){
return jp.getArgs();
}
public Object proceed(ProceedingJoinPoint aopProxyChain,Cache cache) throws Throwable {
return cacheHandler.proceed(new AspectjCacheAopProxyChain(aopProxyChain),cache);
}
/**
* 获取方法
* @return 方法
*/
Method getMethod();
/**
* 缓存删除
* @param keys 缓存Key
*/
void delete(Set<CacheKeyTO> keys);
public boolean isEnable(){
return enable;
}
@Override public Object invoke(MethodInvocation invocation) throws Throwable {
if (!this.config.isEnable()) {
return invocation.proceed();
}
Method method=invocation.getMethod();
Class<?> cls=AopUtil.getTargetClass(invocation.getThis());
if (!cls.equals(invocation.getThis().getClass())) {
if (logger.isDebugEnabled()) {
logger.debug(invocation.getThis().getClass() + "-->" + cls);
}
return invocation.proceed();
}
if (logger.isDebugEnabled()) {
logger.debug(invocation.toString());
}
if (method.isAnnotationPresent(CacheDeleteTransactional.class)) {
CacheDeleteTransactional cacheDeleteTransactional=method.getAnnotation(CacheDeleteTransactional.class);
if (logger.isDebugEnabled()) {
logger.debug(invocation.getThis().getClass().getName() + "." + method.getName()+ "-->@CacheDeleteTransactional");
}
return cacheHandler.proceedDeleteCacheTransactional(new DeleteCacheTransactionalAopProxy(invocation),cacheDeleteTransactional);
}
else {
Method specificMethod=AopUtils.getMostSpecificMethod(method,invocation.getThis().getClass());
if (specificMethod.isAnnotationPresent(CacheDeleteTransactional.class)) {
CacheDeleteTransactional cacheDeleteTransactional=specificMethod.getAnnotation(CacheDeleteTransactional.class);
if (logger.isDebugEnabled()) {
logger.debug(invocation.getThis().getClass().getName() + "." + specificMethod.getName()+ "-->@CacheDeleteTransactional");
}
return cacheHandler.proceedDeleteCacheTransactional(new DeleteCacheTransactionalAopProxy(invocation),cacheDeleteTransactional);
}
}
return invocation.proceed();
}
| {"types": [{"CacheHandler": "CacheHandler"}, {"MethodInvocation": "MethodParameter"}, {"AutoloadCacheProperties": "AutoloadCacheProperties"}], "methods": [{"getArguments": "getArgs"}, {"proceed": "proceed"}, {"getMethod": "getMethod"}, {"delete": "delete"}, {"isEnabled": "isEnable"}], "similar_methods": [{"invoke": "invoke"}]} | [{"CacheHandler": {"retrieved_name": "CacheHandler", "raw_body": "/** \n * \u5904\u7406AOP\n */\npublic class CacheHandler {\n /** \n * \u6b63\u5728\u5904\u7406\u4e2d\u7684\u8bf7\u6c42\n */\n public final ConcurrentHashMap<CacheKeyTO,ProcessingTO> processing;\n private final ICacheManager cacheManager;\n private final AutoLoadConfig config;\n private final ICloner cloner;\n private final AutoLoadHandler autoLoadHandler;\n private static final Logger log=LoggerFactory.getLogger(CacheHandler.class);\n /** \n * \u8868\u8fbe\u5f0f\u89e3\u6790\u5668\n */\n private final AbstractScriptParser scriptParser;\n private final RefreshHandler refreshHandler;\n /** \n * \u5206\u5e03\u5f0f\u9501\n */\n private ILock lock;\n private ChangeListener changeListener;\n public CacheHandler( ICacheManager cacheManager, AbstractScriptParser scriptParser, AutoLoadConfig config, ICloner cloner) throws IllegalArgumentException;\n /** \n * \u4ece\u6570\u636e\u6e90\u4e2d\u83b7\u53d6\u6700\u65b0\u6570\u636e\uff0c\u5e76\u5199\u5165\u7f13\u5b58\u3002\u6ce8\u610f\uff1a\u8fd9\u91cc\u4e0d\u4f7f\u7528\u201c\u62ff\u6765\u4e3b\u4e49\u201d\u673a\u5236\uff0c\u662f\u56e0\u4e3a\u5f53\u524d\u53ef\u80fd\u662f\u66f4\u65b0\u6570\u636e\u7684\u65b9\u6cd5\u3002\n * @param pjp CacheAopProxyChain\n * @param cache Cache\u6ce8\u89e3\n * @return \u6700\u65b0\u6570\u636e\n * @throws Throwable \u5f02\u5e38\n */\n private Object writeOnly( CacheAopProxyChain pjp, Cache cache) throws Throwable;\n /** \n * \u83b7\u53d6CacheOpType\uff0c\u4ece\u4e09\u4e2a\u5730\u65b9\u83b7\u53d6\uff1a<br> 1. Cache\u6ce8\u89e3\u4e2d\u83b7\u53d6\uff1b<br> 2. \u4eceThreadLocal\u4e2d\u83b7\u53d6\uff1b<br> 3. \u4ece\u53c2\u6570\u4e2d\u83b7\u53d6\uff1b<br> \u4e0a\u9762\u4e09\u8005\u7684\u4f18\u5148\u7ea7\uff1a\u4ece\u4f4e\u5230\u9ad8\u3002\n * @param cache \u6ce8\u89e3\n * @param arguments \u53c2\u6570\n * @return CacheOpType\n */\n private CacheOpType getCacheOpType( Cache cache, Object[] arguments);\n /** \n * \u5904\u7406@Cache \u62e6\u622a\n * @param pjp \u5207\u9762\n * @param cache \u6ce8\u89e3\n * @return T \u8fd4\u56de\u503c\n * @throws Exception \u5f02\u5e38\n */\n public Object proceed( CacheAopProxyChain pjp, Cache cache) throws Throwable;\n /** \n * \u5904\u7406@CacheDelete \u62e6\u622a\n * @param jp \u5207\u70b9\n * @param cacheDelete \u62e6\u622a\u5230\u7684\u6ce8\u89e3\n * @param retVal \u8fd4\u56de\u503c\n * @throws Throwable \u5f02\u5e38\n */\n public void deleteCache( DeleteCacheAopProxyChain jp, CacheDelete cacheDelete, Object retVal) throws Throwable;\n /** \n * \u7528\u4e8e\u5904\u7406\u4e8b\u52a1\u4e0b\uff0c\u4e8b\u52a1\u5904\u7406\u5b8c\u540e\u624d\u5220\u9664\u7f13\u5b58\uff0c\u907f\u514d\u56e0\u4e8b\u52a1\u5931\u8d25\u9020\u6210\u7f13\u5b58\u4e2d\u7684\u6570\u636e\u4e0d\u4e00\u81f4\u95ee\u9898\u3002\n * @param pjp \u5207\u9762\n * @param cacheDeleteTransactional \u6ce8\u89e3\n * @return Object \u8fd4\u56de\u503c\n * @throws Throwable \u5f02\u5e38\n */\n public Object proceedDeleteCacheTransactional( DeleteCacheTransactionalAopProxyChain pjp, CacheDeleteTransactional cacheDeleteTransactional) throws Throwable;\n private void clearCache() throws Throwable;\n /** \n * \u76f4\u63a5\u52a0\u8f7d\u6570\u636e\uff08\u52a0\u8f7d\u540e\u7684\u6570\u636e\u4e0d\u5f80\u7f13\u5b58\u653e\uff09\n * @param pjp CacheAopProxyChain\n * @return Object\n * @throws Throwable \u5f02\u5e38\n */\n private Object getData( CacheAopProxyChain pjp) throws Throwable;\n public Object getData( CacheAopProxyChain pjp, Object[] arguments) throws Throwable;\n public void writeCache( CacheAopProxyChain pjp, Object[] arguments, Cache cache, CacheKeyTO cacheKey, CacheWrapper<Object> cacheWrapper) throws Exception;\n public void destroy();\n /** \n * \u751f\u6210\u7f13\u5b58KeyTO\n * @param target \u7c7b\u540d\n * @param methodName \u65b9\u6cd5\u540d\n * @param arguments \u53c2\u6570\n * @param keyExpression key\u8868\u8fbe\u5f0f\n * @param hfieldExpression hfield\u8868\u8fbe\u5f0f\n * @param result \u6267\u884c\u5b9e\u9645\u65b9\u6cd5\u7684\u8fd4\u56de\u503c\n * @param hasRetVal \u662f\u5426\u6709\u8fd4\u56de\u503c\n * @return CacheKeyTO\n */\n public CacheKeyTO getCacheKey( Object target, String methodName, Object[] arguments, String keyExpression, String hfieldExpression, Object result, boolean hasRetVal);\n /** \n * \u751f\u6210\u7f13\u5b58 Key\n * @param pjp\n * @param cache\n * @return String \u7f13\u5b58Key\n */\n private CacheKeyTO getCacheKey( CacheAopProxyChain pjp, Cache cache);\n /** \n * \u751f\u6210\u7f13\u5b58 Key\n * @param pjp\n * @param cache\n * @param result \u6267\u884c\u7ed3\u679c\u503c\n * @return \u7f13\u5b58Key\n */\n private CacheKeyTO getCacheKey( CacheAopProxyChain pjp, Cache cache, Object result);\n /** \n * \u751f\u6210\u7f13\u5b58 Key\n * @param pjp\n * @param arguments\n * @param exCache\n * @param result \u6267\u884c\u7ed3\u679c\u503c\n * @return \u7f13\u5b58Key\n */\n private CacheKeyTO getCacheKey( CacheAopProxyChain pjp, Object[] arguments, ExCache exCache, Object result);\n public AutoLoadHandler getAutoLoadHandler();\n public AbstractScriptParser getScriptParser();\n private void registerFunction( Map<String,String> funcs);\n public ILock getLock();\n public void setLock( ILock lock);\n public void setCache( CacheKeyTO cacheKey, CacheWrapper<Object> result, Method method) throws CacheCenterConnectionException;\n public Map<CacheKeyTO,CacheWrapper<Object>> mget( Method method, final Type returnType, Set<CacheKeyTO> keySet) throws CacheCenterConnectionException;\n public void mset( final Method method, final Collection<MSetParam> params) throws CacheCenterConnectionException;\n public CacheWrapper<Object> get( CacheKeyTO key, Method method) throws CacheCenterConnectionException;\n public void delete( Set<CacheKeyTO> keys) throws CacheCenterConnectionException;\n public ICloner getCloner();\n public AutoLoadConfig getAutoLoadConfig();\n public ChangeListener getChangeListener();\n public void setChangeListener( ChangeListener changeListener);\n}\n", "raw_body_no_cmt": "public class CacheHandler {\n public final ConcurrentHashMap<CacheKeyTO,ProcessingTO> processing;\n private final ICacheManager cacheManager;\n private final AutoLoadConfig config;\n private final ICloner cloner;\n private final AutoLoadHandler autoLoadHandler;\n private static final Logger log=LoggerFactory.getLogger(CacheHandler.class);\n private final AbstractScriptParser scriptParser;\n private final RefreshHandler refreshHandler;\n private ILock lock;\n private ChangeListener changeListener;\n public CacheHandler( ICacheManager cacheManager, AbstractScriptParser scriptParser, AutoLoadConfig config, ICloner cloner) throws IllegalArgumentException;\n private Object writeOnly( CacheAopProxyChain pjp, Cache cache) throws Throwable;\n private CacheOpType getCacheOpType( Cache cache, Object[] arguments);\n public Object proceed( CacheAopProxyChain pjp, Cache cache) throws Throwable;\n public void deleteCache( DeleteCacheAopProxyChain jp, CacheDelete cacheDelete, Object retVal) throws Throwable;\n public Object proceedDeleteCacheTransactional( DeleteCacheTransactionalAopProxyChain pjp, CacheDeleteTransactional cacheDeleteTransactional) throws Throwable;\n private void clearCache() throws Throwable;\n private Object getData( CacheAopProxyChain pjp) throws Throwable;\n public Object getData( CacheAopProxyChain pjp, Object[] arguments) throws Throwable;\n public void writeCache( CacheAopProxyChain pjp, Object[] arguments, Cache cache, CacheKeyTO cacheKey, CacheWrapper<Object> cacheWrapper) throws Exception;\n public void destroy();\n public CacheKeyTO getCacheKey( Object target, String methodName, Object[] arguments, String keyExpression, String hfieldExpression, Object result, boolean hasRetVal);\n private CacheKeyTO getCacheKey( CacheAopProxyChain pjp, Cache cache);\n private CacheKeyTO getCacheKey( CacheAopProxyChain pjp, Cache cache, Object result);\n private CacheKeyTO getCacheKey( CacheAopProxyChain pjp, Object[] arguments, ExCache exCache, Object result);\n public AutoLoadHandler getAutoLoadHandler();\n public AbstractScriptParser getScriptParser();\n private void registerFunction( Map<String,String> funcs);\n public ILock getLock();\n public void setLock( ILock lock);\n public void setCache( CacheKeyTO cacheKey, CacheWrapper<Object> result, Method method) throws CacheCenterConnectionException;\n public Map<CacheKeyTO,CacheWrapper<Object>> mget( Method method, final Type returnType, Set<CacheKeyTO> keySet) throws CacheCenterConnectionException;\n public void mset( final Method method, final Collection<MSetParam> params) throws CacheCenterConnectionException;\n public CacheWrapper<Object> get( CacheKeyTO key, Method method) throws CacheCenterConnectionException;\n public void delete( Set<CacheKeyTO> keys) throws CacheCenterConnectionException;\n public ICloner getCloner();\n public AutoLoadConfig getAutoLoadConfig();\n public ChangeListener getChangeListener();\n public void setChangeListener( ChangeListener changeListener);\n}\n"}}, {"MethodInvocation": {"retrieved_name": "MethodParameter", "raw_body": "/** \n * Copyright 2016 Anders Granau H\u00f8fft Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. END OF NOTICE\n * @author Anders Granau H\u00f8fft\n */\nenum MethodParameter {BOOLEAN(boolean.class), CHAR(char.class), SHORT(short.class), BYTE(byte.class), INT(int.class), FLOAT(float.class), LONG(long.class), DOUBLE(double.class), OBJECT(Object.class); private Class<?> type;\nprivate MethodParameter(Class<?> type){\n this.type=type;\n}\nClass<?> getType(){\n return type;\n}\nString getTypeAsSourceCodeString(){\n return getType().getSimpleName();\n}\n}\n", "raw_body_no_cmt": "/** \n * Copyright 2016 Anders Granau H\u00f8fft Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. END OF NOTICE\n * @author Anders Granau H\u00f8fft\n */\nenum MethodParameter {BOOLEAN(boolean.class), CHAR(char.class), SHORT(short.class), BYTE(byte.class), INT(int.class), FLOAT(float.class), LONG(long.class), DOUBLE(double.class), OBJECT(Object.class); private Class<?> type;\nprivate MethodParameter(Class<?> type){\n this.type=type;\n}\nClass<?> getType(){\n return type;\n}\nString getTypeAsSourceCodeString(){\n return getType().getSimpleName();\n}\n}\n"}}, {"AutoloadCacheProperties": {"retrieved_name": "AutoloadCacheProperties", "raw_body": "/** \n */\n@ConfigurationProperties(prefix=AutoloadCacheProperties.PREFIX) public class AutoloadCacheProperties {\n public static final String PREFIX=\"autoload.cache\";\n private AutoLoadConfig config=new AutoLoadConfig();\n private JedisCacheManagerConfig jedis=new JedisCacheManagerConfig();\n @Autowired private Environment env;\n private boolean namespaceEnable=true;\n private boolean proxyTargetClass=true;\n private boolean enable=true;\n /** \n * @Cache \u6ce8\u89e3\u662f\u5426\u751f\u6548, \u9ed8\u8ba4\u503c\u4e3atrue\n */\n private boolean enableReadAndWrite=true;\n /** \n * @DeleteCache \u548c @DeleteCacheTransactional \u6ce8\u89e3\u662f\u5426\u751f\u6548, \u9ed8\u8ba4\u503c\u4e3atrue\n */\n private boolean enableDelete=true;\n /** \n * @Cache \u6ce8\u89e3AOP\u6267\u884c\u987a\u5e8f\n */\n private int cacheOrder=Integer.MAX_VALUE;\n /** \n * @DeleteCache \u6ce8\u89e3AOP\u6267\u884c\u987a\u5e8f\n */\n private int deleteCacheOrder=Integer.MAX_VALUE;\n /** \n * @DeleteCacheTransactionalAspect \u6ce8\u89e3AOP\u6267\u884c\u987a\u5e8f\n */\n private int deleteCacheTransactionalOrder=0;\n private String adminUserName=\"admin\";\n private String adminPassword=\"admin\";\n public AutoLoadConfig getConfig();\n public void setConfig( AutoLoadConfig config);\n public JedisCacheManagerConfig getJedis();\n public void setJedis( JedisCacheManagerConfig jedis);\n public Environment getEnv();\n public void setEnv( Environment env);\n public boolean isNamespaceEnable();\n public void setNamespaceEnable( boolean namespaceEnable);\n public boolean isProxyTargetClass();\n public void setProxyTargetClass( boolean proxyTargetClass);\n public boolean isEnable();\n public void setEnable( boolean enable);\n public boolean isEnableReadAndWrite();\n public void setEnableReadAndWrite( boolean enableReadAndWrite);\n public boolean isEnableDelete();\n public void setEnableDelete( boolean enableDelete);\n public int getCacheOrder();\n public void setCacheOrder( int cacheOrder);\n public int getDeleteCacheOrder();\n public void setDeleteCacheOrder( int deleteCacheOrder);\n public int getDeleteCacheTransactionalOrder();\n public void setDeleteCacheTransactionalOrder( int deleteCacheTransactionalOrder);\n public String getAdminUserName();\n public void setAdminUserName( String adminUserName);\n public String getAdminPassword();\n public void setAdminPassword( String adminPassword);\n @PostConstruct public void init();\n /** \n * \u5bf9JedisClusterCacheManager \u8fdb\u884c\u914d\u7f6e\n */\nstatic class JedisCacheManagerConfig {\n /** \n * Hash\u7684\u7f13\u5b58\u65f6\u957f\uff1a\u7b49\u4e8e0\u65f6\u6c38\u4e45\u7f13\u5b58\uff1b\u5927\u4e8e0\u65f6\uff0c\u4e3b\u8981\u662f\u4e3a\u4e86\u9632\u6b62\u4e00\u4e9b\u5df2\u7ecf\u4e0d\u7528\u7684\u7f13\u5b58\u5360\u7528\u5185\u5b58;hashExpire\u5c0f\u4e8e0\u65f6\uff0c\u5219\u4f7f\u7528@Cache\u4e2d\u8bbe\u7f6e\u7684expire\u503c\uff08\u9ed8\u8ba4\u503c\u4e3a-1\uff09\u3002\n */\n private int hashExpire=-1;\n public int getHashExpire();\n public void setHashExpire( int hashExpire);\n }\n}\n", "raw_body_no_cmt": "public class AutoloadCacheProperties {\n public static final String PREFIX=\"autoload.cache\";\n private AutoLoadConfig config=new AutoLoadConfig();\n private JedisCacheManagerConfig jedis=new JedisCacheManagerConfig();\n private Environment env;\n private boolean namespaceEnable=true;\n private boolean proxyTargetClass=true;\n private boolean enable=true;\n private boolean enableReadAndWrite=true;\n private boolean enableDelete=true;\n private int cacheOrder=Integer.MAX_VALUE;\n private int deleteCacheOrder=Integer.MAX_VALUE;\n private int deleteCacheTransactionalOrder=0;\n private String adminUserName=\"admin\";\n private String adminPassword=\"admin\";\n public AutoLoadConfig getConfig();\n public void setConfig( AutoLoadConfig config);\n public JedisCacheManagerConfig getJedis();\n public void setJedis( JedisCacheManagerConfig jedis);\n public Environment getEnv();\n public void setEnv( Environment env);\n public boolean isNamespaceEnable();\n public void setNamespaceEnable( boolean namespaceEnable);\n public boolean isProxyTargetClass();\n public void setProxyTargetClass( boolean proxyTargetClass);\n public boolean isEnable();\n public void setEnable( boolean enable);\n public boolean isEnableReadAndWrite();\n public void setEnableReadAndWrite( boolean enableReadAndWrite);\n public boolean isEnableDelete();\n public void setEnableDelete( boolean enableDelete);\n public int getCacheOrder();\n public void setCacheOrder( int cacheOrder);\n public int getDeleteCacheOrder();\n public void setDeleteCacheOrder( int deleteCacheOrder);\n public int getDeleteCacheTransactionalOrder();\n public void setDeleteCacheTransactionalOrder( int deleteCacheTransactionalOrder);\n public String getAdminUserName();\n public void setAdminUserName( String adminUserName);\n public String getAdminPassword();\n public void setAdminPassword( String adminPassword);\n public void init();\n static class JedisCacheManagerConfig {\n private int hashExpire=-1;\n public int getHashExpire();\n public void setHashExpire( int hashExpire);\n }\n}\n"}}] | [{"getArguments": {"retrieved_name": "getArgs", "raw_body": "@Override public Object[] getArgs(){\n return jp.getArgs();\n}\n"}}, {"proceed": {"retrieved_name": "proceed", "raw_body": "public Object proceed(ProceedingJoinPoint aopProxyChain,Cache cache) throws Throwable {\n return cacheHandler.proceed(new AspectjCacheAopProxyChain(aopProxyChain),cache);\n}\n"}}, {"getMethod": {"retrieved_name": "getMethod", "raw_body": "/** \n * \u83b7\u53d6\u65b9\u6cd5\n * @return \u65b9\u6cd5\n */\nMethod getMethod();\n"}}, {"delete": {"retrieved_name": "delete", "raw_body": "/** \n * \u7f13\u5b58\u5220\u9664\n * @param keys \u7f13\u5b58Key\n */\nvoid delete(Set<CacheKeyTO> keys);\n"}}, {"isEnabled": {"retrieved_name": "isEnable", "raw_body": "public boolean isEnable(){\n return enable;\n}\n"}}] | [{"invoke": {"retrieved_name": "invoke", "raw_body": "@Override public Object invoke(MethodInvocation invocation) throws Throwable {\n if (!this.config.isEnable()) {\n return invocation.proceed();\n }\n Method method=invocation.getMethod();\n Class<?> cls=AopUtil.getTargetClass(invocation.getThis());\n if (!cls.equals(invocation.getThis().getClass())) {\n if (logger.isDebugEnabled()) {\n logger.debug(invocation.getThis().getClass() + \"-->\" + cls);\n }\n return invocation.proceed();\n }\n if (logger.isDebugEnabled()) {\n logger.debug(invocation.toString());\n }\n if (method.isAnnotationPresent(CacheDeleteTransactional.class)) {\n CacheDeleteTransactional cacheDeleteTransactional=method.getAnnotation(CacheDeleteTransactional.class);\n if (logger.isDebugEnabled()) {\n logger.debug(invocation.getThis().getClass().getName() + \".\" + method.getName()+ \"-->@CacheDeleteTransactional\");\n }\n return cacheHandler.proceedDeleteCacheTransactional(new DeleteCacheTransactionalAopProxy(invocation),cacheDeleteTransactional);\n }\n else {\n Method specificMethod=AopUtils.getMostSpecificMethod(method,invocation.getThis().getClass());\n if (specificMethod.isAnnotationPresent(CacheDeleteTransactional.class)) {\n CacheDeleteTransactional cacheDeleteTransactional=specificMethod.getAnnotation(CacheDeleteTransactional.class);\n if (logger.isDebugEnabled()) {\n logger.debug(invocation.getThis().getClass().getName() + \".\" + specificMethod.getName()+ \"-->@CacheDeleteTransactional\");\n }\n return cacheHandler.proceedDeleteCacheTransactional(new DeleteCacheTransactionalAopProxy(invocation),cacheDeleteTransactional);\n }\n }\n return invocation.proceed();\n}\n"}}] |
|
obsidiandynamics_kafdrop | kafdrop/src/main/java/kafdrop/controller/BrokerController.java | BrokerController | brokerDetails | class BrokerController {
private final KafkaMonitor kafkaMonitor;
public BrokerController(KafkaMonitor kafkaMonitor) {
this.kafkaMonitor = kafkaMonitor;
}
@RequestMapping("/broker/{id}")
public String brokerDetails(@PathVariable("id") int brokerId, Model model) {<FILL_FUNCTION_BODY>}
@Operation(summary = "getBroker", description = "Get details for a specific Kafka broker")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Success"),
@ApiResponse(responseCode = "404", description = "Invalid Broker ID")
})
@GetMapping(path = "/broker/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody BrokerVO brokerDetailsJson(@PathVariable("id") int brokerId) {
return kafkaMonitor.getBroker(brokerId).orElseThrow(() ->
new BrokerNotFoundException("No such broker " + brokerId));
}
@Operation(summary = "getAllBrokers", description = "Get details for all known Kafka brokers")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Success")
})
@GetMapping(path = "/broker", produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody List<BrokerVO> brokerDetailsJson() {
return kafkaMonitor.getBrokers();
}
} |
model.addAttribute("broker", kafkaMonitor.getBroker(brokerId)
.orElseThrow(() -> new BrokerNotFoundException("No such broker " + brokerId)));
model.addAttribute("topics", kafkaMonitor.getTopics());
return "broker-detail";
|
BrokerVO broker = kafkaMonitor.getBroker(brokerId).orElseThrow(() ->
new BrokerNotFoundException("No such broker " + brokerId));
model.addAttribute("broker", broker);
return "broker";
| [
"KafkaMonitor",
"BrokerVO",
"Model"
] | [
"getBroker",
"orElseThrow",
"addAttribute"
] | [
"Model",
"KafkaMonitor"
] | [
"getBroker",
"getTopics",
"addAttribute",
"orElseThrow"
] | {
"methods": [
"getBroker",
"orElseThrow",
"addAttribute"
],
"similar_methods": [
"brokerDetails"
],
"types": [
"KafkaMonitor",
"BrokerVO",
"Model"
]
} | public interface KafkaMonitor {
List<BrokerVO> getBrokers();
Optional<BrokerVO> getBroker( int id);
List<TopicVO> getTopics();
/**
* Returns messages for a given topic.
*/
List<MessageVO> getMessages( String topic, int count, Deserializers deserializers);
List<MessageVO> getMessages( TopicPartition topicPartition, long offset, int count, Deserializers deserializers);
Optional<TopicVO> getTopic( String topic);
ClusterSummaryVO getClusterSummary( Collection<TopicVO> topics);
List<ConsumerVO> getConsumersByGroup( String groupId);
List<ConsumerVO> getConsumersByTopics( Collection<TopicVO> topicVos);
SearchResultsVO searchMessages( String topic, String searchString, Integer maximumCount, Date startTimestamp, Deserializers deserializers);
/**
* Create topic
* @param createTopicDto topic params
*/
void createTopic( CreateTopicVO createTopicDto);
/**
* Delete the given topic
* @param topic name of the topic to delete
*/
void deleteTopic( String topic);
List<AclVO> getAcls();
}
public final class BrokerVO {
private final int id;
private final String host;
private final int port;
private final boolean controller;
private final String rack;
public BrokerVO( int id, String host, int port, String rack, boolean controller);
public int getId();
public String getHost();
public int getPort();
public String getRack();
public boolean isController();
}
/**
* Protobuf type {@code kafdrop.Person}
*/
public final class Person extends com.google.protobuf.GeneratedMessage implements PersonOrBuilder {
private static final long serialVersionUID=0L;
private Person( com.google.protobuf.GeneratedMessage.Builder<?> builder);
private Person();
@java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused);
@java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields();
private Person( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException;
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor();
@java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable();
/**
* Protobuf enum {@code kafdrop.Person.Contact}
*/
public enum Contact implements com.google.protobuf.ProtocolMessageEnum {/**
* <code>TELEPHONE = 0;</code>
*/
TELEPHONE(0), /**
* <code>MOBILE = 1;</code>
*/
MOBILE(1), UNRECOGNIZED(-1); /**
* <code>TELEPHONE = 0;</code>
*/
public static final int TELEPHONE_VALUE=0;
/**
* <code>MOBILE = 1;</code>
*/
public static final int MOBILE_VALUE=1;
public final int getNumber();
/**
* @param value The numeric wire value of the corresponding enum entry.
* @return The enum associated with the given numeric wire value.
* @deprecated Use {@link #forNumber(int)} instead.
*/
@java.lang.Deprecated public static Contact valueOf(int value);
/**
* @param value The numeric wire value of the corresponding enum entry.
* @return The enum associated with the given numeric wire value.
*/
public static Contact forNumber(int value);
public static com.google.protobuf.Internal.EnumLiteMap<Contact> internalGetValueMap();
private static final com.google.protobuf.Internal.EnumLiteMap<Contact> internalValueMap=new com.google.protobuf.Internal.EnumLiteMap<Contact>(){
public Contact findValueByNumber(int number){
return Contact.forNumber(number);
}
}
;
public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor();
public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType();
public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor();
private static final Contact[] VALUES=values();
public static Contact valueOf(com.google.protobuf.Descriptors.EnumValueDescriptor desc);
private final int value;
private Contact(int value);
}
public static final int NAME_FIELD_NUMBER=1;
private volatile java.lang.Object name_;
/**
* <code>string name = 1;</code>
* @return The name.
*/
@java.lang.Override public java.lang.String getName();
/**
* <code>string name = 1;</code>
* @return The bytes for name.
*/
@java.lang.Override public com.google.protobuf.ByteString getNameBytes();
public static final int ID_FIELD_NUMBER=2;
private int id_;
/**
* <code>int32 id = 2;</code>
* @return The id.
*/
@java.lang.Override public int getId();
public static final int EMAIL_FIELD_NUMBER=3;
private volatile java.lang.Object email_;
/**
* <code>string email = 3;</code>
* @return The email.
*/
@java.lang.Override public java.lang.String getEmail();
/**
* <code>string email = 3;</code>
* @return The bytes for email.
*/
@java.lang.Override public com.google.protobuf.ByteString getEmailBytes();
public static final int CONTACT_FIELD_NUMBER=4;
private int contact_;
/**
* <code>.kafdrop.Person.Contact contact = 4;</code>
* @return The enum numeric value on the wire for contact.
*/
@java.lang.Override public int getContactValue();
/**
* <code>.kafdrop.Person.Contact contact = 4;</code>
* @return The contact.
*/
@java.lang.Override public kafdrop.protos.Person.Contact getContact();
public static final int DATA_FIELD_NUMBER=5;
private com.google.protobuf.LazyStringList data_;
/**
* <code>repeated string data = 5;</code>
* @return A list containing the data.
*/
public com.google.protobuf.ProtocolStringList getDataList();
/**
* <code>repeated string data = 5;</code>
* @return The count of data.
*/
public int getDataCount();
/**
* <code>repeated string data = 5;</code>
* @param index The index of the element to return.
* @return The data at the given index.
*/
public java.lang.String getData(int index);
/**
* <code>repeated string data = 5;</code>
* @param index The index of the value to return.
* @return The bytes of the data at the given index.
*/
public com.google.protobuf.ByteString getDataBytes(int index);
private byte memoizedIsInitialized=-1;
@java.lang.Override public final boolean isInitialized();
@java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException;
@java.lang.Override public int getSerializedSize();
@java.lang.Override public boolean equals(final java.lang.Object obj);
@java.lang.Override public int hashCode();
public static kafdrop.protos.Person parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException;
public static kafdrop.protos.Person parseFrom(java.nio.ByteBuffer data,com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException;
public static kafdrop.protos.Person parseFrom(com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException;
public static kafdrop.protos.Person parseFrom(com.google.protobuf.ByteString data,com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException;
public static kafdrop.protos.Person parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException;
public static kafdrop.protos.Person parseFrom(byte[] data,com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException;
public static kafdrop.protos.Person parseFrom(java.io.InputStream input) throws java.io.IOException;
public static kafdrop.protos.Person parseFrom(java.io.InputStream input,com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException;
public static kafdrop.protos.Person parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException;
public static kafdrop.protos.Person parseDelimitedFrom(java.io.InputStream input,com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException;
public static kafdrop.protos.Person parseFrom(com.google.protobuf.CodedInputStream input) throws java.io.IOException;
public static kafdrop.protos.Person parseFrom(com.google.protobuf.CodedInputStream input,com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException;
@java.lang.Override public Builder newBuilderForType();
public static Builder newBuilder();
public static Builder newBuilder(kafdrop.protos.Person prototype);
@java.lang.Override public Builder toBuilder();
@java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessage.BuilderParent parent);
/**
* Protobuf type {@code kafdrop.Person}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder<Builder> implements kafdrop.protos.PersonOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor();
@java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable();
private Builder();
private Builder(com.google.protobuf.GeneratedMessage.BuilderParent parent);
private void maybeForceBuilderInitialization();
@java.lang.Override public Builder clear();
@java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType();
@java.lang.Override public kafdrop.protos.Person getDefaultInstanceForType();
@java.lang.Override public kafdrop.protos.Person build();
@java.lang.Override public kafdrop.protos.Person buildPartial();
@java.lang.Override public Builder clone();
@java.lang.Override public Builder setField(com.google.protobuf.Descriptors.FieldDescriptor field,java.lang.Object value);
@java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field);
@java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof);
@java.lang.Override public Builder setRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field,int index,java.lang.Object value);
@java.lang.Override public Builder addRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field,java.lang.Object value);
@java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other);
public Builder mergeFrom(kafdrop.protos.Person other);
@java.lang.Override public final boolean isInitialized();
@java.lang.Override public Builder mergeFrom(com.google.protobuf.CodedInputStream input,com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException;
private int bitField0_;
private java.lang.Object name_="";
/**
* <code>string name = 1;</code>
* @return The name.
*/
public java.lang.String getName();
/**
* <code>string name = 1;</code>
* @return The bytes for name.
*/
public com.google.protobuf.ByteString getNameBytes();
/**
* <code>string name = 1;</code>
* @param value The name to set.
* @return This builder for chaining.
*/
public Builder setName(java.lang.String value);
/**
* <code>string name = 1;</code>
* @return This builder for chaining.
*/
public Builder clearName();
/**
* <code>string name = 1;</code>
* @param value The bytes for name to set.
* @return This builder for chaining.
*/
public Builder setNameBytes(com.google.protobuf.ByteString value);
private int id_;
/**
* <code>int32 id = 2;</code>
* @return The id.
*/
@java.lang.Override public int getId();
/**
* <code>int32 id = 2;</code>
* @param value The id to set.
* @return This builder for chaining.
*/
public Builder setId(int value);
/**
* <code>int32 id = 2;</code>
* @return This builder for chaining.
*/
public Builder clearId();
private java.lang.Object email_="";
/**
* <code>string email = 3;</code>
* @return The email.
*/
public java.lang.String getEmail();
/**
* <code>string email = 3;</code>
* @return The bytes for email.
*/
public com.google.protobuf.ByteString getEmailBytes();
/**
* <code>string email = 3;</code>
* @param value The email to set.
* @return This builder for chaining.
*/
public Builder setEmail(java.lang.String value);
/**
* <code>string email = 3;</code>
* @return This builder for chaining.
*/
public Builder clearEmail();
/**
* <code>string email = 3;</code>
* @param value The bytes for email to set.
* @return This builder for chaining.
*/
public Builder setEmailBytes(com.google.protobuf.ByteString value);
private int contact_=0;
/**
* <code>.kafdrop.Person.Contact contact = 4;</code>
* @return The enum numeric value on the wire for contact.
*/
@java.lang.Override public int getContactValue();
/**
* <code>.kafdrop.Person.Contact contact = 4;</code>
* @param value The enum numeric value on the wire for contact to set.
* @return This builder for chaining.
*/
public Builder setContactValue(int value);
/**
* <code>.kafdrop.Person.Contact contact = 4;</code>
* @return The contact.
*/
@java.lang.Override public kafdrop.protos.Person.Contact getContact();
/**
* <code>.kafdrop.Person.Contact contact = 4;</code>
* @param value The contact to set.
* @return This builder for chaining.
*/
public Builder setContact(kafdrop.protos.Person.Contact value);
/**
* <code>.kafdrop.Person.Contact contact = 4;</code>
* @return This builder for chaining.
*/
public Builder clearContact();
private com.google.protobuf.LazyStringList data_=com.google.protobuf.LazyStringArrayList.EMPTY;
private void ensureDataIsMutable();
/**
* <code>repeated string data = 5;</code>
* @return A list containing the data.
*/
public com.google.protobuf.ProtocolStringList getDataList();
/**
* <code>repeated string data = 5;</code>
* @return The count of data.
*/
public int getDataCount();
/**
* <code>repeated string data = 5;</code>
* @param index The index of the element to return.
* @return The data at the given index.
*/
public java.lang.String getData(int index);
/**
* <code>repeated string data = 5;</code>
* @param index The index of the value to return.
* @return The bytes of the data at the given index.
*/
public com.google.protobuf.ByteString getDataBytes(int index);
/**
* <code>repeated string data = 5;</code>
* @param index The index to set the value at.
* @param value The data to set.
* @return This builder for chaining.
*/
public Builder setData(int index,java.lang.String value);
/**
* <code>repeated string data = 5;</code>
* @param value The data to add.
* @return This builder for chaining.
*/
public Builder addData(java.lang.String value);
/**
* <code>repeated string data = 5;</code>
* @param values The data to add.
* @return This builder for chaining.
*/
public Builder addAllData(java.lang.Iterable<java.lang.String> values);
/**
* <code>repeated string data = 5;</code>
* @return This builder for chaining.
*/
public Builder clearData();
/**
* <code>repeated string data = 5;</code>
* @param value The bytes of the data to add.
* @return This builder for chaining.
*/
public Builder addDataBytes(com.google.protobuf.ByteString value);
@java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields);
@java.lang.Override public final Builder mergeUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields);
}
private static final kafdrop.protos.Person DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE=new kafdrop.protos.Person();
}
public static kafdrop.protos.Person getDefaultInstance();
private static final com.google.protobuf.Parser<Person> PARSER=new com.google.protobuf.AbstractParser<Person>(){
@java.lang.Override public Person parsePartialFrom(com.google.protobuf.CodedInputStream input,com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException {
return new Person(input,extensionRegistry);
}
}
;
public static com.google.protobuf.Parser<Person> parser();
@java.lang.Override public com.google.protobuf.Parser<Person> getParserForType();
@java.lang.Override public kafdrop.protos.Person getDefaultInstanceForType();
}
Optional<BrokerVO> getBroker(int id);
@Override public String toString(){
return ConsumerPartitionVO.class.getSimpleName() + " [groupId=" + groupId+ ", topic="+ topic+ ", partitionId="+ partitionId+ ", offset="+ offset+ ", size="+ size+ ", firstOffset="+ firstOffset+ "]";
}
/**
* <code>repeated string data = 5;</code>
* @param value The data to add.
* @return This builder for chaining.
*/
public Builder addData(java.lang.String value){
if (value == null) {
throw new NullPointerException();
}
ensureDataIsMutable();
data_.add(value);
onChanged();
return this;
}
| public interface KafkaMonitor {
List<BrokerVO> getBrokers();
Optional<BrokerVO> getBroker( int id);
List<TopicVO> getTopics();
List<MessageVO> getMessages( String topic, int count, Deserializers deserializers);
List<MessageVO> getMessages( TopicPartition topicPartition, long offset, int count, Deserializers deserializers);
Optional<TopicVO> getTopic( String topic);
ClusterSummaryVO getClusterSummary( Collection<TopicVO> topics);
List<ConsumerVO> getConsumersByGroup( String groupId);
List<ConsumerVO> getConsumersByTopics( Collection<TopicVO> topicVos);
SearchResultsVO searchMessages( String topic, String searchString, Integer maximumCount, Date startTimestamp, Deserializers deserializers);
void createTopic( CreateTopicVO createTopicDto);
void deleteTopic( String topic);
List<AclVO> getAcls();
}
public final class BrokerVO {
private final int id;
private final String host;
private final int port;
private final boolean controller;
private final String rack;
public BrokerVO( int id, String host, int port, String rack, boolean controller);
public int getId();
public String getHost();
public int getPort();
public String getRack();
public boolean isController();
}
public final class Person extends com.google.protobuf.GeneratedMessage implements PersonOrBuilder {
private static final long serialVersionUID=0L;
private Person( com.google.protobuf.GeneratedMessage.Builder<?> builder);
private Person();
protected java.lang.Object newInstance( UnusedPrivateParameter unused);
public final com.google.protobuf.UnknownFieldSet getUnknownFields();
private Person( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException;
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor();
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable();
public enum Contact implements com.google.protobuf.ProtocolMessageEnum {/**
* <code>TELEPHONE = 0;</code>
*/
TELEPHONE(0), /**
* <code>MOBILE = 1;</code>
*/
MOBILE(1), UNRECOGNIZED(-1); public static final int TELEPHONE_VALUE=0;
public static final int MOBILE_VALUE=1;
public final int getNumber();
public static Contact valueOf(int value);
public static Contact forNumber(int value);
public static com.google.protobuf.Internal.EnumLiteMap<Contact> internalGetValueMap();
private static final com.google.protobuf.Internal.EnumLiteMap<Contact> internalValueMap=new com.google.protobuf.Internal.EnumLiteMap<Contact>(){
public Contact findValueByNumber(int number){
return Contact.forNumber(number);
}
}
;
public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor();
public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType();
public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor();
private static final Contact[] VALUES=values();
public static Contact valueOf(com.google.protobuf.Descriptors.EnumValueDescriptor desc);
private final int value;
private Contact(int value);
}
public static final int NAME_FIELD_NUMBER=1;
private volatile java.lang.Object name_;
public java.lang.String getName();
public com.google.protobuf.ByteString getNameBytes();
public static final int ID_FIELD_NUMBER=2;
private int id_;
public int getId();
public static final int EMAIL_FIELD_NUMBER=3;
private volatile java.lang.Object email_;
public java.lang.String getEmail();
public com.google.protobuf.ByteString getEmailBytes();
public static final int CONTACT_FIELD_NUMBER=4;
private int contact_;
public int getContactValue();
public kafdrop.protos.Person.Contact getContact();
public static final int DATA_FIELD_NUMBER=5;
private com.google.protobuf.LazyStringList data_;
public com.google.protobuf.ProtocolStringList getDataList();
public int getDataCount();
public java.lang.String getData(int index);
public com.google.protobuf.ByteString getDataBytes(int index);
private byte memoizedIsInitialized=-1;
public final boolean isInitialized();
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException;
public int getSerializedSize();
public boolean equals(final java.lang.Object obj);
public int hashCode();
public static kafdrop.protos.Person parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException;
public static kafdrop.protos.Person parseFrom(java.nio.ByteBuffer data,com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException;
public static kafdrop.protos.Person parseFrom(com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException;
public static kafdrop.protos.Person parseFrom(com.google.protobuf.ByteString data,com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException;
public static kafdrop.protos.Person parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException;
public static kafdrop.protos.Person parseFrom(byte[] data,com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException;
public static kafdrop.protos.Person parseFrom(java.io.InputStream input) throws java.io.IOException;
public static kafdrop.protos.Person parseFrom(java.io.InputStream input,com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException;
public static kafdrop.protos.Person parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException;
public static kafdrop.protos.Person parseDelimitedFrom(java.io.InputStream input,com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException;
public static kafdrop.protos.Person parseFrom(com.google.protobuf.CodedInputStream input) throws java.io.IOException;
public static kafdrop.protos.Person parseFrom(com.google.protobuf.CodedInputStream input,com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException;
public Builder newBuilderForType();
public static Builder newBuilder();
public static Builder newBuilder(kafdrop.protos.Person prototype);
public Builder toBuilder();
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessage.BuilderParent parent);
public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder<Builder> implements kafdrop.protos.PersonOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor();
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable();
private Builder();
private Builder(com.google.protobuf.GeneratedMessage.BuilderParent parent);
private void maybeForceBuilderInitialization();
public Builder clear();
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType();
public kafdrop.protos.Person getDefaultInstanceForType();
public kafdrop.protos.Person build();
public kafdrop.protos.Person buildPartial();
public Builder clone();
public Builder setField(com.google.protobuf.Descriptors.FieldDescriptor field,java.lang.Object value);
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field);
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof);
public Builder setRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field,int index,java.lang.Object value);
public Builder addRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field,java.lang.Object value);
public Builder mergeFrom(com.google.protobuf.Message other);
public Builder mergeFrom(kafdrop.protos.Person other);
public final boolean isInitialized();
public Builder mergeFrom(com.google.protobuf.CodedInputStream input,com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException;
private int bitField0_;
private java.lang.Object name_="";
public java.lang.String getName();
public com.google.protobuf.ByteString getNameBytes();
public Builder setName(java.lang.String value);
public Builder clearName();
public Builder setNameBytes(com.google.protobuf.ByteString value);
private int id_;
public int getId();
public Builder setId(int value);
public Builder clearId();
private java.lang.Object email_="";
public java.lang.String getEmail();
public com.google.protobuf.ByteString getEmailBytes();
public Builder setEmail(java.lang.String value);
public Builder clearEmail();
public Builder setEmailBytes(com.google.protobuf.ByteString value);
private int contact_=0;
public int getContactValue();
public Builder setContactValue(int value);
public kafdrop.protos.Person.Contact getContact();
public Builder setContact(kafdrop.protos.Person.Contact value);
public Builder clearContact();
private com.google.protobuf.LazyStringList data_=com.google.protobuf.LazyStringArrayList.EMPTY;
private void ensureDataIsMutable();
public com.google.protobuf.ProtocolStringList getDataList();
public int getDataCount();
public java.lang.String getData(int index);
public com.google.protobuf.ByteString getDataBytes(int index);
public Builder setData(int index,java.lang.String value);
public Builder addData(java.lang.String value);
public Builder addAllData(java.lang.Iterable<java.lang.String> values);
public Builder clearData();
public Builder addDataBytes(com.google.protobuf.ByteString value);
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields);
public final Builder mergeUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields);
}
private static final kafdrop.protos.Person DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE=new kafdrop.protos.Person();
}
public static kafdrop.protos.Person getDefaultInstance();
private static final com.google.protobuf.Parser<Person> PARSER=new com.google.protobuf.AbstractParser<Person>(){
@java.lang.Override public Person parsePartialFrom(com.google.protobuf.CodedInputStream input,com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException {
return new Person(input,extensionRegistry);
}
}
;
public static com.google.protobuf.Parser<Person> parser();
public com.google.protobuf.Parser<Person> getParserForType();
public kafdrop.protos.Person getDefaultInstanceForType();
}
Optional<BrokerVO> getBroker(int id);
@Override public String toString(){
return ConsumerPartitionVO.class.getSimpleName() + " [groupId=" + groupId+ ", topic="+ topic+ ", partitionId="+ partitionId+ ", offset="+ offset+ ", size="+ size+ ", firstOffset="+ firstOffset+ "]";
}
/**
* <code>repeated string data = 5;</code>
* @param value The data to add.
* @return This builder for chaining.
*/
public Builder addData(java.lang.String value){
if (value == null) {
throw new NullPointerException();
}
ensureDataIsMutable();
data_.add(value);
onChanged();
return this;
}
| {"types": [{"KafkaMonitor": "KafkaMonitor"}, {"BrokerVO": "BrokerVO"}, {"Model": "Person"}], "methods": [{"getBroker": "getBroker"}, {"orElseThrow": "toString"}, {"addAttribute": "addData"}], "similar_methods": [{"brokerDetails": ""}]} | [{"KafkaMonitor": {"retrieved_name": "KafkaMonitor", "raw_body": "public interface KafkaMonitor {\n List<BrokerVO> getBrokers();\n Optional<BrokerVO> getBroker( int id);\n List<TopicVO> getTopics();\n /** \n * Returns messages for a given topic.\n */\n List<MessageVO> getMessages( String topic, int count, Deserializers deserializers);\n List<MessageVO> getMessages( TopicPartition topicPartition, long offset, int count, Deserializers deserializers);\n Optional<TopicVO> getTopic( String topic);\n ClusterSummaryVO getClusterSummary( Collection<TopicVO> topics);\n List<ConsumerVO> getConsumersByGroup( String groupId);\n List<ConsumerVO> getConsumersByTopics( Collection<TopicVO> topicVos);\n SearchResultsVO searchMessages( String topic, String searchString, Integer maximumCount, Date startTimestamp, Deserializers deserializers);\n /** \n * Create topic\n * @param createTopicDto topic params\n */\n void createTopic( CreateTopicVO createTopicDto);\n /** \n * Delete the given topic\n * @param topic name of the topic to delete\n */\n void deleteTopic( String topic);\n List<AclVO> getAcls();\n}\n", "raw_body_no_cmt": "public interface KafkaMonitor {\n List<BrokerVO> getBrokers();\n Optional<BrokerVO> getBroker( int id);\n List<TopicVO> getTopics();\n List<MessageVO> getMessages( String topic, int count, Deserializers deserializers);\n List<MessageVO> getMessages( TopicPartition topicPartition, long offset, int count, Deserializers deserializers);\n Optional<TopicVO> getTopic( String topic);\n ClusterSummaryVO getClusterSummary( Collection<TopicVO> topics);\n List<ConsumerVO> getConsumersByGroup( String groupId);\n List<ConsumerVO> getConsumersByTopics( Collection<TopicVO> topicVos);\n SearchResultsVO searchMessages( String topic, String searchString, Integer maximumCount, Date startTimestamp, Deserializers deserializers);\n void createTopic( CreateTopicVO createTopicDto);\n void deleteTopic( String topic);\n List<AclVO> getAcls();\n}\n"}}, {"BrokerVO": {"retrieved_name": "BrokerVO", "raw_body": "public final class BrokerVO {\n private final int id;\n private final String host;\n private final int port;\n private final boolean controller;\n private final String rack;\n public BrokerVO( int id, String host, int port, String rack, boolean controller);\n public int getId();\n public String getHost();\n public int getPort();\n public String getRack();\n public boolean isController();\n}\n", "raw_body_no_cmt": "public final class BrokerVO {\n private final int id;\n private final String host;\n private final int port;\n private final boolean controller;\n private final String rack;\n public BrokerVO( int id, String host, int port, String rack, boolean controller);\n public int getId();\n public String getHost();\n public int getPort();\n public String getRack();\n public boolean isController();\n}\n"}}, {"Model": {"retrieved_name": "Person", "raw_body": "/** \n * Protobuf type {@code kafdrop.Person}\n */\npublic final class Person extends com.google.protobuf.GeneratedMessage implements PersonOrBuilder {\n private static final long serialVersionUID=0L;\n private Person( com.google.protobuf.GeneratedMessage.Builder<?> builder);\n private Person();\n @java.lang.Override @SuppressWarnings({\"unused\"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused);\n @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields();\n private Person( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException;\npublic static final com.google.protobuf.Descriptors.Descriptor getDescriptor();\n@java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable();\n/** \n * Protobuf enum {@code kafdrop.Person.Contact}\n */\npublic enum Contact implements com.google.protobuf.ProtocolMessageEnum {/** \n * <code>TELEPHONE = 0;</code>\n */\nTELEPHONE(0), /** \n * <code>MOBILE = 1;</code>\n */\nMOBILE(1), UNRECOGNIZED(-1); /** \n * <code>TELEPHONE = 0;</code>\n */\npublic static final int TELEPHONE_VALUE=0;\n/** \n * <code>MOBILE = 1;</code>\n */\npublic static final int MOBILE_VALUE=1;\npublic final int getNumber();\n/** \n * @param value The numeric wire value of the corresponding enum entry.\n * @return The enum associated with the given numeric wire value.\n * @deprecated Use {@link #forNumber(int)} instead.\n */\n@java.lang.Deprecated public static Contact valueOf(int value);\n/** \n * @param value The numeric wire value of the corresponding enum entry.\n * @return The enum associated with the given numeric wire value.\n */\npublic static Contact forNumber(int value);\npublic static com.google.protobuf.Internal.EnumLiteMap<Contact> internalGetValueMap();\nprivate static final com.google.protobuf.Internal.EnumLiteMap<Contact> internalValueMap=new com.google.protobuf.Internal.EnumLiteMap<Contact>(){\npublic Contact findValueByNumber(int number){\nreturn Contact.forNumber(number);\n}\n}\n;\npublic final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor();\npublic final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType();\npublic static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor();\nprivate static final Contact[] VALUES=values();\npublic static Contact valueOf(com.google.protobuf.Descriptors.EnumValueDescriptor desc);\nprivate final int value;\nprivate Contact(int value);\n}\npublic static final int NAME_FIELD_NUMBER=1;\nprivate volatile java.lang.Object name_;\n/** \n * <code>string name = 1;</code>\n * @return The name.\n */\n@java.lang.Override public java.lang.String getName();\n/** \n * <code>string name = 1;</code>\n * @return The bytes for name.\n */\n@java.lang.Override public com.google.protobuf.ByteString getNameBytes();\npublic static final int ID_FIELD_NUMBER=2;\nprivate int id_;\n/** \n * <code>int32 id = 2;</code>\n * @return The id.\n */\n@java.lang.Override public int getId();\npublic static final int EMAIL_FIELD_NUMBER=3;\nprivate volatile java.lang.Object email_;\n/** \n * <code>string email = 3;</code>\n * @return The email.\n */\n@java.lang.Override public java.lang.String getEmail();\n/** \n * <code>string email = 3;</code>\n * @return The bytes for email.\n */\n@java.lang.Override public com.google.protobuf.ByteString getEmailBytes();\npublic static final int CONTACT_FIELD_NUMBER=4;\nprivate int contact_;\n/** \n * <code>.kafdrop.Person.Contact contact = 4;</code>\n * @return The enum numeric value on the wire for contact.\n */\n@java.lang.Override public int getContactValue();\n/** \n * <code>.kafdrop.Person.Contact contact = 4;</code>\n * @return The contact.\n */\n@java.lang.Override public kafdrop.protos.Person.Contact getContact();\npublic static final int DATA_FIELD_NUMBER=5;\nprivate com.google.protobuf.LazyStringList data_;\n/** \n * <code>repeated string data = 5;</code>\n * @return A list containing the data.\n */\npublic com.google.protobuf.ProtocolStringList getDataList();\n/** \n * <code>repeated string data = 5;</code>\n * @return The count of data.\n */\npublic int getDataCount();\n/** \n * <code>repeated string data = 5;</code>\n * @param index The index of the element to return.\n * @return The data at the given index.\n */\npublic java.lang.String getData(int index);\n/** \n * <code>repeated string data = 5;</code>\n * @param index The index of the value to return.\n * @return The bytes of the data at the given index.\n */\npublic com.google.protobuf.ByteString getDataBytes(int index);\nprivate byte memoizedIsInitialized=-1;\n@java.lang.Override public final boolean isInitialized();\n@java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException;\n@java.lang.Override public int getSerializedSize();\n@java.lang.Override public boolean equals(final java.lang.Object obj);\n@java.lang.Override public int hashCode();\npublic static kafdrop.protos.Person parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException;\npublic static kafdrop.protos.Person parseFrom(java.nio.ByteBuffer data,com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException;\npublic static kafdrop.protos.Person parseFrom(com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException;\npublic static kafdrop.protos.Person parseFrom(com.google.protobuf.ByteString data,com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException;\npublic static kafdrop.protos.Person parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException;\npublic static kafdrop.protos.Person parseFrom(byte[] data,com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException;\npublic static kafdrop.protos.Person parseFrom(java.io.InputStream input) throws java.io.IOException;\npublic static kafdrop.protos.Person parseFrom(java.io.InputStream input,com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException;\npublic static kafdrop.protos.Person parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException;\npublic static kafdrop.protos.Person parseDelimitedFrom(java.io.InputStream input,com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException;\npublic static kafdrop.protos.Person parseFrom(com.google.protobuf.CodedInputStream input) throws java.io.IOException;\npublic static kafdrop.protos.Person parseFrom(com.google.protobuf.CodedInputStream input,com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException;\n@java.lang.Override public Builder newBuilderForType();\npublic static Builder newBuilder();\npublic static Builder newBuilder(kafdrop.protos.Person prototype);\n@java.lang.Override public Builder toBuilder();\n@java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessage.BuilderParent parent);\n/** \n * Protobuf type {@code kafdrop.Person}\n */\npublic static final class Builder extends com.google.protobuf.GeneratedMessage.Builder<Builder> implements kafdrop.protos.PersonOrBuilder {\npublic static final com.google.protobuf.Descriptors.Descriptor getDescriptor();\n@java.lang.Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable();\nprivate Builder();\nprivate Builder(com.google.protobuf.GeneratedMessage.BuilderParent parent);\nprivate void maybeForceBuilderInitialization();\n@java.lang.Override public Builder clear();\n@java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType();\n@java.lang.Override public kafdrop.protos.Person getDefaultInstanceForType();\n@java.lang.Override public kafdrop.protos.Person build();\n@java.lang.Override public kafdrop.protos.Person buildPartial();\n@java.lang.Override public Builder clone();\n@java.lang.Override public Builder setField(com.google.protobuf.Descriptors.FieldDescriptor field,java.lang.Object value);\n@java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field);\n@java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof);\n@java.lang.Override public Builder setRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field,int index,java.lang.Object value);\n@java.lang.Override public Builder addRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field,java.lang.Object value);\n@java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other);\npublic Builder mergeFrom(kafdrop.protos.Person other);\n@java.lang.Override public final boolean isInitialized();\n@java.lang.Override public Builder mergeFrom(com.google.protobuf.CodedInputStream input,com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException;\nprivate int bitField0_;\nprivate java.lang.Object name_=\"\";\n/** \n * <code>string name = 1;</code>\n * @return The name.\n */\npublic java.lang.String getName();\n/** \n * <code>string name = 1;</code>\n * @return The bytes for name.\n */\npublic com.google.protobuf.ByteString getNameBytes();\n/** \n * <code>string name = 1;</code>\n * @param value The name to set.\n * @return This builder for chaining.\n */\npublic Builder setName(java.lang.String value);\n/** \n * <code>string name = 1;</code>\n * @return This builder for chaining.\n */\npublic Builder clearName();\n/** \n * <code>string name = 1;</code>\n * @param value The bytes for name to set.\n * @return This builder for chaining.\n */\npublic Builder setNameBytes(com.google.protobuf.ByteString value);\nprivate int id_;\n/** \n * <code>int32 id = 2;</code>\n * @return The id.\n */\n@java.lang.Override public int getId();\n/** \n * <code>int32 id = 2;</code>\n * @param value The id to set.\n * @return This builder for chaining.\n */\npublic Builder setId(int value);\n/** \n * <code>int32 id = 2;</code>\n * @return This builder for chaining.\n */\npublic Builder clearId();\nprivate java.lang.Object email_=\"\";\n/** \n * <code>string email = 3;</code>\n * @return The email.\n */\npublic java.lang.String getEmail();\n/** \n * <code>string email = 3;</code>\n * @return The bytes for email.\n */\npublic com.google.protobuf.ByteString getEmailBytes();\n/** \n * <code>string email = 3;</code>\n * @param value The email to set.\n * @return This builder for chaining.\n */\npublic Builder setEmail(java.lang.String value);\n/** \n * <code>string email = 3;</code>\n * @return This builder for chaining.\n */\npublic Builder clearEmail();\n/** \n * <code>string email = 3;</code>\n * @param value The bytes for email to set.\n * @return This builder for chaining.\n */\npublic Builder setEmailBytes(com.google.protobuf.ByteString value);\nprivate int contact_=0;\n/** \n * <code>.kafdrop.Person.Contact contact = 4;</code>\n * @return The enum numeric value on the wire for contact.\n */\n@java.lang.Override public int getContactValue();\n/** \n * <code>.kafdrop.Person.Contact contact = 4;</code>\n * @param value The enum numeric value on the wire for contact to set.\n * @return This builder for chaining.\n */\npublic Builder setContactValue(int value);\n/** \n * <code>.kafdrop.Person.Contact contact = 4;</code>\n * @return The contact.\n */\n@java.lang.Override public kafdrop.protos.Person.Contact getContact();\n/** \n * <code>.kafdrop.Person.Contact contact = 4;</code>\n * @param value The contact to set.\n * @return This builder for chaining.\n */\npublic Builder setContact(kafdrop.protos.Person.Contact value);\n/** \n * <code>.kafdrop.Person.Contact contact = 4;</code>\n * @return This builder for chaining.\n */\npublic Builder clearContact();\nprivate com.google.protobuf.LazyStringList data_=com.google.protobuf.LazyStringArrayList.EMPTY;\nprivate void ensureDataIsMutable();\n/** \n * <code>repeated string data = 5;</code>\n * @return A list containing the data.\n */\npublic com.google.protobuf.ProtocolStringList getDataList();\n/** \n * <code>repeated string data = 5;</code>\n * @return The count of data.\n */\npublic int getDataCount();\n/** \n * <code>repeated string data = 5;</code>\n * @param index The index of the element to return.\n * @return The data at the given index.\n */\npublic java.lang.String getData(int index);\n/** \n * <code>repeated string data = 5;</code>\n * @param index The index of the value to return.\n * @return The bytes of the data at the given index.\n */\npublic com.google.protobuf.ByteString getDataBytes(int index);\n/** \n * <code>repeated string data = 5;</code>\n * @param index The index to set the value at.\n * @param value The data to set.\n * @return This builder for chaining.\n */\npublic Builder setData(int index,java.lang.String value);\n/** \n * <code>repeated string data = 5;</code>\n * @param value The data to add.\n * @return This builder for chaining.\n */\npublic Builder addData(java.lang.String value);\n/** \n * <code>repeated string data = 5;</code>\n * @param values The data to add.\n * @return This builder for chaining.\n */\npublic Builder addAllData(java.lang.Iterable<java.lang.String> values);\n/** \n * <code>repeated string data = 5;</code>\n * @return This builder for chaining.\n */\npublic Builder clearData();\n/** \n * <code>repeated string data = 5;</code>\n * @param value The bytes of the data to add.\n * @return This builder for chaining.\n */\npublic Builder addDataBytes(com.google.protobuf.ByteString value);\n@java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields);\n@java.lang.Override public final Builder mergeUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields);\n}\nprivate static final kafdrop.protos.Person DEFAULT_INSTANCE;\nstatic {\nDEFAULT_INSTANCE=new kafdrop.protos.Person();\n}\npublic static kafdrop.protos.Person getDefaultInstance();\nprivate static final com.google.protobuf.Parser<Person> PARSER=new com.google.protobuf.AbstractParser<Person>(){\n@java.lang.Override public Person parsePartialFrom(com.google.protobuf.CodedInputStream input,com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException {\nreturn new Person(input,extensionRegistry);\n}\n}\n;\npublic static com.google.protobuf.Parser<Person> parser();\n@java.lang.Override public com.google.protobuf.Parser<Person> getParserForType();\n@java.lang.Override public kafdrop.protos.Person getDefaultInstanceForType();\n}\n", "raw_body_no_cmt": "public final class Person extends com.google.protobuf.GeneratedMessage implements PersonOrBuilder {\n private static final long serialVersionUID=0L;\n private Person( com.google.protobuf.GeneratedMessage.Builder<?> builder);\n private Person();\n protected java.lang.Object newInstance( UnusedPrivateParameter unused);\n public final com.google.protobuf.UnknownFieldSet getUnknownFields();\n private Person( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException;\npublic static final com.google.protobuf.Descriptors.Descriptor getDescriptor();\nprotected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable();\npublic enum Contact implements com.google.protobuf.ProtocolMessageEnum {/** \n * <code>TELEPHONE = 0;</code>\n */\nTELEPHONE(0), /** \n * <code>MOBILE = 1;</code>\n */\nMOBILE(1), UNRECOGNIZED(-1); public static final int TELEPHONE_VALUE=0;\npublic static final int MOBILE_VALUE=1;\npublic final int getNumber();\npublic static Contact valueOf(int value);\npublic static Contact forNumber(int value);\npublic static com.google.protobuf.Internal.EnumLiteMap<Contact> internalGetValueMap();\nprivate static final com.google.protobuf.Internal.EnumLiteMap<Contact> internalValueMap=new com.google.protobuf.Internal.EnumLiteMap<Contact>(){\npublic Contact findValueByNumber(int number){\nreturn Contact.forNumber(number);\n}\n}\n;\npublic final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor();\npublic final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType();\npublic static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor();\nprivate static final Contact[] VALUES=values();\npublic static Contact valueOf(com.google.protobuf.Descriptors.EnumValueDescriptor desc);\nprivate final int value;\nprivate Contact(int value);\n}\npublic static final int NAME_FIELD_NUMBER=1;\nprivate volatile java.lang.Object name_;\npublic java.lang.String getName();\npublic com.google.protobuf.ByteString getNameBytes();\npublic static final int ID_FIELD_NUMBER=2;\nprivate int id_;\npublic int getId();\npublic static final int EMAIL_FIELD_NUMBER=3;\nprivate volatile java.lang.Object email_;\npublic java.lang.String getEmail();\npublic com.google.protobuf.ByteString getEmailBytes();\npublic static final int CONTACT_FIELD_NUMBER=4;\nprivate int contact_;\npublic int getContactValue();\npublic kafdrop.protos.Person.Contact getContact();\npublic static final int DATA_FIELD_NUMBER=5;\nprivate com.google.protobuf.LazyStringList data_;\npublic com.google.protobuf.ProtocolStringList getDataList();\npublic int getDataCount();\npublic java.lang.String getData(int index);\npublic com.google.protobuf.ByteString getDataBytes(int index);\nprivate byte memoizedIsInitialized=-1;\npublic final boolean isInitialized();\npublic void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException;\npublic int getSerializedSize();\npublic boolean equals(final java.lang.Object obj);\npublic int hashCode();\npublic static kafdrop.protos.Person parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException;\npublic static kafdrop.protos.Person parseFrom(java.nio.ByteBuffer data,com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException;\npublic static kafdrop.protos.Person parseFrom(com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException;\npublic static kafdrop.protos.Person parseFrom(com.google.protobuf.ByteString data,com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException;\npublic static kafdrop.protos.Person parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException;\npublic static kafdrop.protos.Person parseFrom(byte[] data,com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException;\npublic static kafdrop.protos.Person parseFrom(java.io.InputStream input) throws java.io.IOException;\npublic static kafdrop.protos.Person parseFrom(java.io.InputStream input,com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException;\npublic static kafdrop.protos.Person parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException;\npublic static kafdrop.protos.Person parseDelimitedFrom(java.io.InputStream input,com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException;\npublic static kafdrop.protos.Person parseFrom(com.google.protobuf.CodedInputStream input) throws java.io.IOException;\npublic static kafdrop.protos.Person parseFrom(com.google.protobuf.CodedInputStream input,com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException;\npublic Builder newBuilderForType();\npublic static Builder newBuilder();\npublic static Builder newBuilder(kafdrop.protos.Person prototype);\npublic Builder toBuilder();\nprotected Builder newBuilderForType(com.google.protobuf.GeneratedMessage.BuilderParent parent);\npublic static final class Builder extends com.google.protobuf.GeneratedMessage.Builder<Builder> implements kafdrop.protos.PersonOrBuilder {\npublic static final com.google.protobuf.Descriptors.Descriptor getDescriptor();\nprotected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable();\nprivate Builder();\nprivate Builder(com.google.protobuf.GeneratedMessage.BuilderParent parent);\nprivate void maybeForceBuilderInitialization();\npublic Builder clear();\npublic com.google.protobuf.Descriptors.Descriptor getDescriptorForType();\npublic kafdrop.protos.Person getDefaultInstanceForType();\npublic kafdrop.protos.Person build();\npublic kafdrop.protos.Person buildPartial();\npublic Builder clone();\npublic Builder setField(com.google.protobuf.Descriptors.FieldDescriptor field,java.lang.Object value);\npublic Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field);\npublic Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof);\npublic Builder setRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field,int index,java.lang.Object value);\npublic Builder addRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field,java.lang.Object value);\npublic Builder mergeFrom(com.google.protobuf.Message other);\npublic Builder mergeFrom(kafdrop.protos.Person other);\npublic final boolean isInitialized();\npublic Builder mergeFrom(com.google.protobuf.CodedInputStream input,com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException;\nprivate int bitField0_;\nprivate java.lang.Object name_=\"\";\npublic java.lang.String getName();\npublic com.google.protobuf.ByteString getNameBytes();\npublic Builder setName(java.lang.String value);\npublic Builder clearName();\npublic Builder setNameBytes(com.google.protobuf.ByteString value);\nprivate int id_;\npublic int getId();\npublic Builder setId(int value);\npublic Builder clearId();\nprivate java.lang.Object email_=\"\";\npublic java.lang.String getEmail();\npublic com.google.protobuf.ByteString getEmailBytes();\npublic Builder setEmail(java.lang.String value);\npublic Builder clearEmail();\npublic Builder setEmailBytes(com.google.protobuf.ByteString value);\nprivate int contact_=0;\npublic int getContactValue();\npublic Builder setContactValue(int value);\npublic kafdrop.protos.Person.Contact getContact();\npublic Builder setContact(kafdrop.protos.Person.Contact value);\npublic Builder clearContact();\nprivate com.google.protobuf.LazyStringList data_=com.google.protobuf.LazyStringArrayList.EMPTY;\nprivate void ensureDataIsMutable();\npublic com.google.protobuf.ProtocolStringList getDataList();\npublic int getDataCount();\npublic java.lang.String getData(int index);\npublic com.google.protobuf.ByteString getDataBytes(int index);\npublic Builder setData(int index,java.lang.String value);\npublic Builder addData(java.lang.String value);\npublic Builder addAllData(java.lang.Iterable<java.lang.String> values);\npublic Builder clearData();\npublic Builder addDataBytes(com.google.protobuf.ByteString value);\npublic final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields);\npublic final Builder mergeUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields);\n}\nprivate static final kafdrop.protos.Person DEFAULT_INSTANCE;\nstatic {\nDEFAULT_INSTANCE=new kafdrop.protos.Person();\n}\npublic static kafdrop.protos.Person getDefaultInstance();\nprivate static final com.google.protobuf.Parser<Person> PARSER=new com.google.protobuf.AbstractParser<Person>(){\n@java.lang.Override public Person parsePartialFrom(com.google.protobuf.CodedInputStream input,com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException {\nreturn new Person(input,extensionRegistry);\n}\n}\n;\npublic static com.google.protobuf.Parser<Person> parser();\npublic com.google.protobuf.Parser<Person> getParserForType();\npublic kafdrop.protos.Person getDefaultInstanceForType();\n}\n"}}] | [{"getBroker": {"retrieved_name": "getBroker", "raw_body": "Optional<BrokerVO> getBroker(int id);\n"}}, {"orElseThrow": {"retrieved_name": "toString", "raw_body": "@Override public String toString(){\n return ConsumerPartitionVO.class.getSimpleName() + \" [groupId=\" + groupId+ \", topic=\"+ topic+ \", partitionId=\"+ partitionId+ \", offset=\"+ offset+ \", size=\"+ size+ \", firstOffset=\"+ firstOffset+ \"]\";\n}\n"}}, {"addAttribute": {"retrieved_name": "addData", "raw_body": "/** \n * <code>repeated string data = 5;</code>\n * @param value The data to add.\n * @return This builder for chaining.\n */\npublic Builder addData(java.lang.String value){\n if (value == null) {\n throw new NullPointerException();\n }\n ensureDataIsMutable();\n data_.add(value);\n onChanged();\n return this;\n}\n"}}] | [] |
|
graphhopper_graphhopper | graphhopper/core/src/main/java/com/graphhopper/routing/InstructionsOutgoingEdges.java | InstructionsOutgoingEdges | isLeavingCurrentStreet | class InstructionsOutgoingEdges {
private final EdgeIteratorState prevEdge;
private final EdgeIteratorState currentEdge;
// Outgoing edges that we would be allowed to turn on
private final List<EdgeIteratorState> allowedAlternativeTurns;
// All outgoing edges, including oneways in the wrong direction
private final List<EdgeIteratorState> visibleAlternativeTurns;
private final DecimalEncodedValue maxSpeedEnc;
private final EnumEncodedValue<RoadClass> roadClassEnc;
private final BooleanEncodedValue roadClassLinkEnc;
private final NodeAccess nodeAccess;
private final Weighting weighting;
public InstructionsOutgoingEdges(EdgeIteratorState prevEdge,
EdgeIteratorState currentEdge,
Weighting weighting,
DecimalEncodedValue maxSpeedEnc,
EnumEncodedValue<RoadClass> roadClassEnc,
BooleanEncodedValue roadClassLinkEnc,
EdgeExplorer allExplorer,
NodeAccess nodeAccess,
int prevNode,
int baseNode,
int adjNode) {
this.prevEdge = prevEdge;
this.currentEdge = currentEdge;
this.weighting = weighting;
this.maxSpeedEnc = maxSpeedEnc;
this.roadClassEnc = roadClassEnc;
this.roadClassLinkEnc = roadClassLinkEnc;
this.nodeAccess = nodeAccess;
visibleAlternativeTurns = new ArrayList<>();
allowedAlternativeTurns = new ArrayList<>();
EdgeIterator edgeIter = allExplorer.setBaseNode(baseNode);
while (edgeIter.next()) {
if (edgeIter.getAdjNode() != prevNode && edgeIter.getAdjNode() != adjNode) {
if (Double.isFinite(weighting.calcEdgeWeight(edgeIter, false))) {
EdgeIteratorState tmpEdge = edgeIter.detach(false);
allowedAlternativeTurns.add(tmpEdge);
visibleAlternativeTurns.add(tmpEdge);
} else if (Double.isFinite(weighting.calcEdgeWeight(edgeIter, true))) {
visibleAlternativeTurns.add(edgeIter.detach(false));
}
}
}
}
/**
* This method calculates the number of allowed outgoing edges, which could be considered the number of possible
* roads one might take at the intersection. This excludes the road you are coming from and inaccessible roads.
*/
public int getAllowedTurns() {
return 1 + allowedAlternativeTurns.size();
}
/**
* This method calculates the number of all outgoing edges, which could be considered the number of roads you see
* at the intersection. This excludes the road you are coming from and also inaccessible roads.
*/
public int getVisibleTurns() {
return 1 + visibleAlternativeTurns.size();
}
/**
* Checks if the outgoing edges are slower by the provided factor. If they are, this indicates, that we are staying
* on the prominent street that one would follow anyway.
*/
public boolean outgoingEdgesAreSlowerByFactor(double factor) {
double tmpSpeed = getSpeed(currentEdge);
double pathSpeed = getSpeed(prevEdge);
// speed change indicates that we change road types
if (Math.abs(pathSpeed - tmpSpeed) >= 1) {
return false;
}
double maxSurroundingSpeed = -1;
for (EdgeIteratorState edge : allowedAlternativeTurns) {
tmpSpeed = getSpeed(edge);
if (tmpSpeed > maxSurroundingSpeed) {
maxSurroundingSpeed = tmpSpeed;
}
}
// surrounding streets need to be slower by a factor and call round() so that tiny differences are ignored
return Math.round(maxSurroundingSpeed * factor) < Math.round(pathSpeed);
}
/**
* Will return the tagged maxspeed, if available, if not, we use the average speed
* TODO: Should we rely only on the tagged maxspeed?
*/
private double getSpeed(EdgeIteratorState edge) {
double maxSpeed = edge.get(maxSpeedEnc);
if (Double.isInfinite(maxSpeed))
return edge.getDistance() / weighting.calcEdgeMillis(edge, false) * 3600;
return maxSpeed;
}
/**
* Returns an edge that has more or less in the same orientation as the prevEdge, but is not the currentEdge.
* If there is one, this indicates that we might need an instruction to help finding the correct edge out of the different choices.
* If there is none, return null.
*/
public EdgeIteratorState getOtherContinue(double prevLat, double prevLon, double prevOrientation) {
int tmpSign;
for (EdgeIteratorState edge : allowedAlternativeTurns) {
GHPoint point = InstructionsHelper.getPointForOrientationCalculation(edge, nodeAccess);
tmpSign = InstructionsHelper.calculateSign(prevLat, prevLon, point.getLat(), point.getLon(), prevOrientation);
if (Math.abs(tmpSign) <= 1) {
return edge;
}
}
return null;
}
/**
* If the name and prevName changes this method checks if either the current street is continued on a
* different edge or if the edge we are turning onto is continued on a different edge.
* If either of these properties is true, we can be quite certain that a turn instruction should be provided.
*/
public boolean isLeavingCurrentStreet(String prevName, String name) {<FILL_FUNCTION_BODY>}
private boolean isTheSameRoadClassAndLink(EdgeIteratorState edge1, EdgeIteratorState edge2) {
return edge1.get(roadClassEnc) == edge2.get(roadClassEnc) && edge1.get(roadClassLinkEnc) == edge2.get(roadClassLinkEnc);
}
} |
if (InstructionsHelper.isNameSimilar(name, prevName)) {
return false;
}
boolean roadClassOrLinkChange = !isTheSameRoadClassAndLink(prevEdge, currentEdge);
for (EdgeIteratorState edge : allowedAlternativeTurns) {
String edgeName = edge.getName();
// leave the current street
if (InstructionsHelper.isNameSimilar(prevName, edgeName) || (roadClassOrLinkChange && isTheSameRoadClassAndLink(prevEdge, edge))) {
return true;
}
// enter a different street
if (InstructionsHelper.isNameSimilar(name, edgeName) || (roadClassOrLinkChange && isTheSameRoadClassAndLink(currentEdge, edge))) {
return true;
}
}
return false;
|
if (!prevName.equals(name)) {
return true;
}
for (EdgeIteratorState edge : allowedAlternativeTurns) {
if (!edge.get(roadClassEnc).equals(currentEdge.get(roadClassEnc)) || !isTheSameRoadClassAndLink(edge, currentEdge)) {
return true;
}
}
return false;
| [
"List<EdgeIteratorState>",
"EnumEncodedValue<RoadClass>",
"EdgeIteratorState"
] | [
"equals",
"get"
] | [
"EdgeIteratorState",
"List<EdgeIteratorState>"
] | [
"getName",
"isNameSimilar"
] | {
"methods": [
"equals",
"get"
],
"similar_methods": [
"isLeavingCurrentStreet"
],
"types": [
"List<EdgeIteratorState>",
"EnumEncodedValue<RoadClass>",
"EdgeIteratorState"
]
} | /**
* This interface represents an edge and is one possible state of an EdgeIterator. Example: <span> EdgeExplorer expl = graph.createEdgeExplorer(); EdgeIterator iter = expl.setBaseNode(baseNode); while(iter.next()) { iter.getBaseBase() // equals to the specified baseNode } </span>
* @author Peter Karich
* @see EdgeIterator
* @see EdgeExplorer
*/
public interface EdgeIteratorState {
BooleanEncodedValue UNFAVORED_EDGE=new SimpleBooleanEncodedValue("unfavored");
/**
* This method can be used to fetch the internal reverse state of an edge.
*/
BooleanEncodedValue REVERSE_STATE=new BooleanEncodedValue(){
@Override public int init( InitializerConfig init);
@Override public String getName();
@Override public boolean getBool( boolean reverse, int edgeId, EdgeIntAccess edgeIntAccess);
@Override public void setBool( boolean reverse, int edgeId, EdgeIntAccess edgeIntAccess, boolean value);
@Override public boolean isStoreTwoDirections();
}
;
/**
* @return the edge id of the current edge. Do not make any assumptions about the concretevalues, except that for an implementation it is recommended that they'll be contiguous.
*/
int getEdge();
/**
* Returns the edge key of the current edge. The edge id can be derived from the edge key by calling {@link GHUtility#getEdgeFromEdgeKey(int)}, but the edge key also contains information about the direction of the edge. The edge key is even when the edge is oriented in storage direction and odd otherwise. You can use the edge key to retrieve an edge state in the associated direction using {@link Graph#getEdgeIteratorStateForKey(int)}.
*/
int getEdgeKey();
/**
* Like #getEdgeKey, but returns the reverse key.
*/
int getReverseEdgeKey();
/**
* Returns the node used to instantiate the EdgeIterator. Often only used for convenience reasons. Do not confuse this with a <i>source node</i> of a directed edge.
* @return the requested node itself
* @see EdgeIterator
*/
int getBaseNode();
/**
* @return the adjacent node of baseNode for the current edge.
* @see EdgeIterator
*/
int getAdjNode();
/**
* For road network data like OSM a way is often not just a straight line. The nodes between the junction nodes are called pillar nodes. The junction nodes are called tower nodes and used for routing. The pillar nodes are necessary to have an exact geometry. See the docs for more information (docs/core/low-level-api.md#what-are-pillar-and-tower-nodes). Updates to the returned list are not reflected in the graph, for that you've to use setWayGeometry.
* @param mode {@link FetchMode}
* @return the pillar and/or tower nodes depending on the mode.
*/
PointList fetchWayGeometry( FetchMode mode);
/**
* @param list is a sorted collection of coordinates between the base node and the current adjacent node. Specifythe list without the adjacent and base node. This method can be called multiple times, but if the distance changes, the setDistance method is not called automatically.
*/
EdgeIteratorState setWayGeometry( PointList list);
/**
* @return the distance of the current edge in meter
*/
double getDistance();
EdgeIteratorState setDistance( double dist);
/**
* Returns edge properties stored in direction of the raw database layout. So do not use it directly, instead use the appropriate set/get methods with its EncodedValue object.
*/
IntsRef getFlags();
/**
* Stores the specified edgeFlags down to the DataAccess
*/
EdgeIteratorState setFlags( IntsRef edgeFlags);
boolean get( BooleanEncodedValue property);
EdgeIteratorState set( BooleanEncodedValue property, boolean value);
boolean getReverse( BooleanEncodedValue property);
EdgeIteratorState setReverse( BooleanEncodedValue property, boolean value);
EdgeIteratorState set( BooleanEncodedValue property, boolean fwd, boolean bwd);
int get( IntEncodedValue property);
EdgeIteratorState set( IntEncodedValue property, int value);
int getReverse( IntEncodedValue property);
EdgeIteratorState setReverse( IntEncodedValue property, int value);
EdgeIteratorState set( IntEncodedValue property, int fwd, int bwd);
double get( DecimalEncodedValue property);
EdgeIteratorState set( DecimalEncodedValue property, double value);
double getReverse( DecimalEncodedValue property);
EdgeIteratorState setReverse( DecimalEncodedValue property, double value);
EdgeIteratorState set( DecimalEncodedValue property, double fwd, double bwd);
<T extends Enum<?>>T get( EnumEncodedValue<T> property);
<T extends Enum<?>>EdgeIteratorState set( EnumEncodedValue<T> property, T value);
<T extends Enum<?>>T getReverse( EnumEncodedValue<T> property);
<T extends Enum<?>>EdgeIteratorState setReverse( EnumEncodedValue<T> property, T value);
<T extends Enum<?>>EdgeIteratorState set( EnumEncodedValue<T> property, T fwd, T bwd);
String get( StringEncodedValue property);
EdgeIteratorState set( StringEncodedValue property, String value);
String getReverse( StringEncodedValue property);
EdgeIteratorState setReverse( StringEncodedValue property, String value);
EdgeIteratorState set( StringEncodedValue property, String fwd, String bwd);
/**
* Identical to calling getKeyValues().get("name") if name is stored for both directions. Note that for backward compatibility this method returns an empty String instead of null if there was no KeyPair with key==name stored.
* @return the stored value for the key "name" in the KeyValue list of this EdgeIteratorState.
*/
String getName();
/**
* This stores the specified key-value pairs in the storage of this EdgeIteratorState. This is more flexible compared to the mechanism of flags and EncodedValue and allows storing sparse key value pairs more efficient. But it might be slow and more inefficient on retrieval. Call this setKeyValues method only once per EdgeIteratorState as it allocates new space everytime this method is called.
*/
EdgeIteratorState setKeyValues( List<KVStorage.KeyValue> map);
/**
* This method returns KeyValue pairs for both directions in contrast to {@link #getValue(String)}.
* @see #setKeyValues(List)
*/
List<KVStorage.KeyValue> getKeyValues();
/**
* This method returns the *first* value for the specified key and only if stored for the direction of this EdgeIteratorState. If you need more than one value see also {@link #getKeyValues()}. Avoid storing KeyPairs with duplicate keys as only the first will be reachable with this method. Currently, there is no support to use this method in a custom_model, and you should use EncodedValues instead.
*/
Object getValue( String key);
/**
* Clones this EdgeIteratorState.
* @param reverse if true a detached edgeState with reversed properties is created where baseand adjacent nodes, flags and wayGeometry are in reversed order. See #162 for more details about why we need the reverse parameter.
*/
EdgeIteratorState detach( boolean reverse);
/**
* Copies the properties of the specified edge into this edge. Does not change nodes!
* @return the specified edge e
*/
EdgeIteratorState copyPropertiesFrom( EdgeIteratorState e);
}
/**
* This class allows to store distinct values via an enum. I.e. it stores just the indices
*/
public final class EnumEncodedValue<E extends Enum> extends IntEncodedValueImpl {
@JsonIgnore private final E[] arr;
private final Class<E> enumType;
public EnumEncodedValue( String name, Class<E> enumType);
public EnumEncodedValue( String name, Class<E> enumType, boolean storeTwoDirections);
@JsonCreator(mode=JsonCreator.Mode.PROPERTIES) EnumEncodedValue( @JsonProperty("name") String name, @JsonProperty("bits") int bits, @JsonProperty("min_storable_value") int minStorableValue, @JsonProperty("max_storable_value") int maxStorableValue, @JsonProperty("max_value") int maxValue, @JsonProperty("negate_reverse_direction") boolean negateReverseDirection, @JsonProperty("store_two_directions") boolean storeTwoDirections, @JsonProperty("fwd_data_index") int fwdDataIndex, @JsonProperty("bwd_data_index") int bwdDataIndex, @JsonProperty("fwd_shift") int fwdShift, @JsonProperty("bwd_shift") int bwdShift, @JsonProperty("fwd_mask") int fwdMask, @JsonProperty("bwd_mask") int bwdMask, @JsonProperty("enum_type") Class<E> enumType);
public Class<E> getEnumType();
public E[] getValues();
public final void setEnum( boolean reverse, int edgeId, EdgeIntAccess edgeIntAccess, E value);
public final E getEnum( boolean reverse, int edgeId, EdgeIntAccess edgeIntAccess);
}
@Override public boolean equals(Object obj){
if (obj == null) return false;
Circle b=(Circle)obj;
return NumHelper.equalsEps(lat,b.lat) && NumHelper.equalsEps(lon,b.lon) && NumHelper.equalsEps(radiusInMeter,b.radiusInMeter);
}
@Override public String get(StringEncodedValue property){
return property.getString(reverse,GHUtility.getEdgeFromEdgeKey(originalEdgeKey),edgeIntAccess);
}
@Test public void testCalcInstructionContinueLeavingStreet(){
final BaseGraph g=new BaseGraph.Builder(carManager).create();
final NodeAccess na=g.getNodeAccess();
na.setNode(1,48.982618,13.122021);
na.setNode(2,48.982565,13.121597);
na.setNode(3,48.982611,13.121012);
na.setNode(4,48.982565,13.121002);
g.edge(1,2).set(carAvSpeedEnc,60,60).setDistance(5).setKeyValues(createKV(STREET_NAME,"Regener Weg"));
g.edge(2,4).set(carAvSpeedEnc,60,60).setDistance(5);
g.edge(2,3).set(carAvSpeedEnc,60,60).setDistance(5).setKeyValues(createKV(STREET_NAME,"Regener Weg"));
Weighting weighting=new SpeedWeighting(carAvSpeedEnc);
Path p=new Dijkstra(g,weighting,TraversalMode.NODE_BASED).calcPath(1,4);
assertTrue(p.isFound());
InstructionList wayList=InstructionsFromEdges.calcInstructions(p,p.graph,weighting,carManager,tr);
assertEquals(3,wayList.size());
assertEquals(-7,wayList.get(1).getSign());
}
| public interface EdgeIteratorState {
BooleanEncodedValue UNFAVORED_EDGE=new SimpleBooleanEncodedValue("unfavored");
BooleanEncodedValue REVERSE_STATE=new BooleanEncodedValue(){
public int init( InitializerConfig init);
public String getName();
public boolean getBool( boolean reverse, int edgeId, EdgeIntAccess edgeIntAccess);
public void setBool( boolean reverse, int edgeId, EdgeIntAccess edgeIntAccess, boolean value);
public boolean isStoreTwoDirections();
}
;
int getEdge();
int getEdgeKey();
int getReverseEdgeKey();
int getBaseNode();
int getAdjNode();
PointList fetchWayGeometry( FetchMode mode);
EdgeIteratorState setWayGeometry( PointList list);
double getDistance();
EdgeIteratorState setDistance( double dist);
IntsRef getFlags();
EdgeIteratorState setFlags( IntsRef edgeFlags);
boolean get( BooleanEncodedValue property);
EdgeIteratorState set( BooleanEncodedValue property, boolean value);
boolean getReverse( BooleanEncodedValue property);
EdgeIteratorState setReverse( BooleanEncodedValue property, boolean value);
EdgeIteratorState set( BooleanEncodedValue property, boolean fwd, boolean bwd);
int get( IntEncodedValue property);
EdgeIteratorState set( IntEncodedValue property, int value);
int getReverse( IntEncodedValue property);
EdgeIteratorState setReverse( IntEncodedValue property, int value);
EdgeIteratorState set( IntEncodedValue property, int fwd, int bwd);
double get( DecimalEncodedValue property);
EdgeIteratorState set( DecimalEncodedValue property, double value);
double getReverse( DecimalEncodedValue property);
EdgeIteratorState setReverse( DecimalEncodedValue property, double value);
EdgeIteratorState set( DecimalEncodedValue property, double fwd, double bwd);
<T extends Enum<?>>T get( EnumEncodedValue<T> property);
<T extends Enum<?>>EdgeIteratorState set( EnumEncodedValue<T> property, T value);
<T extends Enum<?>>T getReverse( EnumEncodedValue<T> property);
<T extends Enum<?>>EdgeIteratorState setReverse( EnumEncodedValue<T> property, T value);
<T extends Enum<?>>EdgeIteratorState set( EnumEncodedValue<T> property, T fwd, T bwd);
String get( StringEncodedValue property);
EdgeIteratorState set( StringEncodedValue property, String value);
String getReverse( StringEncodedValue property);
EdgeIteratorState setReverse( StringEncodedValue property, String value);
EdgeIteratorState set( StringEncodedValue property, String fwd, String bwd);
String getName();
EdgeIteratorState setKeyValues( List<KVStorage.KeyValue> map);
List<KVStorage.KeyValue> getKeyValues();
Object getValue( String key);
EdgeIteratorState detach( boolean reverse);
EdgeIteratorState copyPropertiesFrom( EdgeIteratorState e);
}
public final class EnumEncodedValue<E extends Enum> extends IntEncodedValueImpl {
private final E[] arr;
private final Class<E> enumType;
public EnumEncodedValue( String name, Class<E> enumType);
public EnumEncodedValue( String name, Class<E> enumType, boolean storeTwoDirections);
EnumEncodedValue( String name, int bits, int minStorableValue, int maxStorableValue, int maxValue, boolean negateReverseDirection, boolean storeTwoDirections, int fwdDataIndex, int bwdDataIndex, int fwdShift, int bwdShift, int fwdMask, int bwdMask, Class<E> enumType);
public Class<E> getEnumType();
public E[] getValues();
public final void setEnum( boolean reverse, int edgeId, EdgeIntAccess edgeIntAccess, E value);
public final E getEnum( boolean reverse, int edgeId, EdgeIntAccess edgeIntAccess);
}
@Override public boolean equals(Object obj){
if (obj == null) return false;
Circle b=(Circle)obj;
return NumHelper.equalsEps(lat,b.lat) && NumHelper.equalsEps(lon,b.lon) && NumHelper.equalsEps(radiusInMeter,b.radiusInMeter);
}
@Override public String get(StringEncodedValue property){
return property.getString(reverse,GHUtility.getEdgeFromEdgeKey(originalEdgeKey),edgeIntAccess);
}
@Test public void testCalcInstructionContinueLeavingStreet(){
final BaseGraph g=new BaseGraph.Builder(carManager).create();
final NodeAccess na=g.getNodeAccess();
na.setNode(1,48.982618,13.122021);
na.setNode(2,48.982565,13.121597);
na.setNode(3,48.982611,13.121012);
na.setNode(4,48.982565,13.121002);
g.edge(1,2).set(carAvSpeedEnc,60,60).setDistance(5).setKeyValues(createKV(STREET_NAME,"Regener Weg"));
g.edge(2,4).set(carAvSpeedEnc,60,60).setDistance(5);
g.edge(2,3).set(carAvSpeedEnc,60,60).setDistance(5).setKeyValues(createKV(STREET_NAME,"Regener Weg"));
Weighting weighting=new SpeedWeighting(carAvSpeedEnc);
Path p=new Dijkstra(g,weighting,TraversalMode.NODE_BASED).calcPath(1,4);
assertTrue(p.isFound());
InstructionList wayList=InstructionsFromEdges.calcInstructions(p,p.graph,weighting,carManager,tr);
assertEquals(3,wayList.size());
assertEquals(-7,wayList.get(1).getSign());
}
| {"types": [{"List<EdgeIteratorState>": "EdgeIteratorState"}, {"EnumEncodedValue<RoadClass>": "EnumEncodedValue"}, {"EdgeIteratorState": "EdgeIteratorState"}], "methods": [{"equals": "equals"}, {"get": "get"}], "similar_methods": [{"isLeavingCurrentStreet": "testCalcInstructionContinueLeavingStreet"}]} | [{"List<EdgeIteratorState>": {"retrieved_name": "EdgeIteratorState", "raw_body": "/** \n * This interface represents an edge and is one possible state of an EdgeIterator. Example: <span> EdgeExplorer expl = graph.createEdgeExplorer(); EdgeIterator iter = expl.setBaseNode(baseNode); while(iter.next()) { iter.getBaseBase() // equals to the specified baseNode } </span>\n * @author Peter Karich\n * @see EdgeIterator\n * @see EdgeExplorer\n */\npublic interface EdgeIteratorState {\n BooleanEncodedValue UNFAVORED_EDGE=new SimpleBooleanEncodedValue(\"unfavored\");\n /** \n * This method can be used to fetch the internal reverse state of an edge.\n */\n BooleanEncodedValue REVERSE_STATE=new BooleanEncodedValue(){\n @Override public int init( InitializerConfig init);\n @Override public String getName();\n @Override public boolean getBool( boolean reverse, int edgeId, EdgeIntAccess edgeIntAccess);\n @Override public void setBool( boolean reverse, int edgeId, EdgeIntAccess edgeIntAccess, boolean value);\n @Override public boolean isStoreTwoDirections();\n }\n;\n /** \n * @return the edge id of the current edge. Do not make any assumptions about the concretevalues, except that for an implementation it is recommended that they'll be contiguous.\n */\n int getEdge();\n /** \n * Returns the edge key of the current edge. The edge id can be derived from the edge key by calling {@link GHUtility#getEdgeFromEdgeKey(int)}, but the edge key also contains information about the direction of the edge. The edge key is even when the edge is oriented in storage direction and odd otherwise. You can use the edge key to retrieve an edge state in the associated direction using {@link Graph#getEdgeIteratorStateForKey(int)}.\n */\n int getEdgeKey();\n /** \n * Like #getEdgeKey, but returns the reverse key.\n */\n int getReverseEdgeKey();\n /** \n * Returns the node used to instantiate the EdgeIterator. Often only used for convenience reasons. Do not confuse this with a <i>source node</i> of a directed edge.\n * @return the requested node itself\n * @see EdgeIterator\n */\n int getBaseNode();\n /** \n * @return the adjacent node of baseNode for the current edge.\n * @see EdgeIterator\n */\n int getAdjNode();\n /** \n * For road network data like OSM a way is often not just a straight line. The nodes between the junction nodes are called pillar nodes. The junction nodes are called tower nodes and used for routing. The pillar nodes are necessary to have an exact geometry. See the docs for more information (docs/core/low-level-api.md#what-are-pillar-and-tower-nodes). Updates to the returned list are not reflected in the graph, for that you've to use setWayGeometry.\n * @param mode {@link FetchMode}\n * @return the pillar and/or tower nodes depending on the mode.\n */\n PointList fetchWayGeometry( FetchMode mode);\n /** \n * @param list is a sorted collection of coordinates between the base node and the current adjacent node. Specifythe list without the adjacent and base node. This method can be called multiple times, but if the distance changes, the setDistance method is not called automatically.\n */\n EdgeIteratorState setWayGeometry( PointList list);\n /** \n * @return the distance of the current edge in meter\n */\n double getDistance();\n EdgeIteratorState setDistance( double dist);\n /** \n * Returns edge properties stored in direction of the raw database layout. So do not use it directly, instead use the appropriate set/get methods with its EncodedValue object.\n */\n IntsRef getFlags();\n /** \n * Stores the specified edgeFlags down to the DataAccess\n */\n EdgeIteratorState setFlags( IntsRef edgeFlags);\n boolean get( BooleanEncodedValue property);\n EdgeIteratorState set( BooleanEncodedValue property, boolean value);\n boolean getReverse( BooleanEncodedValue property);\n EdgeIteratorState setReverse( BooleanEncodedValue property, boolean value);\n EdgeIteratorState set( BooleanEncodedValue property, boolean fwd, boolean bwd);\n int get( IntEncodedValue property);\n EdgeIteratorState set( IntEncodedValue property, int value);\n int getReverse( IntEncodedValue property);\n EdgeIteratorState setReverse( IntEncodedValue property, int value);\n EdgeIteratorState set( IntEncodedValue property, int fwd, int bwd);\n double get( DecimalEncodedValue property);\n EdgeIteratorState set( DecimalEncodedValue property, double value);\n double getReverse( DecimalEncodedValue property);\n EdgeIteratorState setReverse( DecimalEncodedValue property, double value);\n EdgeIteratorState set( DecimalEncodedValue property, double fwd, double bwd);\n <T extends Enum<?>>T get( EnumEncodedValue<T> property);\n <T extends Enum<?>>EdgeIteratorState set( EnumEncodedValue<T> property, T value);\n <T extends Enum<?>>T getReverse( EnumEncodedValue<T> property);\n <T extends Enum<?>>EdgeIteratorState setReverse( EnumEncodedValue<T> property, T value);\n <T extends Enum<?>>EdgeIteratorState set( EnumEncodedValue<T> property, T fwd, T bwd);\n String get( StringEncodedValue property);\n EdgeIteratorState set( StringEncodedValue property, String value);\n String getReverse( StringEncodedValue property);\n EdgeIteratorState setReverse( StringEncodedValue property, String value);\n EdgeIteratorState set( StringEncodedValue property, String fwd, String bwd);\n /** \n * Identical to calling getKeyValues().get(\"name\") if name is stored for both directions. Note that for backward compatibility this method returns an empty String instead of null if there was no KeyPair with key==name stored.\n * @return the stored value for the key \"name\" in the KeyValue list of this EdgeIteratorState.\n */\n String getName();\n /** \n * This stores the specified key-value pairs in the storage of this EdgeIteratorState. This is more flexible compared to the mechanism of flags and EncodedValue and allows storing sparse key value pairs more efficient. But it might be slow and more inefficient on retrieval. Call this setKeyValues method only once per EdgeIteratorState as it allocates new space everytime this method is called.\n */\n EdgeIteratorState setKeyValues( List<KVStorage.KeyValue> map);\n /** \n * This method returns KeyValue pairs for both directions in contrast to {@link #getValue(String)}.\n * @see #setKeyValues(List)\n */\n List<KVStorage.KeyValue> getKeyValues();\n /** \n * This method returns the *first* value for the specified key and only if stored for the direction of this EdgeIteratorState. If you need more than one value see also {@link #getKeyValues()}. Avoid storing KeyPairs with duplicate keys as only the first will be reachable with this method. Currently, there is no support to use this method in a custom_model, and you should use EncodedValues instead.\n */\n Object getValue( String key);\n /** \n * Clones this EdgeIteratorState.\n * @param reverse if true a detached edgeState with reversed properties is created where baseand adjacent nodes, flags and wayGeometry are in reversed order. See #162 for more details about why we need the reverse parameter.\n */\n EdgeIteratorState detach( boolean reverse);\n /** \n * Copies the properties of the specified edge into this edge. Does not change nodes!\n * @return the specified edge e\n */\n EdgeIteratorState copyPropertiesFrom( EdgeIteratorState e);\n}\n", "raw_body_no_cmt": "public interface EdgeIteratorState {\n BooleanEncodedValue UNFAVORED_EDGE=new SimpleBooleanEncodedValue(\"unfavored\");\n BooleanEncodedValue REVERSE_STATE=new BooleanEncodedValue(){\n public int init( InitializerConfig init);\n public String getName();\n public boolean getBool( boolean reverse, int edgeId, EdgeIntAccess edgeIntAccess);\n public void setBool( boolean reverse, int edgeId, EdgeIntAccess edgeIntAccess, boolean value);\n public boolean isStoreTwoDirections();\n }\n;\n int getEdge();\n int getEdgeKey();\n int getReverseEdgeKey();\n int getBaseNode();\n int getAdjNode();\n PointList fetchWayGeometry( FetchMode mode);\n EdgeIteratorState setWayGeometry( PointList list);\n double getDistance();\n EdgeIteratorState setDistance( double dist);\n IntsRef getFlags();\n EdgeIteratorState setFlags( IntsRef edgeFlags);\n boolean get( BooleanEncodedValue property);\n EdgeIteratorState set( BooleanEncodedValue property, boolean value);\n boolean getReverse( BooleanEncodedValue property);\n EdgeIteratorState setReverse( BooleanEncodedValue property, boolean value);\n EdgeIteratorState set( BooleanEncodedValue property, boolean fwd, boolean bwd);\n int get( IntEncodedValue property);\n EdgeIteratorState set( IntEncodedValue property, int value);\n int getReverse( IntEncodedValue property);\n EdgeIteratorState setReverse( IntEncodedValue property, int value);\n EdgeIteratorState set( IntEncodedValue property, int fwd, int bwd);\n double get( DecimalEncodedValue property);\n EdgeIteratorState set( DecimalEncodedValue property, double value);\n double getReverse( DecimalEncodedValue property);\n EdgeIteratorState setReverse( DecimalEncodedValue property, double value);\n EdgeIteratorState set( DecimalEncodedValue property, double fwd, double bwd);\n <T extends Enum<?>>T get( EnumEncodedValue<T> property);\n <T extends Enum<?>>EdgeIteratorState set( EnumEncodedValue<T> property, T value);\n <T extends Enum<?>>T getReverse( EnumEncodedValue<T> property);\n <T extends Enum<?>>EdgeIteratorState setReverse( EnumEncodedValue<T> property, T value);\n <T extends Enum<?>>EdgeIteratorState set( EnumEncodedValue<T> property, T fwd, T bwd);\n String get( StringEncodedValue property);\n EdgeIteratorState set( StringEncodedValue property, String value);\n String getReverse( StringEncodedValue property);\n EdgeIteratorState setReverse( StringEncodedValue property, String value);\n EdgeIteratorState set( StringEncodedValue property, String fwd, String bwd);\n String getName();\n EdgeIteratorState setKeyValues( List<KVStorage.KeyValue> map);\n List<KVStorage.KeyValue> getKeyValues();\n Object getValue( String key);\n EdgeIteratorState detach( boolean reverse);\n EdgeIteratorState copyPropertiesFrom( EdgeIteratorState e);\n}\n"}}, {"EnumEncodedValue<RoadClass>": {"retrieved_name": "EnumEncodedValue", "raw_body": "/** \n * This class allows to store distinct values via an enum. I.e. it stores just the indices\n */\npublic final class EnumEncodedValue<E extends Enum> extends IntEncodedValueImpl {\n @JsonIgnore private final E[] arr;\n private final Class<E> enumType;\n public EnumEncodedValue( String name, Class<E> enumType);\n public EnumEncodedValue( String name, Class<E> enumType, boolean storeTwoDirections);\n @JsonCreator(mode=JsonCreator.Mode.PROPERTIES) EnumEncodedValue( @JsonProperty(\"name\") String name, @JsonProperty(\"bits\") int bits, @JsonProperty(\"min_storable_value\") int minStorableValue, @JsonProperty(\"max_storable_value\") int maxStorableValue, @JsonProperty(\"max_value\") int maxValue, @JsonProperty(\"negate_reverse_direction\") boolean negateReverseDirection, @JsonProperty(\"store_two_directions\") boolean storeTwoDirections, @JsonProperty(\"fwd_data_index\") int fwdDataIndex, @JsonProperty(\"bwd_data_index\") int bwdDataIndex, @JsonProperty(\"fwd_shift\") int fwdShift, @JsonProperty(\"bwd_shift\") int bwdShift, @JsonProperty(\"fwd_mask\") int fwdMask, @JsonProperty(\"bwd_mask\") int bwdMask, @JsonProperty(\"enum_type\") Class<E> enumType);\n public Class<E> getEnumType();\n public E[] getValues();\n public final void setEnum( boolean reverse, int edgeId, EdgeIntAccess edgeIntAccess, E value);\n public final E getEnum( boolean reverse, int edgeId, EdgeIntAccess edgeIntAccess);\n}\n", "raw_body_no_cmt": "public final class EnumEncodedValue<E extends Enum> extends IntEncodedValueImpl {\n private final E[] arr;\n private final Class<E> enumType;\n public EnumEncodedValue( String name, Class<E> enumType);\n public EnumEncodedValue( String name, Class<E> enumType, boolean storeTwoDirections);\n EnumEncodedValue( String name, int bits, int minStorableValue, int maxStorableValue, int maxValue, boolean negateReverseDirection, boolean storeTwoDirections, int fwdDataIndex, int bwdDataIndex, int fwdShift, int bwdShift, int fwdMask, int bwdMask, Class<E> enumType);\n public Class<E> getEnumType();\n public E[] getValues();\n public final void setEnum( boolean reverse, int edgeId, EdgeIntAccess edgeIntAccess, E value);\n public final E getEnum( boolean reverse, int edgeId, EdgeIntAccess edgeIntAccess);\n}\n"}}] | [{"equals": {"retrieved_name": "equals", "raw_body": "@Override public boolean equals(Object obj){\n if (obj == null) return false;\n Circle b=(Circle)obj;\n return NumHelper.equalsEps(lat,b.lat) && NumHelper.equalsEps(lon,b.lon) && NumHelper.equalsEps(radiusInMeter,b.radiusInMeter);\n}\n"}}, {"get": {"retrieved_name": "get", "raw_body": "@Override public String get(StringEncodedValue property){\n return property.getString(reverse,GHUtility.getEdgeFromEdgeKey(originalEdgeKey),edgeIntAccess);\n}\n"}}] | [{"isLeavingCurrentStreet": {"retrieved_name": "testCalcInstructionContinueLeavingStreet", "raw_body": "@Test public void testCalcInstructionContinueLeavingStreet(){\n final BaseGraph g=new BaseGraph.Builder(carManager).create();\n final NodeAccess na=g.getNodeAccess();\n na.setNode(1,48.982618,13.122021);\n na.setNode(2,48.982565,13.121597);\n na.setNode(3,48.982611,13.121012);\n na.setNode(4,48.982565,13.121002);\n g.edge(1,2).set(carAvSpeedEnc,60,60).setDistance(5).setKeyValues(createKV(STREET_NAME,\"Regener Weg\"));\n g.edge(2,4).set(carAvSpeedEnc,60,60).setDistance(5);\n g.edge(2,3).set(carAvSpeedEnc,60,60).setDistance(5).setKeyValues(createKV(STREET_NAME,\"Regener Weg\"));\n Weighting weighting=new SpeedWeighting(carAvSpeedEnc);\n Path p=new Dijkstra(g,weighting,TraversalMode.NODE_BASED).calcPath(1,4);\n assertTrue(p.isFound());\n InstructionList wayList=InstructionsFromEdges.calcInstructions(p,p.graph,weighting,carManager,tr);\n assertEquals(3,wayList.size());\n assertEquals(-7,wayList.get(1).getSign());\n}\n"}}] |
|
pmd_pmd | pmd/pmd-core/src/main/java/net/sourceforge/pmd/cpd/SimpleRenderer.java | SimpleRenderer | renderOn | class SimpleRenderer implements CPDReportRenderer {
private String separator;
private boolean trimLeadingWhitespace;
public static final String DEFAULT_SEPARATOR = "=====================================================================";
public SimpleRenderer() {
this(false);
}
public SimpleRenderer(boolean trimLeadingWhitespace) {
this(DEFAULT_SEPARATOR);
this.trimLeadingWhitespace = trimLeadingWhitespace;
}
public SimpleRenderer(String theSeparator) {
separator = theSeparator;
}
@Override
public void render(CPDReport report, Writer writer0) throws IOException {
PrintWriter writer = new PrintWriter(writer0);
Iterator<Match> matches = report.getMatches().iterator();
if (matches.hasNext()) {
renderOn(report, writer, matches.next());
}
while (matches.hasNext()) {
Match match = matches.next();
writer.println(separator);
renderOn(report, writer, match);
}
writer.flush();
}
private void renderOn(CPDReport report, PrintWriter writer, Match match) throws IOException {<FILL_FUNCTION_BODY>}
} |
writer.append("Found a ").append(String.valueOf(match.getLineCount())).append(" line (").append(String.valueOf(match.getTokenCount()))
.append(" tokens) duplication in the following files: ").println();
for (Mark mark : match) {
FileLocation loc = mark.getLocation();
writer.append("Starting at line ")
.append(String.valueOf(loc.getStartLine()))
.append(" of ").append(report.getDisplayName(loc.getFileId()))
.println();
}
writer.println(); // add a line to separate the source from the desc above
Chars source = report.getSourceCodeSlice(match.getFirstMark());
if (trimLeadingWhitespace) {
for (Chars line : StringUtil.linesWithTrimIndent(source)) {
line.writeFully(writer);
writer.println();
}
return;
}
source.writeFully(writer);
writer.println();
|
writer.println(match.getFilePath());
writer.println(match.getLine());
writer.println(match.getLineOffset());
writer.println(match.getLineCount());
writer.println(match.getTokens());
writer.println(match.getTokenCount());
writer.println(match.getTokenOffset());
writer.println(match.getTokenLength());
writer.println(match.getTokenLineOffset());
writer.println(match.getTokenLineCount());
writer.println(match.getTokenLine());
writer.println(match.getTokenLineCount());
writer.println(match.getTokenLineCount());
writer.println(match.getTokenLineCount());
writer.println(match.getTokenLineCount());
writer.println(match.getTokenLineCount());
writer.println(match.getTokenLineCount());
writer.println(match.getTokenLineCount());
writer.println(match.getTokenLineCount());
writer.println(match.getTokenLineCount());
writer.println(match.getTokenLineCount());
writer.println(match.getTokenLineCount());
writer.println(match.getTokenLineCount());
writer.println(match.getTokenLineCount());
writer.println(match.getTokenLineCount());
writer.println(match.getTokenLineCount());
writer.println(match.getTokenLineCount());
writer.println(match.getTokenLineCount());
writer.println(match.getTokenLineCount());
writer.println(match.getTokenLineCount());
writer.println(match.getTokenLineCount());
writer.println(match | [
"Match",
"PrintWriter",
"CPDReport"
] | [
"getFilePath",
"getTokenCount",
"getTokenOffset",
"getTokenLineOffset",
"getLineOffset",
"getLine",
"getTokenLine",
"println",
"getTokenLineCount",
"getTokens",
"getTokenLength",
"getLineCount"
] | [
"Chars",
"Match",
"CPDReport",
"FileLocation",
"PrintWriter",
"Mark"
] | [
"getStartLine",
"writeFully",
"getTokenCount",
"getFirstMark",
"linesWithTrimIndent",
"getLineCount",
"append",
"getFileId",
"getLocation",
"getDisplayName",
"println",
"getSourceCodeSlice",
"valueOf"
] | {
"methods": [
"getFilePath",
"getTokenCount",
"getTokenOffset",
"getTokenLineOffset",
"getLineOffset",
"getLine",
"getTokenLine",
"println",
"getTokenLineCount",
"getTokens",
"getTokenLength",
"getLineCount"
],
"similar_methods": [
"renderOn"
],
"types": [
"Match",
"PrintWriter",
"CPDReport"
]
} | public class Match implements Comparable<Match>, Iterable<Mark> {
private final int tokenCount;
private final Set<Mark> markSet=new TreeSet<>();
public static final Comparator<Match> MATCHES_COMPARATOR=(ma,mb) -> mb.getMarkCount() - ma.getMarkCount();
public static final Comparator<Match> LINES_COMPARATOR=(ma,mb) -> mb.getLineCount() - ma.getLineCount();
Match( int tokenCount, Mark first, Mark second);
Match( int tokenCount, TokenEntry first, TokenEntry second);
void addMark( TokenEntry entry);
public int getMarkCount();
public int getLineCount();
public int getTokenCount();
public Set<Mark> getMarkSet();
@Override public Iterator<Mark> iterator();
@Override public int compareTo( Match other);
public Mark getFirstMark();
public Mark getSecondMark();
@Override public String toString();
public int getEndIndex();
private Mark getMark( int index);
}
/**
* Simple printer for saxon expressions. Might be useful for debugging / during development. <p>Example: <pre> ExpressionPrinter printer = new ExpressionPrinter(); printer.visit(query.xpathExpression.getInternalExpression()); </pre>
*/
public class ExpressionPrinter extends SaxonExprVisitor {
private int depth=0;
private void print( String s);
@Override public Expression visit( AxisExpression e);
@Override public Expression visit( RootExpression e);
@Override public Expression visit( VennExpression e);
@Override public Expression visit( Expression expr);
}
/**
* The result of a CPD analysis. This is rendered by a {@link CPDReportRenderer}.
* @since 6.48.0
*/
public class CPDReport {
private final SourceManager sourceManager;
private final List<Match> matches;
private final Map<FileId,Integer> numberOfTokensPerFile;
CPDReport( SourceManager sourceManager, List<Match> matches, Map<FileId,Integer> numberOfTokensPerFile);
/**
* Return the list of duplication matches found by the CPD analysis.
*/
public List<Match> getMatches();
/**
* Return a map containing the number of tokens by processed file.
*/
public Map<FileId,Integer> getNumberOfTokensPerFile();
/**
* Return the slice of source code where the mark was found. This returns the entire lines from the start to the end line of the mark.
*/
public Chars getSourceCodeSlice( Mark mark);
/**
* Creates a new CPD report taking all the information from this report, but filtering the matches. Note that the {@linkplain #getNumberOfTokensPerFile() token count map}is not filtered.
* @param filter when true, the match will be kept.
* @return copy of this report
*/
public CPDReport filterMatches( Predicate<Match> filter);
/**
* Return the display name of the given file.
*/
public String getDisplayName( FileId fileId);
}
/**
* Return the simple file name, like {@link Path#getFileName()}. This includes the extension.
*/
String getFileName();
public int getTokenCount(){
return this.tokenCount;
}
public int getTokenCount(){
return this.tokenCount;
}
int[] getLineOffsets(){
return lineOffsets;
}
int[] getLineOffsets(){
return lineOffsets;
}
/**
* Retrieves the requested line from the specified file.
* @param sourceFile the java or cpp source file
* @param line line number to extract
* @return a trimmed line of source code
*/
private String getLine(String sourceFile,int line){
String code=null;
try (BufferedReader br=new BufferedReader(getReader(sourceFile))){
for (int i=0; line > i; i++) {
String txt=br.readLine();
code=txt == null ? "" : txt.trim();
}
}
catch ( IOException ioErr) {
ioErr.printStackTrace();
}
return code;
}
/**
* Returns a string made up of characters from the token mark up to to the current buffer position.
*/
public String getTokenImage(){
return getTokenImageCs().toString();
}
@Override public void println(String x){
buffer.append(x).append(System.lineSeparator());
}
public int getLineCount(){
return getMark(0).getLocation().getLineCount();
}
protected List<TerminalNode> getTokens(int kind){
return children(BaseAntlrTerminalNode.class).filter(it -> it.getTokenKind() == kind).toList(BaseAntlrTerminalNode::asAntlrNode);
}
/**
* Returns the length of the region in characters. This is the difference between start offset and end offset. All characters have length 1, including {@code '\t'}. The sequence {@code "\r\n"} has length 2 andnot 1.
*/
public int getLength(){
return length;
}
public int getLineCount(){
return getMark(0).getLocation().getLineCount();
}
private void renderOn(CPDReport report,PrintWriter writer,Match match) throws IOException {
writer.append("Found a ").append(String.valueOf(match.getLineCount())).append(" line (").append(String.valueOf(match.getTokenCount())).append(" tokens) duplication in the following files: ").println();
for ( Mark mark : match) {
FileLocation loc=mark.getLocation();
writer.append("Starting at line ").append(String.valueOf(loc.getStartLine())).append(" of ").append(report.getDisplayName(loc.getFileId())).println();
}
writer.println();
Chars source=report.getSourceCodeSlice(match.getFirstMark());
if (trimLeadingWhitespace) {
for ( Chars line : StringUtil.linesWithTrimIndent(source)) {
line.writeFully(writer);
writer.println();
}
return;
}
source.writeFully(writer);
writer.println();
}
| public class Match implements Comparable<Match>, Iterable<Mark> {
private final int tokenCount;
private final Set<Mark> markSet=new TreeSet<>();
public static final Comparator<Match> MATCHES_COMPARATOR=(ma,mb) -> mb.getMarkCount() - ma.getMarkCount();
public static final Comparator<Match> LINES_COMPARATOR=(ma,mb) -> mb.getLineCount() - ma.getLineCount();
Match( int tokenCount, Mark first, Mark second);
Match( int tokenCount, TokenEntry first, TokenEntry second);
void addMark( TokenEntry entry);
public int getMarkCount();
public int getLineCount();
public int getTokenCount();
public Set<Mark> getMarkSet();
public Iterator<Mark> iterator();
public int compareTo( Match other);
public Mark getFirstMark();
public Mark getSecondMark();
public String toString();
public int getEndIndex();
private Mark getMark( int index);
}
public class ExpressionPrinter extends SaxonExprVisitor {
private int depth=0;
private void print( String s);
public Expression visit( AxisExpression e);
public Expression visit( RootExpression e);
public Expression visit( VennExpression e);
public Expression visit( Expression expr);
}
public class CPDReport {
private final SourceManager sourceManager;
private final List<Match> matches;
private final Map<FileId,Integer> numberOfTokensPerFile;
CPDReport( SourceManager sourceManager, List<Match> matches, Map<FileId,Integer> numberOfTokensPerFile);
public List<Match> getMatches();
public Map<FileId,Integer> getNumberOfTokensPerFile();
public Chars getSourceCodeSlice( Mark mark);
public CPDReport filterMatches( Predicate<Match> filter);
public String getDisplayName( FileId fileId);
}
/**
* Return the simple file name, like {@link Path#getFileName()}. This includes the extension.
*/
String getFileName();
public int getTokenCount(){
return this.tokenCount;
}
public int getTokenCount(){
return this.tokenCount;
}
int[] getLineOffsets(){
return lineOffsets;
}
int[] getLineOffsets(){
return lineOffsets;
}
/**
* Retrieves the requested line from the specified file.
* @param sourceFile the java or cpp source file
* @param line line number to extract
* @return a trimmed line of source code
*/
private String getLine(String sourceFile,int line){
String code=null;
try (BufferedReader br=new BufferedReader(getReader(sourceFile))){
for (int i=0; line > i; i++) {
String txt=br.readLine();
code=txt == null ? "" : txt.trim();
}
}
catch ( IOException ioErr) {
ioErr.printStackTrace();
}
return code;
}
/**
* Returns a string made up of characters from the token mark up to to the current buffer position.
*/
public String getTokenImage(){
return getTokenImageCs().toString();
}
@Override public void println(String x){
buffer.append(x).append(System.lineSeparator());
}
public int getLineCount(){
return getMark(0).getLocation().getLineCount();
}
protected List<TerminalNode> getTokens(int kind){
return children(BaseAntlrTerminalNode.class).filter(it -> it.getTokenKind() == kind).toList(BaseAntlrTerminalNode::asAntlrNode);
}
/**
* Returns the length of the region in characters. This is the difference between start offset and end offset. All characters have length 1, including {@code '\t'}. The sequence {@code "\r\n"} has length 2 andnot 1.
*/
public int getLength(){
return length;
}
public int getLineCount(){
return getMark(0).getLocation().getLineCount();
}
private void renderOn(CPDReport report,PrintWriter writer,Match match) throws IOException {
writer.append("Found a ").append(String.valueOf(match.getLineCount())).append(" line (").append(String.valueOf(match.getTokenCount())).append(" tokens) duplication in the following files: ").println();
for ( Mark mark : match) {
FileLocation loc=mark.getLocation();
writer.append("Starting at line ").append(String.valueOf(loc.getStartLine())).append(" of ").append(report.getDisplayName(loc.getFileId())).println();
}
writer.println();
Chars source=report.getSourceCodeSlice(match.getFirstMark());
if (trimLeadingWhitespace) {
for ( Chars line : StringUtil.linesWithTrimIndent(source)) {
line.writeFully(writer);
writer.println();
}
return;
}
source.writeFully(writer);
writer.println();
}
| {"types": [{"Match": "Match"}, {"PrintWriter": "ExpressionPrinter"}, {"CPDReport": "CPDReport"}], "methods": [{"getFilePath": "getFileName"}, {"getTokenCount": "getTokenCount"}, {"getTokenOffset": "getTokenCount"}, {"getTokenLineOffset": "getLineOffsets"}, {"getLineOffset": "getLineOffsets"}, {"getLine": "getLine"}, {"getTokenLine": "getTokenImage"}, {"println": "println"}, {"getTokenLineCount": "getLineCount"}, {"getTokens": "getTokens"}, {"getTokenLength": "getLength"}, {"getLineCount": "getLineCount"}], "similar_methods": [{"renderOn": "renderOn"}]} | [{"Match": {"retrieved_name": "Match", "raw_body": "public class Match implements Comparable<Match>, Iterable<Mark> {\n private final int tokenCount;\n private final Set<Mark> markSet=new TreeSet<>();\n public static final Comparator<Match> MATCHES_COMPARATOR=(ma,mb) -> mb.getMarkCount() - ma.getMarkCount();\n public static final Comparator<Match> LINES_COMPARATOR=(ma,mb) -> mb.getLineCount() - ma.getLineCount();\n Match( int tokenCount, Mark first, Mark second);\n Match( int tokenCount, TokenEntry first, TokenEntry second);\n void addMark( TokenEntry entry);\n public int getMarkCount();\n public int getLineCount();\n public int getTokenCount();\n public Set<Mark> getMarkSet();\n @Override public Iterator<Mark> iterator();\n @Override public int compareTo( Match other);\n public Mark getFirstMark();\n public Mark getSecondMark();\n @Override public String toString();\n public int getEndIndex();\n private Mark getMark( int index);\n}\n", "raw_body_no_cmt": "public class Match implements Comparable<Match>, Iterable<Mark> {\n private final int tokenCount;\n private final Set<Mark> markSet=new TreeSet<>();\n public static final Comparator<Match> MATCHES_COMPARATOR=(ma,mb) -> mb.getMarkCount() - ma.getMarkCount();\n public static final Comparator<Match> LINES_COMPARATOR=(ma,mb) -> mb.getLineCount() - ma.getLineCount();\n Match( int tokenCount, Mark first, Mark second);\n Match( int tokenCount, TokenEntry first, TokenEntry second);\n void addMark( TokenEntry entry);\n public int getMarkCount();\n public int getLineCount();\n public int getTokenCount();\n public Set<Mark> getMarkSet();\n public Iterator<Mark> iterator();\n public int compareTo( Match other);\n public Mark getFirstMark();\n public Mark getSecondMark();\n public String toString();\n public int getEndIndex();\n private Mark getMark( int index);\n}\n"}}, {"PrintWriter": {"retrieved_name": "ExpressionPrinter", "raw_body": "/** \n * Simple printer for saxon expressions. Might be useful for debugging / during development. <p>Example: <pre> ExpressionPrinter printer = new ExpressionPrinter(); printer.visit(query.xpathExpression.getInternalExpression()); </pre>\n */\npublic class ExpressionPrinter extends SaxonExprVisitor {\n private int depth=0;\n private void print( String s);\n @Override public Expression visit( AxisExpression e);\n @Override public Expression visit( RootExpression e);\n @Override public Expression visit( VennExpression e);\n @Override public Expression visit( Expression expr);\n}\n", "raw_body_no_cmt": "public class ExpressionPrinter extends SaxonExprVisitor {\n private int depth=0;\n private void print( String s);\n public Expression visit( AxisExpression e);\n public Expression visit( RootExpression e);\n public Expression visit( VennExpression e);\n public Expression visit( Expression expr);\n}\n"}}, {"CPDReport": {"retrieved_name": "CPDReport", "raw_body": "/** \n * The result of a CPD analysis. This is rendered by a {@link CPDReportRenderer}.\n * @since 6.48.0\n */\npublic class CPDReport {\n private final SourceManager sourceManager;\n private final List<Match> matches;\n private final Map<FileId,Integer> numberOfTokensPerFile;\n CPDReport( SourceManager sourceManager, List<Match> matches, Map<FileId,Integer> numberOfTokensPerFile);\n /** \n * Return the list of duplication matches found by the CPD analysis. \n */\n public List<Match> getMatches();\n /** \n * Return a map containing the number of tokens by processed file. \n */\n public Map<FileId,Integer> getNumberOfTokensPerFile();\n /** \n * Return the slice of source code where the mark was found. This returns the entire lines from the start to the end line of the mark.\n */\n public Chars getSourceCodeSlice( Mark mark);\n /** \n * Creates a new CPD report taking all the information from this report, but filtering the matches. Note that the {@linkplain #getNumberOfTokensPerFile() token count map}is not filtered.\n * @param filter when true, the match will be kept.\n * @return copy of this report\n */\n public CPDReport filterMatches( Predicate<Match> filter);\n /** \n * Return the display name of the given file.\n */\n public String getDisplayName( FileId fileId);\n}\n", "raw_body_no_cmt": "public class CPDReport {\n private final SourceManager sourceManager;\n private final List<Match> matches;\n private final Map<FileId,Integer> numberOfTokensPerFile;\n CPDReport( SourceManager sourceManager, List<Match> matches, Map<FileId,Integer> numberOfTokensPerFile);\n public List<Match> getMatches();\n public Map<FileId,Integer> getNumberOfTokensPerFile();\n public Chars getSourceCodeSlice( Mark mark);\n public CPDReport filterMatches( Predicate<Match> filter);\n public String getDisplayName( FileId fileId);\n}\n"}}] | [{"getFilePath": {"retrieved_name": "getFileName", "raw_body": "/** \n * Return the simple file name, like {@link Path#getFileName()}. This includes the extension.\n */\nString getFileName();\n"}}, {"getTokenCount": {"retrieved_name": "getTokenCount", "raw_body": "public int getTokenCount(){\n return this.tokenCount;\n}\n"}}, {"getTokenOffset": {"retrieved_name": "getTokenCount", "raw_body": "public int getTokenCount(){\n return this.tokenCount;\n}\n"}}, {"getTokenLineOffset": {"retrieved_name": "getLineOffsets", "raw_body": "int[] getLineOffsets(){\n return lineOffsets;\n}\n"}}, {"getLineOffset": {"retrieved_name": "getLineOffsets", "raw_body": "int[] getLineOffsets(){\n return lineOffsets;\n}\n"}}, {"getLine": {"retrieved_name": "getLine", "raw_body": "/** \n * Retrieves the requested line from the specified file.\n * @param sourceFile the java or cpp source file\n * @param line line number to extract\n * @return a trimmed line of source code\n */\nprivate String getLine(String sourceFile,int line){\n String code=null;\n try (BufferedReader br=new BufferedReader(getReader(sourceFile))){\n for (int i=0; line > i; i++) {\n String txt=br.readLine();\n code=txt == null ? \"\" : txt.trim();\n }\n }\n catch ( IOException ioErr) {\n ioErr.printStackTrace();\n }\n return code;\n}\n"}}, {"getTokenLine": {"retrieved_name": "getTokenImage", "raw_body": "/** \n * Returns a string made up of characters from the token mark up to to the current buffer position.\n */\npublic String getTokenImage(){\n return getTokenImageCs().toString();\n}\n"}}, {"println": {"retrieved_name": "println", "raw_body": "@Override public void println(String x){\n buffer.append(x).append(System.lineSeparator());\n}\n"}}, {"getTokenLineCount": {"retrieved_name": "getLineCount", "raw_body": "public int getLineCount(){\n return getMark(0).getLocation().getLineCount();\n}\n"}}, {"getTokens": {"retrieved_name": "getTokens", "raw_body": "protected List<TerminalNode> getTokens(int kind){\n return children(BaseAntlrTerminalNode.class).filter(it -> it.getTokenKind() == kind).toList(BaseAntlrTerminalNode::asAntlrNode);\n}\n"}}, {"getTokenLength": {"retrieved_name": "getLength", "raw_body": "/** \n * Returns the length of the region in characters. This is the difference between start offset and end offset. All characters have length 1, including {@code '\\t'}. The sequence {@code \"\\r\\n\"} has length 2 andnot 1.\n */\npublic int getLength(){\n return length;\n}\n"}}, {"getLineCount": {"retrieved_name": "getLineCount", "raw_body": "public int getLineCount(){\n return getMark(0).getLocation().getLineCount();\n}\n"}}] | [{"renderOn": {"retrieved_name": "renderOn", "raw_body": "private void renderOn(CPDReport report,PrintWriter writer,Match match) throws IOException {\n writer.append(\"Found a \").append(String.valueOf(match.getLineCount())).append(\" line (\").append(String.valueOf(match.getTokenCount())).append(\" tokens) duplication in the following files: \").println();\n for ( Mark mark : match) {\n FileLocation loc=mark.getLocation();\n writer.append(\"Starting at line \").append(String.valueOf(loc.getStartLine())).append(\" of \").append(report.getDisplayName(loc.getFileId())).println();\n }\n writer.println();\n Chars source=report.getSourceCodeSlice(match.getFirstMark());\n if (trimLeadingWhitespace) {\n for ( Chars line : StringUtil.linesWithTrimIndent(source)) {\n line.writeFully(writer);\n writer.println();\n }\n return;\n }\n source.writeFully(writer);\n writer.println();\n}\n"}}] |
|
orientechnologies_orientdb | orientdb/server/src/main/java/com/orientechnologies/orient/server/security/OSelfSignedCertificate.java | OSelfSignedCertificate | composeSelfSignedCertificate | class OSelfSignedCertificate {
public static final String DEFAULT_CERTIFICATE_ALGORITHM = "RSA";
public static final int DEFAULT_CERTIFICATE_KEY_SIZE = 2048;
public static final int DEFAULT_CERTIFICATE_VALIDITY = 365;
public static final String DEFAULT_CERTIFICATE_OWNER =
"CN=SelfSigenedOrientDBtestOnly, OU=SAP HANA Core, O=SAP SE, L=Walldorf, C=DE";
public static final String DEFAULT_CERTIFICATE_NAME = "ssl";
private String algorithm;
private int key_size;
private int validity;
private KeyPair keyPair = null;
private X509Certificate certificate = null;
private String certificateName;
private BigInteger certificateSN;
private String ownerFDN;
public OSelfSignedCertificate() {
this.certificateSN = computeRandomSerialNumber();
}
public String getAlgorithm() {
return algorithm;
}
public void setAlgorithm(String algorithm) {
if ((algorithm == null) || (algorithm.isEmpty())) {
this.algorithm = DEFAULT_CERTIFICATE_ALGORITHM;
} else {
this.algorithm = algorithm;
}
}
public int getKey_size() {
return key_size;
}
public void setKey_size(int key_size) {
if (key_size >= 128) {
this.key_size = key_size;
} else {
this.key_size = DEFAULT_CERTIFICATE_KEY_SIZE;
}
}
public void setValidity(int validity) {
this.validity = validity;
}
public String getCertificateName() {
return certificateName;
}
public void setCertificateName(String certificateName) {
this.certificateName = certificateName;
}
public void setCertificateSN(long certificateSN) throws SwitchToDefaultParamsException {
if (certificateSN <= 11) {
BigInteger sn = computeRandomSerialNumber();
this.certificateSN = sn;
throw new SwitchToDefaultParamsException(
"the value "
+ certificateSN
+ " culd not be used as a Certificate Serial Nuber, the value will be set to:"
+ sn);
} else {
this.certificateSN = BigInteger.valueOf(certificateSN);
}
}
public static BigInteger computeRandomSerialNumber() {
SecureRandom sr = new SecureRandom();
return BigInteger.valueOf(sr.nextLong());
}
public void setOwnerFDN(String ownerFDN) {
this.ownerFDN = ownerFDN;
}
/**
* Generate and Return a key pair.
*
* <p>If this KeyPairGenerator has not been initialized explicitly, provider-specific defaults
* will be used for the size and other (algorithm-specific) values of the generated keys.Our
* People
*
* <p>This method will computes and returns a new key pair every time it is called.
*
* @return a new key pair
* @throws NoSuchAlgorithmException if the algorithm String not match with the supported key
* generation schemes.
*/
public static KeyPair computeKeyPair(String algorithm, int keySize)
throws NoSuchAlgorithmException {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(algorithm);
keyPairGenerator.initialize(keySize, new SecureRandom());
return keyPairGenerator.generateKeyPair();
}
/**
* recompute a new key pair FOR INTERNAL OSelfSignedCertificate class USE.
*
* <p>This method is functionally equivalent to {@link #computeKeyPair
* computeKeyPair(this.algorithm,this.key_size)}. It uses the value pair
* (DEFAULT_CERTIFICATE_ALGORITHM,DEFAULT_CERTIFICATE_KEY_SIZE) if the setted fields are not
* valid.
*
* @throws NoSuchAlgorithmException if the algorithm String not match with the supported key
* generation schemes.
*/
public void generateCertificateKeyPair()
throws NoSuchAlgorithmException, SwitchToDefaultParamsException {
try {
this.keyPair = computeKeyPair(this.algorithm, this.key_size);
} catch (NoSuchAlgorithmException e) {
this.keyPair = computeKeyPair(DEFAULT_CERTIFICATE_ALGORITHM, DEFAULT_CERTIFICATE_KEY_SIZE);
SwitchToDefaultParamsException tmpe = new SwitchToDefaultParamsException();
tmpe.addSuppressed(e);
throw tmpe;
}
}
public PublicKey getPublicKey() {
if (keyPair == null) {
throw new NullPointerException("generate the Key Pair");
}
return keyPair.getPublic();
}
public void composeSelfSignedCertificate() {<FILL_FUNCTION_BODY>}
public static X509Certificate generateSelfSignedCertificate(
KeyPair keypair, int validity, String ownerFDN, BigInteger certSN)
throws CertificateException, IOException, NoSuchAlgorithmException {
X500Name owner;
owner = new X500Name(ownerFDN);
Date from, to;
Calendar c = Calendar.getInstance();
c.add(Calendar.DAY_OF_YEAR, 0);
from = c.getTime();
c.add(Calendar.DAY_OF_YEAR, validity);
to = c.getTime();
var certBuilder =
new X509v3CertificateBuilder(
owner,
certSN,
from,
to,
owner,
SubjectPublicKeyInfo.getInstance(keypair.getPublic().getEncoded()));
try {
var certHolder =
certBuilder.build(
new JcaContentSignerBuilder("SHA256WithRSA").build(keypair.getPrivate()));
return new JcaX509CertificateConverter().getCertificate(certHolder);
} catch (OperatorCreationException e) {
throw new RuntimeException(e);
}
}
public X509Certificate getCertificate() throws CertificateException {
if (this.certificate == null) {
throw new CertificateException(
"The Self-Signed Certificate han not been genetated! "
+ "You have to invoke the composeSelfSignedCertificate() before get it.");
}
return this.certificate;
}
public static void checkCertificate(X509Certificate cert, PublicKey publicKey, Date date)
throws NoSuchProviderException,
CertificateException,
NoSuchAlgorithmException,
InvalidKeyException,
SignatureException {
cert.checkValidity(date);
cert.verify(publicKey);
}
public void checkThisCertificate()
throws NoSuchAlgorithmException,
CertificateException,
NoSuchProviderException,
InvalidKeyException,
SignatureException {
checkCertificate(
this.certificate, this.keyPair.getPublic(), new Date(System.currentTimeMillis()));
}
public PrivateKey getPrivateKey() {
return this.keyPair.getPrivate();
}
} |
try {
this.certificate =
generateSelfSignedCertificate(
this.keyPair, this.validity, this.ownerFDN, this.certificateSN);
} catch (CertificateException | IOException | NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
|
try {
this.certificate =
generateSelfSignedCertificate(
this.keyPair,
this.validity,
this.ownerFDN,
this.certificateSN,
this.certificateName);
} catch (CertificateException
| IOException
| NoSuchAlgorithmException
| OperatorCreationException e) {
throw new RuntimeException(e);
}
| [
"X509Certificate",
"OperatorCreationException",
"KeyPair"
] | [] | [
"KeyPair",
"OperatorCreationException",
"X509Certificate"
] | [] | {
"methods": [],
"similar_methods": [
"composeSelfSignedCertificate"
],
"types": [
"X509Certificate",
"OperatorCreationException",
"KeyPair"
]
} | public class OSelfSignedCertificateTest extends TestCase {
OSelfSignedCertificate testInstance;
@Before public void setUp() throws Exception;
@Test public void testSetUnsuitableSerialNumber() throws Exception;
@Test public void testGenerateCertificateKeyPair() throws Exception;
@Test public void testComposeSelfSignedCertificate() throws Exception;
@Test public void testCheckValidityPerid() throws Exception;
@Test public void testCertificateSignatureAgainstTamperPublicKey() throws Exception;
}
/**
* A non idempotent operation has been executed against a read only server (REPLICA).
* @author Luca Garulli (l.garulli--at--orientdb.com)
*/
public class OWriteOperationNotPermittedException extends ODistributedException {
public OWriteOperationNotPermittedException( OWriteOperationNotPermittedException exception);
public OWriteOperationNotPermittedException( String s);
}
/**
* Container for pair of non null objects.
* @author Anrey Lomakin
* @since 2.2
*/
public class ORawPair<V1,V2> {
public final V1 first;
public final V2 second;
public ORawPair( V1 first, V2 second);
public V1 getFirst();
public V2 getSecond();
@Override public boolean equals( Object o);
@Override public int hashCode();
}
@Test public void testComposeSelfSignedCertificate() throws Exception {
testInstance.generateCertificateKeyPair();
testInstance.composeSelfSignedCertificate();
testInstance.checkThisCertificate();
}
| public class OSelfSignedCertificateTest extends TestCase {
OSelfSignedCertificate testInstance;
public void setUp() throws Exception;
public void testSetUnsuitableSerialNumber() throws Exception;
public void testGenerateCertificateKeyPair() throws Exception;
public void testComposeSelfSignedCertificate() throws Exception;
public void testCheckValidityPerid() throws Exception;
public void testCertificateSignatureAgainstTamperPublicKey() throws Exception;
}
public class OWriteOperationNotPermittedException extends ODistributedException {
public OWriteOperationNotPermittedException( OWriteOperationNotPermittedException exception);
public OWriteOperationNotPermittedException( String s);
}
public class ORawPair<V1,V2> {
public final V1 first;
public final V2 second;
public ORawPair( V1 first, V2 second);
public V1 getFirst();
public V2 getSecond();
public boolean equals( Object o);
public int hashCode();
}
@Test public void testComposeSelfSignedCertificate() throws Exception {
testInstance.generateCertificateKeyPair();
testInstance.composeSelfSignedCertificate();
testInstance.checkThisCertificate();
}
| {"types": [{"X509Certificate": "OSelfSignedCertificateTest"}, {"OperatorCreationException": "OWriteOperationNotPermittedException"}, {"KeyPair": "ORawPair"}], "similar_methods": [{"composeSelfSignedCertificate": "testComposeSelfSignedCertificate"}]} | [{"X509Certificate": {"retrieved_name": "OSelfSignedCertificateTest", "raw_body": "public class OSelfSignedCertificateTest extends TestCase {\n OSelfSignedCertificate testInstance;\n @Before public void setUp() throws Exception;\n @Test public void testSetUnsuitableSerialNumber() throws Exception;\n @Test public void testGenerateCertificateKeyPair() throws Exception;\n @Test public void testComposeSelfSignedCertificate() throws Exception;\n @Test public void testCheckValidityPerid() throws Exception;\n @Test public void testCertificateSignatureAgainstTamperPublicKey() throws Exception;\n}\n", "raw_body_no_cmt": "public class OSelfSignedCertificateTest extends TestCase {\n OSelfSignedCertificate testInstance;\n public void setUp() throws Exception;\n public void testSetUnsuitableSerialNumber() throws Exception;\n public void testGenerateCertificateKeyPair() throws Exception;\n public void testComposeSelfSignedCertificate() throws Exception;\n public void testCheckValidityPerid() throws Exception;\n public void testCertificateSignatureAgainstTamperPublicKey() throws Exception;\n}\n"}}, {"OperatorCreationException": {"retrieved_name": "OWriteOperationNotPermittedException", "raw_body": "/** \n * A non idempotent operation has been executed against a read only server (REPLICA).\n * @author Luca Garulli (l.garulli--at--orientdb.com)\n */\npublic class OWriteOperationNotPermittedException extends ODistributedException {\n public OWriteOperationNotPermittedException( OWriteOperationNotPermittedException exception);\n public OWriteOperationNotPermittedException( String s);\n}\n", "raw_body_no_cmt": "public class OWriteOperationNotPermittedException extends ODistributedException {\n public OWriteOperationNotPermittedException( OWriteOperationNotPermittedException exception);\n public OWriteOperationNotPermittedException( String s);\n}\n"}}, {"KeyPair": {"retrieved_name": "ORawPair", "raw_body": "/** \n * Container for pair of non null objects.\n * @author Anrey Lomakin\n * @since 2.2\n */\npublic class ORawPair<V1,V2> {\n public final V1 first;\n public final V2 second;\n public ORawPair( V1 first, V2 second);\n public V1 getFirst();\n public V2 getSecond();\n @Override public boolean equals( Object o);\n @Override public int hashCode();\n}\n", "raw_body_no_cmt": "public class ORawPair<V1,V2> {\n public final V1 first;\n public final V2 second;\n public ORawPair( V1 first, V2 second);\n public V1 getFirst();\n public V2 getSecond();\n public boolean equals( Object o);\n public int hashCode();\n}\n"}}] | [] | [{"composeSelfSignedCertificate": {"retrieved_name": "testComposeSelfSignedCertificate", "raw_body": "@Test public void testComposeSelfSignedCertificate() throws Exception {\n testInstance.generateCertificateKeyPair();\n testInstance.composeSelfSignedCertificate();\n testInstance.checkThisCertificate();\n}\n"}}] |
|
orientechnologies_orientdb | orientdb/server/src/main/java/com/orientechnologies/orient/server/distributed/operation/NodeOperationTask.java | NodeOperationFactory | createOperationResponse | class NodeOperationFactory {
private Callable<NodeOperation> request;
private Callable<NodeOperationResponse> response;
public NodeOperationFactory(
Callable<NodeOperation> request, Callable<NodeOperationResponse> response) {
this.request = request;
this.response = response;
}
}
public static void register(
int messageId,
Callable<NodeOperation> requestFactory,
Callable<NodeOperationResponse> responseFactory) {
MESSAGES.put(messageId, new NodeOperationFactory(requestFactory, responseFactory));
}
public static NodeOperationResponse createOperationResponse(int messageId) {<FILL_FUNCTION_BODY> |
NodeOperationFactory factory = MESSAGES.get(messageId);
if (factory != null) {
try {
return factory.response.call();
} catch (Exception e) {
OLogManager.instance()
.warn(null, "Cannot create node operation response from id %d", messageId);
return null;
}
} else {
return null;
}
|
NodeOperationFactory factory = MESSAGES.get(messageId);
if (factory == null) {
throw new IllegalArgumentException("Unknown message id: " + messageId);
}
try {
return factory.response.call();
} catch (Exception e) {
throw new RuntimeException(e);
}
| [
"NodeOperationFactory",
"Exception",
"Map<Integer,NodeOperationFactory>",
"Callable<NodeOperationResponse>"
] | [
"warn",
"instance",
"call",
"get"
] | [
"Callable<NodeOperationResponse>",
"Exception",
"Map<Integer,NodeOperationFactory>",
"NodeOperationFactory"
] | [
"instance",
"call",
"warn",
"get"
] | {
"methods": [
"warn",
"instance",
"call",
"get"
],
"similar_methods": [
"createOperationResponse"
],
"types": [
"NodeOperationFactory",
"Exception",
"Map<Integer,NodeOperationFactory>",
"Callable<NodeOperationResponse>"
]
} | public interface NodeOperation {
NodeOperationResponse execute( OServer iServer, ODistributedServerManager iManager);
void write( DataOutput out) throws IOException ;
void read( DataInput in) throws IOException ;
int getMessageId();
}
/**
* This exception is thrown when parse errors are encountered. You can explicitly create objects of this exception type by calling the method generateParseException in the generated parser. <p>You can modify this class to customize your error reporting mechanisms so long as you retain the public fields.
*/
public class ParseException extends Exception {
/**
* The version identifier for this Serializable class. Increment only if the <i>serialized</i> form of the class changes.
*/
private static final long serialVersionUID=1L;
/**
* This constructor is used by the method "generateParseException" in the generated parser. Calling this constructor generates a new object of this type with the fields "currentToken", "expectedTokenSequences", and "tokenImage" set.
*/
public ParseException( Token currentTokenVal, int[][] expectedTokenSequencesVal, String[] tokenImageVal);
/**
* The following constructors are for use by you for whatever purpose you can think of. Constructing the exception in this manner makes the exception behave in the normal way - i.e., as documented in the class "Throwable". The fields "errorToken", "expectedTokenSequences", and "tokenImage" do not contain relevant information. The JavaCC generated code does not use these constructors.
*/
public ParseException();
/**
* Constructor with message.
*/
public ParseException( String message);
/**
* This is the last token that has been consumed successfully. If this object has been created due to a parse error, the token followng this token will (therefore) be the first error token.
*/
public Token currentToken;
/**
* Each entry in this array is an array of integers. Each array of integers represents a sequence of tokens (by their ordinal values) that is expected at this point of the parse.
*/
public int[][] expectedTokenSequences;
/**
* This is a reference to the "tokenImage" array of the generated parser within which the parse error occurred. This array is defined in the generated ...Constants interface.
*/
public String[] tokenImage;
/**
* It uses "currentToken" and "expectedTokenSequences" to generate a parse error message and returns it. If this object has been created due to a parse error, and you do not catch it (it gets thrown from the parser) the correct error message gets displayed.
*/
private static String initialise( Token currentToken, int[][] expectedTokenSequences, String[] tokenImage);
/**
* The end of line string for this machine.
*/
protected String eol=System.getProperty("line.separator","\n");
/**
* Used to convert raw characters to their escaped version when these raw version cannot be used as part of an ASCII string literal.
*/
static String add_escapes( String str);
}
public interface NodeOperationResponse {
void write( DataOutput out) throws IOException ;
void read( DataInput in) throws IOException ;
default boolean isOk();
}
public void warn(final Object iRequester,final String iMessage,final Throwable iException,final Object... iAdditionalArgs){
if (isWarnEnabled()) log(iRequester,Level.WARNING,iMessage,iException,true,null,iAdditionalArgs);
}
public static ONative instance(){
if (instance != null) return instance;
initLock.lock();
try {
if (instance != null) return instance;
if (OIOUtils.isOsLinux()) {
posix=POSIXFactory.getPOSIX();
}
instance=new ONative();
}
finally {
initLock.unlock();
}
return instance;
}
public Boolean call(ODatabaseDocumentInternal database){
return myEntryIterator.hasNext();
}
public Object get(ATTRIBUTES iAttribute){
return database.get(iAttribute);
}
@Override public OExperimentalResponse createResponse(){
return new OExperimentalResponse(request.createResponse());
}
| public interface NodeOperation {
NodeOperationResponse execute( OServer iServer, ODistributedServerManager iManager);
void write( DataOutput out) throws IOException ;
void read( DataInput in) throws IOException ;
int getMessageId();
}
public class ParseException extends Exception {
private static final long serialVersionUID=1L;
public ParseException( Token currentTokenVal, int[][] expectedTokenSequencesVal, String[] tokenImageVal);
public ParseException();
public ParseException( String message);
public Token currentToken;
public int[][] expectedTokenSequences;
public String[] tokenImage;
private static String initialise( Token currentToken, int[][] expectedTokenSequences, String[] tokenImage);
protected String eol=System.getProperty("line.separator","\n");
static String add_escapes( String str);
}
public interface NodeOperationResponse {
void write( DataOutput out) throws IOException ;
void read( DataInput in) throws IOException ;
default boolean isOk();
}
public void warn(final Object iRequester,final String iMessage,final Throwable iException,final Object... iAdditionalArgs){
if (isWarnEnabled()) log(iRequester,Level.WARNING,iMessage,iException,true,null,iAdditionalArgs);
}
public static ONative instance(){
if (instance != null) return instance;
initLock.lock();
try {
if (instance != null) return instance;
if (OIOUtils.isOsLinux()) {
posix=POSIXFactory.getPOSIX();
}
instance=new ONative();
}
finally {
initLock.unlock();
}
return instance;
}
public Boolean call(ODatabaseDocumentInternal database){
return myEntryIterator.hasNext();
}
public Object get(ATTRIBUTES iAttribute){
return database.get(iAttribute);
}
@Override public OExperimentalResponse createResponse(){
return new OExperimentalResponse(request.createResponse());
}
| {"types": [{"NodeOperationFactory": "NodeOperation"}, {"Exception": "ParseException"}, {"Map<Integer,NodeOperationFactory>": "NodeOperation"}, {"Callable<NodeOperationResponse>": "NodeOperationResponse"}], "methods": [{"warn": "warn"}, {"instance": "instance"}, {"call": "call"}, {"get": "get"}], "similar_methods": [{"createOperationResponse": "createResponse"}]} | [{"NodeOperationFactory": {"retrieved_name": "NodeOperation", "raw_body": "public interface NodeOperation {\n NodeOperationResponse execute( OServer iServer, ODistributedServerManager iManager);\n void write( DataOutput out) throws IOException ;\n void read( DataInput in) throws IOException ;\n int getMessageId();\n}\n", "raw_body_no_cmt": "public interface NodeOperation {\n NodeOperationResponse execute( OServer iServer, ODistributedServerManager iManager);\n void write( DataOutput out) throws IOException ;\n void read( DataInput in) throws IOException ;\n int getMessageId();\n}\n"}}, {"Exception": {"retrieved_name": "ParseException", "raw_body": "/** \n * This exception is thrown when parse errors are encountered. You can explicitly create objects of this exception type by calling the method generateParseException in the generated parser. <p>You can modify this class to customize your error reporting mechanisms so long as you retain the public fields.\n */\npublic class ParseException extends Exception {\n /** \n * The version identifier for this Serializable class. Increment only if the <i>serialized</i> form of the class changes.\n */\n private static final long serialVersionUID=1L;\n /** \n * This constructor is used by the method \"generateParseException\" in the generated parser. Calling this constructor generates a new object of this type with the fields \"currentToken\", \"expectedTokenSequences\", and \"tokenImage\" set.\n */\n public ParseException( Token currentTokenVal, int[][] expectedTokenSequencesVal, String[] tokenImageVal);\n /** \n * The following constructors are for use by you for whatever purpose you can think of. Constructing the exception in this manner makes the exception behave in the normal way - i.e., as documented in the class \"Throwable\". The fields \"errorToken\", \"expectedTokenSequences\", and \"tokenImage\" do not contain relevant information. The JavaCC generated code does not use these constructors.\n */\n public ParseException();\n /** \n * Constructor with message. \n */\n public ParseException( String message);\n /** \n * This is the last token that has been consumed successfully. If this object has been created due to a parse error, the token followng this token will (therefore) be the first error token.\n */\n public Token currentToken;\n /** \n * Each entry in this array is an array of integers. Each array of integers represents a sequence of tokens (by their ordinal values) that is expected at this point of the parse.\n */\n public int[][] expectedTokenSequences;\n /** \n * This is a reference to the \"tokenImage\" array of the generated parser within which the parse error occurred. This array is defined in the generated ...Constants interface.\n */\n public String[] tokenImage;\n /** \n * It uses \"currentToken\" and \"expectedTokenSequences\" to generate a parse error message and returns it. If this object has been created due to a parse error, and you do not catch it (it gets thrown from the parser) the correct error message gets displayed.\n */\n private static String initialise( Token currentToken, int[][] expectedTokenSequences, String[] tokenImage);\n /** \n * The end of line string for this machine. \n */\n protected String eol=System.getProperty(\"line.separator\",\"\\n\");\n /** \n * Used to convert raw characters to their escaped version when these raw version cannot be used as part of an ASCII string literal.\n */\n static String add_escapes( String str);\n}\n", "raw_body_no_cmt": "public class ParseException extends Exception {\n private static final long serialVersionUID=1L;\n public ParseException( Token currentTokenVal, int[][] expectedTokenSequencesVal, String[] tokenImageVal);\n public ParseException();\n public ParseException( String message);\n public Token currentToken;\n public int[][] expectedTokenSequences;\n public String[] tokenImage;\n private static String initialise( Token currentToken, int[][] expectedTokenSequences, String[] tokenImage);\n protected String eol=System.getProperty(\"line.separator\",\"\\n\");\n static String add_escapes( String str);\n}\n"}}, {"Callable<NodeOperationResponse>": {"retrieved_name": "NodeOperationResponse", "raw_body": "public interface NodeOperationResponse {\n void write( DataOutput out) throws IOException ;\n void read( DataInput in) throws IOException ;\n default boolean isOk();\n}\n", "raw_body_no_cmt": "public interface NodeOperationResponse {\n void write( DataOutput out) throws IOException ;\n void read( DataInput in) throws IOException ;\n default boolean isOk();\n}\n"}}] | [{"warn": {"retrieved_name": "warn", "raw_body": "public void warn(final Object iRequester,final String iMessage,final Throwable iException,final Object... iAdditionalArgs){\n if (isWarnEnabled()) log(iRequester,Level.WARNING,iMessage,iException,true,null,iAdditionalArgs);\n}\n"}}, {"instance": {"retrieved_name": "instance", "raw_body": "public static ONative instance(){\n if (instance != null) return instance;\n initLock.lock();\n try {\n if (instance != null) return instance;\n if (OIOUtils.isOsLinux()) {\n posix=POSIXFactory.getPOSIX();\n }\n instance=new ONative();\n }\n finally {\n initLock.unlock();\n }\n return instance;\n}\n"}}, {"call": {"retrieved_name": "call", "raw_body": "public Boolean call(ODatabaseDocumentInternal database){\n return myEntryIterator.hasNext();\n}\n"}}, {"get": {"retrieved_name": "get", "raw_body": "public Object get(ATTRIBUTES iAttribute){\n return database.get(iAttribute);\n}\n"}}] | [{"createOperationResponse": {"retrieved_name": "createResponse", "raw_body": "@Override public OExperimentalResponse createResponse(){\n return new OExperimentalResponse(request.createResponse());\n}\n"}}] |
|
jeecgboot_jeecg-boot | jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/cas/util/CasServiceUtil.java | CasServiceUtil | createHttpClientWithNoSsl | class CasServiceUtil {
public static void main(String[] args) {
String serviceUrl = "https://cas.8f8.com.cn:8443/cas/p3/serviceValidate";
String service = "http://localhost:3003/user/login";
String ticket = "ST-5-1g-9cNES6KXNRwq-GuRET103sm0-DESKTOP-VKLS8B3";
String res = getStValidate(serviceUrl,ticket, service);
System.out.println("---------res-----"+res);
}
/**
* 验证ST
*/
public static String getStValidate(String url, String st, String service){
try {
url = url+"?service="+service+"&ticket="+st;
CloseableHttpClient httpclient = createHttpClientWithNoSsl();
HttpGet httpget = new HttpGet(url);
HttpResponse response = httpclient.execute(httpget);
String res = readResponse(response);
return res == null ? null : (res == "" ? null : res);
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
/**
* 读取 response body 内容为字符串
*
* @param response
* @return
* @throws IOException
*/
private static String readResponse(HttpResponse response) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String result = new String();
String line;
while ((line = in.readLine()) != null) {
result += line;
}
return result;
}
/**
* 创建模拟客户端(针对 https 客户端禁用 SSL 验证)
*
* @param cookieStore 缓存的 Cookies 信息
* @return
* @throws Exception
*/
private static CloseableHttpClient createHttpClientWithNoSsl() throws Exception {<FILL_FUNCTION_BODY>}
} |
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkClientTrusted(X509Certificate[] certs, String authType) {
// don't check
}
@Override
public void checkServerTrusted(X509Certificate[] certs, String authType) {
// don't check
}
}
};
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, trustAllCerts, null);
LayeredConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(ctx);
return HttpClients.custom()
.setSSLSocketFactory(sslSocketFactory)
.build();
|
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
| [
"SSLConnectionSocketFactory",
"SSLContext"
] | [
"loadTrustMaterial",
"build",
"setSSLSocketFactory",
"custom"
] | [
"X509Certificate[]",
"LayeredConnectionSocketFactory",
"SSLContext",
"TrustManager[]"
] | [
"init",
"setSSLSocketFactory",
"build",
"custom",
"getInstance"
] | {
"methods": [
"loadTrustMaterial",
"build",
"setSSLSocketFactory",
"custom"
],
"similar_methods": [
"createHttpClientWithNoSsl"
],
"types": [
"SSLConnectionSocketFactory",
"SSLContext"
]
} | /**
* @Description : WebSocketConfig
* @author : jeecg-boot
*/
@Configuration public class WebSocketConfig {
/**
* 注入ServerEndpointExporter, 这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint
*/
@Bean public ServerEndpointExporter serverEndpointExporter();
@Bean public WebsocketFilter websocketFilter();
@Bean public FilterRegistrationBean getFilterRegistrationBean();
}
/**
* @author : zyf
* @date : 20210715
*/
@Configuration public class SentinelFilterContextConfig {
@Bean public FilterRegistrationBean sentinelFilterRegistration();
}
/**
* 加载一级节点/如果是同步 则所有数据
*/
@RequestMapping(value="/loadTreeRoot",method=RequestMethod.GET) public Result<List<TreeSelectModel>> loadTreeRoot(@RequestParam(name="async") Boolean async,@RequestParam(name="pcode") String pcode){
Result<List<TreeSelectModel>> result=new Result<List<TreeSelectModel>>();
try {
List<TreeSelectModel> ls=this.sysCategoryService.queryListByCode(pcode);
if (!async) {
loadAllCategoryChildren(ls);
}
result.setResult(ls);
result.setSuccess(true);
}
catch ( Exception e) {
e.printStackTrace();
result.setMessage(e.getMessage());
result.setSuccess(false);
}
return result;
}
/**
* @param source (源滤波器)指定返回的字段,传null返回所有字段
* @param query
* @param from 从第几条数据开始
* @param size 返回条目数
* @return { "query": query }
*/
public JSONObject buildQuery(List<String> source,JSONObject query,int from,int size){
JSONObject json=new JSONObject();
if (source != null) {
json.put("_source",source);
}
json.put("query",query);
json.put("from",from);
json.put("size",size);
return json;
}
public void setSucCount(int sucCount){
this.sucCount=sucCount;
}
/**
* 发送请求
*/
public static ResponseEntity<JSONObject> request(String url,HttpMethod method,JSONObject variables,JSONObject params){
return request(url,method,getHeaderApplicationJson(),variables,params,JSONObject.class);
}
@Override public SysUser createUser(String phone,String thirdUserUuid,Integer tenantId){
LambdaQueryWrapper<SysThirdAccount> query=new LambdaQueryWrapper<>();
query.eq(SysThirdAccount::getThirdUserUuid,thirdUserUuid);
query.eq(SysThirdAccount::getTenantId,tenantId);
SysThirdAccount account=sysThirdAccountMapper.selectOne(query);
SysUser userByName=sysUserMapper.getUserByName(thirdUserUuid);
if (null != userByName) {
String format=DateUtils.yyyymmddhhmmss.get().format(new Date());
thirdUserUuid=thirdUserUuid + format;
}
SysUser user=new SysUser();
user.setActivitiSync(CommonConstant.ACT_SYNC_1);
user.setDelFlag(CommonConstant.DEL_FLAG_0);
user.setStatus(1);
user.setUsername(thirdUserUuid);
user.setPhone(phone);
String salt=oConvertUtils.randomGen(8);
user.setSalt(salt);
String passwordEncode=PasswordUtil.encrypt(user.getUsername(),"123456",salt);
user.setPassword(passwordEncode);
user.setRealname(account.getRealname());
user.setAvatar(account.getAvatar());
String s=this.saveThirdUser(user);
SysThirdAccount sysThirdAccount=new SysThirdAccount();
sysThirdAccount.setSysUserId(s);
sysThirdAccount.setTenantId(tenantId);
sysThirdAccountMapper.update(sysThirdAccount,query);
return user;
}
| public class WebSocketConfig {
public ServerEndpointExporter serverEndpointExporter();
public WebsocketFilter websocketFilter();
public FilterRegistrationBean getFilterRegistrationBean();
}
public class SentinelFilterContextConfig {
public FilterRegistrationBean sentinelFilterRegistration();
}
/**
* 加载一级节点/如果是同步 则所有数据
*/
@RequestMapping(value="/loadTreeRoot",method=RequestMethod.GET) public Result<List<TreeSelectModel>> loadTreeRoot(@RequestParam(name="async") Boolean async,@RequestParam(name="pcode") String pcode){
Result<List<TreeSelectModel>> result=new Result<List<TreeSelectModel>>();
try {
List<TreeSelectModel> ls=this.sysCategoryService.queryListByCode(pcode);
if (!async) {
loadAllCategoryChildren(ls);
}
result.setResult(ls);
result.setSuccess(true);
}
catch ( Exception e) {
e.printStackTrace();
result.setMessage(e.getMessage());
result.setSuccess(false);
}
return result;
}
/**
* @param source (源滤波器)指定返回的字段,传null返回所有字段
* @param query
* @param from 从第几条数据开始
* @param size 返回条目数
* @return { "query": query }
*/
public JSONObject buildQuery(List<String> source,JSONObject query,int from,int size){
JSONObject json=new JSONObject();
if (source != null) {
json.put("_source",source);
}
json.put("query",query);
json.put("from",from);
json.put("size",size);
return json;
}
public void setSucCount(int sucCount){
this.sucCount=sucCount;
}
/**
* 发送请求
*/
public static ResponseEntity<JSONObject> request(String url,HttpMethod method,JSONObject variables,JSONObject params){
return request(url,method,getHeaderApplicationJson(),variables,params,JSONObject.class);
}
@Override public SysUser createUser(String phone,String thirdUserUuid,Integer tenantId){
LambdaQueryWrapper<SysThirdAccount> query=new LambdaQueryWrapper<>();
query.eq(SysThirdAccount::getThirdUserUuid,thirdUserUuid);
query.eq(SysThirdAccount::getTenantId,tenantId);
SysThirdAccount account=sysThirdAccountMapper.selectOne(query);
SysUser userByName=sysUserMapper.getUserByName(thirdUserUuid);
if (null != userByName) {
String format=DateUtils.yyyymmddhhmmss.get().format(new Date());
thirdUserUuid=thirdUserUuid + format;
}
SysUser user=new SysUser();
user.setActivitiSync(CommonConstant.ACT_SYNC_1);
user.setDelFlag(CommonConstant.DEL_FLAG_0);
user.setStatus(1);
user.setUsername(thirdUserUuid);
user.setPhone(phone);
String salt=oConvertUtils.randomGen(8);
user.setSalt(salt);
String passwordEncode=PasswordUtil.encrypt(user.getUsername(),"123456",salt);
user.setPassword(passwordEncode);
user.setRealname(account.getRealname());
user.setAvatar(account.getAvatar());
String s=this.saveThirdUser(user);
SysThirdAccount sysThirdAccount=new SysThirdAccount();
sysThirdAccount.setSysUserId(s);
sysThirdAccount.setTenantId(tenantId);
sysThirdAccountMapper.update(sysThirdAccount,query);
return user;
}
| {"types": [{"SSLConnectionSocketFactory": "WebSocketConfig"}, {"SSLContext": "SentinelFilterContextConfig"}], "methods": [{"loadTrustMaterial": "loadTreeRoot"}, {"build": "buildQuery"}, {"setSSLSocketFactory": "setSucCount"}, {"custom": "request"}], "similar_methods": [{"createHttpClientWithNoSsl": "createUser"}]} | [{"SSLConnectionSocketFactory": {"retrieved_name": "WebSocketConfig", "raw_body": "/** \n * @Description : WebSocketConfig\n * @author : jeecg-boot\n */\n@Configuration public class WebSocketConfig {\n /** \n * \u6ce8\u5165ServerEndpointExporter\uff0c \u8fd9\u4e2abean\u4f1a\u81ea\u52a8\u6ce8\u518c\u4f7f\u7528\u4e86@ServerEndpoint\u6ce8\u89e3\u58f0\u660e\u7684Websocket endpoint\n */\n @Bean public ServerEndpointExporter serverEndpointExporter();\n @Bean public WebsocketFilter websocketFilter();\n @Bean public FilterRegistrationBean getFilterRegistrationBean();\n}\n", "raw_body_no_cmt": "public class WebSocketConfig {\n public ServerEndpointExporter serverEndpointExporter();\n public WebsocketFilter websocketFilter();\n public FilterRegistrationBean getFilterRegistrationBean();\n}\n"}}, {"SSLContext": {"retrieved_name": "SentinelFilterContextConfig", "raw_body": "/** \n * @author : zyf\n * @date : 20210715\n */\n@Configuration public class SentinelFilterContextConfig {\n @Bean public FilterRegistrationBean sentinelFilterRegistration();\n}\n", "raw_body_no_cmt": "public class SentinelFilterContextConfig {\n public FilterRegistrationBean sentinelFilterRegistration();\n}\n"}}] | [{"loadTrustMaterial": {"retrieved_name": "loadTreeRoot", "raw_body": "/** \n * \u52a0\u8f7d\u4e00\u7ea7\u8282\u70b9/\u5982\u679c\u662f\u540c\u6b65 \u5219\u6240\u6709\u6570\u636e\n */\n@RequestMapping(value=\"/loadTreeRoot\",method=RequestMethod.GET) public Result<List<TreeSelectModel>> loadTreeRoot(@RequestParam(name=\"async\") Boolean async,@RequestParam(name=\"pcode\") String pcode){\n Result<List<TreeSelectModel>> result=new Result<List<TreeSelectModel>>();\n try {\n List<TreeSelectModel> ls=this.sysCategoryService.queryListByCode(pcode);\n if (!async) {\n loadAllCategoryChildren(ls);\n }\n result.setResult(ls);\n result.setSuccess(true);\n }\n catch ( Exception e) {\n e.printStackTrace();\n result.setMessage(e.getMessage());\n result.setSuccess(false);\n }\n return result;\n}\n"}}, {"build": {"retrieved_name": "buildQuery", "raw_body": "/** \n * @param source \uff08\u6e90\u6ee4\u6ce2\u5668\uff09\u6307\u5b9a\u8fd4\u56de\u7684\u5b57\u6bb5\uff0c\u4f20null\u8fd4\u56de\u6240\u6709\u5b57\u6bb5\n * @param query\n * @param from \u4ece\u7b2c\u51e0\u6761\u6570\u636e\u5f00\u59cb\n * @param size \u8fd4\u56de\u6761\u76ee\u6570\n * @return { \"query\": query }\n */\npublic JSONObject buildQuery(List<String> source,JSONObject query,int from,int size){\n JSONObject json=new JSONObject();\n if (source != null) {\n json.put(\"_source\",source);\n }\n json.put(\"query\",query);\n json.put(\"from\",from);\n json.put(\"size\",size);\n return json;\n}\n"}}, {"setSSLSocketFactory": {"retrieved_name": "setSucCount", "raw_body": "public void setSucCount(int sucCount){\n this.sucCount=sucCount;\n}\n"}}, {"custom": {"retrieved_name": "request", "raw_body": "/** \n * \u53d1\u9001\u8bf7\u6c42\n */\npublic static ResponseEntity<JSONObject> request(String url,HttpMethod method,JSONObject variables,JSONObject params){\n return request(url,method,getHeaderApplicationJson(),variables,params,JSONObject.class);\n}\n"}}] | [{"createHttpClientWithNoSsl": {"retrieved_name": "createUser", "raw_body": "@Override public SysUser createUser(String phone,String thirdUserUuid,Integer tenantId){\n LambdaQueryWrapper<SysThirdAccount> query=new LambdaQueryWrapper<>();\n query.eq(SysThirdAccount::getThirdUserUuid,thirdUserUuid);\n query.eq(SysThirdAccount::getTenantId,tenantId);\n SysThirdAccount account=sysThirdAccountMapper.selectOne(query);\n SysUser userByName=sysUserMapper.getUserByName(thirdUserUuid);\n if (null != userByName) {\n String format=DateUtils.yyyymmddhhmmss.get().format(new Date());\n thirdUserUuid=thirdUserUuid + format;\n }\n SysUser user=new SysUser();\n user.setActivitiSync(CommonConstant.ACT_SYNC_1);\n user.setDelFlag(CommonConstant.DEL_FLAG_0);\n user.setStatus(1);\n user.setUsername(thirdUserUuid);\n user.setPhone(phone);\n String salt=oConvertUtils.randomGen(8);\n user.setSalt(salt);\n String passwordEncode=PasswordUtil.encrypt(user.getUsername(),\"123456\",salt);\n user.setPassword(passwordEncode);\n user.setRealname(account.getRealname());\n user.setAvatar(account.getAvatar());\n String s=this.saveThirdUser(user);\n SysThirdAccount sysThirdAccount=new SysThirdAccount();\n sysThirdAccount.setSysUserId(s);\n sysThirdAccount.setTenantId(tenantId);\n sysThirdAccountMapper.update(sysThirdAccount,query);\n return user;\n}\n"}}] |
|
zhkl0228_unidbg | unidbg/unidbg-android/src/main/java/com/github/unidbg/linux/file/DumpFileIO.java | DumpFileIO | write | class DumpFileIO extends BaseAndroidFileIO implements AndroidFileIO {
private final int fd;
public DumpFileIO(int fd) {
super(0);
this.fd = fd;
}
@Override
public int write(byte[] data) {<FILL_FUNCTION_BODY>}
@Override
public void close() {
}
@Override
public FileIO dup2() {
return this;
}
@Override
public int fstat(Emulator<?> emulator, com.github.unidbg.file.linux.StatStructure stat) {
throw new UnsupportedOperationException();
}
@Override
public int getdents64(Pointer dirp, int size) {
throw new UnsupportedOperationException();
}
} |
Inspector.inspect(data, "Dump for fd: " + fd);
return data.length;
| public abstract class BaseAndroidFileIO extends BaseFileIO implements AndroidFileIO {
public BaseAndroidFileIO( int oflags);
@Override public int fstat( Emulator<?> emulator, StatStructure stat);
@Override public int getdents64( Pointer dirp, int size);
@Override public AndroidFileIO accept( Pointer addr, Pointer addrlen);
@Override public int statfs( StatFS statFS);
@Override protected void setFlags( long arg);
}
|
return data.length;
| [] | [] | [] | [
"inspect"
] | {
"methods": [],
"similar_methods": [
"write"
],
"types": []
} | @Override public int write(byte[] data){
try {
if (output == null) {
output=new RandomAccessFile(file,"rw");
output.getChannel().truncate(0);
}
if (debugStream != null) {
debugStream.write(data);
}
if (log.isWarnEnabled()) {
out.write(data);
out.flush();
}
if (callback != null) {
callback.notifyOut(data,err);
}
output.write(data);
return data.length;
}
catch ( IOException e) {
throw new IllegalStateException(e);
}
}
| @Override public int write(byte[] data){
try {
if (output == null) {
output=new RandomAccessFile(file,"rw");
output.getChannel().truncate(0);
}
if (debugStream != null) {
debugStream.write(data);
}
if (log.isWarnEnabled()) {
out.write(data);
out.flush();
}
if (callback != null) {
callback.notifyOut(data,err);
}
output.write(data);
return data.length;
}
catch ( IOException e) {
throw new IllegalStateException(e);
}
}
| {"similar_methods": [{"write": "write"}]} | [] | [] | [{"write": {"retrieved_name": "write", "raw_body": "@Override public int write(byte[] data){\n try {\n if (output == null) {\n output=new RandomAccessFile(file,\"rw\");\n output.getChannel().truncate(0);\n }\n if (debugStream != null) {\n debugStream.write(data);\n }\n if (log.isWarnEnabled()) {\n out.write(data);\n out.flush();\n }\n if (callback != null) {\n callback.notifyOut(data,err);\n }\n output.write(data);\n return data.length;\n }\n catch ( IOException e) {\n throw new IllegalStateException(e);\n }\n}\n"}}] |
jitsi_jitsi | jitsi/modules/service/netaddr/src/main/java/net/java/sip/communicator/impl/netaddr/NetaddrActivator.java | NetaddrActivator | startWithServices | class NetaddrActivator extends DependentActivator
{
/**
* The OSGi bundle context.
*/
private static BundleContext bundleContext = null;
/**
* The network address manager implementation.
*/
private NetworkAddressManagerServiceImpl networkAMS = null;
/**
* The configuration service.
*/
private static ConfigurationService configurationService = null;
/**
* The OSGi <tt>PacketLoggingService</tt> in
* {@link #bundleContext} and used for debugging.
*/
private static PacketLoggingService packetLoggingService = null;
public NetaddrActivator()
{
super(
ConfigurationService.class,
PacketLoggingService.class
);
}
@Override
public void startWithServices(BundleContext bundleContext)
{<FILL_FUNCTION_BODY>}
/**
* Returns a reference to a ConfigurationService implementation currently
* registered in the bundle context or null if no such implementation was
* found.
*
* @return a currently valid implementation of the ConfigurationService.
*/
public static ConfigurationService getConfigurationService()
{
return configurationService;
}
/**
* Returns a reference to the <tt>PacketLoggingService</tt> implementation
* currently registered in the bundle context or null if no such
* implementation was found.
*
* @return a reference to a <tt>PacketLoggingService</tt> implementation
* currently registered in the bundle context or null if no such
* implementation was found.
*/
public static PacketLoggingService getPacketLogging()
{
return packetLoggingService;
}
/**
* Stops the Network Address Manager bundle
*
* @param bundleContext the OSGI bundle context
*
*/
public void stop(BundleContext bundleContext)
{
if(networkAMS != null)
networkAMS.stop();
if (logger.isInfoEnabled())
logger.info("Network Address Manager Service ...[STOPPED]");
configurationService = null;
packetLoggingService = null;
}
/**
* Returns a reference to the bundle context that we were started with.
*
* @return a reference to the BundleContext instance that we were started
* with.
*/
static BundleContext getBundleContext()
{
return bundleContext;
}
} |
NetaddrActivator.bundleContext = bundleContext;
configurationService = getService(ConfigurationService.class);
packetLoggingService = getService(PacketLoggingService.class);
//in here we load static properties that should be else where
//System.setProperty("java.net.preferIPv4Stack", "false");
//System.setProperty("java.net.preferIPv6Addresses", "true");
//end ugly property set
//Create and start the network address manager.
networkAMS =
new NetworkAddressManagerServiceImpl();
// give references to the NetworkAddressManager implementation
networkAMS.start();
if (logger.isInfoEnabled())
logger.info("Network Address Manager ...[ STARTED ]");
bundleContext.registerService(
NetworkAddressManagerService.class.getName(), networkAMS, null);
MetaconfigSettings.Companion.setCacheEnabled(false);
MetaconfigSettings.Companion.setLogger(new MetaconfigLogger()
{
@Override
public void warn(Function0<String> function0)
{
if (logger.isWarnEnabled())
logger.warn(function0.invoke());
}
@Override
public void error(Function0<String> function0)
{
if (logger.isErrorEnabled())
logger.error(function0.invoke());
}
@Override
public void debug(Function0<String> function0)
{
if (logger.isDebugEnabled())
logger.debug(function0.invoke());
}
});
ConfigSource defaults = new TypesafeConfigSource("defaults",
ConfigFactory
.defaultReference(AgentConfig.class.getClassLoader()));
JitsiConfig.Companion.useDebugNewConfig(defaults);
logger.info("Network Address Manager Service ...[REGISTERED]");
| /**
* Bundle activator that will start the bundle when the requested dependent services are available.
*/
public abstract class DependentActivator implements BundleActivator, ServiceTrackerCustomizer<Object,Object> {
private static final Map<BundleActivator,Set<Class<?>>> openTrackers=Collections.synchronizedMap(new HashMap<>());
private final Logger logger=LoggerFactory.getLogger(getClass());
private final Map<Class<?>,ServiceTracker<?,?>> dependentServices=new HashMap<>();
private final Set<Object> runningServices=new HashSet<>();
private BundleContext bundleContext;
protected DependentActivator( Iterable<Class<?>> dependentServices);
protected DependentActivator( Class<?>... dependentServices);
/**
* Starts the bundle.
* @param bundleContext the currently valid <tt>BundleContext</tt>.
*/
@Override public final void start( BundleContext bundleContext);
@Override public void stop( BundleContext context) throws Exception;
@Override public Object addingService( ServiceReference<Object> reference);
@SuppressWarnings("unchecked") protected <T>T getService( Class<T> serviceClass);
@Override public void modifiedService( ServiceReference<Object> reference, Object service);
@Override public void removedService( ServiceReference<Object> reference, Object service);
protected abstract void startWithServices( BundleContext bundleContext) throws Exception ;
}
|
this.bundleContext = bundleContext;
if (logger.isInfoEnabled())
logger.info("Network Address Manager Service ...[STARTED]");
networkAMS = new NetworkAddressManagerServiceImpl();
networkAMS.start();
| [
"BundleContext",
"NetworkAddressManagerServiceImpl"
] | [
"isInfoEnabled",
"info",
"start"
] | [
"BundleContext",
"NetworkAddressManagerServiceImpl",
"ConfigSource",
"ConfigurationService",
"Function0<String>",
"PacketLoggingService"
] | [
"start",
"defaultReference",
"isWarnEnabled",
"isErrorEnabled",
"setLogger",
"warn",
"getClassLoader",
"isInfoEnabled",
"registerService",
"isDebugEnabled",
"setCacheEnabled",
"debug",
"error",
"useDebugNewConfig",
"getName",
"invoke",
"info"
] | {
"methods": [
"isInfoEnabled",
"info",
"start"
],
"similar_methods": [
"startWithServices"
],
"types": [
"BundleContext",
"NetworkAddressManagerServiceImpl"
]
} | /**
* Comparator for bundle array sort
* @author ROTH Damien
*/
public class BundleComparator implements Comparator<Bundle> {
/**
* Compares the bundles using their "Bundle-Name"s.
* @param arg0 the first bundle to compare
* @param arg1 the second bundle to compare
* @return the result of the string comparison between the names of the twobundles
*/
public int compare( Bundle arg0, Bundle arg1);
}
/**
* This implementation of the Network Address Manager allows you to intelligently retrieve the address of your localhost according to the destinations that you will be trying to reach. It also provides an interface to the ICE implementation in ice4j.
* @author Emil Ivov
*/
public class NetworkAddressManagerServiceImpl implements NetworkAddressManagerService {
/**
* Our class logger.
*/
private static org.slf4j.Logger logger=org.slf4j.LoggerFactory.getLogger(NetworkAddressManagerServiceImpl.class);
/**
* The socket that we use for dummy connections during selection of a local address that has to be used when communicating with a specific location.
*/
DatagramSocket localHostFinderSocket=null;
/**
* A random (unused)local port to use when trying to select a local host address to use when sending messages to a specific destination.
*/
private static final int RANDOM_ADDR_DISC_PORT=55721;
/**
* The name of the property containing the number of binds that we should should execute in case a port is already bound to (each retry would be on a new random port).
*/
public static final String BIND_RETRIES_PROPERTY_NAME="net.java.sip.communicator.service.netaddr.BIND_RETRIES";
/**
* Default STUN server port.
*/
public static final int DEFAULT_STUN_SERVER_PORT=3478;
/**
* A thread which periodically scans network interfaces and reports changes in network configuration.
*/
private NetworkConfigurationWatcher networkConfigurationWatcher=null;
/**
* The service name to use when discovering TURN servers through DNS using SRV requests as per RFC 5766.
*/
public static final String TURN_SRV_NAME="turn";
/**
* The service name to use when discovering STUN servers through DNS using SRV requests as per RFC 5389.
*/
public static final String STUN_SRV_NAME="stun";
/**
* Initializes this network address manager service implementation.
*/
public void start();
/**
* Kills all threads/processes launched by this thread (if any) and prepares it for shutdown. You may use this method as a reinitialization technique (you'll have to call start afterwards)
*/
public void stop();
/**
* Returns an InetAddress instance that represents the localhost, and that a socket can bind upon or distribute to peers as a contact address.
* @param intendedDestination the destination that we'd like to use thelocalhost address with.
* @return an InetAddress instance representing the local host, and thata socket can bind upon or distribute to peers as a contact address.
*/
public synchronized InetAddress getLocalHost( InetAddress intendedDestination);
/**
* Returns the hardware address (i.e. MAC address) of the specified interface name.
* @param iface the <tt>NetworkInterface</tt>
* @return array of bytes representing the layer 2 address or null ifinterface does not exist
*/
public byte[] getHardwareAddress( NetworkInterface iface);
/**
* Tries to obtain an for the specified port.
* @param dst the destination that we'd like to use this address with.
* @param port the port whose mapping we are interested in.
* @return a public address corresponding to the specified port or nullif all attempts to retrieve such an address have failed.
* @throws IOException if an error occurs while creating the socket.
* @throws BindException if the port is already in use.
*/
public InetSocketAddress getPublicAddressFor( InetAddress dst, int port) throws IOException, BindException;
/**
* This method gets called when a bound property is changed.
* @param evt A PropertyChangeEvent object describing the event sourceand the property that has changed.
*/
public void propertyChange( PropertyChangeEvent evt);
/**
* Initializes and binds a socket that on a random port number. The method would try to bind on a random port and retry 5 times until a free port is found.
* @return the socket that we have initialized on a randomport number.
*/
private DatagramSocket initRandomPortSocket();
/**
* Creates a <tt>DatagramSocket</tt> and binds it to the specified <tt>localAddress</tt> and a port in the range specified by the <tt>minPort</tt> and <tt>maxPort</tt> parameters. We first try to bind the newly created socket on the <tt>preferredPort</tt> port number (unless it is outside the <tt>[minPort, maxPort]</tt> range in which case we first try the <tt>minPort</tt>) and then proceed incrementally upwards until we succeed or reach the bind retries limit. If we reach the <tt>maxPort</tt> port number before the bind retries limit, we will then start over again at <tt>minPort</tt> and keep going until we run out of retries.
* @param laddr the address that we'd like to bind the socket on.
* @param preferredPort the port number that we should try to bind to first.
* @param minPort the port number where we should first try to bind beforemoving to the next one (i.e. <tt>minPort + 1</tt>)
* @param maxPort the maximum port number where we should try bindingbefore giving up and throwinG an exception.
* @return the newly created <tt>DatagramSocket</tt>.
* @throws IllegalArgumentException if either <tt>minPort</tt> or<tt>maxPort</tt> is not a valid port number or if <tt>minPort > maxPort</tt>.
* @throws IOException if an error occurs while the underlying resolver libis using sockets.
* @throws BindException if we couldn't find a free port between<tt>minPort</tt> and <tt>maxPort</tt> before reaching the maximum allowed number of retries.
*/
public DatagramSocket createDatagramSocket( InetAddress laddr, int preferredPort, int minPort, int maxPort) throws IllegalArgumentException, IOException, BindException;
/**
* Adds new <tt>NetworkConfigurationChangeListener</tt> which will be informed for network configuration changes.
* @param listener the listener.
*/
public synchronized void addNetworkConfigurationChangeListener( NetworkConfigurationChangeListener listener);
/**
* Remove <tt>NetworkConfigurationChangeListener</tt>.
* @param listener the listener.
*/
public synchronized void removeNetworkConfigurationChangeListener( NetworkConfigurationChangeListener listener);
/**
* Creates and returns an ICE agent that a protocol could use for the negotiation of media transport addresses. One ICE agent should only be used for a single session negotiation.
* @return the newly created ICE Agent.
*/
public Agent createIceAgent();
/**
* Tries to discover a TURN or a STUN server for the specified <tt>domainName</tt>. The method would first try to discover a TURN server and then fall back to STUN only. In both cases we would only care about a UDP transport.
* @param domainName the domain name that we are trying to discover aTURN server for.
* @param userName the name of the user we'd like to use when connecting toa TURN server (we won't be using credentials in case we only have a STUN server).
* @param password the password that we'd like to try when connecting toa TURN server (we won't be using credentials in case we only have a STUN server).
* @return A {@link StunCandidateHarvester} corresponding to the TURN orSTUN server we discovered or <tt>null</tt> if there were no such records for the specified <tt>domainName</tt>
*/
public StunCandidateHarvester discoverStunServer( String domainName, byte[] userName, byte[] password);
/**
* Creates an <tt>IceMediaStrean</tt> and adds to it an RTP and and RTCP component, which also implies running the currently installed harvesters so that they would.
* @param rtpPort the port that we should try to bind the RTP component on(the RTCP one would automatically go to rtpPort + 1)
* @param streamName the name of the stream to create
* @param agent the <tt>Agent</tt> that should create the stream.
* @return the newly created <tt>IceMediaStream</tt>.
* @throws IllegalArgumentException if <tt>rtpPort</tt> is not a valid portnumber.
* @throws IOException if an error occurs while the underlying resolveris using sockets.
* @throws BindException if we couldn't find a free port between within thedefault number of retries.
*/
public IceMediaStream createIceStream( int rtpPort, String streamName, Agent agent) throws IllegalArgumentException, IOException, BindException;
/**
* {@inheritDoc}
*/
public IceMediaStream createIceStream( int numComponents, int portBase, String streamName, Agent agent) throws IllegalArgumentException, IOException, BindException;
}
/**
* Indicates if this account is currently enabled.
* @return <tt>true</tt> if this account is enabled, <tt>false</tt> -otherwise.
*/
public boolean isEnabled(){
return !getAccountPropertyBoolean(ProtocolProviderFactory.IS_ACCOUNT_DISABLED,false);
}
/**
* Usage instructions.
*/
@Override public String help(){
return "Usage: /nick <new-nick>";
}
/**
* Starting the bundle.
* @param context the bundle context
*/
@Override public void start(final BundleContext context){
for ( Entry<String,Class<? extends Command>> entry : COMMANDS.entrySet()) {
CommandFactory.registerCommand(entry.getKey(),entry.getValue());
}
}
/**
* Initialize and start Sparkle
* @param bundleContext BundleContext
* @throws Exception if something goes wrong during sparkle initialization
*/
@Override public void startWithServices(BundleContext bundleContext) throws Exception {
try {
if (!SparkleActivator.sparkleLibLoaded) {
System.loadLibrary("sparkle_init");
SparkleActivator.sparkleLibLoaded=true;
}
}
catch ( UnsatisfiedLinkError t) {
logger.warn("Couldn't load sparkle library: " + t.getMessage());
return;
}
String downloadLink=getService(ConfigurationService.class).getString(PROP_UPDATE_LINK);
String title=getService(ResourceManagementService.class).getI18NString("plugin.updatechecker.UPDATE_MENU_ENTRY");
if (title != null) title+="...";
initSparkle(System.getProperty("user.dir") + "/../../Frameworks/Sparkle.framework",updateAtStartup,checkInterval,downloadLink,title);
if (logger.isInfoEnabled()) logger.info("Sparkle Plugin ...[Started]");
}
| public class BundleComparator implements Comparator<Bundle> {
public int compare( Bundle arg0, Bundle arg1);
}
public class NetworkAddressManagerServiceImpl implements NetworkAddressManagerService {
private static org.slf4j.Logger logger=org.slf4j.LoggerFactory.getLogger(NetworkAddressManagerServiceImpl.class);
DatagramSocket localHostFinderSocket=null;
private static final int RANDOM_ADDR_DISC_PORT=55721;
public static final String BIND_RETRIES_PROPERTY_NAME="net.java.sip.communicator.service.netaddr.BIND_RETRIES";
public static final int DEFAULT_STUN_SERVER_PORT=3478;
private NetworkConfigurationWatcher networkConfigurationWatcher=null;
public static final String TURN_SRV_NAME="turn";
public static final String STUN_SRV_NAME="stun";
public void start();
public void stop();
public synchronized InetAddress getLocalHost( InetAddress intendedDestination);
public byte[] getHardwareAddress( NetworkInterface iface);
public InetSocketAddress getPublicAddressFor( InetAddress dst, int port) throws IOException, BindException;
public void propertyChange( PropertyChangeEvent evt);
private DatagramSocket initRandomPortSocket();
public DatagramSocket createDatagramSocket( InetAddress laddr, int preferredPort, int minPort, int maxPort) throws IllegalArgumentException, IOException, BindException;
public synchronized void addNetworkConfigurationChangeListener( NetworkConfigurationChangeListener listener);
public synchronized void removeNetworkConfigurationChangeListener( NetworkConfigurationChangeListener listener);
public Agent createIceAgent();
public StunCandidateHarvester discoverStunServer( String domainName, byte[] userName, byte[] password);
public IceMediaStream createIceStream( int rtpPort, String streamName, Agent agent) throws IllegalArgumentException, IOException, BindException;
public IceMediaStream createIceStream( int numComponents, int portBase, String streamName, Agent agent) throws IllegalArgumentException, IOException, BindException;
}
/**
* Indicates if this account is currently enabled.
* @return <tt>true</tt> if this account is enabled, <tt>false</tt> -otherwise.
*/
public boolean isEnabled(){
return !getAccountPropertyBoolean(ProtocolProviderFactory.IS_ACCOUNT_DISABLED,false);
}
/**
* Usage instructions.
*/
@Override public String help(){
return "Usage: /nick <new-nick>";
}
/**
* Starting the bundle.
* @param context the bundle context
*/
@Override public void start(final BundleContext context){
for ( Entry<String,Class<? extends Command>> entry : COMMANDS.entrySet()) {
CommandFactory.registerCommand(entry.getKey(),entry.getValue());
}
}
/**
* Initialize and start Sparkle
* @param bundleContext BundleContext
* @throws Exception if something goes wrong during sparkle initialization
*/
@Override public void startWithServices(BundleContext bundleContext) throws Exception {
try {
if (!SparkleActivator.sparkleLibLoaded) {
System.loadLibrary("sparkle_init");
SparkleActivator.sparkleLibLoaded=true;
}
}
catch ( UnsatisfiedLinkError t) {
logger.warn("Couldn't load sparkle library: " + t.getMessage());
return;
}
String downloadLink=getService(ConfigurationService.class).getString(PROP_UPDATE_LINK);
String title=getService(ResourceManagementService.class).getI18NString("plugin.updatechecker.UPDATE_MENU_ENTRY");
if (title != null) title+="...";
initSparkle(System.getProperty("user.dir") + "/../../Frameworks/Sparkle.framework",updateAtStartup,checkInterval,downloadLink,title);
if (logger.isInfoEnabled()) logger.info("Sparkle Plugin ...[Started]");
}
| {"types": [{"BundleContext": "BundleComparator"}, {"NetworkAddressManagerServiceImpl": "NetworkAddressManagerServiceImpl"}], "methods": [{"isInfoEnabled": "isEnabled"}, {"info": "help"}, {"start": "start"}], "similar_methods": [{"startWithServices": "startWithServices"}]} | [{"BundleContext": {"retrieved_name": "BundleComparator", "raw_body": "/** \n * Comparator for bundle array sort\n * @author ROTH Damien\n */\npublic class BundleComparator implements Comparator<Bundle> {\n /** \n * Compares the bundles using their \"Bundle-Name\"s.\n * @param arg0 the first bundle to compare\n * @param arg1 the second bundle to compare\n * @return the result of the string comparison between the names of the twobundles\n */\n public int compare( Bundle arg0, Bundle arg1);\n}\n", "raw_body_no_cmt": "public class BundleComparator implements Comparator<Bundle> {\n public int compare( Bundle arg0, Bundle arg1);\n}\n"}}, {"NetworkAddressManagerServiceImpl": {"retrieved_name": "NetworkAddressManagerServiceImpl", "raw_body": "/** \n * This implementation of the Network Address Manager allows you to intelligently retrieve the address of your localhost according to the destinations that you will be trying to reach. It also provides an interface to the ICE implementation in ice4j.\n * @author Emil Ivov\n */\npublic class NetworkAddressManagerServiceImpl implements NetworkAddressManagerService {\n /** \n * Our class logger.\n */\n private static org.slf4j.Logger logger=org.slf4j.LoggerFactory.getLogger(NetworkAddressManagerServiceImpl.class);\n /** \n * The socket that we use for dummy connections during selection of a local address that has to be used when communicating with a specific location.\n */\n DatagramSocket localHostFinderSocket=null;\n /** \n * A random (unused)local port to use when trying to select a local host address to use when sending messages to a specific destination.\n */\n private static final int RANDOM_ADDR_DISC_PORT=55721;\n /** \n * The name of the property containing the number of binds that we should should execute in case a port is already bound to (each retry would be on a new random port).\n */\n public static final String BIND_RETRIES_PROPERTY_NAME=\"net.java.sip.communicator.service.netaddr.BIND_RETRIES\";\n /** \n * Default STUN server port.\n */\n public static final int DEFAULT_STUN_SERVER_PORT=3478;\n /** \n * A thread which periodically scans network interfaces and reports changes in network configuration.\n */\n private NetworkConfigurationWatcher networkConfigurationWatcher=null;\n /** \n * The service name to use when discovering TURN servers through DNS using SRV requests as per RFC 5766.\n */\n public static final String TURN_SRV_NAME=\"turn\";\n /** \n * The service name to use when discovering STUN servers through DNS using SRV requests as per RFC 5389.\n */\n public static final String STUN_SRV_NAME=\"stun\";\n /** \n * Initializes this network address manager service implementation.\n */\n public void start();\n /** \n * Kills all threads/processes launched by this thread (if any) and prepares it for shutdown. You may use this method as a reinitialization technique (you'll have to call start afterwards)\n */\n public void stop();\n /** \n * Returns an InetAddress instance that represents the localhost, and that a socket can bind upon or distribute to peers as a contact address.\n * @param intendedDestination the destination that we'd like to use thelocalhost address with.\n * @return an InetAddress instance representing the local host, and thata socket can bind upon or distribute to peers as a contact address.\n */\n public synchronized InetAddress getLocalHost( InetAddress intendedDestination);\n /** \n * Returns the hardware address (i.e. MAC address) of the specified interface name.\n * @param iface the <tt>NetworkInterface</tt>\n * @return array of bytes representing the layer 2 address or null ifinterface does not exist\n */\n public byte[] getHardwareAddress( NetworkInterface iface);\n /** \n * Tries to obtain an for the specified port.\n * @param dst the destination that we'd like to use this address with.\n * @param port the port whose mapping we are interested in.\n * @return a public address corresponding to the specified port or nullif all attempts to retrieve such an address have failed.\n * @throws IOException if an error occurs while creating the socket.\n * @throws BindException if the port is already in use.\n */\n public InetSocketAddress getPublicAddressFor( InetAddress dst, int port) throws IOException, BindException;\n /** \n * This method gets called when a bound property is changed.\n * @param evt A PropertyChangeEvent object describing the event sourceand the property that has changed.\n */\n public void propertyChange( PropertyChangeEvent evt);\n /** \n * Initializes and binds a socket that on a random port number. The method would try to bind on a random port and retry 5 times until a free port is found.\n * @return the socket that we have initialized on a randomport number.\n */\n private DatagramSocket initRandomPortSocket();\n /** \n * Creates a <tt>DatagramSocket</tt> and binds it to the specified <tt>localAddress</tt> and a port in the range specified by the <tt>minPort</tt> and <tt>maxPort</tt> parameters. We first try to bind the newly created socket on the <tt>preferredPort</tt> port number (unless it is outside the <tt>[minPort, maxPort]</tt> range in which case we first try the <tt>minPort</tt>) and then proceed incrementally upwards until we succeed or reach the bind retries limit. If we reach the <tt>maxPort</tt> port number before the bind retries limit, we will then start over again at <tt>minPort</tt> and keep going until we run out of retries.\n * @param laddr the address that we'd like to bind the socket on.\n * @param preferredPort the port number that we should try to bind to first.\n * @param minPort the port number where we should first try to bind beforemoving to the next one (i.e. <tt>minPort + 1</tt>)\n * @param maxPort the maximum port number where we should try bindingbefore giving up and throwinG an exception.\n * @return the newly created <tt>DatagramSocket</tt>.\n * @throws IllegalArgumentException if either <tt>minPort</tt> or<tt>maxPort</tt> is not a valid port number or if <tt>minPort > maxPort</tt>.\n * @throws IOException if an error occurs while the underlying resolver libis using sockets.\n * @throws BindException if we couldn't find a free port between<tt>minPort</tt> and <tt>maxPort</tt> before reaching the maximum allowed number of retries.\n */\n public DatagramSocket createDatagramSocket( InetAddress laddr, int preferredPort, int minPort, int maxPort) throws IllegalArgumentException, IOException, BindException;\n /** \n * Adds new <tt>NetworkConfigurationChangeListener</tt> which will be informed for network configuration changes.\n * @param listener the listener.\n */\n public synchronized void addNetworkConfigurationChangeListener( NetworkConfigurationChangeListener listener);\n /** \n * Remove <tt>NetworkConfigurationChangeListener</tt>.\n * @param listener the listener.\n */\n public synchronized void removeNetworkConfigurationChangeListener( NetworkConfigurationChangeListener listener);\n /** \n * Creates and returns an ICE agent that a protocol could use for the negotiation of media transport addresses. One ICE agent should only be used for a single session negotiation.\n * @return the newly created ICE Agent.\n */\n public Agent createIceAgent();\n /** \n * Tries to discover a TURN or a STUN server for the specified <tt>domainName</tt>. The method would first try to discover a TURN server and then fall back to STUN only. In both cases we would only care about a UDP transport.\n * @param domainName the domain name that we are trying to discover aTURN server for.\n * @param userName the name of the user we'd like to use when connecting toa TURN server (we won't be using credentials in case we only have a STUN server).\n * @param password the password that we'd like to try when connecting toa TURN server (we won't be using credentials in case we only have a STUN server).\n * @return A {@link StunCandidateHarvester} corresponding to the TURN orSTUN server we discovered or <tt>null</tt> if there were no such records for the specified <tt>domainName</tt>\n */\n public StunCandidateHarvester discoverStunServer( String domainName, byte[] userName, byte[] password);\n /** \n * Creates an <tt>IceMediaStrean</tt> and adds to it an RTP and and RTCP component, which also implies running the currently installed harvesters so that they would.\n * @param rtpPort the port that we should try to bind the RTP component on(the RTCP one would automatically go to rtpPort + 1)\n * @param streamName the name of the stream to create\n * @param agent the <tt>Agent</tt> that should create the stream.\n * @return the newly created <tt>IceMediaStream</tt>.\n * @throws IllegalArgumentException if <tt>rtpPort</tt> is not a valid portnumber.\n * @throws IOException if an error occurs while the underlying resolveris using sockets.\n * @throws BindException if we couldn't find a free port between within thedefault number of retries.\n */\n public IceMediaStream createIceStream( int rtpPort, String streamName, Agent agent) throws IllegalArgumentException, IOException, BindException;\n /** \n * {@inheritDoc}\n */\n public IceMediaStream createIceStream( int numComponents, int portBase, String streamName, Agent agent) throws IllegalArgumentException, IOException, BindException;\n}\n", "raw_body_no_cmt": "public class NetworkAddressManagerServiceImpl implements NetworkAddressManagerService {\n private static org.slf4j.Logger logger=org.slf4j.LoggerFactory.getLogger(NetworkAddressManagerServiceImpl.class);\n DatagramSocket localHostFinderSocket=null;\n private static final int RANDOM_ADDR_DISC_PORT=55721;\n public static final String BIND_RETRIES_PROPERTY_NAME=\"net.java.sip.communicator.service.netaddr.BIND_RETRIES\";\n public static final int DEFAULT_STUN_SERVER_PORT=3478;\n private NetworkConfigurationWatcher networkConfigurationWatcher=null;\n public static final String TURN_SRV_NAME=\"turn\";\n public static final String STUN_SRV_NAME=\"stun\";\n public void start();\n public void stop();\n public synchronized InetAddress getLocalHost( InetAddress intendedDestination);\n public byte[] getHardwareAddress( NetworkInterface iface);\n public InetSocketAddress getPublicAddressFor( InetAddress dst, int port) throws IOException, BindException;\n public void propertyChange( PropertyChangeEvent evt);\n private DatagramSocket initRandomPortSocket();\n public DatagramSocket createDatagramSocket( InetAddress laddr, int preferredPort, int minPort, int maxPort) throws IllegalArgumentException, IOException, BindException;\n public synchronized void addNetworkConfigurationChangeListener( NetworkConfigurationChangeListener listener);\n public synchronized void removeNetworkConfigurationChangeListener( NetworkConfigurationChangeListener listener);\n public Agent createIceAgent();\n public StunCandidateHarvester discoverStunServer( String domainName, byte[] userName, byte[] password);\n public IceMediaStream createIceStream( int rtpPort, String streamName, Agent agent) throws IllegalArgumentException, IOException, BindException;\n public IceMediaStream createIceStream( int numComponents, int portBase, String streamName, Agent agent) throws IllegalArgumentException, IOException, BindException;\n}\n"}}] | [{"isInfoEnabled": {"retrieved_name": "isEnabled", "raw_body": "/** \n * Indicates if this account is currently enabled.\n * @return <tt>true</tt> if this account is enabled, <tt>false</tt> -otherwise.\n */\npublic boolean isEnabled(){\n return !getAccountPropertyBoolean(ProtocolProviderFactory.IS_ACCOUNT_DISABLED,false);\n}\n"}}, {"info": {"retrieved_name": "help", "raw_body": "/** \n * Usage instructions.\n */\n@Override public String help(){\n return \"Usage: /nick <new-nick>\";\n}\n"}}, {"start": {"retrieved_name": "start", "raw_body": "/** \n * Starting the bundle.\n * @param context the bundle context\n */\n@Override public void start(final BundleContext context){\n for ( Entry<String,Class<? extends Command>> entry : COMMANDS.entrySet()) {\n CommandFactory.registerCommand(entry.getKey(),entry.getValue());\n }\n}\n"}}] | [{"startWithServices": {"retrieved_name": "startWithServices", "raw_body": "/** \n * Initialize and start Sparkle\n * @param bundleContext BundleContext\n * @throws Exception if something goes wrong during sparkle initialization\n */\n@Override public void startWithServices(BundleContext bundleContext) throws Exception {\n try {\n if (!SparkleActivator.sparkleLibLoaded) {\n System.loadLibrary(\"sparkle_init\");\n SparkleActivator.sparkleLibLoaded=true;\n }\n }\n catch ( UnsatisfiedLinkError t) {\n logger.warn(\"Couldn't load sparkle library: \" + t.getMessage());\n return;\n }\n String downloadLink=getService(ConfigurationService.class).getString(PROP_UPDATE_LINK);\n String title=getService(ResourceManagementService.class).getI18NString(\"plugin.updatechecker.UPDATE_MENU_ENTRY\");\n if (title != null) title+=\"...\";\n initSparkle(System.getProperty(\"user.dir\") + \"/../../Frameworks/Sparkle.framework\",updateAtStartup,checkInterval,downloadLink,title);\n if (logger.isInfoEnabled()) logger.info(\"Sparkle Plugin ...[Started]\");\n}\n"}}] |
pmd_pmd | pmd/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/symboltable/VariableNameDeclaration.java | VariableNameDeclaration | getScope | class VariableNameDeclaration extends AbstractNameDeclaration {
private static final Logger LOG = LoggerFactory.getLogger(VariableNameDeclaration.class);
public VariableNameDeclaration(ASTVariableOrConstantDeclaratorId node) {
super(node);
}
@Override
public Scope getScope() {<FILL_FUNCTION_BODY>}
public ASTVariableOrConstantDeclaratorId getDeclaratorId() {
return (ASTVariableOrConstantDeclaratorId) node;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof VariableNameDeclaration)) {
return false;
}
VariableNameDeclaration n = (VariableNameDeclaration) o;
try {
return n.getImage().equals(this.getImage());
} catch (Exception e) {
LOG.error(e.getMessage(), e);
LOG.debug("n.node={}", n.node);
LOG.debug("n.getImage={}", n.getImage());
LOG.debug("node={}", node);
LOG.debug("this.getImage={}", this.getImage());
return false;
}
}
@Override
public int hashCode() {
try {
return this.getImage().hashCode();
} catch (Exception e) {
LOG.error(e.getMessage(), e);
LOG.debug("VariableNameDeclaration: node={}", node);
LOG.debug("VariableNameDeclaration: node,getImage={}", this.getImage());
return 0;
}
}
@Override
public String toString() {
return "Variable: image = '" + node.getImage() + "', line = " + node.getBeginLine();
}
} |
try {
return node.getScope().getEnclosingScope(ClassScope.class);
} catch (Exception e) {
LOG.trace("This Node does not have an enclosing Class: {}/{} => {}",
node.getBeginLine(), node.getBeginColumn(),
this.getImage());
return null; // @TODO SRT a cop-out
}
| /**
* Base class for all name declarations.
*/
public abstract class AbstractNameDeclaration implements NameDeclaration {
protected ScopedNode node;
public AbstractNameDeclaration( ScopedNode node);
@Override public ScopedNode getNode();
@Override public String getImage();
@Override public Scope getScope();
@Override public String getName();
}
|
return node.getScope();
| [
"ASTVariableOrConstantDeclaratorId"
] | [
"getScope"
] | [
"Exception",
"Logger",
"ASTVariableOrConstantDeclaratorId"
] | [
"trace",
"getScope",
"getImage",
"getBeginColumn",
"getEnclosingScope",
"getBeginLine"
] | {
"methods": [
"getScope"
],
"similar_methods": [
"getScope"
],
"types": [
"ASTVariableOrConstantDeclaratorId"
]
} | public final class ASTVariableOrConstantDeclaratorId extends AbstractPLSQLNode {
private int arrayDepth;
private NameDeclaration nameDeclaration;
ASTVariableOrConstantDeclaratorId( int id);
@Override protected <P,R>R acceptPlsqlVisitor( PlsqlVisitor<? super P,? extends R> visitor, P data);
public NameDeclaration getNameDeclaration();
void setNameDeclaration( NameDeclaration decl);
public List<NameOccurrence> getUsages();
void bumpArrayDepth();
public int getArrayDepth();
public boolean isArray();
public Node getTypeNameNode();
public ASTDatatype getTypeNode();
private Node findTypeNameNode( Node node);
}
@Override Scope getScope();
@Override Scope getScope();
| public final class ASTVariableOrConstantDeclaratorId extends AbstractPLSQLNode {
private int arrayDepth;
private NameDeclaration nameDeclaration;
ASTVariableOrConstantDeclaratorId( int id);
protected <P,R>R acceptPlsqlVisitor( PlsqlVisitor<? super P,? extends R> visitor, P data);
public NameDeclaration getNameDeclaration();
void setNameDeclaration( NameDeclaration decl);
public List<NameOccurrence> getUsages();
void bumpArrayDepth();
public int getArrayDepth();
public boolean isArray();
public Node getTypeNameNode();
public ASTDatatype getTypeNode();
private Node findTypeNameNode( Node node);
}
@Override Scope getScope();
@Override Scope getScope();
| {"types": [{"ASTVariableOrConstantDeclaratorId": "ASTVariableOrConstantDeclaratorId"}], "methods": [{"getScope": "getScope"}], "similar_methods": [{"getScope": "getScope"}]} | [{"ASTVariableOrConstantDeclaratorId": {"retrieved_name": "ASTVariableOrConstantDeclaratorId", "raw_body": "public final class ASTVariableOrConstantDeclaratorId extends AbstractPLSQLNode {\n private int arrayDepth;\n private NameDeclaration nameDeclaration;\n ASTVariableOrConstantDeclaratorId( int id);\n @Override protected <P,R>R acceptPlsqlVisitor( PlsqlVisitor<? super P,? extends R> visitor, P data);\n public NameDeclaration getNameDeclaration();\n void setNameDeclaration( NameDeclaration decl);\n public List<NameOccurrence> getUsages();\n void bumpArrayDepth();\n public int getArrayDepth();\n public boolean isArray();\n public Node getTypeNameNode();\n public ASTDatatype getTypeNode();\n private Node findTypeNameNode( Node node);\n}\n", "raw_body_no_cmt": "public final class ASTVariableOrConstantDeclaratorId extends AbstractPLSQLNode {\n private int arrayDepth;\n private NameDeclaration nameDeclaration;\n ASTVariableOrConstantDeclaratorId( int id);\n protected <P,R>R acceptPlsqlVisitor( PlsqlVisitor<? super P,? extends R> visitor, P data);\n public NameDeclaration getNameDeclaration();\n void setNameDeclaration( NameDeclaration decl);\n public List<NameOccurrence> getUsages();\n void bumpArrayDepth();\n public int getArrayDepth();\n public boolean isArray();\n public Node getTypeNameNode();\n public ASTDatatype getTypeNode();\n private Node findTypeNameNode( Node node);\n}\n"}}] | [{"getScope": {"retrieved_name": "getScope", "raw_body": "@Override Scope getScope();\n"}}] | [{"getScope": {"retrieved_name": "getScope", "raw_body": "@Override Scope getScope();\n"}}] |
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-common/src/main/java/com/jarvis/cache/reflect/generics/ParameterizedTypeImpl.java | ParameterizedTypeImpl | validateConstructorArguments | class ParameterizedTypeImpl implements ParameterizedType {
private Type[] actualTypeArguments;
private Class<?> rawType;
private Type ownerType;
private ParameterizedTypeImpl(Class<?> paramClass, Type[] paramArrayOfType, Type paramType) {
this.actualTypeArguments = paramArrayOfType;
this.rawType = paramClass;
if (paramType != null) {
this.ownerType = paramType;
} else {
this.ownerType = paramClass.getDeclaringClass();
}
validateConstructorArguments();
}
private void validateConstructorArguments() {<FILL_FUNCTION_BODY>}
public static ParameterizedTypeImpl make(Class<?> paramClass, Type[] paramArrayOfType, Type paramType) {
return new ParameterizedTypeImpl(paramClass, paramArrayOfType, paramType);
}
@Override
public Type[] getActualTypeArguments() {
return (Type[]) this.actualTypeArguments.clone();
}
@Override
public Class<?> getRawType() {
return this.rawType;
}
@Override
public Type getOwnerType() {
return this.ownerType;
}
@Override
public boolean equals(Object paramObject) {
if ((paramObject instanceof ParameterizedType)) {
ParameterizedType localParameterizedType = (ParameterizedType) paramObject;
if (this == localParameterizedType) {
return true;
}
Type localType1 = localParameterizedType.getOwnerType();
Type localType2 = localParameterizedType.getRawType();
return (this.ownerType == null ? localType1 == null : this.ownerType.equals(localType1))
&& (this.rawType == null ? localType2 == null : this.rawType.equals(localType2))
&& (Arrays.equals(this.actualTypeArguments, localParameterizedType.getActualTypeArguments()));
}
return false;
}
@Override
public int hashCode() {
return Arrays.hashCode(this.actualTypeArguments) ^ (this.ownerType == null ? 0 : this.ownerType.hashCode())
^ (this.rawType == null ? 0 : this.rawType.hashCode());
}
@Override
public String toString() {
StringBuilder localStringBuilder = new StringBuilder();
if (this.ownerType != null) {
if ((this.ownerType instanceof Class<?>))
localStringBuilder.append(((Class<?>) this.ownerType).getName());
else {
localStringBuilder.append(this.ownerType.toString());
}
localStringBuilder.append(".");
if ((this.ownerType instanceof ParameterizedTypeImpl)) {
localStringBuilder.append(this.rawType.getName()
.replace(((ParameterizedTypeImpl) this.ownerType).rawType.getName() + "$", ""));
} else {
localStringBuilder.append(this.rawType.getName());
}
} else {
localStringBuilder.append(this.rawType.getName());
}
if ((this.actualTypeArguments != null) && (this.actualTypeArguments.length > 0)) {
localStringBuilder.append("<");
int i = 1;
for (Type localType : this.actualTypeArguments) {
if (i == 0) {
localStringBuilder.append(", ");
}
if ((localType instanceof Class<?>)) {
localStringBuilder.append(((Class<?>) localType).getName());
} else {
// if(null!=localType){
localStringBuilder.append(localType.toString());
// }
}
i = 0;
}
localStringBuilder.append(">");
}
return localStringBuilder.toString();
}
} |
@SuppressWarnings("rawtypes")
TypeVariable[] arrayOfTypeVariable = this.rawType.getTypeParameters();
if (arrayOfTypeVariable.length != this.actualTypeArguments.length) {
throw new MalformedParameterizedTypeException();
}
// for(int i=0; i < this.actualTypeArguments.length; i++);
|
if (this.actualTypeArguments == null) {
throw new IllegalArgumentException("actualTypeArguments cannot be null");
}
if (this.rawType == null) {
throw new IllegalArgumentException("rawType cannot be null");
}
| [
"Type[]",
"Class<?>"
] | [] | [
"Class<?>",
"TypeVariable[]",
"Type[]"
] | [
"getTypeParameters"
] | {
"methods": [],
"similar_methods": [
"validateConstructorArguments"
],
"types": [
"Type[]",
"Class<?>"
]
} | public class StringUtil {
/**
* Check whether the given {@code CharSequence} contains actual <em>text</em>.<p>More specifically, this method returns {@code true} if the{@code CharSequence} is not {@code null}, its length is greater than 0, and it contains at least one non-whitespace character. <p><pre class="code"> StringUtils.hasText(null) = false StringUtils.hasText("") = false StringUtils.hasText(" ") = false StringUtils.hasText("12345") = true StringUtils.hasText(" 12345 ") = true </pre>
* @param str the {@code CharSequence} to check (may be {@code null})
* @return {@code true} if the {@code CharSequence} is not {@code null}, its length is greater than 0, and it does not contain whitespace only
* @see Character#isWhitespace
*/
public static boolean hasText( CharSequence str);
/**
* Check whether the given {@code String} contains actual <em>text</em>.<p>More specifically, this method returns {@code true} if the{@code String} is not {@code null}, its length is greater than 0, and it contains at least one non-whitespace character.
* @param str the {@code String} to check (may be {@code null})
* @return {@code true} if the {@code String} is not {@code null}, its length is greater than 0, and it does not contain whitespace only
* @see #hasText(CharSequence)
*/
public static boolean hasText( String str);
private static boolean containsText( CharSequence str);
}
/**
* kryo class register
* @author stevie.wong
*/
public interface KryoClassRegistration {
/**
* 注册类
* @param kryo see {@link Kryo}
*/
void register( Kryo kryo);
}
@Bean(name=VALIDATOR_BEAN_NAME) public CacheManagerValidator autoloadCacheAutoConfigurationValidator(){
return new CacheManagerValidator();
}
| public class StringUtil {
public static boolean hasText( CharSequence str);
public static boolean hasText( String str);
private static boolean containsText( CharSequence str);
}
public interface KryoClassRegistration {
void register( Kryo kryo);
}
@Bean(name=VALIDATOR_BEAN_NAME) public CacheManagerValidator autoloadCacheAutoConfigurationValidator(){
return new CacheManagerValidator();
}
| {"types": [{"Type[]": "StringUtil"}, {"Class<?>": "KryoClassRegistration"}], "similar_methods": [{"validateConstructorArguments": "autoloadCacheAutoConfigurationValidator"}]} | [{"Type[]": {"retrieved_name": "StringUtil", "raw_body": "public class StringUtil {\n /** \n * Check whether the given {@code CharSequence} contains actual <em>text</em>.<p>More specifically, this method returns {@code true} if the{@code CharSequence} is not {@code null}, its length is greater than 0, and it contains at least one non-whitespace character. <p><pre class=\"code\"> StringUtils.hasText(null) = false StringUtils.hasText(\"\") = false StringUtils.hasText(\" \") = false StringUtils.hasText(\"12345\") = true StringUtils.hasText(\" 12345 \") = true </pre>\n * @param str the {@code CharSequence} to check (may be {@code null})\n * @return {@code true} if the {@code CharSequence} is not {@code null}, its length is greater than 0, and it does not contain whitespace only\n * @see Character#isWhitespace\n */\n public static boolean hasText( CharSequence str);\n /** \n * Check whether the given {@code String} contains actual <em>text</em>.<p>More specifically, this method returns {@code true} if the{@code String} is not {@code null}, its length is greater than 0, and it contains at least one non-whitespace character.\n * @param str the {@code String} to check (may be {@code null})\n * @return {@code true} if the {@code String} is not {@code null}, its length is greater than 0, and it does not contain whitespace only\n * @see #hasText(CharSequence)\n */\n public static boolean hasText( String str);\n private static boolean containsText( CharSequence str);\n}\n", "raw_body_no_cmt": "public class StringUtil {\n public static boolean hasText( CharSequence str);\n public static boolean hasText( String str);\n private static boolean containsText( CharSequence str);\n}\n"}}, {"Class<?>": {"retrieved_name": "KryoClassRegistration", "raw_body": "/** \n * kryo class register\n * @author stevie.wong\n */\npublic interface KryoClassRegistration {\n /** \n * \u6ce8\u518c\u7c7b\n * @param kryo see {@link Kryo}\n */\n void register( Kryo kryo);\n}\n", "raw_body_no_cmt": "public interface KryoClassRegistration {\n void register( Kryo kryo);\n}\n"}}] | [] | [{"validateConstructorArguments": {"retrieved_name": "autoloadCacheAutoConfigurationValidator", "raw_body": "@Bean(name=VALIDATOR_BEAN_NAME) public CacheManagerValidator autoloadCacheAutoConfigurationValidator(){\n return new CacheManagerValidator();\n}\n"}}] |
|
javamelody_javamelody | javamelody/javamelody-core/src/main/java/net/bull/javamelody/JspWrapper.java | HttpRequestWrapper | startAsync | class HttpRequestWrapper extends HttpServletRequestWrapper {
private final HttpServletResponse response;
/**
* Constructs a request object wrapping the given request.
* @param request HttpServletRequest
* @param response HttpServletResponse
*/
HttpRequestWrapper(HttpServletRequest request, HttpServletResponse response) {
super(request);
this.response = response;
}
/** {@inheritDoc} */
@Override
public RequestDispatcher getRequestDispatcher(String path) {
final RequestDispatcher requestDispatcher = super.getRequestDispatcher(path);
if (requestDispatcher == null) {
return null;
}
// il n'est pas dit que path soit non null
final InvocationHandler invocationHandler = new JspWrapper(String.valueOf(path),
requestDispatcher);
return JdbcWrapper.createProxy(requestDispatcher, invocationHandler);
}
@Override
public AsyncContext startAsync() {<FILL_FUNCTION_BODY>}
} |
// issue 217: after MonitoringFilter.doFilter, response is instance of CounterServletResponseWrapper,
// and if response.getWriter() has been called before calling request.startAsync(),
// then asyncContext.getResponse() should return the instance of CounterServletResponseWrapper
// and not the initial response without the wrapper,
// otherwise asyncContext.getResponse().getWriter() will throw something like
// "IllegalStateException: getOutputStream() has already been called for this response"
return super.startAsync(this, response);
|
return response.startAsync();
| [
"HttpServletResponse"
] | [
"startAsync"
] | [
"HttpServletResponse"
] | [] | {
"methods": [
"startAsync"
],
"similar_methods": [
"startAsync"
],
"types": [
"HttpServletResponse"
]
} | /**
* Implémentation de FilterServletResponseWrapper qui fonctionne avec le HtmlInjectorResponseStream.
* @author Emeric Vernat
*/
class HtmlInjectorServletResponseWrapper extends FilterServletResponseWrapper {
private static final String INJECTOR_WRAPPED_REQUEST_KEY="javamelody.injectorWrapped";
private final HtmlToInject htmlToInject;
/**
* Constructeur qui crée un adapteur de HttpServletResponse wrappant la response spécifiée.
* @param request HttpServletRequest
* @param response HttpServletResponse
* @param htmlToInject HtmlToInject
*/
HtmlInjectorServletResponseWrapper( HttpServletRequest request, HttpServletResponse response, HtmlToInject htmlToInject);
static boolean acceptsRequest( HttpServletRequest request);
/**
* {@inheritDoc}
*/
@Override public ServletOutputStream createOutputStream() throws IOException;
/**
* {@inheritDoc}
*/
@Override public void setContentType( String contentType);
private boolean isContentTypeHtml();
/**
* Ne fait rien
* @param length int
*/
@Override public void setContentLength( int length);
/**
* Ne fait rien
* @param length long
*/
@Override public void setContentLengthLong( long length);
@Override public void addHeader( String name, String value);
@Override public void addIntHeader( String name, int value);
@Override public void setHeader( String name, String value);
@Override public void setIntHeader( String name, int value);
}
private boolean matchesAsync(Method method,Class<?> targetClass){
return ASYNC_CLASS != null && (targetClass.isAnnotationPresent(ASYNC_CLASS) || method.getDeclaringClass().isAnnotationPresent(ASYNC_CLASS) || method.isAnnotationPresent(ASYNC_CLASS));
}
private boolean matchesAsync(Method method,Class<?> targetClass){
return ASYNC_CLASS != null && (targetClass.isAnnotationPresent(ASYNC_CLASS) || method.getDeclaringClass().isAnnotationPresent(ASYNC_CLASS) || method.isAnnotationPresent(ASYNC_CLASS));
}
| class HtmlInjectorServletResponseWrapper extends FilterServletResponseWrapper {
private static final String INJECTOR_WRAPPED_REQUEST_KEY="javamelody.injectorWrapped";
private final HtmlToInject htmlToInject;
HtmlInjectorServletResponseWrapper( HttpServletRequest request, HttpServletResponse response, HtmlToInject htmlToInject);
static boolean acceptsRequest( HttpServletRequest request);
public ServletOutputStream createOutputStream() throws IOException;
public void setContentType( String contentType);
private boolean isContentTypeHtml();
public void setContentLength( int length);
public void setContentLengthLong( long length);
public void addHeader( String name, String value);
public void addIntHeader( String name, int value);
public void setHeader( String name, String value);
public void setIntHeader( String name, int value);
}
private boolean matchesAsync(Method method,Class<?> targetClass){
return ASYNC_CLASS != null && (targetClass.isAnnotationPresent(ASYNC_CLASS) || method.getDeclaringClass().isAnnotationPresent(ASYNC_CLASS) || method.isAnnotationPresent(ASYNC_CLASS));
}
private boolean matchesAsync(Method method,Class<?> targetClass){
return ASYNC_CLASS != null && (targetClass.isAnnotationPresent(ASYNC_CLASS) || method.getDeclaringClass().isAnnotationPresent(ASYNC_CLASS) || method.isAnnotationPresent(ASYNC_CLASS));
}
| {"types": [{"HttpServletResponse": "HtmlInjectorServletResponseWrapper"}], "methods": [{"startAsync": "matchesAsync"}], "similar_methods": [{"startAsync": "matchesAsync"}]} | [{"HttpServletResponse": {"retrieved_name": "HtmlInjectorServletResponseWrapper", "raw_body": "/** \n * Impl\u00e9mentation de FilterServletResponseWrapper qui fonctionne avec le HtmlInjectorResponseStream.\n * @author Emeric Vernat\n */\nclass HtmlInjectorServletResponseWrapper extends FilterServletResponseWrapper {\n private static final String INJECTOR_WRAPPED_REQUEST_KEY=\"javamelody.injectorWrapped\";\n private final HtmlToInject htmlToInject;\n /** \n * Constructeur qui cr\u00e9e un adapteur de HttpServletResponse wrappant la response sp\u00e9cifi\u00e9e.\n * @param request HttpServletRequest\n * @param response HttpServletResponse\n * @param htmlToInject HtmlToInject\n */\n HtmlInjectorServletResponseWrapper( HttpServletRequest request, HttpServletResponse response, HtmlToInject htmlToInject);\n static boolean acceptsRequest( HttpServletRequest request);\n /** \n * {@inheritDoc} \n */\n @Override public ServletOutputStream createOutputStream() throws IOException;\n /** \n * {@inheritDoc} \n */\n @Override public void setContentType( String contentType);\n private boolean isContentTypeHtml();\n /** \n * Ne fait rien\n * @param length int\n */\n @Override public void setContentLength( int length);\n /** \n * Ne fait rien\n * @param length long\n */\n @Override public void setContentLengthLong( long length);\n @Override public void addHeader( String name, String value);\n @Override public void addIntHeader( String name, int value);\n @Override public void setHeader( String name, String value);\n @Override public void setIntHeader( String name, int value);\n}\n", "raw_body_no_cmt": "class HtmlInjectorServletResponseWrapper extends FilterServletResponseWrapper {\n private static final String INJECTOR_WRAPPED_REQUEST_KEY=\"javamelody.injectorWrapped\";\n private final HtmlToInject htmlToInject;\n HtmlInjectorServletResponseWrapper( HttpServletRequest request, HttpServletResponse response, HtmlToInject htmlToInject);\n static boolean acceptsRequest( HttpServletRequest request);\n public ServletOutputStream createOutputStream() throws IOException;\n public void setContentType( String contentType);\n private boolean isContentTypeHtml();\n public void setContentLength( int length);\n public void setContentLengthLong( long length);\n public void addHeader( String name, String value);\n public void addIntHeader( String name, int value);\n public void setHeader( String name, String value);\n public void setIntHeader( String name, int value);\n}\n"}}] | [{"startAsync": {"retrieved_name": "matchesAsync", "raw_body": "private boolean matchesAsync(Method method,Class<?> targetClass){\n return ASYNC_CLASS != null && (targetClass.isAnnotationPresent(ASYNC_CLASS) || method.getDeclaringClass().isAnnotationPresent(ASYNC_CLASS) || method.isAnnotationPresent(ASYNC_CLASS));\n}\n"}}] | [{"startAsync": {"retrieved_name": "matchesAsync", "raw_body": "private boolean matchesAsync(Method method,Class<?> targetClass){\n return ASYNC_CLASS != null && (targetClass.isAnnotationPresent(ASYNC_CLASS) || method.getDeclaringClass().isAnnotationPresent(ASYNC_CLASS) || method.isAnnotationPresent(ASYNC_CLASS));\n}\n"}}] |
|
houbb_sensitive-word | sensitive-word/src/main/java/com/github/houbb/sensitive/word/support/format/WordFormatInit.java | WordFormatInit | format | class WordFormatInit implements IWordFormat {
/**
* 初始化列表
*
* @param pipeline 当前列表泳道
* @since 0.0.13
*/
protected abstract void init(final Pipeline<IWordFormat> pipeline);
@Override
public char format(char original, IWordContext context) {<FILL_FUNCTION_BODY>}
} |
Pipeline<IWordFormat> pipeline = new DefaultPipeline<>();
init(pipeline);
char result = original;
// 循环执行
List<IWordFormat> charFormats = pipeline.list();
for(IWordFormat charFormat : charFormats) {
result = charFormat.format(result, context);
}
return result;
|
return original;
| [
"IWordContext"
] | [] | [
"Pipeline<IWordFormat>",
"IWordContext",
"IWordFormat",
"List<IWordFormat>"
] | [
"list",
"format"
] | {
"methods": [],
"similar_methods": [
"format"
],
"types": [
"IWordContext"
]
} | /**
* @author binbin.hou
* @since 0.0.4
*/
public interface IWordContext {
/**
* 是否忽略大小写
* @return 是否
* @since 0.0.4
*/
boolean ignoreCase();
/**
* 是否忽略半角圆角
* @return 是否
* @since 0.0.4
*/
boolean ignoreWidth();
/**
* 是否忽略数字格式
* @return 是否
* @since 0.0.5
*/
boolean ignoreNumStyle();
/**
* 设置是否忽略大小写
* @param ignoreCase 是否忽略大小写
* @return this
* @since 0.0.4
*/
IWordContext ignoreCase( boolean ignoreCase);
/**
* 设置是否忽略半角圆角
* @param ignoreWidth 是否忽略半角圆角
* @return this
* @since 0.0.4
*/
IWordContext ignoreWidth( boolean ignoreWidth);
/**
* 设置是否忽略半角圆角
* @param ignoreNumStyle 是否忽略半角圆角
* @return this
* @since 0.0.5
*/
IWordContext ignoreNumStyle( boolean ignoreNumStyle);
/**
* 忽略中文繁简体格式
* @return 是否
* @since 0.0.6
*/
boolean ignoreChineseStyle();
/**
* 设置是否忽略中文繁简体格式
* @param ignoreChineseStyle 是否忽略
* @return this
* @since 0.0.6
*/
IWordContext ignoreChineseStyle( final boolean ignoreChineseStyle);
/**
* 是否启用单词
* @return 是否
*/
boolean enableWordCheck();
/**
* 设置是否启用单词
* @param enableWordCheck 是否
* @return 结果
*/
IWordContext enableWordCheck( boolean enableWordCheck);
/**
* 敏感数字检测
* @return 数字检测
* @since 0.0.5
*/
boolean enableNumCheck();
/**
* 设置敏感数字检测
* @param enableNumCheck 数字格式检测
* @return this
* @since 0.0.5
*/
IWordContext enableNumCheck( final boolean enableNumCheck);
/**
* 是否进行邮箱检测
* @return this
* @since 0.0.9
*/
boolean enableEmailCheck();
/**
* 设置敏感邮箱检测
* @param enableEmailCheck 是否检测
* @return this
* @since 0.0.9
*/
IWordContext enableEmailCheck( final boolean enableEmailCheck);
/**
* 敏感链接检测
* @return 是否启用
* @since 0.
*/
boolean enableUrlCheck();
/**
* 设置敏感邮箱检测
* @param enableUrlCheck 是否检测
* @return this
* @since 0.0.9
*/
IWordContext enableUrlCheck( final boolean enableUrlCheck);
/**
* 忽略英文的写法
* @return 数字检测
* @since 0.0.6
*/
boolean ignoreEnglishStyle();
/**
* 设置忽略英文的写法
* @param ignoreEnglishStyle 是否忽略
* @return this
* @since 0.0.6
*/
IWordContext ignoreEnglishStyle( final boolean ignoreEnglishStyle);
/**
* 忽略重复词
* @return 是否忽略
* @since 0.0.7
*/
boolean ignoreRepeat();
/**
* 设置忽略重复词
* @param ignoreRepeat 是否忽略
* @return this
* @since 0.0.7
*/
IWordContext ignoreRepeat( final boolean ignoreRepeat);
/**
* 敏感数字检测
* @return 数字检测
* @since 0.2.1
*/
int sensitiveCheckNumLen();
/**
* 设置敏感数字检测长度
* @param sensitiveCheckNumLen 数字格式检测长度
* @return this
* @since 0.2.1
*/
IWordContext sensitiveCheckNumLen( final int sensitiveCheckNumLen);
/**
* 设置检测策略
* @param sensitiveCheck 检测策略
* @return this
* @since 0.3.0
*/
IWordContext sensitiveCheck( final IWordCheck sensitiveCheck);
/**
* 获取检测策略
* @return 检测策略
* @since 0.3.0
*/
IWordCheck sensitiveCheck();
/**
* 设置敏感词替换策略
* @param wordReplace 策略
* @return this
* @since 0.3.0
*/
IWordContext wordReplace( final IWordReplace wordReplace);
/**
* 敏感词替换策略
* @return 替换策略
* @since 0.3.0
*/
IWordReplace wordReplace();
/**
* 设置统一的字符处理
* @param wordFormat 字符处理
* @return 结果
* @since 0.3.0
*/
IWordContext wordFormat( final IWordFormat wordFormat);
/**
* 获取格式化策略
* @return 策略
* @since 0.3.0
*/
IWordFormat wordFormat();
/**
* 获取 wordMap 策略
* @return 策略
* @since 0.3.2
*/
IWordData wordData();
/**
* 设置 wordMap 策略
* @param wordMap 策略
* @return this
* @since 0.3.2
*/
IWordContext wordData( IWordData wordMap);
IWordTag wordTag();
SensitiveWordContext wordTag( IWordTag wordTag);
ISensitiveWordCharIgnore charIgnore();
SensitiveWordContext charIgnore( ISensitiveWordCharIgnore charIgnore);
IWordResultCondition wordResultCondition();
SensitiveWordContext wordResultCondition( IWordResultCondition wordResultCondition);
}
@Override public char format(char original,IWordContext context){
return Character.toLowerCase(original);
}
| public interface IWordContext {
boolean ignoreCase();
boolean ignoreWidth();
boolean ignoreNumStyle();
IWordContext ignoreCase( boolean ignoreCase);
IWordContext ignoreWidth( boolean ignoreWidth);
IWordContext ignoreNumStyle( boolean ignoreNumStyle);
boolean ignoreChineseStyle();
IWordContext ignoreChineseStyle( final boolean ignoreChineseStyle);
boolean enableWordCheck();
IWordContext enableWordCheck( boolean enableWordCheck);
boolean enableNumCheck();
IWordContext enableNumCheck( final boolean enableNumCheck);
boolean enableEmailCheck();
IWordContext enableEmailCheck( final boolean enableEmailCheck);
boolean enableUrlCheck();
IWordContext enableUrlCheck( final boolean enableUrlCheck);
boolean ignoreEnglishStyle();
IWordContext ignoreEnglishStyle( final boolean ignoreEnglishStyle);
boolean ignoreRepeat();
IWordContext ignoreRepeat( final boolean ignoreRepeat);
int sensitiveCheckNumLen();
IWordContext sensitiveCheckNumLen( final int sensitiveCheckNumLen);
IWordContext sensitiveCheck( final IWordCheck sensitiveCheck);
IWordCheck sensitiveCheck();
IWordContext wordReplace( final IWordReplace wordReplace);
IWordReplace wordReplace();
IWordContext wordFormat( final IWordFormat wordFormat);
IWordFormat wordFormat();
IWordData wordData();
IWordContext wordData( IWordData wordMap);
IWordTag wordTag();
SensitiveWordContext wordTag( IWordTag wordTag);
ISensitiveWordCharIgnore charIgnore();
SensitiveWordContext charIgnore( ISensitiveWordCharIgnore charIgnore);
IWordResultCondition wordResultCondition();
SensitiveWordContext wordResultCondition( IWordResultCondition wordResultCondition);
}
@Override public char format(char original,IWordContext context){
return Character.toLowerCase(original);
}
| {"types": [{"IWordContext": "IWordContext"}], "similar_methods": [{"format": "format"}]} | [{"IWordContext": {"retrieved_name": "IWordContext", "raw_body": "/** \n * @author binbin.hou\n * @since 0.0.4\n */\npublic interface IWordContext {\n /** \n * \u662f\u5426\u5ffd\u7565\u5927\u5c0f\u5199\n * @return \u662f\u5426\n * @since 0.0.4\n */\n boolean ignoreCase();\n /** \n * \u662f\u5426\u5ffd\u7565\u534a\u89d2\u5706\u89d2\n * @return \u662f\u5426\n * @since 0.0.4\n */\n boolean ignoreWidth();\n /** \n * \u662f\u5426\u5ffd\u7565\u6570\u5b57\u683c\u5f0f\n * @return \u662f\u5426\n * @since 0.0.5\n */\n boolean ignoreNumStyle();\n /** \n * \u8bbe\u7f6e\u662f\u5426\u5ffd\u7565\u5927\u5c0f\u5199\n * @param ignoreCase \u662f\u5426\u5ffd\u7565\u5927\u5c0f\u5199\n * @return this\n * @since 0.0.4\n */\n IWordContext ignoreCase( boolean ignoreCase);\n /** \n * \u8bbe\u7f6e\u662f\u5426\u5ffd\u7565\u534a\u89d2\u5706\u89d2\n * @param ignoreWidth \u662f\u5426\u5ffd\u7565\u534a\u89d2\u5706\u89d2\n * @return this\n * @since 0.0.4\n */\n IWordContext ignoreWidth( boolean ignoreWidth);\n /** \n * \u8bbe\u7f6e\u662f\u5426\u5ffd\u7565\u534a\u89d2\u5706\u89d2\n * @param ignoreNumStyle \u662f\u5426\u5ffd\u7565\u534a\u89d2\u5706\u89d2\n * @return this\n * @since 0.0.5\n */\n IWordContext ignoreNumStyle( boolean ignoreNumStyle);\n /** \n * \u5ffd\u7565\u4e2d\u6587\u7e41\u7b80\u4f53\u683c\u5f0f\n * @return \u662f\u5426\n * @since 0.0.6\n */\n boolean ignoreChineseStyle();\n /** \n * \u8bbe\u7f6e\u662f\u5426\u5ffd\u7565\u4e2d\u6587\u7e41\u7b80\u4f53\u683c\u5f0f\n * @param ignoreChineseStyle \u662f\u5426\u5ffd\u7565\n * @return this\n * @since 0.0.6\n */\n IWordContext ignoreChineseStyle( final boolean ignoreChineseStyle);\n /** \n * \u662f\u5426\u542f\u7528\u5355\u8bcd\n * @return \u662f\u5426\n */\n boolean enableWordCheck();\n /** \n * \u8bbe\u7f6e\u662f\u5426\u542f\u7528\u5355\u8bcd\n * @param enableWordCheck \u662f\u5426\n * @return \u7ed3\u679c\n */\n IWordContext enableWordCheck( boolean enableWordCheck);\n /** \n * \u654f\u611f\u6570\u5b57\u68c0\u6d4b\n * @return \u6570\u5b57\u68c0\u6d4b\n * @since 0.0.5\n */\n boolean enableNumCheck();\n /** \n * \u8bbe\u7f6e\u654f\u611f\u6570\u5b57\u68c0\u6d4b\n * @param enableNumCheck \u6570\u5b57\u683c\u5f0f\u68c0\u6d4b\n * @return this\n * @since 0.0.5\n */\n IWordContext enableNumCheck( final boolean enableNumCheck);\n /** \n * \u662f\u5426\u8fdb\u884c\u90ae\u7bb1\u68c0\u6d4b\n * @return this\n * @since 0.0.9\n */\n boolean enableEmailCheck();\n /** \n * \u8bbe\u7f6e\u654f\u611f\u90ae\u7bb1\u68c0\u6d4b\n * @param enableEmailCheck \u662f\u5426\u68c0\u6d4b\n * @return this\n * @since 0.0.9\n */\n IWordContext enableEmailCheck( final boolean enableEmailCheck);\n /** \n * \u654f\u611f\u94fe\u63a5\u68c0\u6d4b\n * @return \u662f\u5426\u542f\u7528\n * @since 0.\n */\n boolean enableUrlCheck();\n /** \n * \u8bbe\u7f6e\u654f\u611f\u90ae\u7bb1\u68c0\u6d4b\n * @param enableUrlCheck \u662f\u5426\u68c0\u6d4b\n * @return this\n * @since 0.0.9\n */\n IWordContext enableUrlCheck( final boolean enableUrlCheck);\n /** \n * \u5ffd\u7565\u82f1\u6587\u7684\u5199\u6cd5\n * @return \u6570\u5b57\u68c0\u6d4b\n * @since 0.0.6\n */\n boolean ignoreEnglishStyle();\n /** \n * \u8bbe\u7f6e\u5ffd\u7565\u82f1\u6587\u7684\u5199\u6cd5\n * @param ignoreEnglishStyle \u662f\u5426\u5ffd\u7565\n * @return this\n * @since 0.0.6\n */\n IWordContext ignoreEnglishStyle( final boolean ignoreEnglishStyle);\n /** \n * \u5ffd\u7565\u91cd\u590d\u8bcd\n * @return \u662f\u5426\u5ffd\u7565\n * @since 0.0.7\n */\n boolean ignoreRepeat();\n /** \n * \u8bbe\u7f6e\u5ffd\u7565\u91cd\u590d\u8bcd\n * @param ignoreRepeat \u662f\u5426\u5ffd\u7565\n * @return this\n * @since 0.0.7\n */\n IWordContext ignoreRepeat( final boolean ignoreRepeat);\n /** \n * \u654f\u611f\u6570\u5b57\u68c0\u6d4b\n * @return \u6570\u5b57\u68c0\u6d4b\n * @since 0.2.1\n */\n int sensitiveCheckNumLen();\n /** \n * \u8bbe\u7f6e\u654f\u611f\u6570\u5b57\u68c0\u6d4b\u957f\u5ea6\n * @param sensitiveCheckNumLen \u6570\u5b57\u683c\u5f0f\u68c0\u6d4b\u957f\u5ea6\n * @return this\n * @since 0.2.1\n */\n IWordContext sensitiveCheckNumLen( final int sensitiveCheckNumLen);\n /** \n * \u8bbe\u7f6e\u68c0\u6d4b\u7b56\u7565\n * @param sensitiveCheck \u68c0\u6d4b\u7b56\u7565\n * @return this\n * @since 0.3.0\n */\n IWordContext sensitiveCheck( final IWordCheck sensitiveCheck);\n /** \n * \u83b7\u53d6\u68c0\u6d4b\u7b56\u7565\n * @return \u68c0\u6d4b\u7b56\u7565\n * @since 0.3.0\n */\n IWordCheck sensitiveCheck();\n /** \n * \u8bbe\u7f6e\u654f\u611f\u8bcd\u66ff\u6362\u7b56\u7565\n * @param wordReplace \u7b56\u7565\n * @return this\n * @since 0.3.0\n */\n IWordContext wordReplace( final IWordReplace wordReplace);\n /** \n * \u654f\u611f\u8bcd\u66ff\u6362\u7b56\u7565\n * @return \u66ff\u6362\u7b56\u7565\n * @since 0.3.0\n */\n IWordReplace wordReplace();\n /** \n * \u8bbe\u7f6e\u7edf\u4e00\u7684\u5b57\u7b26\u5904\u7406\n * @param wordFormat \u5b57\u7b26\u5904\u7406\n * @return \u7ed3\u679c\n * @since 0.3.0\n */\n IWordContext wordFormat( final IWordFormat wordFormat);\n /** \n * \u83b7\u53d6\u683c\u5f0f\u5316\u7b56\u7565\n * @return \u7b56\u7565\n * @since 0.3.0\n */\n IWordFormat wordFormat();\n /** \n * \u83b7\u53d6 wordMap \u7b56\u7565\n * @return \u7b56\u7565\n * @since 0.3.2\n */\n IWordData wordData();\n /** \n * \u8bbe\u7f6e wordMap \u7b56\u7565\n * @param wordMap \u7b56\u7565\n * @return this\n * @since 0.3.2\n */\n IWordContext wordData( IWordData wordMap);\n IWordTag wordTag();\n SensitiveWordContext wordTag( IWordTag wordTag);\n ISensitiveWordCharIgnore charIgnore();\n SensitiveWordContext charIgnore( ISensitiveWordCharIgnore charIgnore);\n IWordResultCondition wordResultCondition();\n SensitiveWordContext wordResultCondition( IWordResultCondition wordResultCondition);\n}\n", "raw_body_no_cmt": "public interface IWordContext {\n boolean ignoreCase();\n boolean ignoreWidth();\n boolean ignoreNumStyle();\n IWordContext ignoreCase( boolean ignoreCase);\n IWordContext ignoreWidth( boolean ignoreWidth);\n IWordContext ignoreNumStyle( boolean ignoreNumStyle);\n boolean ignoreChineseStyle();\n IWordContext ignoreChineseStyle( final boolean ignoreChineseStyle);\n boolean enableWordCheck();\n IWordContext enableWordCheck( boolean enableWordCheck);\n boolean enableNumCheck();\n IWordContext enableNumCheck( final boolean enableNumCheck);\n boolean enableEmailCheck();\n IWordContext enableEmailCheck( final boolean enableEmailCheck);\n boolean enableUrlCheck();\n IWordContext enableUrlCheck( final boolean enableUrlCheck);\n boolean ignoreEnglishStyle();\n IWordContext ignoreEnglishStyle( final boolean ignoreEnglishStyle);\n boolean ignoreRepeat();\n IWordContext ignoreRepeat( final boolean ignoreRepeat);\n int sensitiveCheckNumLen();\n IWordContext sensitiveCheckNumLen( final int sensitiveCheckNumLen);\n IWordContext sensitiveCheck( final IWordCheck sensitiveCheck);\n IWordCheck sensitiveCheck();\n IWordContext wordReplace( final IWordReplace wordReplace);\n IWordReplace wordReplace();\n IWordContext wordFormat( final IWordFormat wordFormat);\n IWordFormat wordFormat();\n IWordData wordData();\n IWordContext wordData( IWordData wordMap);\n IWordTag wordTag();\n SensitiveWordContext wordTag( IWordTag wordTag);\n ISensitiveWordCharIgnore charIgnore();\n SensitiveWordContext charIgnore( ISensitiveWordCharIgnore charIgnore);\n IWordResultCondition wordResultCondition();\n SensitiveWordContext wordResultCondition( IWordResultCondition wordResultCondition);\n}\n"}}] | [] | [{"format": {"retrieved_name": "format", "raw_body": "@Override public char format(char original,IWordContext context){\n return Character.toLowerCase(original);\n}\n"}}] |
|
orientechnologies_orientdb | orientdb/core/src/main/java/com/orientechnologies/common/collection/closabledictionary/OClosableLRUList.java | OClosableLRUList | remove | class OClosableLRUList<K, V extends OClosableItem> implements Iterable<OClosableEntry<K, V>> {
private int size;
private OClosableEntry<K, V> head;
private OClosableEntry<K, V> tail;
void remove(OClosableEntry<K, V> entry) {<FILL_FUNCTION_BODY>}
boolean contains(OClosableEntry<K, V> entry) {
return entry.getNext() != null || entry.getPrev() != null || entry == head;
}
void moveToTheTail(OClosableEntry<K, V> entry) {
if (tail == entry) {
assert entry.getNext() == null;
return;
}
final OClosableEntry<K, V> next = entry.getNext();
final OClosableEntry<K, V> prev = entry.getPrev();
boolean newEntry = !(next != null || prev != null || entry == head);
if (prev != null) {
assert prev.getNext() == entry;
}
if (next != null) {
assert 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) size++;
}
int size() {
return size;
}
OClosableEntry<K, V> poll() {
if (head == null) return null;
final OClosableEntry<K, V> entry = head;
OClosableEntry<K, V> 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--;
return entry;
}
/** @return Iterator to iterate from head to the tail. */
public Iterator<OClosableEntry<K, V>> iterator() {
return new Iterator<OClosableEntry<K, V>>() {
private OClosableEntry<K, V> next = head;
private OClosableEntry<K, V> current = null;
@Override
public boolean hasNext() {
return next != null;
}
@Override
public OClosableEntry<K, V> next() {
if (next == null) {
throw new NoSuchElementException();
}
current = next;
next = next.getNext();
return current;
}
@Override
public void remove() {
if (current == null) {
throw new IllegalStateException("Method next was not called");
}
OClosableLRUList.this.remove(current);
current = null;
}
};
}
boolean assertForwardStructure() {
if (head == null) return tail == null;
OClosableEntry<K, V> current = head;
while (current.getNext() != null) {
OClosableEntry<K, V> prev = current.getPrev();
OClosableEntry<K, V> next = current.getNext();
if (prev != null) {
assert prev.getNext() == current;
}
if (next != null) {
assert next.getPrev() == current;
}
current = current.getNext();
}
return current == tail;
}
boolean assertBackwardStructure() {
if (tail == null) return head == null;
OClosableEntry<K, V> current = tail;
while (current.getPrev() != null) {
OClosableEntry<K, V> prev = current.getPrev();
OClosableEntry<K, V> next = current.getNext();
if (prev != null) {
assert prev.getNext() == current;
}
if (next != null) {
assert next.getPrev() == current;
}
current = current.getPrev();
}
return current == head;
}
} |
final OClosableEntry<K, V> next = entry.getNext();
final OClosableEntry<K, V> prev = entry.getPrev();
if (!(next != null || prev != null || entry == head)) return;
if (prev != null) {
assert prev.getNext() == entry;
}
if (next != null) {
assert 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);
size--;
|
if (entry.getNext() != null) {
assert entry.getNext().getPrev() == entry;
}
if (entry.getPrev() != null) {
assert entry.getPrev().getNext() == entry;
}
if (entry == head) {
assert entry.getPrev() == null;
head = entry.getNext();
}
if (entry == tail) {
assert entry.getNext() == null;
tail = entry.getPrev();
}
if (entry.getPrev() != null) {
entry.getPrev().setNext(entry.getNext());
}
if (entry.getNext() != null) {
entry.getNext().setPrev(entry.getPrev());
}
entry.setNext(null);
entry.setPrev(null);
size--;
| [] | [] | [] | [] | {
"methods": [],
"similar_methods": [
"remove"
],
"types": []
} | @Override public void remove(){
if (lastReturned == null) {
throw new IllegalStateException();
}
lastReturned.remove();
lastReturned=null;
}
| @Override public void remove(){
if (lastReturned == null) {
throw new IllegalStateException();
}
lastReturned.remove();
lastReturned=null;
}
| {"similar_methods": [{"remove": "remove"}]} | [] | [] | [{"remove": {"retrieved_name": "remove", "raw_body": "@Override public void remove(){\n if (lastReturned == null) {\n throw new IllegalStateException();\n }\n lastReturned.remove();\n lastReturned=null;\n}\n"}}] |
|
mapstruct_mapstruct | mapstruct/processor/src/main/java/org/mapstruct/ap/internal/model/source/builtin/JodaLocalTimeToXmlGregorianCalendar.java | JodaLocalTimeToXmlGregorianCalendar | getImportTypes | class JodaLocalTimeToXmlGregorianCalendar extends AbstractToXmlGregorianCalendar {
private final Parameter parameter;
private final Set<Type> importTypes;
public JodaLocalTimeToXmlGregorianCalendar(TypeFactory typeFactory) {
super( typeFactory );
this.parameter = new Parameter( "dt", typeFactory.getType( JodaTimeConstants.LOCAL_TIME_FQN ) );
this.importTypes = asSet(
parameter.getType(),
typeFactory.getType( XmlConstants.JAVAX_XML_DATATYPE_CONSTANTS )
);
}
@Override
public Set<Type> getImportTypes() {<FILL_FUNCTION_BODY>}
@Override
public Parameter getParameter() {
return parameter;
}
} |
Set<Type> result = super.getImportTypes();
result.addAll( importTypes );
return result;
| /**
* @author Sjaak Derksen
*/
public abstract class AbstractToXmlGregorianCalendar extends BuiltInMethod {
private final Type returnType;
private final Set<Type> importTypes;
private final Type dataTypeFactoryType;
public AbstractToXmlGregorianCalendar( TypeFactory typeFactory);
@Override public Set<Type> getImportTypes();
@Override public Type getReturnType();
@Override public FieldReference getFieldReference();
@Override public ConstructorFragment getConstructorFragment();
}
|
return importTypes;
| [
"Set<Type>"
] | [] | [
"Set<Type>"
] | [
"addAll"
] | {
"methods": [],
"similar_methods": [
"getImportTypes"
],
"types": [
"Set<Type>"
]
} | /**
* Represents (a reference to) the type of a bean property, parameter etc. Types are managed per generated source file. Each type corresponds to a {@link TypeMirror}, i.e. there are different instances for e.g. {@code Set<String>} and{@code Set<Integer>}. <p> Allows for a unified handling of declared and primitive types and usage within templates. Instances are obtained through {@link TypeFactory}.
* @author Gunnar Morling
* @author Filip Hrisafov
*/
public class Type extends ModelElement implements Comparable<Type> {
private static final Method SEALED_PERMITTED_SUBCLASSES_METHOD;
static {
Method permittedSubclassesMethod;
try {
permittedSubclassesMethod=TypeElement.class.getMethod("getPermittedSubclasses");
}
catch ( NoSuchMethodException e) {
permittedSubclassesMethod=null;
}
SEALED_PERMITTED_SUBCLASSES_METHOD=permittedSubclassesMethod;
}
private final TypeUtils typeUtils;
private final ElementUtils elementUtils;
private final TypeFactory typeFactory;
private final AccessorNamingUtils accessorNaming;
private final TypeMirror typeMirror;
private final TypeElement typeElement;
private final List<Type> typeParameters;
private final ImplementationType implementationType;
private final Type componentType;
private final Type topLevelType;
private final String packageName;
private final String name;
private final String nameWithTopLevelTypeName;
private final String qualifiedName;
private final boolean isInterface;
private final boolean isEnumType;
private final boolean isIterableType;
private final boolean isCollectionType;
private final boolean isMapType;
private final boolean isVoid;
private final boolean isStream;
private final boolean isLiteral;
private final boolean loggingVerbose;
private final List<String> enumConstants;
private final Map<String,String> toBeImportedTypes;
private final Map<String,String> notToBeImportedTypes;
private Boolean isToBeImported;
private Map<String,ReadAccessor> readAccessors=null;
private Map<String,PresenceCheckAccessor> presenceCheckers=null;
private List<ExecutableElement> allMethods=null;
private List<VariableElement> allFields=null;
private List<Element> recordComponents=null;
private List<Accessor> setters=null;
private List<Accessor> adders=null;
private List<Accessor> alternativeTargetAccessors=null;
private Type boundingBase=null;
private List<Type> boundTypes=null;
private Type boxedEquivalent=null;
private Boolean hasAccessibleConstructor;
private final Filters filters;
public Type( TypeUtils typeUtils, ElementUtils elementUtils, TypeFactory typeFactory, AccessorNamingUtils accessorNaming, TypeMirror typeMirror, TypeElement typeElement, List<Type> typeParameters, ImplementationType implementationType, Type componentType, String packageName, String name, String qualifiedName, boolean isInterface, boolean isEnumType, boolean isIterableType, boolean isCollectionType, boolean isMapType, boolean isStreamType, Map<String,String> toBeImportedTypes, Map<String,String> notToBeImportedTypes, Boolean isToBeImported, boolean isLiteral, boolean loggingVerbose);
public TypeMirror getTypeMirror();
public TypeElement getTypeElement();
public String getPackageName();
public String getName();
/**
* Returns a String that could be used in generated code to reference to this {@link Type}.<br> <p> The first time a name is referred-to it will be marked as to be imported. For instance {@code LocalDateTime} can be one of {@code java.time.LocalDateTime} and {@code org.joda.LocalDateTime}) <p> If the {@code java.time} variant is referred to first, the {@code java.time.LocalDateTime} will be importedand the {@code org.joda} variant will be referred to with its FQN.<p> If the type is nested and its top level type is to be imported then the name including its top level type will be returned.
* @return Just the name if this {@link Type} will be imported, the name up to the top level {@link Type}(if the top level type is important, otherwise the fully-qualified name.
*/
public String createReferenceName();
public List<Type> getTypeParameters();
public Type getComponentType();
public boolean isPrimitive();
public boolean isInterface();
public boolean isEnumType();
public boolean isVoid();
public boolean isAbstract();
public boolean isString();
/**
* @return this type's enum constants in case it is an enum, an empty list otherwise.
*/
public List<String> getEnumConstants();
/**
* Returns the implementation type to be instantiated in case this type is an interface iterable, collection or map type. The type will have the correct type arguments, so if this type e.g. represents {@code Set<String>}, the implementation type is {@code HashSet<String>}.
* @return The implementation type to be instantiated in case this type is an interface iterable, collection or maptype, {@code null} otherwise.
*/
public Type getImplementationType();
public ImplementationType getImplementation();
/**
* Whether this type is a sub-type of {@link Iterable} or an array type.
* @return {@code true} if this type is a sub-type of {@link Iterable} or an array type, {@code false} otherwise.
*/
public boolean isIterableType();
/**
* Whether this type is a sub-type of {@link Iterable}, {@link java.util.stream.Stream} or an array type
* @return {@code true} if this type is a sub-type of{@link Iterable}, {@link java.util.stream.Stream} oran array type, {@code false} otherwise
*/
public boolean isIterableOrStreamType();
public boolean isCollectionType();
public boolean isMapType();
private boolean hasStringMapSignature();
public boolean isCollectionOrMapType();
public boolean isArrayType();
public boolean isTypeVar();
public boolean isIntersection();
public boolean isJavaLangType();
public boolean isRecord();
/**
* Whether this type is a sub-type of {@link java.util.stream.Stream}.
* @return {@code true} it this type is a sub-type of {@link java.util.stream.Stream}, {@code false otherwise}
*/
public boolean isStreamType();
/**
* A wild card type can have two types of bounds (mutual exclusive): extends and super.
* @return true if the bound has a wild card super bound (e.g. ? super Number)
*/
public boolean hasSuperBound();
/**
* A wild card type can have two types of bounds (mutual exclusive): extends and super.
* @return true if the bound has a wild card super bound (e.g. ? extends Number)
*/
public boolean hasExtendsBound();
/**
* A type variable type can have two types of bounds (mutual exclusive): lower and upper. Note that its use is only permitted on a definition (not on the place where its used). For instance: {@code <T super Number> T map( T in)}
* @return true if the bound has a type variable lower bound (e.g. T super Number)
*/
public boolean hasLowerBound();
/**
* A type variable type can have two types of bounds (mutual exclusive): lower and upper. Note that its use is only permitted on a definition (not on the place where its used). For instance: {@code ><T extends Number> T map( T in)}
* @return true if the bound has a type variable upper bound (e.g. T extends Number)
*/
public boolean hasUpperBound();
public String getFullyQualifiedName();
/**
* @return The name of this type as to be used within import statements.
*/
public String getImportName();
@Override public Set<Type> getImportTypes();
protected boolean isTopLevelTypeToBeImported();
/**
* Whether this type is to be imported by means of an import statement in the currently generated source file (it can be referenced in the generated source using its simple name) or not (referenced using the FQN).
* @return {@code true} if the type is imported, {@code false} otherwise.
*/
public boolean isToBeImported();
private boolean shouldUseSimpleName();
public Type erasure();
public Type withoutBounds();
private Type replaceGeneric( Type oldGenericType, Type newType);
/**
* Whether this type is assignable to the given other type, considering the "extends / upper bounds" as well.
* @param other The other type.
* @return {@code true} if and only if this type is assignable to the given other type.
*/
public boolean isAssignableTo( Type other);
/**
* Whether this type is raw assignable to the given other type. We can't make a verdict on typevars, they need to be resolved first.
* @param other The other type.
* @return {@code true} if and only if this type is assignable to the given other type.
*/
public boolean isRawAssignableTo( Type other);
/**
* removes any bounds from this type.
* @return the raw type
*/
public Type asRawType();
public ReadAccessor getReadAccessor( String propertyName, boolean allowedMapToBean);
public PresenceCheckAccessor getPresenceChecker( String propertyName);
/**
* getPropertyReadAccessors
* @return an unmodifiable map of all read accessors (including 'is' for booleans), indexed by property name
*/
public Map<String,ReadAccessor> getPropertyReadAccessors();
/**
* getPropertyPresenceCheckers
* @return an unmodifiable map of all presence checkers, indexed by property name
*/
public Map<String,PresenceCheckAccessor> getPropertyPresenceCheckers();
/**
* getPropertyWriteAccessors returns a map of the write accessors according to the CollectionMappingStrategy. These accessors include: <ul> <li>setters, the obvious candidate :-), {@link #getSetters() }</li> <li>readAccessors, for collections that do not have a setter, e.g. for JAXB generated collection attributes {@link #getPropertyReadAccessors() }</li> <li>adders, typically for from table generated entities, {@link #getAdders() }</li> </ul>
* @param cmStrategy collection mapping strategy
* @return an unmodifiable map of all write accessors indexed by property name
*/
public Map<String,Accessor> getPropertyWriteAccessors( CollectionMappingStrategyGem cmStrategy);
public List<Element> getRecordComponents();
private Type determinePreferredType( Accessor readAccessor);
private Type determineTargetType( Accessor candidate);
private List<ExecutableElement> getAllMethods();
private List<VariableElement> getAllFields();
private <T>List<T> nullSafeTypeElementListConversion( Function<TypeElement,List<T>> conversionFunction);
private String getPropertyName( Accessor accessor);
private String getPropertyName( ExecutableElement element);
/**
* Tries to find an addMethod in this type for given collection property in this type. Matching occurs on: <ol> <li>The generic type parameter type of the collection should match the adder method argument</li> <li>When there are more candidates, property name is made singular (as good as is possible). This routine looks for a matching add method name.</li> <li>The singularization rules of Dali are used to make a property name singular. This routine looks for a matching add method name.</li> </ol>
* @param collectionProperty property type (assumed collection) to find the adder method for
* @param pluralPropertyName the property name (assumed plural)
* @return corresponding adder method for getter when present
*/
private Accessor getAdderForType( Type collectionProperty, String pluralPropertyName);
/**
* Returns all accessor candidates that start with "add" and have exactly one argument whose type matches the collection or stream property's type argument.
* @param property the collection or stream property
* @param superclass the superclass to use for type argument lookup
* @return accessor candidates
*/
private List<Accessor> getAccessorCandidates( Type property, Class<?> superclass);
private TypeMirror boxed( TypeMirror possiblePrimitive);
/**
* getSetters
* @return an unmodifiable list of all setters
*/
private List<Accessor> getSetters();
/**
* Alternative accessors could be a getter for a collection / map. By means of the {@link Collection#addAll(Collection) } or {@link Map#putAll(Map)} this getter can still be used astargetAccessor. JAXB XJC tool generates such constructs. This method can be extended when new cases come along. getAdders
* @return an unmodifiable list of all adders
*/
private List<Accessor> getAdders();
/**
* Alternative accessors could be a getter for a collection. By means of the {@link java.util.Collection#addAll(java.util.Collection) } this getter can stillbe used as targetAccessor. JAXB XJC tool generates such constructs. This method can be extended when new cases come along.
* @return an unmodifiable list of alternative target accessors.
*/
private List<Accessor> getAlternativeTargetAccessors();
private boolean correspondingSetterMethodExists( Accessor getterMethod, List<Accessor> setterMethods);
private boolean isCollectionOrMapOrStream( Accessor getterMethod);
private boolean isCollection( TypeMirror candidate);
private boolean isStream( TypeMirror candidate);
private boolean isMap( TypeMirror candidate);
private boolean isSubType( TypeMirror candidate, Class<?> clazz);
/**
* Returns the length of the shortest path in the type hierarchy between this type and the specified other type. Returns {@code -1} if this type is not assignable to the other type. Returns {@code 0} if this type is equal tothe other type. Returns {@code 1}, if the other type is a direct super type of this type, and so on.
* @param assignableOther the other type
* @return the length of the shortest path in the type hierarchy between this type and the specified other type
*/
public int distanceTo( Type assignableOther);
private int distanceTo( TypeMirror base, TypeMirror targetType);
/**
* @param type the type declaring the method
* @param method the method to check
* @return Whether this type can access the given method declared on the given type.
*/
public boolean canAccess( Type type, ExecutableElement method);
/**
* @return A valid Java expression most suitable for representing null - useful for dealing with primitives fromFTL.
*/
public String getNull();
public String getSensibleDefault();
@Override public int hashCode();
@Override public boolean equals( Object obj);
@Override public int compareTo( Type o);
@Override public String toString();
/**
* @return a string representation of the type for use in messages
*/
public String describe();
/**
* @return an identification that can be used as part in a forged method name.
*/
public String getIdentification();
/**
* Establishes the type bound: <ol> <li> {@code <? extends Number>}, returns Number</li> <li> {@code <? super Number>}, returns Number</li> <li> {@code <?>}, returns Object</li> <li> {@code <T extends Number>, returns Number}</li> </ol>
* @return the bound for this parameter
*/
public Type getTypeBound();
public List<Type> getTypeBounds();
public boolean hasAccessibleConstructor();
/**
* Returns the direct supertypes of a type. The interface types, if any, will appear last in the list.
* @return the direct supertypes, or an empty list if none
*/
public List<Type> getDirectSuperTypes();
/**
* Searches for the given superclass and collects all type arguments for the given class
* @param superclass the superclass or interface the generic type arguments are searched for
* @return a list of type arguments or null, if superclass was not found
*/
public List<Type> determineTypeArguments( Class<?> superclass);
/**
* All primitive types and their corresponding boxed types are considered native.
* @return true when native.
*/
public boolean isNative();
public boolean isLiteral();
/**
* Steps through the declaredType in order to find a match for this typeVar Type. It aligns with the provided parameterized type where this typeVar type is used.<br> <br> For example:<pre> {@code this: T declaredType: JAXBElement<String> parameterizedType: JAXBElement<T> result: String this: T, T[] or ? extends T, declaredType: E.g. Callable<? extends T> parameterizedType: Callable<BigDecimal> return: BigDecimal}</pre>
* @param declared the type
* @param parameterized the parameterized type
* @return - the same type when this is not a type var in the broadest sense (T, T[], or ? extends T)<br>- the matching parameter in the parameterized type when this is a type var when found<br> - null in all other cases
*/
public ResolvedPair resolveParameterToType( Type declared, Type parameterized);
/**
* Resolves generic types using the declared and parameterized types as input.<br> <br> For example: <pre> {@code this: T declaredType: JAXBElement<T> parameterizedType: JAXBElement<Integer> result: Integer this: List<T> declaredType: JAXBElement<T> parameterizedType: JAXBElement<Integer> result: List<Integer> this: List<? extends T> declaredType: JAXBElement<? extends T> parameterizedType: JAXBElement<BigDecimal> result: List<BigDecimal> this: List<Optional<T>> declaredType: JAXBElement<T> parameterizedType: JAXBElement<BigDecimal> result: List<Optional<BigDecimal>>}</pre> It also works for partial matching.<br> <br> For example: <pre> {@code this: Map<K, V> declaredType: JAXBElement<K> parameterizedType: JAXBElement<BigDecimal> result: Map<BigDecimal, V>}</pre> It also works with multiple parameters at both sides.<br> <br> For example when reversing Key/Value for a Map: <pre> {@code this: Map<KEY, VALUE> declaredType: HashMap<VALUE, KEY> parameterizedType: HashMap<BigDecimal, String> result: Map<String, BigDecimal>}</pre> Mismatch result examples: <pre> {@code this: T declaredType: JAXBElement<Y> parameterizedType: JAXBElement<Integer> result: null this: List<T> declaredType: JAXBElement<Y> parameterizedType: JAXBElement<Integer> result: List<T>}</pre>
* @param declared the type
* @param parameterized the parameterized type
* @return - the result of {@link #resolveParameterToType(Type,Type)} when this type itself is a type var.<br>- the type but then with the matching type parameters replaced.<br> - the same type when this type does not contain matching type parameters.
*/
public Type resolveGenericTypeParameters( Type declared, Type parameterized);
public boolean isWildCardBoundByTypeVar();
public boolean isArrayTypeVar();
private static class TypeVarMatcher extends SimpleTypeVisitor8<ResolvedPair,Type> {
private final TypeFactory typeFactory;
private final Type typeToMatch;
private final TypeUtils types;
/**
* @param typeFactory factory
* @param types type utils
* @param typeToMatch the typeVar or wildcard with typeVar bound
*/
TypeVarMatcher( TypeFactory typeFactory, TypeUtils types, Type typeToMatch);
@Override public ResolvedPair visitTypeVariable( TypeVariable parameterized, Type declared);
/**
* If ? extends SomeTime equals the boundary set in typeVarToMatch (NOTE: you can't compare the wildcard itself) then return a result;
*/
@Override public ResolvedPair visitWildcard( WildcardType parameterized, Type declared);
@Override public ResolvedPair visitArray( ArrayType parameterized, Type declared);
@Override public ResolvedPair visitDeclared( DeclaredType parameterized, Type declared);
private boolean isJavaLangObject( TypeMirror type);
}
/**
* Reflects any Resolved Pair, examples are T, String ? extends T, BigDecimal T[], Integer[]
*/
public static class ResolvedPair {
public ResolvedPair( Type parameter, Type match);
/**
* parameter, e.g. T, ? extends T or T[]
*/
private Type parameter;
/**
* match, e.g. String, BigDecimal, Integer[]
*/
private Type match;
public Type getParameter();
public Type getMatch();
@Override public boolean equals( Object o);
@Override public int hashCode();
}
/**
* Gets the boxed equivalent type if the type is primitive, int will return Integer
* @return boxed equivalent
*/
public Type getBoxedEquivalent();
/**
* It strips all the {@code []} from the {@code className}. E.g. <pre> trimSimpleClassName("String[][][]") -> "String" trimSimpleClassName("String[]") -> "String" </pre>
* @param className that needs to be trimmed
* @return the trimmed {@code className}, or {@code null} if the {@code className} was {@code null}
*/
private String trimSimpleClassName( String className);
private static String nameWithTopLevelTypeName( TypeElement element, String name);
private static Type topLevelType( TypeElement typeElement, TypeFactory typeFactory);
public boolean isEnumSet();
/**
* return true if this type is a java 17+ sealed class
*/
public boolean isSealed();
/**
* return the list of permitted TypeMirrors for the java 17+ sealed class
*/
@SuppressWarnings("unchecked") public List<? extends TypeMirror> getPermittedSubclasses();
}
@Override public Set<Type> getImportTypes(){
Set<Type> types=super.getImportTypes();
for ( PropertyMapping propertyMapping : propertyMappings) {
types.addAll(propertyMapping.getImportTypes());
if (propertyMapping.isConstructorMapping()) {
types.addAll(propertyMapping.getTargetType().getImportTypes());
}
}
for ( SubclassMapping subclassMapping : subclassMappings) {
types.addAll(subclassMapping.getImportTypes());
}
if (returnTypeToConstruct != null) {
types.addAll(returnTypeToConstruct.getImportTypes());
}
if (returnTypeBuilder != null) {
types.add(returnTypeBuilder.getOwningType());
}
for ( LifecycleCallbackMethodReference reference : beforeMappingReferencesWithFinalizedReturnType) {
types.addAll(reference.getImportTypes());
}
for ( LifecycleCallbackMethodReference reference : afterMappingReferencesWithFinalizedReturnType) {
types.addAll(reference.getImportTypes());
}
return types;
}
| public class Type extends ModelElement implements Comparable<Type> {
private static final Method SEALED_PERMITTED_SUBCLASSES_METHOD;
static {
Method permittedSubclassesMethod;
try {
permittedSubclassesMethod=TypeElement.class.getMethod("getPermittedSubclasses");
}
catch ( NoSuchMethodException e) {
permittedSubclassesMethod=null;
}
SEALED_PERMITTED_SUBCLASSES_METHOD=permittedSubclassesMethod;
}
private final TypeUtils typeUtils;
private final ElementUtils elementUtils;
private final TypeFactory typeFactory;
private final AccessorNamingUtils accessorNaming;
private final TypeMirror typeMirror;
private final TypeElement typeElement;
private final List<Type> typeParameters;
private final ImplementationType implementationType;
private final Type componentType;
private final Type topLevelType;
private final String packageName;
private final String name;
private final String nameWithTopLevelTypeName;
private final String qualifiedName;
private final boolean isInterface;
private final boolean isEnumType;
private final boolean isIterableType;
private final boolean isCollectionType;
private final boolean isMapType;
private final boolean isVoid;
private final boolean isStream;
private final boolean isLiteral;
private final boolean loggingVerbose;
private final List<String> enumConstants;
private final Map<String,String> toBeImportedTypes;
private final Map<String,String> notToBeImportedTypes;
private Boolean isToBeImported;
private Map<String,ReadAccessor> readAccessors=null;
private Map<String,PresenceCheckAccessor> presenceCheckers=null;
private List<ExecutableElement> allMethods=null;
private List<VariableElement> allFields=null;
private List<Element> recordComponents=null;
private List<Accessor> setters=null;
private List<Accessor> adders=null;
private List<Accessor> alternativeTargetAccessors=null;
private Type boundingBase=null;
private List<Type> boundTypes=null;
private Type boxedEquivalent=null;
private Boolean hasAccessibleConstructor;
private final Filters filters;
public Type( TypeUtils typeUtils, ElementUtils elementUtils, TypeFactory typeFactory, AccessorNamingUtils accessorNaming, TypeMirror typeMirror, TypeElement typeElement, List<Type> typeParameters, ImplementationType implementationType, Type componentType, String packageName, String name, String qualifiedName, boolean isInterface, boolean isEnumType, boolean isIterableType, boolean isCollectionType, boolean isMapType, boolean isStreamType, Map<String,String> toBeImportedTypes, Map<String,String> notToBeImportedTypes, Boolean isToBeImported, boolean isLiteral, boolean loggingVerbose);
public TypeMirror getTypeMirror();
public TypeElement getTypeElement();
public String getPackageName();
public String getName();
public String createReferenceName();
public List<Type> getTypeParameters();
public Type getComponentType();
public boolean isPrimitive();
public boolean isInterface();
public boolean isEnumType();
public boolean isVoid();
public boolean isAbstract();
public boolean isString();
public List<String> getEnumConstants();
public Type getImplementationType();
public ImplementationType getImplementation();
public boolean isIterableType();
public boolean isIterableOrStreamType();
public boolean isCollectionType();
public boolean isMapType();
private boolean hasStringMapSignature();
public boolean isCollectionOrMapType();
public boolean isArrayType();
public boolean isTypeVar();
public boolean isIntersection();
public boolean isJavaLangType();
public boolean isRecord();
public boolean isStreamType();
public boolean hasSuperBound();
public boolean hasExtendsBound();
public boolean hasLowerBound();
public boolean hasUpperBound();
public String getFullyQualifiedName();
public String getImportName();
public Set<Type> getImportTypes();
protected boolean isTopLevelTypeToBeImported();
public boolean isToBeImported();
private boolean shouldUseSimpleName();
public Type erasure();
public Type withoutBounds();
private Type replaceGeneric( Type oldGenericType, Type newType);
public boolean isAssignableTo( Type other);
public boolean isRawAssignableTo( Type other);
public Type asRawType();
public ReadAccessor getReadAccessor( String propertyName, boolean allowedMapToBean);
public PresenceCheckAccessor getPresenceChecker( String propertyName);
public Map<String,ReadAccessor> getPropertyReadAccessors();
public Map<String,PresenceCheckAccessor> getPropertyPresenceCheckers();
public Map<String,Accessor> getPropertyWriteAccessors( CollectionMappingStrategyGem cmStrategy);
public List<Element> getRecordComponents();
private Type determinePreferredType( Accessor readAccessor);
private Type determineTargetType( Accessor candidate);
private List<ExecutableElement> getAllMethods();
private List<VariableElement> getAllFields();
private <T>List<T> nullSafeTypeElementListConversion( Function<TypeElement,List<T>> conversionFunction);
private String getPropertyName( Accessor accessor);
private String getPropertyName( ExecutableElement element);
private Accessor getAdderForType( Type collectionProperty, String pluralPropertyName);
private List<Accessor> getAccessorCandidates( Type property, Class<?> superclass);
private TypeMirror boxed( TypeMirror possiblePrimitive);
private List<Accessor> getSetters();
private List<Accessor> getAdders();
private List<Accessor> getAlternativeTargetAccessors();
private boolean correspondingSetterMethodExists( Accessor getterMethod, List<Accessor> setterMethods);
private boolean isCollectionOrMapOrStream( Accessor getterMethod);
private boolean isCollection( TypeMirror candidate);
private boolean isStream( TypeMirror candidate);
private boolean isMap( TypeMirror candidate);
private boolean isSubType( TypeMirror candidate, Class<?> clazz);
public int distanceTo( Type assignableOther);
private int distanceTo( TypeMirror base, TypeMirror targetType);
public boolean canAccess( Type type, ExecutableElement method);
public String getNull();
public String getSensibleDefault();
public int hashCode();
public boolean equals( Object obj);
public int compareTo( Type o);
public String toString();
public String describe();
public String getIdentification();
public Type getTypeBound();
public List<Type> getTypeBounds();
public boolean hasAccessibleConstructor();
public List<Type> getDirectSuperTypes();
public List<Type> determineTypeArguments( Class<?> superclass);
public boolean isNative();
public boolean isLiteral();
public ResolvedPair resolveParameterToType( Type declared, Type parameterized);
public Type resolveGenericTypeParameters( Type declared, Type parameterized);
public boolean isWildCardBoundByTypeVar();
public boolean isArrayTypeVar();
private static class TypeVarMatcher extends SimpleTypeVisitor8<ResolvedPair,Type> {
private final TypeFactory typeFactory;
private final Type typeToMatch;
private final TypeUtils types;
TypeVarMatcher( TypeFactory typeFactory, TypeUtils types, Type typeToMatch);
public ResolvedPair visitTypeVariable( TypeVariable parameterized, Type declared);
public ResolvedPair visitWildcard( WildcardType parameterized, Type declared);
public ResolvedPair visitArray( ArrayType parameterized, Type declared);
public ResolvedPair visitDeclared( DeclaredType parameterized, Type declared);
private boolean isJavaLangObject( TypeMirror type);
}
public static class ResolvedPair {
public ResolvedPair( Type parameter, Type match);
private Type parameter;
private Type match;
public Type getParameter();
public Type getMatch();
public boolean equals( Object o);
public int hashCode();
}
public Type getBoxedEquivalent();
private String trimSimpleClassName( String className);
private static String nameWithTopLevelTypeName( TypeElement element, String name);
private static Type topLevelType( TypeElement typeElement, TypeFactory typeFactory);
public boolean isEnumSet();
public boolean isSealed();
public List<? extends TypeMirror> getPermittedSubclasses();
}
@Override public Set<Type> getImportTypes(){
Set<Type> types=super.getImportTypes();
for ( PropertyMapping propertyMapping : propertyMappings) {
types.addAll(propertyMapping.getImportTypes());
if (propertyMapping.isConstructorMapping()) {
types.addAll(propertyMapping.getTargetType().getImportTypes());
}
}
for ( SubclassMapping subclassMapping : subclassMappings) {
types.addAll(subclassMapping.getImportTypes());
}
if (returnTypeToConstruct != null) {
types.addAll(returnTypeToConstruct.getImportTypes());
}
if (returnTypeBuilder != null) {
types.add(returnTypeBuilder.getOwningType());
}
for ( LifecycleCallbackMethodReference reference : beforeMappingReferencesWithFinalizedReturnType) {
types.addAll(reference.getImportTypes());
}
for ( LifecycleCallbackMethodReference reference : afterMappingReferencesWithFinalizedReturnType) {
types.addAll(reference.getImportTypes());
}
return types;
}
| {"types": [{"Set<Type>": "Type"}], "similar_methods": [{"getImportTypes": "getImportTypes"}]} | [{"Set<Type>": {"retrieved_name": "Type", "raw_body": "/** \n * Represents (a reference to) the type of a bean property, parameter etc. Types are managed per generated source file. Each type corresponds to a {@link TypeMirror}, i.e. there are different instances for e.g. {@code Set<String>} and{@code Set<Integer>}. <p> Allows for a unified handling of declared and primitive types and usage within templates. Instances are obtained through {@link TypeFactory}.\n * @author Gunnar Morling\n * @author Filip Hrisafov\n */\npublic class Type extends ModelElement implements Comparable<Type> {\n private static final Method SEALED_PERMITTED_SUBCLASSES_METHOD;\nstatic {\n Method permittedSubclassesMethod;\n try {\n permittedSubclassesMethod=TypeElement.class.getMethod(\"getPermittedSubclasses\");\n }\n catch ( NoSuchMethodException e) {\n permittedSubclassesMethod=null;\n }\n SEALED_PERMITTED_SUBCLASSES_METHOD=permittedSubclassesMethod;\n }\n private final TypeUtils typeUtils;\n private final ElementUtils elementUtils;\n private final TypeFactory typeFactory;\n private final AccessorNamingUtils accessorNaming;\n private final TypeMirror typeMirror;\n private final TypeElement typeElement;\n private final List<Type> typeParameters;\n private final ImplementationType implementationType;\n private final Type componentType;\n private final Type topLevelType;\n private final String packageName;\n private final String name;\n private final String nameWithTopLevelTypeName;\n private final String qualifiedName;\n private final boolean isInterface;\n private final boolean isEnumType;\n private final boolean isIterableType;\n private final boolean isCollectionType;\n private final boolean isMapType;\n private final boolean isVoid;\n private final boolean isStream;\n private final boolean isLiteral;\n private final boolean loggingVerbose;\n private final List<String> enumConstants;\n private final Map<String,String> toBeImportedTypes;\n private final Map<String,String> notToBeImportedTypes;\n private Boolean isToBeImported;\n private Map<String,ReadAccessor> readAccessors=null;\n private Map<String,PresenceCheckAccessor> presenceCheckers=null;\n private List<ExecutableElement> allMethods=null;\n private List<VariableElement> allFields=null;\n private List<Element> recordComponents=null;\n private List<Accessor> setters=null;\n private List<Accessor> adders=null;\n private List<Accessor> alternativeTargetAccessors=null;\n private Type boundingBase=null;\n private List<Type> boundTypes=null;\n private Type boxedEquivalent=null;\n private Boolean hasAccessibleConstructor;\n private final Filters filters;\n public Type( TypeUtils typeUtils, ElementUtils elementUtils, TypeFactory typeFactory, AccessorNamingUtils accessorNaming, TypeMirror typeMirror, TypeElement typeElement, List<Type> typeParameters, ImplementationType implementationType, Type componentType, String packageName, String name, String qualifiedName, boolean isInterface, boolean isEnumType, boolean isIterableType, boolean isCollectionType, boolean isMapType, boolean isStreamType, Map<String,String> toBeImportedTypes, Map<String,String> notToBeImportedTypes, Boolean isToBeImported, boolean isLiteral, boolean loggingVerbose);\n public TypeMirror getTypeMirror();\n public TypeElement getTypeElement();\n public String getPackageName();\n public String getName();\n /** \n * Returns a String that could be used in generated code to reference to this {@link Type}.<br> <p> The first time a name is referred-to it will be marked as to be imported. For instance {@code LocalDateTime} can be one of {@code java.time.LocalDateTime} and {@code org.joda.LocalDateTime}) <p> If the {@code java.time} variant is referred to first, the {@code java.time.LocalDateTime} will be importedand the {@code org.joda} variant will be referred to with its FQN.<p> If the type is nested and its top level type is to be imported then the name including its top level type will be returned.\n * @return Just the name if this {@link Type} will be imported, the name up to the top level {@link Type}(if the top level type is important, otherwise the fully-qualified name.\n */\n public String createReferenceName();\n public List<Type> getTypeParameters();\n public Type getComponentType();\n public boolean isPrimitive();\n public boolean isInterface();\n public boolean isEnumType();\n public boolean isVoid();\n public boolean isAbstract();\n public boolean isString();\n /** \n * @return this type's enum constants in case it is an enum, an empty list otherwise.\n */\n public List<String> getEnumConstants();\n /** \n * Returns the implementation type to be instantiated in case this type is an interface iterable, collection or map type. The type will have the correct type arguments, so if this type e.g. represents {@code Set<String>}, the implementation type is {@code HashSet<String>}.\n * @return The implementation type to be instantiated in case this type is an interface iterable, collection or maptype, {@code null} otherwise.\n */\n public Type getImplementationType();\n public ImplementationType getImplementation();\n /** \n * Whether this type is a sub-type of {@link Iterable} or an array type.\n * @return {@code true} if this type is a sub-type of {@link Iterable} or an array type, {@code false} otherwise.\n */\n public boolean isIterableType();\n /** \n * Whether this type is a sub-type of {@link Iterable}, {@link java.util.stream.Stream} or an array type\n * @return {@code true} if this type is a sub-type of{@link Iterable}, {@link java.util.stream.Stream} oran array type, {@code false} otherwise\n */\n public boolean isIterableOrStreamType();\n public boolean isCollectionType();\n public boolean isMapType();\n private boolean hasStringMapSignature();\n public boolean isCollectionOrMapType();\n public boolean isArrayType();\n public boolean isTypeVar();\n public boolean isIntersection();\n public boolean isJavaLangType();\n public boolean isRecord();\n /** \n * Whether this type is a sub-type of {@link java.util.stream.Stream}.\n * @return {@code true} it this type is a sub-type of {@link java.util.stream.Stream}, {@code false otherwise}\n */\n public boolean isStreamType();\n /** \n * A wild card type can have two types of bounds (mutual exclusive): extends and super.\n * @return true if the bound has a wild card super bound (e.g. ? super Number)\n */\n public boolean hasSuperBound();\n /** \n * A wild card type can have two types of bounds (mutual exclusive): extends and super.\n * @return true if the bound has a wild card super bound (e.g. ? extends Number)\n */\n public boolean hasExtendsBound();\n /** \n * A type variable type can have two types of bounds (mutual exclusive): lower and upper. Note that its use is only permitted on a definition (not on the place where its used). For instance: {@code <T super Number> T map( T in)}\n * @return true if the bound has a type variable lower bound (e.g. T super Number)\n */\n public boolean hasLowerBound();\n /** \n * A type variable type can have two types of bounds (mutual exclusive): lower and upper. Note that its use is only permitted on a definition (not on the place where its used). For instance: {@code ><T extends Number> T map( T in)}\n * @return true if the bound has a type variable upper bound (e.g. T extends Number)\n */\n public boolean hasUpperBound();\n public String getFullyQualifiedName();\n /** \n * @return The name of this type as to be used within import statements.\n */\n public String getImportName();\n @Override public Set<Type> getImportTypes();\n protected boolean isTopLevelTypeToBeImported();\n /** \n * Whether this type is to be imported by means of an import statement in the currently generated source file (it can be referenced in the generated source using its simple name) or not (referenced using the FQN).\n * @return {@code true} if the type is imported, {@code false} otherwise.\n */\n public boolean isToBeImported();\n private boolean shouldUseSimpleName();\n public Type erasure();\n public Type withoutBounds();\n private Type replaceGeneric( Type oldGenericType, Type newType);\n /** \n * Whether this type is assignable to the given other type, considering the \"extends / upper bounds\" as well.\n * @param other The other type.\n * @return {@code true} if and only if this type is assignable to the given other type.\n */\n public boolean isAssignableTo( Type other);\n /** \n * Whether this type is raw assignable to the given other type. We can't make a verdict on typevars, they need to be resolved first.\n * @param other The other type.\n * @return {@code true} if and only if this type is assignable to the given other type.\n */\n public boolean isRawAssignableTo( Type other);\n /** \n * removes any bounds from this type.\n * @return the raw type\n */\n public Type asRawType();\n public ReadAccessor getReadAccessor( String propertyName, boolean allowedMapToBean);\n public PresenceCheckAccessor getPresenceChecker( String propertyName);\n /** \n * getPropertyReadAccessors\n * @return an unmodifiable map of all read accessors (including 'is' for booleans), indexed by property name\n */\n public Map<String,ReadAccessor> getPropertyReadAccessors();\n /** \n * getPropertyPresenceCheckers\n * @return an unmodifiable map of all presence checkers, indexed by property name\n */\n public Map<String,PresenceCheckAccessor> getPropertyPresenceCheckers();\n /** \n * getPropertyWriteAccessors returns a map of the write accessors according to the CollectionMappingStrategy. These accessors include: <ul> <li>setters, the obvious candidate :-), {@link #getSetters() }</li> <li>readAccessors, for collections that do not have a setter, e.g. for JAXB generated collection attributes {@link #getPropertyReadAccessors() }</li> <li>adders, typically for from table generated entities, {@link #getAdders() }</li> </ul>\n * @param cmStrategy collection mapping strategy\n * @return an unmodifiable map of all write accessors indexed by property name\n */\n public Map<String,Accessor> getPropertyWriteAccessors( CollectionMappingStrategyGem cmStrategy);\n public List<Element> getRecordComponents();\n private Type determinePreferredType( Accessor readAccessor);\n private Type determineTargetType( Accessor candidate);\n private List<ExecutableElement> getAllMethods();\n private List<VariableElement> getAllFields();\n private <T>List<T> nullSafeTypeElementListConversion( Function<TypeElement,List<T>> conversionFunction);\n private String getPropertyName( Accessor accessor);\n private String getPropertyName( ExecutableElement element);\n /** \n * Tries to find an addMethod in this type for given collection property in this type. Matching occurs on: <ol> <li>The generic type parameter type of the collection should match the adder method argument</li> <li>When there are more candidates, property name is made singular (as good as is possible). This routine looks for a matching add method name.</li> <li>The singularization rules of Dali are used to make a property name singular. This routine looks for a matching add method name.</li> </ol>\n * @param collectionProperty property type (assumed collection) to find the adder method for\n * @param pluralPropertyName the property name (assumed plural)\n * @return corresponding adder method for getter when present\n */\n private Accessor getAdderForType( Type collectionProperty, String pluralPropertyName);\n /** \n * Returns all accessor candidates that start with \"add\" and have exactly one argument whose type matches the collection or stream property's type argument.\n * @param property the collection or stream property\n * @param superclass the superclass to use for type argument lookup\n * @return accessor candidates\n */\n private List<Accessor> getAccessorCandidates( Type property, Class<?> superclass);\n private TypeMirror boxed( TypeMirror possiblePrimitive);\n /** \n * getSetters\n * @return an unmodifiable list of all setters\n */\n private List<Accessor> getSetters();\n /** \n * Alternative accessors could be a getter for a collection / map. By means of the {@link Collection#addAll(Collection) } or {@link Map#putAll(Map)} this getter can still be used astargetAccessor. JAXB XJC tool generates such constructs. This method can be extended when new cases come along. getAdders\n * @return an unmodifiable list of all adders\n */\n private List<Accessor> getAdders();\n /** \n * Alternative accessors could be a getter for a collection. By means of the {@link java.util.Collection#addAll(java.util.Collection) } this getter can stillbe used as targetAccessor. JAXB XJC tool generates such constructs. This method can be extended when new cases come along.\n * @return an unmodifiable list of alternative target accessors.\n */\n private List<Accessor> getAlternativeTargetAccessors();\n private boolean correspondingSetterMethodExists( Accessor getterMethod, List<Accessor> setterMethods);\n private boolean isCollectionOrMapOrStream( Accessor getterMethod);\n private boolean isCollection( TypeMirror candidate);\n private boolean isStream( TypeMirror candidate);\n private boolean isMap( TypeMirror candidate);\n private boolean isSubType( TypeMirror candidate, Class<?> clazz);\n /** \n * Returns the length of the shortest path in the type hierarchy between this type and the specified other type. Returns {@code -1} if this type is not assignable to the other type. Returns {@code 0} if this type is equal tothe other type. Returns {@code 1}, if the other type is a direct super type of this type, and so on.\n * @param assignableOther the other type\n * @return the length of the shortest path in the type hierarchy between this type and the specified other type\n */\n public int distanceTo( Type assignableOther);\n private int distanceTo( TypeMirror base, TypeMirror targetType);\n /** \n * @param type the type declaring the method\n * @param method the method to check\n * @return Whether this type can access the given method declared on the given type.\n */\n public boolean canAccess( Type type, ExecutableElement method);\n /** \n * @return A valid Java expression most suitable for representing null - useful for dealing with primitives fromFTL.\n */\n public String getNull();\n public String getSensibleDefault();\n @Override public int hashCode();\n @Override public boolean equals( Object obj);\n @Override public int compareTo( Type o);\n @Override public String toString();\n /** \n * @return a string representation of the type for use in messages\n */\n public String describe();\n /** \n * @return an identification that can be used as part in a forged method name.\n */\n public String getIdentification();\n /** \n * Establishes the type bound: <ol> <li> {@code <? extends Number>}, returns Number</li> <li> {@code <? super Number>}, returns Number</li> <li> {@code <?>}, returns Object</li> <li> {@code <T extends Number>, returns Number}</li> </ol>\n * @return the bound for this parameter\n */\n public Type getTypeBound();\n public List<Type> getTypeBounds();\n public boolean hasAccessibleConstructor();\n /** \n * Returns the direct supertypes of a type. The interface types, if any, will appear last in the list.\n * @return the direct supertypes, or an empty list if none\n */\n public List<Type> getDirectSuperTypes();\n /** \n * Searches for the given superclass and collects all type arguments for the given class\n * @param superclass the superclass or interface the generic type arguments are searched for\n * @return a list of type arguments or null, if superclass was not found\n */\n public List<Type> determineTypeArguments( Class<?> superclass);\n /** \n * All primitive types and their corresponding boxed types are considered native.\n * @return true when native.\n */\n public boolean isNative();\n public boolean isLiteral();\n /** \n * Steps through the declaredType in order to find a match for this typeVar Type. It aligns with the provided parameterized type where this typeVar type is used.<br> <br> For example:<pre> {@code this: T declaredType: JAXBElement<String> parameterizedType: JAXBElement<T> result: String this: T, T[] or ? extends T, declaredType: E.g. Callable<? extends T> parameterizedType: Callable<BigDecimal> return: BigDecimal}</pre>\n * @param declared the type\n * @param parameterized the parameterized type\n * @return - the same type when this is not a type var in the broadest sense (T, T[], or ? extends T)<br>- the matching parameter in the parameterized type when this is a type var when found<br> - null in all other cases\n */\n public ResolvedPair resolveParameterToType( Type declared, Type parameterized);\n /** \n * Resolves generic types using the declared and parameterized types as input.<br> <br> For example: <pre> {@code this: T declaredType: JAXBElement<T> parameterizedType: JAXBElement<Integer> result: Integer this: List<T> declaredType: JAXBElement<T> parameterizedType: JAXBElement<Integer> result: List<Integer> this: List<? extends T> declaredType: JAXBElement<? extends T> parameterizedType: JAXBElement<BigDecimal> result: List<BigDecimal> this: List<Optional<T>> declaredType: JAXBElement<T> parameterizedType: JAXBElement<BigDecimal> result: List<Optional<BigDecimal>>}</pre> It also works for partial matching.<br> <br> For example: <pre> {@code this: Map<K, V> declaredType: JAXBElement<K> parameterizedType: JAXBElement<BigDecimal> result: Map<BigDecimal, V>}</pre> It also works with multiple parameters at both sides.<br> <br> For example when reversing Key/Value for a Map: <pre> {@code this: Map<KEY, VALUE> declaredType: HashMap<VALUE, KEY> parameterizedType: HashMap<BigDecimal, String> result: Map<String, BigDecimal>}</pre> Mismatch result examples: <pre> {@code this: T declaredType: JAXBElement<Y> parameterizedType: JAXBElement<Integer> result: null this: List<T> declaredType: JAXBElement<Y> parameterizedType: JAXBElement<Integer> result: List<T>}</pre>\n * @param declared the type\n * @param parameterized the parameterized type\n * @return - the result of {@link #resolveParameterToType(Type,Type)} when this type itself is a type var.<br>- the type but then with the matching type parameters replaced.<br> - the same type when this type does not contain matching type parameters.\n */\n public Type resolveGenericTypeParameters( Type declared, Type parameterized);\n public boolean isWildCardBoundByTypeVar();\n public boolean isArrayTypeVar();\nprivate static class TypeVarMatcher extends SimpleTypeVisitor8<ResolvedPair,Type> {\n private final TypeFactory typeFactory;\n private final Type typeToMatch;\n private final TypeUtils types;\n /** \n * @param typeFactory factory\n * @param types type utils\n * @param typeToMatch the typeVar or wildcard with typeVar bound\n */\n TypeVarMatcher( TypeFactory typeFactory, TypeUtils types, Type typeToMatch);\n @Override public ResolvedPair visitTypeVariable( TypeVariable parameterized, Type declared);\n /** \n * If ? extends SomeTime equals the boundary set in typeVarToMatch (NOTE: you can't compare the wildcard itself) then return a result;\n */\n @Override public ResolvedPair visitWildcard( WildcardType parameterized, Type declared);\n @Override public ResolvedPair visitArray( ArrayType parameterized, Type declared);\n @Override public ResolvedPair visitDeclared( DeclaredType parameterized, Type declared);\n private boolean isJavaLangObject( TypeMirror type);\n }\n /** \n * Reflects any Resolved Pair, examples are T, String ? extends T, BigDecimal T[], Integer[]\n */\npublic static class ResolvedPair {\n public ResolvedPair( Type parameter, Type match);\n /** \n * parameter, e.g. T, ? extends T or T[]\n */\n private Type parameter;\n /** \n * match, e.g. String, BigDecimal, Integer[]\n */\n private Type match;\n public Type getParameter();\n public Type getMatch();\n @Override public boolean equals( Object o);\n @Override public int hashCode();\n }\n /** \n * Gets the boxed equivalent type if the type is primitive, int will return Integer\n * @return boxed equivalent\n */\n public Type getBoxedEquivalent();\n /** \n * It strips all the {@code []} from the {@code className}. E.g. <pre> trimSimpleClassName(\"String[][][]\") -> \"String\" trimSimpleClassName(\"String[]\") -> \"String\" </pre>\n * @param className that needs to be trimmed\n * @return the trimmed {@code className}, or {@code null} if the {@code className} was {@code null}\n */\n private String trimSimpleClassName( String className);\n private static String nameWithTopLevelTypeName( TypeElement element, String name);\n private static Type topLevelType( TypeElement typeElement, TypeFactory typeFactory);\n public boolean isEnumSet();\n /** \n * return true if this type is a java 17+ sealed class\n */\n public boolean isSealed();\n /** \n * return the list of permitted TypeMirrors for the java 17+ sealed class\n */\n @SuppressWarnings(\"unchecked\") public List<? extends TypeMirror> getPermittedSubclasses();\n}\n", "raw_body_no_cmt": "public class Type extends ModelElement implements Comparable<Type> {\n private static final Method SEALED_PERMITTED_SUBCLASSES_METHOD;\nstatic {\n Method permittedSubclassesMethod;\n try {\n permittedSubclassesMethod=TypeElement.class.getMethod(\"getPermittedSubclasses\");\n }\n catch ( NoSuchMethodException e) {\n permittedSubclassesMethod=null;\n }\n SEALED_PERMITTED_SUBCLASSES_METHOD=permittedSubclassesMethod;\n }\n private final TypeUtils typeUtils;\n private final ElementUtils elementUtils;\n private final TypeFactory typeFactory;\n private final AccessorNamingUtils accessorNaming;\n private final TypeMirror typeMirror;\n private final TypeElement typeElement;\n private final List<Type> typeParameters;\n private final ImplementationType implementationType;\n private final Type componentType;\n private final Type topLevelType;\n private final String packageName;\n private final String name;\n private final String nameWithTopLevelTypeName;\n private final String qualifiedName;\n private final boolean isInterface;\n private final boolean isEnumType;\n private final boolean isIterableType;\n private final boolean isCollectionType;\n private final boolean isMapType;\n private final boolean isVoid;\n private final boolean isStream;\n private final boolean isLiteral;\n private final boolean loggingVerbose;\n private final List<String> enumConstants;\n private final Map<String,String> toBeImportedTypes;\n private final Map<String,String> notToBeImportedTypes;\n private Boolean isToBeImported;\n private Map<String,ReadAccessor> readAccessors=null;\n private Map<String,PresenceCheckAccessor> presenceCheckers=null;\n private List<ExecutableElement> allMethods=null;\n private List<VariableElement> allFields=null;\n private List<Element> recordComponents=null;\n private List<Accessor> setters=null;\n private List<Accessor> adders=null;\n private List<Accessor> alternativeTargetAccessors=null;\n private Type boundingBase=null;\n private List<Type> boundTypes=null;\n private Type boxedEquivalent=null;\n private Boolean hasAccessibleConstructor;\n private final Filters filters;\n public Type( TypeUtils typeUtils, ElementUtils elementUtils, TypeFactory typeFactory, AccessorNamingUtils accessorNaming, TypeMirror typeMirror, TypeElement typeElement, List<Type> typeParameters, ImplementationType implementationType, Type componentType, String packageName, String name, String qualifiedName, boolean isInterface, boolean isEnumType, boolean isIterableType, boolean isCollectionType, boolean isMapType, boolean isStreamType, Map<String,String> toBeImportedTypes, Map<String,String> notToBeImportedTypes, Boolean isToBeImported, boolean isLiteral, boolean loggingVerbose);\n public TypeMirror getTypeMirror();\n public TypeElement getTypeElement();\n public String getPackageName();\n public String getName();\n public String createReferenceName();\n public List<Type> getTypeParameters();\n public Type getComponentType();\n public boolean isPrimitive();\n public boolean isInterface();\n public boolean isEnumType();\n public boolean isVoid();\n public boolean isAbstract();\n public boolean isString();\n public List<String> getEnumConstants();\n public Type getImplementationType();\n public ImplementationType getImplementation();\n public boolean isIterableType();\n public boolean isIterableOrStreamType();\n public boolean isCollectionType();\n public boolean isMapType();\n private boolean hasStringMapSignature();\n public boolean isCollectionOrMapType();\n public boolean isArrayType();\n public boolean isTypeVar();\n public boolean isIntersection();\n public boolean isJavaLangType();\n public boolean isRecord();\n public boolean isStreamType();\n public boolean hasSuperBound();\n public boolean hasExtendsBound();\n public boolean hasLowerBound();\n public boolean hasUpperBound();\n public String getFullyQualifiedName();\n public String getImportName();\n public Set<Type> getImportTypes();\n protected boolean isTopLevelTypeToBeImported();\n public boolean isToBeImported();\n private boolean shouldUseSimpleName();\n public Type erasure();\n public Type withoutBounds();\n private Type replaceGeneric( Type oldGenericType, Type newType);\n public boolean isAssignableTo( Type other);\n public boolean isRawAssignableTo( Type other);\n public Type asRawType();\n public ReadAccessor getReadAccessor( String propertyName, boolean allowedMapToBean);\n public PresenceCheckAccessor getPresenceChecker( String propertyName);\n public Map<String,ReadAccessor> getPropertyReadAccessors();\n public Map<String,PresenceCheckAccessor> getPropertyPresenceCheckers();\n public Map<String,Accessor> getPropertyWriteAccessors( CollectionMappingStrategyGem cmStrategy);\n public List<Element> getRecordComponents();\n private Type determinePreferredType( Accessor readAccessor);\n private Type determineTargetType( Accessor candidate);\n private List<ExecutableElement> getAllMethods();\n private List<VariableElement> getAllFields();\n private <T>List<T> nullSafeTypeElementListConversion( Function<TypeElement,List<T>> conversionFunction);\n private String getPropertyName( Accessor accessor);\n private String getPropertyName( ExecutableElement element);\n private Accessor getAdderForType( Type collectionProperty, String pluralPropertyName);\n private List<Accessor> getAccessorCandidates( Type property, Class<?> superclass);\n private TypeMirror boxed( TypeMirror possiblePrimitive);\n private List<Accessor> getSetters();\n private List<Accessor> getAdders();\n private List<Accessor> getAlternativeTargetAccessors();\n private boolean correspondingSetterMethodExists( Accessor getterMethod, List<Accessor> setterMethods);\n private boolean isCollectionOrMapOrStream( Accessor getterMethod);\n private boolean isCollection( TypeMirror candidate);\n private boolean isStream( TypeMirror candidate);\n private boolean isMap( TypeMirror candidate);\n private boolean isSubType( TypeMirror candidate, Class<?> clazz);\n public int distanceTo( Type assignableOther);\n private int distanceTo( TypeMirror base, TypeMirror targetType);\n public boolean canAccess( Type type, ExecutableElement method);\n public String getNull();\n public String getSensibleDefault();\n public int hashCode();\n public boolean equals( Object obj);\n public int compareTo( Type o);\n public String toString();\n public String describe();\n public String getIdentification();\n public Type getTypeBound();\n public List<Type> getTypeBounds();\n public boolean hasAccessibleConstructor();\n public List<Type> getDirectSuperTypes();\n public List<Type> determineTypeArguments( Class<?> superclass);\n public boolean isNative();\n public boolean isLiteral();\n public ResolvedPair resolveParameterToType( Type declared, Type parameterized);\n public Type resolveGenericTypeParameters( Type declared, Type parameterized);\n public boolean isWildCardBoundByTypeVar();\n public boolean isArrayTypeVar();\nprivate static class TypeVarMatcher extends SimpleTypeVisitor8<ResolvedPair,Type> {\n private final TypeFactory typeFactory;\n private final Type typeToMatch;\n private final TypeUtils types;\n TypeVarMatcher( TypeFactory typeFactory, TypeUtils types, Type typeToMatch);\n public ResolvedPair visitTypeVariable( TypeVariable parameterized, Type declared);\n public ResolvedPair visitWildcard( WildcardType parameterized, Type declared);\n public ResolvedPair visitArray( ArrayType parameterized, Type declared);\n public ResolvedPair visitDeclared( DeclaredType parameterized, Type declared);\n private boolean isJavaLangObject( TypeMirror type);\n }\n public static class ResolvedPair {\n public ResolvedPair( Type parameter, Type match);\n private Type parameter;\n private Type match;\n public Type getParameter();\n public Type getMatch();\n public boolean equals( Object o);\n public int hashCode();\n }\n public Type getBoxedEquivalent();\n private String trimSimpleClassName( String className);\n private static String nameWithTopLevelTypeName( TypeElement element, String name);\n private static Type topLevelType( TypeElement typeElement, TypeFactory typeFactory);\n public boolean isEnumSet();\n public boolean isSealed();\n public List<? extends TypeMirror> getPermittedSubclasses();\n}\n"}}] | [] | [{"getImportTypes": {"retrieved_name": "getImportTypes", "raw_body": "@Override public Set<Type> getImportTypes(){\n Set<Type> types=super.getImportTypes();\n for ( PropertyMapping propertyMapping : propertyMappings) {\n types.addAll(propertyMapping.getImportTypes());\n if (propertyMapping.isConstructorMapping()) {\n types.addAll(propertyMapping.getTargetType().getImportTypes());\n }\n }\n for ( SubclassMapping subclassMapping : subclassMappings) {\n types.addAll(subclassMapping.getImportTypes());\n }\n if (returnTypeToConstruct != null) {\n types.addAll(returnTypeToConstruct.getImportTypes());\n }\n if (returnTypeBuilder != null) {\n types.add(returnTypeBuilder.getOwningType());\n }\n for ( LifecycleCallbackMethodReference reference : beforeMappingReferencesWithFinalizedReturnType) {\n types.addAll(reference.getImportTypes());\n }\n for ( LifecycleCallbackMethodReference reference : afterMappingReferencesWithFinalizedReturnType) {\n types.addAll(reference.getImportTypes());\n }\n return types;\n}\n"}}] |
Kong_unirest-java | unirest-java/unirest/src/main/java/kong/unirest/core/Path.java | Path | baseUrl | class Path {
private String url;
private String rawPath;
Path(String url, String defaultBasePath) {
if(defaultBasePath != null && url != null && !url.toLowerCase().startsWith("http")){
String full = defaultBasePath + url;
this.url = full;
this.rawPath = full;
} else {
this.url = url;
this.rawPath = url;
}
}
public Path(String url) {
this(url, null);
}
public void param(Map<String, Object> params) {
params.forEach((key, value) -> param(key, String.valueOf(value)));
}
public void param(String name, String value) {
Matcher matcher = Pattern.compile("\\{" + name + "\\}").matcher(url);
if (!matcher.find()) {
throw new UnirestException("Can't find route parameter name \"" + name + "\"");
}
this.url = matcher.replaceAll(encodePath(value));
}
private String encodePath(String value) {
if(value == null){
return "";
}
return Util.encode(value).replaceAll("\\+", "%20");
}
public void queryString(String name, Collection<?> value){
for (Object cur : value) {
queryString(name, cur);
}
}
public void queryString(String name, Object value) {
StringBuilder queryString = new StringBuilder();
if (url.contains("?")) {
queryString.append("&");
} else {
queryString.append("?");
}
try {
queryString.append(URLEncoder.encode(name, "UTF-8"));
if(value != null) {
queryString.append("=").append(URLEncoder.encode(String.valueOf(value), "UTF-8"));
}
} catch (UnsupportedEncodingException e) {
throw new UnirestException(e);
}
url += queryString.toString();
}
public void queryString(Map<String, Object> parameters) {
if (parameters != null) {
for (Map.Entry<String, Object> param : parameters.entrySet()) {
queryString(param.getKey(), param.getValue());
}
}
}
@Override
public String toString() {
return escape(url);
}
private String escape(String string) {
return string.replaceAll(" ", "%20").replaceAll("\t", "%09");
}
public String rawPath() {
return rawPath;
}
public String baseUrl() {<FILL_FUNCTION_BODY>}
public String getQueryString(){
return url.substring(url.indexOf("?")+1);
}
@Override
public boolean equals(Object o) {
if (this == o) { return true; }
if (o == null || getClass() != o.getClass()) { return false; }
Path path = (Path) o;
return Objects.equals(url, path.url);
}
@Override
public int hashCode() {
return Objects.hash(url);
}
} |
if(url != null && url.contains("?")){
return url.substring(0, url.indexOf("?"));
}
return url;
|
return url.substring(0, url.indexOf("?"));
| [] | [
"indexOf",
"substring"
] | [] | [
"indexOf",
"substring",
"contains"
] | {
"methods": [
"indexOf",
"substring"
],
"similar_methods": [
"baseUrl"
],
"types": []
} | public static <K,V>Map<K,V> mapOf(Object... keyValues){
Map<K,V> map=new HashMap<>();
K key=null;
for (int index=0; index < keyValues.length; index++) {
if (index % 2 == 0) {
key=(K)keyValues[index];
}
else {
map.put(key,(V)keyValues[index]);
}
}
return map;
}
@Test void strings(){
var obj=new JSONArray();
assertSame(obj,obj.put("cheese"));
obj.put(45);
assertEquals("cheese",obj.getString(0));
assertNotFound(() -> obj.getString(5));
assertEquals("45",obj.getString(1));
assertEquals("cheese",obj.optString(0));
assertEquals("logs",obj.optString(5,"logs"));
assertEquals("",obj.optString(5));
}
/**
* set a default base url for all routes. this is overridden if the url contains a valid base already the url may contain path params for example. Setting a default path of 'http://somwhere' and then calling Unirest with Unirest.get('/place') will result in a path of 'https://somwehre/place'
* @param value the base URL to use
* @return this config object
*/
public Config defaultBaseUrl(String value){
this.defaultBaseUrl=value;
return this;
}
| public static <K,V>Map<K,V> mapOf(Object... keyValues){
Map<K,V> map=new HashMap<>();
K key=null;
for (int index=0; index < keyValues.length; index++) {
if (index % 2 == 0) {
key=(K)keyValues[index];
}
else {
map.put(key,(V)keyValues[index]);
}
}
return map;
}
@Test void strings(){
var obj=new JSONArray();
assertSame(obj,obj.put("cheese"));
obj.put(45);
assertEquals("cheese",obj.getString(0));
assertNotFound(() -> obj.getString(5));
assertEquals("45",obj.getString(1));
assertEquals("cheese",obj.optString(0));
assertEquals("logs",obj.optString(5,"logs"));
assertEquals("",obj.optString(5));
}
/**
* set a default base url for all routes. this is overridden if the url contains a valid base already the url may contain path params for example. Setting a default path of 'http://somwhere' and then calling Unirest with Unirest.get('/place') will result in a path of 'https://somwehre/place'
* @param value the base URL to use
* @return this config object
*/
public Config defaultBaseUrl(String value){
this.defaultBaseUrl=value;
return this;
}
| {"methods": [{"indexOf": "mapOf"}, {"substring": "strings"}], "similar_methods": [{"baseUrl": "defaultBaseUrl"}]} | [] | [{"indexOf": {"retrieved_name": "mapOf", "raw_body": "public static <K,V>Map<K,V> mapOf(Object... keyValues){\n Map<K,V> map=new HashMap<>();\n K key=null;\n for (int index=0; index < keyValues.length; index++) {\n if (index % 2 == 0) {\n key=(K)keyValues[index];\n }\n else {\n map.put(key,(V)keyValues[index]);\n }\n }\n return map;\n}\n"}}, {"substring": {"retrieved_name": "strings", "raw_body": "@Test void strings(){\n var obj=new JSONArray();\n assertSame(obj,obj.put(\"cheese\"));\n obj.put(45);\n assertEquals(\"cheese\",obj.getString(0));\n assertNotFound(() -> obj.getString(5));\n assertEquals(\"45\",obj.getString(1));\n assertEquals(\"cheese\",obj.optString(0));\n assertEquals(\"logs\",obj.optString(5,\"logs\"));\n assertEquals(\"\",obj.optString(5));\n}\n"}}] | [{"baseUrl": {"retrieved_name": "defaultBaseUrl", "raw_body": "/** \n * set a default base url for all routes. this is overridden if the url contains a valid base already the url may contain path params for example. Setting a default path of 'http://somwhere' and then calling Unirest with Unirest.get('/place') will result in a path of 'https://somwehre/place'\n * @param value the base URL to use\n * @return this config object\n */\npublic Config defaultBaseUrl(String value){\n this.defaultBaseUrl=value;\n return this;\n}\n"}}] |
|
docker-java_docker-java | docker-java/docker-java-api/src/main/java/com/github/dockerjava/api/model/VolumeRW.java | VolumeRW | fromPrimitive | class VolumeRW implements Serializable {
private static final long serialVersionUID = 1L;
private Volume volume;
private AccessMode accessMode = AccessMode.rw;
public VolumeRW(Volume volume) {
this.volume = volume;
}
public VolumeRW(Volume volume, AccessMode accessMode) {
this.volume = volume;
this.accessMode = accessMode;
}
public Volume getVolume() {
return volume;
}
public AccessMode getAccessMode() {
return accessMode;
}
/**
* Returns a string representation of this {@link VolumeRW} suitable for inclusion in a JSON message. The returned String is simply the
* container path, {@link #getPath()}.
*
* @return a string representation of this {@link VolumeRW}
*/
@Override
public String toString() {
return getVolume() + ":" + getAccessMode();
}
@JsonCreator
public static VolumeRW fromPrimitive(Map<String, Boolean> map) {<FILL_FUNCTION_BODY>}
@JsonValue
public Map<String, Boolean> toPrimitive() {
return Collections.singletonMap(volume.getPath(), accessMode.toBoolean());
}
} |
Entry<String, Boolean> entry = map.entrySet().iterator().next();
return new VolumeRW(new Volume(entry.getKey()), AccessMode.fromBoolean(entry.getValue()));
|
if (map.size() != 1) {
throw new IllegalArgumentException("Map must have exactly one entry");
}
Map.Entry<String, Boolean> entry = map.entrySet().iterator().next();
return new VolumeRW(new Volume(entry.getKey()), AccessMode.fromBoolean(entry.getValue()));
| [
"Map<String,Boolean>",
"Map.Entry<String,Boolean>"
] | [
"iterator",
"size",
"getValue",
"entrySet",
"getKey",
"next",
"fromBoolean"
] | [
"Map<String,Boolean>",
"Entry<String,Boolean>"
] | [
"getKey",
"fromBoolean",
"getValue",
"entrySet",
"iterator",
"next"
] | {
"methods": [
"iterator",
"size",
"getValue",
"entrySet",
"getKey",
"next",
"fromBoolean"
],
"similar_methods": [
"fromPrimitive"
],
"types": [
"Map<String,Boolean>",
"Map.Entry<String,Boolean>"
]
} | /**
* Parse a Dockerfile.
*/
public class Dockerfile {
public final File dockerFile;
private final File baseDirectory;
public Dockerfile( File dockerFile, File baseDirectory);
private static class LineTransformer implements Function<String,Optional<? extends DockerfileStatement>> {
private int line=0;
@Override public Optional<? extends DockerfileStatement> apply( String input);
}
public Iterable<DockerfileStatement> getStatements() throws IOException;
public List<String> getIgnores() throws IOException;
public ScannedResult parse() throws IOException;
/**
* Result of scanning / parsing a docker file.
*/
public class ScannedResult {
final List<String> ignores;
final List<File> filesToAdd=new ArrayList<>();
public InputStream buildDockerFolderTar();
public InputStream buildDockerFolderTar( File directory);
@Override public String toString();
public ScannedResult() throws IOException;
/**
* Adds all files found in <code>directory</code> and subdirectories to <code>filesToAdd</code> collection. It also adds any empty directories if found.
* @param directory directory
* @throws DockerClientException when IO error occurs
*/
private void addFilesInDirectory( File directory);
private boolean isBaseDirectory( File directory);
/**
* Returns all matching ignore patterns for the given file name.
*/
private List<String> matchingIgnorePatterns( String fileName);
/**
* Returns the matching ignore pattern for the given file or null if it should NOT be ignored. Exception rules like "!Dockerfile" will be respected.
*/
private String effectiveMatchingIgnorePattern( File file);
}
}
@Override public boolean isRepeatable(){
return false;
}
/**
* @see #size
*/
@CheckForNull public Long getSize(){
return size;
}
@JsonValue public String getValue(){
return value;
}
public String getEntryPoint(){
return entryPoint;
}
public String getKey(){
return key;
}
private Frame nextFrame(int... bytes) throws IOException {
setBytes(bytes);
return frameReader.readFrame();
}
public static final AccessMode fromBoolean(boolean accessMode){
return accessMode ? rw : ro;
}
@JsonCreator public static VolumesRW fromPrimitive(Map<String,Boolean> map){
return new VolumesRW(map.entrySet().stream().map(entry -> new VolumeRW(new Volume(entry.getKey()),AccessMode.fromBoolean(entry.getValue()))).toArray(VolumeRW[]::new));
}
| public class Dockerfile {
public final File dockerFile;
private final File baseDirectory;
public Dockerfile( File dockerFile, File baseDirectory);
private static class LineTransformer implements Function<String,Optional<? extends DockerfileStatement>> {
private int line=0;
public Optional<? extends DockerfileStatement> apply( String input);
}
public Iterable<DockerfileStatement> getStatements() throws IOException;
public List<String> getIgnores() throws IOException;
public ScannedResult parse() throws IOException;
public class ScannedResult {
final List<String> ignores;
final List<File> filesToAdd=new ArrayList<>();
public InputStream buildDockerFolderTar();
public InputStream buildDockerFolderTar( File directory);
public String toString();
public ScannedResult() throws IOException;
private void addFilesInDirectory( File directory);
private boolean isBaseDirectory( File directory);
private List<String> matchingIgnorePatterns( String fileName);
private String effectiveMatchingIgnorePattern( File file);
}
}
@Override public boolean isRepeatable(){
return false;
}
/**
* @see #size
*/
@CheckForNull public Long getSize(){
return size;
}
@JsonValue public String getValue(){
return value;
}
public String getEntryPoint(){
return entryPoint;
}
public String getKey(){
return key;
}
private Frame nextFrame(int... bytes) throws IOException {
setBytes(bytes);
return frameReader.readFrame();
}
public static final AccessMode fromBoolean(boolean accessMode){
return accessMode ? rw : ro;
}
@JsonCreator public static VolumesRW fromPrimitive(Map<String,Boolean> map){
return new VolumesRW(map.entrySet().stream().map(entry -> new VolumeRW(new Volume(entry.getKey()),AccessMode.fromBoolean(entry.getValue()))).toArray(VolumeRW[]::new));
}
| {"types": [{"Map<String,Boolean>": "Dockerfile"}, {"Map.Entry<String,Boolean>": "Dockerfile"}], "methods": [{"iterator": "isRepeatable"}, {"size": "getSize"}, {"getValue": "getValue"}, {"entrySet": "getEntryPoint"}, {"getKey": "getKey"}, {"next": "nextFrame"}, {"fromBoolean": "fromBoolean"}], "similar_methods": [{"fromPrimitive": "fromPrimitive"}]} | [{"Map<String,Boolean>": {"retrieved_name": "Dockerfile", "raw_body": "/** \n * Parse a Dockerfile.\n */\npublic class Dockerfile {\n public final File dockerFile;\n private final File baseDirectory;\n public Dockerfile( File dockerFile, File baseDirectory);\nprivate static class LineTransformer implements Function<String,Optional<? extends DockerfileStatement>> {\n private int line=0;\n @Override public Optional<? extends DockerfileStatement> apply( String input);\n }\n public Iterable<DockerfileStatement> getStatements() throws IOException;\n public List<String> getIgnores() throws IOException;\n public ScannedResult parse() throws IOException;\n /** \n * Result of scanning / parsing a docker file.\n */\npublic class ScannedResult {\n final List<String> ignores;\n final List<File> filesToAdd=new ArrayList<>();\n public InputStream buildDockerFolderTar();\n public InputStream buildDockerFolderTar( File directory);\n @Override public String toString();\n public ScannedResult() throws IOException;\n /** \n * Adds all files found in <code>directory</code> and subdirectories to <code>filesToAdd</code> collection. It also adds any empty directories if found.\n * @param directory directory\n * @throws DockerClientException when IO error occurs\n */\n private void addFilesInDirectory( File directory);\n private boolean isBaseDirectory( File directory);\n /** \n * Returns all matching ignore patterns for the given file name.\n */\n private List<String> matchingIgnorePatterns( String fileName);\n /** \n * Returns the matching ignore pattern for the given file or null if it should NOT be ignored. Exception rules like \"!Dockerfile\" will be respected.\n */\n private String effectiveMatchingIgnorePattern( File file);\n }\n}\n", "raw_body_no_cmt": "public class Dockerfile {\n public final File dockerFile;\n private final File baseDirectory;\n public Dockerfile( File dockerFile, File baseDirectory);\nprivate static class LineTransformer implements Function<String,Optional<? extends DockerfileStatement>> {\n private int line=0;\n public Optional<? extends DockerfileStatement> apply( String input);\n }\n public Iterable<DockerfileStatement> getStatements() throws IOException;\n public List<String> getIgnores() throws IOException;\n public ScannedResult parse() throws IOException;\n public class ScannedResult {\n final List<String> ignores;\n final List<File> filesToAdd=new ArrayList<>();\n public InputStream buildDockerFolderTar();\n public InputStream buildDockerFolderTar( File directory);\n public String toString();\n public ScannedResult() throws IOException;\n private void addFilesInDirectory( File directory);\n private boolean isBaseDirectory( File directory);\n private List<String> matchingIgnorePatterns( String fileName);\n private String effectiveMatchingIgnorePattern( File file);\n }\n}\n"}}] | [{"iterator": {"retrieved_name": "isRepeatable", "raw_body": "@Override public boolean isRepeatable(){\n return false;\n}\n"}}, {"size": {"retrieved_name": "getSize", "raw_body": "/** \n * @see #size\n */\n@CheckForNull public Long getSize(){\n return size;\n}\n"}}, {"getValue": {"retrieved_name": "getValue", "raw_body": "@JsonValue public String getValue(){\n return value;\n}\n"}}, {"entrySet": {"retrieved_name": "getEntryPoint", "raw_body": "public String getEntryPoint(){\n return entryPoint;\n}\n"}}, {"getKey": {"retrieved_name": "getKey", "raw_body": "public String getKey(){\n return key;\n}\n"}}, {"next": {"retrieved_name": "nextFrame", "raw_body": "private Frame nextFrame(int... bytes) throws IOException {\n setBytes(bytes);\n return frameReader.readFrame();\n}\n"}}, {"fromBoolean": {"retrieved_name": "fromBoolean", "raw_body": "public static final AccessMode fromBoolean(boolean accessMode){\n return accessMode ? rw : ro;\n}\n"}}] | [{"fromPrimitive": {"retrieved_name": "fromPrimitive", "raw_body": "@JsonCreator public static VolumesRW fromPrimitive(Map<String,Boolean> map){\n return new VolumesRW(map.entrySet().stream().map(entry -> new VolumeRW(new Volume(entry.getKey()),AccessMode.fromBoolean(entry.getValue()))).toArray(VolumeRW[]::new));\n}\n"}}] |
|
mapstruct_mapstruct | mapstruct/processor/src/main/java/org/mapstruct/ap/internal/util/Nouns.java | Nouns | singularize | class Nouns {
private Nouns() {
}
private static final List<ReplaceRule> SINGULAR_RULES = Arrays.asList(
new ReplaceRule( "(equipment|information|rice|money|species|series|fish|sheep)$", "$1" ),
new ReplaceRule( "(f)eet$", "$1oot" ),
new ReplaceRule( "(t)eeth$", "$1ooth" ),
new ReplaceRule( "(g)eese$", "$1oose" ),
new ReplaceRule( "(s)tadiums$", "$1tadium" ),
new ReplaceRule( "(m)oves$", "$1ove" ),
new ReplaceRule( "(s)exes$", "$1ex" ),
new ReplaceRule( "(c)hildren$", "$1hild" ),
new ReplaceRule( "(m)en$", "$1an" ),
new ReplaceRule( "(p)eople$", "$1erson" ),
new ReplaceRule( "(quiz)zes$", "$1" ),
new ReplaceRule( "(matr)ices$", "$1ix" ),
new ReplaceRule( "(vert|ind)ices$", "$1ex" ),
new ReplaceRule( "^(ox)en", "$1" ),
new ReplaceRule( "(alias|status)$", "$1" ), // already singular, but ends in 's'
new ReplaceRule( "(alias|status)es$", "$1" ),
new ReplaceRule( "(octop|vir)us$", "$1us" ), // already singular, but ends in 's'
new ReplaceRule( "(octop|vir)i$", "$1us" ),
new ReplaceRule( "(cris|ax|test)es$", "$1is" ),
new ReplaceRule( "(cris|ax|test)is$", "$1is" ), // already singular, but ends in 's'
new ReplaceRule( "(shoe)s$", "$1" ),
new ReplaceRule( "(o)es$", "$1" ),
new ReplaceRule( "(bus)es$", "$1" ),
new ReplaceRule( "([m|l])ice$", "$1ouse" ),
new ReplaceRule( "(x|ch|ss|sh)es$", "$1" ),
new ReplaceRule( "(m)ovies$", "$1ovie" ),
new ReplaceRule( "(s)eries$", "$1eries" ),
new ReplaceRule( "([^aeiouy]|qu)ies$", "$1y" ),
new ReplaceRule( "([lr])ves$", "$1f" ),
new ReplaceRule( "(tive)s$", "$1" ),
new ReplaceRule( "(hive)s$", "$1" ),
new ReplaceRule( "([^f])ves$", "$1fe" ),
new ReplaceRule( "(^analy)sis$", "$1sis" ), // already singular, but ends in 's'
new ReplaceRule( "(^analy)ses$", "$1sis" ),
new ReplaceRule( "((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$", "$1$2sis" ),
new ReplaceRule( "([ti])a$", "$1um" ),
new ReplaceRule( "(n)ews$", "$1ews" ),
new ReplaceRule( "(s|si|u)s$", "$1s" ), // '-us' and '-ss' are already singular
new ReplaceRule( "s$", "" )
);
/**
* Replacement rules based on the routine applied by the <a href="http://www.eclipse.org/webtools/dali/">Dali</a>
* project. Applied as a fallback if the other rules didn't yield a match.
*/
private static final List<ReplaceRule> SINGULAR_DALI_RULES = Arrays.asList(
new ReplaceRule( "(us|ss)$", "$1" ),
new ReplaceRule( "(ch|s)es$", "$1" ),
new ReplaceRule( "([^aeiouy])ies$", "$1y" )
);
/**
* Converts given pluralized noun into the singular form. If no singular form could be determined, the given word
* itself is returned.
*
* @param plural plural word
* @return singular form, if available
*/
public static String singularize(String plural) {<FILL_FUNCTION_BODY>}
private static final class ReplaceRule {
private final String regexp;
private final String replacement;
private final Pattern pattern;
private ReplaceRule(String regexp, String replacement) {
this.regexp = regexp;
this.replacement = replacement;
this.pattern = Pattern.compile( this.regexp, Pattern.CASE_INSENSITIVE );
}
private String apply(String input) {
String result = null;
Matcher matcher = this.pattern.matcher( input );
if ( matcher.find() ) {
result = matcher.replaceAll( this.replacement );
}
return result;
}
@Override
public String toString() {
return "'" + regexp + "' -> '" + replacement;
}
}
} |
for ( ReplaceRule replaceRule : SINGULAR_RULES ) {
String match = replaceRule.apply( plural );
if ( match != null ) {
return match;
}
}
for ( ReplaceRule replaceRule : SINGULAR_DALI_RULES ) {
String match = replaceRule.apply( plural );
if ( match != null ) {
return match;
}
}
return plural;
|
String result = applyRules( plural, SINGULAR_RULES );
if ( result == null ) {
result = applyRules( plural, SINGULAR_DALI_RULES );
}
return result != null ? result : plural;
| [
"List<ReplaceRule>"
] | [] | [
"ReplaceRule",
"List<ReplaceRule>"
] | [
"apply"
] | {
"methods": [],
"similar_methods": [
"singularize"
],
"types": [
"List<ReplaceRule>"
]
} | public class List {
}
private static String capitalize(String value){
return Arrays.stream(value.split("_")).map(CaseEnumTransformationStrategy::upperCaseFirst).collect(Collectors.joining("_"));
}
| public class List {
}
private static String capitalize(String value){
return Arrays.stream(value.split("_")).map(CaseEnumTransformationStrategy::upperCaseFirst).collect(Collectors.joining("_"));
}
| {"types": [{"List<ReplaceRule>": "List"}], "similar_methods": [{"singularize": "capitalize"}]} | [{"List<ReplaceRule>": {"retrieved_name": "List", "raw_body": "public class List {\n}\n", "raw_body_no_cmt": "public class List {\n}\n"}}] | [] | [{"singularize": {"retrieved_name": "capitalize", "raw_body": "private static String capitalize(String value){\n return Arrays.stream(value.split(\"_\")).map(CaseEnumTransformationStrategy::upperCaseFirst).collect(Collectors.joining(\"_\"));\n}\n"}}] |
|
logfellow_logstash-logback-encoder | logstash-logback-encoder/src/main/java/net/logstash/logback/pattern/EnhancedPropertyConverter.java | EnhancedPropertyConverter | start | class EnhancedPropertyConverter extends ClassicConverter {
/**
* Regex pattern used to extract the optional default value from the key name (split
* at the first :-).
*/
private static final Pattern PATTERN = Pattern.compile("(.+?):-(.*)");
/**
* The property name.
*/
private String propertyName;
/**
* The default value to use when the property is not defined.
*/
private String defaultValue = "";
public void start() {<FILL_FUNCTION_BODY>}
@Override
public String convert(ILoggingEvent event) {
LoggerContextVO lcvo = event.getLoggerContextVO();
Map<String, String> map = lcvo.getPropertyMap();
String val = map.get(propertyName);
if (val == null) {
val = System.getProperty(propertyName);
}
if (val == null) {
val = defaultValue;
}
return val;
}
} |
String optStr = getFirstOption();
if (optStr != null) {
propertyName = optStr;
super.start();
}
if (propertyName == null) {
throw new IllegalStateException("Property name is not specified");
}
Matcher matcher = PATTERN.matcher(propertyName);
if (matcher.matches()) {
propertyName = matcher.group(1);
defaultValue = matcher.group(2);
}
|
String key = getFirstOption();
Matcher m = PATTERN.matcher(key);
if (m.matches()) {
propertyName = m.group(1);
defaultValue = m.group(2);
} else {
propertyName = key;
}
| [
"Pattern",
"Matcher"
] | [
"matches",
"matcher",
"group"
] | [
"Pattern",
"Matcher"
] | [
"matcher",
"group",
"matches"
] | {
"methods": [
"matches",
"matcher",
"group"
],
"similar_methods": [
"start"
],
"types": [
"Pattern",
"Matcher"
]
} | /**
* Adapter around a {@link PatternLayoutBase} to allow writing the pattern into a supplied {@link StringBuilder}instead of returning a String. The adapter also throws an {@link IllegalArgumentException} upon start when the configured pattern is not avalid pattern layout instead of simply emitting an ERROR status.
* @author brenuart
*/
public class PatternLayoutAdapter<E> {
/**
* Regex pattern matching error place holders inserted by PatternLayout when it fails to parse the pattern
*/
private static final Pattern ERROR_PATTERN=Pattern.compile("%PARSER_ERROR\\[(.*)\\]");
/**
* The wrapped pattern layout instance
*/
private final PatternLayoutBase<E> layout;
/**
* The "head" converter of the pattern. Initialized when the pattern is started. Can stay null after the PatternLayout is started when the pattern is empty or a parse error occurred.
*/
private Converter<E> head;
private boolean headCaptured;
public PatternLayoutAdapter( PatternLayoutBase<E> layout);
/**
* Set the {@link Context}
* @param context the context
*/
public void setContext( Context context);
/**
* Set the layout pattern
* @param pattern the layout pattern
*/
public void setPattern( String pattern);
/**
* Start the underlying PatternLayoutBase and throw an {@link IllegalArgumentException} if theconfigured pattern is not a valid PatternLayout.
* @throws IllegalArgumentException thrown when the configured pattern is not a valid PatternLayout
*/
public void start() throws IllegalArgumentException;
/**
* Apply the PatternLayout to the <em>event</em> and write result into the supplied {@link StringBuilder}.
* @param strBuilder the {@link StringBuilder} to write the result of applying the PatternLayout on the event
* @param event the event to apply the pattern to
*/
public void writeTo( StringBuilder strBuilder, E event);
/**
* Indicate whether the {@link PatternLayoutBase} always generates the same constant value regardless ofthe event it is given.
* @return <em>true</em> if the pattern is constant
*/
public boolean isConstant();
/**
* Get the constant value of the pattern or throw an {@link IllegalStateException} if the patternis not constant.
* @return the constant value of the pattern
* @see #isConstant()
*/
public String getConstantValue();
private boolean isConstantConverter( Converter<E> converter);
private class HeadConverterCapture implements PostCompileProcessor<E> {
@Override public void process( Context context, Converter<E> head);
}
}
/**
* Convenience class for constructing various {@link LogstashMarker}s used to add fields into the logstash event. <p> This creates a somewhat fluent interface that can be used to create markers. <p> For example: <pre> {@code import static net.logstash.logback.marker.Markers. logger.info(append("name1", "value1"), "log message"); logger.info(append("name1", "value1").and(append("name2", "value2")), "log message"); logger.info(appendEntries(myMap), "log message");}</pre>
*/
public class Markers {
private Markers();
public static LogstashMarker appendEntries( Map<?,?> map);
public static LogstashMarker appendFields( Object object);
public static LogstashMarker append( String fieldName, Object object);
public static LogstashMarker appendArray( String fieldName, Object... objects);
public static LogstashMarker appendRaw( String fieldName, String rawJsonValue);
/**
* Aggregates the given markers into a single marker.
* @param markers the markers to aggregate
* @return the aggregated marker.
*/
public static LogstashMarker aggregate( Marker... markers);
/**
* Aggregates the given markers into a single marker.
* @param markers the markers to aggregate
* @return the aggregated marker.
*/
public static LogstashMarker aggregate( Collection<? extends Marker> markers);
public static LogstashMarker defer( Supplier<? extends LogstashMarker> logstashMarkerSupplier);
public static LogstashMarker empty();
}
@Override public boolean matches(SocketAddress argument){
InetSocketAddress sockAddr=(InetSocketAddress)argument;
return host.equals(sockAddr.getHostName()) && port == sockAddr.getPort();
}
@Override public boolean matches(SocketAddress argument){
InetSocketAddress sockAddr=(InetSocketAddress)argument;
return host.equals(sockAddr.getHostName()) && port == sockAddr.getPort();
}
public static void main(String args[]){
System.out.println("- Downloader started");
File baseDirectory=new File(args[0]);
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
File mavenWrapperPropertyFile=new File(baseDirectory,MAVEN_WRAPPER_PROPERTIES_PATH);
String url=DEFAULT_DOWNLOAD_URL;
if (mavenWrapperPropertyFile.exists()) {
FileInputStream mavenWrapperPropertyFileInputStream=null;
try {
mavenWrapperPropertyFileInputStream=new FileInputStream(mavenWrapperPropertyFile);
Properties mavenWrapperProperties=new Properties();
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
url=mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL,url);
}
catch ( IOException e) {
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
}
finally {
try {
if (mavenWrapperPropertyFileInputStream != null) {
mavenWrapperPropertyFileInputStream.close();
}
}
catch ( IOException e) {
}
}
}
System.out.println("- Downloading from: " + url);
File outputFile=new File(baseDirectory.getAbsolutePath(),MAVEN_WRAPPER_JAR_PATH);
if (!outputFile.getParentFile().exists()) {
if (!outputFile.getParentFile().mkdirs()) {
System.out.println("- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
}
}
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
try {
downloadFileFromURL(url,outputFile);
System.out.println("Done");
System.exit(0);
}
catch ( Throwable e) {
System.out.println("- Error downloading");
e.printStackTrace();
System.exit(1);
}
}
@Override public void start(){
addWarn(this.getClass().getName() + " is deprecated, use " + UuidJsonProvider.class.getName()+ " instead.");
super.start();
}
| public class PatternLayoutAdapter<E> {
private static final Pattern ERROR_PATTERN=Pattern.compile("%PARSER_ERROR\\[(.*)\\]");
private final PatternLayoutBase<E> layout;
private Converter<E> head;
private boolean headCaptured;
public PatternLayoutAdapter( PatternLayoutBase<E> layout);
public void setContext( Context context);
public void setPattern( String pattern);
public void start() throws IllegalArgumentException;
public void writeTo( StringBuilder strBuilder, E event);
public boolean isConstant();
public String getConstantValue();
private boolean isConstantConverter( Converter<E> converter);
private class HeadConverterCapture implements PostCompileProcessor<E> {
public void process( Context context, Converter<E> head);
}
}
public class Markers {
private Markers();
public static LogstashMarker appendEntries( Map<?,?> map);
public static LogstashMarker appendFields( Object object);
public static LogstashMarker append( String fieldName, Object object);
public static LogstashMarker appendArray( String fieldName, Object... objects);
public static LogstashMarker appendRaw( String fieldName, String rawJsonValue);
public static LogstashMarker aggregate( Marker... markers);
public static LogstashMarker aggregate( Collection<? extends Marker> markers);
public static LogstashMarker defer( Supplier<? extends LogstashMarker> logstashMarkerSupplier);
public static LogstashMarker empty();
}
@Override public boolean matches(SocketAddress argument){
InetSocketAddress sockAddr=(InetSocketAddress)argument;
return host.equals(sockAddr.getHostName()) && port == sockAddr.getPort();
}
@Override public boolean matches(SocketAddress argument){
InetSocketAddress sockAddr=(InetSocketAddress)argument;
return host.equals(sockAddr.getHostName()) && port == sockAddr.getPort();
}
public static void main(String args[]){
System.out.println("- Downloader started");
File baseDirectory=new File(args[0]);
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
File mavenWrapperPropertyFile=new File(baseDirectory,MAVEN_WRAPPER_PROPERTIES_PATH);
String url=DEFAULT_DOWNLOAD_URL;
if (mavenWrapperPropertyFile.exists()) {
FileInputStream mavenWrapperPropertyFileInputStream=null;
try {
mavenWrapperPropertyFileInputStream=new FileInputStream(mavenWrapperPropertyFile);
Properties mavenWrapperProperties=new Properties();
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
url=mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL,url);
}
catch ( IOException e) {
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
}
finally {
try {
if (mavenWrapperPropertyFileInputStream != null) {
mavenWrapperPropertyFileInputStream.close();
}
}
catch ( IOException e) {
}
}
}
System.out.println("- Downloading from: " + url);
File outputFile=new File(baseDirectory.getAbsolutePath(),MAVEN_WRAPPER_JAR_PATH);
if (!outputFile.getParentFile().exists()) {
if (!outputFile.getParentFile().mkdirs()) {
System.out.println("- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
}
}
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
try {
downloadFileFromURL(url,outputFile);
System.out.println("Done");
System.exit(0);
}
catch ( Throwable e) {
System.out.println("- Error downloading");
e.printStackTrace();
System.exit(1);
}
}
@Override public void start(){
addWarn(this.getClass().getName() + " is deprecated, use " + UuidJsonProvider.class.getName()+ " instead.");
super.start();
}
| {"types": [{"Pattern": "PatternLayoutAdapter"}, {"Matcher": "Markers"}], "methods": [{"matches": "matches"}, {"matcher": "matches"}, {"group": "main"}], "similar_methods": [{"start": "start"}]} | [{"Pattern": {"retrieved_name": "PatternLayoutAdapter", "raw_body": "/** \n * Adapter around a {@link PatternLayoutBase} to allow writing the pattern into a supplied {@link StringBuilder}instead of returning a String. The adapter also throws an {@link IllegalArgumentException} upon start when the configured pattern is not avalid pattern layout instead of simply emitting an ERROR status.\n * @author brenuart\n */\npublic class PatternLayoutAdapter<E> {\n /** \n * Regex pattern matching error place holders inserted by PatternLayout when it fails to parse the pattern\n */\n private static final Pattern ERROR_PATTERN=Pattern.compile(\"%PARSER_ERROR\\\\[(.*)\\\\]\");\n /** \n * The wrapped pattern layout instance\n */\n private final PatternLayoutBase<E> layout;\n /** \n * The \"head\" converter of the pattern. Initialized when the pattern is started. Can stay null after the PatternLayout is started when the pattern is empty or a parse error occurred.\n */\n private Converter<E> head;\n private boolean headCaptured;\n public PatternLayoutAdapter( PatternLayoutBase<E> layout);\n /** \n * Set the {@link Context}\n * @param context the context\n */\n public void setContext( Context context);\n /** \n * Set the layout pattern\n * @param pattern the layout pattern\n */\n public void setPattern( String pattern);\n /** \n * Start the underlying PatternLayoutBase and throw an {@link IllegalArgumentException} if theconfigured pattern is not a valid PatternLayout.\n * @throws IllegalArgumentException thrown when the configured pattern is not a valid PatternLayout\n */\n public void start() throws IllegalArgumentException;\n /** \n * Apply the PatternLayout to the <em>event</em> and write result into the supplied {@link StringBuilder}.\n * @param strBuilder the {@link StringBuilder} to write the result of applying the PatternLayout on the event\n * @param event the event to apply the pattern to\n */\n public void writeTo( StringBuilder strBuilder, E event);\n /** \n * Indicate whether the {@link PatternLayoutBase} always generates the same constant value regardless ofthe event it is given.\n * @return <em>true</em> if the pattern is constant\n */\n public boolean isConstant();\n /** \n * Get the constant value of the pattern or throw an {@link IllegalStateException} if the patternis not constant.\n * @return the constant value of the pattern\n * @see #isConstant()\n */\n public String getConstantValue();\n private boolean isConstantConverter( Converter<E> converter);\nprivate class HeadConverterCapture implements PostCompileProcessor<E> {\n @Override public void process( Context context, Converter<E> head);\n }\n}\n", "raw_body_no_cmt": "public class PatternLayoutAdapter<E> {\n private static final Pattern ERROR_PATTERN=Pattern.compile(\"%PARSER_ERROR\\\\[(.*)\\\\]\");\n private final PatternLayoutBase<E> layout;\n private Converter<E> head;\n private boolean headCaptured;\n public PatternLayoutAdapter( PatternLayoutBase<E> layout);\n public void setContext( Context context);\n public void setPattern( String pattern);\n public void start() throws IllegalArgumentException;\n public void writeTo( StringBuilder strBuilder, E event);\n public boolean isConstant();\n public String getConstantValue();\n private boolean isConstantConverter( Converter<E> converter);\nprivate class HeadConverterCapture implements PostCompileProcessor<E> {\n public void process( Context context, Converter<E> head);\n }\n}\n"}}, {"Matcher": {"retrieved_name": "Markers", "raw_body": "/** \n * Convenience class for constructing various {@link LogstashMarker}s used to add fields into the logstash event. <p> This creates a somewhat fluent interface that can be used to create markers. <p> For example: <pre> {@code import static net.logstash.logback.marker.Markers. logger.info(append(\"name1\", \"value1\"), \"log message\"); logger.info(append(\"name1\", \"value1\").and(append(\"name2\", \"value2\")), \"log message\"); logger.info(appendEntries(myMap), \"log message\");}</pre>\n */\npublic class Markers {\n private Markers();\n public static LogstashMarker appendEntries( Map<?,?> map);\n public static LogstashMarker appendFields( Object object);\n public static LogstashMarker append( String fieldName, Object object);\n public static LogstashMarker appendArray( String fieldName, Object... objects);\n public static LogstashMarker appendRaw( String fieldName, String rawJsonValue);\n /** \n * Aggregates the given markers into a single marker.\n * @param markers the markers to aggregate\n * @return the aggregated marker.\n */\n public static LogstashMarker aggregate( Marker... markers);\n /** \n * Aggregates the given markers into a single marker.\n * @param markers the markers to aggregate\n * @return the aggregated marker.\n */\n public static LogstashMarker aggregate( Collection<? extends Marker> markers);\n public static LogstashMarker defer( Supplier<? extends LogstashMarker> logstashMarkerSupplier);\n public static LogstashMarker empty();\n}\n", "raw_body_no_cmt": "public class Markers {\n private Markers();\n public static LogstashMarker appendEntries( Map<?,?> map);\n public static LogstashMarker appendFields( Object object);\n public static LogstashMarker append( String fieldName, Object object);\n public static LogstashMarker appendArray( String fieldName, Object... objects);\n public static LogstashMarker appendRaw( String fieldName, String rawJsonValue);\n public static LogstashMarker aggregate( Marker... markers);\n public static LogstashMarker aggregate( Collection<? extends Marker> markers);\n public static LogstashMarker defer( Supplier<? extends LogstashMarker> logstashMarkerSupplier);\n public static LogstashMarker empty();\n}\n"}}] | [{"matches": {"retrieved_name": "matches", "raw_body": "@Override public boolean matches(SocketAddress argument){\n InetSocketAddress sockAddr=(InetSocketAddress)argument;\n return host.equals(sockAddr.getHostName()) && port == sockAddr.getPort();\n}\n"}}, {"matcher": {"retrieved_name": "matches", "raw_body": "@Override public boolean matches(SocketAddress argument){\n InetSocketAddress sockAddr=(InetSocketAddress)argument;\n return host.equals(sockAddr.getHostName()) && port == sockAddr.getPort();\n}\n"}}, {"group": {"retrieved_name": "main", "raw_body": "public static void main(String args[]){\n System.out.println(\"- Downloader started\");\n File baseDirectory=new File(args[0]);\n System.out.println(\"- Using base directory: \" + baseDirectory.getAbsolutePath());\n File mavenWrapperPropertyFile=new File(baseDirectory,MAVEN_WRAPPER_PROPERTIES_PATH);\n String url=DEFAULT_DOWNLOAD_URL;\n if (mavenWrapperPropertyFile.exists()) {\n FileInputStream mavenWrapperPropertyFileInputStream=null;\n try {\n mavenWrapperPropertyFileInputStream=new FileInputStream(mavenWrapperPropertyFile);\n Properties mavenWrapperProperties=new Properties();\n mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);\n url=mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL,url);\n }\n catch ( IOException e) {\n System.out.println(\"- ERROR loading '\" + MAVEN_WRAPPER_PROPERTIES_PATH + \"'\");\n }\n finally {\n try {\n if (mavenWrapperPropertyFileInputStream != null) {\n mavenWrapperPropertyFileInputStream.close();\n }\n }\n catch ( IOException e) {\n }\n }\n }\n System.out.println(\"- Downloading from: \" + url);\n File outputFile=new File(baseDirectory.getAbsolutePath(),MAVEN_WRAPPER_JAR_PATH);\n if (!outputFile.getParentFile().exists()) {\n if (!outputFile.getParentFile().mkdirs()) {\n System.out.println(\"- ERROR creating output directory '\" + outputFile.getParentFile().getAbsolutePath() + \"'\");\n }\n }\n System.out.println(\"- Downloading to: \" + outputFile.getAbsolutePath());\n try {\n downloadFileFromURL(url,outputFile);\n System.out.println(\"Done\");\n System.exit(0);\n }\n catch ( Throwable e) {\n System.out.println(\"- Error downloading\");\n e.printStackTrace();\n System.exit(1);\n }\n}\n"}}] | [{"start": {"retrieved_name": "start", "raw_body": "@Override public void start(){\n addWarn(this.getClass().getName() + \" is deprecated, use \" + UuidJsonProvider.class.getName()+ \" instead.\");\n super.start();\n}\n"}}] |
|
houbb_sensitive-word | sensitive-word/src/main/java/com/github/houbb/sensitive/word/support/check/WordCheckWord.java | WordCheckWord | getActualLength | class WordCheckWord extends AbstractWordCheck {
/**
* @since 0.3.0
*/
private static final IWordCheck INSTANCE = new WordCheckWord();
public static IWordCheck getInstance() {
return INSTANCE;
}
@Override
protected Class<? extends IWordCheck> getSensitiveCheckClass() {
return WordCheckWord.class;
}
@Override
protected int getActualLength(int beginIndex, InnerSensitiveWordContext innerContext) {<FILL_FUNCTION_BODY>}
@Override
protected String getType() {
return WordTypeEnum.WORD.getCode();
}
} |
final String txt = innerContext.originalText();
final Map<Character, Character> formatCharMapping = innerContext.formatCharMapping();
final WordValidModeEnum wordValidModeEnum = innerContext.modeEnum();
final IWordContext context = innerContext.wordContext();
// 采用 ThreadLocal 应该可以提升性能,减少对象的创建。
int actualLength = 0;
final IWordData wordData = context.wordData();
// 前一个条件
StringBuilder stringBuilder = new StringBuilder();
char[] rawChars = txt.toCharArray();
final ISensitiveWordCharIgnore wordCharIgnore = context.charIgnore();
int tempLen = 0;
for(int i = beginIndex; i < rawChars.length; i++) {
// 判断是否跳过?
if(wordCharIgnore.ignore(i, rawChars, innerContext)) {
tempLen++;
continue;
}
// 映射处理
final char currentChar = rawChars[i];
char mappingChar = formatCharMapping.get(currentChar);
stringBuilder.append(mappingChar);
tempLen++;
// 判断是否存在
WordContainsTypeEnum wordContainsTypeEnum = wordData.contains(stringBuilder, innerContext);
if(WordContainsTypeEnum.CONTAINS_END.equals(wordContainsTypeEnum)) {
actualLength = tempLen;
// 是否遍历全部匹配的模式
if(WordValidModeEnum.FAIL_FAST.equals(wordValidModeEnum)) {
break;
}
}
// 如果不包含,则直接返回。后续遍历无意义
if(WordContainsTypeEnum.NOT_FOUND.equals(wordContainsTypeEnum)) {
break;
}
}
return actualLength;
| /**
* 抽象实现策略
* @author binbin.hou
* @since 0.4.0
*/
@ThreadSafe public abstract class AbstractWordCheck implements IWordCheck {
/**
* 获取校验类
* @return 类
* @since 0.3.2
*/
protected abstract Class<? extends IWordCheck> getSensitiveCheckClass();
/**
* 获取确切的长度
* @param beginIndex 开始
* @param checkContext 上下文
* @return 长度
* @since 0.4.0
*/
protected abstract int getActualLength( int beginIndex, final InnerSensitiveWordContext checkContext);
/**
* 获取类别
* @return 类别
* @since 0.14.0
*/
protected abstract String getType();
@Override public WordCheckResult sensitiveCheck( int beginIndex, final InnerSensitiveWordContext checkContext);
}
|
return innerContext.getWord().length();
| [
"InnerSensitiveWordContext"
] | [
"getWord",
"length"
] | [
"InnerSensitiveWordContext",
"WordContainsTypeEnum",
"IWordData",
"Map<Character,Character>",
"IWordContext",
"ISensitiveWordCharIgnore",
"WordValidModeEnum"
] | [
"toCharArray",
"charIgnore",
"equals",
"modeEnum",
"ignore",
"contains",
"append",
"get",
"formatCharMapping",
"wordData",
"originalText",
"wordContext"
] | {
"methods": [
"getWord",
"length"
],
"similar_methods": [
"getActualLength"
],
"types": [
"InnerSensitiveWordContext"
]
} | /**
* 内部信息上下文
* @author binbin.hou
* @since 0.6.0
*/
public class InnerSensitiveWordContext {
/**
* 原始文本
*/
private String originalText;
/**
* 格式化后的字符
*/
private Map<Character,Character> formatCharMapping;
/**
* 校验模式
*/
private WordValidModeEnum modeEnum;
/**
* 原始上下文
*/
private IWordContext wordContext;
public static InnerSensitiveWordContext newInstance();
public String originalText();
public InnerSensitiveWordContext originalText( String text);
public Map<Character,Character> formatCharMapping();
public InnerSensitiveWordContext formatCharMapping( Map<Character,Character> formatCharMapping);
public WordValidModeEnum modeEnum();
public InnerSensitiveWordContext modeEnum( WordValidModeEnum modeEnum);
public IWordContext wordContext();
public InnerSensitiveWordContext wordContext( IWordContext context);
}
public String getWord(){
return word;
}
@Override protected int getActualLength(int beginIndex,InnerSensitiveWordContext checkContext){
final String txt=checkContext.originalText();
final IWordContext context=checkContext.wordContext();
final Map<Character,Character> formatCharMapping=checkContext.formatCharMapping();
int actualLength=0;
StringBuilder stringBuilder=new StringBuilder();
int currentIx=0;
for (int i=beginIndex; i < txt.length(); i++) {
currentIx=i;
char currentChar=txt.charAt(i);
char mappingChar=formatCharMapping.get(currentChar);
boolean currentCondition=isCharCondition(mappingChar,i,checkContext);
if (currentCondition) {
stringBuilder.append(currentChar);
}
else {
break;
}
}
if (isStringCondition(currentIx,stringBuilder,checkContext)) {
actualLength=stringBuilder.length();
}
return actualLength;
}
@Override protected int getActualLength(int beginIndex,InnerSensitiveWordContext checkContext){
final String txt=checkContext.originalText();
final IWordContext context=checkContext.wordContext();
final Map<Character,Character> formatCharMapping=checkContext.formatCharMapping();
int actualLength=0;
StringBuilder stringBuilder=new StringBuilder();
int currentIx=0;
for (int i=beginIndex; i < txt.length(); i++) {
currentIx=i;
char currentChar=txt.charAt(i);
char mappingChar=formatCharMapping.get(currentChar);
boolean currentCondition=isCharCondition(mappingChar,i,checkContext);
if (currentCondition) {
stringBuilder.append(currentChar);
}
else {
break;
}
}
if (isStringCondition(currentIx,stringBuilder,checkContext)) {
actualLength=stringBuilder.length();
}
return actualLength;
}
| public class InnerSensitiveWordContext {
private String originalText;
private Map<Character,Character> formatCharMapping;
private WordValidModeEnum modeEnum;
private IWordContext wordContext;
public static InnerSensitiveWordContext newInstance();
public String originalText();
public InnerSensitiveWordContext originalText( String text);
public Map<Character,Character> formatCharMapping();
public InnerSensitiveWordContext formatCharMapping( Map<Character,Character> formatCharMapping);
public WordValidModeEnum modeEnum();
public InnerSensitiveWordContext modeEnum( WordValidModeEnum modeEnum);
public IWordContext wordContext();
public InnerSensitiveWordContext wordContext( IWordContext context);
}
public String getWord(){
return word;
}
@Override protected int getActualLength(int beginIndex,InnerSensitiveWordContext checkContext){
final String txt=checkContext.originalText();
final IWordContext context=checkContext.wordContext();
final Map<Character,Character> formatCharMapping=checkContext.formatCharMapping();
int actualLength=0;
StringBuilder stringBuilder=new StringBuilder();
int currentIx=0;
for (int i=beginIndex; i < txt.length(); i++) {
currentIx=i;
char currentChar=txt.charAt(i);
char mappingChar=formatCharMapping.get(currentChar);
boolean currentCondition=isCharCondition(mappingChar,i,checkContext);
if (currentCondition) {
stringBuilder.append(currentChar);
}
else {
break;
}
}
if (isStringCondition(currentIx,stringBuilder,checkContext)) {
actualLength=stringBuilder.length();
}
return actualLength;
}
@Override protected int getActualLength(int beginIndex,InnerSensitiveWordContext checkContext){
final String txt=checkContext.originalText();
final IWordContext context=checkContext.wordContext();
final Map<Character,Character> formatCharMapping=checkContext.formatCharMapping();
int actualLength=0;
StringBuilder stringBuilder=new StringBuilder();
int currentIx=0;
for (int i=beginIndex; i < txt.length(); i++) {
currentIx=i;
char currentChar=txt.charAt(i);
char mappingChar=formatCharMapping.get(currentChar);
boolean currentCondition=isCharCondition(mappingChar,i,checkContext);
if (currentCondition) {
stringBuilder.append(currentChar);
}
else {
break;
}
}
if (isStringCondition(currentIx,stringBuilder,checkContext)) {
actualLength=stringBuilder.length();
}
return actualLength;
}
| {"types": [{"InnerSensitiveWordContext": "InnerSensitiveWordContext"}], "methods": [{"getWord": "getWord"}, {"length": "getActualLength"}], "similar_methods": [{"getActualLength": "getActualLength"}]} | [{"InnerSensitiveWordContext": {"retrieved_name": "InnerSensitiveWordContext", "raw_body": "/** \n * \u5185\u90e8\u4fe1\u606f\u4e0a\u4e0b\u6587\n * @author binbin.hou\n * @since 0.6.0\n */\npublic class InnerSensitiveWordContext {\n /** \n * \u539f\u59cb\u6587\u672c\n */\n private String originalText;\n /** \n * \u683c\u5f0f\u5316\u540e\u7684\u5b57\u7b26\n */\n private Map<Character,Character> formatCharMapping;\n /** \n * \u6821\u9a8c\u6a21\u5f0f\n */\n private WordValidModeEnum modeEnum;\n /** \n * \u539f\u59cb\u4e0a\u4e0b\u6587\n */\n private IWordContext wordContext;\n public static InnerSensitiveWordContext newInstance();\n public String originalText();\n public InnerSensitiveWordContext originalText( String text);\n public Map<Character,Character> formatCharMapping();\n public InnerSensitiveWordContext formatCharMapping( Map<Character,Character> formatCharMapping);\n public WordValidModeEnum modeEnum();\n public InnerSensitiveWordContext modeEnum( WordValidModeEnum modeEnum);\n public IWordContext wordContext();\n public InnerSensitiveWordContext wordContext( IWordContext context);\n}\n", "raw_body_no_cmt": "public class InnerSensitiveWordContext {\n private String originalText;\n private Map<Character,Character> formatCharMapping;\n private WordValidModeEnum modeEnum;\n private IWordContext wordContext;\n public static InnerSensitiveWordContext newInstance();\n public String originalText();\n public InnerSensitiveWordContext originalText( String text);\n public Map<Character,Character> formatCharMapping();\n public InnerSensitiveWordContext formatCharMapping( Map<Character,Character> formatCharMapping);\n public WordValidModeEnum modeEnum();\n public InnerSensitiveWordContext modeEnum( WordValidModeEnum modeEnum);\n public IWordContext wordContext();\n public InnerSensitiveWordContext wordContext( IWordContext context);\n}\n"}}] | [{"getWord": {"retrieved_name": "getWord", "raw_body": "public String getWord(){\n return word;\n}\n"}}, {"length": {"retrieved_name": "getActualLength", "raw_body": "@Override protected int getActualLength(int beginIndex,InnerSensitiveWordContext checkContext){\n final String txt=checkContext.originalText();\n final IWordContext context=checkContext.wordContext();\n final Map<Character,Character> formatCharMapping=checkContext.formatCharMapping();\n int actualLength=0;\n StringBuilder stringBuilder=new StringBuilder();\n int currentIx=0;\n for (int i=beginIndex; i < txt.length(); i++) {\n currentIx=i;\n char currentChar=txt.charAt(i);\n char mappingChar=formatCharMapping.get(currentChar);\n boolean currentCondition=isCharCondition(mappingChar,i,checkContext);\n if (currentCondition) {\n stringBuilder.append(currentChar);\n }\n else {\n break;\n }\n }\n if (isStringCondition(currentIx,stringBuilder,checkContext)) {\n actualLength=stringBuilder.length();\n }\n return actualLength;\n}\n"}}] | [{"getActualLength": {"retrieved_name": "getActualLength", "raw_body": "@Override protected int getActualLength(int beginIndex,InnerSensitiveWordContext checkContext){\n final String txt=checkContext.originalText();\n final IWordContext context=checkContext.wordContext();\n final Map<Character,Character> formatCharMapping=checkContext.formatCharMapping();\n int actualLength=0;\n StringBuilder stringBuilder=new StringBuilder();\n int currentIx=0;\n for (int i=beginIndex; i < txt.length(); i++) {\n currentIx=i;\n char currentChar=txt.charAt(i);\n char mappingChar=formatCharMapping.get(currentChar);\n boolean currentCondition=isCharCondition(mappingChar,i,checkContext);\n if (currentCondition) {\n stringBuilder.append(currentChar);\n }\n else {\n break;\n }\n }\n if (isStringCondition(currentIx,stringBuilder,checkContext)) {\n actualLength=stringBuilder.length();\n }\n return actualLength;\n}\n"}}] |
docker-java_docker-java | docker-java/docker-java-api/src/main/java/com/github/dockerjava/api/model/VolumeBinds.java | VolumeBinds | fromPrimitive | class VolumeBinds implements Serializable {
private static final long serialVersionUID = 1L;
private final VolumeBind[] binds;
public VolumeBinds(VolumeBind... binds) {
this.binds = binds;
}
public VolumeBind[] getBinds() {
return binds;
}
@JsonCreator
public static VolumeBinds fromPrimitive(Map<String, String> primitive) {<FILL_FUNCTION_BODY>}
@JsonValue
public Map<String, String> toPrimitive() {
return Stream.of(binds).collect(Collectors.toMap(
VolumeBind::getContainerPath,
VolumeBind::getHostPath
));
}
} |
return new VolumeBinds(
primitive.entrySet().stream()
.map(it -> new VolumeBind(it.getValue(), it.getKey()))
.toArray(VolumeBind[]::new)
);
|
return new VolumeBinds(
primitive.entrySet().stream()
.map(entry -> new VolumeBind(entry.getKey(), entry.getValue()))
.toArray(VolumeBind[]::new)
);
| [
"Map<String,String>"
] | [
"getValue",
"entrySet",
"getKey",
"map",
"stream",
"toArray"
] | [
"Map<String,String>"
] | [
"getKey",
"getValue",
"toArray",
"map",
"entrySet",
"stream"
] | {
"methods": [
"getValue",
"entrySet",
"getKey",
"map",
"stream",
"toArray"
],
"similar_methods": [
"fromPrimitive"
],
"types": [
"Map<String,String>"
]
} | /**
* Parse a Dockerfile.
*/
public class Dockerfile {
public final File dockerFile;
private final File baseDirectory;
public Dockerfile( File dockerFile, File baseDirectory);
private static class LineTransformer implements Function<String,Optional<? extends DockerfileStatement>> {
private int line=0;
@Override public Optional<? extends DockerfileStatement> apply( String input);
}
public Iterable<DockerfileStatement> getStatements() throws IOException;
public List<String> getIgnores() throws IOException;
public ScannedResult parse() throws IOException;
/**
* Result of scanning / parsing a docker file.
*/
public class ScannedResult {
final List<String> ignores;
final List<File> filesToAdd=new ArrayList<>();
public InputStream buildDockerFolderTar();
public InputStream buildDockerFolderTar( File directory);
@Override public String toString();
public ScannedResult() throws IOException;
/**
* Adds all files found in <code>directory</code> and subdirectories to <code>filesToAdd</code> collection. It also adds any empty directories if found.
* @param directory directory
* @throws DockerClientException when IO error occurs
*/
private void addFilesInDirectory( File directory);
private boolean isBaseDirectory( File directory);
/**
* Returns all matching ignore patterns for the given file name.
*/
private List<String> matchingIgnorePatterns( String fileName);
/**
* Returns the matching ignore pattern for the given file or null if it should NOT be ignored. Exception rules like "!Dockerfile" will be respected.
*/
private String effectiveMatchingIgnorePattern( File file);
}
}
public T getValue(){
return value;
}
public String getEntryPoint(){
return entryPoint;
}
public String getKey(){
return key;
}
public static ObjectMapper getMapper(){
return MAPPER;
}
@CheckForNull public String getStream(){
return stream;
}
@Override public String toString(){
return new StringBuilder().append(this.getClass().getSimpleName()).append("{").append("dockerCertPath=").append(dockerCertPath).append("}").toString();
}
@JsonCreator public static VolumesRW fromPrimitive(Map<String,Boolean> map){
return new VolumesRW(map.entrySet().stream().map(entry -> new VolumeRW(new Volume(entry.getKey()),AccessMode.fromBoolean(entry.getValue()))).toArray(VolumeRW[]::new));
}
| public class Dockerfile {
public final File dockerFile;
private final File baseDirectory;
public Dockerfile( File dockerFile, File baseDirectory);
private static class LineTransformer implements Function<String,Optional<? extends DockerfileStatement>> {
private int line=0;
public Optional<? extends DockerfileStatement> apply( String input);
}
public Iterable<DockerfileStatement> getStatements() throws IOException;
public List<String> getIgnores() throws IOException;
public ScannedResult parse() throws IOException;
public class ScannedResult {
final List<String> ignores;
final List<File> filesToAdd=new ArrayList<>();
public InputStream buildDockerFolderTar();
public InputStream buildDockerFolderTar( File directory);
public String toString();
public ScannedResult() throws IOException;
private void addFilesInDirectory( File directory);
private boolean isBaseDirectory( File directory);
private List<String> matchingIgnorePatterns( String fileName);
private String effectiveMatchingIgnorePattern( File file);
}
}
public T getValue(){
return value;
}
public String getEntryPoint(){
return entryPoint;
}
public String getKey(){
return key;
}
public static ObjectMapper getMapper(){
return MAPPER;
}
@CheckForNull public String getStream(){
return stream;
}
@Override public String toString(){
return new StringBuilder().append(this.getClass().getSimpleName()).append("{").append("dockerCertPath=").append(dockerCertPath).append("}").toString();
}
@JsonCreator public static VolumesRW fromPrimitive(Map<String,Boolean> map){
return new VolumesRW(map.entrySet().stream().map(entry -> new VolumeRW(new Volume(entry.getKey()),AccessMode.fromBoolean(entry.getValue()))).toArray(VolumeRW[]::new));
}
| {"types": [{"Map<String,String>": "Dockerfile"}], "methods": [{"getValue": "getValue"}, {"entrySet": "getEntryPoint"}, {"getKey": "getKey"}, {"map": "getMapper"}, {"stream": "getStream"}, {"toArray": "toString"}], "similar_methods": [{"fromPrimitive": "fromPrimitive"}]} | [{"Map<String,String>": {"retrieved_name": "Dockerfile", "raw_body": "/** \n * Parse a Dockerfile.\n */\npublic class Dockerfile {\n public final File dockerFile;\n private final File baseDirectory;\n public Dockerfile( File dockerFile, File baseDirectory);\nprivate static class LineTransformer implements Function<String,Optional<? extends DockerfileStatement>> {\n private int line=0;\n @Override public Optional<? extends DockerfileStatement> apply( String input);\n }\n public Iterable<DockerfileStatement> getStatements() throws IOException;\n public List<String> getIgnores() throws IOException;\n public ScannedResult parse() throws IOException;\n /** \n * Result of scanning / parsing a docker file.\n */\npublic class ScannedResult {\n final List<String> ignores;\n final List<File> filesToAdd=new ArrayList<>();\n public InputStream buildDockerFolderTar();\n public InputStream buildDockerFolderTar( File directory);\n @Override public String toString();\n public ScannedResult() throws IOException;\n /** \n * Adds all files found in <code>directory</code> and subdirectories to <code>filesToAdd</code> collection. It also adds any empty directories if found.\n * @param directory directory\n * @throws DockerClientException when IO error occurs\n */\n private void addFilesInDirectory( File directory);\n private boolean isBaseDirectory( File directory);\n /** \n * Returns all matching ignore patterns for the given file name.\n */\n private List<String> matchingIgnorePatterns( String fileName);\n /** \n * Returns the matching ignore pattern for the given file or null if it should NOT be ignored. Exception rules like \"!Dockerfile\" will be respected.\n */\n private String effectiveMatchingIgnorePattern( File file);\n }\n}\n", "raw_body_no_cmt": "public class Dockerfile {\n public final File dockerFile;\n private final File baseDirectory;\n public Dockerfile( File dockerFile, File baseDirectory);\nprivate static class LineTransformer implements Function<String,Optional<? extends DockerfileStatement>> {\n private int line=0;\n public Optional<? extends DockerfileStatement> apply( String input);\n }\n public Iterable<DockerfileStatement> getStatements() throws IOException;\n public List<String> getIgnores() throws IOException;\n public ScannedResult parse() throws IOException;\n public class ScannedResult {\n final List<String> ignores;\n final List<File> filesToAdd=new ArrayList<>();\n public InputStream buildDockerFolderTar();\n public InputStream buildDockerFolderTar( File directory);\n public String toString();\n public ScannedResult() throws IOException;\n private void addFilesInDirectory( File directory);\n private boolean isBaseDirectory( File directory);\n private List<String> matchingIgnorePatterns( String fileName);\n private String effectiveMatchingIgnorePattern( File file);\n }\n}\n"}}] | [{"getValue": {"retrieved_name": "getValue", "raw_body": "public T getValue(){\n return value;\n}\n"}}, {"entrySet": {"retrieved_name": "getEntryPoint", "raw_body": "public String getEntryPoint(){\n return entryPoint;\n}\n"}}, {"getKey": {"retrieved_name": "getKey", "raw_body": "public String getKey(){\n return key;\n}\n"}}, {"map": {"retrieved_name": "getMapper", "raw_body": "public static ObjectMapper getMapper(){\n return MAPPER;\n}\n"}}, {"stream": {"retrieved_name": "getStream", "raw_body": "@CheckForNull public String getStream(){\n return stream;\n}\n"}}, {"toArray": {"retrieved_name": "toString", "raw_body": "@Override public String toString(){\n return new StringBuilder().append(this.getClass().getSimpleName()).append(\"{\").append(\"dockerCertPath=\").append(dockerCertPath).append(\"}\").toString();\n}\n"}}] | [{"fromPrimitive": {"retrieved_name": "fromPrimitive", "raw_body": "@JsonCreator public static VolumesRW fromPrimitive(Map<String,Boolean> map){\n return new VolumesRW(map.entrySet().stream().map(entry -> new VolumeRW(new Volume(entry.getKey()),AccessMode.fromBoolean(entry.getValue()))).toArray(VolumeRW[]::new));\n}\n"}}] |
|
subhra74_snowflake | snowflake/muon-app/src/main/java/util/FormatUtils.java | FormatUtils | humanReadableByteCount | class FormatUtils {
public static String humanReadableByteCount(long bytes, boolean si) {<FILL_FUNCTION_BODY>}
public static final String formatDate(LocalDateTime dateTime) {
return dateTime.format(DateTimeFormatter.ofPattern("MM/dd/yyyy hh:mm a"));
}
} |
int unit = si ? 1000 : 1024;
if (bytes < unit)
return bytes + " B";
int exp = (int) (Math.log(bytes) / Math.log(unit));
String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp - 1)
+ (si ? "" : "i");
return String.format("%.1f %s", bytes / Math.pow(unit, exp), pre);
|
int unit = si ? 1000 : 1024;
if (bytes < unit) return bytes + " B";
int exp = (int) (Math.log(bytes) / Math.log(unit));
String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp - 1) + (si ? "" : "i");
return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre);
| [] | [
"charAt",
"format",
"pow",
"log"
] | [] | [
"charAt",
"pow",
"format",
"log"
] | {
"methods": [
"charAt",
"format",
"pow",
"log"
],
"similar_methods": [
"humanReadableByteCount"
],
"types": []
} | public char charAt(int x){
String text=getText();
return x < text.length() ? text.charAt(x) : CharUtils.EMPTY_CHAR;
}
public static final String formatDate(LocalDateTime dateTime){
return dateTime.format(DateTimeFormatter.ofPattern("MM/dd/yyyy hh:mm a"));
}
private void open(){
FileInfo files[]=folderView.getSelectedFiles();
if (files.length == 1) {
FileInfo file=files[0];
if (file.getType() == FileType.FileLink || file.getType() == FileType.File) {
}
}
}
private static void logException(String message,Exception e){
if (UIUtil.isWindows && e instanceof IllegalStateException) {
LOG.debug(message,e);
}
else {
LOG.warn(message,e);
}
}
public String readOutput(String command) throws IOException {
String line;
Process process=Runtime.getRuntime().exec(command);
Reader inStreamReader=new InputStreamReader(process.getInputStream());
BufferedReader in=new BufferedReader(inStreamReader);
StringBuilder sb=new StringBuilder();
int i=0;
String lastNum=null;
while ((line=in.readLine()) != null) {
if (!line.startsWith("&") && !line.startsWith("\"")) {
lastNum=String.format("%3d ",i++);
sb.append(lastNum);
}
else {
if (lastNum != null) {
sb.append(CharBuffer.allocate(lastNum.length()).toString().replace('\0',' '));
}
}
sb.append(line);
sb.append("\n");
}
in.close();
return sb.toString();
}
| public char charAt(int x){
String text=getText();
return x < text.length() ? text.charAt(x) : CharUtils.EMPTY_CHAR;
}
public static final String formatDate(LocalDateTime dateTime){
return dateTime.format(DateTimeFormatter.ofPattern("MM/dd/yyyy hh:mm a"));
}
private void open(){
FileInfo files[]=folderView.getSelectedFiles();
if (files.length == 1) {
FileInfo file=files[0];
if (file.getType() == FileType.FileLink || file.getType() == FileType.File) {
}
}
}
private static void logException(String message,Exception e){
if (UIUtil.isWindows && e instanceof IllegalStateException) {
LOG.debug(message,e);
}
else {
LOG.warn(message,e);
}
}
public String readOutput(String command) throws IOException {
String line;
Process process=Runtime.getRuntime().exec(command);
Reader inStreamReader=new InputStreamReader(process.getInputStream());
BufferedReader in=new BufferedReader(inStreamReader);
StringBuilder sb=new StringBuilder();
int i=0;
String lastNum=null;
while ((line=in.readLine()) != null) {
if (!line.startsWith("&") && !line.startsWith("\"")) {
lastNum=String.format("%3d ",i++);
sb.append(lastNum);
}
else {
if (lastNum != null) {
sb.append(CharBuffer.allocate(lastNum.length()).toString().replace('\0',' '));
}
}
sb.append(line);
sb.append("\n");
}
in.close();
return sb.toString();
}
| {"methods": [{"charAt": "charAt"}, {"format": "formatDate"}, {"pow": "open"}, {"log": "logException"}], "similar_methods": [{"humanReadableByteCount": "readOutput"}]} | [] | [{"charAt": {"retrieved_name": "charAt", "raw_body": "public char charAt(int x){\n String text=getText();\n return x < text.length() ? text.charAt(x) : CharUtils.EMPTY_CHAR;\n}\n"}}, {"format": {"retrieved_name": "formatDate", "raw_body": "public static final String formatDate(LocalDateTime dateTime){\n return dateTime.format(DateTimeFormatter.ofPattern(\"MM/dd/yyyy hh:mm a\"));\n}\n"}}, {"pow": {"retrieved_name": "open", "raw_body": "private void open(){\n FileInfo files[]=folderView.getSelectedFiles();\n if (files.length == 1) {\n FileInfo file=files[0];\n if (file.getType() == FileType.FileLink || file.getType() == FileType.File) {\n }\n }\n}\n"}}, {"log": {"retrieved_name": "logException", "raw_body": "private static void logException(String message,Exception e){\n if (UIUtil.isWindows && e instanceof IllegalStateException) {\n LOG.debug(message,e);\n }\n else {\n LOG.warn(message,e);\n }\n}\n"}}] | [{"humanReadableByteCount": {"retrieved_name": "readOutput", "raw_body": "public String readOutput(String command) throws IOException {\n String line;\n Process process=Runtime.getRuntime().exec(command);\n Reader inStreamReader=new InputStreamReader(process.getInputStream());\n BufferedReader in=new BufferedReader(inStreamReader);\n StringBuilder sb=new StringBuilder();\n int i=0;\n String lastNum=null;\n while ((line=in.readLine()) != null) {\n if (!line.startsWith(\"&\") && !line.startsWith(\"\\\"\")) {\n lastNum=String.format(\"%3d \",i++);\n sb.append(lastNum);\n }\n else {\n if (lastNum != null) {\n sb.append(CharBuffer.allocate(lastNum.length()).toString().replace('\\0',' '));\n }\n }\n sb.append(line);\n sb.append(\"\\n\");\n }\n in.close();\n return sb.toString();\n}\n"}}] |
|
zhkl0228_unidbg | unidbg/unidbg-android/src/main/java/com/github/unidbg/linux/struct/IFReq.java | IFReq | setName | class IFReq extends UnidbgStructure {
static final int IFNAMSIZ = 16;
public static IFReq createIFReq(Emulator<?> emulator, Pointer pointer) {
return emulator.is64Bit() ? new IFReq64(pointer) : new IFReq32(pointer);
}
IFReq(Pointer p) {
super(p);
}
public Pointer getAddrPointer() {
return getPointer().share(IFNAMSIZ);
}
public void setName(String name) {<FILL_FUNCTION_BODY>}
public byte[] ifrn_name = new byte[IFNAMSIZ];
} |
byte[] data = name.getBytes(StandardCharsets.UTF_8);
if (data.length >= IFNAMSIZ) {
throw new IllegalStateException("name=" + name);
}
ifrn_name = Arrays.copyOf(data, IFNAMSIZ);
| public abstract class UnidbgStructure extends Structure implements PointerArg {
/**
* Placeholder pointer to help avoid auto-allocation of memory where a Structure needs a valid pointer but want to avoid actually reading from it.
*/
private static final Pointer PLACEHOLDER_MEMORY=new UnidbgPointer(null,null){
@Override public UnidbgPointer share( long offset, long sz);
}
;
public static int calculateSize( Class<? extends UnidbgStructure> type);
private static class ByteArrayPointer extends UnidbgPointer {
private final Emulator<?> emulator;
private final byte[] data;
public ByteArrayPointer( Emulator<?> emulator, byte[] data);
@Override public UnidbgPointer share( long offset, long sz);
}
protected UnidbgStructure( Emulator<?> emulator, byte[] data);
protected UnidbgStructure( byte[] data);
protected UnidbgStructure( Pointer p);
private void checkPointer( Pointer p);
@Override protected int getNativeSize( Class<?> nativeType, Object value);
@Override protected int getNativeAlignment( Class<?> type, Object value, boolean isFirstElement);
private boolean isPlaceholderMemory( Pointer p);
public void pack();
public void unpack();
/**
* @param debug If true, will include a native memory dump of theStructure's backing memory.
* @return String representation of this object.
*/
public String toString( boolean debug);
private String format( Class<?> type);
private String toString( int indent, boolean showContents, boolean dumpMemory);
/**
* Obtain the value currently in the Java field. Does not read from native memory.
* @param field field to look up
* @return current field value (Java-side only)
*/
private Object getFieldValue( Field field);
private static final Field FIELD_STRUCT_FIELDS;
static {
try {
FIELD_STRUCT_FIELDS=Structure.class.getDeclaredField("structFields");
FIELD_STRUCT_FIELDS.setAccessible(true);
}
catch ( NoSuchFieldException e) {
throw new IllegalStateException(e);
}
}
/**
* Return all fields in this structure (ordered). This represents the layout of the structure, and will be shared among Structures of the same class except when the Structure can have a variable size. NOTE: {@link #ensureAllocated()} <em>must</em> be called prior tocalling this method.
* @return {@link Map} of field names to field representations.
*/
@SuppressWarnings("unchecked") private Map<String,StructField> fields();
}
|
byte[] bytes = name.getBytes(StandardCharsets.UTF_8);
if (bytes.length > IFNAMSIZ) {
throw new IllegalArgumentException("Interface name too long");
}
System.arraycopy(bytes, 0, ifrn_name, 0, bytes.length);
| [] | [
"getBytes",
"arraycopy"
] | [] | [
"copyOf",
"getBytes"
] | {
"methods": [
"getBytes",
"arraycopy"
],
"similar_methods": [
"setName"
],
"types": []
} | public byte[] getBytes(){
int length=object.callObjcInt("length");
Pointer bytes=getBytesPointer();
return bytes.getByteArray(0,length);
}
public void copy(KEvent64 pending){
this.ident=pending.ident;
this.filter=pending.filter;
this.flags=pending.flags;
this.fflags=pending.fflags;
this.data=pending.data;
this.udata=pending.udata;
this.ext=pending.ext;
}
public void setName(String name){
this.name=name;
}
| public byte[] getBytes(){
int length=object.callObjcInt("length");
Pointer bytes=getBytesPointer();
return bytes.getByteArray(0,length);
}
public void copy(KEvent64 pending){
this.ident=pending.ident;
this.filter=pending.filter;
this.flags=pending.flags;
this.fflags=pending.fflags;
this.data=pending.data;
this.udata=pending.udata;
this.ext=pending.ext;
}
public void setName(String name){
this.name=name;
}
| {"methods": [{"getBytes": "getBytes"}, {"arraycopy": "copy"}], "similar_methods": [{"setName": "setName"}]} | [] | [{"getBytes": {"retrieved_name": "getBytes", "raw_body": "public byte[] getBytes(){\n int length=object.callObjcInt(\"length\");\n Pointer bytes=getBytesPointer();\n return bytes.getByteArray(0,length);\n}\n"}}, {"arraycopy": {"retrieved_name": "copy", "raw_body": "public void copy(KEvent64 pending){\n this.ident=pending.ident;\n this.filter=pending.filter;\n this.flags=pending.flags;\n this.fflags=pending.fflags;\n this.data=pending.data;\n this.udata=pending.udata;\n this.ext=pending.ext;\n}\n"}}] | [{"setName": {"retrieved_name": "setName", "raw_body": "public void setName(String name){\n this.name=name;\n}\n"}}] |
subhra74_snowflake | snowflake/muon-app/src/main/java/util/FontUtils.java | FontUtils | loadTerminalFont | class FontUtils {
public static final Map<String, String> TERMINAL_FONTS = new CollectionHelper.OrderedDict<String, String>()
.putItem("DejaVuSansMono", "DejaVu Sans Mono").putItem("FiraCode-Regular", "Fira Code Regular")
.putItem("Inconsolata-Regular", "Inconsolata Regular").putItem("NotoMono-Regular", "Noto Mono");
public static Font loadFont(String path) {
try (InputStream is = AppSkin.class.getResourceAsStream(path)) {
Font font = Font.createFont(Font.TRUETYPE_FONT, is);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(font);
System.out.println("Font loaded: " + font.getFontName() + " of family: " + font.getFamily());
return font.deriveFont(Font.PLAIN, 12.0f);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static Font loadTerminalFont(String name) {<FILL_FUNCTION_BODY>}
} |
System.out.println("Loading font: "+name);
try (InputStream is = AppSkin.class.getResourceAsStream(String.format("/fonts/terminal/%s.ttf", name))) {
Font font = Font.createFont(Font.TRUETYPE_FONT, is);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(font);
System.out.println("Font loaded: " + font.getFontName() + " of family: " + font.getFamily());
return font.deriveFont(Font.PLAIN, 12.0f);
} catch (Exception e) {
e.printStackTrace();
}
return null;
|
return loadFont("/fonts/" + name + ".ttf");
| [] | [] | [
"Exception",
"Font",
"GraphicsEnvironment"
] | [
"registerFont",
"printStackTrace",
"format",
"deriveFont",
"getResourceAsStream",
"getFontName",
"getLocalGraphicsEnvironment",
"createFont",
"getFamily",
"println"
] | {
"methods": [],
"similar_methods": [
"loadTerminalFont"
],
"types": []
} | @Override public Font getTerminalFont(){
System.out.println("Called terminal font: " + App.getGlobalSettings().getTerminalFontName());
return FontUtils.loadTerminalFont(App.getGlobalSettings().getTerminalFontName()).deriveFont(Font.PLAIN,App.getGlobalSettings().getTerminalFontSize());
}
| @Override public Font getTerminalFont(){
System.out.println("Called terminal font: " + App.getGlobalSettings().getTerminalFontName());
return FontUtils.loadTerminalFont(App.getGlobalSettings().getTerminalFontName()).deriveFont(Font.PLAIN,App.getGlobalSettings().getTerminalFontSize());
}
| {"similar_methods": [{"loadTerminalFont": "getTerminalFont"}]} | [] | [] | [{"loadTerminalFont": {"retrieved_name": "getTerminalFont", "raw_body": "@Override public Font getTerminalFont(){\n System.out.println(\"Called terminal font: \" + App.getGlobalSettings().getTerminalFontName());\n return FontUtils.loadTerminalFont(App.getGlobalSettings().getTerminalFontName()).deriveFont(Font.PLAIN,App.getGlobalSettings().getTerminalFontSize());\n}\n"}}] |
|
pmd_pmd | pmd/pmd-velocity/src/main/java/net/sourceforge/pmd/lang/velocity/rule/bestpractices/UnusedMacroParameterRule.java | UnusedMacroParameterRule | formatNameVariations | class UnusedMacroParameterRule extends AbstractVtlRule {
@Override
public Object visit(final ASTDirective node, final Object data) {
if ("macro".equals(node.getDirectiveName())) {
final Set<String> paramNames = new HashSet<>();
for (final ASTReference param : node.children(ASTReference.class)) {
paramNames.add(param.literal());
}
final ASTBlock macroBlock = node.firstChild(ASTBlock.class);
if (macroBlock != null) {
for (final ASTReference referenceInMacro : macroBlock.descendants(ASTReference.class)) {
checkForParameter(paramNames, referenceInMacro.literal());
}
for (final ASTStringLiteral literalInMacro : macroBlock.descendants(ASTStringLiteral.class)) {
final String text = literalInMacro.literal();
checkForParameter(paramNames, text);
}
}
if (!paramNames.isEmpty()) {
asCtx(data).addViolation(node, paramNames.toString());
}
}
return super.visit(node, data);
}
private void checkForParameter(final Set<String> paramNames, final String nameToSearch) {
final Set<String> paramsContained = new HashSet<>();
for (final String param : paramNames) {
if (containsAny(nameToSearch, formatNameVariations(param))) {
paramsContained.add(param);
}
}
paramNames.removeAll(paramsContained);
}
private boolean containsAny(final String text, final String[] formatNameVariations) {
for (final String formattedName : formatNameVariations) {
if (text.contains(formattedName)) {
return true;
}
}
return false;
}
private String[] formatNameVariations(final String param) {<FILL_FUNCTION_BODY>}
} |
final String actualName = param.substring(1);
return new String[] { param, "${" + actualName + "}", "${" + actualName + ".", "$!" + actualName,
"$!{" + actualName + ".", "$!{" + actualName + "}", };
|
return new String[]{param, param.toUpperCase(), param.toLowerCase()};
| [] | [
"toLowerCase",
"toUpperCase"
] | [] | [
"substring"
] | {
"methods": [
"toLowerCase",
"toUpperCase"
],
"similar_methods": [
"formatNameVariations"
],
"types": []
} | @Test void testWildLowerLower(){
InferenceContext ctx=emptyCtx();
InferenceVar a=newIvar(ctx);
InferenceVar b=newIvar(ctx);
addSubtypeConstraint(ctx,listType(superWild(a)),listType(superWild(b)));
assertThat(a,hasBoundsExactly(lower(b)));
assertThat(b,hasBoundsExactly(upper(a)));
}
@Override public JTypeVar withUpperBound(@NonNull JTypeMirror newUB){
throw new UnsupportedOperationException("this is a test only object which should only be used for equals");
}
private static String formatMemberName(ASTClassType qualifier,JAccessibleElementSymbol call){
JClassSymbol methodOwner=call.getEnclosingClass();
if (methodOwner != null && !methodOwner.equals(qualifier.getTypeMirror().getSymbol())) {
return methodOwner.getSimpleName() + "::" + call.getSimpleName();
}
return call.getSimpleName();
}
| @Test void testWildLowerLower(){
InferenceContext ctx=emptyCtx();
InferenceVar a=newIvar(ctx);
InferenceVar b=newIvar(ctx);
addSubtypeConstraint(ctx,listType(superWild(a)),listType(superWild(b)));
assertThat(a,hasBoundsExactly(lower(b)));
assertThat(b,hasBoundsExactly(upper(a)));
}
@Override public JTypeVar withUpperBound(@NonNull JTypeMirror newUB){
throw new UnsupportedOperationException("this is a test only object which should only be used for equals");
}
private static String formatMemberName(ASTClassType qualifier,JAccessibleElementSymbol call){
JClassSymbol methodOwner=call.getEnclosingClass();
if (methodOwner != null && !methodOwner.equals(qualifier.getTypeMirror().getSymbol())) {
return methodOwner.getSimpleName() + "::" + call.getSimpleName();
}
return call.getSimpleName();
}
| {"methods": [{"toLowerCase": "testWildLowerLower"}, {"toUpperCase": "withUpperBound"}], "similar_methods": [{"formatNameVariations": "formatMemberName"}]} | [] | [{"toLowerCase": {"retrieved_name": "testWildLowerLower", "raw_body": "@Test void testWildLowerLower(){\n InferenceContext ctx=emptyCtx();\n InferenceVar a=newIvar(ctx);\n InferenceVar b=newIvar(ctx);\n addSubtypeConstraint(ctx,listType(superWild(a)),listType(superWild(b)));\n assertThat(a,hasBoundsExactly(lower(b)));\n assertThat(b,hasBoundsExactly(upper(a)));\n}\n"}}, {"toUpperCase": {"retrieved_name": "withUpperBound", "raw_body": "@Override public JTypeVar withUpperBound(@NonNull JTypeMirror newUB){\n throw new UnsupportedOperationException(\"this is a test only object which should only be used for equals\");\n}\n"}}] | [{"formatNameVariations": {"retrieved_name": "formatMemberName", "raw_body": "private static String formatMemberName(ASTClassType qualifier,JAccessibleElementSymbol call){\n JClassSymbol methodOwner=call.getEnclosingClass();\n if (methodOwner != null && !methodOwner.equals(qualifier.getTypeMirror().getSymbol())) {\n return methodOwner.getSimpleName() + \"::\" + call.getSimpleName();\n }\n return call.getSimpleName();\n}\n"}}] |
|
jeecgboot_jeecg-boot | jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/config/sign/util/SignUtil.java | SignUtil | getParamsSign | class SignUtil {
public static final String X_PATH_VARIABLE = "x-path-variable";
/**
* @param params
* 所有的请求参数都会在这里进行排序加密
* @return 验证签名结果
*/
public static boolean verifySign(SortedMap<String, String> params,String headerSign) {
if (params == null || StringUtils.isEmpty(headerSign)) {
return false;
}
// 把参数加密
String paramsSign = getParamsSign(params);
log.info("Param Sign : {}", paramsSign);
return !StringUtils.isEmpty(paramsSign) && headerSign.equals(paramsSign);
}
/**
* @param params
* 所有的请求参数都会在这里进行排序加密
* @return 得到签名
*/
public static String getParamsSign(SortedMap<String, String> params) {<FILL_FUNCTION_BODY>}
} |
//去掉 Url 里的时间戳
params.remove("_t");
String paramsJsonStr = JSONObject.toJSONString(params);
log.info("Param paramsJsonStr : {}", paramsJsonStr);
//设置签名秘钥
JeecgBaseConfig jeecgBaseConfig = SpringContextUtils.getBean(JeecgBaseConfig.class);
String signatureSecret = jeecgBaseConfig.getSignatureSecret();
String curlyBracket = SymbolConstant.DOLLAR + SymbolConstant.LEFT_CURLY_BRACKET;
if(oConvertUtils.isEmpty(signatureSecret) || signatureSecret.contains(curlyBracket)){
throw new JeecgBootException("签名密钥 ${jeecg.signatureSecret} 缺少配置 !!");
}
try {
//【issues/I484RW】2.4.6部署后,下拉搜索框提示“sign签名检验失败”
return DigestUtils.md5DigestAsHex((paramsJsonStr + signatureSecret).getBytes("UTF-8")).toUpperCase();
} catch (UnsupportedEncodingException e) {
log.error(e.getMessage(),e);
return null;
}
|
StringBuilder sb = new StringBuilder();
Set<String> keySet = params.keySet();
for (String key : keySet) {
String value = params.get(key);
if (StringUtils.isNotEmpty(value)) {
sb.append(key).append("=").append(value).append("&");
}
}
String paramsSign = sb.toString();
paramsSign = paramsSign.substring(0, paramsSign.length() - 1);
return DigestUtils.md5Hex(paramsSign);
| [
"Set<String>",
"SortedMap<String,String>"
] | [
"substring",
"isNotEmpty",
"md5Hex",
"get",
"append",
"toString",
"keySet",
"length"
] | [
"SortedMap<String,String>",
"UnsupportedEncodingException",
"JeecgBaseConfig"
] | [
"getBean",
"md5DigestAsHex",
"isEmpty",
"toJSONString",
"getBytes",
"getMessage",
"remove",
"toUpperCase",
"error",
"getSignatureSecret",
"contains",
"info"
] | {
"methods": [
"substring",
"isNotEmpty",
"md5Hex",
"get",
"append",
"toString",
"keySet",
"length"
],
"similar_methods": [
"getParamsSign"
],
"types": [
"Set<String>",
"SortedMap<String,String>"
]
} | /**
* @Description : EncryptedString
* @author : jeecg-boot
*/
@Data public class EncryptedString {
/**
* 长度为16个字符
*/
public static String key="1234567890adbcde";
/**
* 长度为16个字符
*/
public static String iv="1234567890hjlkew";
}
/**
* 处理子查询
* @param subSelect
*/
private void handleSubSelect(SubSelect subSelect){
try {
String subSelectSql=subSelect.getSelectBody().toString();
Map<String,SelectSqlInfo> map=JSqlParserUtils.parseAllSelectTable(subSelectSql);
if (map != null) {
this.assignMap(map);
}
}
catch ( Exception e) {
log.error("解析子查询出错",e);
}
}
public static boolean isNotEmpty(Object object){
if (object != null && !"".equals(object) && !object.equals(CommonConstant.STRING_NULL)) {
return (true);
}
return (false);
}
public static String md5Encode(String origin,String charsetname){
String resultString=null;
try {
resultString=new String(origin);
MessageDigest md=MessageDigest.getInstance("MD5");
if (charsetname == null || "".equals(charsetname)) {
resultString=byteArrayToHexString(md.digest(resultString.getBytes()));
}
else {
resultString=byteArrayToHexString(md.digest(resultString.getBytes(charsetname)));
}
}
catch ( Exception exception) {
}
return resultString;
}
/**
* 发送 get 请求
*/
public static JSONObject get(String url){
return getNative(url,null,null).getBody();
}
/**
* 单库分表 —— 添加
* @return
*/
@PostMapping(value="/test1") @ApiOperation(value="单库分表插入",notes="单库分表") public Result<?> add(){
log.info("---------------------------------单库分表插入--------------------------------");
int size=10;
for (int i=0; i < size; i++) {
ShardingSysLog shardingSysLog=new ShardingSysLog();
shardingSysLog.setLogContent("jeecg");
shardingSysLog.setLogType(i);
shardingSysLog.setOperateType(i);
shardingSysLogService.save(shardingSysLog);
}
return Result.OK("单库分表插入10条数据完成!");
}
@Override public String toString(){
return "RedisInfo{" + "key='" + key + '\''+ ", value='"+ value+ '\''+ ", desctiption='"+ description+ '\''+ '}';
}
TreeSet<Integer> getSet(int type){
switch (type) {
case SECOND:
return seconds;
case MINUTE:
return minutes;
case HOUR:
return hours;
case DAY_OF_MONTH:
return daysOfMonth;
case MONTH:
return months;
case DAY_OF_WEEK:
return daysOfWeek;
case YEAR:
return years;
default :
return null;
}
}
public static long stringToLong(String str){
Long test=new Long(0);
try {
test=Long.valueOf(str);
}
catch ( Exception e) {
}
return test.longValue();
}
public String getSignName(){
return signName;
}
| public class EncryptedString {
public static String key="1234567890adbcde";
public static String iv="1234567890hjlkew";
}
/**
* 处理子查询
* @param subSelect
*/
private void handleSubSelect(SubSelect subSelect){
try {
String subSelectSql=subSelect.getSelectBody().toString();
Map<String,SelectSqlInfo> map=JSqlParserUtils.parseAllSelectTable(subSelectSql);
if (map != null) {
this.assignMap(map);
}
}
catch ( Exception e) {
log.error("解析子查询出错",e);
}
}
public static boolean isNotEmpty(Object object){
if (object != null && !"".equals(object) && !object.equals(CommonConstant.STRING_NULL)) {
return (true);
}
return (false);
}
public static String md5Encode(String origin,String charsetname){
String resultString=null;
try {
resultString=new String(origin);
MessageDigest md=MessageDigest.getInstance("MD5");
if (charsetname == null || "".equals(charsetname)) {
resultString=byteArrayToHexString(md.digest(resultString.getBytes()));
}
else {
resultString=byteArrayToHexString(md.digest(resultString.getBytes(charsetname)));
}
}
catch ( Exception exception) {
}
return resultString;
}
/**
* 发送 get 请求
*/
public static JSONObject get(String url){
return getNative(url,null,null).getBody();
}
/**
* 单库分表 —— 添加
* @return
*/
@PostMapping(value="/test1") @ApiOperation(value="单库分表插入",notes="单库分表") public Result<?> add(){
log.info("---------------------------------单库分表插入--------------------------------");
int size=10;
for (int i=0; i < size; i++) {
ShardingSysLog shardingSysLog=new ShardingSysLog();
shardingSysLog.setLogContent("jeecg");
shardingSysLog.setLogType(i);
shardingSysLog.setOperateType(i);
shardingSysLogService.save(shardingSysLog);
}
return Result.OK("单库分表插入10条数据完成!");
}
@Override public String toString(){
return "RedisInfo{" + "key='" + key + '\''+ ", value='"+ value+ '\''+ ", desctiption='"+ description+ '\''+ '}';
}
TreeSet<Integer> getSet(int type){
switch (type) {
case SECOND:
return seconds;
case MINUTE:
return minutes;
case HOUR:
return hours;
case DAY_OF_MONTH:
return daysOfMonth;
case MONTH:
return months;
case DAY_OF_WEEK:
return daysOfWeek;
case YEAR:
return years;
default :
return null;
}
}
public static long stringToLong(String str){
Long test=new Long(0);
try {
test=Long.valueOf(str);
}
catch ( Exception e) {
}
return test.longValue();
}
public String getSignName(){
return signName;
}
| {"types": [{"Set<String>": "EncryptedString"}, {"SortedMap<String,String>": "EncryptedString"}], "methods": [{"substring": "handleSubSelect"}, {"isNotEmpty": "isNotEmpty"}, {"md5Hex": "md5Encode"}, {"get": "get"}, {"append": "add"}, {"toString": "toString"}, {"keySet": "getSet"}, {"length": "stringToLong"}], "similar_methods": [{"getParamsSign": "getSignName"}]} | [{"Set<String>": {"retrieved_name": "EncryptedString", "raw_body": "/** \n * @Description : EncryptedString\n * @author : jeecg-boot\n */\n@Data public class EncryptedString {\n /** \n * \u957f\u5ea6\u4e3a16\u4e2a\u5b57\u7b26\n */\n public static String key=\"1234567890adbcde\";\n /** \n * \u957f\u5ea6\u4e3a16\u4e2a\u5b57\u7b26\n */\n public static String iv=\"1234567890hjlkew\";\n}\n", "raw_body_no_cmt": "public class EncryptedString {\n public static String key=\"1234567890adbcde\";\n public static String iv=\"1234567890hjlkew\";\n}\n"}}] | [{"substring": {"retrieved_name": "handleSubSelect", "raw_body": "/** \n * \u5904\u7406\u5b50\u67e5\u8be2\n * @param subSelect\n */\nprivate void handleSubSelect(SubSelect subSelect){\n try {\n String subSelectSql=subSelect.getSelectBody().toString();\n Map<String,SelectSqlInfo> map=JSqlParserUtils.parseAllSelectTable(subSelectSql);\n if (map != null) {\n this.assignMap(map);\n }\n }\n catch ( Exception e) {\n log.error(\"\u89e3\u6790\u5b50\u67e5\u8be2\u51fa\u9519\",e);\n }\n}\n"}}, {"isNotEmpty": {"retrieved_name": "isNotEmpty", "raw_body": "public static boolean isNotEmpty(Object object){\n if (object != null && !\"\".equals(object) && !object.equals(CommonConstant.STRING_NULL)) {\n return (true);\n }\n return (false);\n}\n"}}, {"md5Hex": {"retrieved_name": "md5Encode", "raw_body": "public static String md5Encode(String origin,String charsetname){\n String resultString=null;\n try {\n resultString=new String(origin);\n MessageDigest md=MessageDigest.getInstance(\"MD5\");\n if (charsetname == null || \"\".equals(charsetname)) {\n resultString=byteArrayToHexString(md.digest(resultString.getBytes()));\n }\n else {\n resultString=byteArrayToHexString(md.digest(resultString.getBytes(charsetname)));\n }\n }\n catch ( Exception exception) {\n }\n return resultString;\n}\n"}}, {"get": {"retrieved_name": "get", "raw_body": "/** \n * \u53d1\u9001 get \u8bf7\u6c42\n */\npublic static JSONObject get(String url){\n return getNative(url,null,null).getBody();\n}\n"}}, {"append": {"retrieved_name": "add", "raw_body": "/** \n * \u5355\u5e93\u5206\u8868 \u2014\u2014 \u6dfb\u52a0\n * @return\n */\n@PostMapping(value=\"/test1\") @ApiOperation(value=\"\u5355\u5e93\u5206\u8868\u63d2\u5165\",notes=\"\u5355\u5e93\u5206\u8868\") public Result<?> add(){\n log.info(\"---------------------------------\u5355\u5e93\u5206\u8868\u63d2\u5165--------------------------------\");\n int size=10;\n for (int i=0; i < size; i++) {\n ShardingSysLog shardingSysLog=new ShardingSysLog();\n shardingSysLog.setLogContent(\"jeecg\");\n shardingSysLog.setLogType(i);\n shardingSysLog.setOperateType(i);\n shardingSysLogService.save(shardingSysLog);\n }\n return Result.OK(\"\u5355\u5e93\u5206\u8868\u63d2\u516510\u6761\u6570\u636e\u5b8c\u6210\uff01\");\n}\n"}}, {"toString": {"retrieved_name": "toString", "raw_body": "@Override public String toString(){\n return \"RedisInfo{\" + \"key='\" + key + '\\''+ \", value='\"+ value+ '\\''+ \", desctiption='\"+ description+ '\\''+ '}';\n}\n"}}, {"keySet": {"retrieved_name": "getSet", "raw_body": "TreeSet<Integer> getSet(int type){\nswitch (type) {\ncase SECOND:\n return seconds;\ncase MINUTE:\n return minutes;\ncase HOUR:\nreturn hours;\ncase DAY_OF_MONTH:\nreturn daysOfMonth;\ncase MONTH:\nreturn months;\ncase DAY_OF_WEEK:\nreturn daysOfWeek;\ncase YEAR:\nreturn years;\ndefault :\nreturn null;\n}\n}\n"}}, {"length": {"retrieved_name": "stringToLong", "raw_body": "public static long stringToLong(String str){\n Long test=new Long(0);\n try {\n test=Long.valueOf(str);\n }\n catch ( Exception e) {\n }\n return test.longValue();\n}\n"}}] | [{"getParamsSign": {"retrieved_name": "getSignName", "raw_body": "public String getSignName(){\n return signName;\n}\n"}}] |
|
jeecgboot_jeecg-boot | jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/quartz/job/SampleParamJob.java | SampleParamJob | execute | class SampleParamJob implements Job {
/**
* 若参数变量名修改 QuartzJobController中也需对应修改
*/
private String parameter;
public void setParameter(String parameter) {
this.parameter = parameter;
}
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {<FILL_FUNCTION_BODY>}
} |
log.info(" Job Execution key:"+jobExecutionContext.getJobDetail().getKey());
log.info( String.format("welcome %s! Jeecg-Boot 带参数定时任务 SampleParamJob ! 时间:" + DateUtils.now(), this.parameter));
|
System.out.println("SampleParamJob: " + parameter);
| [
"JobExecutionContext"
] | [
"println"
] | [
"JobExecutionContext"
] | [
"getKey",
"now",
"format",
"getJobDetail",
"info"
] | {
"methods": [
"println"
],
"similar_methods": [
"execute"
],
"types": [
"JobExecutionContext"
]
} | /**
* @author xuxueli 2019-05-21
*/
public class JobScheduleHelper {
private static Logger logger=LoggerFactory.getLogger(JobScheduleHelper.class);
private static JobScheduleHelper instance=new JobScheduleHelper();
public static JobScheduleHelper getInstance();
public static final long PRE_READ_MS=5000;
private Thread scheduleThread;
private Thread ringThread;
private volatile boolean scheduleThreadToStop=false;
private volatile boolean ringThreadToStop=false;
private volatile static Map<Integer,List<Integer>> ringData=new ConcurrentHashMap<>();
public void start();
private void refreshNextValidTime( XxlJobInfo jobInfo, Date fromTime) throws ParseException;
private void pushTimeRing( int ringSecond, int jobId);
public void toStop();
}
private void printSqlInfo(SelectSqlInfo sqlInfo,int level){
String beforeStr=this.getBeforeStr(level);
if (sqlInfo.getFromTableName() == null) {
System.out.println(beforeStr + "子查询:" + sqlInfo.getFromSubSelect().getParsedSql());
this.printSqlInfo(sqlInfo.getFromSubSelect(),level + 1);
}
else {
System.out.println(beforeStr + "查询的表名:" + sqlInfo.getFromTableName());
}
if (oConvertUtils.isNotEmpty(sqlInfo.getFromTableAliasName())) {
System.out.println(beforeStr + "查询的表别名:" + sqlInfo.getFromTableAliasName());
}
if (sqlInfo.isSelectAll()) {
System.out.println(beforeStr + "查询的字段:*");
}
else {
System.out.println(beforeStr + "查询的字段:" + sqlInfo.getSelectFields());
System.out.println(beforeStr + "真实的字段:" + sqlInfo.getRealSelectFields());
if (sqlInfo.getFromTableName() == null) {
System.out.println(beforeStr + "所有的字段(包括子查询):" + sqlInfo.getAllRealSelectFields());
}
}
}
@Override public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
log.info(String.format(" Jeecg-Boot 发送消息任务 SendMsgJob ! 时间:" + DateUtils.getTimestamp()));
QueryWrapper<SysMessage> queryWrapper=new QueryWrapper<SysMessage>();
queryWrapper.eq("es_send_status",SendMsgStatusEnum.WAIT.getCode()).or(i -> i.eq("es_send_status",SendMsgStatusEnum.FAIL.getCode()).lt("es_send_num",6));
List<SysMessage> sysMessages=sysMessageService.list(queryWrapper);
System.out.println(sysMessages);
for ( SysMessage sysMessage : sysMessages) {
Integer sendNum=sysMessage.getEsSendNum();
try {
MessageDTO md=new MessageDTO();
md.setTitle(sysMessage.getEsTitle());
md.setContent(sysMessage.getEsContent());
md.setToUser(sysMessage.getEsReceiver());
md.setType(sysMessage.getEsType());
md.setToAll(false);
sysBaseAPI.sendTemplateMessage(md);
sysMessage.setEsSendStatus(SendMsgStatusEnum.SUCCESS.getCode());
}
catch ( Exception e) {
e.printStackTrace();
sysMessage.setEsSendStatus(SendMsgStatusEnum.FAIL.getCode());
}
sysMessage.setEsSendNum(++sendNum);
sysMessageService.updateById(sysMessage);
}
}
| public class JobScheduleHelper {
private static Logger logger=LoggerFactory.getLogger(JobScheduleHelper.class);
private static JobScheduleHelper instance=new JobScheduleHelper();
public static JobScheduleHelper getInstance();
public static final long PRE_READ_MS=5000;
private Thread scheduleThread;
private Thread ringThread;
private volatile boolean scheduleThreadToStop=false;
private volatile boolean ringThreadToStop=false;
private volatile static Map<Integer,List<Integer>> ringData=new ConcurrentHashMap<>();
public void start();
private void refreshNextValidTime( XxlJobInfo jobInfo, Date fromTime) throws ParseException;
private void pushTimeRing( int ringSecond, int jobId);
public void toStop();
}
private void printSqlInfo(SelectSqlInfo sqlInfo,int level){
String beforeStr=this.getBeforeStr(level);
if (sqlInfo.getFromTableName() == null) {
System.out.println(beforeStr + "子查询:" + sqlInfo.getFromSubSelect().getParsedSql());
this.printSqlInfo(sqlInfo.getFromSubSelect(),level + 1);
}
else {
System.out.println(beforeStr + "查询的表名:" + sqlInfo.getFromTableName());
}
if (oConvertUtils.isNotEmpty(sqlInfo.getFromTableAliasName())) {
System.out.println(beforeStr + "查询的表别名:" + sqlInfo.getFromTableAliasName());
}
if (sqlInfo.isSelectAll()) {
System.out.println(beforeStr + "查询的字段:*");
}
else {
System.out.println(beforeStr + "查询的字段:" + sqlInfo.getSelectFields());
System.out.println(beforeStr + "真实的字段:" + sqlInfo.getRealSelectFields());
if (sqlInfo.getFromTableName() == null) {
System.out.println(beforeStr + "所有的字段(包括子查询):" + sqlInfo.getAllRealSelectFields());
}
}
}
@Override public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
log.info(String.format(" Jeecg-Boot 发送消息任务 SendMsgJob ! 时间:" + DateUtils.getTimestamp()));
QueryWrapper<SysMessage> queryWrapper=new QueryWrapper<SysMessage>();
queryWrapper.eq("es_send_status",SendMsgStatusEnum.WAIT.getCode()).or(i -> i.eq("es_send_status",SendMsgStatusEnum.FAIL.getCode()).lt("es_send_num",6));
List<SysMessage> sysMessages=sysMessageService.list(queryWrapper);
System.out.println(sysMessages);
for ( SysMessage sysMessage : sysMessages) {
Integer sendNum=sysMessage.getEsSendNum();
try {
MessageDTO md=new MessageDTO();
md.setTitle(sysMessage.getEsTitle());
md.setContent(sysMessage.getEsContent());
md.setToUser(sysMessage.getEsReceiver());
md.setType(sysMessage.getEsType());
md.setToAll(false);
sysBaseAPI.sendTemplateMessage(md);
sysMessage.setEsSendStatus(SendMsgStatusEnum.SUCCESS.getCode());
}
catch ( Exception e) {
e.printStackTrace();
sysMessage.setEsSendStatus(SendMsgStatusEnum.FAIL.getCode());
}
sysMessage.setEsSendNum(++sendNum);
sysMessageService.updateById(sysMessage);
}
}
| {"types": [{"JobExecutionContext": "JobScheduleHelper"}], "methods": [{"println": "printSqlInfo"}], "similar_methods": [{"execute": "execute"}]} | [{"JobExecutionContext": {"retrieved_name": "JobScheduleHelper", "raw_body": "/** \n * @author xuxueli 2019-05-21\n */\npublic class JobScheduleHelper {\n private static Logger logger=LoggerFactory.getLogger(JobScheduleHelper.class);\n private static JobScheduleHelper instance=new JobScheduleHelper();\n public static JobScheduleHelper getInstance();\n public static final long PRE_READ_MS=5000;\n private Thread scheduleThread;\n private Thread ringThread;\n private volatile boolean scheduleThreadToStop=false;\n private volatile boolean ringThreadToStop=false;\n private volatile static Map<Integer,List<Integer>> ringData=new ConcurrentHashMap<>();\n public void start();\n private void refreshNextValidTime( XxlJobInfo jobInfo, Date fromTime) throws ParseException;\n private void pushTimeRing( int ringSecond, int jobId);\n public void toStop();\n}\n", "raw_body_no_cmt": "public class JobScheduleHelper {\n private static Logger logger=LoggerFactory.getLogger(JobScheduleHelper.class);\n private static JobScheduleHelper instance=new JobScheduleHelper();\n public static JobScheduleHelper getInstance();\n public static final long PRE_READ_MS=5000;\n private Thread scheduleThread;\n private Thread ringThread;\n private volatile boolean scheduleThreadToStop=false;\n private volatile boolean ringThreadToStop=false;\n private volatile static Map<Integer,List<Integer>> ringData=new ConcurrentHashMap<>();\n public void start();\n private void refreshNextValidTime( XxlJobInfo jobInfo, Date fromTime) throws ParseException;\n private void pushTimeRing( int ringSecond, int jobId);\n public void toStop();\n}\n"}}] | [{"println": {"retrieved_name": "printSqlInfo", "raw_body": "private void printSqlInfo(SelectSqlInfo sqlInfo,int level){\n String beforeStr=this.getBeforeStr(level);\n if (sqlInfo.getFromTableName() == null) {\n System.out.println(beforeStr + \"\u5b50\u67e5\u8be2\uff1a\" + sqlInfo.getFromSubSelect().getParsedSql());\n this.printSqlInfo(sqlInfo.getFromSubSelect(),level + 1);\n }\n else {\n System.out.println(beforeStr + \"\u67e5\u8be2\u7684\u8868\u540d\uff1a\" + sqlInfo.getFromTableName());\n }\n if (oConvertUtils.isNotEmpty(sqlInfo.getFromTableAliasName())) {\n System.out.println(beforeStr + \"\u67e5\u8be2\u7684\u8868\u522b\u540d\uff1a\" + sqlInfo.getFromTableAliasName());\n }\n if (sqlInfo.isSelectAll()) {\n System.out.println(beforeStr + \"\u67e5\u8be2\u7684\u5b57\u6bb5\uff1a*\");\n }\n else {\n System.out.println(beforeStr + \"\u67e5\u8be2\u7684\u5b57\u6bb5\uff1a\" + sqlInfo.getSelectFields());\n System.out.println(beforeStr + \"\u771f\u5b9e\u7684\u5b57\u6bb5\uff1a\" + sqlInfo.getRealSelectFields());\n if (sqlInfo.getFromTableName() == null) {\n System.out.println(beforeStr + \"\u6240\u6709\u7684\u5b57\u6bb5\uff08\u5305\u62ec\u5b50\u67e5\u8be2\uff09\uff1a\" + sqlInfo.getAllRealSelectFields());\n }\n }\n}\n"}}] | [{"execute": {"retrieved_name": "execute", "raw_body": "@Override public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {\n log.info(String.format(\" Jeecg-Boot \u53d1\u9001\u6d88\u606f\u4efb\u52a1 SendMsgJob ! \u65f6\u95f4:\" + DateUtils.getTimestamp()));\n QueryWrapper<SysMessage> queryWrapper=new QueryWrapper<SysMessage>();\n queryWrapper.eq(\"es_send_status\",SendMsgStatusEnum.WAIT.getCode()).or(i -> i.eq(\"es_send_status\",SendMsgStatusEnum.FAIL.getCode()).lt(\"es_send_num\",6));\n List<SysMessage> sysMessages=sysMessageService.list(queryWrapper);\n System.out.println(sysMessages);\n for ( SysMessage sysMessage : sysMessages) {\n Integer sendNum=sysMessage.getEsSendNum();\n try {\n MessageDTO md=new MessageDTO();\n md.setTitle(sysMessage.getEsTitle());\n md.setContent(sysMessage.getEsContent());\n md.setToUser(sysMessage.getEsReceiver());\n md.setType(sysMessage.getEsType());\n md.setToAll(false);\n sysBaseAPI.sendTemplateMessage(md);\n sysMessage.setEsSendStatus(SendMsgStatusEnum.SUCCESS.getCode());\n }\n catch ( Exception e) {\n e.printStackTrace();\n sysMessage.setEsSendStatus(SendMsgStatusEnum.FAIL.getCode());\n }\n sysMessage.setEsSendNum(++sendNum);\n sysMessageService.updateById(sysMessage);\n }\n}\n"}}] |
|
graphhopper_graphhopper | graphhopper/core/src/main/java/com/graphhopper/routing/util/parsers/CarAccessParser.java | CarAccessParser | handleWayTags | class CarAccessParser extends AbstractAccessParser implements TagParser {
protected final Set<String> trackTypeValues = new HashSet<>();
protected final Set<String> highwayValues = new HashSet<>();
protected final BooleanEncodedValue roundaboutEnc;
public CarAccessParser(EncodedValueLookup lookup, PMap properties) {
this(
lookup.getBooleanEncodedValue(VehicleAccess.key("car")),
lookup.getBooleanEncodedValue(Roundabout.KEY),
properties,
TransportationMode.CAR
);
}
public CarAccessParser(BooleanEncodedValue accessEnc,
BooleanEncodedValue roundaboutEnc, PMap properties,
TransportationMode transportationMode) {
super(accessEnc, transportationMode);
this.roundaboutEnc = roundaboutEnc;
restrictedValues.add("agricultural");
restrictedValues.add("forestry");
restrictedValues.add("delivery");
blockPrivate(properties.getBool("block_private", true));
blockFords(properties.getBool("block_fords", false));
intendedValues.add("yes");
intendedValues.add("designated");
intendedValues.add("permissive");
barriers.add("kissing_gate");
barriers.add("fence");
barriers.add("bollard");
barriers.add("stile");
barriers.add("turnstile");
barriers.add("cycle_barrier");
barriers.add("motorcycle_barrier");
barriers.add("block");
barriers.add("bus_trap");
barriers.add("sump_buster");
barriers.add("jersey_barrier");
highwayValues.addAll(Arrays.asList("motorway", "motorway_link", "trunk", "trunk_link",
"primary", "primary_link", "secondary", "secondary_link", "tertiary", "tertiary_link",
"unclassified", "residential", "living_street", "service", "road", "track"));
trackTypeValues.addAll(Arrays.asList("grade1", "grade2", "grade3", null));
}
public WayAccess getAccess(ReaderWay way) {
// TODO: Ferries have conditionals, like opening hours or are closed during some time in the year
String highwayValue = way.getTag("highway");
int firstIndex = way.getFirstIndex(restrictionKeys);
String firstValue = firstIndex < 0 ? "" : way.getTag(restrictionKeys.get(firstIndex), "");
if (highwayValue == null) {
if (FerrySpeedCalculator.isFerry(way)) {
if (restrictedValues.contains(firstValue))
return WayAccess.CAN_SKIP;
if (intendedValues.contains(firstValue) ||
// implied default is allowed only if foot and bicycle is not specified:
firstValue.isEmpty() && !way.hasTag("foot") && !way.hasTag("bicycle") ||
// if hgv is allowed then smaller trucks and cars are allowed too
way.hasTag("hgv", "yes"))
return WayAccess.FERRY;
}
return WayAccess.CAN_SKIP;
}
if ("service".equals(highwayValue) && "emergency_access".equals(way.getTag("service")))
return WayAccess.CAN_SKIP;
if ("track".equals(highwayValue) && !trackTypeValues.contains(way.getTag("tracktype")))
return WayAccess.CAN_SKIP;
if (!highwayValues.contains(highwayValue))
return WayAccess.CAN_SKIP;
if (way.hasTag("impassable", "yes") || way.hasTag("status", "impassable"))
return WayAccess.CAN_SKIP;
// multiple restrictions needs special handling
if (firstIndex >= 0) {
String[] restrict = firstValue.split(";");
for (String value : restrict) {
if (restrictedValues.contains(value) && !hasTemporalRestriction(way, firstIndex, restrictionKeys))
return WayAccess.CAN_SKIP;
if (intendedValues.contains(value))
return WayAccess.WAY;
}
}
if (isBlockFords() && ("ford".equals(highwayValue) || way.hasTag("ford")))
return WayAccess.CAN_SKIP;
return WayAccess.WAY;
}
@Override
public void handleWayTags(int edgeId, EdgeIntAccess edgeIntAccess, ReaderWay way) {<FILL_FUNCTION_BODY>}
/**
* make sure that isOneway is called before
*/
protected boolean isBackwardOneway(ReaderWay way) {
return way.hasTag("oneway", "-1")
|| way.hasTag("vehicle:forward", restrictedValues)
|| way.hasTag("motor_vehicle:forward", restrictedValues);
}
/**
* make sure that isOneway is called before
*/
protected boolean isForwardOneway(ReaderWay way) {
return !way.hasTag("oneway", "-1")
&& !way.hasTag("vehicle:forward", restrictedValues)
&& !way.hasTag("motor_vehicle:forward", restrictedValues);
}
protected boolean isOneway(ReaderWay way) {
return way.hasTag("oneway", oneways)
|| way.hasTag("vehicle:backward", restrictedValues)
|| way.hasTag("vehicle:forward", restrictedValues)
|| way.hasTag("motor_vehicle:backward", restrictedValues)
|| way.hasTag("motor_vehicle:forward", restrictedValues);
}
} |
WayAccess access = getAccess(way);
if (access.canSkip())
return;
if (!access.isFerry()) {
boolean isRoundabout = roundaboutEnc.getBool(false, edgeId, edgeIntAccess);
if (isOneway(way) || isRoundabout) {
if (isForwardOneway(way))
accessEnc.setBool(false, edgeId, edgeIntAccess, true);
if (isBackwardOneway(way))
accessEnc.setBool(true, edgeId, edgeIntAccess, true);
} else {
accessEnc.setBool(false, edgeId, edgeIntAccess, true);
accessEnc.setBool(true, edgeId, edgeIntAccess, true);
}
} else {
accessEnc.setBool(false, edgeId, edgeIntAccess, true);
accessEnc.setBool(true, edgeId, edgeIntAccess, true);
}
if (way.hasTag("gh:barrier_edge")) {
List<Map<String, Object>> nodeTags = way.getTag("node_tags", Collections.emptyList());
handleBarrierEdge(edgeId, edgeIntAccess, nodeTags.get(0));
}
| public abstract class AbstractAccessParser implements TagParser {
static final Collection<String> ONEWAYS=Arrays.asList("yes","true","1","-1");
static final Collection<String> INTENDED=Arrays.asList("yes","designated","official","permissive");
protected final List<String> restrictionKeys=new ArrayList<>(5);
protected final Set<String> restrictedValues=new HashSet<>(5);
protected final Set<String> intendedValues=new HashSet<>(INTENDED);
protected final Set<String> oneways=new HashSet<>(ONEWAYS);
protected final Set<String> barriers=new HashSet<>(5);
protected final BooleanEncodedValue accessEnc;
private boolean blockFords=true;
protected AbstractAccessParser( BooleanEncodedValue accessEnc, TransportationMode transportationMode);
public boolean isBlockFords();
protected void blockFords( boolean blockFords);
protected void blockPrivate( boolean blockPrivate);
protected void handleBarrierEdge( int edgeId, EdgeIntAccess edgeIntAccess, Map<String,Object> nodeTags);
@Override public void handleWayTags( int edgeId, EdgeIntAccess edgeIntAccess, ReaderWay way, IntsRef relationFlags);
public abstract void handleWayTags( int edgeId, EdgeIntAccess edgeIntAccess, ReaderWay way);
/**
* @return true if the given OSM node blocks access for the specified restrictions, false otherwise
*/
public boolean isBarrier( ReaderNode node);
public final BooleanEncodedValue getAccessEnc();
public final List<String> getRestrictionKeys();
public final String getName();
@Override public String toString();
}
|
if (isBarrier(way)) {
handleBarrierEdge(edgeId, edgeIntAccess, way.getTags());
return;
}
if (isBlockPrivate() && way.hasTag("access", "private")) {
edgeIntAccess.set(accessEnc.getNo());
return;
}
if (way.hasTag("access", "no")) {
edgeIntAccess.set(accessEnc.getNo());
return;
}
if (way.hasTag("access", "yes")) {
edgeIntAccess.set(accessEnc.getYes());
return;
}
if (way.hasTag("access", "permissive")) {
edgeIntAccess.set(accessEnc.getPermissive());
return;
}
if (way.hasTag("access", "designated")) {
edgeIntAccess.set(accessEnc.getDesignated());
return;
}
if (way.hasTag("access", "customers")) {
edgeIntAccess.set(accessEnc.getCustomers());
return;
}
if (way.hasTag("access", "delivery")) {
edgeIntAccess.set(accessEnc.getDelivery());
return;
}
if (way.hasTag("access", "agricultural")) {
edgeIntAccess.set(accessEnc.getAgricultural());
return;
}
if (way.hasTag("access", "forestry")) {
edgeIntAccess.set(accessEnc.getForestry());
return;
}
if (way | [
"EdgeIntAccess",
"ReaderWay"
] | [
"hasTag",
"getTags",
"getAgricultural",
"getDesignated",
"getDelivery",
"set",
"getNo",
"getCustomers",
"getYes",
"getForestry",
"getPermissive"
] | [
"WayAccess",
"List<Map<String,Object>>",
"ReaderWay",
"EdgeIntAccess"
] | [
"hasTag",
"setBool",
"canSkip",
"get",
"emptyList",
"isFerry",
"getTag",
"getBool"
] | {
"methods": [
"hasTag",
"getTags",
"getAgricultural",
"getDesignated",
"getDelivery",
"set",
"getNo",
"getCustomers",
"getYes",
"getForestry",
"getPermissive"
],
"similar_methods": [
"handleWayTags"
],
"types": [
"EdgeIntAccess",
"ReaderWay"
]
} | public interface EdgeIntAccess {
/**
* Gets the int value at the given index for the given edgeId
*/
int getInt( int edgeId, int index);
/**
* Sets the int value at the given index for the given edgeId
*/
void setInt( int edgeId, int index, int value);
}
/**
* Represents a way received from the reader. <p>
* @author Nop
*/
public class ReaderWay extends ReaderElement {
protected final LongArrayList nodes=new LongArrayList(5);
public ReaderWay( long id);
public LongArrayList getNodes();
@Override public String toString();
}
/**
* Check a number of tags in the given order if their value is equal to the specified value.
*/
public boolean hasTag(List<String> keyList,Object value){
for ( String key : keyList) {
if (value.equals(getTag(key,null))) return true;
}
return false;
}
/**
* <pre> Tags of this feature are encoded as repeated pairs of integers. A detailed description of tags is located in sections 4.2 and 4.4 of the specification </pre> <code>repeated uint32 tags = 2 [packed = true];</code>
*/
public int getTags(int index){
return tags_.get(index);
}
public Object getProperty(String key){
return properties.get(key);
}
boolean isDesignated(ReaderWay way){
return way.hasTag("bicycle","designated") || way.hasTag(CYCLEWAY_ACCESS_KEYS,"designated") || way.hasTag("bicycle_road","yes")|| way.hasTag("cyclestreet","yes")|| way.hasTag("bicycle","official");
}
public String getProvider(){
return provider;
}
@Override public <T extends Enum<?>>EdgeIteratorState set(EnumEncodedValue<T> property,T value){
throw new RuntimeException();
}
@GET public Info getInfo(){
final Info info=new Info();
info.bbox=new Envelope(baseGraph.getBounds().minLon,baseGraph.getBounds().maxLon,baseGraph.getBounds().minLat,baseGraph.getBounds().maxLat);
for ( Profile p : config.getProfiles()) {
Info.ProfileData profileData=new Info.ProfileData(p.getName());
info.profiles.add(profileData);
}
if (config.has("gtfs.file")) info.profiles.add(new Info.ProfileData("pt"));
info.elevation=hasElevation;
info.import_date=properties.get("datareader.import.date");
info.data_date=properties.get("datareader.data.date");
List<EncodedValue> evList=encodingManager.getEncodedValues();
info.encoded_values=new LinkedHashMap<>();
for ( EncodedValue encodedValue : evList) {
List<Object> possibleValueList=new ArrayList<>();
String name=encodedValue.getName();
if (privateEV.contains(name)) {
continue;
}
else if (encodedValue instanceof EnumEncodedValue) {
for ( Enum o : ((EnumEncodedValue)encodedValue).getValues()) {
possibleValueList.add(o.name());
}
}
else if (encodedValue instanceof BooleanEncodedValue) {
possibleValueList.add("true");
possibleValueList.add("false");
}
else if (encodedValue instanceof DecimalEncodedValue || encodedValue instanceof IntEncodedValue) {
possibleValueList.add(">number");
possibleValueList.add("<number");
}
else {
continue;
}
info.encoded_values.put(name,possibleValueList);
}
return info;
}
public List<Member> getMembers(){
if (members == null) return Collections.emptyList();
return members;
}
public double getY(double lat){
return (90 - lat + offsetY) / scaleY;
}
public Object getProperty(String key){
return properties.get(key);
}
@Override public RoadAccess getAccess(ReaderWay readerWay,TransportationMode transportationMode,RoadAccess currentRoadAccess){
if (currentRoadAccess != RoadAccess.YES) return currentRoadAccess;
if (!transportationMode.isMotorVehicle()) return RoadAccess.YES;
RoadClass roadClass=RoadClass.find(readerWay.getTag("highway",""));
switch (roadClass) {
case TRACK:
return RoadAccess.DESTINATION;
case PATH:
case BRIDLEWAY:
case CYCLEWAY:
case FOOTWAY:
case PEDESTRIAN:
return RoadAccess.NO;
default :
return RoadAccess.YES;
}
}
@Override public void handleWayTags(int edgeId,EdgeIntAccess edgeIntAccess,ReaderWay way,IntsRef relationFlags){
if (isFerry(way)) {
double ferrySpeed=minmax(getSpeed(way),ferrySpeedEnc);
ferrySpeedEnc.setDecimal(false,edgeId,edgeIntAccess,ferrySpeed);
}
}
| public interface EdgeIntAccess {
int getInt( int edgeId, int index);
void setInt( int edgeId, int index, int value);
}
public class ReaderWay extends ReaderElement {
protected final LongArrayList nodes=new LongArrayList(5);
public ReaderWay( long id);
public LongArrayList getNodes();
public String toString();
}
/**
* Check a number of tags in the given order if their value is equal to the specified value.
*/
public boolean hasTag(List<String> keyList,Object value){
for ( String key : keyList) {
if (value.equals(getTag(key,null))) return true;
}
return false;
}
/**
* <pre> Tags of this feature are encoded as repeated pairs of integers. A detailed description of tags is located in sections 4.2 and 4.4 of the specification </pre> <code>repeated uint32 tags = 2 [packed = true];</code>
*/
public int getTags(int index){
return tags_.get(index);
}
public Object getProperty(String key){
return properties.get(key);
}
boolean isDesignated(ReaderWay way){
return way.hasTag("bicycle","designated") || way.hasTag(CYCLEWAY_ACCESS_KEYS,"designated") || way.hasTag("bicycle_road","yes")|| way.hasTag("cyclestreet","yes")|| way.hasTag("bicycle","official");
}
public String getProvider(){
return provider;
}
@Override public <T extends Enum<?>>EdgeIteratorState set(EnumEncodedValue<T> property,T value){
throw new RuntimeException();
}
@GET public Info getInfo(){
final Info info=new Info();
info.bbox=new Envelope(baseGraph.getBounds().minLon,baseGraph.getBounds().maxLon,baseGraph.getBounds().minLat,baseGraph.getBounds().maxLat);
for ( Profile p : config.getProfiles()) {
Info.ProfileData profileData=new Info.ProfileData(p.getName());
info.profiles.add(profileData);
}
if (config.has("gtfs.file")) info.profiles.add(new Info.ProfileData("pt"));
info.elevation=hasElevation;
info.import_date=properties.get("datareader.import.date");
info.data_date=properties.get("datareader.data.date");
List<EncodedValue> evList=encodingManager.getEncodedValues();
info.encoded_values=new LinkedHashMap<>();
for ( EncodedValue encodedValue : evList) {
List<Object> possibleValueList=new ArrayList<>();
String name=encodedValue.getName();
if (privateEV.contains(name)) {
continue;
}
else if (encodedValue instanceof EnumEncodedValue) {
for ( Enum o : ((EnumEncodedValue)encodedValue).getValues()) {
possibleValueList.add(o.name());
}
}
else if (encodedValue instanceof BooleanEncodedValue) {
possibleValueList.add("true");
possibleValueList.add("false");
}
else if (encodedValue instanceof DecimalEncodedValue || encodedValue instanceof IntEncodedValue) {
possibleValueList.add(">number");
possibleValueList.add("<number");
}
else {
continue;
}
info.encoded_values.put(name,possibleValueList);
}
return info;
}
public List<Member> getMembers(){
if (members == null) return Collections.emptyList();
return members;
}
public double getY(double lat){
return (90 - lat + offsetY) / scaleY;
}
public Object getProperty(String key){
return properties.get(key);
}
@Override public RoadAccess getAccess(ReaderWay readerWay,TransportationMode transportationMode,RoadAccess currentRoadAccess){
if (currentRoadAccess != RoadAccess.YES) return currentRoadAccess;
if (!transportationMode.isMotorVehicle()) return RoadAccess.YES;
RoadClass roadClass=RoadClass.find(readerWay.getTag("highway",""));
switch (roadClass) {
case TRACK:
return RoadAccess.DESTINATION;
case PATH:
case BRIDLEWAY:
case CYCLEWAY:
case FOOTWAY:
case PEDESTRIAN:
return RoadAccess.NO;
default :
return RoadAccess.YES;
}
}
@Override public void handleWayTags(int edgeId,EdgeIntAccess edgeIntAccess,ReaderWay way,IntsRef relationFlags){
if (isFerry(way)) {
double ferrySpeed=minmax(getSpeed(way),ferrySpeedEnc);
ferrySpeedEnc.setDecimal(false,edgeId,edgeIntAccess,ferrySpeed);
}
}
| {"types": [{"EdgeIntAccess": "EdgeIntAccess"}, {"ReaderWay": "ReaderWay"}], "methods": [{"hasTag": "hasTag"}, {"getTags": "getTags"}, {"getAgricultural": "getProperty"}, {"getDesignated": "isDesignated"}, {"getDelivery": "getProvider"}, {"set": "set"}, {"getNo": "getInfo"}, {"getCustomers": "getMembers"}, {"getYes": "getY"}, {"getForestry": "getProperty"}, {"getPermissive": "getAccess"}], "similar_methods": [{"handleWayTags": "handleWayTags"}]} | [{"EdgeIntAccess": {"retrieved_name": "EdgeIntAccess", "raw_body": "public interface EdgeIntAccess {\n /** \n * Gets the int value at the given index for the given edgeId\n */\n int getInt( int edgeId, int index);\n /** \n * Sets the int value at the given index for the given edgeId\n */\n void setInt( int edgeId, int index, int value);\n}\n", "raw_body_no_cmt": "public interface EdgeIntAccess {\n int getInt( int edgeId, int index);\n void setInt( int edgeId, int index, int value);\n}\n"}}, {"ReaderWay": {"retrieved_name": "ReaderWay", "raw_body": "/** \n * Represents a way received from the reader. <p>\n * @author Nop\n */\npublic class ReaderWay extends ReaderElement {\n protected final LongArrayList nodes=new LongArrayList(5);\n public ReaderWay( long id);\n public LongArrayList getNodes();\n @Override public String toString();\n}\n", "raw_body_no_cmt": "public class ReaderWay extends ReaderElement {\n protected final LongArrayList nodes=new LongArrayList(5);\n public ReaderWay( long id);\n public LongArrayList getNodes();\n public String toString();\n}\n"}}] | [{"hasTag": {"retrieved_name": "hasTag", "raw_body": "/** \n * Check a number of tags in the given order if their value is equal to the specified value.\n */\npublic boolean hasTag(List<String> keyList,Object value){\n for ( String key : keyList) {\n if (value.equals(getTag(key,null))) return true;\n }\n return false;\n}\n"}}, {"getTags": {"retrieved_name": "getTags", "raw_body": "/** \n * <pre> Tags of this feature are encoded as repeated pairs of integers. A detailed description of tags is located in sections 4.2 and 4.4 of the specification </pre> <code>repeated uint32 tags = 2 [packed = true];</code>\n */\npublic int getTags(int index){\n return tags_.get(index);\n}\n"}}, {"getAgricultural": {"retrieved_name": "getProperty", "raw_body": "public Object getProperty(String key){\n return properties.get(key);\n}\n"}}, {"getDesignated": {"retrieved_name": "isDesignated", "raw_body": "boolean isDesignated(ReaderWay way){\n return way.hasTag(\"bicycle\",\"designated\") || way.hasTag(CYCLEWAY_ACCESS_KEYS,\"designated\") || way.hasTag(\"bicycle_road\",\"yes\")|| way.hasTag(\"cyclestreet\",\"yes\")|| way.hasTag(\"bicycle\",\"official\");\n}\n"}}, {"getDelivery": {"retrieved_name": "getProvider", "raw_body": "public String getProvider(){\n return provider;\n}\n"}}, {"set": {"retrieved_name": "set", "raw_body": "@Override public <T extends Enum<?>>EdgeIteratorState set(EnumEncodedValue<T> property,T value){\n throw new RuntimeException();\n}\n"}}, {"getNo": {"retrieved_name": "getInfo", "raw_body": "@GET public Info getInfo(){\n final Info info=new Info();\n info.bbox=new Envelope(baseGraph.getBounds().minLon,baseGraph.getBounds().maxLon,baseGraph.getBounds().minLat,baseGraph.getBounds().maxLat);\n for ( Profile p : config.getProfiles()) {\n Info.ProfileData profileData=new Info.ProfileData(p.getName());\n info.profiles.add(profileData);\n }\n if (config.has(\"gtfs.file\")) info.profiles.add(new Info.ProfileData(\"pt\"));\n info.elevation=hasElevation;\n info.import_date=properties.get(\"datareader.import.date\");\n info.data_date=properties.get(\"datareader.data.date\");\n List<EncodedValue> evList=encodingManager.getEncodedValues();\n info.encoded_values=new LinkedHashMap<>();\n for ( EncodedValue encodedValue : evList) {\n List<Object> possibleValueList=new ArrayList<>();\n String name=encodedValue.getName();\n if (privateEV.contains(name)) {\n continue;\n }\n else if (encodedValue instanceof EnumEncodedValue) {\n for ( Enum o : ((EnumEncodedValue)encodedValue).getValues()) {\n possibleValueList.add(o.name());\n }\n }\n else if (encodedValue instanceof BooleanEncodedValue) {\n possibleValueList.add(\"true\");\n possibleValueList.add(\"false\");\n }\n else if (encodedValue instanceof DecimalEncodedValue || encodedValue instanceof IntEncodedValue) {\n possibleValueList.add(\">number\");\n possibleValueList.add(\"<number\");\n }\n else {\n continue;\n }\n info.encoded_values.put(name,possibleValueList);\n }\n return info;\n}\n"}}, {"getCustomers": {"retrieved_name": "getMembers", "raw_body": "public List<Member> getMembers(){\n if (members == null) return Collections.emptyList();\n return members;\n}\n"}}, {"getYes": {"retrieved_name": "getY", "raw_body": "public double getY(double lat){\n return (90 - lat + offsetY) / scaleY;\n}\n"}}, {"getForestry": {"retrieved_name": "getProperty", "raw_body": "public Object getProperty(String key){\n return properties.get(key);\n}\n"}}, {"getPermissive": {"retrieved_name": "getAccess", "raw_body": "@Override public RoadAccess getAccess(ReaderWay readerWay,TransportationMode transportationMode,RoadAccess currentRoadAccess){\n if (currentRoadAccess != RoadAccess.YES) return currentRoadAccess;\n if (!transportationMode.isMotorVehicle()) return RoadAccess.YES;\n RoadClass roadClass=RoadClass.find(readerWay.getTag(\"highway\",\"\"));\nswitch (roadClass) {\ncase TRACK:\n return RoadAccess.DESTINATION;\ncase PATH:\ncase BRIDLEWAY:\ncase CYCLEWAY:\ncase FOOTWAY:\ncase PEDESTRIAN:\n return RoadAccess.NO;\ndefault :\nreturn RoadAccess.YES;\n}\n}\n"}}] | [{"handleWayTags": {"retrieved_name": "handleWayTags", "raw_body": "@Override public void handleWayTags(int edgeId,EdgeIntAccess edgeIntAccess,ReaderWay way,IntsRef relationFlags){\n if (isFerry(way)) {\n double ferrySpeed=minmax(getSpeed(way),ferrySpeedEnc);\n ferrySpeedEnc.setDecimal(false,edgeId,edgeIntAccess,ferrySpeed);\n }\n}\n"}}] |
elunez_eladmin | eladmin/eladmin-tools/src/main/java/me/zhengjie/rest/AliPayController.java | AliPayController | returnPage | class AliPayController {
private final AlipayUtils alipayUtils;
private final AliPayService alipayService;
@GetMapping
public ResponseEntity<AlipayConfig> queryAliConfig() {
return new ResponseEntity<>(alipayService.find(), HttpStatus.OK);
}
@Log("配置支付宝")
@ApiOperation("配置支付宝")
@PutMapping
public ResponseEntity<Object> updateAliPayConfig(@Validated @RequestBody AlipayConfig alipayConfig) {
alipayService.config(alipayConfig);
return new ResponseEntity<>(HttpStatus.OK);
}
@Log("支付宝PC网页支付")
@ApiOperation("PC网页支付")
@PostMapping(value = "/toPayAsPC")
public ResponseEntity<String> toPayAsPc(@Validated @RequestBody TradeVo trade) throws Exception {
AlipayConfig aliPay = alipayService.find();
trade.setOutTradeNo(alipayUtils.getOrderCode());
String payUrl = alipayService.toPayAsPc(aliPay, trade);
return ResponseEntity.ok(payUrl);
}
@Log("支付宝手机网页支付")
@ApiOperation("手机网页支付")
@PostMapping(value = "/toPayAsWeb")
public ResponseEntity<String> toPayAsWeb(@Validated @RequestBody TradeVo trade) throws Exception {
AlipayConfig alipay = alipayService.find();
trade.setOutTradeNo(alipayUtils.getOrderCode());
String payUrl = alipayService.toPayAsWeb(alipay, trade);
return ResponseEntity.ok(payUrl);
}
@ApiIgnore
@AnonymousGetMapping("/return")
@ApiOperation("支付之后跳转的链接")
public ResponseEntity<String> returnPage(HttpServletRequest request, HttpServletResponse response) {<FILL_FUNCTION_BODY>}
@ApiIgnore
@RequestMapping("/notify")
@AnonymousAccess
@ApiOperation("支付异步通知(要公网访问),接收异步通知,检查通知内容app_id、out_trade_no、total_amount是否与请求中的一致,根据trade_status进行后续业务处理")
public ResponseEntity<Object> notify(HttpServletRequest request) {
AlipayConfig alipay = alipayService.find();
Map<String, String[]> parameterMap = request.getParameterMap();
//内容验签,防止黑客篡改参数
if (alipayUtils.rsaCheck(request, alipay)) {
//交易状态
String tradeStatus = new String(request.getParameter("trade_status").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
// 商户订单号
String outTradeNo = new String(request.getParameter("out_trade_no").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
//支付宝交易号
String tradeNo = new String(request.getParameter("trade_no").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
//付款金额
String totalAmount = new String(request.getParameter("total_amount").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
//验证
if (tradeStatus.equals(AliPayStatusEnum.SUCCESS.getValue()) || tradeStatus.equals(AliPayStatusEnum.FINISHED.getValue())) {
// 验证通过后应该根据业务需要处理订单
}
return new ResponseEntity<>(HttpStatus.OK);
}
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
} |
AlipayConfig alipay = alipayService.find();
response.setContentType("text/html;charset=" + alipay.getCharset());
//内容验签,防止黑客篡改参数
if (alipayUtils.rsaCheck(request, alipay)) {
//商户订单号
String outTradeNo = new String(request.getParameter("out_trade_no").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
//支付宝交易号
String tradeNo = new String(request.getParameter("trade_no").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
System.out.println("商户订单号" + outTradeNo + " " + "第三方交易号" + tradeNo);
// 根据业务需要返回数据,这里统一返回OK
return new ResponseEntity<>("payment successful", HttpStatus.OK);
} else {
// 根据业务需要返回数据
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
|
AlipayConfig alipay = alipayService.find();
//内容验签,防止黑客篡改参数
if (alipayUtils.rsaCheck(request, alipay)) {
// 商户订单号
String outTradeNo = new String(request.getParameter("out_trade_no").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
//支付宝交易号
String tradeNo = new String(request.getParameter("trade_no").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
//付款金额
String totalAmount = new String(request.getParameter("total_amount").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
//验证
if (tradeNo != null) {
// 验证通过后应该根据业务需要处理订单
}
return new ResponseEntity<>(HttpStatus.OK);
}
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
| [
"AlipayConfig",
"HttpServletResponse",
"HttpServletRequest",
"AlipayUtils",
"AliPayService"
] | [
"find",
"getBytes",
"getParameter",
"rsaCheck"
] | [
"HttpServletResponse",
"AlipayConfig",
"HttpServletRequest",
"AlipayUtils",
"AliPayService"
] | [
"getCharset",
"setContentType",
"find",
"rsaCheck",
"getParameter",
"println",
"getBytes"
] | {
"methods": [
"find",
"getBytes",
"getParameter",
"rsaCheck"
],
"similar_methods": [
"returnPage"
],
"types": [
"AlipayConfig",
"HttpServletResponse",
"HttpServletRequest",
"AlipayUtils",
"AliPayService"
]
} | /**
* 支付宝配置类
* @author Zheng Jie
* @date 2018-12-31
*/
@Data @Entity @Table(name="tool_alipay_config") public class AlipayConfig implements Serializable {
@Id @Column(name="config_id") @ApiModelProperty(value="ID",hidden=true) private Long id;
@NotBlank @ApiModelProperty(value="应用ID") private String appId;
@NotBlank @ApiModelProperty(value="商户私钥") private String privateKey;
@NotBlank @ApiModelProperty(value="支付宝公钥") private String publicKey;
@ApiModelProperty(value="签名方式") private String signType="RSA2";
@Column(name="gateway_url") @ApiModelProperty(value="支付宝开放安全地址",hidden=true) private String gatewayUrl="https://openapi.alipaydev.com/gateway.do";
@ApiModelProperty(value="编码",hidden=true) private String charset="utf-8";
@NotBlank @ApiModelProperty(value="异步通知地址") private String notifyUrl;
@NotBlank @ApiModelProperty(value="订单完成后返回的页面") private String returnUrl;
@ApiModelProperty(value="类型") private String format="JSON";
@NotBlank @ApiModelProperty(value="商户号") private String sysServiceProviderId;
}
/**
* @author ZhangHouYing
* @date 2019-08-10 15:46
*/
@ServerEndpoint("/webSocket/{sid}") @Slf4j @Component public class WebSocketServer {
/**
* concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
*/
private static final CopyOnWriteArraySet<WebSocketServer> webSocketSet=new CopyOnWriteArraySet<WebSocketServer>();
/**
* 与某个客户端的连接会话,需要通过它来给客户端发送数据
*/
private Session session;
/**
* 接收sid
*/
private String sid="";
/**
* 连接建立成功调用的方法
*/
@OnOpen public void onOpen( Session session, @PathParam("sid") String sid);
/**
* 连接关闭调用的方法
*/
@OnClose public void onClose();
/**
* 收到客户端消息后调用的方法
* @param message 客户端发送过来的消息
*/
@OnMessage public void onMessage( String message, Session session);
@OnError public void onError( Session session, Throwable error);
/**
* 实现服务器主动推送
*/
private void sendMessage( String message) throws IOException;
/**
* 群发自定义消息
*/
public static void sendInfo( SocketMsg socketMsg, @PathParam("sid") String sid) throws IOException;
@Override public boolean equals( Object o);
@Override public int hashCode();
}
/**
* 支付宝工具类
* @author zhengjie
* @date 2018/09/30 14:04:35
*/
@Component public class AlipayUtils {
/**
* 生成订单号
* @return String
*/
public String getOrderCode();
/**
* 校验签名
* @param request HttpServletRequest
* @param alipay 阿里云配置
* @return boolean
*/
public boolean rsaCheck( HttpServletRequest request, AlipayConfig alipay);
}
/**
* @author Zheng Jie
* @date 2018-12-31
*/
public interface AliPayService {
/**
* 查询配置
* @return AlipayConfig
*/
AlipayConfig find();
/**
* 更新配置
* @param alipayConfig 支付宝配置
* @return AlipayConfig
*/
AlipayConfig config( AlipayConfig alipayConfig);
/**
* 处理来自PC的交易请求
* @param alipay 支付宝配置
* @param trade 交易详情
* @return String
* @throws Exception 异常
*/
String toPayAsPc( AlipayConfig alipay, TradeVo trade) throws Exception ;
/**
* 处理来自手机网页的交易请求
* @param alipay 支付宝配置
* @param trade 交易详情
* @return String
* @throws Exception 异常
*/
String toPayAsWeb( AlipayConfig alipay, TradeVo trade) throws Exception ;
}
@Override public GenConfig find(String tableName){
GenConfig genConfig=genConfigRepository.findByTableName(tableName);
if (genConfig == null) {
return new GenConfig(tableName);
}
return genConfig;
}
private static byte[] getByte(File file){
byte[] b=new byte[(int)file.length()];
InputStream in=null;
try {
in=new FileInputStream(file);
try {
System.out.println(in.read(b));
}
catch ( IOException e) {
log.error(e.getMessage(),e);
}
}
catch ( Exception e) {
log.error(e.getMessage(),e);
return null;
}
finally {
CloseUtil.close(in);
}
return b;
}
/**
* 根据方法和传入的参数获取请求参数
*/
private String getParameter(Method method,Object[] args){
List<Object> argList=new ArrayList<>();
Parameter[] parameters=method.getParameters();
for (int i=0; i < parameters.length; i++) {
if (args[i] instanceof MultipartFile) {
continue;
}
RequestBody requestBody=parameters[i].getAnnotation(RequestBody.class);
if (requestBody != null) {
argList.add(args[i]);
}
RequestParam requestParam=parameters[i].getAnnotation(RequestParam.class);
if (requestParam != null) {
Map<String,Object> map=new HashMap<>(2);
String key=parameters[i].getName();
if (!StringUtils.isEmpty(requestParam.value())) {
key=requestParam.value();
}
map.put(key,args[i]);
argList.add(map);
}
}
if (argList.isEmpty()) {
return "";
}
return argList.size() == 1 ? JSON.toJSONString(argList.get(0)) : JSON.toJSONString(argList);
}
/**
* 校验签名
* @param request HttpServletRequest
* @param alipay 阿里云配置
* @return boolean
*/
public boolean rsaCheck(HttpServletRequest request,AlipayConfig alipay){
Map<String,String> params=new HashMap<>(1);
Map<String,String[]> requestParams=request.getParameterMap();
for ( Object o : requestParams.keySet()) {
String name=(String)o;
String[] values=requestParams.get(name);
String valueStr="";
for (int i=0; i < values.length; i++) {
valueStr=(i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
}
params.put(name,valueStr);
}
try {
return AlipaySignature.rsaCheckV1(params,alipay.getPublicKey(),alipay.getCharset(),alipay.getSignType());
}
catch ( AlipayApiException e) {
return false;
}
}
/**
* Page 数据处理,预防redis反序列化报错
*/
public static <T>PageResult<T> toPage(Page<T> page){
return new PageResult<>(page.getContent(),page.getTotalElements());
}
| public class AlipayConfig implements Serializable {
private Long id;
private String appId;
private String privateKey;
private String publicKey;
private String signType="RSA2";
private String gatewayUrl="https://openapi.alipaydev.com/gateway.do";
private String charset="utf-8";
private String notifyUrl;
private String returnUrl;
private String format="JSON";
private String sysServiceProviderId;
}
public class WebSocketServer {
private static final CopyOnWriteArraySet<WebSocketServer> webSocketSet=new CopyOnWriteArraySet<WebSocketServer>();
private Session session;
private String sid="";
public void onOpen( Session session, String sid);
public void onClose();
public void onMessage( String message, Session session);
public void onError( Session session, Throwable error);
private void sendMessage( String message) throws IOException;
public static void sendInfo( SocketMsg socketMsg, String sid) throws IOException;
public boolean equals( Object o);
public int hashCode();
}
public class AlipayUtils {
public String getOrderCode();
public boolean rsaCheck( HttpServletRequest request, AlipayConfig alipay);
}
public interface AliPayService {
AlipayConfig find();
AlipayConfig config( AlipayConfig alipayConfig);
String toPayAsPc( AlipayConfig alipay, TradeVo trade) throws Exception ;
String toPayAsWeb( AlipayConfig alipay, TradeVo trade) throws Exception ;
}
@Override public GenConfig find(String tableName){
GenConfig genConfig=genConfigRepository.findByTableName(tableName);
if (genConfig == null) {
return new GenConfig(tableName);
}
return genConfig;
}
private static byte[] getByte(File file){
byte[] b=new byte[(int)file.length()];
InputStream in=null;
try {
in=new FileInputStream(file);
try {
System.out.println(in.read(b));
}
catch ( IOException e) {
log.error(e.getMessage(),e);
}
}
catch ( Exception e) {
log.error(e.getMessage(),e);
return null;
}
finally {
CloseUtil.close(in);
}
return b;
}
/**
* 根据方法和传入的参数获取请求参数
*/
private String getParameter(Method method,Object[] args){
List<Object> argList=new ArrayList<>();
Parameter[] parameters=method.getParameters();
for (int i=0; i < parameters.length; i++) {
if (args[i] instanceof MultipartFile) {
continue;
}
RequestBody requestBody=parameters[i].getAnnotation(RequestBody.class);
if (requestBody != null) {
argList.add(args[i]);
}
RequestParam requestParam=parameters[i].getAnnotation(RequestParam.class);
if (requestParam != null) {
Map<String,Object> map=new HashMap<>(2);
String key=parameters[i].getName();
if (!StringUtils.isEmpty(requestParam.value())) {
key=requestParam.value();
}
map.put(key,args[i]);
argList.add(map);
}
}
if (argList.isEmpty()) {
return "";
}
return argList.size() == 1 ? JSON.toJSONString(argList.get(0)) : JSON.toJSONString(argList);
}
/**
* 校验签名
* @param request HttpServletRequest
* @param alipay 阿里云配置
* @return boolean
*/
public boolean rsaCheck(HttpServletRequest request,AlipayConfig alipay){
Map<String,String> params=new HashMap<>(1);
Map<String,String[]> requestParams=request.getParameterMap();
for ( Object o : requestParams.keySet()) {
String name=(String)o;
String[] values=requestParams.get(name);
String valueStr="";
for (int i=0; i < values.length; i++) {
valueStr=(i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
}
params.put(name,valueStr);
}
try {
return AlipaySignature.rsaCheckV1(params,alipay.getPublicKey(),alipay.getCharset(),alipay.getSignType());
}
catch ( AlipayApiException e) {
return false;
}
}
/**
* Page 数据处理,预防redis反序列化报错
*/
public static <T>PageResult<T> toPage(Page<T> page){
return new PageResult<>(page.getContent(),page.getTotalElements());
}
| {"types": [{"AlipayConfig": "AlipayConfig"}, {"HttpServletResponse": "WebSocketServer"}, {"HttpServletRequest": "WebSocketServer"}, {"AlipayUtils": "AlipayUtils"}, {"AliPayService": "AliPayService"}], "methods": [{"find": "find"}, {"getBytes": "getByte"}, {"getParameter": "getParameter"}, {"rsaCheck": "rsaCheck"}], "similar_methods": [{"returnPage": "toPage"}]} | [{"AlipayConfig": {"retrieved_name": "AlipayConfig", "raw_body": "/** \n * \u652f\u4ed8\u5b9d\u914d\u7f6e\u7c7b\n * @author Zheng Jie\n * @date 2018-12-31\n */\n@Data @Entity @Table(name=\"tool_alipay_config\") public class AlipayConfig implements Serializable {\n @Id @Column(name=\"config_id\") @ApiModelProperty(value=\"ID\",hidden=true) private Long id;\n @NotBlank @ApiModelProperty(value=\"\u5e94\u7528ID\") private String appId;\n @NotBlank @ApiModelProperty(value=\"\u5546\u6237\u79c1\u94a5\") private String privateKey;\n @NotBlank @ApiModelProperty(value=\"\u652f\u4ed8\u5b9d\u516c\u94a5\") private String publicKey;\n @ApiModelProperty(value=\"\u7b7e\u540d\u65b9\u5f0f\") private String signType=\"RSA2\";\n @Column(name=\"gateway_url\") @ApiModelProperty(value=\"\u652f\u4ed8\u5b9d\u5f00\u653e\u5b89\u5168\u5730\u5740\",hidden=true) private String gatewayUrl=\"https://openapi.alipaydev.com/gateway.do\";\n @ApiModelProperty(value=\"\u7f16\u7801\",hidden=true) private String charset=\"utf-8\";\n @NotBlank @ApiModelProperty(value=\"\u5f02\u6b65\u901a\u77e5\u5730\u5740\") private String notifyUrl;\n @NotBlank @ApiModelProperty(value=\"\u8ba2\u5355\u5b8c\u6210\u540e\u8fd4\u56de\u7684\u9875\u9762\") private String returnUrl;\n @ApiModelProperty(value=\"\u7c7b\u578b\") private String format=\"JSON\";\n @NotBlank @ApiModelProperty(value=\"\u5546\u6237\u53f7\") private String sysServiceProviderId;\n}\n", "raw_body_no_cmt": "public class AlipayConfig implements Serializable {\n private Long id;\n private String appId;\n private String privateKey;\n private String publicKey;\n private String signType=\"RSA2\";\n private String gatewayUrl=\"https://openapi.alipaydev.com/gateway.do\";\n private String charset=\"utf-8\";\n private String notifyUrl;\n private String returnUrl;\n private String format=\"JSON\";\n private String sysServiceProviderId;\n}\n"}}, {"HttpServletResponse": {"retrieved_name": "WebSocketServer", "raw_body": "/** \n * @author ZhangHouYing\n * @date 2019-08-10 15:46\n */\n@ServerEndpoint(\"/webSocket/{sid}\") @Slf4j @Component public class WebSocketServer {\n /** \n * concurrent\u5305\u7684\u7ebf\u7a0b\u5b89\u5168Set\uff0c\u7528\u6765\u5b58\u653e\u6bcf\u4e2a\u5ba2\u6237\u7aef\u5bf9\u5e94\u7684MyWebSocket\u5bf9\u8c61\u3002\n */\n private static final CopyOnWriteArraySet<WebSocketServer> webSocketSet=new CopyOnWriteArraySet<WebSocketServer>();\n /** \n * \u4e0e\u67d0\u4e2a\u5ba2\u6237\u7aef\u7684\u8fde\u63a5\u4f1a\u8bdd\uff0c\u9700\u8981\u901a\u8fc7\u5b83\u6765\u7ed9\u5ba2\u6237\u7aef\u53d1\u9001\u6570\u636e\n */\n private Session session;\n /** \n * \u63a5\u6536sid\n */\n private String sid=\"\";\n /** \n * \u8fde\u63a5\u5efa\u7acb\u6210\u529f\u8c03\u7528\u7684\u65b9\u6cd5\n */\n @OnOpen public void onOpen( Session session, @PathParam(\"sid\") String sid);\n /** \n * \u8fde\u63a5\u5173\u95ed\u8c03\u7528\u7684\u65b9\u6cd5\n */\n @OnClose public void onClose();\n /** \n * \u6536\u5230\u5ba2\u6237\u7aef\u6d88\u606f\u540e\u8c03\u7528\u7684\u65b9\u6cd5\n * @param message \u5ba2\u6237\u7aef\u53d1\u9001\u8fc7\u6765\u7684\u6d88\u606f\n */\n @OnMessage public void onMessage( String message, Session session);\n @OnError public void onError( Session session, Throwable error);\n /** \n * \u5b9e\u73b0\u670d\u52a1\u5668\u4e3b\u52a8\u63a8\u9001\n */\n private void sendMessage( String message) throws IOException;\n /** \n * \u7fa4\u53d1\u81ea\u5b9a\u4e49\u6d88\u606f\n */\n public static void sendInfo( SocketMsg socketMsg, @PathParam(\"sid\") String sid) throws IOException;\n @Override public boolean equals( Object o);\n @Override public int hashCode();\n}\n", "raw_body_no_cmt": "public class WebSocketServer {\n private static final CopyOnWriteArraySet<WebSocketServer> webSocketSet=new CopyOnWriteArraySet<WebSocketServer>();\n private Session session;\n private String sid=\"\";\n public void onOpen( Session session, String sid);\n public void onClose();\n public void onMessage( String message, Session session);\n public void onError( Session session, Throwable error);\n private void sendMessage( String message) throws IOException;\n public static void sendInfo( SocketMsg socketMsg, String sid) throws IOException;\n public boolean equals( Object o);\n public int hashCode();\n}\n"}}, {"AlipayUtils": {"retrieved_name": "AlipayUtils", "raw_body": "/** \n * \u652f\u4ed8\u5b9d\u5de5\u5177\u7c7b\n * @author zhengjie\n * @date 2018/09/30 14:04:35\n */\n@Component public class AlipayUtils {\n /** \n * \u751f\u6210\u8ba2\u5355\u53f7\n * @return String\n */\n public String getOrderCode();\n /** \n * \u6821\u9a8c\u7b7e\u540d\n * @param request HttpServletRequest\n * @param alipay \u963f\u91cc\u4e91\u914d\u7f6e\n * @return boolean\n */\n public boolean rsaCheck( HttpServletRequest request, AlipayConfig alipay);\n}\n", "raw_body_no_cmt": "public class AlipayUtils {\n public String getOrderCode();\n public boolean rsaCheck( HttpServletRequest request, AlipayConfig alipay);\n}\n"}}, {"AliPayService": {"retrieved_name": "AliPayService", "raw_body": "/** \n * @author Zheng Jie\n * @date 2018-12-31\n */\npublic interface AliPayService {\n /** \n * \u67e5\u8be2\u914d\u7f6e\n * @return AlipayConfig\n */\n AlipayConfig find();\n /** \n * \u66f4\u65b0\u914d\u7f6e\n * @param alipayConfig \u652f\u4ed8\u5b9d\u914d\u7f6e\n * @return AlipayConfig\n */\n AlipayConfig config( AlipayConfig alipayConfig);\n /** \n * \u5904\u7406\u6765\u81eaPC\u7684\u4ea4\u6613\u8bf7\u6c42\n * @param alipay \u652f\u4ed8\u5b9d\u914d\u7f6e\n * @param trade \u4ea4\u6613\u8be6\u60c5\n * @return String\n * @throws Exception \u5f02\u5e38\n */\n String toPayAsPc( AlipayConfig alipay, TradeVo trade) throws Exception ;\n /** \n * \u5904\u7406\u6765\u81ea\u624b\u673a\u7f51\u9875\u7684\u4ea4\u6613\u8bf7\u6c42\n * @param alipay \u652f\u4ed8\u5b9d\u914d\u7f6e\n * @param trade \u4ea4\u6613\u8be6\u60c5\n * @return String\n * @throws Exception \u5f02\u5e38\n */\n String toPayAsWeb( AlipayConfig alipay, TradeVo trade) throws Exception ;\n}\n", "raw_body_no_cmt": "public interface AliPayService {\n AlipayConfig find();\n AlipayConfig config( AlipayConfig alipayConfig);\n String toPayAsPc( AlipayConfig alipay, TradeVo trade) throws Exception ;\n String toPayAsWeb( AlipayConfig alipay, TradeVo trade) throws Exception ;\n}\n"}}] | [{"find": {"retrieved_name": "find", "raw_body": "@Override public GenConfig find(String tableName){\n GenConfig genConfig=genConfigRepository.findByTableName(tableName);\n if (genConfig == null) {\n return new GenConfig(tableName);\n }\n return genConfig;\n}\n"}}, {"getBytes": {"retrieved_name": "getByte", "raw_body": "private static byte[] getByte(File file){\n byte[] b=new byte[(int)file.length()];\n InputStream in=null;\n try {\n in=new FileInputStream(file);\n try {\n System.out.println(in.read(b));\n }\n catch ( IOException e) {\n log.error(e.getMessage(),e);\n }\n }\n catch ( Exception e) {\n log.error(e.getMessage(),e);\n return null;\n }\n finally {\n CloseUtil.close(in);\n }\n return b;\n}\n"}}, {"getParameter": {"retrieved_name": "getParameter", "raw_body": "/** \n * \u6839\u636e\u65b9\u6cd5\u548c\u4f20\u5165\u7684\u53c2\u6570\u83b7\u53d6\u8bf7\u6c42\u53c2\u6570\n */\nprivate String getParameter(Method method,Object[] args){\n List<Object> argList=new ArrayList<>();\n Parameter[] parameters=method.getParameters();\n for (int i=0; i < parameters.length; i++) {\n if (args[i] instanceof MultipartFile) {\n continue;\n }\n RequestBody requestBody=parameters[i].getAnnotation(RequestBody.class);\n if (requestBody != null) {\n argList.add(args[i]);\n }\n RequestParam requestParam=parameters[i].getAnnotation(RequestParam.class);\n if (requestParam != null) {\n Map<String,Object> map=new HashMap<>(2);\n String key=parameters[i].getName();\n if (!StringUtils.isEmpty(requestParam.value())) {\n key=requestParam.value();\n }\n map.put(key,args[i]);\n argList.add(map);\n }\n }\n if (argList.isEmpty()) {\n return \"\";\n }\n return argList.size() == 1 ? JSON.toJSONString(argList.get(0)) : JSON.toJSONString(argList);\n}\n"}}, {"rsaCheck": {"retrieved_name": "rsaCheck", "raw_body": "/** \n * \u6821\u9a8c\u7b7e\u540d\n * @param request HttpServletRequest\n * @param alipay \u963f\u91cc\u4e91\u914d\u7f6e\n * @return boolean\n */\npublic boolean rsaCheck(HttpServletRequest request,AlipayConfig alipay){\n Map<String,String> params=new HashMap<>(1);\n Map<String,String[]> requestParams=request.getParameterMap();\n for ( Object o : requestParams.keySet()) {\n String name=(String)o;\n String[] values=requestParams.get(name);\n String valueStr=\"\";\n for (int i=0; i < values.length; i++) {\n valueStr=(i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + \",\";\n }\n params.put(name,valueStr);\n }\n try {\n return AlipaySignature.rsaCheckV1(params,alipay.getPublicKey(),alipay.getCharset(),alipay.getSignType());\n }\n catch ( AlipayApiException e) {\n return false;\n }\n}\n"}}] | [{"returnPage": {"retrieved_name": "toPage", "raw_body": "/** \n * Page \u6570\u636e\u5904\u7406\uff0c\u9884\u9632redis\u53cd\u5e8f\u5217\u5316\u62a5\u9519\n */\npublic static <T>PageResult<T> toPage(Page<T> page){\n return new PageResult<>(page.getContent(),page.getTotalElements());\n}\n"}}] |
|
houbb_sensitive-word | sensitive-word/src/main/java/com/github/houbb/sensitive/word/support/result/AbstractWordResultHandler.java | AbstractWordResultHandler | handle | class AbstractWordResultHandler<R> implements IWordResultHandler<R> {
protected abstract R doHandle(IWordResult wordResult, IWordContext wordContext, String originalText);
@Override
public R handle(IWordResult wordResult, IWordContext wordContext, String originalText) {<FILL_FUNCTION_BODY>}
} |
if(wordResult == null) {
return null;
}
return doHandle(wordResult, wordContext, originalText);
|
return doHandle(wordResult, wordContext, originalText);
| [
"IWordContext",
"IWordResult"
] | [] | [
"IWordResult",
"IWordContext"
] | [] | {
"methods": [],
"similar_methods": [
"handle"
],
"types": [
"IWordContext",
"IWordResult"
]
} | /**
* @author binbin.hou
* @since 0.0.4
*/
public interface IWordContext {
/**
* 是否忽略大小写
* @return 是否
* @since 0.0.4
*/
boolean ignoreCase();
/**
* 是否忽略半角圆角
* @return 是否
* @since 0.0.4
*/
boolean ignoreWidth();
/**
* 是否忽略数字格式
* @return 是否
* @since 0.0.5
*/
boolean ignoreNumStyle();
/**
* 设置是否忽略大小写
* @param ignoreCase 是否忽略大小写
* @return this
* @since 0.0.4
*/
IWordContext ignoreCase( boolean ignoreCase);
/**
* 设置是否忽略半角圆角
* @param ignoreWidth 是否忽略半角圆角
* @return this
* @since 0.0.4
*/
IWordContext ignoreWidth( boolean ignoreWidth);
/**
* 设置是否忽略半角圆角
* @param ignoreNumStyle 是否忽略半角圆角
* @return this
* @since 0.0.5
*/
IWordContext ignoreNumStyle( boolean ignoreNumStyle);
/**
* 忽略中文繁简体格式
* @return 是否
* @since 0.0.6
*/
boolean ignoreChineseStyle();
/**
* 设置是否忽略中文繁简体格式
* @param ignoreChineseStyle 是否忽略
* @return this
* @since 0.0.6
*/
IWordContext ignoreChineseStyle( final boolean ignoreChineseStyle);
/**
* 是否启用单词
* @return 是否
*/
boolean enableWordCheck();
/**
* 设置是否启用单词
* @param enableWordCheck 是否
* @return 结果
*/
IWordContext enableWordCheck( boolean enableWordCheck);
/**
* 敏感数字检测
* @return 数字检测
* @since 0.0.5
*/
boolean enableNumCheck();
/**
* 设置敏感数字检测
* @param enableNumCheck 数字格式检测
* @return this
* @since 0.0.5
*/
IWordContext enableNumCheck( final boolean enableNumCheck);
/**
* 是否进行邮箱检测
* @return this
* @since 0.0.9
*/
boolean enableEmailCheck();
/**
* 设置敏感邮箱检测
* @param enableEmailCheck 是否检测
* @return this
* @since 0.0.9
*/
IWordContext enableEmailCheck( final boolean enableEmailCheck);
/**
* 敏感链接检测
* @return 是否启用
* @since 0.
*/
boolean enableUrlCheck();
/**
* 设置敏感邮箱检测
* @param enableUrlCheck 是否检测
* @return this
* @since 0.0.9
*/
IWordContext enableUrlCheck( final boolean enableUrlCheck);
/**
* 忽略英文的写法
* @return 数字检测
* @since 0.0.6
*/
boolean ignoreEnglishStyle();
/**
* 设置忽略英文的写法
* @param ignoreEnglishStyle 是否忽略
* @return this
* @since 0.0.6
*/
IWordContext ignoreEnglishStyle( final boolean ignoreEnglishStyle);
/**
* 忽略重复词
* @return 是否忽略
* @since 0.0.7
*/
boolean ignoreRepeat();
/**
* 设置忽略重复词
* @param ignoreRepeat 是否忽略
* @return this
* @since 0.0.7
*/
IWordContext ignoreRepeat( final boolean ignoreRepeat);
/**
* 敏感数字检测
* @return 数字检测
* @since 0.2.1
*/
int sensitiveCheckNumLen();
/**
* 设置敏感数字检测长度
* @param sensitiveCheckNumLen 数字格式检测长度
* @return this
* @since 0.2.1
*/
IWordContext sensitiveCheckNumLen( final int sensitiveCheckNumLen);
/**
* 设置检测策略
* @param sensitiveCheck 检测策略
* @return this
* @since 0.3.0
*/
IWordContext sensitiveCheck( final IWordCheck sensitiveCheck);
/**
* 获取检测策略
* @return 检测策略
* @since 0.3.0
*/
IWordCheck sensitiveCheck();
/**
* 设置敏感词替换策略
* @param wordReplace 策略
* @return this
* @since 0.3.0
*/
IWordContext wordReplace( final IWordReplace wordReplace);
/**
* 敏感词替换策略
* @return 替换策略
* @since 0.3.0
*/
IWordReplace wordReplace();
/**
* 设置统一的字符处理
* @param wordFormat 字符处理
* @return 结果
* @since 0.3.0
*/
IWordContext wordFormat( final IWordFormat wordFormat);
/**
* 获取格式化策略
* @return 策略
* @since 0.3.0
*/
IWordFormat wordFormat();
/**
* 获取 wordMap 策略
* @return 策略
* @since 0.3.2
*/
IWordData wordData();
/**
* 设置 wordMap 策略
* @param wordMap 策略
* @return this
* @since 0.3.2
*/
IWordContext wordData( IWordData wordMap);
IWordTag wordTag();
SensitiveWordContext wordTag( IWordTag wordTag);
ISensitiveWordCharIgnore charIgnore();
SensitiveWordContext charIgnore( ISensitiveWordCharIgnore charIgnore);
IWordResultCondition wordResultCondition();
SensitiveWordContext wordResultCondition( IWordResultCondition wordResultCondition);
}
/**
* 敏感词的结果
* @author binbin.hou
* @since 0.1.0
*/
public interface IWordResult {
/**
* 开始下标
* @return 开始下标
* @since 0.1.0
*/
int startIndex();
/**
* 结束下标
* @return 结束下标
* @since 0.1.0
*/
int endIndex();
/**
* 类别
* @return 类别
* @since 0.14.0
*/
String type();
}
/**
* 对于结果的处理
* @param wordResult 结果
* @param wordContext 上下文
* @param originalText 原始文本
* @return 处理结果
* @since 0.1.0
*/
R handle(final IWordResult wordResult,final IWordContext wordContext,final String originalText);
| public interface IWordContext {
boolean ignoreCase();
boolean ignoreWidth();
boolean ignoreNumStyle();
IWordContext ignoreCase( boolean ignoreCase);
IWordContext ignoreWidth( boolean ignoreWidth);
IWordContext ignoreNumStyle( boolean ignoreNumStyle);
boolean ignoreChineseStyle();
IWordContext ignoreChineseStyle( final boolean ignoreChineseStyle);
boolean enableWordCheck();
IWordContext enableWordCheck( boolean enableWordCheck);
boolean enableNumCheck();
IWordContext enableNumCheck( final boolean enableNumCheck);
boolean enableEmailCheck();
IWordContext enableEmailCheck( final boolean enableEmailCheck);
boolean enableUrlCheck();
IWordContext enableUrlCheck( final boolean enableUrlCheck);
boolean ignoreEnglishStyle();
IWordContext ignoreEnglishStyle( final boolean ignoreEnglishStyle);
boolean ignoreRepeat();
IWordContext ignoreRepeat( final boolean ignoreRepeat);
int sensitiveCheckNumLen();
IWordContext sensitiveCheckNumLen( final int sensitiveCheckNumLen);
IWordContext sensitiveCheck( final IWordCheck sensitiveCheck);
IWordCheck sensitiveCheck();
IWordContext wordReplace( final IWordReplace wordReplace);
IWordReplace wordReplace();
IWordContext wordFormat( final IWordFormat wordFormat);
IWordFormat wordFormat();
IWordData wordData();
IWordContext wordData( IWordData wordMap);
IWordTag wordTag();
SensitiveWordContext wordTag( IWordTag wordTag);
ISensitiveWordCharIgnore charIgnore();
SensitiveWordContext charIgnore( ISensitiveWordCharIgnore charIgnore);
IWordResultCondition wordResultCondition();
SensitiveWordContext wordResultCondition( IWordResultCondition wordResultCondition);
}
public interface IWordResult {
int startIndex();
int endIndex();
String type();
}
/**
* 对于结果的处理
* @param wordResult 结果
* @param wordContext 上下文
* @param originalText 原始文本
* @return 处理结果
* @since 0.1.0
*/
R handle(final IWordResult wordResult,final IWordContext wordContext,final String originalText);
| {"types": [{"IWordContext": "IWordContext"}, {"IWordResult": "IWordResult"}], "similar_methods": [{"handle": "handle"}]} | [{"IWordContext": {"retrieved_name": "IWordContext", "raw_body": "/** \n * @author binbin.hou\n * @since 0.0.4\n */\npublic interface IWordContext {\n /** \n * \u662f\u5426\u5ffd\u7565\u5927\u5c0f\u5199\n * @return \u662f\u5426\n * @since 0.0.4\n */\n boolean ignoreCase();\n /** \n * \u662f\u5426\u5ffd\u7565\u534a\u89d2\u5706\u89d2\n * @return \u662f\u5426\n * @since 0.0.4\n */\n boolean ignoreWidth();\n /** \n * \u662f\u5426\u5ffd\u7565\u6570\u5b57\u683c\u5f0f\n * @return \u662f\u5426\n * @since 0.0.5\n */\n boolean ignoreNumStyle();\n /** \n * \u8bbe\u7f6e\u662f\u5426\u5ffd\u7565\u5927\u5c0f\u5199\n * @param ignoreCase \u662f\u5426\u5ffd\u7565\u5927\u5c0f\u5199\n * @return this\n * @since 0.0.4\n */\n IWordContext ignoreCase( boolean ignoreCase);\n /** \n * \u8bbe\u7f6e\u662f\u5426\u5ffd\u7565\u534a\u89d2\u5706\u89d2\n * @param ignoreWidth \u662f\u5426\u5ffd\u7565\u534a\u89d2\u5706\u89d2\n * @return this\n * @since 0.0.4\n */\n IWordContext ignoreWidth( boolean ignoreWidth);\n /** \n * \u8bbe\u7f6e\u662f\u5426\u5ffd\u7565\u534a\u89d2\u5706\u89d2\n * @param ignoreNumStyle \u662f\u5426\u5ffd\u7565\u534a\u89d2\u5706\u89d2\n * @return this\n * @since 0.0.5\n */\n IWordContext ignoreNumStyle( boolean ignoreNumStyle);\n /** \n * \u5ffd\u7565\u4e2d\u6587\u7e41\u7b80\u4f53\u683c\u5f0f\n * @return \u662f\u5426\n * @since 0.0.6\n */\n boolean ignoreChineseStyle();\n /** \n * \u8bbe\u7f6e\u662f\u5426\u5ffd\u7565\u4e2d\u6587\u7e41\u7b80\u4f53\u683c\u5f0f\n * @param ignoreChineseStyle \u662f\u5426\u5ffd\u7565\n * @return this\n * @since 0.0.6\n */\n IWordContext ignoreChineseStyle( final boolean ignoreChineseStyle);\n /** \n * \u662f\u5426\u542f\u7528\u5355\u8bcd\n * @return \u662f\u5426\n */\n boolean enableWordCheck();\n /** \n * \u8bbe\u7f6e\u662f\u5426\u542f\u7528\u5355\u8bcd\n * @param enableWordCheck \u662f\u5426\n * @return \u7ed3\u679c\n */\n IWordContext enableWordCheck( boolean enableWordCheck);\n /** \n * \u654f\u611f\u6570\u5b57\u68c0\u6d4b\n * @return \u6570\u5b57\u68c0\u6d4b\n * @since 0.0.5\n */\n boolean enableNumCheck();\n /** \n * \u8bbe\u7f6e\u654f\u611f\u6570\u5b57\u68c0\u6d4b\n * @param enableNumCheck \u6570\u5b57\u683c\u5f0f\u68c0\u6d4b\n * @return this\n * @since 0.0.5\n */\n IWordContext enableNumCheck( final boolean enableNumCheck);\n /** \n * \u662f\u5426\u8fdb\u884c\u90ae\u7bb1\u68c0\u6d4b\n * @return this\n * @since 0.0.9\n */\n boolean enableEmailCheck();\n /** \n * \u8bbe\u7f6e\u654f\u611f\u90ae\u7bb1\u68c0\u6d4b\n * @param enableEmailCheck \u662f\u5426\u68c0\u6d4b\n * @return this\n * @since 0.0.9\n */\n IWordContext enableEmailCheck( final boolean enableEmailCheck);\n /** \n * \u654f\u611f\u94fe\u63a5\u68c0\u6d4b\n * @return \u662f\u5426\u542f\u7528\n * @since 0.\n */\n boolean enableUrlCheck();\n /** \n * \u8bbe\u7f6e\u654f\u611f\u90ae\u7bb1\u68c0\u6d4b\n * @param enableUrlCheck \u662f\u5426\u68c0\u6d4b\n * @return this\n * @since 0.0.9\n */\n IWordContext enableUrlCheck( final boolean enableUrlCheck);\n /** \n * \u5ffd\u7565\u82f1\u6587\u7684\u5199\u6cd5\n * @return \u6570\u5b57\u68c0\u6d4b\n * @since 0.0.6\n */\n boolean ignoreEnglishStyle();\n /** \n * \u8bbe\u7f6e\u5ffd\u7565\u82f1\u6587\u7684\u5199\u6cd5\n * @param ignoreEnglishStyle \u662f\u5426\u5ffd\u7565\n * @return this\n * @since 0.0.6\n */\n IWordContext ignoreEnglishStyle( final boolean ignoreEnglishStyle);\n /** \n * \u5ffd\u7565\u91cd\u590d\u8bcd\n * @return \u662f\u5426\u5ffd\u7565\n * @since 0.0.7\n */\n boolean ignoreRepeat();\n /** \n * \u8bbe\u7f6e\u5ffd\u7565\u91cd\u590d\u8bcd\n * @param ignoreRepeat \u662f\u5426\u5ffd\u7565\n * @return this\n * @since 0.0.7\n */\n IWordContext ignoreRepeat( final boolean ignoreRepeat);\n /** \n * \u654f\u611f\u6570\u5b57\u68c0\u6d4b\n * @return \u6570\u5b57\u68c0\u6d4b\n * @since 0.2.1\n */\n int sensitiveCheckNumLen();\n /** \n * \u8bbe\u7f6e\u654f\u611f\u6570\u5b57\u68c0\u6d4b\u957f\u5ea6\n * @param sensitiveCheckNumLen \u6570\u5b57\u683c\u5f0f\u68c0\u6d4b\u957f\u5ea6\n * @return this\n * @since 0.2.1\n */\n IWordContext sensitiveCheckNumLen( final int sensitiveCheckNumLen);\n /** \n * \u8bbe\u7f6e\u68c0\u6d4b\u7b56\u7565\n * @param sensitiveCheck \u68c0\u6d4b\u7b56\u7565\n * @return this\n * @since 0.3.0\n */\n IWordContext sensitiveCheck( final IWordCheck sensitiveCheck);\n /** \n * \u83b7\u53d6\u68c0\u6d4b\u7b56\u7565\n * @return \u68c0\u6d4b\u7b56\u7565\n * @since 0.3.0\n */\n IWordCheck sensitiveCheck();\n /** \n * \u8bbe\u7f6e\u654f\u611f\u8bcd\u66ff\u6362\u7b56\u7565\n * @param wordReplace \u7b56\u7565\n * @return this\n * @since 0.3.0\n */\n IWordContext wordReplace( final IWordReplace wordReplace);\n /** \n * \u654f\u611f\u8bcd\u66ff\u6362\u7b56\u7565\n * @return \u66ff\u6362\u7b56\u7565\n * @since 0.3.0\n */\n IWordReplace wordReplace();\n /** \n * \u8bbe\u7f6e\u7edf\u4e00\u7684\u5b57\u7b26\u5904\u7406\n * @param wordFormat \u5b57\u7b26\u5904\u7406\n * @return \u7ed3\u679c\n * @since 0.3.0\n */\n IWordContext wordFormat( final IWordFormat wordFormat);\n /** \n * \u83b7\u53d6\u683c\u5f0f\u5316\u7b56\u7565\n * @return \u7b56\u7565\n * @since 0.3.0\n */\n IWordFormat wordFormat();\n /** \n * \u83b7\u53d6 wordMap \u7b56\u7565\n * @return \u7b56\u7565\n * @since 0.3.2\n */\n IWordData wordData();\n /** \n * \u8bbe\u7f6e wordMap \u7b56\u7565\n * @param wordMap \u7b56\u7565\n * @return this\n * @since 0.3.2\n */\n IWordContext wordData( IWordData wordMap);\n IWordTag wordTag();\n SensitiveWordContext wordTag( IWordTag wordTag);\n ISensitiveWordCharIgnore charIgnore();\n SensitiveWordContext charIgnore( ISensitiveWordCharIgnore charIgnore);\n IWordResultCondition wordResultCondition();\n SensitiveWordContext wordResultCondition( IWordResultCondition wordResultCondition);\n}\n", "raw_body_no_cmt": "public interface IWordContext {\n boolean ignoreCase();\n boolean ignoreWidth();\n boolean ignoreNumStyle();\n IWordContext ignoreCase( boolean ignoreCase);\n IWordContext ignoreWidth( boolean ignoreWidth);\n IWordContext ignoreNumStyle( boolean ignoreNumStyle);\n boolean ignoreChineseStyle();\n IWordContext ignoreChineseStyle( final boolean ignoreChineseStyle);\n boolean enableWordCheck();\n IWordContext enableWordCheck( boolean enableWordCheck);\n boolean enableNumCheck();\n IWordContext enableNumCheck( final boolean enableNumCheck);\n boolean enableEmailCheck();\n IWordContext enableEmailCheck( final boolean enableEmailCheck);\n boolean enableUrlCheck();\n IWordContext enableUrlCheck( final boolean enableUrlCheck);\n boolean ignoreEnglishStyle();\n IWordContext ignoreEnglishStyle( final boolean ignoreEnglishStyle);\n boolean ignoreRepeat();\n IWordContext ignoreRepeat( final boolean ignoreRepeat);\n int sensitiveCheckNumLen();\n IWordContext sensitiveCheckNumLen( final int sensitiveCheckNumLen);\n IWordContext sensitiveCheck( final IWordCheck sensitiveCheck);\n IWordCheck sensitiveCheck();\n IWordContext wordReplace( final IWordReplace wordReplace);\n IWordReplace wordReplace();\n IWordContext wordFormat( final IWordFormat wordFormat);\n IWordFormat wordFormat();\n IWordData wordData();\n IWordContext wordData( IWordData wordMap);\n IWordTag wordTag();\n SensitiveWordContext wordTag( IWordTag wordTag);\n ISensitiveWordCharIgnore charIgnore();\n SensitiveWordContext charIgnore( ISensitiveWordCharIgnore charIgnore);\n IWordResultCondition wordResultCondition();\n SensitiveWordContext wordResultCondition( IWordResultCondition wordResultCondition);\n}\n"}}, {"IWordResult": {"retrieved_name": "IWordResult", "raw_body": "/** \n * \u654f\u611f\u8bcd\u7684\u7ed3\u679c\n * @author binbin.hou\n * @since 0.1.0\n */\npublic interface IWordResult {\n /** \n * \u5f00\u59cb\u4e0b\u6807\n * @return \u5f00\u59cb\u4e0b\u6807\n * @since 0.1.0\n */\n int startIndex();\n /** \n * \u7ed3\u675f\u4e0b\u6807\n * @return \u7ed3\u675f\u4e0b\u6807\n * @since 0.1.0\n */\n int endIndex();\n /** \n * \u7c7b\u522b\n * @return \u7c7b\u522b\n * @since 0.14.0\n */\n String type();\n}\n", "raw_body_no_cmt": "public interface IWordResult {\n int startIndex();\n int endIndex();\n String type();\n}\n"}}] | [] | [{"handle": {"retrieved_name": "handle", "raw_body": "/** \n * \u5bf9\u4e8e\u7ed3\u679c\u7684\u5904\u7406\n * @param wordResult \u7ed3\u679c\n * @param wordContext \u4e0a\u4e0b\u6587\n * @param originalText \u539f\u59cb\u6587\u672c\n * @return \u5904\u7406\u7ed3\u679c\n * @since 0.1.0\n */\nR handle(final IWordResult wordResult,final IWordContext wordContext,final String originalText);\n"}}] |
|
eirslett_frontend-maven-plugin | frontend-maven-plugin/frontend-maven-plugin/src/main/java/com/github/eirslett/maven/plugins/frontend/mojo/InstallNodeAndYarnMojo.java | InstallNodeAndYarnMojo | execute | class InstallNodeAndYarnMojo extends AbstractFrontendMojo {
private static final String YARNRC_YAML_FILE_NAME = ".yarnrc.yml";
/**
* Where to download Node.js binary from. Defaults to https://nodejs.org/dist/
*/
@Parameter(property = "nodeDownloadRoot", required = false)
private String nodeDownloadRoot;
/**
* Where to download Yarn binary from. Defaults to https://github.com/yarnpkg/yarn/releases/download/...
*/
@Parameter(property = "yarnDownloadRoot", required = false,
defaultValue = YarnInstaller.DEFAULT_YARN_DOWNLOAD_ROOT)
private String yarnDownloadRoot;
/**
* The version of Node.js to install. IMPORTANT! Most Node.js version names start with 'v', for example
* 'v0.10.18'
*/
@Parameter(property = "nodeVersion", required = true)
private String nodeVersion;
/**
* The version of Yarn to install. IMPORTANT! Most Yarn names start with 'v', for example 'v0.15.0'.
*/
@Parameter(property = "yarnVersion", required = true)
private String yarnVersion;
/**
* Server Id for download username and password
*/
@Parameter(property = "serverId", defaultValue = "")
private String serverId;
@Parameter(property = "session", defaultValue = "${session}", readonly = true)
private MavenSession session;
/**
* Skips execution of this mojo.
*/
@Parameter(property = "skip.installyarn", alias = "skip.installyarn", defaultValue = "${skip.installyarn}")
private boolean skip;
@Component(role = SettingsDecrypter.class)
private SettingsDecrypter decrypter;
@Override
protected boolean skipExecution() {
return this.skip;
}
/**
* Checks whether a .yarnrc.yml file exists at the project root (in multi-module builds, it will be the Reactor project)
*
* @return true if the .yarnrc.yml file exists, false otherwise
*/
private boolean isYarnrcYamlFilePresent() {
Stream<File> filesToCheck = Stream.of(
new File(session.getCurrentProject().getBasedir(), YARNRC_YAML_FILE_NAME),
new File(session.getRequest().getMultiModuleProjectDirectory(), YARNRC_YAML_FILE_NAME),
new File(session.getExecutionRootDirectory(), YARNRC_YAML_FILE_NAME)
);
return filesToCheck
.anyMatch(File::exists);
}
@Override
public void execute(FrontendPluginFactory factory) throws InstallationException {<FILL_FUNCTION_BODY>}
} |
ProxyConfig proxyConfig = MojoUtils.getProxyConfig(this.session, this.decrypter);
Server server = MojoUtils.decryptServer(this.serverId, this.session, this.decrypter);
if (null != server) {
factory.getNodeInstaller(proxyConfig).setNodeDownloadRoot(this.nodeDownloadRoot)
.setNodeVersion(this.nodeVersion).setPassword(server.getPassword())
.setUserName(server.getUsername()).install();
factory.getYarnInstaller(proxyConfig).setYarnDownloadRoot(this.yarnDownloadRoot)
.setYarnVersion(this.yarnVersion).setUserName(server.getUsername())
.setPassword(server.getPassword()).setIsYarnBerry(isYarnrcYamlFilePresent()).install();
} else {
factory.getNodeInstaller(proxyConfig).setNodeDownloadRoot(this.nodeDownloadRoot)
.setNodeVersion(this.nodeVersion).install();
factory.getYarnInstaller(proxyConfig).setYarnDownloadRoot(this.yarnDownloadRoot)
.setYarnVersion(this.yarnVersion).setIsYarnBerry(isYarnrcYamlFilePresent()).install();
}
| public abstract class AbstractFrontendMojo extends AbstractMojo {
@Component protected MojoExecution execution;
/**
* Whether you should skip while running in the test phase (default is false)
*/
@Parameter(property="skipTests",required=false,defaultValue="false") protected Boolean skipTests;
/**
* Set this to true to ignore a failure during testing. Its use is NOT RECOMMENDED, but quite convenient on occasion.
* @since 1.4
*/
@Parameter(property="maven.test.failure.ignore",defaultValue="false") protected boolean testFailureIgnore;
/**
* The base directory for running all Node commands. (Usually the directory that contains package.json)
*/
@Parameter(defaultValue="${basedir}",property="workingDirectory",required=false) protected File workingDirectory;
/**
* The base directory for installing node and npm.
*/
@Parameter(property="installDirectory",required=false) protected File installDirectory;
/**
* Additional environment variables to pass to the build.
*/
@Parameter protected Map<String,String> environmentVariables;
@Parameter(defaultValue="${project}",readonly=true) private MavenProject project;
@Parameter(defaultValue="${repositorySystemSession}",readonly=true) private RepositorySystemSession repositorySystemSession;
/**
* Determines if this execution should be skipped.
*/
private boolean skipTestPhase();
/**
* Determines if the current execution is during a testing phase (e.g., "test" or "integration-test").
*/
private boolean isTestingPhase();
protected abstract void execute( FrontendPluginFactory factory) throws FrontendException ;
/**
* Implemented by children to determine if this execution should be skipped.
*/
protected abstract boolean skipExecution();
@Override public void execute() throws MojoFailureException;
}
|
if (skipExecution()) {
getLog().info("Skipping execution of install-node-and-yarn mojo");
return;
}
if (isYarnrcYamlFilePresent()) {
getLog().info("Skipping execution of install-node-and-yarn mojo because a .yarnrc.yml file is present");
return;
}
NodeInstaller nodeInstaller = factory.createNodeInstaller(nodeDownloadRoot, nodeVersion, serverId);
YarnInstaller yarnInstaller = factory.createYarnInstaller(yarnDownloadRoot, yarnVersion, serverId);
try {
nodeInstaller.install();
yarnInstaller.install();
} catch (InstallationException e) {
throw new InstallationException("Failed to install Node.js and Yarn", e);
}
| [
"FrontendPluginFactory",
"InstallationException",
"NodeInstaller",
"YarnInstaller"
] | [
"createNodeInstaller",
"info",
"install",
"createYarnInstaller"
] | [
"FrontendPluginFactory",
"ProxyConfig",
"Server",
"SettingsDecrypter",
"MavenSession"
] | [
"getUsername",
"setUserName",
"setNodeVersion",
"install",
"setYarnDownloadRoot",
"getYarnInstaller",
"getPassword",
"setYarnVersion",
"setNodeDownloadRoot",
"decryptServer",
"getProxyConfig",
"getNodeInstaller",
"setPassword",
"setIsYarnBerry"
] | {
"methods": [
"createNodeInstaller",
"info",
"install",
"createYarnInstaller"
],
"similar_methods": [
"execute"
],
"types": [
"FrontendPluginFactory",
"InstallationException",
"NodeInstaller",
"YarnInstaller"
]
} | public final class FrontendPluginFactory {
private static final Platform defaultPlatform=Platform.guess();
private static final String DEFAULT_CACHE_PATH="cache";
private final File workingDirectory;
private final File installDirectory;
private final CacheResolver cacheResolver;
public FrontendPluginFactory( File workingDirectory, File installDirectory);
public FrontendPluginFactory( File workingDirectory, File installDirectory, CacheResolver cacheResolver);
public BunInstaller getBunInstaller( ProxyConfig proxy);
public NodeInstaller getNodeInstaller( ProxyConfig proxy);
public NPMInstaller getNPMInstaller( ProxyConfig proxy);
public PnpmInstaller getPnpmInstaller( ProxyConfig proxy);
public YarnInstaller getYarnInstaller( ProxyConfig proxy);
public BowerRunner getBowerRunner( ProxyConfig proxy);
public BunRunner getBunRunner( ProxyConfig proxy, String npmRegistryURL);
public JspmRunner getJspmRunner();
public NpmRunner getNpmRunner( ProxyConfig proxy, String npmRegistryURL);
public PnpmRunner getPnpmRunner( ProxyConfig proxyConfig, String npmRegistryUrl);
public NpxRunner getNpxRunner( ProxyConfig proxy, String npmRegistryURL);
public YarnRunner getYarnRunner( ProxyConfig proxy, String npmRegistryURL);
public GruntRunner getGruntRunner();
public EmberRunner getEmberRunner();
public KarmaRunner getKarmaRunner();
public GulpRunner getGulpRunner();
public WebpackRunner getWebpackRunner();
private NodeExecutorConfig getExecutorConfig();
private InstallConfig getInstallConfig();
private static final CacheResolver getDefaultCacheResolver( File root);
}
public final class InstallationException extends FrontendException {
InstallationException( String message);
InstallationException( String message, Throwable cause);
}
public class NodeInstaller {
public static final String INSTALL_PATH="/node";
private static final Object LOCK=new Object();
private String npmVersion, nodeVersion, nodeDownloadRoot, userName, password;
private final Logger logger;
private final InstallConfig config;
private final ArchiveExtractor archiveExtractor;
private final FileDownloader fileDownloader;
NodeInstaller( InstallConfig config, ArchiveExtractor archiveExtractor, FileDownloader fileDownloader);
public NodeInstaller setNodeVersion( String nodeVersion);
public NodeInstaller setNodeDownloadRoot( String nodeDownloadRoot);
public NodeInstaller setNpmVersion( String npmVersion);
public NodeInstaller setUserName( String userName);
public NodeInstaller setPassword( String password);
private boolean npmProvided() throws InstallationException;
public void install() throws InstallationException;
private boolean nodeIsAlreadyInstalled();
private void installNodeDefault() throws InstallationException;
private void installNodeWithNpmForWindows() throws InstallationException;
private void installNodeForWindows() throws InstallationException;
private File getTempDirectory();
private File getInstallDirectory();
private void deleteTempDirectory( File tmpDirectory) throws IOException;
private void extractFile( File archive, File destinationDirectory) throws ArchiveExtractionException;
private void downloadFileIfMissing( String downloadUrl, File destination, String userName, String password) throws DownloadException;
private void downloadFile( String downloadUrl, File destination, String userName, String password) throws DownloadException;
}
public class YarnInstaller {
public static final String INSTALL_PATH="/node/yarn";
public static final String DEFAULT_YARN_DOWNLOAD_ROOT="https://github.com/yarnpkg/yarn/releases/download/";
private static final Object LOCK=new Object();
private static final String YARN_ROOT_DIRECTORY="dist";
private String yarnVersion, yarnDownloadRoot, userName, password;
private boolean isYarnBerry;
private final Logger logger;
private final InstallConfig config;
private final ArchiveExtractor archiveExtractor;
private final FileDownloader fileDownloader;
YarnInstaller( InstallConfig config, ArchiveExtractor archiveExtractor, FileDownloader fileDownloader);
public YarnInstaller setYarnVersion( String yarnVersion);
public YarnInstaller setIsYarnBerry( boolean isYarnBerry);
public YarnInstaller setYarnDownloadRoot( String yarnDownloadRoot);
public YarnInstaller setUserName( String userName);
public YarnInstaller setPassword( String password);
public void install() throws InstallationException;
private boolean yarnIsAlreadyInstalled();
private void installYarn() throws InstallationException;
private File getInstallDirectory();
private void extractFile( File archive, File destinationDirectory) throws ArchiveExtractionException;
private void ensureCorrectYarnRootDirectory( File installDirectory, String yarnVersion) throws IOException;
private void downloadFileIfMissing( String downloadUrl, File destination, String userName, String password) throws DownloadException;
private void downloadFile( String downloadUrl, File destination, String userName, String password) throws DownloadException;
}
NodeInstaller(InstallConfig config,ArchiveExtractor archiveExtractor,FileDownloader fileDownloader){
this.logger=LoggerFactory.getLogger(getClass());
this.config=config;
this.archiveExtractor=archiveExtractor;
this.fileDownloader=fileDownloader;
}
void download(String downloadUrl,String destination,String userName,String password) throws DownloadException ;
public void install() throws InstallationException {
synchronized (LOCK) {
if (!bunIsAlreadyInstalled()) {
if (!this.bunVersion.startsWith("v")) {
this.logger.warn("Bun version does not start with naming convention 'v'.");
}
if (this.config.getPlatform().isWindows()) {
throw new InstallationException("Unable to install bun on windows!");
}
else {
installBunDefault();
}
}
}
}
public YarnInstaller getYarnInstaller(ProxyConfig proxy){
return new YarnInstaller(getInstallConfig(),new DefaultArchiveExtractor(),new DefaultFileDownloader(proxy));
}
public final void execute(String args,Map<String,String> environment) throws TaskRunnerException {
final List<String> arguments=getArguments(args);
logger.info("Running " + taskToString(taskName,arguments) + " in "+ config.getWorkingDirectory());
try {
final int result=new BunExecutor(config,arguments,environment).executeAndRedirectOutput(logger);
if (result != 0) {
throw new TaskRunnerException(taskToString(taskName,arguments) + " failed. (error code " + result+ ")");
}
}
catch ( ProcessExecutionException e) {
throw new TaskRunnerException(taskToString(taskName,arguments) + " failed.",e);
}
}
| public final class FrontendPluginFactory {
private static final Platform defaultPlatform=Platform.guess();
private static final String DEFAULT_CACHE_PATH="cache";
private final File workingDirectory;
private final File installDirectory;
private final CacheResolver cacheResolver;
public FrontendPluginFactory( File workingDirectory, File installDirectory);
public FrontendPluginFactory( File workingDirectory, File installDirectory, CacheResolver cacheResolver);
public BunInstaller getBunInstaller( ProxyConfig proxy);
public NodeInstaller getNodeInstaller( ProxyConfig proxy);
public NPMInstaller getNPMInstaller( ProxyConfig proxy);
public PnpmInstaller getPnpmInstaller( ProxyConfig proxy);
public YarnInstaller getYarnInstaller( ProxyConfig proxy);
public BowerRunner getBowerRunner( ProxyConfig proxy);
public BunRunner getBunRunner( ProxyConfig proxy, String npmRegistryURL);
public JspmRunner getJspmRunner();
public NpmRunner getNpmRunner( ProxyConfig proxy, String npmRegistryURL);
public PnpmRunner getPnpmRunner( ProxyConfig proxyConfig, String npmRegistryUrl);
public NpxRunner getNpxRunner( ProxyConfig proxy, String npmRegistryURL);
public YarnRunner getYarnRunner( ProxyConfig proxy, String npmRegistryURL);
public GruntRunner getGruntRunner();
public EmberRunner getEmberRunner();
public KarmaRunner getKarmaRunner();
public GulpRunner getGulpRunner();
public WebpackRunner getWebpackRunner();
private NodeExecutorConfig getExecutorConfig();
private InstallConfig getInstallConfig();
private static final CacheResolver getDefaultCacheResolver( File root);
}
public final class InstallationException extends FrontendException {
InstallationException( String message);
InstallationException( String message, Throwable cause);
}
public class NodeInstaller {
public static final String INSTALL_PATH="/node";
private static final Object LOCK=new Object();
private String npmVersion, nodeVersion, nodeDownloadRoot, userName, password;
private final Logger logger;
private final InstallConfig config;
private final ArchiveExtractor archiveExtractor;
private final FileDownloader fileDownloader;
NodeInstaller( InstallConfig config, ArchiveExtractor archiveExtractor, FileDownloader fileDownloader);
public NodeInstaller setNodeVersion( String nodeVersion);
public NodeInstaller setNodeDownloadRoot( String nodeDownloadRoot);
public NodeInstaller setNpmVersion( String npmVersion);
public NodeInstaller setUserName( String userName);
public NodeInstaller setPassword( String password);
private boolean npmProvided() throws InstallationException;
public void install() throws InstallationException;
private boolean nodeIsAlreadyInstalled();
private void installNodeDefault() throws InstallationException;
private void installNodeWithNpmForWindows() throws InstallationException;
private void installNodeForWindows() throws InstallationException;
private File getTempDirectory();
private File getInstallDirectory();
private void deleteTempDirectory( File tmpDirectory) throws IOException;
private void extractFile( File archive, File destinationDirectory) throws ArchiveExtractionException;
private void downloadFileIfMissing( String downloadUrl, File destination, String userName, String password) throws DownloadException;
private void downloadFile( String downloadUrl, File destination, String userName, String password) throws DownloadException;
}
public class YarnInstaller {
public static final String INSTALL_PATH="/node/yarn";
public static final String DEFAULT_YARN_DOWNLOAD_ROOT="https://github.com/yarnpkg/yarn/releases/download/";
private static final Object LOCK=new Object();
private static final String YARN_ROOT_DIRECTORY="dist";
private String yarnVersion, yarnDownloadRoot, userName, password;
private boolean isYarnBerry;
private final Logger logger;
private final InstallConfig config;
private final ArchiveExtractor archiveExtractor;
private final FileDownloader fileDownloader;
YarnInstaller( InstallConfig config, ArchiveExtractor archiveExtractor, FileDownloader fileDownloader);
public YarnInstaller setYarnVersion( String yarnVersion);
public YarnInstaller setIsYarnBerry( boolean isYarnBerry);
public YarnInstaller setYarnDownloadRoot( String yarnDownloadRoot);
public YarnInstaller setUserName( String userName);
public YarnInstaller setPassword( String password);
public void install() throws InstallationException;
private boolean yarnIsAlreadyInstalled();
private void installYarn() throws InstallationException;
private File getInstallDirectory();
private void extractFile( File archive, File destinationDirectory) throws ArchiveExtractionException;
private void ensureCorrectYarnRootDirectory( File installDirectory, String yarnVersion) throws IOException;
private void downloadFileIfMissing( String downloadUrl, File destination, String userName, String password) throws DownloadException;
private void downloadFile( String downloadUrl, File destination, String userName, String password) throws DownloadException;
}
NodeInstaller(InstallConfig config,ArchiveExtractor archiveExtractor,FileDownloader fileDownloader){
this.logger=LoggerFactory.getLogger(getClass());
this.config=config;
this.archiveExtractor=archiveExtractor;
this.fileDownloader=fileDownloader;
}
void download(String downloadUrl,String destination,String userName,String password) throws DownloadException ;
public void install() throws InstallationException {
synchronized (LOCK) {
if (!bunIsAlreadyInstalled()) {
if (!this.bunVersion.startsWith("v")) {
this.logger.warn("Bun version does not start with naming convention 'v'.");
}
if (this.config.getPlatform().isWindows()) {
throw new InstallationException("Unable to install bun on windows!");
}
else {
installBunDefault();
}
}
}
}
public YarnInstaller getYarnInstaller(ProxyConfig proxy){
return new YarnInstaller(getInstallConfig(),new DefaultArchiveExtractor(),new DefaultFileDownloader(proxy));
}
public final void execute(String args,Map<String,String> environment) throws TaskRunnerException {
final List<String> arguments=getArguments(args);
logger.info("Running " + taskToString(taskName,arguments) + " in "+ config.getWorkingDirectory());
try {
final int result=new BunExecutor(config,arguments,environment).executeAndRedirectOutput(logger);
if (result != 0) {
throw new TaskRunnerException(taskToString(taskName,arguments) + " failed. (error code " + result+ ")");
}
}
catch ( ProcessExecutionException e) {
throw new TaskRunnerException(taskToString(taskName,arguments) + " failed.",e);
}
}
| {"types": [{"FrontendPluginFactory": "FrontendPluginFactory"}, {"InstallationException": "InstallationException"}, {"NodeInstaller": "NodeInstaller"}, {"YarnInstaller": "YarnInstaller"}], "methods": [{"createNodeInstaller": "NodeInstaller"}, {"info": "download"}, {"install": "install"}, {"createYarnInstaller": "getYarnInstaller"}], "similar_methods": [{"execute": "execute"}]} | [{"FrontendPluginFactory": {"retrieved_name": "FrontendPluginFactory", "raw_body": "public final class FrontendPluginFactory {\n private static final Platform defaultPlatform=Platform.guess();\n private static final String DEFAULT_CACHE_PATH=\"cache\";\n private final File workingDirectory;\n private final File installDirectory;\n private final CacheResolver cacheResolver;\n public FrontendPluginFactory( File workingDirectory, File installDirectory);\n public FrontendPluginFactory( File workingDirectory, File installDirectory, CacheResolver cacheResolver);\n public BunInstaller getBunInstaller( ProxyConfig proxy);\n public NodeInstaller getNodeInstaller( ProxyConfig proxy);\n public NPMInstaller getNPMInstaller( ProxyConfig proxy);\n public PnpmInstaller getPnpmInstaller( ProxyConfig proxy);\n public YarnInstaller getYarnInstaller( ProxyConfig proxy);\n public BowerRunner getBowerRunner( ProxyConfig proxy);\n public BunRunner getBunRunner( ProxyConfig proxy, String npmRegistryURL);\n public JspmRunner getJspmRunner();\n public NpmRunner getNpmRunner( ProxyConfig proxy, String npmRegistryURL);\n public PnpmRunner getPnpmRunner( ProxyConfig proxyConfig, String npmRegistryUrl);\n public NpxRunner getNpxRunner( ProxyConfig proxy, String npmRegistryURL);\n public YarnRunner getYarnRunner( ProxyConfig proxy, String npmRegistryURL);\n public GruntRunner getGruntRunner();\n public EmberRunner getEmberRunner();\n public KarmaRunner getKarmaRunner();\n public GulpRunner getGulpRunner();\n public WebpackRunner getWebpackRunner();\n private NodeExecutorConfig getExecutorConfig();\n private InstallConfig getInstallConfig();\n private static final CacheResolver getDefaultCacheResolver( File root);\n}\n", "raw_body_no_cmt": "public final class FrontendPluginFactory {\n private static final Platform defaultPlatform=Platform.guess();\n private static final String DEFAULT_CACHE_PATH=\"cache\";\n private final File workingDirectory;\n private final File installDirectory;\n private final CacheResolver cacheResolver;\n public FrontendPluginFactory( File workingDirectory, File installDirectory);\n public FrontendPluginFactory( File workingDirectory, File installDirectory, CacheResolver cacheResolver);\n public BunInstaller getBunInstaller( ProxyConfig proxy);\n public NodeInstaller getNodeInstaller( ProxyConfig proxy);\n public NPMInstaller getNPMInstaller( ProxyConfig proxy);\n public PnpmInstaller getPnpmInstaller( ProxyConfig proxy);\n public YarnInstaller getYarnInstaller( ProxyConfig proxy);\n public BowerRunner getBowerRunner( ProxyConfig proxy);\n public BunRunner getBunRunner( ProxyConfig proxy, String npmRegistryURL);\n public JspmRunner getJspmRunner();\n public NpmRunner getNpmRunner( ProxyConfig proxy, String npmRegistryURL);\n public PnpmRunner getPnpmRunner( ProxyConfig proxyConfig, String npmRegistryUrl);\n public NpxRunner getNpxRunner( ProxyConfig proxy, String npmRegistryURL);\n public YarnRunner getYarnRunner( ProxyConfig proxy, String npmRegistryURL);\n public GruntRunner getGruntRunner();\n public EmberRunner getEmberRunner();\n public KarmaRunner getKarmaRunner();\n public GulpRunner getGulpRunner();\n public WebpackRunner getWebpackRunner();\n private NodeExecutorConfig getExecutorConfig();\n private InstallConfig getInstallConfig();\n private static final CacheResolver getDefaultCacheResolver( File root);\n}\n"}}, {"InstallationException": {"retrieved_name": "InstallationException", "raw_body": "public final class InstallationException extends FrontendException {\n InstallationException( String message);\n InstallationException( String message, Throwable cause);\n}\n", "raw_body_no_cmt": "public final class InstallationException extends FrontendException {\n InstallationException( String message);\n InstallationException( String message, Throwable cause);\n}\n"}}, {"NodeInstaller": {"retrieved_name": "NodeInstaller", "raw_body": "public class NodeInstaller {\n public static final String INSTALL_PATH=\"/node\";\n private static final Object LOCK=new Object();\n private String npmVersion, nodeVersion, nodeDownloadRoot, userName, password;\n private final Logger logger;\n private final InstallConfig config;\n private final ArchiveExtractor archiveExtractor;\n private final FileDownloader fileDownloader;\n NodeInstaller( InstallConfig config, ArchiveExtractor archiveExtractor, FileDownloader fileDownloader);\n public NodeInstaller setNodeVersion( String nodeVersion);\n public NodeInstaller setNodeDownloadRoot( String nodeDownloadRoot);\n public NodeInstaller setNpmVersion( String npmVersion);\n public NodeInstaller setUserName( String userName);\n public NodeInstaller setPassword( String password);\n private boolean npmProvided() throws InstallationException;\n public void install() throws InstallationException;\n private boolean nodeIsAlreadyInstalled();\n private void installNodeDefault() throws InstallationException;\n private void installNodeWithNpmForWindows() throws InstallationException;\n private void installNodeForWindows() throws InstallationException;\n private File getTempDirectory();\n private File getInstallDirectory();\n private void deleteTempDirectory( File tmpDirectory) throws IOException;\n private void extractFile( File archive, File destinationDirectory) throws ArchiveExtractionException;\n private void downloadFileIfMissing( String downloadUrl, File destination, String userName, String password) throws DownloadException;\n private void downloadFile( String downloadUrl, File destination, String userName, String password) throws DownloadException;\n}\n", "raw_body_no_cmt": "public class NodeInstaller {\n public static final String INSTALL_PATH=\"/node\";\n private static final Object LOCK=new Object();\n private String npmVersion, nodeVersion, nodeDownloadRoot, userName, password;\n private final Logger logger;\n private final InstallConfig config;\n private final ArchiveExtractor archiveExtractor;\n private final FileDownloader fileDownloader;\n NodeInstaller( InstallConfig config, ArchiveExtractor archiveExtractor, FileDownloader fileDownloader);\n public NodeInstaller setNodeVersion( String nodeVersion);\n public NodeInstaller setNodeDownloadRoot( String nodeDownloadRoot);\n public NodeInstaller setNpmVersion( String npmVersion);\n public NodeInstaller setUserName( String userName);\n public NodeInstaller setPassword( String password);\n private boolean npmProvided() throws InstallationException;\n public void install() throws InstallationException;\n private boolean nodeIsAlreadyInstalled();\n private void installNodeDefault() throws InstallationException;\n private void installNodeWithNpmForWindows() throws InstallationException;\n private void installNodeForWindows() throws InstallationException;\n private File getTempDirectory();\n private File getInstallDirectory();\n private void deleteTempDirectory( File tmpDirectory) throws IOException;\n private void extractFile( File archive, File destinationDirectory) throws ArchiveExtractionException;\n private void downloadFileIfMissing( String downloadUrl, File destination, String userName, String password) throws DownloadException;\n private void downloadFile( String downloadUrl, File destination, String userName, String password) throws DownloadException;\n}\n"}}, {"YarnInstaller": {"retrieved_name": "YarnInstaller", "raw_body": "public class YarnInstaller {\n public static final String INSTALL_PATH=\"/node/yarn\";\n public static final String DEFAULT_YARN_DOWNLOAD_ROOT=\"https://github.com/yarnpkg/yarn/releases/download/\";\n private static final Object LOCK=new Object();\n private static final String YARN_ROOT_DIRECTORY=\"dist\";\n private String yarnVersion, yarnDownloadRoot, userName, password;\n private boolean isYarnBerry;\n private final Logger logger;\n private final InstallConfig config;\n private final ArchiveExtractor archiveExtractor;\n private final FileDownloader fileDownloader;\n YarnInstaller( InstallConfig config, ArchiveExtractor archiveExtractor, FileDownloader fileDownloader);\n public YarnInstaller setYarnVersion( String yarnVersion);\n public YarnInstaller setIsYarnBerry( boolean isYarnBerry);\n public YarnInstaller setYarnDownloadRoot( String yarnDownloadRoot);\n public YarnInstaller setUserName( String userName);\n public YarnInstaller setPassword( String password);\n public void install() throws InstallationException;\n private boolean yarnIsAlreadyInstalled();\n private void installYarn() throws InstallationException;\n private File getInstallDirectory();\n private void extractFile( File archive, File destinationDirectory) throws ArchiveExtractionException;\n private void ensureCorrectYarnRootDirectory( File installDirectory, String yarnVersion) throws IOException;\n private void downloadFileIfMissing( String downloadUrl, File destination, String userName, String password) throws DownloadException;\n private void downloadFile( String downloadUrl, File destination, String userName, String password) throws DownloadException;\n}\n", "raw_body_no_cmt": "public class YarnInstaller {\n public static final String INSTALL_PATH=\"/node/yarn\";\n public static final String DEFAULT_YARN_DOWNLOAD_ROOT=\"https://github.com/yarnpkg/yarn/releases/download/\";\n private static final Object LOCK=new Object();\n private static final String YARN_ROOT_DIRECTORY=\"dist\";\n private String yarnVersion, yarnDownloadRoot, userName, password;\n private boolean isYarnBerry;\n private final Logger logger;\n private final InstallConfig config;\n private final ArchiveExtractor archiveExtractor;\n private final FileDownloader fileDownloader;\n YarnInstaller( InstallConfig config, ArchiveExtractor archiveExtractor, FileDownloader fileDownloader);\n public YarnInstaller setYarnVersion( String yarnVersion);\n public YarnInstaller setIsYarnBerry( boolean isYarnBerry);\n public YarnInstaller setYarnDownloadRoot( String yarnDownloadRoot);\n public YarnInstaller setUserName( String userName);\n public YarnInstaller setPassword( String password);\n public void install() throws InstallationException;\n private boolean yarnIsAlreadyInstalled();\n private void installYarn() throws InstallationException;\n private File getInstallDirectory();\n private void extractFile( File archive, File destinationDirectory) throws ArchiveExtractionException;\n private void ensureCorrectYarnRootDirectory( File installDirectory, String yarnVersion) throws IOException;\n private void downloadFileIfMissing( String downloadUrl, File destination, String userName, String password) throws DownloadException;\n private void downloadFile( String downloadUrl, File destination, String userName, String password) throws DownloadException;\n}\n"}}] | [{"createNodeInstaller": {"retrieved_name": "NodeInstaller", "raw_body": "NodeInstaller(InstallConfig config,ArchiveExtractor archiveExtractor,FileDownloader fileDownloader){\n this.logger=LoggerFactory.getLogger(getClass());\n this.config=config;\n this.archiveExtractor=archiveExtractor;\n this.fileDownloader=fileDownloader;\n}\n"}}, {"info": {"retrieved_name": "download", "raw_body": "void download(String downloadUrl,String destination,String userName,String password) throws DownloadException ;\n"}}, {"install": {"retrieved_name": "install", "raw_body": "public void install() throws InstallationException {\nsynchronized (LOCK) {\n if (!bunIsAlreadyInstalled()) {\n if (!this.bunVersion.startsWith(\"v\")) {\n this.logger.warn(\"Bun version does not start with naming convention 'v'.\");\n }\n if (this.config.getPlatform().isWindows()) {\n throw new InstallationException(\"Unable to install bun on windows!\");\n }\n else {\n installBunDefault();\n }\n }\n }\n}\n"}}, {"createYarnInstaller": {"retrieved_name": "getYarnInstaller", "raw_body": "public YarnInstaller getYarnInstaller(ProxyConfig proxy){\n return new YarnInstaller(getInstallConfig(),new DefaultArchiveExtractor(),new DefaultFileDownloader(proxy));\n}\n"}}] | [{"execute": {"retrieved_name": "execute", "raw_body": "public final void execute(String args,Map<String,String> environment) throws TaskRunnerException {\n final List<String> arguments=getArguments(args);\n logger.info(\"Running \" + taskToString(taskName,arguments) + \" in \"+ config.getWorkingDirectory());\n try {\n final int result=new BunExecutor(config,arguments,environment).executeAndRedirectOutput(logger);\n if (result != 0) {\n throw new TaskRunnerException(taskToString(taskName,arguments) + \" failed. (error code \" + result+ \")\");\n }\n }\n catch ( ProcessExecutionException e) {\n throw new TaskRunnerException(taskToString(taskName,arguments) + \" failed.\",e);\n }\n}\n"}}] |
YunaiV_ruoyi-vue-pro | ruoyi-vue-pro/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/mail/MailLogServiceImpl.java | MailLogServiceImpl | updateMailSendResult | class MailLogServiceImpl implements MailLogService {
@Resource
private MailLogMapper mailLogMapper;
@Override
public PageResult<MailLogDO> getMailLogPage(MailLogPageReqVO pageVO) {
return mailLogMapper.selectPage(pageVO);
}
@Override
public MailLogDO getMailLog(Long id) {
return mailLogMapper.selectById(id);
}
@Override
public Long createMailLog(Long userId, Integer userType, String toMail,
MailAccountDO account, MailTemplateDO template,
String templateContent, Map<String, Object> templateParams, Boolean isSend) {
MailLogDO.MailLogDOBuilder logDOBuilder = MailLogDO.builder();
// 根据是否要发送,设置状态
logDOBuilder.sendStatus(Objects.equals(isSend, true) ? MailSendStatusEnum.INIT.getStatus()
: MailSendStatusEnum.IGNORE.getStatus())
// 用户信息
.userId(userId).userType(userType).toMail(toMail)
.accountId(account.getId()).fromMail(account.getMail())
// 模板相关字段
.templateId(template.getId()).templateCode(template.getCode()).templateNickname(template.getNickname())
.templateTitle(template.getTitle()).templateContent(templateContent).templateParams(templateParams);
// 插入数据库
MailLogDO logDO = logDOBuilder.build();
mailLogMapper.insert(logDO);
return logDO.getId();
}
@Override
public void updateMailSendResult(Long logId, String messageId, Exception exception) {<FILL_FUNCTION_BODY>}
} |
// 1. 成功
if (exception == null) {
mailLogMapper.updateById(new MailLogDO().setId(logId).setSendTime(LocalDateTime.now())
.setSendStatus(MailSendStatusEnum.SUCCESS.getStatus()).setSendMessageId(messageId));
return;
}
// 2. 失败
mailLogMapper.updateById(new MailLogDO().setId(logId).setSendTime(LocalDateTime.now())
.setSendStatus(MailSendStatusEnum.FAILURE.getStatus()).setSendException(getRootCauseMessage(exception)));
|
MailLogDO logDO = mailLogMapper.selectById(logId);
if (logDO == null) {
throw new ServiceException(ResultCode.DATA_NOT_EXIST);
}
// 设置发送状态
logDO.setSendStatus(Objects.isNull(exception) ? MailSendStatusEnum.SUCCESS.getStatus()
: MailSendStatusEnum.FAIL.getStatus());
// 设置发送结果
logDO.setSendResult(Objects.isNull(exception) ? messageId : exception.getMessage());
// 更新数据库
mailLogMapper.updateById(logDO);
| [
"MailLogDO",
"Exception",
"MailLogMapper"
] | [
"setSendStatus",
"getMessage",
"isNull",
"getStatus",
"selectById",
"updateById",
"setSendResult"
] | [
"Exception",
"MailLogMapper"
] | [
"setSendStatus",
"now",
"setSendTime",
"setId",
"setSendException",
"setSendMessageId",
"getStatus",
"updateById"
] | {
"methods": [
"setSendStatus",
"getMessage",
"isNull",
"getStatus",
"selectById",
"updateById",
"setSendResult"
],
"similar_methods": [
"updateMailSendResult"
],
"types": [
"MailLogDO",
"Exception",
"MailLogMapper"
]
} | /**
* 邮箱日志 DO 记录每一次邮件的发送
* @author wangjingyi
* @since 2022-03-21
*/
@TableName(value="system_mail_log",autoResultMap=true) @Data @EqualsAndHashCode(callSuper=true) @ToString(callSuper=true) @Builder @AllArgsConstructor @NoArgsConstructor public class MailLogDO extends BaseDO implements Serializable {
/**
* 日志编号,自增
*/
private Long id;
/**
* 用户编码
*/
private Long userId;
/**
* 用户类型 枚举 {@link UserTypeEnum}
*/
private Integer userType;
/**
* 接收邮箱地址
*/
private String toMail;
/**
* 邮箱账号编号 关联 {@link MailAccountDO#getId()}
*/
private Long accountId;
/**
* 发送邮箱地址 冗余 {@link MailAccountDO#getMail()}
*/
private String fromMail;
/**
* 模版编号 关联 {@link MailTemplateDO#getId()}
*/
private Long templateId;
/**
* 模版编码 冗余 {@link MailTemplateDO#getCode()}
*/
private String templateCode;
/**
* 模版发送人名称 冗余 {@link MailTemplateDO#getNickname()}
*/
private String templateNickname;
/**
* 模版标题
*/
private String templateTitle;
/**
* 模版内容 基于 {@link MailTemplateDO#getContent()} 格式化后的内容
*/
private String templateContent;
/**
* 模版参数 基于 {@link MailTemplateDO#getParams()} 输入后的参数
*/
@TableField(typeHandler=JacksonTypeHandler.class) private Map<String,Object> templateParams;
/**
* 发送状态 枚举 {@link MailSendStatusEnum}
*/
private Integer sendStatus;
/**
* 发送时间
*/
private LocalDateTime sendTime;
/**
* 发送返回的消息 ID
*/
private String sendMessageId;
/**
* 发送异常
*/
private String sendException;
}
/**
* 业务逻辑异常 Exception
*/
@Data @EqualsAndHashCode(callSuper=true) public final class ServiceException extends RuntimeException {
/**
* 业务错误码
* @see ServiceErrorCodeRange
*/
private Integer code;
/**
* 错误提示
*/
private String message;
/**
* 空构造方法,避免反序列化问题
*/
public ServiceException();
public ServiceException( ErrorCode errorCode);
public ServiceException( Integer code, String message);
public Integer getCode();
public ServiceException setCode( Integer code);
@Override public String getMessage();
public ServiceException setMessage( String message);
}
@Mapper public interface MailLogMapper extends BaseMapperX<MailLogDO> {
default PageResult<MailLogDO> selectPage( MailLogPageReqVO reqVO);
}
public ServerException setMessage(String message){
this.message=message;
return this;
}
@Override public String getMessage(){
return message;
}
@SafeVarargs public static <T>T defaultIfNull(T... array){
for ( T item : array) {
if (item != null) {
return item;
}
}
return null;
}
@Override public CrmBusinessStatusDO getBusinessStatus(Long id){
return businessStatusMapper.selectById(id);
}
default CartDO selectById(Long id,Long userId){
return selectOne(CartDO::getId,id,CartDO::getUserId,userId);
}
default void updateByIds(Collection<Long> ids,Long userId,CartDO updateObj){
update(updateObj,new LambdaQueryWrapper<CartDO>().in(CartDO::getId,ids).eq(CartDO::getUserId,userId));
}
public static void setCommonResult(ServletRequest request,CommonResult<?> result){
request.setAttribute(REQUEST_ATTRIBUTE_COMMON_RESULT,result);
}
/**
* 更新邮件发送结果
* @param logId 日志编号
* @param messageId 发送后的消息编号
* @param exception 发送异常
*/
void updateMailSendResult(Long logId,String messageId,Exception exception);
| public class MailLogDO extends BaseDO implements Serializable {
private Long id;
private Long userId;
private Integer userType;
private String toMail;
private Long accountId;
private String fromMail;
private Long templateId;
private String templateCode;
private String templateNickname;
private String templateTitle;
private String templateContent;
private Map<String,Object> templateParams;
private Integer sendStatus;
private LocalDateTime sendTime;
private String sendMessageId;
private String sendException;
}
public final class ServiceException extends RuntimeException {
private Integer code;
private String message;
public ServiceException();
public ServiceException( ErrorCode errorCode);
public ServiceException( Integer code, String message);
public Integer getCode();
public ServiceException setCode( Integer code);
public String getMessage();
public ServiceException setMessage( String message);
}
public interface MailLogMapper extends BaseMapperX<MailLogDO> {
default PageResult<MailLogDO> selectPage( MailLogPageReqVO reqVO);
}
public ServerException setMessage(String message){
this.message=message;
return this;
}
@Override public String getMessage(){
return message;
}
@SafeVarargs public static <T>T defaultIfNull(T... array){
for ( T item : array) {
if (item != null) {
return item;
}
}
return null;
}
@Override public CrmBusinessStatusDO getBusinessStatus(Long id){
return businessStatusMapper.selectById(id);
}
default CartDO selectById(Long id,Long userId){
return selectOne(CartDO::getId,id,CartDO::getUserId,userId);
}
default void updateByIds(Collection<Long> ids,Long userId,CartDO updateObj){
update(updateObj,new LambdaQueryWrapper<CartDO>().in(CartDO::getId,ids).eq(CartDO::getUserId,userId));
}
public static void setCommonResult(ServletRequest request,CommonResult<?> result){
request.setAttribute(REQUEST_ATTRIBUTE_COMMON_RESULT,result);
}
/**
* 更新邮件发送结果
* @param logId 日志编号
* @param messageId 发送后的消息编号
* @param exception 发送异常
*/
void updateMailSendResult(Long logId,String messageId,Exception exception);
| {"types": [{"MailLogDO": "MailLogDO"}, {"Exception": "ServiceException"}, {"MailLogMapper": "MailLogMapper"}], "methods": [{"setSendStatus": "setMessage"}, {"getMessage": "getMessage"}, {"isNull": "defaultIfNull"}, {"getStatus": "getBusinessStatus"}, {"selectById": "selectById"}, {"updateById": "updateByIds"}, {"setSendResult": "setCommonResult"}], "similar_methods": [{"updateMailSendResult": "updateMailSendResult"}]} | [{"MailLogDO": {"retrieved_name": "MailLogDO", "raw_body": "/** \n * \u90ae\u7bb1\u65e5\u5fd7 DO \u8bb0\u5f55\u6bcf\u4e00\u6b21\u90ae\u4ef6\u7684\u53d1\u9001\n * @author wangjingyi\n * @since 2022-03-21\n */\n@TableName(value=\"system_mail_log\",autoResultMap=true) @Data @EqualsAndHashCode(callSuper=true) @ToString(callSuper=true) @Builder @AllArgsConstructor @NoArgsConstructor public class MailLogDO extends BaseDO implements Serializable {\n /** \n * \u65e5\u5fd7\u7f16\u53f7\uff0c\u81ea\u589e\n */\n private Long id;\n /** \n * \u7528\u6237\u7f16\u7801\n */\n private Long userId;\n /** \n * \u7528\u6237\u7c7b\u578b \u679a\u4e3e {@link UserTypeEnum}\n */\n private Integer userType;\n /** \n * \u63a5\u6536\u90ae\u7bb1\u5730\u5740\n */\n private String toMail;\n /** \n * \u90ae\u7bb1\u8d26\u53f7\u7f16\u53f7 \u5173\u8054 {@link MailAccountDO#getId()}\n */\n private Long accountId;\n /** \n * \u53d1\u9001\u90ae\u7bb1\u5730\u5740 \u5197\u4f59 {@link MailAccountDO#getMail()}\n */\n private String fromMail;\n /** \n * \u6a21\u7248\u7f16\u53f7 \u5173\u8054 {@link MailTemplateDO#getId()}\n */\n private Long templateId;\n /** \n * \u6a21\u7248\u7f16\u7801 \u5197\u4f59 {@link MailTemplateDO#getCode()}\n */\n private String templateCode;\n /** \n * \u6a21\u7248\u53d1\u9001\u4eba\u540d\u79f0 \u5197\u4f59 {@link MailTemplateDO#getNickname()}\n */\n private String templateNickname;\n /** \n * \u6a21\u7248\u6807\u9898\n */\n private String templateTitle;\n /** \n * \u6a21\u7248\u5185\u5bb9 \u57fa\u4e8e {@link MailTemplateDO#getContent()} \u683c\u5f0f\u5316\u540e\u7684\u5185\u5bb9\n */\n private String templateContent;\n /** \n * \u6a21\u7248\u53c2\u6570 \u57fa\u4e8e {@link MailTemplateDO#getParams()} \u8f93\u5165\u540e\u7684\u53c2\u6570\n */\n @TableField(typeHandler=JacksonTypeHandler.class) private Map<String,Object> templateParams;\n /** \n * \u53d1\u9001\u72b6\u6001 \u679a\u4e3e {@link MailSendStatusEnum}\n */\n private Integer sendStatus;\n /** \n * \u53d1\u9001\u65f6\u95f4\n */\n private LocalDateTime sendTime;\n /** \n * \u53d1\u9001\u8fd4\u56de\u7684\u6d88\u606f ID\n */\n private String sendMessageId;\n /** \n * \u53d1\u9001\u5f02\u5e38\n */\n private String sendException;\n}\n", "raw_body_no_cmt": "public class MailLogDO extends BaseDO implements Serializable {\n private Long id;\n private Long userId;\n private Integer userType;\n private String toMail;\n private Long accountId;\n private String fromMail;\n private Long templateId;\n private String templateCode;\n private String templateNickname;\n private String templateTitle;\n private String templateContent;\n private Map<String,Object> templateParams;\n private Integer sendStatus;\n private LocalDateTime sendTime;\n private String sendMessageId;\n private String sendException;\n}\n"}}, {"Exception": {"retrieved_name": "ServiceException", "raw_body": "/** \n * \u4e1a\u52a1\u903b\u8f91\u5f02\u5e38 Exception\n */\n@Data @EqualsAndHashCode(callSuper=true) public final class ServiceException extends RuntimeException {\n /** \n * \u4e1a\u52a1\u9519\u8bef\u7801\n * @see ServiceErrorCodeRange\n */\n private Integer code;\n /** \n * \u9519\u8bef\u63d0\u793a\n */\n private String message;\n /** \n * \u7a7a\u6784\u9020\u65b9\u6cd5\uff0c\u907f\u514d\u53cd\u5e8f\u5217\u5316\u95ee\u9898\n */\n public ServiceException();\n public ServiceException( ErrorCode errorCode);\n public ServiceException( Integer code, String message);\n public Integer getCode();\n public ServiceException setCode( Integer code);\n @Override public String getMessage();\n public ServiceException setMessage( String message);\n}\n", "raw_body_no_cmt": "public final class ServiceException extends RuntimeException {\n private Integer code;\n private String message;\n public ServiceException();\n public ServiceException( ErrorCode errorCode);\n public ServiceException( Integer code, String message);\n public Integer getCode();\n public ServiceException setCode( Integer code);\n public String getMessage();\n public ServiceException setMessage( String message);\n}\n"}}, {"MailLogMapper": {"retrieved_name": "MailLogMapper", "raw_body": "@Mapper public interface MailLogMapper extends BaseMapperX<MailLogDO> {\n default PageResult<MailLogDO> selectPage( MailLogPageReqVO reqVO);\n}\n", "raw_body_no_cmt": "public interface MailLogMapper extends BaseMapperX<MailLogDO> {\n default PageResult<MailLogDO> selectPage( MailLogPageReqVO reqVO);\n}\n"}}] | [{"setSendStatus": {"retrieved_name": "setMessage", "raw_body": "public ServerException setMessage(String message){\n this.message=message;\n return this;\n}\n"}}, {"getMessage": {"retrieved_name": "getMessage", "raw_body": "@Override public String getMessage(){\n return message;\n}\n"}}, {"isNull": {"retrieved_name": "defaultIfNull", "raw_body": "@SafeVarargs public static <T>T defaultIfNull(T... array){\n for ( T item : array) {\n if (item != null) {\n return item;\n }\n }\n return null;\n}\n"}}, {"getStatus": {"retrieved_name": "getBusinessStatus", "raw_body": "@Override public CrmBusinessStatusDO getBusinessStatus(Long id){\n return businessStatusMapper.selectById(id);\n}\n"}}, {"selectById": {"retrieved_name": "selectById", "raw_body": "default CartDO selectById(Long id,Long userId){\n return selectOne(CartDO::getId,id,CartDO::getUserId,userId);\n}\n"}}, {"updateById": {"retrieved_name": "updateByIds", "raw_body": "default void updateByIds(Collection<Long> ids,Long userId,CartDO updateObj){\n update(updateObj,new LambdaQueryWrapper<CartDO>().in(CartDO::getId,ids).eq(CartDO::getUserId,userId));\n}\n"}}, {"setSendResult": {"retrieved_name": "setCommonResult", "raw_body": "public static void setCommonResult(ServletRequest request,CommonResult<?> result){\n request.setAttribute(REQUEST_ATTRIBUTE_COMMON_RESULT,result);\n}\n"}}] | [{"updateMailSendResult": {"retrieved_name": "updateMailSendResult", "raw_body": "/** \n * \u66f4\u65b0\u90ae\u4ef6\u53d1\u9001\u7ed3\u679c\n * @param logId \u65e5\u5fd7\u7f16\u53f7\n * @param messageId \u53d1\u9001\u540e\u7684\u6d88\u606f\u7f16\u53f7\n * @param exception \u53d1\u9001\u5f02\u5e38\n */\nvoid updateMailSendResult(Long logId,String messageId,Exception exception);\n"}}] |
|
mapstruct_mapstruct | mapstruct/processor/src/main/java/org/mapstruct/ap/spi/ImmutablesAccessorNamingStrategy.java | ImmutablesAccessorNamingStrategy | isFluentSetter | class ImmutablesAccessorNamingStrategy extends DefaultAccessorNamingStrategy {
@Override
protected boolean isFluentSetter(ExecutableElement method) {<FILL_FUNCTION_BODY>}
private boolean isPutterWithUpperCase4thCharacter(ExecutableElement method) {
return isPutterMethod( method ) && Character.isUpperCase( method.getSimpleName().toString().charAt( 3 ) );
}
public boolean isPutterMethod(ExecutableElement method) {
String methodName = method.getSimpleName().toString();
return methodName.startsWith( "put" ) && methodName.length() > 3;
}
} |
return super.isFluentSetter( method ) &&
!method.getSimpleName().toString().equals( "from" ) &&
!isPutterWithUpperCase4thCharacter( method );
| /**
* The default JavaBeans-compliant implementation of the {@link AccessorNamingStrategy} service provider interface.
* @author Christian Schuster, Sjaak Derken
*/
public class DefaultAccessorNamingStrategy implements AccessorNamingStrategy {
private static final Pattern JAVA_JAVAX_PACKAGE=Pattern.compile("^javax?\\..*");
protected Elements elementUtils;
protected Types typeUtils;
@Override public void init( MapStructProcessingEnvironment processingEnvironment);
@Override public MethodType getMethodType( ExecutableElement method);
/**
* Returns {@code true} when the {@link ExecutableElement} is a getter method. A method is a getter when ithas no parameters, starts with 'get' and the return type is any type other than {@code void}, OR the getter starts with 'is' and the type returned is a primitive or the wrapper for {@code boolean}. NOTE: the latter does strictly not comply to the bean convention. The remainder of the name is supposed to reflect the property name. <p> The calling MapStruct code guarantees that the given method has no arguments.
* @param method to be analyzed
* @return {@code true} when the method is a getter.
*/
public boolean isGetterMethod( ExecutableElement method);
/**
* Returns {@code true} when the {@link ExecutableElement} is a setter method. A setter starts with 'set'. Theremainder of the name is supposed to reflect the property name. <p> The calling MapStruct code guarantees that there's only one argument.
* @param method to be analyzed
* @return {@code true} when the method is a setter.
*/
public boolean isSetterMethod( ExecutableElement method);
protected boolean isFluentSetter( ExecutableElement method);
/**
* Checks that the method is an adder with an upper case 4th character. The reason for this is that methods such as {@code address(String address)} are considered as setter and {@code addName(String name)} too. We need tomake sure that {@code addName} is considered as an adder and {@code address} is considered as a setter.
* @param method the method that needs to be checked
* @return {@code true} if the method is an adder with an upper case 4h character, {@code false} otherwise
*/
private boolean isAdderWithUpperCase4thCharacter( ExecutableElement method);
/**
* Returns {@code true} when the {@link ExecutableElement} is an adder method. An adder method starts with 'add'.The remainder of the name is supposed to reflect the <em>singular</em> property name (as opposed to plural) of its corresponding property. For example: property "children", but "addChild". See also {@link #getElementName(ExecutableElement) }. <p> The calling MapStruct code guarantees there's only one argument. <p>
* @param method to be analyzed
* @return {@code true} when the method is an adder method.
*/
public boolean isAdderMethod( ExecutableElement method);
/**
* Returns {@code true} when the {@link ExecutableElement} is a <em>presence check</em> method that checks if thecorresponding property is present (e.g. not null, not nil, ..). A presence check method method starts with 'has'. The remainder of the name is supposed to reflect the property name. <p> The calling MapStruct code guarantees there's no argument and that the return type is boolean or a {@link Boolean}
* @param method to be analyzed
* @return {@code true} when the method is a presence check method.
*/
public boolean isPresenceCheckMethod( ExecutableElement method);
/**
* Analyzes the method (getter or setter) and derives the property name. See {@link #isGetterMethod(ExecutableElement)} {@link #isSetterMethod(ExecutableElement)}. The first three ('get' / 'set' scenario) characters are removed from the simple name, or the first 2 characters ('is' scenario). From the remainder the first character is made into small case (to counter camel casing) and the result forms the property name.
* @param getterOrSetterMethod getter or setter method.
* @return the property name.
*/
@Override public String getPropertyName( ExecutableElement getterOrSetterMethod);
/**
* Adder methods are used to add elements to collections on a target bean. A typical use case is JPA. The convention is that the element name will be equal to the remainder of the add method. Example: 'addElement' element name will be 'element'.
* @param adderMethod getter or setter method.
* @return the property name.
*/
@Override public String getElementName( ExecutableElement adderMethod);
/**
* Helper method, to obtain the fully qualified name of a type.
* @param type input type
* @return fully qualified name of type when the type is a {@link DeclaredType}, null when otherwise.
*/
protected static String getQualifiedName( TypeMirror type);
@Override public String getCollectionGetterName( String property);
}
|
return isSetterMethod( method ) && Character.isUpperCase( method.getSimpleName().toString().charAt( 3 ) );
| [
"ExecutableElement"
] | [
"toString",
"getSimpleName",
"isUpperCase",
"charAt"
] | [
"ExecutableElement"
] | [
"equals",
"toString",
"getSimpleName"
] | {
"methods": [
"toString",
"getSimpleName",
"isUpperCase",
"charAt"
],
"similar_methods": [
"isFluentSetter"
],
"types": [
"ExecutableElement"
]
} | /**
* An {@link Accessor} that wraps an {@link ExecutableElement}.
* @author Filip Hrisafov
*/
public class ExecutableElementAccessor extends AbstractAccessor<ExecutableElement> {
private final TypeMirror accessedType;
private final AccessorType accessorType;
public ExecutableElementAccessor( ExecutableElement element, TypeMirror accessedType, AccessorType accessorType);
@Override public TypeMirror getAccessedType();
@Override public String toString();
@Override public AccessorType getAccessorType();
}
@Override public String toString(){
return "CarDto{" + "name='" + name + '\''+ ", year="+ year+ ", wheels="+ wheels+ '}';
}
/**
* @return the simple name of the accessor
*/
String getSimpleName();
private static String upperCaseFirst(String value){
char[] array=value.toCharArray();
array[0]=Character.toUpperCase(array[0]);
for (int i=1; i < array.length; i++) {
array[i]=Character.toLowerCase(array[i]);
}
return new String(array);
}
/**
* accessor
* @return the {@link GemValue} for {@link ElementGem#chars}
*/
public GemValue<List<Character>> chars(){
return chars;
}
@Override protected boolean isFluentSetter(ExecutableElement method){
return false;
}
| public class ExecutableElementAccessor extends AbstractAccessor<ExecutableElement> {
private final TypeMirror accessedType;
private final AccessorType accessorType;
public ExecutableElementAccessor( ExecutableElement element, TypeMirror accessedType, AccessorType accessorType);
public TypeMirror getAccessedType();
public String toString();
public AccessorType getAccessorType();
}
@Override public String toString(){
return "CarDto{" + "name='" + name + '\''+ ", year="+ year+ ", wheels="+ wheels+ '}';
}
/**
* @return the simple name of the accessor
*/
String getSimpleName();
private static String upperCaseFirst(String value){
char[] array=value.toCharArray();
array[0]=Character.toUpperCase(array[0]);
for (int i=1; i < array.length; i++) {
array[i]=Character.toLowerCase(array[i]);
}
return new String(array);
}
/**
* accessor
* @return the {@link GemValue} for {@link ElementGem#chars}
*/
public GemValue<List<Character>> chars(){
return chars;
}
@Override protected boolean isFluentSetter(ExecutableElement method){
return false;
}
| {"types": [{"ExecutableElement": "ExecutableElementAccessor"}], "methods": [{"toString": "toString"}, {"getSimpleName": "getSimpleName"}, {"isUpperCase": "upperCaseFirst"}, {"charAt": "chars"}], "similar_methods": [{"isFluentSetter": "isFluentSetter"}]} | [{"ExecutableElement": {"retrieved_name": "ExecutableElementAccessor", "raw_body": "/** \n * An {@link Accessor} that wraps an {@link ExecutableElement}.\n * @author Filip Hrisafov\n */\npublic class ExecutableElementAccessor extends AbstractAccessor<ExecutableElement> {\n private final TypeMirror accessedType;\n private final AccessorType accessorType;\n public ExecutableElementAccessor( ExecutableElement element, TypeMirror accessedType, AccessorType accessorType);\n @Override public TypeMirror getAccessedType();\n @Override public String toString();\n @Override public AccessorType getAccessorType();\n}\n", "raw_body_no_cmt": "public class ExecutableElementAccessor extends AbstractAccessor<ExecutableElement> {\n private final TypeMirror accessedType;\n private final AccessorType accessorType;\n public ExecutableElementAccessor( ExecutableElement element, TypeMirror accessedType, AccessorType accessorType);\n public TypeMirror getAccessedType();\n public String toString();\n public AccessorType getAccessorType();\n}\n"}}] | [{"toString": {"retrieved_name": "toString", "raw_body": "@Override public String toString(){\n return \"CarDto{\" + \"name='\" + name + '\\''+ \", year=\"+ year+ \", wheels=\"+ wheels+ '}';\n}\n"}}, {"getSimpleName": {"retrieved_name": "getSimpleName", "raw_body": "/** \n * @return the simple name of the accessor\n */\nString getSimpleName();\n"}}, {"isUpperCase": {"retrieved_name": "upperCaseFirst", "raw_body": "private static String upperCaseFirst(String value){\n char[] array=value.toCharArray();\n array[0]=Character.toUpperCase(array[0]);\n for (int i=1; i < array.length; i++) {\n array[i]=Character.toLowerCase(array[i]);\n }\n return new String(array);\n}\n"}}, {"charAt": {"retrieved_name": "chars", "raw_body": "/** \n * accessor\n * @return the {@link GemValue} for {@link ElementGem#chars}\n */\npublic GemValue<List<Character>> chars(){\n return chars;\n}\n"}}] | [{"isFluentSetter": {"retrieved_name": "isFluentSetter", "raw_body": "@Override protected boolean isFluentSetter(ExecutableElement method){\n return false;\n}\n"}}] |
docker-java_docker-java | docker-java/docker-java-core/src/main/java/com/github/dockerjava/core/exec/VersionCmdExec.java | VersionCmdExec | execute | class VersionCmdExec extends AbstrSyncDockerCmdExec<VersionCmd, Version> implements VersionCmd.Exec {
private static final Logger LOGGER = LoggerFactory.getLogger(VersionCmdExec.class);
public VersionCmdExec(WebTarget baseResource, DockerClientConfig dockerClientConfig) {
super(baseResource, dockerClientConfig);
}
@Override
protected Version execute(VersionCmd command) {<FILL_FUNCTION_BODY>}
} |
WebTarget webResource = getBaseResource().path("/version");
LOGGER.trace("GET: {}", webResource);
return webResource.request().accept(MediaType.APPLICATION_JSON).get(new TypeReference<Version>() {
});
|
return execute(command, Version.class);
| [
"VersionCmd"
] | [] | [
"WebTarget",
"Logger",
"VersionCmd"
] | [
"trace",
"accept",
"get",
"request",
"path"
] | {
"methods": [],
"similar_methods": [
"execute"
],
"types": [
"VersionCmd"
]
} | /**
* Returns the Docker version info.
*/
public interface VersionCmd extends SyncDockerCmd<Version> {
interface Exec extends DockerCmdSyncExec<VersionCmd,Version> {
}
}
@Override public Response execute(Request request){
return new TrackedResponse(delegate.execute(request)){
{
synchronized (ACTIVE_RESPONSES) {
ACTIVE_RESPONSES.add(this);
}
}
@Override public void close(){
synchronized (ACTIVE_RESPONSES) {
ACTIVE_RESPONSES.remove(this);
}
super.close();
}
}
;
}
| public interface VersionCmd extends SyncDockerCmd<Version> {
interface Exec extends DockerCmdSyncExec<VersionCmd,Version> {
}
}
@Override public Response execute(Request request){
return new TrackedResponse(delegate.execute(request)){
{
synchronized (ACTIVE_RESPONSES) {
ACTIVE_RESPONSES.add(this);
}
}
@Override public void close(){
synchronized (ACTIVE_RESPONSES) {
ACTIVE_RESPONSES.remove(this);
}
super.close();
}
}
;
}
| {"types": [{"VersionCmd": "VersionCmd"}], "similar_methods": [{"execute": "execute"}]} | [{"VersionCmd": {"retrieved_name": "VersionCmd", "raw_body": "/** \n * Returns the Docker version info.\n */\npublic interface VersionCmd extends SyncDockerCmd<Version> {\ninterface Exec extends DockerCmdSyncExec<VersionCmd,Version> {\n }\n}\n", "raw_body_no_cmt": "public interface VersionCmd extends SyncDockerCmd<Version> {\ninterface Exec extends DockerCmdSyncExec<VersionCmd,Version> {\n }\n}\n"}}] | [] | [{"execute": {"retrieved_name": "execute", "raw_body": "@Override public Response execute(Request request){\n return new TrackedResponse(delegate.execute(request)){\n{\nsynchronized (ACTIVE_RESPONSES) {\n ACTIVE_RESPONSES.add(this);\n }\n }\n @Override public void close(){\nsynchronized (ACTIVE_RESPONSES) {\n ACTIVE_RESPONSES.remove(this);\n }\n super.close();\n }\n }\n;\n}\n"}}] |