proj_name
stringclasses
26 values
relative_path
stringlengths
42
165
class_name
stringlengths
3
46
func_name
stringlengths
2
44
masked_class
stringlengths
80
7.9k
func_body
stringlengths
76
5.98k
len_input
int64
30
1.88k
len_output
int64
25
1.43k
total
int64
73
2.03k
initial_context
stringclasses
74 values
javamelody_javamelody
javamelody/javamelody-core/src/main/java/net/bull/javamelody/SpringDataSourceBeanPostProcessor.java
SpringDataSourceBeanPostProcessor
postProcessAfterInitialization
class SpringDataSourceBeanPostProcessor implements BeanPostProcessor, PriorityOrdered { private Set<String> excludedDatasources; // l'interface PriorityOrdered place la priorité assez haute dans le contexte Spring // quelle que soit la valeur de order private int order = LOWEST_PRECEDENCE; private final Class<?> delegatingDataSourceClass = getDelegatingDataSourceClass(); /** * Définit les noms des datasources Spring exclues. * @param excludedDatasources Set */ public void setExcludedDatasources(Set<String> excludedDatasources) { this.excludedDatasources = excludedDatasources; // exemple: // <bean id="springDataSourceBeanPostProcessor" class="net.bull.javamelody.SpringDataSourceBeanPostProcessor"> // <property name="excludedDatasources"> // <set> // <value>excludedDataSourceName</value> // </set> // </property> // </bean> } /** {@inheritDoc} */ @Override public int getOrder() { return order; } /** * Définit la priorité dans le contexte Spring. * @param order int */ public void setOrder(int order) { this.order = order; } /** {@inheritDoc} */ @Override public Object postProcessBeforeInitialization(Object bean, String beanName) { return bean; } private boolean isExcludedDataSource(String beanName) { if (excludedDatasources != null && excludedDatasources.contains(beanName)) { LOG.debug("Spring datasource excluded: " + beanName); return true; } return false; } /** {@inheritDoc} */ @Override public Object postProcessAfterInitialization(Object bean, String beanName) {<FILL_FUNCTION_BODY>} private Object createProxy(final Object bean, final String beanName) { final InvocationHandler invocationHandler = new InvocationHandler() { /** {@inheritDoc} */ @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object result = method.invoke(bean, args); if (result instanceof DataSource) { result = JdbcWrapper.SINGLETON.createDataSourceProxy(beanName, (DataSource) result); } return result; } }; return JdbcWrapper.createProxy(bean, invocationHandler); } private boolean isDelegatingDataSourceAndAlreadyProxied(Object bean, String beanName) { // bean instanceof DelegatingDataSource ? // use reflection in case spring-jdbc is not available if (delegatingDataSourceClass != null && delegatingDataSourceClass.isInstance(bean)) { final DataSource targetDataSource; try { targetDataSource = (DataSource) delegatingDataSourceClass .getMethod("getTargetDataSource").invoke(bean); } catch (final Exception e) { // call to ((DelegatingDataSource) bean).getTargetDataSource() is not supposed to fail throw new IllegalStateException(e); } if (JdbcWrapper.isProxyAlready(targetDataSource)) { LOG.debug("Spring delegating datasource excluded: " + beanName); return true; } } return false; } private static Class<?> getDelegatingDataSourceClass() { try { return Class.forName("org.springframework.jdbc.datasource.DelegatingDataSource"); } catch (final ClassNotFoundException e) { return null; } } }
if (bean instanceof DataSource) { // on ne teste isExcludedDataSource que si on est sur une datasource if (isExcludedDataSource(beanName) || Parameters.isNoDatabase() || isDelegatingDataSourceAndAlreadyProxied(bean, beanName)) { return bean; } final DataSource dataSource = (DataSource) bean; JdbcWrapper.registerSpringDataSource(beanName, dataSource); final DataSource result = JdbcWrapper.SINGLETON.createDataSourceProxy(beanName, dataSource); LOG.debug("Spring datasource wrapped: " + beanName); return result; } else if (bean instanceof JndiObjectFactoryBean) { // ou sur un JndiObjectFactoryBean if (isExcludedDataSource(beanName) || Parameters.isNoDatabase()) { return bean; } // fix issue 20 final Object result = createProxy(bean, beanName); LOG.debug("Spring JNDI factory wrapped: " + beanName); return result; } // I tried here in the post-processor to fix "quartz jobs which are scheduled with spring // are not displayed in javamelody, except if there is the following property for // SchedulerFactoryBean in spring xml: // <property name="exposeSchedulerInRepository" value="true" /> ", // but I had some problem with Spring creating the scheduler // twice and so registering the scheduler in SchedulerRepository with the same name // as the one registered below (and Quartz wants not) // else if (bean != null // && "org.springframework.scheduling.quartz.SchedulerFactoryBean".equals(bean // .getClass().getName())) { // try { // // Remarque: on ajoute nous même le scheduler de Spring dans le SchedulerRepository // // de Quartz, car l'appel ici de schedulerFactoryBean.setExposeSchedulerInRepository(true) // // est trop tard et ne fonctionnerait pas // final Method method = bean.getClass().getMethod("getScheduler", (Class<?>[]) null); // final Scheduler scheduler = (Scheduler) method.invoke(bean, (Object[]) null); // // final SchedulerRepository schedulerRepository = SchedulerRepository.getInstance(); // synchronized (schedulerRepository) { // if (schedulerRepository.lookup(scheduler.getSchedulerName()) == null) { // schedulerRepository.bind(scheduler); // scheduler.addGlobalJobListener(new JobGlobalListener()); // } // } // } catch (final NoSuchMethodException e) { // // si la méthode n'existe pas (avant spring 2.5.6), alors cela marche sans rien faire // return bean; // } catch (final InvocationTargetException e) { // // tant pis // return bean; // } catch (final IllegalAccessException e) { // // tant pis // return bean; // } catch (SchedulerException e) { // // tant pis // return bean; // } // } return bean;
1,046
928
1,974
mapstruct_mapstruct
mapstruct/processor/src/main/java/org/mapstruct/ap/spi/StripSuffixEnumTransformationStrategy.java
StripSuffixEnumTransformationStrategy
transform
class StripSuffixEnumTransformationStrategy implements EnumTransformationStrategy { @Override public String getStrategyName() { return "stripSuffix"; } @Override public String transform(String value, String configuration) {<FILL_FUNCTION_BODY>} }
if ( value.endsWith( configuration ) ) { return value.substring( 0, value.length() - configuration.length() ); } return value;
76
45
121
jeecgboot_jeecg-boot
jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/system/util/RandImageUtil.java
RandImageUtil
getRandColor
class RandImageUtil { public static final String KEY = "JEECG_LOGIN_KEY"; /** * 定义图形大小 */ private static final int WIDTH = 105; /** * 定义图形大小 */ private static final int HEIGHT = 35; /** * 定义干扰线数量 */ private static final int COUNT = 200; /** * 干扰线的长度=1.414*lineWidth */ private static final int LINE_WIDTH = 2; /** * 图片格式 */ private static final String IMG_FORMAT = "JPEG"; /** * base64 图片前缀 */ private static final String BASE64_PRE = "data:image/jpg;base64,"; /** * 直接通过response 返回图片 * @param response * @param resultCode * @throws IOException */ public static void generate(HttpServletResponse response, String resultCode) throws IOException { BufferedImage image = getImageBuffer(resultCode); // 输出图象到页面 ImageIO.write(image, IMG_FORMAT, response.getOutputStream()); } /** * 生成base64字符串 * @param resultCode * @return * @throws IOException */ public static String generate(String resultCode) throws IOException { BufferedImage image = getImageBuffer(resultCode); ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); //写入流中 ImageIO.write(image, IMG_FORMAT, byteStream); //转换成字节 byte[] bytes = byteStream.toByteArray(); //转换成base64串 String base64 = Base64.getEncoder().encodeToString(bytes).trim(); //删除 \r\n base64 = base64.replaceAll("\n", "").replaceAll("\r", ""); //写到指定位置 //ImageIO.write(bufferedImage, "png", new File("")); return BASE64_PRE+base64; } private static BufferedImage getImageBuffer(String resultCode){ // 在内存中创建图象 final BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB); // 获取图形上下文 final Graphics2D graphics = (Graphics2D) image.getGraphics(); // 设定背景颜色 // ---1 graphics.setColor(Color.WHITE); graphics.fillRect(0, 0, WIDTH, HEIGHT); // 设定边框颜色 // graphics.setColor(getRandColor(100, 200)); // ---2 graphics.drawRect(0, 0, WIDTH - 1, HEIGHT - 1); // SHA1PRNG是-种常用的随机数生成算法,处理弱随机数问题 SecureRandom random; try { random = SecureRandom.getInstance("SHA1PRNG"); } catch (NoSuchAlgorithmException e) { random = new SecureRandom(); } // 随机产生干扰线,使图象中的认证码不易被其它程序探测到 for (int i = 0; i < COUNT; i++) { // ---3 graphics.setColor(getRandColor(150, 200)); // 保证画在边框之内 final int x = random.nextInt(WIDTH - LINE_WIDTH - 1) + 1; final int y = random.nextInt(HEIGHT - LINE_WIDTH - 1) + 1; final int xl = random.nextInt(LINE_WIDTH); final int yl = random.nextInt(LINE_WIDTH); graphics.drawLine(x, y, x + xl, y + yl); } // 取随机产生的认证码 for (int i = 0; i < resultCode.length(); i++) { // 将认证码显示到图象中,调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成 // graphics.setColor(new Color(20 + random.nextInt(130), 20 + random // .nextInt(130), 20 + random.nextInt(130))); // 设置字体颜色 graphics.setColor(Color.BLACK); // 设置字体样式 // graphics.setFont(new Font("Arial Black", Font.ITALIC, 18)); graphics.setFont(new Font("Times New Roman", Font.BOLD, 24)); // 设置字符,字符间距,上边距 graphics.drawString(String.valueOf(resultCode.charAt(i)), (23 * i) + 8, 26); } // 图象生效 graphics.dispose(); return image; } private static Color getRandColor(int fc, int bc) {<FILL_FUNCTION_BODY>} }
// 取得给定范围随机颜色 final Random random = new Random(); int length = 255; if (fc > length) { fc = length; } if (bc > length) { bc = length; } final int r = fc + random.nextInt(bc - fc); final int g = fc + random.nextInt(bc - fc); final int b = fc + random.nextInt(bc - fc); return new Color(r, g, b);
1,313
139
1,452
houbb_sensitive-word
sensitive-word/src/main/java/com/github/houbb/sensitive/word/support/result/WordTagsDto.java
WordTagsDto
toString
class WordTagsDto implements Serializable { private String word; private Set<String> tags; public String getWord() { return word; } public void setWord(String word) { this.word = word; } public Set<String> getTags() { return tags; } public void setTags(Set<String> tags) { this.tags = tags; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "WordTagsDto{" + "word='" + word + '\'' + ", tags=" + tags + '}';
141
39
180
spring-cloud_spring-cloud-gateway
spring-cloud-gateway/spring-cloud-gateway-server/src/main/java/org/springframework/cloud/gateway/filter/factory/RemoveRequestParameterGatewayFilterFactory.java
RemoveRequestParameterGatewayFilterFactory
apply
class RemoveRequestParameterGatewayFilterFactory extends AbstractGatewayFilterFactory<AbstractGatewayFilterFactory.NameConfig> { public RemoveRequestParameterGatewayFilterFactory() { super(NameConfig.class); } @Override public List<String> shortcutFieldOrder() { return Arrays.asList(NAME_KEY); } @Override public GatewayFilter apply(NameConfig config) {<FILL_FUNCTION_BODY>} }
return new GatewayFilter() { @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { ServerHttpRequest request = exchange.getRequest(); MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<>(request.getQueryParams()); queryParams.remove(config.getName()); URI newUri = UriComponentsBuilder.fromUri(request.getURI()) .replaceQueryParams(unmodifiableMultiValueMap(queryParams)).build().toUri(); ServerHttpRequest updatedRequest = exchange.getRequest().mutate().uri(newUri).build(); return chain.filter(exchange.mutate().request(updatedRequest).build()); } @Override public String toString() { return filterToStringCreator(RemoveRequestParameterGatewayFilterFactory.this) .append("name", config.getName()).toString(); } };
119
236
355
docker-java_docker-java
docker-java/docker-java-core/src/main/java/com/github/dockerjava/core/command/ResizeExecCmdImpl.java
ResizeExecCmdImpl
withExecId
class ResizeExecCmdImpl extends AbstrDockerCmd<ResizeExecCmd, Void> implements ResizeExecCmd { private String execId; private Integer height; private Integer width; public ResizeExecCmdImpl(ResizeExecCmd.Exec exec, String execId) { super(exec); withExecId(execId); } @Override public String getExecId() { return execId; } @Override public Integer getHeight() { return height; } @Override public Integer getWidth() { return width; } @Override public ResizeExecCmd withExecId(String execId) {<FILL_FUNCTION_BODY>} @Override public ResizeExecCmd withSize(int height, int width) { this.height = height; this.width = width; return this; } /** * @throws NotFoundException no such exec instance */ @Override public Void exec() throws NotFoundException { return super.exec(); } }
this.execId = Objects.requireNonNull(execId, "execId was not specified"); return this;
283
32
315
jeecgboot_jeecg-boot
jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/system/service/impl/SysRolePermissionServiceImpl.java
SysRolePermissionServiceImpl
saveRolePermission
class SysRolePermissionServiceImpl extends ServiceImpl<SysRolePermissionMapper, SysRolePermission> implements ISysRolePermissionService { @Override public void saveRolePermission(String roleId, String permissionIds) {<FILL_FUNCTION_BODY>} @Override public void saveRolePermission(String roleId, String permissionIds, String lastPermissionIds) { String ip = ""; try { //获取request HttpServletRequest request = SpringContextUtils.getHttpServletRequest(); //获取IP地址 ip = IpUtils.getIpAddr(request); } catch (Exception e) { ip = "127.0.0.1"; } List<String> add = getDiff(lastPermissionIds,permissionIds); if(add!=null && add.size()>0) { List<SysRolePermission> list = new ArrayList<SysRolePermission>(); for (String p : add) { if(oConvertUtils.isNotEmpty(p)) { SysRolePermission rolepms = new SysRolePermission(roleId, p); rolepms.setOperateDate(new Date()); rolepms.setOperateIp(ip); list.add(rolepms); } } this.saveBatch(list); } List<String> delete = getDiff(permissionIds,lastPermissionIds); if(delete!=null && delete.size()>0) { for (String permissionId : delete) { this.remove(new QueryWrapper<SysRolePermission>().lambda().eq(SysRolePermission::getRoleId, roleId).eq(SysRolePermission::getPermissionId, permissionId)); } } } /** * 从diff中找出main中没有的元素 * @param main * @param diff * @return */ private List<String> getDiff(String main,String diff){ if(oConvertUtils.isEmpty(diff)) { return null; } if(oConvertUtils.isEmpty(main)) { return Arrays.asList(diff.split(",")); } String[] mainArr = main.split(","); String[] diffArr = diff.split(","); Map<String, Integer> map = new HashMap(5); for (String string : mainArr) { map.put(string, 1); } List<String> res = new ArrayList<String>(); for (String key : diffArr) { if(oConvertUtils.isNotEmpty(key) && !map.containsKey(key)) { res.add(key); } } return res; } }
String ip = ""; try { //获取request HttpServletRequest request = SpringContextUtils.getHttpServletRequest(); //获取IP地址 ip = IpUtils.getIpAddr(request); } catch (Exception e) { ip = "127.0.0.1"; } LambdaQueryWrapper<SysRolePermission> query = new QueryWrapper<SysRolePermission>().lambda().eq(SysRolePermission::getRoleId, roleId); this.remove(query); List<SysRolePermission> list = new ArrayList<SysRolePermission>(); String[] arr = permissionIds.split(","); for (String p : arr) { if(oConvertUtils.isNotEmpty(p)) { SysRolePermission rolepms = new SysRolePermission(roleId, p); rolepms.setOperateDate(new Date()); rolepms.setOperateIp(ip); list.add(rolepms); } } this.saveBatch(list);
691
271
962
pmd_pmd
pmd/pmd-core/src/main/java/net/sourceforge/pmd/cache/internal/AnalysisCacheListener.java
AnalysisCacheListener
startFileAnalysis
class AnalysisCacheListener implements GlobalAnalysisListener { private final AnalysisCache cache; public AnalysisCacheListener(AnalysisCache cache, RuleSets ruleSets, ClassLoader classLoader, Collection<? extends TextFile> textFiles) { this.cache = cache; cache.checkValidity(ruleSets, classLoader, textFiles); } @Override public FileAnalysisListener startFileAnalysis(TextFile file) {<FILL_FUNCTION_BODY>} @Override public void close() throws IOException { cache.persist(); } }
// AnalysisCache instances are handled specially in PmdRunnable return FileAnalysisListener.noop();
144
28
172
mapstruct_mapstruct
mapstruct/processor/src/main/java/org/mapstruct/ap/internal/conversion/PrimitiveToStringConversion.java
PrimitiveToStringConversion
getFromExpression
class PrimitiveToStringConversion extends AbstractNumberToStringConversion { private final Class<?> sourceType; private final Class<?> wrapperType; public PrimitiveToStringConversion(Class<?> sourceType) { super( NativeTypes.isNumber( sourceType ) ); if ( !sourceType.isPrimitive() ) { throw new IllegalArgumentException( sourceType + " is no primitive type." ); } this.sourceType = sourceType; this.wrapperType = NativeTypes.getWrapperType( sourceType ); } @Override public String getToExpression(ConversionContext conversionContext) { if ( requiresDecimalFormat( conversionContext ) ) { StringBuilder sb = new StringBuilder(); appendDecimalFormatter( sb, conversionContext ); sb.append( ".format( <SOURCE> )" ); return sb.toString(); } else { return "String.valueOf( <SOURCE> )"; } } @Override public Set<Type> getToConversionImportTypes(ConversionContext conversionContext) { if ( requiresDecimalFormat( conversionContext ) ) { return Collections.singleton( conversionContext.getTypeFactory().getType( DecimalFormat.class ) ); } return Collections.emptySet(); } @Override public String getFromExpression(ConversionContext conversionContext) {<FILL_FUNCTION_BODY>} @Override protected Set<Type> getFromConversionImportTypes(ConversionContext conversionContext) { if ( requiresDecimalFormat( conversionContext ) ) { return Collections.singleton( conversionContext.getTypeFactory().getType( DecimalFormat.class ) ); } return Collections.emptySet(); } private void appendDecimalFormatter(StringBuilder sb, ConversionContext conversionContext) { sb.append( "new " ); sb.append( decimalFormat( conversionContext ) ); sb.append( "( " ); if ( conversionContext.getNumberFormat() != null ) { sb.append( "\"" ); sb.append( conversionContext.getNumberFormat() ); sb.append( "\"" ); } sb.append( " )" ); } }
if ( requiresDecimalFormat( conversionContext ) ) { StringBuilder sb = new StringBuilder(); appendDecimalFormatter( sb, conversionContext ); sb.append( ".parse( <SOURCE> )." ); sb.append( sourceType.getSimpleName() ); sb.append( "Value()" ); return sb.toString(); } else { return wrapperType.getSimpleName() + ".parse" + Strings.capitalize( sourceType.getSimpleName() ) + "( <SOURCE> )"; }
569
138
707
/** * Abstract base class for {@link PrimitiveToStringConversion}, {@link WrapperToStringConversion}, {@link BigDecimalToStringConversion} and {@link BigIntegerToStringConversion}Contains shared utility methods. * @author Ciaran Liedeman */ public abstract class AbstractNumberToStringConversion extends SimpleConversion { private final boolean sourceTypeNumberSubclass; public AbstractNumberToStringConversion( boolean sourceTypeNumberSubclass); @Override public Set<Type> getToConversionImportTypes( ConversionContext conversionContext); protected boolean requiresDecimalFormat( ConversionContext conversionContext); @Override protected Set<Type> getFromConversionImportTypes( ConversionContext conversionContext); @Override protected List<Type> getFromConversionExceptionTypes( ConversionContext conversionContext); }
javamelody_javamelody
javamelody/javamelody-core/src/main/java/net/bull/javamelody/internal/web/html/HtmlSpringContextReport.java
HtmlSpringContextReport
writeBean
class HtmlSpringContextReport extends HtmlAbstractReport { private final SpringContext springContext; HtmlSpringContextReport(SpringContext springContext, Writer writer) { super(writer); assert springContext != null; this.springContext = springContext; } @Override void toHtml() throws IOException { writeBackLink(); writeln("<br/>"); final List<String> beanDefinitionNames = springContext.getBeanDefinitionNames(); writeTitle("beans.png", getString("Spring_beans")); final HtmlTable table = new HtmlTable(); table.beginTable(getString("Spring_beans")); write("<th>#Nom#</th><th>#Classe#</th><th>Bean</th>"); for (final String beanName : beanDefinitionNames) { table.nextRow(); final Object bean = springContext.getBean(beanName); final Class<?> beanClass = bean.getClass(); String beanToString; try { beanToString = bean.toString(); } catch (final Exception e) { beanToString = e.toString(); } writeBean(beanName, beanClass, beanToString); } table.endTable(); writeln("<div align='right'>" + getFormattedString("nb_beans", beanDefinitionNames.size()) + "</div>"); } private void writeBackLink() throws IOException { writeln("<div class='noPrint'>"); writeln("<a class='back' href=''><img src='?resource=action_back.png' alt='#Retour#'/> #Retour#</a>"); writeln("</div>"); } private void writeBean(String beanName, Class<?> beanClass, String beanToString) throws IOException {<FILL_FUNCTION_BODY>} }
write("<td class='wrappedText'>"); writeDirectly(htmlEncodeButNotSpace(beanName)); write("</td><td class='wrappedText'>"); writeDirectly(HtmlSourceReport.addLinkToClassName(beanClass.getName())); write("</td><td class='wrappedText'>"); writeDirectly(htmlEncodeButNotSpace(beanToString)); write("</td>");
542
131
673
/** * Parent abstrait des classes de rapport html. * @author Emeric Vernat */ public abstract class HtmlAbstractReport { private static final boolean CSRF_PROTECTION_ENABLED=Parameter.CSRF_PROTECTION_ENABLED.getValueAsBoolean(); private final Writer writer; class HtmlTable { private boolean firstRow=true; private boolean oddRow; void beginTable( String summary) throws IOException; void nextRow() throws IOException; void endTable() throws IOException; } HtmlAbstractReport( Writer writer); /** * Perform the default html rendering of the report into the writer. * @throws IOException e */ abstract void toHtml() throws IOException ; Writer getWriter(); void writeDirectly( String html) throws IOException; /** * Écrit un texte dans un flux en remplaçant dans le texte les clés entourées de deux '#' par leurs traductions dans la locale courante. * @param html texte html avec éventuellement des #clé# * @throws IOException e */ void write( String html) throws IOException; /** * Écrit un texte, puis un retour chariot, dans un flux en remplaçant dans le texte les clés entourées de deux '#' par leurs traductions dans la locale courante. * @param html texte html avec éventuellement des #clé# * @throws IOException e */ void writeln( String html) throws IOException; void writeTitle( String imageFileName, String title) throws IOException; void writeShowHideLink( String idToShow, String label) throws IOException; /** * Retourne une traduction dans la locale courante. * @param key clé d'un libellé dans les fichiers de traduction * @return String */ static String getString( String key); /** * Retourne une traduction dans la locale courante et insère les arguments aux positions {i}. * @param key clé d'un libellé dans les fichiers de traduction * @param arguments Valeur à inclure dans le résultat * @return String */ static String getFormattedString( String key, Object... arguments); static String urlEncode( String text); /** * Encode pour affichage en html, en encodant les espaces en nbsp (insécables). * @param text message à encoder * @return String */ static String htmlEncode( String text); /** * Encode pour affichage en html, sans encoder les espaces en nbsp (insécables). * @param text message à encoder * @return String */ static String htmlEncodeButNotSpace( String text); /** * Encode pour affichage en html, sans encoder les espaces en nbsp (insécables) et les retours chariots en br. * @param text message à encoder * @return String */ static String htmlEncodeButNotSpaceAndNewLine( String text); public static String getCsrfTokenUrlPart(); static boolean isPdfEnabled(); }
google_truth
truth/extensions/proto/src/main/java/com/google/common/truth/extensions/proto/IterableOfProtosSubject.java
UsingCorrespondence
delegate
class UsingCorrespondence<M extends Message> implements IterableOfProtosUsingCorrespondence<M> { private final IterableOfProtosSubject<M> subject; private final @Nullable Function<? super M, ? extends Object> keyFunction; UsingCorrespondence( IterableOfProtosSubject<M> subject, @Nullable Function<? super M, ? extends Object> keyFunction) { this.subject = checkNotNull(subject); this.keyFunction = keyFunction; } private IterableSubject.UsingCorrespondence<M, M> delegate(Iterable<? extends M> messages) {<FILL_FUNCTION_BODY>} @Override public IterableOfProtosUsingCorrespondence<M> displayingDiffsPairedBy( Function<? super M, ?> keyFunction) { return new UsingCorrespondence<M>(subject, checkNotNull(keyFunction)); } @Override public void contains(@Nullable M expected) { delegate(Arrays.asList(expected)).contains(expected); } @Override public void doesNotContain(@Nullable M excluded) { delegate(Arrays.asList(excluded)).doesNotContain(excluded); } @Override @CanIgnoreReturnValue public Ordered containsExactly(@Nullable M... expected) { return delegate(Arrays.asList(expected)).containsExactly(expected); } @Override @CanIgnoreReturnValue public Ordered containsExactlyElementsIn(Iterable<? extends M> expected) { return delegate(expected).containsExactlyElementsIn(expected); } @Override @CanIgnoreReturnValue public Ordered containsExactlyElementsIn(M[] expected) { return delegate(Arrays.asList(expected)).containsExactlyElementsIn(expected); } @Override @CanIgnoreReturnValue public Ordered containsAtLeast(@Nullable M first, @Nullable M second, @Nullable M... rest) { return delegate(Lists.asList(first, second, rest)).containsAtLeast(first, second, rest); } @Override @CanIgnoreReturnValue public Ordered containsAtLeastElementsIn(Iterable<? extends M> expected) { return delegate(expected).containsAtLeastElementsIn(expected); } @Override @CanIgnoreReturnValue public Ordered containsAtLeastElementsIn(M[] expected) { return delegate(Arrays.asList(expected)).containsAtLeastElementsIn(expected); } @Override public void containsAnyOf(@Nullable M first, @Nullable M second, @Nullable M... rest) { delegate(Lists.asList(first, second, rest)).containsAnyOf(first, second, rest); } @Override public void containsAnyIn(Iterable<? extends M> expected) { delegate(expected).containsAnyIn(expected); } @Override public void containsAnyIn(M[] expected) { delegate(Arrays.asList(expected)).containsAnyIn(expected); } @Override public void containsNoneOf( @Nullable M firstExcluded, @Nullable M secondExcluded, @Nullable M... restOfExcluded) { delegate(Lists.asList(firstExcluded, secondExcluded, restOfExcluded)) .containsNoneOf(firstExcluded, secondExcluded, restOfExcluded); } @Override public void containsNoneIn(Iterable<? extends M> excluded) { delegate(excluded).containsNoneIn(excluded); } @Override public void containsNoneIn(M[] excluded) { delegate(Arrays.asList(excluded)).containsNoneIn(excluded); } }
IterableSubject.UsingCorrespondence<M, M> usingCorrespondence = subject.comparingElementsUsing( subject .config .withExpectedMessages(messages) .<M>toCorrespondence(FieldScopeUtil.getSingleDescriptor(subject.actual))); if (keyFunction != null) { usingCorrespondence = usingCorrespondence.displayingDiffsPairedBy(keyFunction); } return usingCorrespondence;
949
116
1,065
google_truth
truth/core/src/main/java/com/google/common/truth/IterableSubject.java
Pairer
pair
class Pairer { private final Function<? super A, ?> actualKeyFunction; private final Function<? super E, ?> expectedKeyFunction; Pairer(Function<? super A, ?> actualKeyFunction, Function<? super E, ?> expectedKeyFunction) { this.actualKeyFunction = actualKeyFunction; this.expectedKeyFunction = expectedKeyFunction; } /** * Returns a {@link Pairing} of the given expected and actual values, or {@code null} if the * expected values are not uniquely keyed. */ @Nullable Pairing pair( List<? extends E> expectedValues, List<? extends A> actualValues, Correspondence.ExceptionStore exceptions) {<FILL_FUNCTION_BODY>} List<A> pairOne( E expectedValue, Iterable<? extends A> actualValues, Correspondence.ExceptionStore exceptions) { Object key = expectedKey(expectedValue, exceptions); List<A> matches = new ArrayList<>(); if (key != null) { for (A actual : actualValues) { if (key.equals(actualKey(actual, exceptions))) { matches.add(actual); } } } return matches; } private @Nullable Object actualKey(A actual, Correspondence.ExceptionStore exceptions) { try { return actualKeyFunction.apply(actual); } catch (RuntimeException e) { exceptions.addActualKeyFunctionException( IterableSubject.UsingCorrespondence.Pairer.class, e, actual); return null; } } private @Nullable Object expectedKey(E expected, Correspondence.ExceptionStore exceptions) { try { return expectedKeyFunction.apply(expected); } catch (RuntimeException e) { exceptions.addExpectedKeyFunctionException( IterableSubject.UsingCorrespondence.Pairer.class, e, expected); return null; } } }
Pairing pairing = new Pairing(); // Populate expectedKeys with the keys of the corresponding elements of expectedValues. // We do this ahead of time to avoid invoking the key function twice for each element. List<@Nullable Object> expectedKeys = new ArrayList<>(expectedValues.size()); for (E expected : expectedValues) { expectedKeys.add(expectedKey(expected, exceptions)); } // Populate pairedKeysToExpectedValues with *all* the expected values with non-null keys. // We will remove the unpaired keys later. Return null if we find a duplicate key. for (int i = 0; i < expectedValues.size(); i++) { E expected = expectedValues.get(i); Object key = expectedKeys.get(i); if (key != null) { if (pairing.pairedKeysToExpectedValues.containsKey(key)) { return null; } else { pairing.pairedKeysToExpectedValues.put(key, expected); } } } // Populate pairedKeysToActualValues and unpairedActualValues. for (A actual : actualValues) { Object key = actualKey(actual, exceptions); if (pairing.pairedKeysToExpectedValues.containsKey(key)) { pairing.pairedKeysToActualValues.put(checkNotNull(key), actual); } else { pairing.unpairedActualValues.add(actual); } } // Populate unpairedExpectedValues and remove unpaired keys from pairedKeysToExpectedValues. for (int i = 0; i < expectedValues.size(); i++) { E expected = expectedValues.get(i); Object key = expectedKeys.get(i); if (!pairing.pairedKeysToActualValues.containsKey(key)) { pairing.unpairedExpectedValues.add(expected); pairing.pairedKeysToExpectedValues.remove(key); } } return pairing;
503
501
1,004
orientechnologies_orientdb
orientdb/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateVertex.java
OCommandExecutorSQLCreateVertex
execute
class OCommandExecutorSQLCreateVertex extends OCommandExecutorSQLSetAware implements OCommandDistributedReplicateRequest { public static final String NAME = "CREATE VERTEX"; private OClass clazz; private String clusterName; private List<OPair<String, Object>> fields; @SuppressWarnings("unchecked") public OCommandExecutorSQLCreateVertex parse(final OCommandRequest iRequest) { final OCommandRequestText textRequest = (OCommandRequestText) iRequest; String queryText = textRequest.getText(); String originalQuery = queryText; try { queryText = preParse(queryText, iRequest); textRequest.setText(queryText); final ODatabaseDocument database = getDatabase(); init((OCommandRequestText) iRequest); String className = null; parserRequiredKeyword("CREATE"); parserRequiredKeyword("VERTEX"); String temp = parseOptionalWord(true); while (temp != null) { if (temp.equals("CLUSTER")) { clusterName = parserRequiredWord(false); } else if (temp.equals(KEYWORD_SET)) { fields = new ArrayList<OPair<String, Object>>(); parseSetFields(clazz, fields); } else if (temp.equals(KEYWORD_CONTENT)) { parseContent(); } else if (className == null && temp.length() > 0) { className = temp; if (className == null) // ASSIGN DEFAULT CLASS className = "V"; // GET/CHECK CLASS NAME clazz = ((OMetadataInternal) database.getMetadata()) .getImmutableSchemaSnapshot() .getClass(className); if (clazz == null) throw new OCommandSQLParsingException("Class '" + className + "' was not found"); } temp = parserOptionalWord(true); if (parserIsEnded()) break; } if (className == null) { // ASSIGN DEFAULT CLASS className = "V"; // GET/CHECK CLASS NAME clazz = ((OMetadataInternal) database.getMetadata()) .getImmutableSchemaSnapshot() .getClass(className); if (clazz == null) throw new OCommandSQLParsingException("Class '" + className + "' was not found"); } } finally { textRequest.setText(originalQuery); } return this; } /** Execute the command and return the ODocument object created. */ public Object execute(final Map<Object, Object> iArgs) {<FILL_FUNCTION_BODY>} @Override public DISTRIBUTED_EXECUTION_MODE getDistributedExecutionMode() { return DISTRIBUTED_EXECUTION_MODE.LOCAL; } @Override public QUORUM_TYPE getQuorumType() { return QUORUM_TYPE.WRITE; } @Override public Set<String> getInvolvedClusters() { if (clazz != null) return Collections.singleton( getDatabase().getClusterNameById(clazz.getClusterSelection().getCluster(clazz, null))); else if (clusterName != null) return getInvolvedClustersOfClusters(Collections.singleton(clusterName)); return Collections.EMPTY_SET; } @Override public String getSyntax() { return "CREATE VERTEX [<class>] [CLUSTER <cluster>] [SET <field> = <expression>[,]*]"; } }
if (clazz == null) throw new OCommandExecutionException( "Cannot execute the command because it has not been parsed yet"); // CREATE VERTEX DOES NOT HAVE TO BE IN TX final OVertex vertex = getDatabase().newVertex(clazz); if (fields != null) // EVALUATE FIELDS for (final OPair<String, Object> f : fields) { if (f.getValue() instanceof OSQLFunctionRuntime) f.setValue( ((OSQLFunctionRuntime) f.getValue()).getValue(vertex.getRecord(), null, context)); } OSQLHelper.bindParameters(vertex.getRecord(), fields, new OCommandParameters(iArgs), context); if (content != null) ((ODocument) vertex.getRecord()).merge(content, true, false); if (clusterName != null) vertex.save(clusterName); else vertex.save(); return vertex.getRecord();
921
243
1,164
/** * @author Luca Molino (molino.luca--at--gmail.com) */ public abstract class OCommandExecutorSQLSetAware extends OCommandExecutorSQLAbstract { protected static final String KEYWORD_SET="SET"; protected static final String KEYWORD_CONTENT="CONTENT"; protected ODocument content=null; protected int parameterCounter=0; protected void parseContent(); protected void parseSetFields( final OClass iClass, final List<OPair<String,Object>> fields); protected OClass extractClassFromTarget( String iTarget); protected Object convertValue( OClass iClass, String fieldName, Object v); private ODocument createDocumentFromMap(OClass embeddedType,Map<String,Object> o); @Override public long getDistributedTimeout(); protected Object getFieldValueCountingParameters(String fieldValue); protected ODocument parseJSON(); }
ainilili_ratel
ratel/landlords-client/src/main/java/org/nico/ratel/landlords/client/event/ClientEventListener_CODE_GAME_READY.java
ClientEventListener_CODE_GAME_READY
call
class ClientEventListener_CODE_GAME_READY extends ClientEventListener { @Override public void call(Channel channel, String data) {<FILL_FUNCTION_BODY>} static void gameReady(Channel channel) { SimplePrinter.printNotice("\nDo you want to continue the game? [Y/N]"); String line = SimpleWriter.write(User.INSTANCE.getNickname(), "notReady"); if (line.equals("Y") || line.equals("y")) { ChannelUtils.pushToServer(channel, ServerEventCode.CODE_GAME_READY, ""); return; } ChannelUtils.pushToServer(channel, ServerEventCode.CODE_CLIENT_EXIT, ""); } }
Map<String, Object> map = MapHelper.parser(data); if (SimpleClient.id == (int) map.get("clientId")) { SimplePrinter.printNotice("you are ready to play game."); return; } SimplePrinter.printNotice(map.get("clientNickName").toString() + " is ready to play game.");
185
91
276
public abstract class ClientEventListener { public abstract void call( Channel channel, String data); public final static Map<ClientEventCode,ClientEventListener> LISTENER_MAP=new HashMap<>(); private final static String LISTENER_PREFIX="org.nico.ratel.landlords.client.event.ClientEventListener_"; protected static List<Poker> lastPokers=null; protected static String lastSellClientNickname=null; protected static String lastSellClientType=null; protected static void initLastSellInfo(); @SuppressWarnings("unchecked") public static ClientEventListener get( ClientEventCode code); protected ChannelFuture pushToServer( Channel channel, ServerEventCode code, String datas); protected ChannelFuture pushToServer( Channel channel, ServerEventCode code); }
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/routing/DirectionResolverResult.java
DirectionResolverResult
getOutEdge
class DirectionResolverResult { private static final DirectionResolverResult UNRESTRICTED = new DirectionResolverResult(ANY_EDGE, ANY_EDGE, ANY_EDGE, ANY_EDGE); private static final DirectionResolverResult IMPOSSIBLE = new DirectionResolverResult(NO_EDGE, NO_EDGE, NO_EDGE, NO_EDGE); private final int inEdgeRight; private final int outEdgeRight; private final int inEdgeLeft; private final int outEdgeLeft; public static DirectionResolverResult onlyLeft(int inEdge, int outEdge) { return new DirectionResolverResult(NO_EDGE, NO_EDGE, inEdge, outEdge); } public static DirectionResolverResult onlyRight(int inEdge, int outEdge) { return new DirectionResolverResult(inEdge, outEdge, NO_EDGE, NO_EDGE); } public static DirectionResolverResult restricted(int inEdgeRight, int outEdgeRight, int inEdgeLeft, int outEdgeLeft) { return new DirectionResolverResult(inEdgeRight, outEdgeRight, inEdgeLeft, outEdgeLeft); } public static DirectionResolverResult unrestricted() { return UNRESTRICTED; } public static DirectionResolverResult impossible() { return IMPOSSIBLE; } private DirectionResolverResult(int inEdgeRight, int outEdgeRight, int inEdgeLeft, int outEdgeLeft) { this.inEdgeRight = inEdgeRight; this.outEdgeRight = outEdgeRight; this.inEdgeLeft = inEdgeLeft; this.outEdgeLeft = outEdgeLeft; } public static int getOutEdge(DirectionResolverResult directionResolverResult, String curbside) {<FILL_FUNCTION_BODY>} public static int getInEdge(DirectionResolverResult directionResolverResult, String curbside) { if (curbside.trim().isEmpty()) { curbside = CURBSIDE_ANY; } switch (curbside) { case CURBSIDE_RIGHT: return directionResolverResult.getInEdgeRight(); case CURBSIDE_LEFT: return directionResolverResult.getInEdgeLeft(); case CURBSIDE_ANY: return ANY_EDGE; default: throw new IllegalArgumentException("Unknown value for '" + CURBSIDE + " : " + curbside + "'. allowed: " + CURBSIDE_LEFT + ", " + CURBSIDE_RIGHT + ", " + CURBSIDE_ANY); } } public int getInEdgeRight() { return inEdgeRight; } public int getOutEdgeRight() { return outEdgeRight; } public int getInEdgeLeft() { return inEdgeLeft; } public int getOutEdgeLeft() { return outEdgeLeft; } public boolean isRestricted() { return !equals(UNRESTRICTED); } public boolean isImpossible() { return equals(IMPOSSIBLE); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; DirectionResolverResult that = (DirectionResolverResult) o; return inEdgeRight == that.inEdgeRight && outEdgeRight == that.outEdgeRight && inEdgeLeft == that.inEdgeLeft && outEdgeLeft == that.outEdgeLeft; } @Override public int hashCode() { return Objects.hash(inEdgeRight, outEdgeRight, inEdgeLeft, outEdgeLeft); } @Override public String toString() { if (!isRestricted()) { return "unrestricted"; } else if (isImpossible()) { return "impossible"; } else { return "in-edge-right: " + pretty(inEdgeRight) + ", out-edge-right: " + pretty(outEdgeRight) + ", in-edge-left: " + pretty(inEdgeLeft) + ", out-edge-left: " + pretty(outEdgeLeft); } } private String pretty(int edgeId) { if (edgeId == NO_EDGE) { return "NO_EDGE"; } else if (edgeId == ANY_EDGE) { return "ANY_EDGE"; } else { return edgeId + ""; } } }
if (curbside.trim().isEmpty()) { curbside = CURBSIDE_ANY; } switch (curbside) { case CURBSIDE_RIGHT: return directionResolverResult.getOutEdgeRight(); case CURBSIDE_LEFT: return directionResolverResult.getOutEdgeLeft(); case CURBSIDE_ANY: return ANY_EDGE; default: throw new IllegalArgumentException("Unknown value for " + CURBSIDE + " : '" + curbside + "'. allowed: " + CURBSIDE_LEFT + ", " + CURBSIDE_RIGHT + ", " + CURBSIDE_ANY); }
1,145
175
1,320
jeecgboot_jeecg-boot
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/config/shiro/filters/ResourceCheckFilter.java
ResourceCheckFilter
onAccessDenied
class ResourceCheckFilter extends AccessControlFilter { private String errorUrl; public String getErrorUrl() { return errorUrl; } public void setErrorUrl(String errorUrl) { this.errorUrl = errorUrl; } /** * 表示是否允许访问 ,如果允许访问返回true,否则false; * * @param servletRequest * @param servletResponse * @param o 表示写在拦截器中括号里面的字符串 mappedValue 就是 [urls] 配置中拦截器参数部分 * @return * @throws Exception */ @Override protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) throws Exception { Subject subject = getSubject(servletRequest, servletResponse); String url = getPathWithinApplication(servletRequest); log.info("当前用户正在访问的 url => " + url); return subject.isPermitted(url); } /** * onAccessDenied:表示当访问拒绝时是否已经处理了; 如果返回 true 表示需要继续处理; 如果返回 false * 表示该拦截器实例已经处理了,将直接返回即可。 * * @param servletRequest * @param servletResponse * @return * @throws Exception */ @Override protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {<FILL_FUNCTION_BODY>} }
log.info("当 isAccessAllowed 返回 false 的时候,才会执行 method onAccessDenied "); HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; response.sendRedirect(request.getContextPath() + this.errorUrl); // 返回 false 表示已经处理,例如页面跳转啥的,表示不在走以下的拦截器了(如果还有配置的话) return false;
398
126
524
YunaiV_ruoyi-vue-pro
ruoyi-vue-pro/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/db/DataSourceConfigServiceImpl.java
DataSourceConfigServiceImpl
getDataSourceConfigList
class DataSourceConfigServiceImpl implements DataSourceConfigService { @Resource private DataSourceConfigMapper dataSourceConfigMapper; @Resource private DynamicDataSourceProperties dynamicDataSourceProperties; @Override public Long createDataSourceConfig(DataSourceConfigSaveReqVO createReqVO) { DataSourceConfigDO config = BeanUtils.toBean(createReqVO, DataSourceConfigDO.class); validateConnectionOK(config); // 插入 dataSourceConfigMapper.insert(config); // 返回 return config.getId(); } @Override public void updateDataSourceConfig(DataSourceConfigSaveReqVO updateReqVO) { // 校验存在 validateDataSourceConfigExists(updateReqVO.getId()); DataSourceConfigDO updateObj = BeanUtils.toBean(updateReqVO, DataSourceConfigDO.class); validateConnectionOK(updateObj); // 更新 dataSourceConfigMapper.updateById(updateObj); } @Override public void deleteDataSourceConfig(Long id) { // 校验存在 validateDataSourceConfigExists(id); // 删除 dataSourceConfigMapper.deleteById(id); } private void validateDataSourceConfigExists(Long id) { if (dataSourceConfigMapper.selectById(id) == null) { throw exception(DATA_SOURCE_CONFIG_NOT_EXISTS); } } @Override public DataSourceConfigDO getDataSourceConfig(Long id) { // 如果 id 为 0,默认为 master 的数据源 if (Objects.equals(id, DataSourceConfigDO.ID_MASTER)) { return buildMasterDataSourceConfig(); } // 从 DB 中读取 return dataSourceConfigMapper.selectById(id); } @Override public List<DataSourceConfigDO> getDataSourceConfigList() {<FILL_FUNCTION_BODY>} private void validateConnectionOK(DataSourceConfigDO config) { boolean success = JdbcUtils.isConnectionOK(config.getUrl(), config.getUsername(), config.getPassword()); if (!success) { throw exception(DATA_SOURCE_CONFIG_NOT_OK); } } private DataSourceConfigDO buildMasterDataSourceConfig() { String primary = dynamicDataSourceProperties.getPrimary(); DataSourceProperty dataSourceProperty = dynamicDataSourceProperties.getDatasource().get(primary); return new DataSourceConfigDO().setId(DataSourceConfigDO.ID_MASTER).setName(primary) .setUrl(dataSourceProperty.getUrl()) .setUsername(dataSourceProperty.getUsername()) .setPassword(dataSourceProperty.getPassword()); } }
List<DataSourceConfigDO> result = dataSourceConfigMapper.selectList(); // 补充 master 数据源 result.add(0, buildMasterDataSourceConfig()); return result;
695
50
745
PlayEdu_PlayEdu
PlayEdu/playedu-api/src/main/java/xyz/playedu/api/controller/backend/AdminUserController.java
AdminUserController
Index
class AdminUserController { @Autowired private AdminUserService adminUserService; @Autowired private AdminRoleService roleService; @BackendPermission(slug = BPermissionConstant.ADMIN_USER_INDEX) @GetMapping("/index") @Log(title = "管理员-列表", businessType = BusinessTypeConstant.GET) public JsonResponse Index(@RequestParam HashMap<String, Object> params) {<FILL_FUNCTION_BODY>} @BackendPermission(slug = BPermissionConstant.ADMIN_USER_CUD) @GetMapping("/create") @Log(title = "管理员-新建", businessType = BusinessTypeConstant.GET) public JsonResponse create() { List<AdminRole> roles = roleService.list(); HashMap<String, Object> data = new HashMap<>(); data.put("roles", roles); return JsonResponse.data(data); } @BackendPermission(slug = BPermissionConstant.ADMIN_USER_CUD) @PostMapping("/create") @Log(title = "管理员-新建", businessType = BusinessTypeConstant.INSERT) public JsonResponse store(@RequestBody @Validated AdminUserRequest req) throws ServiceException { if (req.getPassword().length() == 0) { return JsonResponse.error("请输入密码"); } adminUserService.createWithRoleIds( req.getName(), req.getEmail(), req.getPassword(), req.getIsBanLogin(), req.getRoleIds()); return JsonResponse.success(); } @BackendPermission(slug = BPermissionConstant.ADMIN_USER_CUD) @GetMapping("/{id}") @Log(title = "管理员-编辑", businessType = BusinessTypeConstant.GET) public JsonResponse edit(@PathVariable Integer id) throws NotFoundException { AdminUser adminUser = adminUserService.findOrFail(id); List<Integer> roleIds = adminUserService.getRoleIdsByUserId(adminUser.getId()); HashMap<String, Object> data = new HashMap<>(); data.put("user", adminUser); data.put("role_ids", roleIds); return JsonResponse.data(data); } @BackendPermission(slug = BPermissionConstant.ADMIN_USER_CUD) @PutMapping("/{id}") @Log(title = "管理员-编辑", businessType = BusinessTypeConstant.UPDATE) public JsonResponse update( @PathVariable Integer id, @RequestBody @Validated AdminUserRequest req) throws NotFoundException, ServiceException { AdminUser adminUser = adminUserService.findOrFail(id); adminUserService.updateWithRoleIds( adminUser, req.getName(), req.getEmail(), req.getPassword(), req.getIsBanLogin(), req.getRoleIds()); return JsonResponse.success(); } @BackendPermission(slug = BPermissionConstant.ADMIN_USER_CUD) @DeleteMapping("/{id}") @Log(title = "管理员-删除", businessType = BusinessTypeConstant.DELETE) public JsonResponse destroy(@PathVariable Integer id) { adminUserService.removeWithRoleIds(id); return JsonResponse.success(); } }
Integer page = MapUtils.getInteger(params, "page", 1); Integer size = MapUtils.getInteger(params, "size", 10); String name = MapUtils.getString(params, "name"); Integer roleId = MapUtils.getInteger(params, "role_id"); AdminUserPaginateFilter filter = new AdminUserPaginateFilter(); filter.setName(name); filter.setRoleId(roleId); PaginationResult<AdminUser> result = adminUserService.paginate(page, size, filter); Map<Integer, List<Integer>> userRoleIds = new HashMap<>(); if (result.getData() != null && result.getData().size() > 0) { userRoleIds = adminUserService.getAdminUserRoleIds( result.getData().stream().map(AdminUser::getId).toList()); } HashMap<String, Object> data = new HashMap<>(); data.put("data", result.getData()); data.put("total", result.getTotal()); data.put("user_role_ids", userRoleIds); data.put( "roles", roleService.list().stream().collect(Collectors.groupingBy(AdminRole::getId))); return JsonResponse.data(data);
852
332
1,184
javamelody_javamelody
javamelody/javamelody-spring-boot-starter/src/main/java/net/bull/javamelody/MonitoringEndpoint.java
MonitoringEndpoint
report
class MonitoringEndpoint { private final ReportServlet reportServlet; /** * Constructor. * @param servletContext ServletContext */ public MonitoringEndpoint(ServletContext servletContext) { reportServlet = new ReportServlet(); final ServletConfig servletConfig = new ServletConfig() { // only getServletContext() will be used by ReportServlet @Override public ServletContext getServletContext() { return servletContext; } @Override public String getServletName() { return MonitoringEndpoint.class.getName(); } @Override public String getInitParameter(String name) { return null; } @Override public Enumeration<String> getInitParameterNames() { return Collections.emptyEnumeration(); } }; reportServlet.init(servletConfig); } /** * Display a report page. * @return HttpEntity.EMPTY * @throws ServletException e * @throws IOException e */ @ReadOperation public Object report() throws ServletException, IOException {<FILL_FUNCTION_BODY>} }
final ServletRequestAttributes currentRequestAttributes = (ServletRequestAttributes) RequestContextHolder .currentRequestAttributes(); final HttpServletRequest httpServletRequest = currentRequestAttributes.getRequest(); final HttpServletResponse httpResponse = currentRequestAttributes.getResponse(); reportServlet.service(httpServletRequest, httpResponse); // status, headers and body are managed by the servlet, so return HttpEntity.EMPTY return HttpEntity.EMPTY;
291
114
405
elunez_eladmin
eladmin/eladmin-system/src/main/java/me/zhengjie/modules/system/service/dto/MenuDto.java
MenuDto
equals
class MenuDto extends BaseDTO implements Serializable { private Long id; private List<MenuDto> children; private Integer type; private String permission; private String title; private Integer menuSort; private String path; private String component; private Long pid; private Integer subCount; private Boolean iFrame; private Boolean cache; private Boolean hidden; private String componentName; private String icon; public Boolean getHasChildren() { return subCount > 0; } public Boolean getLeaf() { return subCount <= 0; } public String getLabel() { return title; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(id); } }
if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } MenuDto menuDto = (MenuDto) o; return Objects.equals(id, menuDto.id);
241
79
320
/** * @author Zheng Jie * @date 2019年10月24日20:48:53 */ @Getter @Setter public class BaseDTO implements Serializable { private String createBy; private String updateBy; private Timestamp createTime; private Timestamp updateTime; @Override public String toString(); }
houbb_sensitive-word
sensitive-word/src/main/java/com/github/houbb/sensitive/word/support/allow/WordAllowInit.java
WordAllowInit
allow
class WordAllowInit implements IWordAllow { /** * 初始化列表 * * @param pipeline 当前列表泳道 * @since 0.0.13 */ protected abstract void init(final Pipeline<IWordAllow> pipeline); @Override public List<String> allow() {<FILL_FUNCTION_BODY>} }
Pipeline<IWordAllow> pipeline = new DefaultPipeline<>(); this.init(pipeline); List<String> results = new ArrayList<>(); List<IWordAllow> wordAllows = pipeline.list(); for (IWordAllow wordAllow : wordAllows) { List<String> allowList = wordAllow.allow(); results.addAll(allowList); } return results;
100
106
206
spring-cloud_spring-cloud-gateway
spring-cloud-gateway/spring-cloud-gateway-server/src/main/java/org/springframework/cloud/gateway/handler/RoutePredicateHandlerMapping.java
RoutePredicateHandlerMapping
getHandlerInternal
class RoutePredicateHandlerMapping extends AbstractHandlerMapping { private final FilteringWebHandler webHandler; private final RouteLocator routeLocator; private final Integer managementPort; private final ManagementPortType managementPortType; public RoutePredicateHandlerMapping(FilteringWebHandler webHandler, RouteLocator routeLocator, GlobalCorsProperties globalCorsProperties, Environment environment) { this.webHandler = webHandler; this.routeLocator = routeLocator; this.managementPort = getPortProperty(environment, "management.server."); this.managementPortType = getManagementPortType(environment); setOrder(environment.getProperty(GatewayProperties.PREFIX + ".handler-mapping.order", Integer.class, 1)); setCorsConfigurations(globalCorsProperties.getCorsConfigurations()); } private ManagementPortType getManagementPortType(Environment environment) { Integer serverPort = getPortProperty(environment, "server."); if (this.managementPort != null && this.managementPort < 0) { return DISABLED; } return ((this.managementPort == null || (serverPort == null && this.managementPort.equals(8080)) || (this.managementPort != 0 && this.managementPort.equals(serverPort))) ? SAME : DIFFERENT); } private static Integer getPortProperty(Environment environment, String prefix) { return environment.getProperty(prefix + "port", Integer.class); } @Override protected Mono<?> getHandlerInternal(ServerWebExchange exchange) {<FILL_FUNCTION_BODY>} @Override protected CorsConfiguration getCorsConfiguration(Object handler, ServerWebExchange exchange) { // TODO: support cors configuration via properties on a route see gh-229 // see RequestMappingHandlerMapping.initCorsConfiguration() // also see // https://github.com/spring-projects/spring-framework/blob/master/spring-web/src/test/java/org/springframework/web/cors/reactive/CorsWebFilterTests.java return super.getCorsConfiguration(handler, exchange); } // TODO: get desc from factory? private String getExchangeDesc(ServerWebExchange exchange) { StringBuilder out = new StringBuilder(); out.append("Exchange: "); out.append(exchange.getRequest().getMethod()); out.append(" "); out.append(exchange.getRequest().getURI()); return out.toString(); } protected Mono<Route> lookupRoute(ServerWebExchange exchange) { return this.routeLocator.getRoutes() // individually filter routes so that filterWhen error delaying is not a // problem .concatMap(route -> Mono.just(route).filterWhen(r -> { // add the current route we are testing exchange.getAttributes().put(GATEWAY_PREDICATE_ROUTE_ATTR, r.getId()); return r.getPredicate().apply(exchange); }) // instead of immediately stopping main flux due to error, log and // swallow it .doOnError(e -> logger.error("Error applying predicate for route: " + route.getId(), e)) .onErrorResume(e -> Mono.empty())) // .defaultIfEmpty() put a static Route not found // or .switchIfEmpty() // .switchIfEmpty(Mono.<Route>empty().log("noroute")) .next() // TODO: error handling .map(route -> { if (logger.isDebugEnabled()) { logger.debug("Route matched: " + route.getId()); } validateRoute(route, exchange); return route; }); /* * TODO: trace logging if (logger.isTraceEnabled()) { * logger.trace("RouteDefinition did not match: " + routeDefinition.getId()); } */ } /** * Validate the given handler against the current request. * <p> * The default implementation is empty. Can be overridden in subclasses, for example * to enforce specific preconditions expressed in URL mappings. * @param route the Route object to validate * @param exchange current exchange * @throws Exception if validation failed */ @SuppressWarnings("UnusedParameters") protected void validateRoute(Route route, ServerWebExchange exchange) { } protected String getSimpleName() { return "RoutePredicateHandlerMapping"; } public enum ManagementPortType { /** * The management port has been disabled. */ DISABLED, /** * The management port is the same as the server port. */ SAME, /** * The management port and server port are different. */ DIFFERENT; } }
// don't handle requests on management port if set and different than server port if (this.managementPortType == DIFFERENT && this.managementPort != null && exchange.getRequest().getLocalAddress() != null && exchange.getRequest().getLocalAddress().getPort() == this.managementPort) { return Mono.empty(); } exchange.getAttributes().put(GATEWAY_HANDLER_MAPPER_ATTR, getSimpleName()); return Mono.deferContextual(contextView -> { exchange.getAttributes().put(GATEWAY_REACTOR_CONTEXT_ATTR, contextView); return lookupRoute(exchange) // .log("route-predicate-handler-mapping", Level.FINER) //name this .map((Function<Route, ?>) r -> { exchange.getAttributes().remove(GATEWAY_PREDICATE_ROUTE_ATTR); if (logger.isDebugEnabled()) { logger.debug("Mapping [" + getExchangeDesc(exchange) + "] to " + r); } exchange.getAttributes().put(GATEWAY_ROUTE_ATTR, r); return webHandler; }).switchIfEmpty(Mono.empty().then(Mono.fromRunnable(() -> { exchange.getAttributes().remove(GATEWAY_PREDICATE_ROUTE_ATTR); if (logger.isTraceEnabled()) { logger.trace("No RouteDefinition found for [" + getExchangeDesc(exchange) + "]"); } }))); });
1,213
410
1,623
PlexPt_chatgpt-java
chatgpt-java/src/main/java/com/plexpt/chatgpt/Test.java
Test
main
class Test { public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
Proxy proxys = Proxys.http("127.0.0.1",10809); Images images = Images.builder() .proxy(proxys) .apiKey("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") .apiHost("https://api.openai.com/") .timeout(900) .build() .init(); File file = new File("C:\\Users\\马同徽\\Pictures\\微信图片_20230606140621.png"); Variations variations = Variations.ofURL(1,"256x256"); Generations generations = Generations.ofURL("一只鲨鱼和一直蜜蜂结合成一种动物",1,"256x256"); ImagesRensponse imagesRensponse = images.variations(file,variations); System.out.println(imagesRensponse.getCreated()); System.out.println(imagesRensponse.getCode()); System.out.println(imagesRensponse.getMsg()); List<Object> data = imagesRensponse.getData(); for(Object o:data){ System.out.println(o.toString()); } /*Audio audio = Audio.builder() .proxy(proxys) .apiKey("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") .apiHost("https://api.openai.com/") .timeout(900) .build() .init(); File file = new File("D:\\Jenny.mp3"); Transcriptions transcriptions = Transcriptions.of(file, AudioModel.WHISPER1.getValue()); AudioResponse response = audio.transcriptions(transcriptions); System.out.println(response.getText());*/
30
520
550
jeecgboot_jeecg-boot
jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/system/entity/SysDepart.java
SysDepart
equals
class SysDepart implements Serializable { private static final long serialVersionUID = 1L; /**ID*/ @TableId(type = IdType.ASSIGN_ID) private String id; /**父机构ID*/ private String parentId; /**机构/部门名称*/ @Excel(name="机构/部门名称",width=15) private String departName; /**英文名*/ @Excel(name="英文名",width=15) private String departNameEn; /**缩写*/ private String departNameAbbr; /**排序*/ @Excel(name="排序",width=15) private Integer departOrder; /**描述*/ @Excel(name="描述",width=15) private String description; /**机构类别 1=公司,2=组织机构,3=岗位*/ @Excel(name="机构类别",width=15,dicCode="org_category") private String orgCategory; /**机构类型*/ private String orgType; /**机构编码*/ @Excel(name="机构编码",width=15) private String orgCode; /**手机号*/ @Excel(name="手机号",width=15) private String mobile; /**传真*/ @Excel(name="传真",width=15) private String fax; /**地址*/ @Excel(name="地址",width=15) private String address; /**备注*/ @Excel(name="备注",width=15) private String memo; /**状态(1启用,0不启用)*/ @Dict(dicCode = "depart_status") private String status; /**删除状态(0,正常,1已删除)*/ @Dict(dicCode = "del_flag") private String delFlag; /**对接企业微信的ID*/ private String qywxIdentifier; /**创建人*/ private String createBy; /**创建日期*/ @JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd HH:mm:ss") @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") private Date createTime; /**更新人*/ private String updateBy; /**更新日期*/ @JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd HH:mm:ss") @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") private Date updateTime; /**租户ID*/ private java.lang.Integer tenantId; /**是否有叶子节点: 1是0否*/ private Integer izLeaf; //update-begin---author:wangshuai ---date:20200308 for:[JTC-119]在部门管理菜单下设置部门负责人,新增字段负责人ids和旧的负责人ids /**部门负责人的ids*/ @TableField(exist = false) private String directorUserIds; /**旧的部门负责人的ids(用于比较删除和新增)*/ @TableField(exist = false) private String oldDirectorUserIds; //update-end---author:wangshuai ---date:20200308 for:[JTC-119]新增字段负责人ids和旧的负责人ids /** * 重写equals方法 */ @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} /** * 重写hashCode方法 */ @Override public int hashCode() { return Objects.hash(super.hashCode(), id, parentId, departName, departNameEn, departNameAbbr, departOrder, description,orgCategory, orgType, orgCode, mobile, fax, address, memo, status, delFlag, createBy, createTime, updateBy, updateTime, tenantId); } }
if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (!super.equals(o)) { return false; } SysDepart depart = (SysDepart) o; return Objects.equals(id, depart.id) && Objects.equals(parentId, depart.parentId) && Objects.equals(departName, depart.departName) && Objects.equals(departNameEn, depart.departNameEn) && Objects.equals(departNameAbbr, depart.departNameAbbr) && Objects.equals(departOrder, depart.departOrder) && Objects.equals(description, depart.description) && Objects.equals(orgCategory, depart.orgCategory) && Objects.equals(orgType, depart.orgType) && Objects.equals(orgCode, depart.orgCode) && Objects.equals(mobile, depart.mobile) && Objects.equals(fax, depart.fax) && Objects.equals(address, depart.address) && Objects.equals(memo, depart.memo) && Objects.equals(status, depart.status) && Objects.equals(delFlag, depart.delFlag) && Objects.equals(createBy, depart.createBy) && Objects.equals(createTime, depart.createTime) && Objects.equals(updateBy, depart.updateBy) && Objects.equals(tenantId, depart.tenantId) && Objects.equals(updateTime, depart.updateTime);
993
424
1,417
DerekYRC_mini-spring
mini-spring/src/main/java/org/springframework/beans/factory/xml/XmlBeanDefinitionReader.java
XmlBeanDefinitionReader
doLoadBeanDefinitions
class XmlBeanDefinitionReader extends AbstractBeanDefinitionReader { public static final String BEAN_ELEMENT = "bean"; public static final String PROPERTY_ELEMENT = "property"; public static final String ID_ATTRIBUTE = "id"; public static final String NAME_ATTRIBUTE = "name"; public static final String CLASS_ATTRIBUTE = "class"; public static final String VALUE_ATTRIBUTE = "value"; public static final String REF_ATTRIBUTE = "ref"; public static final String INIT_METHOD_ATTRIBUTE = "init-method"; public static final String DESTROY_METHOD_ATTRIBUTE = "destroy-method"; public static final String SCOPE_ATTRIBUTE = "scope"; public static final String LAZYINIT_ATTRIBUTE = "lazyInit"; public static final String BASE_PACKAGE_ATTRIBUTE = "base-package"; public static final String COMPONENT_SCAN_ELEMENT = "component-scan"; public XmlBeanDefinitionReader(BeanDefinitionRegistry registry) { super(registry); } public XmlBeanDefinitionReader(BeanDefinitionRegistry registry, ResourceLoader resourceLoader) { super(registry, resourceLoader); } @Override public void loadBeanDefinitions(String location) throws BeansException { ResourceLoader resourceLoader = getResourceLoader(); Resource resource = resourceLoader.getResource(location); loadBeanDefinitions(resource); } @Override public void loadBeanDefinitions(Resource resource) throws BeansException { try { InputStream inputStream = resource.getInputStream(); try { doLoadBeanDefinitions(inputStream); } finally { inputStream.close(); } } catch (IOException | DocumentException ex) { throw new BeansException("IOException parsing XML document from " + resource, ex); } } protected void doLoadBeanDefinitions(InputStream inputStream) throws DocumentException {<FILL_FUNCTION_BODY>} /** * 扫描注解Component的类,提取信息,组装成BeanDefinition * * @param scanPath */ private void scanPackage(String scanPath) { String[] basePackages = StrUtil.splitToArray(scanPath, ','); ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(getRegistry()); scanner.doScan(basePackages); } }
SAXReader reader = new SAXReader(); Document document = reader.read(inputStream); Element root = document.getRootElement(); //解析context:component-scan标签并扫描指定包中的类,提取类信息,组装成BeanDefinition Element componentScan = root.element(COMPONENT_SCAN_ELEMENT); if (componentScan != null) { String scanPath = componentScan.attributeValue(BASE_PACKAGE_ATTRIBUTE); if (StrUtil.isEmpty(scanPath)) { throw new BeansException("The value of base-package attribute can not be empty or null"); } scanPackage(scanPath); } List<Element> beanList = root.elements(BEAN_ELEMENT); for (Element bean : beanList) { String beanId = bean.attributeValue(ID_ATTRIBUTE); String beanName = bean.attributeValue(NAME_ATTRIBUTE); String className = bean.attributeValue(CLASS_ATTRIBUTE); String initMethodName = bean.attributeValue(INIT_METHOD_ATTRIBUTE); String destroyMethodName = bean.attributeValue(DESTROY_METHOD_ATTRIBUTE); String beanScope = bean.attributeValue(SCOPE_ATTRIBUTE); String lazyInit = bean.attributeValue(LAZYINIT_ATTRIBUTE); Class<?> clazz; try { clazz = Class.forName(className); } catch (ClassNotFoundException e) { throw new BeansException("Cannot find class [" + className + "]"); } //id优先于name beanName = StrUtil.isNotEmpty(beanId) ? beanId : beanName; if (StrUtil.isEmpty(beanName)) { //如果id和name都为空,将类名的第一个字母转为小写后作为bean的名称 beanName = StrUtil.lowerFirst(clazz.getSimpleName()); } BeanDefinition beanDefinition = new BeanDefinition(clazz); beanDefinition.setInitMethodName(initMethodName); beanDefinition.setDestroyMethodName(destroyMethodName); beanDefinition.setLazyInit(Boolean.parseBoolean(lazyInit)); if (StrUtil.isNotEmpty(beanScope)) { beanDefinition.setScope(beanScope); } List<Element> propertyList = bean.elements(PROPERTY_ELEMENT); for (Element property : propertyList) { String propertyNameAttribute = property.attributeValue(NAME_ATTRIBUTE); String propertyValueAttribute = property.attributeValue(VALUE_ATTRIBUTE); String propertyRefAttribute = property.attributeValue(REF_ATTRIBUTE); if (StrUtil.isEmpty(propertyNameAttribute)) { throw new BeansException("The name attribute cannot be null or empty"); } Object value = propertyValueAttribute; if (StrUtil.isNotEmpty(propertyRefAttribute)) { value = new BeanReference(propertyRefAttribute); } PropertyValue propertyValue = new PropertyValue(propertyNameAttribute, value); beanDefinition.getPropertyValues().addPropertyValue(propertyValue); } if (getRegistry().containsBeanDefinition(beanName)) { //beanName不能重名 throw new BeansException("Duplicate beanName[" + beanName + "] is not allowed"); } //注册BeanDefinition getRegistry().registerBeanDefinition(beanName, beanDefinition); }
602
876
1,478
/** * @author derekyi * @date 2020/11/26 */ public abstract class AbstractBeanDefinitionReader implements BeanDefinitionReader { private final BeanDefinitionRegistry registry; private ResourceLoader resourceLoader; protected AbstractBeanDefinitionReader( BeanDefinitionRegistry registry); public AbstractBeanDefinitionReader( BeanDefinitionRegistry registry, ResourceLoader resourceLoader); @Override public BeanDefinitionRegistry getRegistry(); @Override public void loadBeanDefinitions( String[] locations) throws BeansException; public void setResourceLoader( ResourceLoader resourceLoader); @Override public ResourceLoader getResourceLoader(); }
jitsi_jitsi
jitsi/modules/impl/protocol-sip/src/main/java/net/java/sip/communicator/impl/protocol/sip/xcap/model/commonpolicy/TransformationsType.java
TransformationsType
getAny
class TransformationsType { /** * The service-permissions element. */ private ProvideServicePermissionType servicePermission; /** * The person-permissions element. */ private ProvidePersonPermissionType personPermission; /** * The device-permissions element. */ private ProvideDevicePermissionType devicePermission; /** * The list of any elements. */ private List<Element> any; /** * Gets the value of the servicePermission property. * * @return the servicePermission property. */ public ProvideServicePermissionType getServicePermission() { return servicePermission; } /** * Sets the value of the servicePermission property. * * @param servicePermission the servicePermission to set. */ public void setServicePermission( ProvideServicePermissionType servicePermission) { this.servicePermission = servicePermission; } /** * Gets the value of the personPermission property. * * @return the personPermission property. */ public ProvidePersonPermissionType getPersonPermission() { return personPermission; } /** * Sets the value of the personPermission property. * * @param personPermission the personPermission to set. */ public void setPersonPermission( ProvidePersonPermissionType personPermission) { this.personPermission = personPermission; } /** * Gets the value of the devicePermission property. * * @return the devicePermission property. */ public ProvideDevicePermissionType getDevicePermission() { return devicePermission; } /** * Sets the value of the devicePermission property. * * @param devicePermission the devicePermission to set. */ public void setDevicePermission( ProvideDevicePermissionType devicePermission) { this.devicePermission = devicePermission; } /** * Gets the value of the any property. * * @return the any property. */ public List<Element> getAny() {<FILL_FUNCTION_BODY>} }
if (any == null) { any = new ArrayList<Element>(); } return any;
548
32
580
jitsi_jitsi
jitsi/modules/service/certificate/src/main/java/net/java/sip/communicator/impl/certificate/CertificateVerificationActivator.java
CertificateVerificationActivator
getResources
class CertificateVerificationActivator extends DependentActivator { /** * The bundle context for this bundle. */ protected static BundleContext bundleContext; /** * The configuration service. */ private static ConfigurationService configService; /** * The service giving access to all resources. */ private static ResourceManagementService resourcesService; /** * The service to store and access passwords. */ private static CredentialsStorageService credService; /** * The service to create and show dialogs for user interaction. */ private static VerifyCertificateDialogService certificateDialogService; public CertificateVerificationActivator() { super( ConfigurationService.class, ResourceManagementService.class, CredentialsStorageService.class ); } /** * Called when this bundle is started. * * @param bc The execution context of the bundle being started. * @throws Exception if the bundle is not correctly started */ @Override public void startWithServices(BundleContext bc) throws Exception { bundleContext = bc; bundleContext.registerService( CertificateService.class, new CertificateServiceImpl(), null); } /** * Returns the <tt>ConfigurationService</tt> obtained from the bundle * context. * @return the <tt>ConfigurationService</tt> obtained from the bundle * context */ public static ConfigurationService getConfigurationService() { if(configService == null) { configService = ServiceUtils.getService( bundleContext, ConfigurationService.class); } return configService; } /** * Returns the <tt>ResourceManagementService</tt>, through which we will * access all resources. * * @return the <tt>ResourceManagementService</tt>, through which we will * access all resources. */ public static ResourceManagementService getResources() {<FILL_FUNCTION_BODY>} /** * Returns the <tt>CredentialsStorageService</tt>, through which we will * access all passwords. * * @return the <tt>CredentialsStorageService</tt>, through which we will * access all passwords. */ public static CredentialsStorageService getCredService() { if (credService == null) { credService = ServiceUtils.getService( bundleContext, CredentialsStorageService.class); } return credService; } /** * Returns the <tt>VerifyCertificateDialogService</tt>, through which we * will use to create dialogs. * * @return the <tt>VerifyCertificateDialogService</tt>, through which we * will use to create dialogs. */ public static VerifyCertificateDialogService getCertificateDialogService() { if (certificateDialogService == null) { certificateDialogService = ServiceUtils.getService( bundleContext, VerifyCertificateDialogService.class); } return certificateDialogService; } /** * Returns service to show authentication window. * @return return service to show authentication window. */ public static AuthenticationWindowService getAuthenticationWindowService() { return ServiceUtils.getService( bundleContext, AuthenticationWindowService.class); } }
if (resourcesService == null) { resourcesService = ServiceUtils.getService( bundleContext, ResourceManagementService.class); } return resourcesService;
883
50
933
/** * 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 ; }
graphhopper_graphhopper
graphhopper/reader-gtfs/src/main/java/com/conveyal/gtfs/model/Calendar.java
Loader
loadOneRow
class Loader extends Entity.Loader<Calendar> { private final Map<String, Service> services; /** * Create a loader. The map parameter should be an in-memory map that will be modified. We can't write directly * to MapDB because we modify services as we load calendar dates, and this creates concurrentmodificationexceptions. */ public Loader(GTFSFeed feed, Map<String, Service> services) { super(feed, "calendar"); this.services = services; } @Override protected boolean isRequired() { return true; } @Override public void loadOneRow() throws IOException {<FILL_FUNCTION_BODY>} }
/* Calendars and Fares are special: they are stored as joined tables rather than simple maps. */ String service_id = getStringField("service_id", true); // TODO service_id can reference either calendar or calendar_dates. Service service = services.computeIfAbsent(service_id, Service::new); if (service.calendar != null) { feed.errors.add(new DuplicateKeyError(tableName, row, "service_id")); } else { Calendar c = new Calendar(); c.sourceFileLine = row + 1; // offset line number by 1 to account for 0-based row index c.service_id = service.service_id; c.monday = getIntField("monday", true, 0, 1); c.tuesday = getIntField("tuesday", true, 0, 1); c.wednesday = getIntField("wednesday", true, 0, 1); c.thursday = getIntField("thursday", true, 0, 1); c.friday = getIntField("friday", true, 0, 1); c.saturday = getIntField("saturday", true, 0, 1); c.sunday = getIntField("sunday", true, 0, 1); // TODO check valid dates c.start_date = getIntField("start_date", true, 18500101, 22001231); c.end_date = getIntField("end_date", true, 18500101, 22001231); c.feed = feed; c.feed_id = feed.feedId; service.calendar = c; }
180
440
620
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-serializer/autoload-cache-serializer-hessian/src/main/java/com/jarvis/cache/serializer/hession/WeakReferenceDeserializer.java
WeakReferenceDeserializer
readObject
class WeakReferenceDeserializer extends AbstractMapDeserializer { @Override public Object readObject(AbstractHessianInput in, Object[] fields) throws IOException {<FILL_FUNCTION_BODY>} protected WeakReference<Object> instantiate() throws Exception { Object obj = new Object(); return new WeakReference<Object>(obj); } }
try { WeakReference<Object> obj = instantiate(); in.addRef(obj); Object value = in.readObject(); obj = null; return new WeakReference<Object>(value); } catch (IOException e) { throw e; } catch (Exception e) { throw new IOExceptionWrapper(e); }
96
94
190
jitsi_jitsi
jitsi/modules/impl/gui/src/main/java/net/java/sip/communicator/impl/gui/main/chat/OutgoingMessageStyle.java
OutgoingMessageStyle
createIndicatorStyle
class OutgoingMessageStyle extends IncomingMessageStyle { /** * The outgoing message background image path. */ private final static String OUTGOING_MESSAGE_IMAGE_PATH = GuiActivator.getResources().getImageURL( "service.gui.lookandfeel.OUTGOING_MESSAGE_BACKGROUND").toString(); /** * The outgoing message right image path. */ private final static String OUTGOING_MESSAGE_IMAGE_RIGHT_PATH = GuiActivator.getResources().getImageURL( "service.gui.lookandfeel.OUTGOING_MESSAGE_BACKGROUND_RIGHT") .toString(); /** * The outgoing message indicator image path. */ private final static String OUTGOING_MESSAGE_INDICATOR_PATH = GuiActivator.getResources().getImageURL( "service.gui.lookandfeel.OUTGOING_MESSAGE_INDICATOR").toString(); /** * The outgoing message round border image path. */ private final static String OUTGOING_MESSAGE_CURVES_PATH = GuiActivator.getResources().getImageURL( "service.gui.lookandfeel.OUTGOING_MESSAGE_CURVES").toString(); /** * The outgoing message top image path. */ private final static String OUTGOING_MESSAGE_CURVES_TOP_PATH = GuiActivator.getResources().getImageURL( "service.gui.lookandfeel.OUTGOING_MESSAGE_CURVES_TOP").toString(); /** * Creates the style of the table bubble (wrapping the message table). * * @return the style of the table bubble */ public static String createTableBubbleStyle() { return "style=\"" + "width:100%;" + " position:relative;" + "\""; } /** * Creates the style of the table bubble right element. * * @return the style of the table bubble right element */ public static String createTableBubbleMessageRightStyle() { return "style=\"" + "width:6px;" + " background-image: url('" + OUTGOING_MESSAGE_IMAGE_RIGHT_PATH+"');" + " background-repeat: repeat-y;" + " background-position: top left;" + "\""; } /** * Creates the style of the message table bubble. * * @return the style of the message table bubble */ public static String createTableBubbleMessageStyle() { return "style=\"" + "font-size:10px;" + " background-image: url('"+OUTGOING_MESSAGE_IMAGE_PATH+"');" + " background-repeat: repeat-y;" + " background-position: top left;" + "\""; } /** * Creates the style of the table buuble bottom left corner. * * @return the style of the table buuble bottom left corner */ public static String createTableBubbleBlStyle() { return "style=\"" + "height:10px;" + " background-image: url('"+OUTGOING_MESSAGE_CURVES_PATH+"');" + " background-repeat: no-repeat;" + " background-position: 0px -20px;" + "\""; } /** * Creates the style of the table buuble bottom right corner. * * @return the style of the table buuble bottom right corner */ public static String createTableBubbleBrStyle() { return "style=\"" + "width:6px;" + " height:10px;" + " background-image: url('"+OUTGOING_MESSAGE_CURVES_PATH+"');" + " background-repeat: no-repeat;" + " background-position: -2999px -20px;" + "\""; } /** * Creates the style of the table buuble top left corner. * * @return the style of the table buuble top left corner */ public static String createTableBubbleTlStyle() { return "style=\"" + "height:23px;" + " background-image: url('" +OUTGOING_MESSAGE_CURVES_TOP_PATH+"');" + " background-repeat: no-repeat;" + " background-position: top left;" + "\""; } /** * Creates the style of the table buuble top right corner. * * @return the style of the table buuble top right corner */ public static String createTableBubbleTrStyle() { return "style=\"" + "width:6px;" + " height:23px;" + " background-image: url('" +OUTGOING_MESSAGE_CURVES_TOP_PATH+"');" + " background-repeat: no-repeat;" + " background-position: -2999px 0px;" + "\""; } /** * Creates the style of the indicator pointing to the avatar image. * * @return the style of the indicator pointing to the avatar image */ public static String createIndicatorStyle() {<FILL_FUNCTION_BODY>} /** * Creates the style of the avatar image. * * @return the style of the avatar image */ public static String createAvatarStyle() { return "style=\"width:26px;" + " height:26px;" + " float:right;\""; } /** * Creates the style of the date. * * @return the style of the date */ public static String createDateStyle() { return "style =\"" + "color:#6a6868;" + " font-size:10px;" + " padding-top:4px;" + " text-align:right;" + "\""; } }
return "style =\"" + "width:9px;" + " height:19px;" + " background-image: url('" +OUTGOING_MESSAGE_INDICATOR_PATH+"');" + " background-repeat: no-repeat;" + " background-position: top left;" + "\"";
1,632
90
1,722
/** * Defines the CSS style of an incoming chat message elements. * @author Yana Stamcheva */ public class IncomingMessageStyle { /** * The incoming message background image path. */ private final static String INCOMING_MESSAGE_IMAGE_PATH=GuiActivator.getResources().getImageURL("service.gui.lookandfeel.INCOMING_MESSAGE_BACKGROUND").toString(); /** * The incoming message right image path. */ private final static String INCOMING_MESSAGE_IMAGE_RIGHT_PATH=GuiActivator.getResources().getImageURL("service.gui.lookandfeel.INCOMING_MESSAGE_BACKGROUND_RIGHT").toString(); /** * The incoming message indicator image path. */ private final static String INCOMING_MESSAGE_INDICATOR_PATH=GuiActivator.getResources().getImageURL("service.gui.lookandfeel.INCOMING_MESSAGE_INDICATOR").toString(); /** * The incoming message round border image path. */ private final static String INCOMING_MESSAGE_CURVES_PATH=GuiActivator.getResources().getImageURL("service.gui.lookandfeel.INCOMING_MESSAGE_CURVES").toString(); /** * The incoming message top image path. */ private final static String INCOMING_MESSAGE_CURVES_TOP_PATH=GuiActivator.getResources().getImageURL("service.gui.lookandfeel.INCOMING_MESSAGE_CURVES_TOP").toString(); /** * The foreground color of history messages. */ private final static String HISTORY_FOREGROUND_COLOR=GuiActivator.getResources().getColorString("service.gui.CHAT_HISTORY_FOREGROUND"); /** * Creates the global message style. * @return the style attribute defining the global message style. */ public static String createMessageStyle(); public static String createSingleMessageStyle( boolean isHistory, boolean isEdited, boolean isSimpleTheme); /** * Creates the style of the table bubble right element. * @return the style of the table bubble right element */ public static String createTableBubbleMessageRightStyle(); /** * Creates the style of the table bubble (wrapping the message table). * @return the style of the table bubble */ public static String createTableBubbleStyle(); /** * Creates the style of the message table bubble. * @return the style of the message table bubble */ public static String createTableBubbleMessageStyle(); /** * Creates the style of the table buuble bottom left corner. * @return the style of the table buuble bottom left corner */ public static String createTableBubbleBlStyle(); /** * Creates the style of the table buuble bottom right corner. * @return the style of the table buuble bottom right corner */ public static String createTableBubbleBrStyle(); /** * Creates the style of the table buuble top left corner. * @return the style of the table buuble top left corner */ public static String createTableBubbleTlStyle(); /** * Creates the style of the table buuble top right corner. * @return the style of the table buuble top right corner */ public static String createTableBubbleTrStyle(); /** * Creates the style of the indicator pointing to the avatar image. * @return the style of the indicator pointing to the avatar image */ public static String createIndicatorStyle(); /** * Creates the style of the avatar image. * @return the style of the avatar image */ public static String createAvatarStyle(); /** * Creates the header style. * @return the header style. */ public static String createHeaderStyle(); }
logfellow_logstash-logback-encoder
logstash-logback-encoder/src/main/java/net/logstash/logback/composite/AbstractCompositeJsonFormatter.java
DisconnectedOutputStream
decorateGenerator
class DisconnectedOutputStream extends ProxyOutputStream { DisconnectedOutputStream() { super(null); } public void connect(OutputStream out) { this.delegate = out; } public void disconnect() { this.delegate = null; } } private JsonFactory createJsonFactory() { ObjectMapper objectMapper = new ObjectMapper() /* * Assume empty beans are ok. */ .disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); if (findAndRegisterJacksonModules) { try { objectMapper.findAndRegisterModules(); } catch (ServiceConfigurationError serviceConfigurationError) { addError("Error occurred while dynamically loading jackson modules", serviceConfigurationError); } } return decorateFactory(objectMapper.getFactory()); } private JsonFactory decorateFactory(JsonFactory factory) { JsonFactory factoryToDecorate = factory /* * When generators are flushed, don't flush the underlying outputStream. * * This allows some streaming optimizations when using an encoder. * * The encoder generally determines when the stream should be flushed * by an 'immediateFlush' property. * * The 'immediateFlush' property of the encoder can be set to false * when the appender performs the flushes at appropriate times * (such as the end of a batch in the AbstractLogstashTcpSocketAppender). * * Set this prior to decorating, because some generators require * FLUSH_PASSED_TO_STREAM to work properly (e.g. YAML) */ .disable(JsonGenerator.Feature.FLUSH_PASSED_TO_STREAM); return this.jsonFactoryDecorator.decorate(factoryToDecorate) /* * Jackson buffer recycling works by maintaining a pool of buffers per thread. This * feature works best when one JsonGenerator is created per thread, typically in J2EE * environments. * * Each JsonFormatter uses its own instance of JsonGenerator and is reused multiple times * possibly on different threads. The memory buffers allocated by the JsonGenerator do * not belong to a particular thread - hence the recycling feature should be disabled. */ .disable(Feature.USE_THREAD_LOCAL_FOR_BUFFER_RECYCLING); } protected void writeEventToGenerator(JsonGenerator generator, Event event) throws IOException { generator.writeStartObject(); jsonProviders.writeTo(generator, event); generator.writeEndObject(); generator.flush(); } protected void prepareForDeferredProcessing(Event event) { event.prepareForDeferredProcessing(); jsonProviders.prepareForDeferredProcessing(event); } private JsonGenerator createGenerator(OutputStream outputStream) throws IOException { return decorateGenerator(jsonFactory.createGenerator(outputStream, encoding)); } private JsonGenerator decorateGenerator(JsonGenerator generator) {<FILL_FUNCTION_BODY>
JsonGenerator decorated = jsonGeneratorDecorator.decorate(new SimpleObjectJsonGeneratorDelegate(generator)) /* * Don't let the json generator close the underlying outputStream and let the * encoder managed it. */ .disable(JsonGenerator.Feature.AUTO_CLOSE_TARGET); try { decorated = decorated /* * JsonGenerator are reused to serialize multiple log events. * Change the default root value separator to an empty string instead of a single space. */ .setRootValueSeparator(new SerializedString(CoreConstants.EMPTY_STRING)); } catch (UnsupportedOperationException e) { /* * Ignore. * Some generators do not support setting the rootValueSeparator. */ } return decorated;
772
201
973
orientechnologies_orientdb
orientdb/core/src/main/java/com/orientechnologies/orient/core/command/traverse/OTraverseContext.java
OTraverseContext
addTraversed
class OTraverseContext extends OBasicCommandContext { private Memory memory = new StackMemory(); private Set<ORID> history = new HashSet<ORID>(); private OTraverseAbstractProcess<?> currentProcess; public void push(final OTraverseAbstractProcess<?> iProcess) { memory.add(iProcess); } public Map<String, Object> getVariables() { final HashMap<String, Object> map = new HashMap<String, Object>(); map.put("depth", getDepth()); map.put("path", getPath()); map.put("stack", memory.getUnderlying()); // DELEGATE map.putAll(super.getVariables()); return map; } public Object getVariable(final String iName) { final String name = iName.trim().toUpperCase(Locale.ENGLISH); if ("DEPTH".startsWith(name)) return getDepth(); else if (name.startsWith("PATH")) return ODocumentHelper.getFieldValue(getPath(), iName.substring("PATH".length())); else if (name.startsWith("STACK")) { Object result = ODocumentHelper.getFieldValue(memory.getUnderlying(), iName.substring("STACK".length())); if (result instanceof ArrayDeque) { result = ((ArrayDeque) result).clone(); } return result; } else if (name.startsWith("HISTORY")) return ODocumentHelper.getFieldValue(history, iName.substring("HISTORY".length())); else // DELEGATE return super.getVariable(iName); } public void pop(final OIdentifiable currentRecord) { if (currentRecord != null) { final ORID rid = currentRecord.getIdentity(); if (!history.remove(rid)) OLogManager.instance().warn(this, "Element '" + rid + "' not found in traverse history"); } try { memory.dropFrame(); } catch (NoSuchElementException e) { throw new IllegalStateException("Traverse stack is empty", e); } } public OTraverseAbstractProcess<?> next() { currentProcess = memory.next(); return currentProcess; } public boolean isEmpty() { return memory.isEmpty(); } public void reset() { memory.clear(); } public boolean isAlreadyTraversed(final OIdentifiable identity, final int iLevel) { if (history.contains(identity.getIdentity())) return true; // final int[] l = history.get(identity.getIdentity()); // if (l == null) // return false; // // for (int i = 0; i < l.length && l[i] > -1; ++i) // if (l[i] == iLevel) // return true; return false; } public void addTraversed(final OIdentifiable identity, final int iLevel) {<FILL_FUNCTION_BODY>} public String getPath() { return currentProcess == null ? "" : currentProcess.getPath().toString(); } public int getDepth() { return currentProcess == null ? 0 : currentProcess.getPath().getDepth(); } public void setStrategy(final OTraverse.STRATEGY strategy) { if (strategy == OTraverse.STRATEGY.BREADTH_FIRST) memory = new QueueMemory(memory); else memory = new StackMemory(memory); } private interface Memory { void add(OTraverseAbstractProcess<?> iProcess); OTraverseAbstractProcess<?> next(); void dropFrame(); void clear(); Collection<OTraverseAbstractProcess<?>> getUnderlying(); boolean isEmpty(); } private abstract static class AbstractMemory implements Memory { protected final Deque<OTraverseAbstractProcess<?>> deque; public AbstractMemory() { deque = new ArrayDeque<OTraverseAbstractProcess<?>>(); } public AbstractMemory(final Memory memory) { deque = new ArrayDeque<OTraverseAbstractProcess<?>>(memory.getUnderlying()); } @Override public OTraverseAbstractProcess<?> next() { return deque.peek(); } @Override public void dropFrame() { deque.removeFirst(); } @Override public void clear() { deque.clear(); } @Override public boolean isEmpty() { return deque.isEmpty(); } @Override public Collection<OTraverseAbstractProcess<?>> getUnderlying() { return deque; } } private static class StackMemory extends AbstractMemory { public StackMemory() { super(); } public StackMemory(final Memory memory) { super(memory); } @Override public void add(final OTraverseAbstractProcess<?> iProcess) { deque.push(iProcess); } } private static class QueueMemory extends AbstractMemory { public QueueMemory(final Memory memory) { super(memory); } @Override public void add(final OTraverseAbstractProcess<?> iProcess) { deque.addLast(iProcess); } public ODatabaseSession getDatabase() { return ODatabaseRecordThreadLocal.instance().getIfDefined(); } } }
history.add(identity.getIdentity()); // final int[] l = history.get(identity.getIdentity()); // if (l == null) { // final int[] array = new int[BUCKET_SIZE]; // array[0] = iLevel; // Arrays.fill(array, 1, BUCKET_SIZE, -1); // history.put(identity.getIdentity(), array); // } else { // if (l[l.length - 1] > -1) { // // ARRAY FULL, ENLARGE IT // final int[] array = Arrays.copyOf(l, l.length + BUCKET_SIZE); // array[l.length] = iLevel; // Arrays.fill(array, l.length + 1, array.length, -1); // history.put(identity.getIdentity(), array); // } else { // for (int i = l.length - 2; i >= 0; --i) { // if (l[i] > -1) { // l[i + 1] = iLevel; // break; // } // } // } // }
1,422
298
1,720
/** * Basic implementation of OCommandContext interface that stores variables in a map. Supports parent/child context to build a tree of contexts. If a variable is not found on current object the search is applied recursively on child contexts. * @author Luca Garulli (l.garulli--(at)--orientdb.com) */ public class OBasicCommandContext implements OCommandContext { public static final String EXECUTION_BEGUN="EXECUTION_BEGUN"; public static final String TIMEOUT_MS="TIMEOUT_MS"; public static final String TIMEOUT_STRATEGY="TIMEOUT_STARTEGY"; public static final String INVALID_COMPARE_COUNT="INVALID_COMPARE_COUNT"; protected ODatabaseSession database; protected Object[] args; protected boolean recordMetrics=false; protected OCommandContext parent; protected OCommandContext child; protected Map<String,Object> variables; protected Map<Object,Object> inputParameters; protected Set<String> declaredScriptVariables=new HashSet<>(); private long executionStartedOn; private long timeoutMs; private com.orientechnologies.orient.core.command.OCommandContext.TIMEOUT_STRATEGY timeoutStrategy; protected AtomicLong resultsProcessed=new AtomicLong(0); protected Set<Object> uniqueResult=new HashSet<Object>(); private Map<OExecutionStep,OStepStats> stepStats=new IdentityHashMap<>(); private LinkedList<OStepStats> currentStepStats=new LinkedList<>(); public OBasicCommandContext(); public OBasicCommandContext( ODatabaseSession session); public Object getVariable( String iName); public Object getVariable( String iName, final Object iDefault); private Object resolveValue( Object value); protected Object getVariableFromParentHierarchy( String varName); public OCommandContext setDynamicVariable( String iName, final ODynamicVariable iValue); public OCommandContext setVariable( String iName, final Object iValue); boolean hasVariable( String iName); @Override public OCommandContext incrementVariable( String iName); public long updateMetric( final String iName, final long iValue); /** * Returns a read-only map with all the variables. */ public Map<String,Object> getVariables(); /** * Set the inherited context avoiding to copy all the values every time. * @return */ public OCommandContext setChild( final OCommandContext iContext); public OCommandContext getParent(); public OCommandContext setParent( final OCommandContext iParentContext); public OCommandContext setParentWithoutOverridingChild( final OCommandContext iParentContext); @Override public String toString(); public boolean isRecordingMetrics(); public OCommandContext setRecordingMetrics( final boolean recordMetrics); @Override public void beginExecution( final long iTimeout, final TIMEOUT_STRATEGY iStrategy); public boolean checkTimeout(); @Override public OCommandContext copy(); @Override public void merge(final OCommandContext iContext); private void init(); public Map<Object,Object> getInputParameters(); public void setInputParameters(Map<Object,Object> inputParameters); /** * returns the number of results processed. This is intended to be used with LIMIT in SQL statements * @return */ public AtomicLong getResultsProcessed(); /** * adds an item to the unique result set * @param o the result item to add * @return true if the element is successfully added (it was not present yet), false otherwise (itwas already present) */ public synchronized boolean addToUniqueResult(Object o); public ODatabaseSession getDatabase(); public void setDatabase(ODatabaseSession database); @Override public void declareScriptVariable(String varName); @Override public boolean isScriptVariableDeclared(String varName); public void startProfiling(OExecutionStep step); public void endProfiling(OExecutionStep step); @Override public OStepStats getStats(OExecutionStep step); }
orientechnologies_orientdb
orientdb/client/src/main/java/com/orientechnologies/orient/client/remote/message/OSubscribeLiveQueryRequest.java
OSubscribeLiveQueryRequest
write
class OSubscribeLiveQueryRequest implements OBinaryRequest<OSubscribeLiveQueryResponse> { private String query; private Map<String, Object> params; private boolean namedParams; public OSubscribeLiveQueryRequest(String query, Map<String, Object> params) { this.query = query; this.params = params; this.namedParams = true; } public OSubscribeLiveQueryRequest(String query, Object[] params) { this.query = query; this.params = OStorageRemote.paramsArrayToParamsMap(params); this.namedParams = false; } public OSubscribeLiveQueryRequest() {} @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 { this.query = channel.readString(); ODocument paramsDoc = new ODocument(); byte[] bytes = channel.readBytes(); serializer.fromStream(bytes, paramsDoc, null); this.params = paramsDoc.field("params"); this.namedParams = channel.readBoolean(); } @Override public byte getCommand() { return OChannelBinaryProtocol.SUBSCRIBE_PUSH_LIVE_QUERY; } @Override public OSubscribeLiveQueryResponse createResponse() { return new OSubscribeLiveQueryResponse(); } @Override public OBinaryResponse execute(OBinaryRequestExecutor executor) { return executor.executeSubscribeLiveQuery(this); } @Override public String getDescription() { return null; } public String getQuery() { return query; } public Map<String, Object> getParams() { return params; } }
ORecordSerializerNetworkV37Client serializer = new ORecordSerializerNetworkV37Client(); network.writeString(query); // params ODocument parms = new ODocument(); parms.field("params", this.params); byte[] bytes = OMessageHelper.getRecordBytes(parms, serializer); network.writeBytes(bytes); network.writeBoolean(namedParams);
483
103
586
pmd_pmd
pmd/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/LexException.java
LexException
makeReason
class LexException extends FileAnalysisException { private final int line; private final int column; /** * Create a new exception. * * @param line Line number * @param column Column number * @param filename Filename. If unknown, it can be completed with {@link #setFileId(FileId)}} later * @param message Message of the error * @param cause Cause of the error, if any */ public LexException(int line, int column, @Nullable FileId filename, String message, @Nullable Throwable cause) { super(message, cause); this.line = max(line, 1); this.column = max(column, 1); if (filename != null) { super.setFileId(filename); } } /** * Constructor called by JavaCC. * * @apiNote Internal API. */ LexException(boolean eofSeen, String lexStateName, int errorLine, int errorColumn, String errorAfter, char curChar) { super(makeReason(eofSeen, lexStateName, errorAfter, curChar)); line = max(errorLine, 1); column = max(errorColumn, 1); } public int getLine() { return line; } public int getColumn() { return column; } @Override protected @NonNull FileLocation location() { return FileLocation.caret(getFileId(), line, column); } @Override protected String errorKind() { return "Lexical error"; } /** * Replace the file name of this error. * * @param fileId New filename * * @return A new exception */ @Override public LexException setFileId(FileId fileId) { super.setFileId(fileId); return this; } private static String makeReason(boolean eofseen, String lexStateName, String errorAfter, char curChar) {<FILL_FUNCTION_BODY>} }
String message; if (eofseen) { message = "<EOF> "; } else { message = "\"" + StringUtil.escapeJava(String.valueOf(curChar)) + "\"" + " (" + (int) curChar + "), "; } message += "after : \"" + StringUtil.escapeJava(errorAfter) + "\" (in lexical state " + lexStateName + ")"; return message;
534
115
649
/** * An exception that occurs while processing a file. Subtypes include <ul> <li> {@link LexException}: lexical syntax errors <li> {@link ParseException}: syntax errors <li> {@link SemanticException}: exceptions occurring after the parsing phase, because the source code is semantically invalid </ul> */ public class FileAnalysisException extends RuntimeException { private FileId fileId=FileId.UNKNOWN; public FileAnalysisException(); public FileAnalysisException( String message); public FileAnalysisException( Throwable cause); public FileAnalysisException( String message, Throwable cause); public FileAnalysisException setFileId( FileId fileId); protected boolean hasFileName(); /** * The name of the file in which the error occurred. */ public @NonNull FileId getFileId(); @Override public final String getMessage(); protected String errorKind(); protected @Nullable FileLocation location(); private String positionToString(); /** * Wraps the cause into an analysis exception. If it is itself an analysis exception, just returns it after setting the filename for context. * @param fileId Filename * @param message Context message, if the cause is not a {@link FileAnalysisException} * @param cause Exception to wrap * @return An exception */ public static FileAnalysisException wrap( @NonNull FileId fileId, @NonNull String message, @NonNull Throwable cause); }
joelittlejohn_jsonschema2pojo
jsonschema2pojo/jsonschema2pojo-core/src/main/java/org/jsonschema2pojo/rules/RequiredArrayRule.java
RequiredArrayRule
updateGetterSetterJavaDoc
class RequiredArrayRule implements Rule<JDefinedClass, JDefinedClass> { private final RuleFactory ruleFactory; public static final String REQUIRED_COMMENT_TEXT = "\n(Required)"; protected RequiredArrayRule(RuleFactory ruleFactory) { this.ruleFactory = ruleFactory; } @Override public JDefinedClass apply(String nodeName, JsonNode node, JsonNode parent, JDefinedClass jclass, Schema schema) { List<String> requiredFieldMethods = new ArrayList<>(); JsonNode properties = schema.getContent().get("properties"); for (Iterator<JsonNode> iterator = node.elements(); iterator.hasNext(); ) { String requiredArrayItem = iterator.next().asText(); if (requiredArrayItem.isEmpty()) { continue; } JsonNode propertyNode = null; if (properties != null) { propertyNode = properties.findValue(requiredArrayItem); } String fieldName = ruleFactory.getNameHelper().getPropertyName(requiredArrayItem, propertyNode); JFieldVar field = jclass.fields().get(fieldName); if (field == null) { continue; } addJavaDoc(field); if (ruleFactory.getGenerationConfig().isIncludeJsr303Annotations()) { addNotNullAnnotation(field); } if (ruleFactory.getGenerationConfig().isIncludeJsr305Annotations()) { addNonnullAnnotation(field); } requiredFieldMethods.add(getGetterName(fieldName, field.type(), node)); requiredFieldMethods.add(getSetterName(fieldName, node)); } updateGetterSetterJavaDoc(jclass, requiredFieldMethods); return jclass; } private void updateGetterSetterJavaDoc(JDefinedClass jclass, List<String> requiredFieldMethods) {<FILL_FUNCTION_BODY>} private void addNotNullAnnotation(JFieldVar field) { final Class<? extends Annotation> notNullClass = ruleFactory.getGenerationConfig().isUseJakartaValidation() ? NotNull.class : javax.validation.constraints.NotNull.class; field.annotate(notNullClass); } private void addNonnullAnnotation(JFieldVar field) { field.annotate(Nonnull.class); } private void addJavaDoc(JDocCommentable docCommentable) { JDocComment javadoc = docCommentable.javadoc(); javadoc.append(REQUIRED_COMMENT_TEXT); } private String getSetterName(String propertyName, JsonNode node) { return ruleFactory.getNameHelper().getSetterName(propertyName, node); } private String getGetterName(String propertyName, JType type, JsonNode node) { return ruleFactory.getNameHelper().getGetterName(propertyName, type, node); } }
for (Iterator<JMethod> methods = jclass.methods().iterator(); methods.hasNext();) { JMethod method = methods.next(); if (requiredFieldMethods.contains(method.name())) { addJavaDoc(method); } }
755
67
822
ainilili_ratel
ratel/landlords-client/src/main/java/org/nico/ratel/landlords/client/SimpleClient.java
SimpleClient
main
class SimpleClient { public static int id = -1; public final static String VERSION = Features.VERSION_1_3_0; public static String serverAddress; public static int port = 1024; public static String protocol = "pb"; private final static String[] serverAddressSource = new String[]{ "https://raw.githubusercontent.com/ainilili/ratel/master/serverlist.json", //Source "https://cdn.jsdelivr.net/gh/ainilili/ratel@master/serverlist.json", //CN CDN "https://raw.fastgit.org/ainilili/ratel/master/serverlist.json", //HongKong CDN "https://cdn.staticaly.com/gh/ainilili/ratel/master/serverlist.json", //Japanese CDN "https://ghproxy.com/https://raw.githubusercontent.com/ainilili/ratel/master/serverlist.json", //Korea CDN "https://gitee.com/ainilili/ratel/raw/master/serverlist.json" //CN Gitee }; public static void main(String[] args) throws InterruptedException, IOException, URISyntaxException {<FILL_FUNCTION_BODY>} private static List<String> getServerAddressList() { for (String serverAddressSource : serverAddressSource) { try { String serverInfo = StreamUtils.convertToString(new URL(serverAddressSource)); return Noson.convert(serverInfo, new NoType<List<String>>() {}); } catch (IOException e) { SimplePrinter.printNotice("Try connected " + serverAddressSource + " failed: " + e.getMessage()); } } return null; } }
if (args != null && args.length > 0) { for (int index = 0; index < args.length; index = index + 2) { if (index + 1 < args.length) { if (args[index].equalsIgnoreCase("-p") || args[index].equalsIgnoreCase("-port")) { port = Integer.parseInt(args[index + 1]); } if (args[index].equalsIgnoreCase("-h") || args[index].equalsIgnoreCase("-host")) { serverAddress = args[index + 1]; } if (args[index].equalsIgnoreCase("-ptl") || args[index].equalsIgnoreCase("-protocol")) { protocol = args[index + 1]; } } } } if (serverAddress == null) { List<String> serverAddressList = getServerAddressList(); if (serverAddressList == null || serverAddressList.size() == 0) { throw new RuntimeException("Please use '-host' to setting server address."); } SimplePrinter.printNotice("Please select a server:"); for (int i = 0; i < serverAddressList.size(); i++) { SimplePrinter.printNotice((i + 1) + ". " + serverAddressList.get(i)); } int serverPick = Integer.parseInt(SimpleWriter.write(User.INSTANCE.getNickname(), "option")); while (serverPick < 1 || serverPick > serverAddressList.size()) { try { SimplePrinter.printNotice("The server address does not exist!"); serverPick = Integer.parseInt(SimpleWriter.write(User.INSTANCE.getNickname(), "option")); } catch (NumberFormatException ignore) {} } serverAddress = serverAddressList.get(serverPick - 1); String[] elements = serverAddress.split(":"); serverAddress = elements[0]; port = Integer.parseInt(elements[1]); } if (Objects.equals(protocol, "pb")) { new ProtobufProxy().connect(serverAddress, port); } else if (Objects.equals(protocol, "ws")) { new WebsocketProxy().connect(serverAddress, port + 1); } else { throw new UnsupportedOperationException("Unsupported protocol " + protocol); }
452
598
1,050
pmd_pmd
pmd/pmd-core/src/main/java/net/sourceforge/pmd/cpd/VSRenderer.java
VSRenderer
render
class VSRenderer implements CPDReportRenderer { @Override public void render(CPDReport report, Writer writer) throws IOException {<FILL_FUNCTION_BODY>} }
for (Match match: report.getMatches()) { for (Mark mark : match) { FileLocation loc = mark.getLocation(); writer.append(report.getDisplayName(loc.getFileId())) .append('(').append(String.valueOf(loc.getStartLine())).append("):") .append(" Between lines ").append(String.valueOf(loc.getStartLine())) .append(" and ").append(String.valueOf(loc.getEndLine())) .append(System.lineSeparator()); } } writer.flush();
49
147
196
Kong_unirest-java
unirest-java/unirest-modules-mocks/src/main/java/kong/unirest/core/MockListener.java
MockListener
assertIsClosed
class MockListener implements WebSocket.Listener { private List<Message> messagesReceived = new ArrayList<>(); private ByteBuffer ping; private ByteBuffer pong; private boolean open = false; private int closedStatus; private String closedMessage; @Override public void onOpen(WebSocket webSocket) { open = true; WebSocket.Listener.super.onOpen(webSocket); } @Override public CompletionStage<?> onText(WebSocket webSocket, CharSequence data, boolean last) { messagesReceived.add(new Message(String.valueOf(data), last)); return WebSocket.Listener.super.onText(webSocket, data, last); } @Override public CompletionStage<?> onBinary(WebSocket webSocket, ByteBuffer data, boolean last) { messagesReceived.add(new Message(data, last)); return WebSocket.Listener.super.onBinary(webSocket, data, last); } @Override public CompletionStage<?> onPing(WebSocket webSocket, ByteBuffer message) { ping = message; webSocket.sendPong(message); return WebSocket.Listener.super.onPing(webSocket, message); } @Override public CompletionStage<?> onPong(WebSocket webSocket, ByteBuffer message) { this.pong = message; return WebSocket.Listener.super.onPong(webSocket, message); } @Override public CompletionStage<?> onClose(WebSocket webSocket, int statusCode, String reason) { open = false; closedStatus = statusCode; closedMessage = reason; return WebSocket.Listener.super.onClose(webSocket, statusCode, reason); } @Override public void onError(WebSocket webSocket, Throwable error) { WebSocket.Listener.super.onError(webSocket, error); } public void assertReceivedMessage(Object message, boolean last) { if(!messagesReceived.stream().anyMatch(e -> Objects.equals(e.data, message) && Objects.equals(e.last, last))){ throw new UnirestAssertion("Did not receive any message: [%s : %s] ", message, last); } } public void assertIsClosed(int status, String message) {<FILL_FUNCTION_BODY>} /** * assert that a ping message was received. * Note that the onPing method will automatically send a pong to the WebSocket * @param message the message */ public void assertPing(ByteBuffer message) { if(!Objects.equals(ping, message)){ throw new UnirestAssertion("Expected Ping Call with buffer %s but got %s", message, ping); } } /** * assert that a pong message was received. * Note that the onPing method will automatically send a pong to the WebSocket * @param message the message */ public void assertPong(ByteBuffer message) { if(!message.equals(pong)){ throw new UnirestAssertion("Expected Pong Message %s but got %s", message, pong); } } public void assertIsOpen() { if(!open){ throw new UnirestAssertion("Expected socket to be open but was closed."); } } private class Message { private final Object data; private final boolean last; public Message(Object data, boolean last) { this.data = data; this.last = last; } } }
if(open){ throw new UnirestAssertion("Expected to be closed but was not"); } else if (closedStatus != status || !Objects.equals(closedMessage, message)){ throw new UnirestAssertion("Incorrect Closed Status/Message. Expected [%s : %s] but got [%s : %s]", status, message, closedStatus, closedMessage); }
915
101
1,016
DerekYRC_mini-spring
mini-spring/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java
AbstractBeanFactory
getObjectForBeanInstance
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 { Object sharedInstance = getSingleton(name); if (sharedInstance != null) { //如果是FactoryBean,从FactoryBean#getObject中创建bean return getObjectForBeanInstance(sharedInstance, name); } BeanDefinition beanDefinition = getBeanDefinition(name); Object bean = createBean(name, beanDefinition); return getObjectForBeanInstance(bean, name); } /** * 如果是FactoryBean,从FactoryBean#getObject中创建bean * * @param beanInstance * @param beanName * @return */ protected Object getObjectForBeanInstance(Object beanInstance, String beanName) {<FILL_FUNCTION_BODY>} @Override public <T> T getBean(String name, Class<T> requiredType) throws BeansException { return ((T) getBean(name)); } @Override public boolean containsBean(String name) { return containsBeanDefinition(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) { //有则覆盖 this.beanPostProcessors.remove(beanPostProcessor); this.beanPostProcessors.add(beanPostProcessor); } public List<BeanPostProcessor> getBeanPostProcessors() { return this.beanPostProcessors; } public void addEmbeddedValueResolver(StringValueResolver valueResolver) { this.embeddedValueResolvers.add(valueResolver); } public String resolveEmbeddedValue(String value) { String result = value; for (StringValueResolver resolver : this.embeddedValueResolvers) { result = resolver.resolveStringValue(result); } return result; } @Override public ConversionService getConversionService() { return conversionService; } @Override public void setConversionService(ConversionService conversionService) { this.conversionService = conversionService; } }
Object object = beanInstance; if (beanInstance instanceof FactoryBean) { FactoryBean factoryBean = (FactoryBean) beanInstance; try { if (factoryBean.isSingleton()) { //singleton作用域bean,从缓存中获取 object = this.factoryBeanObjectCache.get(beanName); if (object == null) { object = factoryBean.getObject(); this.factoryBeanObjectCache.put(beanName, object); } } else { //prototype作用域bean,新创建bean object = factoryBean.getObject(); } } catch (Exception ex) { throw new BeansException("FactoryBean threw exception on object[" + beanName + "] creation", ex); } } return object;
653
202
855
/** * @author derekyi * @date 2020/11/22 */ public class DefaultSingletonBeanRegistry implements SingletonBeanRegistry { /** * 一级缓存 */ private Map<String,Object> singletonObjects=new HashMap<>(); /** * 二级缓存 */ private Map<String,Object> earlySingletonObjects=new HashMap<>(); /** * 三级缓存 */ private Map<String,ObjectFactory<?>> singletonFactories=new HashMap<String,ObjectFactory<?>>(); private final Map<String,DisposableBean> disposableBeans=new HashMap<>(); @Override public Object getSingleton( String beanName); @Override public void addSingleton( String beanName, Object singletonObject); protected void addSingletonFactory( String beanName, ObjectFactory<?> singletonFactory); public void registerDisposableBean( String beanName, DisposableBean bean); public void destroySingletons(); }
javamelody_javamelody
javamelody/javamelody-core/src/main/java/net/bull/javamelody/internal/model/PID.java
PID
getPIDFromOS
class PID { private PID() { super(); } /** * @return PID du process java */ public static String getPID() { String pid = System.getProperty("pid"); if (pid == null) { // first, reliable with sun jdk (http://golesny.de/wiki/code:javahowtogetpid) final RuntimeMXBean rtb = ManagementFactory.getRuntimeMXBean(); final String processName = rtb.getName(); /* tested on: */ /* - windows xp sp 2, java 1.5.0_13 */ /* - mac os x 10.4.10, java 1.5.0 */ /* - debian linux, java 1.5.0_13 */ /* all return pid@host, e.g 2204@antonius */ if (processName.indexOf('@') != -1) { pid = processName.substring(0, processName.indexOf('@')); } else { pid = getPIDFromOS(); } System.setProperty("pid", pid); } return pid; } static String getPIDFromOS() {<FILL_FUNCTION_BODY>} private static void extractGetPid(File tempFile) throws IOException { try (InputStream input = PID.class .getResourceAsStream("/net/bull/javamelody/resource/getpids.exe")) { InputOutput.pumpToFile(input, tempFile); } } }
String pid; // following is not always reliable as is (for example, see issue 3 on solaris 10 // or http://blog.igorminar.com/2007/03/how-java-application-can-discover-its.html) // Author: Santhosh Kumar T, https://github.com/santhosh-tekuri/jlibs, licence LGPL // Author getpids.exe: Daniel Scheibli, http://www.scheibli.com/projects/getpids/index.html, licence GPL final String[] cmd; File tempFile = null; Process process = null; try { try { if (!System.getProperty("os.name").toLowerCase(Locale.ENGLISH) .contains("windows")) { cmd = new String[] { "/bin/sh", "-c", "echo $$ $PPID" }; } else { // getpids.exe is taken from http://www.scheibli.com/projects/getpids/index.html (GPL) tempFile = File.createTempFile("getpids", ".exe"); // extract the embedded getpids.exe file from the jar and save it to above file extractGetPid(tempFile); cmd = new String[] { tempFile.getAbsolutePath() }; } process = Runtime.getRuntime().exec(cmd); final String processOutput = InputOutput.pumpToString(process.getInputStream(), Charset.defaultCharset()); final StringTokenizer stok = new StringTokenizer(processOutput); stok.nextToken(); // this is pid of the process we spanned pid = stok.nextToken(); // waitFor nécessaire sous windows server 2003 // (sinon le fichier temporaire getpidsxxx.exe n'est pas effacé) process.waitFor(); } finally { if (process != null) { // évitons http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6462165 process.getInputStream().close(); process.getOutputStream().close(); process.getErrorStream().close(); process.destroy(); } if (tempFile != null && !tempFile.delete()) { tempFile.deleteOnExit(); } } } catch (final InterruptedException | IOException e) { pid = e.toString(); } return pid;
440
695
1,135
jitsi_jitsi
jitsi/modules/impl/protocol-irc/src/main/java/net/java/sip/communicator/impl/protocol/irc/ProtocolIconIrcImpl.java
ProtocolIconIrcImpl
getImageInBytes
class ProtocolIconIrcImpl implements ProtocolIcon { /** * The <tt>Logger</tt> used by the <tt>ProtocolIconIrcImpl</tt> class and * its instances for logging output. */ private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ProtocolIconIrcImpl.class); /** * A hash table containing the protocol icon in different sizes. */ private static final Map<String, byte[]> ICONS_TABLE = new HashMap<>(); static { ICONS_TABLE.put(ProtocolIcon.ICON_SIZE_16x16, getImageInBytes("service.protocol.irc.IRC_16x16")); ICONS_TABLE.put(ProtocolIcon.ICON_SIZE_32x32, getImageInBytes("service.protocol.irc.IRC_32x32")); ICONS_TABLE.put(ProtocolIcon.ICON_SIZE_48x48, getImageInBytes("service.protocol.irc.IRC_48x48")); ICONS_TABLE.put(ProtocolIcon.ICON_SIZE_64x64, getImageInBytes("service.protocol.irc.IRC_64x64")); } /** * A hash table containing the path to the protocol icon in different sizes. */ private static final Map<String, String> ICONPATHS_TABLE = new HashMap<>(); static { ResourceManagementService res = IrcActivator.getResources(); if (res == null) { ICONPATHS_TABLE.put(ProtocolIcon.ICON_SIZE_16x16, null); ICONPATHS_TABLE.put(ProtocolIcon.ICON_SIZE_32x32, null); ICONPATHS_TABLE.put(ProtocolIcon.ICON_SIZE_48x48, null); ICONPATHS_TABLE.put(ProtocolIcon.ICON_SIZE_64x64, null); } else { ICONPATHS_TABLE.put(ProtocolIcon.ICON_SIZE_16x16, res.getImagePath( "service.protocol.irc.IRC_16x16")); ICONPATHS_TABLE.put(ProtocolIcon.ICON_SIZE_32x32, res.getImagePath( "service.protocol.irc.IRC_32x32")); ICONPATHS_TABLE.put(ProtocolIcon.ICON_SIZE_48x48, res.getImagePath( "service.protocol.irc.IRC_48x48")); ICONPATHS_TABLE.put(ProtocolIcon.ICON_SIZE_64x64, res.getImagePath( "service.protocol.irc.IRC_64x64")); } } /** * Implements the <tt>ProtocolIcon.getSupportedSizes()</tt> method. Returns * an iterator to a set containing the supported icon sizes. * * @return an iterator to a set containing the supported icon sizes */ public Iterator<String> getSupportedSizes() { return ICONS_TABLE.keySet().iterator(); } /** * Returns TRUE if a icon with the given size is supported, FALSE-otherwise. * * @param iconSize the icon size; one of ICON_SIZE_XXX constants * @return returns <tt>true</tt> if size is supported or <tt>false</tt> if * not. */ public boolean isSizeSupported(final String iconSize) { return ICONS_TABLE.containsKey(iconSize); } /** * Returns the icon image in the given size. * * @param iconSize the icon size; one of ICON_SIZE_XXX constants * @return returns icon image */ public byte[] getIcon(final String iconSize) { return ICONS_TABLE.get(iconSize); } /** * Returns a path to the icon with the given size. * * @param iconSize the icon size; one of ICON_SIZE_XXX constants * @return the path to the icon with the given size */ public String getIconPath(final String iconSize) { return ICONPATHS_TABLE.get(iconSize); } /** * Returns the icon image used to represent the protocol connecting state. * * @return the icon image used to represent the protocol connecting state */ public byte[] getConnectingIcon() { return getImageInBytes("ircConnectingIcon"); } /** * Returns the byte representation of the image corresponding to the given * identifier. * * @param imageID the identifier of the image * @return the byte representation of the image corresponding to the given * identifier. */ static byte[] getImageInBytes(final String imageID) {<FILL_FUNCTION_BODY>} }
ResourceManagementService res = IrcActivator.getResources(); if (res == null) { return null; } InputStream in = res.getImageInputStream(imageID); byte[] image = null; if (in != null) { try { image = new byte[in.available()]; in.read(image); } catch (IOException e) { logger.error("Failed to load image:" + imageID, e); } } return image;
1,305
142
1,447
spring-cloud_spring-cloud-gateway
spring-cloud-gateway/spring-cloud-gateway-server-mvc/src/main/java/org/springframework/cloud/gateway/server/mvc/filter/CircuitBreakerFilterFunctions.java
CircuitBreakerFilterFunctions
circuitBreaker
class CircuitBreakerFilterFunctions { private CircuitBreakerFilterFunctions() { } @Shortcut public static HandlerFilterFunction<ServerResponse, ServerResponse> circuitBreaker(String id) { return circuitBreaker(config -> config.setId(id)); } public static HandlerFilterFunction<ServerResponse, ServerResponse> circuitBreaker(String id, URI fallbackUri) { return circuitBreaker(config -> config.setId(id).setFallbackUri(fallbackUri)); } public static HandlerFilterFunction<ServerResponse, ServerResponse> circuitBreaker(String id, String fallbackPath) { return circuitBreaker(config -> config.setId(id).setFallbackPath(fallbackPath)); } public static HandlerFilterFunction<ServerResponse, ServerResponse> circuitBreaker( Consumer<CircuitBreakerConfig> configConsumer) { CircuitBreakerConfig config = new CircuitBreakerConfig(); configConsumer.accept(config); return circuitBreaker(config); } @Shortcut @Configurable public static HandlerFilterFunction<ServerResponse, ServerResponse> circuitBreaker(CircuitBreakerConfig config) {<FILL_FUNCTION_BODY>} public static class CircuitBreakerConfig { private String id; private String fallbackPath; private Set<String> statusCodes = new HashSet<>(); public String getId() { return id; } public CircuitBreakerConfig setId(String id) { this.id = id; return this; } public String getFallbackPath() { return fallbackPath; } public CircuitBreakerConfig setFallbackUri(String fallbackUri) { Assert.notNull(fallbackUri, "fallbackUri String may not be null"); setFallbackUri(URI.create(fallbackUri)); return this; } public CircuitBreakerConfig setFallbackUri(URI fallbackUri) { if (fallbackUri != null) { Assert.isTrue(fallbackUri.getScheme().equalsIgnoreCase("forward"), () -> "Scheme must be forward, but is " + fallbackUri.getScheme()); fallbackPath = fallbackUri.getPath(); } else { fallbackPath = null; } return this; } public CircuitBreakerConfig setFallbackPath(String fallbackPath) { this.fallbackPath = fallbackPath; return this; } public Set<String> getStatusCodes() { return statusCodes; } public CircuitBreakerConfig setStatusCodes(String... statusCodes) { return setStatusCodes(new LinkedHashSet<>(Arrays.asList(statusCodes))); } public CircuitBreakerConfig setStatusCodes(Set<String> statusCodes) { this.statusCodes = statusCodes; return this; } } public static class CircuitBreakerStatusCodeException extends ResponseStatusException { public CircuitBreakerStatusCodeException(HttpStatusCode statusCode) { super(statusCode); } } public static class FilterSupplier extends SimpleFilterSupplier { public FilterSupplier() { super(CircuitBreakerFilterFunctions.class); } } }
Set<HttpStatusCode> failureStatuses = config.getStatusCodes().stream() .map(status -> HttpStatusHolder.valueOf(status).resolve()).collect(Collectors.toSet()); return (request, next) -> { CircuitBreakerFactory<?, ?> circuitBreakerFactory = MvcUtils.getApplicationContext(request) .getBean(CircuitBreakerFactory.class); // TODO: cache CircuitBreaker circuitBreaker = circuitBreakerFactory.create(config.getId()); return circuitBreaker.run(() -> { try { ServerResponse serverResponse = next.handle(request); // on configured status code, throw exception if (failureStatuses.contains(serverResponse.statusCode())) { throw new CircuitBreakerStatusCodeException(serverResponse.statusCode()); } return serverResponse; } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e); } }, throwable -> { // if no fallback if (!StringUtils.hasText(config.getFallbackPath())) { // if timeout exception, GATEWAY_TIMEOUT if (throwable instanceof TimeoutException) { throw new ResponseStatusException(HttpStatus.GATEWAY_TIMEOUT, throwable.getMessage(), throwable); } // TODO: if not permitted (like circuit open), SERVICE_UNAVAILABLE // TODO: if resume without error, return ok response? throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, throwable.getMessage(), throwable); } // add the throwable as an attribute. That way, if the fallback is a // different gateway route, it can use the fallbackHeaders() filter // to convert it to headers. MvcUtils.putAttribute(request, MvcUtils.CIRCUITBREAKER_EXECUTION_EXCEPTION_ATTR, throwable); // handle fallback // ok() is wrong, but will be overwritten by the forwarded request return GatewayServerResponse.ok().build((httpServletRequest, httpServletResponse) -> { try { String expandedFallback = MvcUtils.expand(request, config.getFallbackPath()); request.servletRequest().getServletContext().getRequestDispatcher(expandedFallback) .forward(httpServletRequest, httpServletResponse); return null; } catch (ServletException | IOException e) { throw new RuntimeException(e); } }); }); };
851
667
1,518
javamelody_javamelody
javamelody/javamelody-core/src/main/java/net/bull/javamelody/internal/web/pdf/PdfCounterErrorReport.java
PdfCounterErrorReport
toPdf
class PdfCounterErrorReport extends PdfAbstractTableReport { private final Counter counter; private final DateFormat dateTimeFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM, I18N.getCurrentLocale()); private final Font severeFont = PdfFonts.SEVERE_CELL.getFont(); private final Font normalFont = PdfFonts.NORMAL.getFont(); PdfCounterErrorReport(Counter counter, Document document) { super(document); assert counter != null; assert counter.isErrorCounter(); this.counter = counter; } @Override void toPdf() throws DocumentException {<FILL_FUNCTION_BODY>} private void writeErrors(List<CounterError> errors) throws DocumentException { assert errors != null; final boolean displayUser = HtmlCounterErrorReport.shouldDisplayUser(errors); final boolean displayHttpRequest = HtmlCounterErrorReport.shouldDisplayHttpRequest(errors); if (errors.size() >= Counter.MAX_ERRORS_COUNT) { addToDocument(new Phrase( getFormattedString("Dernieres_erreurs_seulement", Counter.MAX_ERRORS_COUNT) + '\n', severeFont)); } writeHeader(displayUser, displayHttpRequest); for (final CounterError error : errors) { nextRow(); writeError(error, displayUser, displayHttpRequest); } addTableToDocument(); } private void writeHeader(boolean displayUser, boolean displayHttpRequest) throws DocumentException { final List<String> headers = createHeaders(displayUser, displayHttpRequest); final int[] relativeWidths = new int[headers.size()]; Arrays.fill(relativeWidths, 0, headers.size(), 1); if (displayHttpRequest) { relativeWidths[1] = 4; // requête http } relativeWidths[headers.size() - 1] = 4; // message d'erreur initTable(headers, relativeWidths); } private List<String> createHeaders(boolean displayUser, boolean displayHttpRequest) { final List<String> headers = new ArrayList<>(); headers.add(getString("Date")); if (displayHttpRequest) { headers.add(getString("Requete")); } if (displayUser) { headers.add(getString("Utilisateur")); } headers.add(getString("Erreur")); return headers; } private void writeError(CounterError error, boolean displayUser, boolean displayHttpRequest) { getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT); addCell(dateTimeFormat.format(error.getDate())); getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT); if (displayHttpRequest) { if (error.getHttpRequest() == null) { addCell(""); } else { addCell(error.getHttpRequest()); } } if (displayUser) { if (error.getRemoteUser() == null) { addCell(""); } else { addCell(error.getRemoteUser()); } } addCell(error.getMessage()); } }
final List<CounterError> errors = counter.getErrors(); if (errors.isEmpty()) { addToDocument(new Phrase(getString("Aucune_erreur"), normalFont)); } else { writeErrors(errors); }
933
75
1,008
/** * Parent abstrait des classes de rapport pdf avec un tableau. * @author Emeric Vernat */ abstract class PdfAbstractTableReport extends PdfAbstractReport { private final Font cellFont=PdfFonts.TABLE_CELL.getFont(); private PdfPTable table; private boolean oddRow; PdfAbstractTableReport( Document document); void initTable( List<String> headers, int[] relativeWidths) throws DocumentException; void nextRow(); PdfPCell getDefaultCell(); void addCell( String string); void addCell( Phrase phrase); void addCell( Image image); void addCell( PdfPCell cell); /** * Adds the <CODE>table</CODE> to the <CODE>Document</CODE>. * @return <CODE>true</CODE> if the element was added, <CODE>false</CODE> if not * @throws DocumentException when a document isn't open yet, or has been closed */ boolean addTableToDocument() throws DocumentException; }
subhra74_snowflake
snowflake/muon-jediterm/src/main/java/com/jediterm/terminal/util/Pair.java
Pair
equals
class Pair<A, B> { public final A first; public final B second; // public static <A, B> Pair<A, B> create(A first, B second) { return new Pair<A, B>(first, second); } public static <T> T getFirst(Pair<T, ?> pair) { return pair != null ? pair.first : null; } public static <T> T getSecond(Pair<?, T> pair) { return pair != null ? pair.second : null; } @SuppressWarnings("unchecked") private static final Pair EMPTY = create(null, null); @SuppressWarnings("unchecked") public static <A, B> Pair<A, B> empty() { return EMPTY; } public Pair(A first, B second) { this.first = first; this.second = second; } public final A getFirst() { return first; } public final B getSecond() { return second; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} public int hashCode() { int result = first != null ? first.hashCode() : 0; result = 31 * result + (second != null ? second.hashCode() : 0); return result; } public String toString() { return "<" + first + "," + second + ">"; } }
if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair pair = (Pair)o; if (first != null ? !first.equals(pair.first) : pair.first != null) return false; if (second != null ? !second.equals(pair.second) : pair.second != null) return false; return true;
406
112
518
orientechnologies_orientdb
orientdb/distributed/src/main/java/com/orientechnologies/orient/server/distributed/impl/OLocalKeySource.java
OLocalKeySource
getUniqueKeys
class OLocalKeySource implements OLockKeySource { private final OTransactionId txId; private final OTransactionInternal iTx; private final ODatabaseDocumentDistributed database; public OLocalKeySource( OTransactionId txId, OTransactionInternal iTx, ODatabaseDocumentDistributed database) { this.txId = txId; this.iTx = iTx; this.database = database; } @Override public SortedSet<OTransactionUniqueKey> getUniqueKeys() {<FILL_FUNCTION_BODY>} @Override public OTransactionId getTransactionId() { return txId; } @Override public SortedSet<ORID> getRids() { SortedSet<ORID> set = new TreeSet<ORID>(); for (ORecordOperation operation : iTx.getRecordOperations()) { OTransactionPhase1Task.mapRid(set, operation); } return set; } }
TreeSet<OTransactionUniqueKey> uniqueIndexKeys = new TreeSet<>(); iTx.getIndexOperations() .forEach( (index, changes) -> { OIndexInternal resolvedIndex = changes.resolveAssociatedIndex( index, database.getMetadata().getIndexManagerInternal(), database); if (resolvedIndex.isUnique()) { for (Object keyWithChange : changes.changesPerKey.keySet()) { Object keyChange = OTransactionPhase1Task.mapKey(keyWithChange); uniqueIndexKeys.add(new OTransactionUniqueKey(index, keyChange, 0)); } if (!changes.nullKeyChanges.isEmpty()) { uniqueIndexKeys.add(new OTransactionUniqueKey(index, null, 0)); } } }); return uniqueIndexKeys;
254
210
464
PlayEdu_PlayEdu
PlayEdu/playedu-common/src/main/java/xyz/playedu/common/domain/LdapUser.java
LdapUser
equals
class LdapUser implements Serializable { /** */ @TableId(type = IdType.AUTO) private Integer id; /** 唯一特征值 */ private String uuid; /** 用户ID */ private Integer userId; /** cn */ private String cn; /** dn */ private String dn; /** ou */ private String ou; /** uid */ private String uid; /** 邮箱 */ private String email; /** */ private Date createdAt; /** */ private Date updatedAt; @TableField(exist = false) private static final long serialVersionUID = 1L; /** */ public Integer getId() { return id; } /** */ public void setId(Integer id) { this.id = id; } /** 唯一特征值 */ public String getUuid() { return uuid; } /** 唯一特征值 */ public void setUuid(String uuid) { this.uuid = uuid; } /** 用户ID */ public Integer getUserId() { return userId; } /** 用户ID */ public void setUserId(Integer userId) { this.userId = userId; } /** cn */ public String getCn() { return cn; } /** cn */ public void setCn(String cn) { this.cn = cn; } /** dn */ public String getDn() { return dn; } /** dn */ public void setDn(String dn) { this.dn = dn; } /** ou */ public String getOu() { return ou; } /** ou */ public void setOu(String ou) { this.ou = ou; } /** uid */ public String getUid() { return uid; } /** uid */ public void setUid(String uid) { this.uid = uid; } /** 邮箱 */ public String getEmail() { return email; } /** 邮箱 */ public void setEmail(String email) { this.email = email; } /** */ public Date getCreatedAt() { return createdAt; } /** */ public void setCreatedAt(Date createdAt) { this.createdAt = createdAt; } /** */ public Date getUpdatedAt() { return updatedAt; } /** */ public void setUpdatedAt(Date updatedAt) { this.updatedAt = updatedAt; } @Override public boolean equals(Object that) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getId() == null) ? 0 : getId().hashCode()); result = prime * result + ((getUuid() == null) ? 0 : getUuid().hashCode()); result = prime * result + ((getUserId() == null) ? 0 : getUserId().hashCode()); result = prime * result + ((getCn() == null) ? 0 : getCn().hashCode()); result = prime * result + ((getDn() == null) ? 0 : getDn().hashCode()); result = prime * result + ((getOu() == null) ? 0 : getOu().hashCode()); result = prime * result + ((getUid() == null) ? 0 : getUid().hashCode()); result = prime * result + ((getEmail() == null) ? 0 : getEmail().hashCode()); result = prime * result + ((getCreatedAt() == null) ? 0 : getCreatedAt().hashCode()); result = prime * result + ((getUpdatedAt() == null) ? 0 : getUpdatedAt().hashCode()); return result; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", uuid=").append(uuid); sb.append(", userId=").append(userId); sb.append(", cn=").append(cn); sb.append(", dn=").append(dn); sb.append(", ou=").append(ou); sb.append(", uid=").append(uid); sb.append(", email=").append(email); sb.append(", createdAt=").append(createdAt); sb.append(", updatedAt=").append(updatedAt); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
if (this == that) { return true; } if (that == null) { return false; } if (getClass() != that.getClass()) { return false; } LdapUser other = (LdapUser) that; return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId())) && (this.getUuid() == null ? other.getUuid() == null : this.getUuid().equals(other.getUuid())) && (this.getUserId() == null ? other.getUserId() == null : this.getUserId().equals(other.getUserId())) && (this.getCn() == null ? other.getCn() == null : this.getCn().equals(other.getCn())) && (this.getDn() == null ? other.getDn() == null : this.getDn().equals(other.getDn())) && (this.getOu() == null ? other.getOu() == null : this.getOu().equals(other.getOu())) && (this.getUid() == null ? other.getUid() == null : this.getUid().equals(other.getUid())) && (this.getEmail() == null ? other.getEmail() == null : this.getEmail().equals(other.getEmail())) && (this.getCreatedAt() == null ? other.getCreatedAt() == null : this.getCreatedAt().equals(other.getCreatedAt())) && (this.getUpdatedAt() == null ? other.getUpdatedAt() == null : this.getUpdatedAt().equals(other.getUpdatedAt()));
1,311
460
1,771
pmd_pmd
pmd/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/ast/ASTInput.java
ASTInput
addExcludedLineRange
class ASTInput extends AbstractPLSQLNode implements RootNode { private AstInfo<ASTInput> astInfo; ASTInput(int id) { super(id); } @Override public AstInfo<ASTInput> getAstInfo() { return astInfo; } ASTInput addTaskInfo(ParserTask task) { this.astInfo = new AstInfo<>(task, this); return this; } @Override protected <P, R> R acceptPlsqlVisitor(PlsqlVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } private int excludedRangesCount = 0; private int excludedLinesCount = 0; /** * Let the user know that a range of lines were excluded from parsing. * * @param first First line of the excluded line range (1-based). * @param last Last line of the excluded line range (1-based). */ void addExcludedLineRange(int first, int last) {<FILL_FUNCTION_BODY>} public int getExcludedLinesCount() { return excludedLinesCount; } public int getExcludedRangesCount() { return excludedRangesCount; } }
excludedLinesCount += last - first + 1; excludedRangesCount += 1;
335
25
360
docker-java_docker-java
docker-java/docker-java-core/src/main/java/com/github/dockerjava/core/command/InspectContainerCmdImpl.java
InspectContainerCmdImpl
withContainerId
class InspectContainerCmdImpl extends AbstrDockerCmd<InspectContainerCmd, InspectContainerResponse> implements InspectContainerCmd { private String containerId; private boolean size; public InspectContainerCmdImpl(InspectContainerCmd.Exec exec, String containerId) { super(exec); withContainerId(containerId); } @Override public String getContainerId() { return containerId; } @Override public InspectContainerCmd withContainerId(String containerId) {<FILL_FUNCTION_BODY>} @Override public InspectContainerCmd withSize(Boolean showSize) { this.size = showSize; return this; } @Override public Boolean getSize() { return size; } /** * @throws NotFoundException * No such container */ @Override public InspectContainerResponse exec() throws NotFoundException { return super.exec(); } }
this.containerId = Objects.requireNonNull(containerId, "containerId was not specified"); return this;
253
32
285
spring-cloud_spring-cloud-gateway
spring-cloud-gateway/spring-cloud-gateway-server-mvc/src/main/java/org/springframework/cloud/gateway/server/mvc/filter/LoadBalancerHandlerSupplier.java
LoadBalancerHandlerSupplier
lb
class LoadBalancerHandlerSupplier implements HandlerSupplier { @Override public Collection<Method> get() { return Arrays.asList(getClass().getMethods()); } public static HandlerDiscoverer.Result lb(RouteProperties routeProperties) { return lb(routeProperties.getUri()); } public static HandlerDiscoverer.Result lb(URI uri) {<FILL_FUNCTION_BODY>} }
// TODO: how to do something other than http return new HandlerDiscoverer.Result(HandlerFunctions.http(), Collections.singletonList(LoadBalancerFilterFunctions.lb(uri.getHost())));
111
57
168
spring-cloud_spring-cloud-gateway
spring-cloud-gateway/spring-cloud-gateway-server/src/main/java/org/springframework/cloud/gateway/actuate/GatewayEndpointInfo.java
GatewayEndpointInfo
equals
class GatewayEndpointInfo { private String href; private List<String> methods; public String getHref() { return href; } public void setHref(String href) { this.href = href; } public String[] getMethods() { return methods.stream().toArray(String[]::new); } GatewayEndpointInfo(String href, String method) { this.href = href; this.methods = Collections.singletonList(method); } GatewayEndpointInfo(String href, List<String> methods) { this.href = href; this.methods = methods; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(href, methods); } }
if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } GatewayEndpointInfo that = (GatewayEndpointInfo) o; return Objects.equals(href, that.href) && Objects.equals(methods, that.methods);
217
92
309
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-manager/autoload-cache-manager-jedis/src/main/java/com/jarvis/cache/redis/RetryableJedisClusterPipeline.java
RetryableJedisClusterPipeline
syncAndReturnAll
class RetryableJedisClusterPipeline { /** * 部分字段没有对应的获取方法,只能采用反射来做 * 也可以去继承JedisCluster和JedisSlotBasedConnectionHandler来提供访问接口 **/ private static final Field FIELD_CONNECTION_HANDLER; private static final Field FIELD_CACHE; private static final Logger log = LoggerFactory.getLogger(JedisUtil.class); static { FIELD_CONNECTION_HANDLER = getField(BinaryJedisCluster.class, "connectionHandler"); FIELD_CACHE = getField(JedisClusterConnectionHandler.class, "cache"); } private final JedisSlotBasedConnectionHandler connectionHandler; private final JedisClusterInfoCache clusterInfoCache; private int maxAttempts = 1; public RetryableJedisClusterPipeline(JedisCluster jedisCluster) { connectionHandler = getValue(jedisCluster, FIELD_CONNECTION_HANDLER); clusterInfoCache = getValue(connectionHandler, FIELD_CACHE); } public abstract void execute(JedisClusterPipeline pipeline) throws Exception; /** * 同步读取所有数据. 与syncAndReturnAll()相比,sync()只是没有对数据做反序列化 * @throws Exception redis 异常 */ public void sync() throws Exception { try { JedisClusterPipeline pipeline = new JedisClusterPipeline(clusterInfoCache); execute(pipeline); pipeline.sync(); } catch (JedisMovedDataException jre) { // if MOVED redirection occurred, rebuilds cluster's slot cache, // recommended by Redis cluster specification connectionHandler.renewSlotCache(); if (maxAttempts > 0) { maxAttempts--; sync(); return; } throw jre; } catch (Exception e) { throw e; } } /** * 同步读取所有数据 并按命令顺序返回一个列表 * * @return 按照命令的顺序返回所有的数据 * @throws Exception redis 异常 */ public List<Object> syncAndReturnAll() throws Exception {<FILL_FUNCTION_BODY>} private static Field getField(Class<?> cls, String fieldName) { try { Field field = cls.getDeclaredField(fieldName); field.setAccessible(true); return field; } catch (NoSuchFieldException | SecurityException e) { throw new RuntimeException("cannot find or access field '" + fieldName + "' from " + cls.getName(), e); } } @SuppressWarnings({"unchecked"}) private static <T> T getValue(Object obj, Field field) { try { return (T) field.get(obj); } catch (IllegalArgumentException | IllegalAccessException e) { log.error("get value fail", e); throw new RuntimeException(e); } } }
try { JedisClusterPipeline pipeline = new JedisClusterPipeline(clusterInfoCache); execute(pipeline); return pipeline.syncAndReturnAll(); } catch (JedisMovedDataException jre) { // if MOVED redirection occurred, rebuilds cluster's slot cache, // recommended by Redis cluster specification connectionHandler.renewSlotCache(); if (maxAttempts > 0) { maxAttempts--; return syncAndReturnAll(); } throw jre; } catch (Exception ex) { throw ex; }
806
155
961
joelittlejohn_jsonschema2pojo
jsonschema2pojo/jsonschema2pojo-core/src/main/java/org/jsonschema2pojo/rules/PropertiesRule.java
PropertiesRule
apply
class PropertiesRule implements Rule<JDefinedClass, JDefinedClass> { private final RuleFactory ruleFactory; protected PropertiesRule(RuleFactory ruleFactory) { this.ruleFactory = ruleFactory; } /** * Applies this schema rule to take the required code generation steps. * <p> * For each property present within the properties node, this rule will * invoke the 'property' rule provided by the given schema mapper. * * @param nodeName * the name of the node for which properties are being added * @param node * the properties node, containing property names and their * definition * @param jclass * the Java type which will have the given properties added * @return the given jclass */ @Override public JDefinedClass apply(String nodeName, JsonNode node, JsonNode parent, JDefinedClass jclass, Schema schema) {<FILL_FUNCTION_BODY>} private void addOverrideBuilders(JDefinedClass jclass, JDefinedClass parentJclass) { if (parentJclass == null) { return; } for (JMethod parentJMethod : parentJclass.methods()) { if (parentJMethod.name().startsWith("with") && parentJMethod.params().size() == 1) { addOverrideBuilder(jclass, parentJMethod, parentJMethod.params().get(0)); } } } private void addOverrideBuilder(JDefinedClass thisJDefinedClass, JMethod parentBuilder, JVar parentParam) { // Confirm that this class doesn't already have a builder method matching the same name as the parentBuilder if (thisJDefinedClass.getMethod(parentBuilder.name(), new JType[] {parentParam.type()}) == null) { JMethod builder = thisJDefinedClass.method(parentBuilder.mods().getValue(), thisJDefinedClass, parentBuilder.name()); builder.annotate(Override.class); JVar param = builder.param(parentParam.type(), parentParam.name()); JBlock body = builder.body(); body.invoke(JExpr._super(), parentBuilder).arg(param); body._return(JExpr._this()); } } }
if (node == null) { node = JsonNodeFactory.instance.objectNode(); } for (Iterator<String> properties = node.fieldNames(); properties.hasNext(); ) { String property = properties.next(); ruleFactory.getPropertyRule().apply(property, node.get(property), node, jclass, schema); } if (ruleFactory.getGenerationConfig().isGenerateBuilders() && !jclass._extends().name().equals("Object")) { addOverrideBuilders(jclass, jclass.owner()._getClass(jclass._extends().fullName())); } ruleFactory.getAnnotator().propertyOrder(jclass, node); return jclass;
569
181
750
zhkl0228_unidbg
unidbg/unidbg-android/src/main/java/com/github/unidbg/file/linux/LinuxFileSystem.java
LinuxFileSystem
open
class LinuxFileSystem extends BaseFileSystem<AndroidFileIO> implements FileSystem<AndroidFileIO>, IOConstants { public LinuxFileSystem(Emulator<AndroidFileIO> emulator, File rootDir) { super(emulator, rootDir); } @Override public FileResult<AndroidFileIO> open(String pathname, int oflags) {<FILL_FUNCTION_BODY>} public LogCatHandler getLogCatHandler() { return null; } @Override protected void initialize(File rootDir) throws IOException { super.initialize(rootDir); FileUtils.forceMkdir(new File(rootDir, "system")); FileUtils.forceMkdir(new File(rootDir, "data")); } @Override public AndroidFileIO createSimpleFileIO(File file, int oflags, String path) { return new SimpleFileIO(oflags, file, path); } @Override public AndroidFileIO createDirectoryFileIO(File file, int oflags, String path) { return new DirectoryFileIO(oflags, path, file); } @Override protected AndroidFileIO createStdin(int oflags) { return new Stdin(oflags); } @Override protected AndroidFileIO createStdout(int oflags, File stdio, String pathname) { return new Stdout(oflags, stdio, pathname, IO.STDERR.equals(pathname), null); } @Override protected boolean hasCreat(int oflags) { return (oflags & O_CREAT) != 0; } @Override protected boolean hasDirectory(int oflags) { return (oflags & O_DIRECTORY) != 0; } @Override protected boolean hasAppend(int oflags) { return (oflags & O_APPEND) != 0; } @Override protected boolean hasExcl(int oflags) { return (oflags & O_EXCL) != 0; } }
if ("/dev/tty".equals(pathname)) { return FileResult.<AndroidFileIO>success(new NullFileIO(pathname)); } if ("/proc/self/maps".equals(pathname) || ("/proc/" + emulator.getPid() + "/maps").equals(pathname) || ("/proc/self/task/" + emulator.getPid() + "/maps").equals(pathname)) { return FileResult.<AndroidFileIO>success(new MapsFileIO(emulator, oflags, pathname, emulator.getMemory().getLoadedModules())); } return super.open(pathname, oflags);
541
169
710
zhkl0228_unidbg
unidbg/unidbg-android/src/main/java/com/github/unidbg/linux/android/AndroidARM64Unwinder.java
AndroidARM64Unwinder
unw_step
class AndroidARM64Unwinder extends SimpleARM64Unwinder { private static final Log log = LogFactory.getLog(AndroidARM64Unwinder.class); private final DwarfCursor context; public AndroidARM64Unwinder(Emulator<?> emulator) { super(emulator); this.context = new DwarfCursor64(emulator); } @Override protected Frame unw_step(Emulator<?> emulator, Frame frame) {<FILL_FUNCTION_BODY>} }
try { LinuxModule module = (LinuxModule) emulator.getMemory().findModuleByAddress(this.context.ip); MemoizedObject<GnuEhFrameHeader> ehFrameHeader = module == null ? null : module.ehFrameHeader; if (ehFrameHeader != null) { long fun = this.context.ip - module.base; GnuEhFrameHeader frameHeader = ehFrameHeader.getValue(); Frame ret = frameHeader == null ? null : frameHeader.dwarf_step(emulator, this, module, fun, context); if (ret != null) { return ret; } } } catch (RuntimeException exception) { log.warn("unw_step", exception); } catch (IOException e) { throw new IllegalStateException(e); } return super.unw_step(emulator, frame);
146
224
370
public class SimpleARM64Unwinder extends Unwinder { public SimpleARM64Unwinder( Emulator<?> emulator); @Override protected String getBaseFormat(); @Override public Frame createFrame( UnidbgPointer ip, UnidbgPointer fp); private Frame initFrame( Emulator<?> emulator); @Override protected Frame unw_step( Emulator<?> emulator, Frame frame); }
pmd_pmd
pmd/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/SymbolicValueHelper.java
SymbolicValueHelper
equalsModuloWrapper
class SymbolicValueHelper { private SymbolicValueHelper() { // utility class } static boolean equalsModuloWrapper(SymbolicValue sv, Object other) {<FILL_FUNCTION_BODY>} }
if (other instanceof SymbolicValue) { return sv.equals(other); } else { return sv.valueEquals(other); }
59
41
100
graphhopper_graphhopper
graphhopper/example/src/main/java/com/graphhopper/example/RoutingExample.java
RoutingExample
createGraphHopperInstance
class RoutingExample { public static void main(String[] args) { String relDir = args.length == 1 ? args[0] : ""; GraphHopper hopper = createGraphHopperInstance(relDir + "core/files/andorra.osm.pbf"); routing(hopper); speedModeVersusFlexibleMode(hopper); alternativeRoute(hopper); customizableRouting(relDir + "core/files/andorra.osm.pbf"); // release resources to properly shutdown or start a new instance hopper.close(); } static GraphHopper createGraphHopperInstance(String ghLoc) {<FILL_FUNCTION_BODY>} public static void routing(GraphHopper hopper) { // simple configuration of the request object GHRequest req = new GHRequest(42.508552, 1.532936, 42.507508, 1.528773). // note that we have to specify which profile we are using even when there is only one like here setProfile("car"). // define the language for the turn instructions setLocale(Locale.US); GHResponse rsp = hopper.route(req); // handle errors if (rsp.hasErrors()) throw new RuntimeException(rsp.getErrors().toString()); // use the best path, see the GHResponse class for more possibilities. ResponsePath path = rsp.getBest(); // points, distance in meters and time in millis of the full path PointList pointList = path.getPoints(); double distance = path.getDistance(); long timeInMs = path.getTime(); Translation tr = hopper.getTranslationMap().getWithFallBack(Locale.UK); InstructionList il = path.getInstructions(); // iterate over all turn instructions for (Instruction instruction : il) { // System.out.println("distance " + instruction.getDistance() + " for instruction: " + instruction.getTurnDescription(tr)); } assert il.size() == 6; assert Helper.round(path.getDistance(), -2) == 600; } public static void speedModeVersusFlexibleMode(GraphHopper hopper) { GHRequest req = new GHRequest(42.508552, 1.532936, 42.507508, 1.528773). setProfile("car").setAlgorithm(Parameters.Algorithms.ASTAR_BI).putHint(Parameters.CH.DISABLE, true); GHResponse res = hopper.route(req); if (res.hasErrors()) throw new RuntimeException(res.getErrors().toString()); assert Helper.round(res.getBest().getDistance(), -2) == 600; } public static void alternativeRoute(GraphHopper hopper) { // calculate alternative routes between two points (supported with and without CH) GHRequest req = new GHRequest().setProfile("car"). addPoint(new GHPoint(42.502904, 1.514714)).addPoint(new GHPoint(42.508774, 1.537094)). setAlgorithm(Parameters.Algorithms.ALT_ROUTE); req.getHints().putObject(Parameters.Algorithms.AltRoute.MAX_PATHS, 3); GHResponse res = hopper.route(req); if (res.hasErrors()) throw new RuntimeException(res.getErrors().toString()); assert res.getAll().size() == 2; assert Helper.round(res.getBest().getDistance(), -2) == 2200; } /** * To customize profiles in the config.yml file you can use a json or yml file or embed it directly. See this list: * web/src/test/resources/com/graphhopper/application/resources and https://www.graphhopper.com/?s=customizable+routing */ public static void customizableRouting(String ghLoc) { GraphHopper hopper = new GraphHopper(); hopper.setOSMFile(ghLoc); hopper.setGraphHopperLocation("target/routing-custom-graph-cache"); hopper.setEncodedValuesString("car_access, car_average_speed"); hopper.setProfiles(new Profile("car_custom").setCustomModel(GHUtility.loadCustomModelFromJar("car.json"))); // The hybrid mode uses the "landmark algorithm" and is up to 15x faster than the flexible mode (Dijkstra). // Still it is slower than the speed mode ("contraction hierarchies algorithm") ... hopper.getLMPreparationHandler().setLMProfiles(new LMProfile("car_custom")); hopper.importOrLoad(); // ... but for the hybrid mode we can customize the route calculation even at request time: // 1. a request with default preferences GHRequest req = new GHRequest().setProfile("car_custom"). addPoint(new GHPoint(42.506472, 1.522475)).addPoint(new GHPoint(42.513108, 1.536005)); GHResponse res = hopper.route(req); if (res.hasErrors()) throw new RuntimeException(res.getErrors().toString()); assert Math.round(res.getBest().getTime() / 1000d) == 94; // 2. now avoid the secondary road and reduce the maximum speed, see docs/core/custom-models.md for an in-depth explanation // and also the blog posts https://www.graphhopper.com/?s=customizable+routing CustomModel model = new CustomModel(); model.addToPriority(If("road_class == SECONDARY", MULTIPLY, "0.5")); // unconditional limit to 20km/h model.addToSpeed(If("true", LIMIT, "30")); req.setCustomModel(model); res = hopper.route(req); if (res.hasErrors()) throw new RuntimeException(res.getErrors().toString()); assert Math.round(res.getBest().getTime() / 1000d) == 184; } }
GraphHopper hopper = new GraphHopper(); hopper.setOSMFile(ghLoc); // specify where to store graphhopper files hopper.setGraphHopperLocation("target/routing-graph-cache"); // add all encoded values that are used in the custom model, these are also available as path details or for client-side custom models hopper.setEncodedValuesString("car_access, car_average_speed"); // see docs/core/profiles.md to learn more about profiles hopper.setProfiles(new Profile("car").setCustomModel(GHUtility.loadCustomModelFromJar("car.json"))); // this enables speed mode for the profile we called car hopper.getCHPreparationHandler().setCHProfiles(new CHProfile("car")); // now this can take minutes if it imports or a few seconds for loading of course this is dependent on the area you import hopper.importOrLoad(); return hopper;
1,646
248
1,894
PlayEdu_PlayEdu
PlayEdu/playedu-api/src/main/java/xyz/playedu/api/listener/UserLearnCourseUpdateListener.java
UserLearnCourseUpdateListener
storeLearnDuration
class UserLearnCourseUpdateListener { @Autowired private UserLearnDurationRecordService userLearnDurationRecordService; @Autowired private UserLearnDurationStatsService userLearnDurationStatsService; @EventListener public void storeLearnDuration(UserLearnCourseUpdateEvent event) {<FILL_FUNCTION_BODY>} }
// 观看时长统计 userLearnDurationStatsService.storeOrUpdate( event.getUserId(), event.getStartAt(), event.getEndAt()); // 观看记录 userLearnDurationRecordService.store( event.getUserId(), event.getCourseId(), event.getHourId(), event.getStartAt(), event.getEndAt());
83
103
186
PlayEdu_PlayEdu
PlayEdu/playedu-api/src/main/java/xyz/playedu/api/controller/backend/AdminLogController.java
AdminLogController
detail
class AdminLogController { @Autowired private AdminLogService adminLogService; @Autowired private BackendBus backendBus; @BackendPermission(slug = BPermissionConstant.ADMIN_LOG) @GetMapping("/index") @Log(title = "管理员日志-列表", businessType = BusinessTypeConstant.GET) public JsonResponse index(@RequestParam HashMap<String, Object> params) { Integer page = MapUtils.getInteger(params, "page", 1); Integer size = MapUtils.getInteger(params, "size", 10); String sortField = MapUtils.getString(params, "sort_field"); String sortAlgo = MapUtils.getString(params, "sort_algo"); Integer adminId = MapUtils.getInteger(params, "admin_id"); String adminName = MapUtils.getString(params, "admin_name"); String module = MapUtils.getString(params, "module"); String title = MapUtils.getString(params, "title"); Integer opt = MapUtils.getInteger(params, "opt"); String startTime = MapUtils.getString(params, "start_time"); String endTime = MapUtils.getString(params, "end_time"); AdminLogPaginateFiler filter = new AdminLogPaginateFiler(); if (backendBus.isSuperAdmin()) { filter.setAdminId(adminId); } else { filter.setAdminId(BCtx.getId()); } filter.setAdminName(adminName); filter.setModule(module); filter.setTitle(title); filter.setOpt(opt); filter.setStartTime(startTime); filter.setEndTime(endTime); filter.setSortField(sortField); filter.setSortAlgo(sortAlgo); PaginationResult<AdminLog> result = adminLogService.paginate(page, size, filter); HashMap<String, Object> data = new HashMap<>(); data.put("data", result.getData()); data.put("total", result.getTotal()); return JsonResponse.data(data); } @BackendPermission(slug = BPermissionConstant.ADMIN_LOG) @GetMapping("/detail/{id}") public JsonResponse detail(@PathVariable(name = "id") Integer id) {<FILL_FUNCTION_BODY>} }
Integer adminId = 0; if (!backendBus.isSuperAdmin()) { adminId = BCtx.getId(); } AdminLog log = adminLogService.find(id, adminId); if (log == null) { throw new ServiceException("日志不存在"); } return JsonResponse.data(log);
605
90
695
YunaiV_ruoyi-vue-pro
ruoyi-vue-pro/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/notice/NoticeController.java
NoticeController
push
class NoticeController { @Resource private NoticeService noticeService; @Resource private WebSocketSenderApi webSocketSenderApi; @PostMapping("/create") @Operation(summary = "创建通知公告") @PreAuthorize("@ss.hasPermission('system:notice:create')") public CommonResult<Long> createNotice(@Valid @RequestBody NoticeSaveReqVO createReqVO) { Long noticeId = noticeService.createNotice(createReqVO); return success(noticeId); } @PutMapping("/update") @Operation(summary = "修改通知公告") @PreAuthorize("@ss.hasPermission('system:notice:update')") public CommonResult<Boolean> updateNotice(@Valid @RequestBody NoticeSaveReqVO updateReqVO) { noticeService.updateNotice(updateReqVO); return success(true); } @DeleteMapping("/delete") @Operation(summary = "删除通知公告") @Parameter(name = "id", description = "编号", required = true, example = "1024") @PreAuthorize("@ss.hasPermission('system:notice:delete')") public CommonResult<Boolean> deleteNotice(@RequestParam("id") Long id) { noticeService.deleteNotice(id); return success(true); } @GetMapping("/page") @Operation(summary = "获取通知公告列表") @PreAuthorize("@ss.hasPermission('system:notice:query')") public CommonResult<PageResult<NoticeRespVO>> getNoticePage(@Validated NoticePageReqVO pageReqVO) { PageResult<NoticeDO> pageResult = noticeService.getNoticePage(pageReqVO); return success(BeanUtils.toBean(pageResult, NoticeRespVO.class)); } @GetMapping("/get") @Operation(summary = "获得通知公告") @Parameter(name = "id", description = "编号", required = true, example = "1024") @PreAuthorize("@ss.hasPermission('system:notice:query')") public CommonResult<NoticeRespVO> getNotice(@RequestParam("id") Long id) { NoticeDO notice = noticeService.getNotice(id); return success(BeanUtils.toBean(notice, NoticeRespVO.class)); } @PostMapping("/push") @Operation(summary = "推送通知公告", description = "只发送给 websocket 连接在线的用户") @Parameter(name = "id", description = "编号", required = true, example = "1024") @PreAuthorize("@ss.hasPermission('system:notice:update')") public CommonResult<Boolean> push(@RequestParam("id") Long id) {<FILL_FUNCTION_BODY>} }
NoticeDO notice = noticeService.getNotice(id); Assert.notNull(notice, "公告不能为空"); // 通过 websocket 推送给在线的用户 webSocketSenderApi.sendObject(UserTypeEnum.ADMIN.getValue(), "notice-push", notice); return success(true);
710
82
792
jeecgboot_jeecg-boot
jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/system/service/impl/SysRoleServiceImpl.java
SysRoleServiceImpl
importExcelCheckRoleCode
class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService { @Autowired SysRoleMapper sysRoleMapper; @Autowired SysUserMapper sysUserMapper; @Override public Page<SysRole> listAllSysRole(Page<SysRole> page, SysRole role) { return page.setRecords(sysRoleMapper.listAllSysRole(page,role)); } @Override public SysRole getRoleNoTenant(String roleCode) { return sysRoleMapper.getRoleNoTenant(roleCode); } @Override public Result importExcelCheckRoleCode(MultipartFile file, ImportParams params) throws Exception {<FILL_FUNCTION_BODY>} @Override @Transactional(rollbackFor = Exception.class) public boolean deleteRole(String roleid) { //1.删除角色和用户关系 sysRoleMapper.deleteRoleUserRelation(roleid); //2.删除角色和权限关系 sysRoleMapper.deleteRolePermissionRelation(roleid); //3.删除角色 this.removeById(roleid); return true; } @Override @Transactional(rollbackFor = Exception.class) public boolean deleteBatchRole(String[] roleIds) { //1.删除角色和用户关系 sysUserMapper.deleteBathRoleUserRelation(roleIds); //2.删除角色和权限关系 sysUserMapper.deleteBathRolePermissionRelation(roleIds); //3.删除角色 this.removeByIds(Arrays.asList(roleIds)); return true; } @Override public Long getRoleCountByTenantId(String id, Integer tenantId) { return sysRoleMapper.getRoleCountByTenantId(id,tenantId); } @Override public void checkAdminRoleRejectDel(String ids) { LambdaQueryWrapper<SysRole> query = new LambdaQueryWrapper<>(); query.in(SysRole::getId,Arrays.asList(ids.split(SymbolConstant.COMMA))); query.eq(SysRole::getRoleCode,"admin"); Long adminRoleCount = sysRoleMapper.selectCount(query); if(adminRoleCount>0){ throw new JeecgBootException("admin角色,不允许删除!"); } } }
List<Object> listSysRoles = ExcelImportUtil.importExcel(file.getInputStream(), SysRole.class, params); int totalCount = listSysRoles.size(); List<String> errorStrs = new ArrayList<>(); // 去除 listSysRoles 中重复的数据 for (int i = 0; i < listSysRoles.size(); i++) { String roleCodeI =((SysRole)listSysRoles.get(i)).getRoleCode(); for (int j = i + 1; j < listSysRoles.size(); j++) { String roleCodeJ =((SysRole)listSysRoles.get(j)).getRoleCode(); // 发现重复数据 if (roleCodeI.equals(roleCodeJ)) { errorStrs.add("第 " + (j + 1) + " 行的 roleCode 值:" + roleCodeI + " 已存在,忽略导入"); listSysRoles.remove(j); break; } } } // 去掉 sql 中的重复数据 Integer errorLines=0; Integer successLines=0; List<String> list = ImportExcelUtil.importDateSave(listSysRoles, ISysRoleService.class, errorStrs, CommonConstant.SQL_INDEX_UNIQ_SYS_ROLE_CODE); errorLines+=list.size(); successLines+=(listSysRoles.size()-errorLines); return ImportExcelUtil.imporReturnRes(errorLines,successLines,list);
622
409
1,031
spring-cloud_spring-cloud-gateway
spring-cloud-gateway/spring-cloud-gateway-server-mvc/src/main/java/org/springframework/cloud/gateway/server/mvc/invoke/reflect/OperationMethodParameters.java
OperationMethodParameters
getOperationParameters
class OperationMethodParameters implements OperationParameters { private final List<OperationParameter> operationParameters; /** * Create a new {@link OperationMethodParameters} instance. * @param method the source method * @param parameterNameDiscoverer the parameter name discoverer */ OperationMethodParameters(Method method, ParameterNameDiscoverer parameterNameDiscoverer) { Assert.notNull(method, "Method must not be null"); Assert.notNull(parameterNameDiscoverer, "ParameterNameDiscoverer must not be null"); String[] parameterNames = parameterNameDiscoverer.getParameterNames(method); Parameter[] parameters = method.getParameters(); Assert.state(parameterNames != null, () -> "Failed to extract parameter names for " + method); this.operationParameters = getOperationParameters(parameters, parameterNames); } private List<OperationParameter> getOperationParameters(Parameter[] parameters, String[] names) {<FILL_FUNCTION_BODY>} @Override public int getParameterCount() { return this.operationParameters.size(); } @Override public OperationParameter get(int index) { return this.operationParameters.get(index); } @Override public Iterator<OperationParameter> iterator() { return this.operationParameters.iterator(); } @Override public Stream<OperationParameter> stream() { return this.operationParameters.stream(); } }
List<OperationParameter> operationParameters = new ArrayList<>(parameters.length); for (int i = 0; i < names.length; i++) { operationParameters.add(new OperationMethodParameter(names[i], parameters[i])); } return Collections.unmodifiableList(operationParameters);
348
80
428
YunaiV_ruoyi-vue-pro
ruoyi-vue-pro/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/job/JobLogServiceImpl.java
JobLogServiceImpl
updateJobLogResultAsync
class JobLogServiceImpl implements JobLogService { @Resource private JobLogMapper jobLogMapper; @Override public Long createJobLog(Long jobId, LocalDateTime beginTime, String jobHandlerName, String jobHandlerParam, Integer executeIndex) { JobLogDO log = JobLogDO.builder().jobId(jobId).handlerName(jobHandlerName) .handlerParam(jobHandlerParam).executeIndex(executeIndex) .beginTime(beginTime).status(JobLogStatusEnum.RUNNING.getStatus()).build(); jobLogMapper.insert(log); return log.getId(); } @Override @Async public void updateJobLogResultAsync(Long logId, LocalDateTime endTime, Integer duration, boolean success, String result) {<FILL_FUNCTION_BODY>} @Override @SuppressWarnings("DuplicatedCode") public Integer cleanJobLog(Integer exceedDay, Integer deleteLimit) { int count = 0; LocalDateTime expireDate = LocalDateTime.now().minusDays(exceedDay); // 循环删除,直到没有满足条件的数据 for (int i = 0; i < Short.MAX_VALUE; i++) { int deleteCount = jobLogMapper.deleteByCreateTimeLt(expireDate, deleteLimit); count += deleteCount; // 达到删除预期条数,说明到底了 if (deleteCount < deleteLimit) { break; } } return count; } @Override public JobLogDO getJobLog(Long id) { return jobLogMapper.selectById(id); } @Override public PageResult<JobLogDO> getJobLogPage(JobLogPageReqVO pageReqVO) { return jobLogMapper.selectPage(pageReqVO); } }
try { JobLogDO updateObj = JobLogDO.builder().id(logId).endTime(endTime).duration(duration) .status(success ? JobLogStatusEnum.SUCCESS.getStatus() : JobLogStatusEnum.FAILURE.getStatus()) .result(result).build(); jobLogMapper.updateById(updateObj); } catch (Exception ex) { log.error("[updateJobLogResultAsync][logId({}) endTime({}) duration({}) success({}) result({})]", logId, endTime, duration, success, result); }
462
147
609
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/reader/osm/conditional/DateRangeParser.java
DateRangeParser
createCalendar
class DateRangeParser implements ConditionalValueParser { private static final DateFormat YEAR_MONTH_DAY_DF = create3CharMonthFormatter("yyyy MMM dd"); private static final DateFormat MONTH_DAY_DF = create3CharMonthFormatter("MMM dd"); private static final DateFormat MONTH_DAY2_DF = createFormatter("dd.MM"); private static final DateFormat YEAR_MONTH_DF = create3CharMonthFormatter("yyyy MMM"); private static final DateFormat MONTH_DF = create3CharMonthFormatter("MMM"); private static final List<String> DAY_NAMES = Arrays.asList("Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"); private Calendar date; DateRangeParser() { this(createCalendar()); } public DateRangeParser(Calendar date) { this.date = date; } public static Calendar createCalendar() {<FILL_FUNCTION_BODY>} static ParsedCalendar parseDateString(String dateString) throws ParseException { // Replace occurrences of public holidays dateString = dateString.replaceAll("(,( )*)?(PH|SH)", ""); dateString = dateString.trim(); Calendar calendar = createCalendar(); ParsedCalendar parsedCalendar; try { calendar.setTime(YEAR_MONTH_DAY_DF.parse(dateString)); parsedCalendar = new ParsedCalendar(ParsedCalendar.ParseType.YEAR_MONTH_DAY, calendar); } catch (ParseException e1) { try { calendar.setTime(MONTH_DAY_DF.parse(dateString)); parsedCalendar = new ParsedCalendar(ParsedCalendar.ParseType.MONTH_DAY, calendar); } catch (ParseException e2) { try { calendar.setTime(MONTH_DAY2_DF.parse(dateString)); parsedCalendar = new ParsedCalendar(ParsedCalendar.ParseType.MONTH_DAY, calendar); } catch (ParseException e3) { try { calendar.setTime(YEAR_MONTH_DF.parse(dateString)); parsedCalendar = new ParsedCalendar(ParsedCalendar.ParseType.YEAR_MONTH, calendar); } catch (ParseException e4) { try { calendar.setTime(MONTH_DF.parse(dateString)); parsedCalendar = new ParsedCalendar(ParsedCalendar.ParseType.MONTH, calendar); } catch (ParseException e5) { int index = DAY_NAMES.indexOf(dateString); if (index < 0) throw new ParseException("Unparsable date: \"" + dateString + "\"", 0); // Ranges from 1-7 calendar.set(Calendar.DAY_OF_WEEK, index + 1); parsedCalendar = new ParsedCalendar(ParsedCalendar.ParseType.DAY, calendar); } } } } } return parsedCalendar; } DateRange getRange(String dateRangeString) throws ParseException { if (dateRangeString == null || dateRangeString.isEmpty()) return null; String[] dateArr = dateRangeString.split("-"); if (dateArr.length > 2 || dateArr.length < 1) return null; // throw new IllegalArgumentException("Only Strings containing two Date separated by a '-' or a single Date are allowed"); ParsedCalendar from = parseDateString(dateArr[0]); ParsedCalendar to; if (dateArr.length == 2) to = parseDateString(dateArr[1]); else // faster and safe? // to = new ParsedCalendar(from.parseType, (Calendar) from.parsedCalendar.clone()); to = parseDateString(dateArr[0]); try { return new DateRange(from, to); } catch (IllegalArgumentException ex) { return null; } } @Override public ConditionState checkCondition(String dateRangeString) throws ParseException { DateRange dr = getRange(dateRangeString); if (dr == null) return ConditionState.INVALID; if (dr.isInRange(date)) return ConditionState.TRUE; else return ConditionState.FALSE; } public static DateRangeParser createInstance(String day) { Calendar calendar = createCalendar(); try { if (!day.isEmpty()) calendar.setTime(Helper.createFormatter("yyyy-MM-dd").parse(day)); } catch (ParseException e) { throw new IllegalArgumentException(e); } return new DateRangeParser(calendar); } private static SimpleDateFormat create3CharMonthFormatter(String pattern) { DateFormatSymbols formatSymbols = new DateFormatSymbols(Locale.ENGLISH); formatSymbols.setShortMonths(new String[]{"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}); SimpleDateFormat df = new SimpleDateFormat(pattern, formatSymbols); df.setTimeZone(Helper.UTC); return df; } }
// Use locale US as exception here (instead of UK) to match week order "Su-Sa" used in Calendar for day_of_week. // Inconsistent but we should not use US for other date handling stuff like strange default formatting, related to #647. return Calendar.getInstance(Helper.UTC, Locale.US);
1,354
83
1,437
Kong_unirest-java
unirest-java/unirest/src/main/java/kong/unirest/core/java/MonitoringInputStream.java
MonitoringInputStream
updateProgress
class MonitoringInputStream extends InputStream { private final InputStream in; private volatile long totalNumBytesRead = 0; private ProgressMonitor monitor; public MonitoringInputStream(InputStream value, ProgressMonitor monitor) { this.in = value; this.monitor = monitor; } @Override public int read() throws IOException { return (int)updateProgress(in.read()); } @Override public int read(byte[] b) throws IOException { return (int)updateProgress(in.read(b)); } @Override public int read(byte[] b, int off, int len) throws IOException { return (int)updateProgress(in.read(b, off, len)); } @Override public long skip(long n) throws IOException { return updateProgress(in.skip(n)); } @Override public int available() throws IOException { return in.available(); } @Override public void close() throws IOException { in.close(); } @Override public synchronized void mark(int readlimit) { in.mark(readlimit); } @Override public synchronized void reset() throws IOException { in.reset(); } @Override public boolean markSupported() { return in.markSupported(); } private long updateProgress(long numBytesRead) {<FILL_FUNCTION_BODY>} }
if (numBytesRead > 0) { this.totalNumBytesRead += numBytesRead; monitor.accept("body", null, numBytesRead, totalNumBytesRead); } return numBytesRead;
372
57
429
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-serializer/autoload-cache-serializer-protobuf/src/main/java/com/jarvis/cache/serializer/protobuf/ReadByteBuf.java
ReadByteBuf
readableBytes
class ReadByteBuf { private byte[] array; private int readerIndex; public ReadByteBuf(byte[] array) { this.array = array; this.readerIndex = 0; } public byte readByte() { byte value = HeapByteBufUtil.getByte(array, readerIndex); readerIndex += 1; return value; } public int readInt() { int value = HeapByteBufUtil.getInt(array, readerIndex); readerIndex += 4; return value; } public long readLong() { long value = HeapByteBufUtil.getLong(array, readerIndex); readerIndex += 8; return value; } public byte[] readableBytes() {<FILL_FUNCTION_BODY>} }
byte[] newArray = new byte[array.length - readerIndex]; System.arraycopy(array, readerIndex, newArray, 0, newArray.length); return newArray;
209
49
258
subhra74_snowflake
snowflake/muon-app/src/main/java/muon/app/ssh/GraphicalHostKeyVerifier.java
GraphicalHostKeyVerifier
hostKeyChangedAction
class GraphicalHostKeyVerifier extends OpenSSHKnownHosts { /** * @throws IOException * */ public GraphicalHostKeyVerifier(File knownHostFile) throws IOException { super(knownHostFile); } @Override protected boolean hostKeyUnverifiableAction(String hostname, PublicKey key) { final KeyType type = KeyType.fromKey(key); int resp = JOptionPane.showConfirmDialog(null, String.format( "The authenticity of host '%s' can't be established.\n" + "%s key fingerprint is %s.\nAre you sure you want to continue connecting (yes/no)?", hostname, type, SecurityUtils.getFingerprint(key))); if (resp == JOptionPane.YES_OPTION) { try { this.entries.add(new HostEntry(null, hostname, KeyType.fromKey(key), key)); write(); } catch (Exception e) { e.printStackTrace(); //throw new RuntimeException(e); } return true; } return false; } @Override protected boolean hostKeyChangedAction(String hostname, PublicKey key) {<FILL_FUNCTION_BODY>} @Override public boolean verify(String hostname, int port, PublicKey key) { try { if (!super.verify(hostname, port, key)) { return this.hostKeyUnverifiableAction(hostname, key); } return true; } catch (Exception e) { e.printStackTrace(); return this.hostKeyUnverifiableAction(hostname, key); } } }
final KeyType type = KeyType.fromKey(key); final String fp = SecurityUtils.getFingerprint(key); final String path = getFile().getAbsolutePath(); String msg = String.format("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n" + "@ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @\n" + "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n" + "IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!\n" + "Someone could be eavesdropping on you right now (man-in-the-middle attack)!\n" + "It is also possible that the host key has just been changed.\n" + "The fingerprint for the %s key sent by the remote host is\n" + "%s.\n" + "Do you still want to connect to this server?", type, fp, path); return JOptionPane.showConfirmDialog(null, msg) == JOptionPane.YES_OPTION;
480
326
806
elunez_eladmin
eladmin/eladmin-common/src/main/java/me/zhengjie/exception/EntityNotFoundException.java
EntityNotFoundException
generateMessage
class EntityNotFoundException extends RuntimeException { public EntityNotFoundException(Class clazz, String field, String val) { super(EntityNotFoundException.generateMessage(clazz.getSimpleName(), field, val)); } private static String generateMessage(String entity, String field, String val) {<FILL_FUNCTION_BODY>} }
return StringUtils.capitalize(entity) + " with " + field + " "+ val + " does not exist";
88
34
122
joelittlejohn_jsonschema2pojo
jsonschema2pojo/jsonschema2pojo-core/src/main/java/org/jsonschema2pojo/rules/DescriptionRule.java
DescriptionRule
apply
class DescriptionRule implements Rule<JDocCommentable, JDocComment> { protected DescriptionRule() { } /** * Applies this schema rule to take the required code generation steps. * <p> * When a description node is found and applied with this rule, the value of * the description is added as a class level JavaDoc comment. * * @param nodeName * the name of the object to which this description applies * @param node * the "description" 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;
243
101
344
subhra74_snowflake
snowflake/muon-app/src/main/java/muon/app/ui/components/session/files/view/DndTransferData.java
DndTransferData
toString
class DndTransferData implements Serializable { public enum DndSourceType { SSH, SFTP, FTP, LOCAL } public enum TransferAction { DragDrop, Cut, Copy } private int sessionHashcode; private FileInfo[] files; private String currentDirectory; private int source; private TransferAction transferAction = TransferAction.DragDrop; private DndSourceType sourceType; public DndTransferData(int sessionHashcode, FileInfo[] files, String currentDirectory, int source, DndSourceType sourceType) { this.sessionHashcode = sessionHashcode; this.files = files; this.currentDirectory = currentDirectory; this.source = source; this.sourceType = sourceType; } @Override public String toString() {<FILL_FUNCTION_BODY>} public int getInfo() { return sessionHashcode; } public void setInfo(int info) { this.sessionHashcode = info; } public FileInfo[] getFiles() { return files; } public void setFiles(FileInfo[] files) { this.files = files; } public String getCurrentDirectory() { return currentDirectory; } public void setCurrentDirectory(String currentDirectory) { this.currentDirectory = currentDirectory; } public int getSource() { return source; } public void setSource(int source) { this.source = source; } public TransferAction getTransferAction() { return transferAction; } public void setTransferAction(TransferAction transferAction) { this.transferAction = transferAction; } public DndSourceType getSourceType() { return sourceType; } }
return "DndTransferData{" + "sessionHashcode=" + sessionHashcode + ", files=" + Arrays.toString(files) + ", currentDirectory='" + currentDirectory + '\'' + '}';
513
61
574
zhkl0228_unidbg
unidbg/unidbg-api/src/main/java/com/github/unidbg/TraceMemoryHook.java
TraceMemoryHook
hook
class TraceMemoryHook implements ReadHook, WriteHook, TraceHook { private final boolean read; private final DateFormat dateFormat = new SimpleDateFormat("[HH:mm:ss SSS]"); public TraceMemoryHook(boolean read) { this.read = read; } private PrintStream redirect; TraceReadListener traceReadListener; TraceWriteListener traceWriteListener; private UnHook unHook; @Override public void onAttach(UnHook unHook) { if (this.unHook != null) { throw new IllegalStateException(); } this.unHook = unHook; } @Override public void detach() { if (unHook != null) { unHook.unhook(); unHook = null; } } @Override public void stopTrace() { detach(); IOUtils.close(redirect); redirect = null; } @Override public void setRedirect(PrintStream redirect) { this.redirect = redirect; } @Override public void hook(Backend backend, long address, int size, Object user) {<FILL_FUNCTION_BODY>} private void printMsg(String type, Emulator<?> emulator, long address, int size, String value) { RegisterContext context = emulator.getContext(); UnidbgPointer pc = context.getPCPointer(); UnidbgPointer lr = context.getLRPointer(); PrintStream out = System.out; if (redirect != null) { out = redirect; } StringBuilder builder = new StringBuilder(); builder.append(type).append(Long.toHexString(address)); if (size > 0) { builder.append(", data size = ").append(size).append(", data value = ").append(value); } builder.append(", PC=").append(pc).append(", LR=").append(lr); out.println(builder); } @Override public void hook(Backend backend, long address, int size, long value, Object user) { if (read) { return; } try { Emulator<?> emulator = (Emulator<?>) user; if (traceWriteListener == null || traceWriteListener.onWrite(emulator, address, size, value)) { String str; switch (size) { case 1: str = String.format("0x%02x", value & 0xff); break; case 2: str = String.format("0x%04x", value & 0xffff); break; case 4: str = String.format("0x%08x", value & 0xffffffffL); break; case 8: str = String.format("0x%016x", value); break; default: str = "0x" + Long.toHexString(value); break; } printMsg(dateFormat.format(new Date()) + " Memory WRITE at 0x", emulator, address, size, str); } } catch (BackendException e) { throw new IllegalStateException(e); } } }
if (!read) { return; } try { byte[] data = size == 0 ? new byte[0] : backend.mem_read(address, size); String value; switch (data.length) { case 1: value = String.format("0x%02x", ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN).get() & 0xff); break; case 2: value = String.format("0x%04x", ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN).getShort() & 0xffff); break; case 4: value = String.format("0x%08x", ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN).getInt() & 0xffffffffL); break; case 8: value = String.format("0x%016x", ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN).getLong()); break; default: value = "0x" + Hex.encodeHexString(data); break; } Emulator<?> emulator = (Emulator<?>) user; if (traceReadListener == null || traceReadListener.onRead(emulator, address, data, value)) { printMsg(dateFormat.format(new Date()) + " Memory READ at 0x", emulator, address, size, value); } } catch (BackendException e) { throw new IllegalStateException(e); }
846
408
1,254
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-manager/autoload-cache-manager-jedis/src/main/java/com/jarvis/cache/redis/ShardedJedisCacheManager.java
ShardedJedisClient
delete
class ShardedJedisClient implements IRedis { private static final Logger LOGGER = LoggerFactory.getLogger(ShardedJedisClient.class); private final ShardedJedis shardedJedis; private final AbstractRedisCacheManager cacheManager; public ShardedJedisClient(ShardedJedis shardedJedis, AbstractRedisCacheManager cacheManager) { this.shardedJedis = shardedJedis; this.cacheManager = cacheManager; } @Override public void close() throws IOException { if (null != shardedJedis) { shardedJedis.close(); } } @Override public void set(byte[] key, byte[] value) { Jedis jedis = shardedJedis.getShard(key); jedis.set(key, value); } @Override public void setex(byte[] key, int seconds, byte[] value) { Jedis jedis = shardedJedis.getShard(key); jedis.setex(key, seconds, value); } @Override public void hset(byte[] key, byte[] field, byte[] value) { Jedis jedis = shardedJedis.getShard(key); jedis.hset(key, field, value); } @Override public void hset(byte[] key, byte[] field, byte[] value, int seconds) { Jedis jedis = shardedJedis.getShard(key); Pipeline pipeline = jedis.pipelined(); pipeline.hset(key, field, value); pipeline.expire(key, seconds); pipeline.sync(); } @Override public void mset(Collection<MSetParam> params) { ShardedJedisPipeline pipeline = new ShardedJedisPipeline(); pipeline.setShardedJedis(shardedJedis); try { JedisUtil.executeMSet(pipeline, this.cacheManager, params); } catch (Exception ex) { LOGGER.error(ex.getMessage(), ex); } pipeline.sync(); } @Override public byte[] get(byte[] key) { Jedis jedis = shardedJedis.getShard(key); return jedis.get(key); } @Override public byte[] hget(byte[] key, byte[] field) { Jedis jedis = shardedJedis.getShard(key); return jedis.hget(key, field); } @Override public Map<CacheKeyTO, CacheWrapper<Object>> mget(Type returnType, Set<CacheKeyTO> keys) throws Exception { ShardedJedisPipeline pipeline = new ShardedJedisPipeline(); pipeline.setShardedJedis(shardedJedis); JedisUtil.executeMGet(pipeline, keys); Collection<Object> values = pipeline.syncAndReturnAll(); return cacheManager.deserialize(keys, values, returnType); } @Override public void delete(Set<CacheKeyTO> keys) {<FILL_FUNCTION_BODY>} }
ShardedJedisPipeline pipeline = new ShardedJedisPipeline(); pipeline.setShardedJedis(shardedJedis); JedisUtil.executeDelete(pipeline, keys); pipeline.sync();
842
61
903
obsidiandynamics_kafdrop
kafdrop/src/main/java/kafdrop/config/ini/IniFilePropertySource.java
IniFilePropertySource
loadPropertiesForIniFile
class IniFilePropertySource extends MapPropertySource { public IniFilePropertySource(String name, IniFileProperties source, String[] activeProfiles) { super(name, loadPropertiesForIniFile(source, activeProfiles)); } private static Map<String, Object> loadPropertiesForIniFile(IniFileProperties iniProperties, String[] activeProfiles) {<FILL_FUNCTION_BODY>} }
final Map<String, Object> properties = Maps.newLinkedHashMap(); properties.putAll(iniProperties.getDefaultProperties()); if (activeProfiles != null && activeProfiles.length > 0) { for (String profile : activeProfiles) { final Map<String, String> sectionProperties = iniProperties.getSectionProperties(profile); if (sectionProperties != null) { properties.putAll(sectionProperties); } } } return properties;
109
127
236
PlayEdu_PlayEdu
PlayEdu/playedu-common/src/main/java/xyz/playedu/common/service/impl/CategoryServiceImpl.java
CategoryServiceImpl
updateParentChain
class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService { @Override public List<Category> listByParentId(Integer id) { return list(query().getWrapper().eq("parent_id", id).orderByAsc("sort")); } @Override public List<Category> all() { return list(query().getWrapper().orderByAsc("sort")); } @Override public Category findOrFail(Integer id) throws NotFoundException { Category category = getById(id); if (category == null) { throw new NotFoundException("分类不存在"); } return category; } @Override @Transactional public void deleteById(Integer id) throws NotFoundException { Category category = findOrFail(id); // 更新parent_chain updateParentChain(category.getParentChain(), childrenParentChain(category)); // 删除记录 removeById(category.getId()); } @Override @Transactional public void update(Category category, String name, Integer parentId, Integer sort) throws NotFoundException { String childrenChainPrefix = childrenParentChain(category); Category data = new Category(); data.setId(category.getId()); data.setName(name); if (!category.getParentId().equals(parentId)) { data.setParentId(parentId); if (parentId.equals(0)) { data.setParentChain(""); } else { Category parentResourceCategory = findOrFail(parentId); data.setParentChain(childrenParentChain(parentResourceCategory)); } } if (!category.getSort().equals(sort)) { data.setSort(sort); } // 提交更换 updateById(data); category = getById(category.getId()); updateParentChain(childrenParentChain(category), childrenChainPrefix); } private void updateParentChain(String newChildrenPC, String oldChildrenPC) {<FILL_FUNCTION_BODY>} @Override public void create(String name, Integer parentId, Integer sort) throws NotFoundException { String parentChain = ""; if (parentId != 0) { parentChain = compParentChain(parentId); } Category category = new Category(); category.setName(name); category.setParentId(parentId); category.setParentChain(parentChain); category.setSort(sort); category.setCreatedAt(new Date()); category.setUpdatedAt(new Date()); save(category); } @Override public String childrenParentChain(Category category) { String prefix = category.getId() + ""; if (category.getParentChain() != null && category.getParentChain().length() > 0) { prefix = category.getParentChain() + "," + prefix; } return prefix; } @Override public String compParentChain(Integer parentId) throws NotFoundException { String parentChain = ""; if (parentId != 0) { Category parentResourceCategory = getById(parentId); if (parentResourceCategory == null) { throw new NotFoundException("父级分类不存在"); } String pc = parentResourceCategory.getParentChain(); parentChain = pc == null || pc.length() == 0 ? parentId + "" : pc + "," + parentId; } return parentChain; } @Override public void resetSort(List<Integer> ids) { if (ids == null || ids.size() == 0) { return; } List<Category> categories = new ArrayList<>(); int sortVal = 0; for (Integer idItem : ids) { Integer finalSortVal = ++sortVal; categories.add( new Category() { { setId(idItem); setSort(finalSortVal); } }); } updateBatchById(categories); } @Override @Transactional public void changeParent(Integer id, Integer parentId, List<Integer> ids) throws NotFoundException { Category category = findOrFail(id); update(category, category.getName(), parentId, category.getSort()); // 重置排序 resetSort(ids); } @Override public Map<Integer, List<Category>> groupByParent() { return list(query().getWrapper().orderByAsc("sort")).stream() .collect(Collectors.groupingBy(Category::getParentId)); } @Override public Map<Integer, String> id2name() { return all().stream().collect(Collectors.toMap(Category::getId, Category::getName)); } @Override public Long total() { return count(); } }
List<Category> children = list(query().getWrapper().like("parent_chain", oldChildrenPC + "%")); if (children.size() == 0) { return; } ArrayList<Category> updateRows = new ArrayList<>(); for (Category tmpResourceCategory : children) { Category tmpUpdateResourceCategory = new Category(); tmpUpdateResourceCategory.setId(tmpResourceCategory.getId()); // parentChain计算 String pc = newChildrenPC; if (!tmpResourceCategory.getParentChain().equals(oldChildrenPC)) { pc = tmpResourceCategory .getParentChain() .replaceFirst( oldChildrenPC + ",", newChildrenPC.length() == 0 ? newChildrenPC : newChildrenPC + ','); } tmpUpdateResourceCategory.setParentChain(pc); // parentId计算 int parentId = 0; if (pc != null && pc.length() > 0) { String[] parentIds = pc.split(","); parentId = Integer.parseInt(parentIds[parentIds.length - 1]); } tmpUpdateResourceCategory.setParentId(parentId); updateRows.add(tmpUpdateResourceCategory); } updateBatchById(updateRows);
1,231
318
1,549
YunaiV_ruoyi-vue-pro
ruoyi-vue-pro/yudao-framework/yudao-common/src/main/java/cn/iocoder/yudao/framework/common/util/collection/MapUtils.java
MapUtils
convertMap
class MapUtils { /** * 从哈希表表中,获得 keys 对应的所有 value 数组 * * @param multimap 哈希表 * @param keys keys * @return value 数组 */ public static <K, V> List<V> getList(Multimap<K, V> multimap, Collection<K> keys) { List<V> result = new ArrayList<>(); keys.forEach(k -> { Collection<V> values = multimap.get(k); if (CollectionUtil.isEmpty(values)) { return; } result.addAll(values); }); return result; } /** * 从哈希表查找到 key 对应的 value,然后进一步处理 * key 为 null 时, 不处理 * 注意,如果查找到的 value 为 null 时,不进行处理 * * @param map 哈希表 * @param key key * @param consumer 进一步处理的逻辑 */ public static <K, V> void findAndThen(Map<K, V> map, K key, Consumer<V> consumer) { if (ObjUtil.isNull(key) || CollUtil.isEmpty(map)) { return; } V value = map.get(key); if (value == null) { return; } consumer.accept(value); } public static <K, V> Map<K, V> convertMap(List<KeyValue<K, V>> keyValues) {<FILL_FUNCTION_BODY>} }
Map<K, V> map = Maps.newLinkedHashMapWithExpectedSize(keyValues.size()); keyValues.forEach(keyValue -> map.put(keyValue.getKey(), keyValue.getValue())); return map;
414
61
475
houbb_sensitive-word
sensitive-word/src/main/java/com/github/houbb/sensitive/word/support/deny/WordDenys.java
WordDenys
chains
class WordDenys { private WordDenys(){} /** * 责任链 * @param wordDeny 拒绝 * @param others 其他 * @return 结果 * @since 0.0.13 */ public static IWordDeny chains(final IWordDeny wordDeny, final IWordDeny... others) {<FILL_FUNCTION_BODY>} /** * 系统实现 * @return 结果 * @since 0.0.13 */ public static IWordDeny defaults() { return WordDenySystem.getInstance(); } }
return new WordDenyInit() { @Override protected void init(Pipeline<IWordDeny> pipeline) { pipeline.addLast(wordDeny); if(ArrayUtil.isNotEmpty(others)) { for(IWordDeny other : others) { pipeline.addLast(other); } } } };
166
94
260
jeecgboot_jeecg-boot
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/security/AbstractQueryBlackListHandler.java
AbstractQueryBlackListHandler
isPass
class AbstractQueryBlackListHandler { /** * key-表名 * value-字段名,多个逗号隔开 * 两种配置方式-- 全部配置成小写 * ruleMap.put("sys_user", "*")sys_user所有的字段不支持查询 * ruleMap.put("sys_user", "username,password")sys_user中的username和password不支持查询 */ public static Map<String, String> ruleMap = new HashMap<>(); /** * 以下字符不能出现在表名中或是字段名中 */ public static final Pattern ILLEGAL_NAME_REG = Pattern.compile("[-]{2,}"); static { ruleMap.put("sys_user", "password,salt"); } /** * 根据 sql语句 获取表和字段信息,需要到具体的实现类重写此方法- * 不同的场景 处理可能不太一样 需要自定义,但是返回值确定 * @param sql * @return */ protected abstract List<QueryTable> getQueryTableInfo(String sql); /** * 校验sql语句 成功返回true * @param sql * @return */ public boolean isPass(String sql) {<FILL_FUNCTION_BODY>} /** * 校验表名和字段名是否有效,或是是否会带些特殊的字符串进行sql注入 * issues/4983 SQL Injection in 3.5.1 #4983 * @return */ private boolean checkTableAndFieldsName(List<QueryTable> list){ boolean flag = true; for(QueryTable queryTable: list){ String tableName = queryTable.getName(); if(hasSpecialString(tableName)){ flag = false; log.warn("sql黑名单校验,表名【"+tableName+"】包含特殊字符"); break; } Set<String> fields = queryTable.getFields(); for(String name: fields){ if(hasSpecialString(name)){ flag = false; log.warn("sql黑名单校验,字段名【"+name+"】包含特殊字符"); break; } } } return flag; } /** * 是否包含特殊的字符串 * @param name * @return */ private boolean hasSpecialString(String name){ Matcher m = ILLEGAL_NAME_REG.matcher(name); if (m.find()) { return true; } return false; } /** * 查询的表的信息 */ protected class QueryTable { //表名 private String name; //表的别名 private String alias; // 字段名集合 private Set<String> fields; // 是否查询所有字段 private boolean all; public QueryTable() { } public QueryTable(String name, String alias) { this.name = name; this.alias = alias; this.all = false; this.fields = new HashSet<>(); } public void addField(String field) { this.fields.add(field); } public String getName() { return name; } public Set<String> getFields() { return new HashSet<>(fields); } public void setName(String name) { this.name = name; } public void setFields(Set<String> fields) { this.fields = fields; } public String getAlias() { return alias; } public void setAlias(String alias) { this.alias = alias; } public boolean isAll() { return all; } public void setAll(boolean all) { this.all = all; } /** * 判断是否有相同字段 * * @param fieldString * @return */ public boolean existSameField(String fieldString) { String[] controlFields = fieldString.split(","); for (String sqlField : fields) { for (String controlField : controlFields) { if (sqlField.equals(controlField)) { // 非常明确的列直接比较 log.warn("sql黑名单校验,表【"+name+"】中字段【"+controlField+"】禁止查询"); return true; } else { // 使用表达式的列 只能判读字符串包含了 String aliasColumn = controlField; if (StringUtils.isNotBlank(alias)) { aliasColumn = alias + "." + controlField; } if (sqlField.indexOf(aliasColumn) != -1) { log.warn("sql黑名单校验,表【"+name+"】中字段【"+controlField+"】禁止查询"); return true; } } } } return false; } @Override public String toString() { return "QueryTable{" + "name='" + name + '\'' + ", alias='" + alias + '\'' + ", fields=" + fields + ", all=" + all + '}'; } } public String getError(){ // TODO return "系统设置了安全规则,敏感表和敏感字段禁止查询,联系管理员授权!"; } }
List<QueryTable> list = null; //【jeecg-boot/issues/4040】在线报表不支持子查询,解析报错 #4040 try { list = this.getQueryTableInfo(sql.toLowerCase()); } catch (Exception e) { log.warn("校验sql语句,解析报错:{}",e.getMessage()); } if(list==null){ return true; } log.info(" 获取sql信息 :{} ", list.toString()); boolean flag = checkTableAndFieldsName(list); if(flag == false){ return false; } for (QueryTable table : list) { String name = table.getName(); String fieldRule = ruleMap.get(name); // 有没有配置这张表 if (fieldRule != null) { if ("*".equals(fieldRule) || table.isAll()) { flag = false; log.warn("sql黑名单校验,表【"+name+"】禁止查询"); break; } else if (table.existSameField(fieldRule)) { flag = false; break; } } } // 返回黑名单校验结果(不合法直接抛出异常) if(!flag){ log.error(this.getError()); throw new JeecgSqlInjectionException(this.getError()); } return flag;
1,425
378
1,803
eirslett_frontend-maven-plugin
frontend-maven-plugin/frontend-maven-plugin/src/main/java/com/github/eirslett/maven/plugins/frontend/mojo/InstallBunMojo.java
InstallBunMojo
execute
class InstallBunMojo extends AbstractFrontendMojo { /** * The version of Bun to install. IMPORTANT! Most Bun version names start with 'v', for example * 'v1.0.0' */ @Parameter(property = "bunVersion", required = true) private String bunVersion; /** * 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.installbun", alias = "skip.installbun", defaultValue = "${skip.installbun}") private boolean skip; @Component(role = SettingsDecrypter.class) private SettingsDecrypter decrypter; @Override protected boolean skipExecution() { return this.skip; } @Override public void execute(FrontendPluginFactory factory) throws InstallationException {<FILL_FUNCTION_BODY>} }
ProxyConfig proxyConfig = MojoUtils.getProxyConfig(this.session, this.decrypter); Server server = MojoUtils.decryptServer(this.serverId, this.session, this.decrypter); if (null != server) { factory.getBunInstaller(proxyConfig).setBunVersion(this.bunVersion).setUserName(server.getUsername()) .setPassword(server.getPassword()).install(); } else { factory.getBunInstaller(proxyConfig).setBunVersion(this.bunVersion).install(); }
307
150
457
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; }
PlayEdu_PlayEdu
PlayEdu/playedu-course/src/main/java/xyz/playedu/course/service/impl/CourseChapterServiceImpl.java
CourseChapterServiceImpl
findOrFail
class CourseChapterServiceImpl extends ServiceImpl<CourseChapterMapper, CourseChapter> implements CourseChapterService { @Override public void create(Integer courseId, String name, Integer sort) { CourseChapter chapter = new CourseChapter(); chapter.setCourseId(courseId); chapter.setName(name); chapter.setSort(sort); chapter.setCreatedAt(new Date()); chapter.setUpdatedAt(new Date()); save(chapter); } @Override public void update(CourseChapter chapter, String name, Integer sort) { CourseChapter newChapter = new CourseChapter(); newChapter.setId(chapter.getId()); newChapter.setName(name); newChapter.setSort(sort); updateById(newChapter); } @Override public CourseChapter findOrFail(Integer id) throws NotFoundException { CourseChapter chapter = getOne(query().getWrapper().eq("id", id)); if (chapter == null) { throw new NotFoundException("章节不存在"); } return chapter; } @Override public List<CourseChapter> getChaptersByCourseId(Integer courseId) { return list(query().getWrapper().eq("course_id", courseId).orderByAsc("sort")); } @Override public CourseChapter findOrFail(Integer id, Integer courseId) throws NotFoundException {<FILL_FUNCTION_BODY>} @Override public void updateSort(List<Integer> ids, Integer cid) { if (ids == null || ids.size() == 0) { return; } List<CourseChapter> chapters = new ArrayList<>(); final Integer[] sortVal = {0}; for (Integer idItem : ids) { chapters.add( new CourseChapter() { { setId(idItem); setId(cid); setSort(sortVal[0]++); } }); } updateBatchById(chapters); } }
CourseChapter chapter = getOne(query().getWrapper().eq("id", id).eq("course_id", courseId)); if (chapter == null) { throw new NotFoundException("章节不存在"); } return chapter;
520
63
583
javamelody_javamelody
javamelody/javamelody-core/src/main/java/net/bull/javamelody/JpaPersistence.java
JavaMelodyPersistenceProviderResolver
initJpaCounter
class JavaMelodyPersistenceProviderResolver implements PersistenceProviderResolver { private final PersistenceProviderResolver delegate; JavaMelodyPersistenceProviderResolver(PersistenceProviderResolver delegate) { super(); this.delegate = delegate; } @Override public List<PersistenceProvider> getPersistenceProviders() { // avant de retourner la liste des persistence providers // on met notre JpaPersistence en premier pour qu'il soit toujours choisi // et qu'il délègue au persistence provider final final List<PersistenceProvider> providers = delegate.getPersistenceProviders(); final List<PersistenceProvider> result = new ArrayList<>(); for (final PersistenceProvider provider : providers) { if (provider instanceof JpaPersistence) { result.add(0, provider); } else { result.add(provider); } } return result; } @Override public void clearCachedProviders() { delegate.clearCachedProviders(); } } /** * Active le monitoring JPA par défaut, * même si <provider>net.bull.javamelody.JpaPersistence</provider> n'est pas dans META-INF/persistence.xml */ public static void initPersistenceProviderResolver() { try { PersistenceProviderResolver resolver = PersistenceProviderResolverHolder .getPersistenceProviderResolver(); if (!(resolver instanceof JavaMelodyPersistenceProviderResolver)) { resolver = new JavaMelodyPersistenceProviderResolver(resolver); PersistenceProviderResolverHolder.setPersistenceProviderResolver(resolver); LOG.debug("JPA persistence provider resolver initialized"); } } catch (final Throwable t) { // NOPMD LOG.info("initialization of jpa persistence provider resolver failed, skipping"); } } // cette classe est instanciée dès le démarrage (WildFly notamment), // il ne faut donc pas appeler initJpaCounter() dans le constructeur private void initJpaCounter() {<FILL_FUNCTION_BODY>
// quand cette classe est utilisée, le compteur est affiché // sauf si le paramètre displayed-counters dit le contraire JPA_COUNTER.setDisplayed(!COUNTER_HIDDEN); // setUsed(true) nécessaire ici si le contexte jpa est initialisé avant FilterContext // sinon les statistiques jpa ne sont pas affichées JPA_COUNTER.setUsed(true); LOG.debug("jpa persistence initialized");
615
147
762
jeecgboot_jeecg-boot
jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/message/handle/impl/QywxSendMsgHandle.java
QywxSendMsgHandle
sendMsg
class QywxSendMsgHandle implements ISendMsgHandle { @Autowired private ThirdAppWechatEnterpriseServiceImpl wechatEnterpriseService; @Override public void sendMsg(String esReceiver, String esTitle, String esContent) {<FILL_FUNCTION_BODY>} @Override public void sendMessage(MessageDTO messageDTO) { wechatEnterpriseService.sendMessage(messageDTO, true); } }
log.info("发微信消息模板"); MessageDTO messageDTO = new MessageDTO(); messageDTO.setToUser(esReceiver); messageDTO.setTitle(esTitle); messageDTO.setContent(esContent); messageDTO.setToAll(false); sendMessage(messageDTO);
113
95
208
spring-cloud_spring-cloud-gateway
spring-cloud-gateway/spring-cloud-gateway-server/src/main/java/org/springframework/cloud/gateway/route/RedisRouteDefinitionRepository.java
RedisRouteDefinitionRepository
delete
class RedisRouteDefinitionRepository implements RouteDefinitionRepository { private static final Logger log = LoggerFactory.getLogger(RedisRouteDefinitionRepository.class); /** * Key prefix for RouteDefinition queries to redis. */ private static final String ROUTEDEFINITION_REDIS_KEY_PREFIX_QUERY = "routedefinition_"; private ReactiveRedisTemplate<String, RouteDefinition> reactiveRedisTemplate; private ReactiveValueOperations<String, RouteDefinition> routeDefinitionReactiveValueOperations; public RedisRouteDefinitionRepository(ReactiveRedisTemplate<String, RouteDefinition> reactiveRedisTemplate) { this.reactiveRedisTemplate = reactiveRedisTemplate; this.routeDefinitionReactiveValueOperations = reactiveRedisTemplate.opsForValue(); } @Override public Flux<RouteDefinition> getRouteDefinitions() { return reactiveRedisTemplate.scan(ScanOptions.scanOptions().match(createKey("*")).build()) .flatMap(key -> reactiveRedisTemplate.opsForValue().get(key)) .onErrorContinue((throwable, routeDefinition) -> { if (log.isErrorEnabled()) { log.error("get routes from redis error cause : {}", throwable.toString(), throwable); } }); } @Override public Mono<Void> save(Mono<RouteDefinition> route) { return route.flatMap(routeDefinition -> routeDefinitionReactiveValueOperations .set(createKey(routeDefinition.getId()), routeDefinition).flatMap(success -> { if (success) { return Mono.empty(); } return Mono.defer(() -> Mono.error(new RuntimeException( String.format("Could not add route to redis repository: %s", routeDefinition)))); })); } @Override public Mono<Void> delete(Mono<String> routeId) {<FILL_FUNCTION_BODY>} private String createKey(String routeId) { return ROUTEDEFINITION_REDIS_KEY_PREFIX_QUERY + routeId; } }
return routeId.flatMap(id -> routeDefinitionReactiveValueOperations.delete(createKey(id)).flatMap(success -> { if (success) { return Mono.empty(); } return Mono.defer(() -> Mono.error(new NotFoundException( String.format("Could not remove route from redis repository with id: %s", routeId)))); }));
532
105
637
orientechnologies_orientdb
orientdb/core/src/main/java/com/orientechnologies/orient/core/sql/executor/FetchTemporaryFromTxStep.java
FetchTemporaryFromTxStep
deserialize
class FetchTemporaryFromTxStep extends AbstractExecutionStep { private String className; private Object order; public FetchTemporaryFromTxStep(OCommandContext ctx, String className, boolean profilingEnabled) { super(ctx, profilingEnabled); this.className = className; } @Override public OExecutionStream internalStart(OCommandContext ctx) throws OTimeoutException { getPrev().ifPresent(x -> x.start(ctx).close(ctx)); Iterator<ORecord> data = null; data = init(ctx); if (data == null) { data = Collections.emptyIterator(); } OExecutionStream resultSet = OExecutionStream.iterator((Iterator) data).map(this::setContext); return resultSet; } private OResult setContext(OResult result, OCommandContext context) { context.setVariable("$current", result); return result; } private Iterator<ORecord> init(OCommandContext ctx) { Iterable<? extends ORecordOperation> iterable = ctx.getDatabase().getTransaction().getRecordOperations(); List<ORecord> records = new ArrayList<>(); if (iterable != null) { for (ORecordOperation op : iterable) { ORecord record = op.getRecord(); if (matchesClass(record, className) && !hasCluster(record)) records.add(record); } } if (order == FetchFromClusterExecutionStep.ORDER_ASC) { Collections.sort( records, new Comparator<ORecord>() { @Override public int compare(ORecord o1, ORecord o2) { long p1 = o1.getIdentity().getClusterPosition(); long p2 = o2.getIdentity().getClusterPosition(); if (p1 == p2) { return 0; } else if (p1 > p2) { return 1; } else { return -1; } } }); } else { Collections.sort( records, new Comparator<ORecord>() { @Override public int compare(ORecord o1, ORecord o2) { long p1 = o1.getIdentity().getClusterPosition(); long p2 = o2.getIdentity().getClusterPosition(); if (p1 == p2) { return 0; } else if (p1 > p2) { return -1; } else { return 1; } } }); } return records.iterator(); } private boolean hasCluster(ORecord record) { ORID rid = record.getIdentity(); if (rid == null) { return false; } if (rid.getClusterId() < 0) { return false; } return true; } private boolean matchesClass(ORecord record, String className) { ORecord doc = record.getRecord(); if (!(doc instanceof ODocument)) { return false; } OClass schema = ODocumentInternal.getImmutableSchemaClass(((ODocument) doc)); if (schema == null) return className == null; else if (schema.getName().equals(className)) { return true; } else if (schema.isSubClassOf(className)) { return true; } return false; } public void setOrder(Object order) { this.order = order; } @Override public String prettyPrint(int depth, int indent) { String spaces = OExecutionStepInternal.getIndent(depth, indent); StringBuilder result = new StringBuilder(); result.append(spaces); result.append("+ FETCH NEW RECORDS FROM CURRENT TRANSACTION SCOPE (if any)"); if (profilingEnabled) { result.append(" (" + getCostFormatted() + ")"); } return result.toString(); } @Override public OResult serialize() { OResultInternal result = OExecutionStepInternal.basicSerialize(this); result.setProperty("className", className); return result; } @Override public void deserialize(OResult fromResult) {<FILL_FUNCTION_BODY>} @Override public boolean canBeCached() { return true; } @Override public OExecutionStep copy(OCommandContext ctx) { FetchTemporaryFromTxStep result = new FetchTemporaryFromTxStep(ctx, this.className, profilingEnabled); return result; } }
try { OExecutionStepInternal.basicDeserialize(fromResult, this); className = fromResult.getProperty("className"); } catch (Exception e) { throw OException.wrapException(new OCommandExecutionException(""), e); }
1,195
66
1,261
/** * @author Luigi Dell'Aquila (l.dellaquila-(at)-orientdb.com) */ public abstract class AbstractExecutionStep implements OExecutionStepInternal { protected final OCommandContext ctx; protected Optional<OExecutionStepInternal> prev=Optional.empty(); protected Optional<OExecutionStepInternal> next=Optional.empty(); protected boolean profilingEnabled=false; public AbstractExecutionStep( OCommandContext ctx, boolean profilingEnabled); @Override public void setPrevious( OExecutionStepInternal step); @Override public void setNext( OExecutionStepInternal step); public OCommandContext getContext(); public Optional<OExecutionStepInternal> getPrev(); public Optional<OExecutionStepInternal> getNext(); @Override public void sendTimeout(); private boolean alreadyClosed=false; private long baseCost=0; @Override public void close(); public boolean isProfilingEnabled(); public void setProfilingEnabled( boolean profilingEnabled); public OExecutionStream start( OCommandContext ctx) throws OTimeoutException; protected abstract OExecutionStream internalStart( OCommandContext ctx) throws OTimeoutException ; @Override public long getCost(); protected String getCostFormatted(); }
PlayEdu_PlayEdu
PlayEdu/playedu-common/src/main/java/xyz/playedu/common/domain/AdminUserRole.java
AdminUserRole
hashCode
class AdminUserRole implements Serializable { @JsonProperty("admin_id") private Integer adminId; @JsonProperty("role_id") private Integer roleId; @TableField(exist = false) private static final long serialVersionUID = 1L; @Override public boolean equals(Object that) { if (this == that) { return true; } if (that == null) { return false; } if (getClass() != that.getClass()) { return false; } AdminUserRole other = (AdminUserRole) that; return (this.getAdminId() == null ? other.getAdminId() == null : this.getAdminId().equals(other.getAdminId())) && (this.getRoleId() == null ? other.getRoleId() == null : this.getRoleId().equals(other.getRoleId())); } @Override public int hashCode() {<FILL_FUNCTION_BODY>} @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", adminId=").append(adminId); sb.append(", roleId=").append(roleId); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
final int prime = 31; int result = 1; result = prime * result + ((getAdminId() == null) ? 0 : getAdminId().hashCode()); result = prime * result + ((getRoleId() == null) ? 0 : getRoleId().hashCode()); return result;
393
78
471
YunaiV_ruoyi-vue-pro
ruoyi-vue-pro/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/demo/demo02/Demo02CategoryServiceImpl.java
Demo02CategoryServiceImpl
validateParentDemo02Category
class Demo02CategoryServiceImpl implements Demo02CategoryService { @Resource private Demo02CategoryMapper demo02CategoryMapper; @Override public Long createDemo02Category(Demo02CategorySaveReqVO createReqVO) { // 校验父级编号的有效性 validateParentDemo02Category(null, createReqVO.getParentId()); // 校验名字的唯一性 validateDemo02CategoryNameUnique(null, createReqVO.getParentId(), createReqVO.getName()); // 插入 Demo02CategoryDO demo02Category = BeanUtils.toBean(createReqVO, Demo02CategoryDO.class); demo02CategoryMapper.insert(demo02Category); // 返回 return demo02Category.getId(); } @Override public void updateDemo02Category(Demo02CategorySaveReqVO updateReqVO) { // 校验存在 validateDemo02CategoryExists(updateReqVO.getId()); // 校验父级编号的有效性 validateParentDemo02Category(updateReqVO.getId(), updateReqVO.getParentId()); // 校验名字的唯一性 validateDemo02CategoryNameUnique(updateReqVO.getId(), updateReqVO.getParentId(), updateReqVO.getName()); // 更新 Demo02CategoryDO updateObj = BeanUtils.toBean(updateReqVO, Demo02CategoryDO.class); demo02CategoryMapper.updateById(updateObj); } @Override public void deleteDemo02Category(Long id) { // 校验存在 validateDemo02CategoryExists(id); // 校验是否有子示例分类 if (demo02CategoryMapper.selectCountByParentId(id) > 0) { throw exception(DEMO02_CATEGORY_EXITS_CHILDREN); } // 删除 demo02CategoryMapper.deleteById(id); } private void validateDemo02CategoryExists(Long id) { if (demo02CategoryMapper.selectById(id) == null) { throw exception(DEMO02_CATEGORY_NOT_EXISTS); } } private void validateParentDemo02Category(Long id, Long parentId) {<FILL_FUNCTION_BODY>} private void validateDemo02CategoryNameUnique(Long id, Long parentId, String name) { Demo02CategoryDO demo02Category = demo02CategoryMapper.selectByParentIdAndName(parentId, name); if (demo02Category == null) { return; } // 如果 id 为空,说明不用比较是否为相同 id 的示例分类 if (id == null) { throw exception(DEMO02_CATEGORY_NAME_DUPLICATE); } if (!Objects.equals(demo02Category.getId(), id)) { throw exception(DEMO02_CATEGORY_NAME_DUPLICATE); } } @Override public Demo02CategoryDO getDemo02Category(Long id) { return demo02CategoryMapper.selectById(id); } @Override public List<Demo02CategoryDO> getDemo02CategoryList(Demo02CategoryListReqVO listReqVO) { return demo02CategoryMapper.selectList(listReqVO); } }
if (parentId == null || Demo02CategoryDO.PARENT_ID_ROOT.equals(parentId)) { return; } // 1. 不能设置自己为父示例分类 if (Objects.equals(id, parentId)) { throw exception(DEMO02_CATEGORY_PARENT_ERROR); } // 2. 父示例分类不存在 Demo02CategoryDO parentDemo02Category = demo02CategoryMapper.selectById(parentId); if (parentDemo02Category == null) { throw exception(DEMO02_CATEGORY_PARENT_NOT_EXITS); } // 3. 递归校验父示例分类,如果父示例分类是自己的子示例分类,则报错,避免形成环路 if (id == null) { // id 为空,说明新增,不需要考虑环路 return; } for (int i = 0; i < Short.MAX_VALUE; i++) { // 3.1 校验环路 parentId = parentDemo02Category.getParentId(); if (Objects.equals(id, parentId)) { throw exception(DEMO02_CATEGORY_PARENT_IS_CHILD); } // 3.2 继续递归下一级父示例分类 if (parentId == null || Demo02CategoryDO.PARENT_ID_ROOT.equals(parentId)) { break; } parentDemo02Category = demo02CategoryMapper.selectById(parentId); if (parentDemo02Category == null) { break; } }
916
427
1,343
logfellow_logstash-logback-encoder
logstash-logback-encoder/src/main/java/net/logstash/logback/composite/loggingevent/LogstashMarkersJsonProvider.java
LogstashMarkersJsonProvider
writeLogstashMarkerIfNecessary
class LogstashMarkersJsonProvider extends AbstractJsonProvider<ILoggingEvent> { @Override public void writeTo(JsonGenerator generator, ILoggingEvent event) throws IOException { writeLogstashMarkerIfNecessary(generator, event.getMarkerList()); } private void writeLogstashMarkerIfNecessary(JsonGenerator generator, List<Marker> markers) throws IOException { if (markers != null) { for (Marker marker: markers) { writeLogstashMarkerIfNecessary(generator, marker); } } } private void writeLogstashMarkerIfNecessary(JsonGenerator generator, Marker marker) throws IOException {<FILL_FUNCTION_BODY>} public static boolean isLogstashMarker(Marker marker) { return marker instanceof LogstashMarker; } }
if (marker != null) { if (isLogstashMarker(marker)) { ((LogstashMarker) marker).writeTo(generator); } if (marker.hasReferences()) { for (Iterator<?> i = marker.iterator(); i.hasNext();) { Marker next = (Marker) i.next(); writeLogstashMarkerIfNecessary(generator, next); } } }
217
119
336
eirslett_frontend-maven-plugin
frontend-maven-plugin/frontend-maven-plugin/src/main/java/com/github/eirslett/maven/plugins/frontend/mojo/BowerMojo.java
BowerMojo
getProxyConfig
class BowerMojo extends AbstractFrontendMojo { /** * Bower arguments. Default is "install". */ @Parameter(defaultValue = "install", property = "frontend.bower.arguments", required = false) private String arguments; /** * Skips execution of this mojo. */ @Parameter(property = "skip.bower", defaultValue = "${skip.bower}") private boolean skip; @Parameter(property = "session", defaultValue = "${session}", readonly = true) private MavenSession session; @Parameter(property = "frontend.bower.bowerInheritsProxyConfigFromMaven", required = false, defaultValue = "true") private boolean bowerInheritsProxyConfigFromMaven; @Component(role = SettingsDecrypter.class) private SettingsDecrypter decrypter; @Override protected boolean skipExecution() { return this.skip; } @Override protected synchronized void execute(FrontendPluginFactory factory) throws TaskRunnerException { ProxyConfig proxyConfig = getProxyConfig(); factory.getBowerRunner(proxyConfig).execute(arguments, environmentVariables); } private ProxyConfig getProxyConfig() {<FILL_FUNCTION_BODY>} }
if (bowerInheritsProxyConfigFromMaven) { return MojoUtils.getProxyConfig(session, decrypter); } else { getLog().info("bower not inheriting proxy config from Maven"); return new ProxyConfig(Collections.<ProxyConfig.Proxy>emptyList()); }
336
83
419
public abstract class AbstractFrontendMojo extends AbstractMojo { @Component protected MojoExecution execution; /** * Whether you should skip while running in the test phase (default is false) */ @Parameter(property="skipTests",required=false,defaultValue="false") protected Boolean skipTests; /** * Set this to true to ignore a failure during testing. Its use is NOT RECOMMENDED, but quite convenient on occasion. * @since 1.4 */ @Parameter(property="maven.test.failure.ignore",defaultValue="false") protected boolean testFailureIgnore; /** * The base directory for running all Node commands. (Usually the directory that contains package.json) */ @Parameter(defaultValue="${basedir}",property="workingDirectory",required=false) protected File workingDirectory; /** * The base directory for installing node and npm. */ @Parameter(property="installDirectory",required=false) protected File installDirectory; /** * Additional environment variables to pass to the build. */ @Parameter protected Map<String,String> environmentVariables; @Parameter(defaultValue="${project}",readonly=true) private MavenProject project; @Parameter(defaultValue="${repositorySystemSession}",readonly=true) private RepositorySystemSession repositorySystemSession; /** * Determines if this execution should be skipped. */ private boolean skipTestPhase(); /** * Determines if the current execution is during a testing phase (e.g., "test" or "integration-test"). */ private boolean isTestingPhase(); protected abstract void execute( FrontendPluginFactory factory) throws FrontendException ; /** * Implemented by children to determine if this execution should be skipped. */ protected abstract boolean skipExecution(); @Override public void execute() throws MojoFailureException; }
orientechnologies_orientdb
orientdb/client/src/main/java/com/orientechnologies/orient/client/remote/message/ODeleteRecordRequest.java
ODeleteRecordRequest
read
class ODeleteRecordRequest implements OBinaryAsyncRequest<ODeleteRecordResponse> { private ORecordId rid; private int version; private byte mode; public ODeleteRecordRequest(ORecordId iRid, int iVersion) { this.rid = iRid; this.version = iVersion; } public ODeleteRecordRequest() {} @Override public byte getCommand() { return OChannelBinaryProtocol.REQUEST_RECORD_DELETE; } @Override public String getDescription() { return "Delete Record"; } public void read(OChannelDataInput channel, int protocolVersion, ORecordSerializer serializer) throws IOException {<FILL_FUNCTION_BODY>} @Override public void write(OChannelDataOutput network, OStorageRemoteSession session) throws IOException { network.writeRID(rid); network.writeVersion(version); network.writeByte((byte) mode); } public byte getMode() { return mode; } public ORecordId getRid() { return rid; } public int getVersion() { return version; } @Override public void setMode(byte mode) { this.mode = mode; } @Override public ODeleteRecordResponse createResponse() { return new ODeleteRecordResponse(); } @Override public OBinaryResponse execute(OBinaryRequestExecutor executor) { return executor.executeDeleteRecord(this); } }
rid = channel.readRID(); version = channel.readVersion(); mode = channel.readByte();
395
31
426
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/file/LocalDarwinUdpSocket.java
LocalDarwinUdpSocket
connect
class LocalDarwinUdpSocket extends LocalUdpSocket { private static final Log log = LogFactory.getLog(LocalDarwinUdpSocket.class); public LocalDarwinUdpSocket(Emulator<?> emulator) { super(emulator); } @Override public int connect(Pointer addr, int addrlen) {<FILL_FUNCTION_BODY>} @Override protected int connect(String path) { emulator.getMemory().setErrno(UnixEmulator.EPERM); return -1; } @Override public int getattrlist(AttrList attrList, Pointer attrBuf, int attrBufSize) { throw new UnsupportedOperationException(); } @Override public int getdirentries64(Pointer buf, int bufSize) { throw new UnsupportedOperationException(); } }
String path = addr.getString(2); log.debug("connect path=" + path); return connect(path);
227
35
262
public abstract class LocalUdpSocket extends SocketIO implements FileIO { private static final Log log=LogFactory.getLog(LocalUdpSocket.class); protected interface UdpHandler { void handle( byte[] request) throws IOException ; } protected final Emulator<?> emulator; protected LocalUdpSocket( Emulator<?> emulator); protected UdpHandler handler; @Override public void close(); @Override public int write( byte[] data); protected abstract int connect( String path); @Override public int connect( Pointer addr, int addrlen); @Override protected int getTcpNoDelay(); @Override protected void setTcpNoDelay( int tcpNoDelay); @Override protected void setReuseAddress( int reuseAddress); @Override protected void setKeepAlive( int keepAlive); @Override protected void setSocketRecvBuf( int recvBuf); @Override protected InetSocketAddress getLocalSocketAddress(); @Override protected int connect_ipv6( Pointer addr, int addrlen); @Override protected int connect_ipv4( Pointer addr, int addrlen); }
spring-cloud_spring-cloud-gateway
spring-cloud-gateway/spring-cloud-gateway-server-mvc/src/main/java/org/springframework/cloud/gateway/server/mvc/filter/Bucket4jFilterFunctions.java
RateLimitConfig
setTokens
class RateLimitConfig { Function<RateLimitConfig, BucketConfiguration> configurationBuilder = DEFAULT_CONFIGURATION_BUILDER; long capacity; Duration period; Function<ServerRequest, String> keyResolver; HttpStatusCode statusCode = HttpStatus.TOO_MANY_REQUESTS; Duration timeout; int tokens = 1; String headerName = DEFAULT_HEADER_NAME; public Function<RateLimitConfig, BucketConfiguration> getConfigurationBuilder() { return configurationBuilder; } public void setConfigurationBuilder(Function<RateLimitConfig, BucketConfiguration> configurationBuilder) { Assert.notNull(configurationBuilder, "configurationBuilder may not be null"); this.configurationBuilder = configurationBuilder; } public long getCapacity() { return capacity; } public RateLimitConfig setCapacity(long capacity) { this.capacity = capacity; return this; } public Duration getPeriod() { return period; } public RateLimitConfig setPeriod(Duration period) { this.period = period; return this; } public Function<ServerRequest, String> getKeyResolver() { return keyResolver; } public RateLimitConfig setKeyResolver(Function<ServerRequest, String> keyResolver) { Assert.notNull(keyResolver, "keyResolver may not be null"); this.keyResolver = keyResolver; return this; } public HttpStatusCode getStatusCode() { return statusCode; } public RateLimitConfig setStatusCode(HttpStatusCode statusCode) { this.statusCode = statusCode; return this; } public Duration getTimeout() { return timeout; } public RateLimitConfig setTimeout(Duration timeout) { this.timeout = timeout; return this; } public int getTokens() { return tokens; } public RateLimitConfig setTokens(int tokens) {<FILL_FUNCTION_BODY>} public String getHeaderName() { return headerName; } public RateLimitConfig setHeaderName(String headerName) { Assert.notNull(headerName, "headerName may not be null"); this.headerName = headerName; return this; } }
Assert.isTrue(tokens > 0, "tokens must be greater than zero"); this.tokens = tokens; return this;
602
39
641
ainilili_ratel
ratel/landlords-common/src/main/java/org/nico/ratel/landlords/transfer/TransferProtocolUtils.java
TransferProtocolUtils
unserialize
class TransferProtocolUtils { /** * A protocol header that represents the beginning of an available stream of data */ public static final byte PROTOCOL_HAED = "#".getBytes()[0]; /** * The end of the protocol used to represent the end of an available stream of data */ public static final byte PROTOCOL_TAIL = "$".getBytes()[0]; /** * Serialize the poker list to transportable bytes * * @param obj Poker list * @return Transportable byte array */ public static byte[] serialize(Object obj) { ByteLink bl = new ByteLink(); bl.append(PROTOCOL_HAED); bl.append(Noson.reversal(obj).getBytes()); bl.append(PROTOCOL_TAIL); return bl.toArray(); } /** * Deserialize the byte stream as an object * * @param bytes Byte array * @return Genericity */ public static <T> T unserialize(byte[] bytes, Class<T> clazz) {<FILL_FUNCTION_BODY>} }
ByteKit bk = new ByteKit(bytes); int start = -1; int end = -1; int index = bk.indexOf(PROTOCOL_HAED, 0); if (index != -1) start = index + 1; index = bk.indexOf(PROTOCOL_TAIL, 0); if (index != -1) end = index; if (start != -1 && end != -1 && start > end) { throw new LandlordException("Message format error, head and tail error."); } else { byte[] content = new byte[end - start]; System.arraycopy(bytes, start, content, 0, content.length); return Noson.convert(new String(content), clazz); }
289
205
494
DerekYRC_mini-spring
mini-spring/src/main/java/org/springframework/beans/factory/support/DefaultSingletonBeanRegistry.java
DefaultSingletonBeanRegistry
getSingleton
class DefaultSingletonBeanRegistry implements SingletonBeanRegistry { /** * 一级缓存 */ private Map<String, Object> singletonObjects = new HashMap<>(); /** * 二级缓存 */ private Map<String, Object> earlySingletonObjects = new HashMap<>(); /** * 三级缓存 */ private Map<String, ObjectFactory<?>> singletonFactories = new HashMap<String, ObjectFactory<?>>(); private final Map<String, DisposableBean> disposableBeans = new HashMap<>(); @Override public Object getSingleton(String beanName) {<FILL_FUNCTION_BODY>} @Override public void addSingleton(String beanName, Object singletonObject) { singletonObjects.put(beanName, singletonObject); // 1 earlySingletonObjects.remove(beanName); // 2 singletonFactories.remove(beanName); // 3 } protected void addSingletonFactory(String beanName, ObjectFactory<?> singletonFactory) { singletonFactories.put(beanName, singletonFactory); } public void registerDisposableBean(String beanName, DisposableBean bean) { disposableBeans.put(beanName, bean); } public void destroySingletons() { ArrayList<String> beanNames = new ArrayList<>(disposableBeans.keySet()); for (String beanName : beanNames) { DisposableBean disposableBean = disposableBeans.remove(beanName); try { disposableBean.destroy(); } catch (Exception e) { throw new BeansException("Destroy method on bean with name '" + beanName + "' threw an exception", e); } } } }
Object singletonObject = singletonObjects.get(beanName); if (singletonObject == null) { singletonObject = earlySingletonObjects.get(beanName); if (singletonObject == null) { ObjectFactory<?> singletonFactory = singletonFactories.get(beanName); if (singletonFactory != null) { singletonObject = singletonFactory.getObject(); //从三级缓存放进二级缓存 earlySingletonObjects.put(beanName, singletonObject); singletonFactories.remove(beanName); } } } return singletonObject;
456
167
623
DerekYRC_mini-spring
mini-spring/src/main/java/org/springframework/aop/framework/CglibAopProxy.java
DynamicAdvisedInterceptor
intercept
class DynamicAdvisedInterceptor implements MethodInterceptor { private final AdvisedSupport advised; private DynamicAdvisedInterceptor(AdvisedSupport advised) { this.advised = advised; } @Override public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {<FILL_FUNCTION_BODY>} }
// 获取目标对象 Object target = advised.getTargetSource().getTarget(); Class<?> targetClass = target.getClass(); Object retVal = null; List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass); CglibMethodInvocation methodInvocation = new CglibMethodInvocation(proxy, target, method, args, targetClass, chain, methodProxy); if (chain == null || chain.isEmpty()) { //代理方法 retVal = methodProxy.invoke(target, args); } else { retVal = methodInvocation.proceed(); } return retVal;
101
176
277
google_truth
truth/core/src/main/java/com/google/common/truth/OptionalIntSubject.java
OptionalIntSubject
hasValue
class OptionalIntSubject extends Subject { private final OptionalInt actual; OptionalIntSubject( FailureMetadata failureMetadata, @Nullable OptionalInt subject, @Nullable String typeDescription) { super(failureMetadata, subject, typeDescription); this.actual = subject; } /** Fails if the {@link OptionalInt} is empty or the subject is null. */ public void isPresent() { if (actual == null) { failWithActual(simpleFact("expected present optional")); } else if (!actual.isPresent()) { failWithoutActual(simpleFact("expected to be present")); } } /** Fails if the {@link OptionalInt} is present or the subject is null. */ public void isEmpty() { if (actual == null) { failWithActual(simpleFact("expected empty optional")); } else if (actual.isPresent()) { failWithoutActual( simpleFact("expected to be empty"), fact("but was present with value", actual.getAsInt())); } } /** * Fails if the {@link OptionalInt} does not have the given value or the subject is null. More * sophisticated comparisons can be done using {@code assertThat(optional.getAsInt())…}. */ public void hasValue(int expected) {<FILL_FUNCTION_BODY>} /** * Obsolete factory instance. This factory was previously necessary for assertions like {@code * assertWithMessage(...).about(optionalInts()).that(optional)....}. Now, you can perform * assertions like that without the {@code about(...)} call. * * @deprecated Instead of {@code about(optionalInts()).that(...)}, use just {@code that(...)}. * Similarly, instead of {@code assertAbout(optionalInts()).that(...)}, use just {@code * assertThat(...)}. */ @Deprecated @SuppressWarnings("InlineMeSuggester") // We want users to remove the surrounding call entirely. public static Factory<OptionalIntSubject, OptionalInt> optionalInts() { return (metadata, subject) -> new OptionalIntSubject(metadata, subject, "optionalInt"); } }
if (actual == null) { failWithActual("expected an optional with value", expected); } else if (!actual.isPresent()) { failWithoutActual(fact("expected to have value", expected), simpleFact("but was absent")); } else { checkNoNeedToDisplayBothValues("getAsInt()").that(actual.getAsInt()).isEqualTo(expected); }
549
97
646
/** * An object that lets you perform checks on the value under test. For example, {@code Subject}contains {@link #isEqualTo(Object)} and {@link #isInstanceOf(Class)}, and {@link StringSubject}contains {@link StringSubject#startsWith startsWith(String)}. <p>To create a {@code Subject} instance, most users will call an {@link Truth#assertThat assertThat} method. For information about other ways to create an instance, see <ahref="https://truth.dev/faq#full-chain">this FAQ entry</a>. <h3>For people extending Truth</h3> <p>For information about writing a custom {@link Subject}, see <a href="https://truth.dev/extension">our doc on extensions</a>. * @author David Saff * @author Christian Gruber */ public class Subject { /** * In a fluent assertion chain, the argument to the common overload of {@link StandardSubjectBuilder#about(Subject.Factory) about}, the method that specifies what kind of {@link Subject} to create.<p>For more information about the fluent chain, see <a href="https://truth.dev/faq#full-chain">this FAQ entry</a>. <h3>For people extending Truth</h3> <p>When you write a custom subject, see <a href="https://truth.dev/extension">our doc on extensions</a>. It explains where {@code Subject.Factory} fits into the process. */ public interface Factory<SubjectT extends Subject,ActualT> { /** * Creates a new {@link Subject}. */ SubjectT createSubject( FailureMetadata metadata, @Nullable ActualT actual); } private final @Nullable FailureMetadata metadata; private final @Nullable Object actual; private final @Nullable String typeDescriptionOverride; /** * 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 Subject( FailureMetadata metadata, @Nullable Object actual); /** * Special constructor that lets subclasses provide a description of the type they're testing. For example, {@link ThrowableSubject} passes the description "throwable." Normally, Truth is ableto infer this name from the class name. However, if we lack runtime type information (notably, under j2cl with class metadata off), we might not have access to the original class name. <p>We don't expect to make this a public API: Class names are nearly always available. It's just that we want to be able to run Truth's own tests run with class metadata off, and it's easier to tweak the subjects to know their own names rather than generalize the tests to accept obfuscated names. */ Subject( @Nullable FailureMetadata metadata, @Nullable Object actual, @Nullable String typeDescriptionOverride); /** * Fails if the subject is not null. */ public void isNull(); /** * Fails if the subject is null. */ public void isNotNull(); /** * Fails if the subject is not equal to the given object. For the purposes of this comparison, two objects are equal if any of the following is true: <ul> <li>they are equal according to {@link Objects#equal}<li>they are arrays and are considered equal by the appropriate {@link Arrays#equals}overload <li>they are boxed integer types ( {@code Byte}, {@code Short}, {@code Character}, {@code Integer}, or {@code Long}) and they are numerically equal when converted to {@code Long}. <li>the actual value is a boxed floating-point type ( {@code Double} or {@code Float}), the expected value is an {@code Integer}, and the two are numerically equal when converted to {@code Double}. (This allows {@code assertThat(someDouble).isEqualTo(0)} to pass.)</ul> <p><b>Note:</b> This method does not test the {@link Object#equals} implementation itself; it<i>assumes</i> that method is functioning correctly according to its contract. Testing an {@code equals} implementation requires a utility such as <ahref="https://mvnrepository.com/artifact/com.google.guava/guava-testlib">guava-testlib</a>'s <a href="https://static.javadoc.io/com.google.guava/guava-testlib/23.0/com/google/common/testing/EqualsTester.html">EqualsTester</a>. <p>In some cases, this method might not even call {@code equals}. It may instead perform other tests that will return the same result as long as {@code equals} is implemented according tothe contract for its type. */ public void isEqualTo( @Nullable Object expected); private void standardIsEqualTo( @Nullable Object expected); /** * Fails if the subject is equal to the given object. The meaning of equality is the same as for the {@link #isEqualTo} method. */ public void isNotEqualTo( @Nullable Object unexpected); private void standardIsNotEqualTo( @Nullable Object unexpected); /** * Returns whether {@code actual} equals {@code expected} differ and, in some cases, a descriptionof how they differ. <p>The equality check follows the rules described on {@link #isEqualTo}. */ private ComparisonResult compareForEquality( @Nullable Object expected); private static boolean isIntegralBoxedPrimitive( @Nullable Object o); private static long integralValue( Object o); /** * Fails if the subject is not the same instance as the given object. */ public final void isSameInstanceAs( @Nullable Object expected); /** * Fails if the subject is the same instance as the given object. */ public final void isNotSameInstanceAs( @Nullable Object unexpected); /** * Fails if the subject is not an instance of the given class. */ public void isInstanceOf( Class<?> clazz); /** * Fails if the subject is an instance of the given class. */ public void isNotInstanceOf( Class<?> clazz); private static boolean isInstanceOfType( Object instance, Class<?> clazz); /** * Fails unless the subject is equal to any element in the given iterable. */ public void isIn( @Nullable Iterable<?> iterable); private static boolean contains( Iterable<?> haystack, @Nullable Object needle); /** * Fails unless the subject is equal to any of the given elements. */ public void isAnyOf( @Nullable Object first, @Nullable Object second, @Nullable Object @Nullable ... rest); /** * Fails if the subject is equal to any element in the given iterable. */ public void isNotIn( @Nullable Iterable<?> iterable); /** * Fails if the subject is equal to any of the given elements. */ public void isNoneOf( @Nullable Object first, @Nullable Object second, @Nullable Object @Nullable ... rest); /** * Returns the actual value under test. */ final @Nullable Object actual(); /** * Supplies the direct string representation of the actual value to other methods which may prefix or otherwise position it in an error message. This should only be overridden to provide an improved string representation of the value under test, as it would appear in any given error message, and should not be used for additional prefixing. <p>Subjects should override this with care. <p>By default, this returns {@code String.ValueOf(getActualValue())}. */ @ForOverride protected String actualCustomStringRepresentation(); final String actualCustomStringRepresentationForPackageMembersToCall(); private String formatActualOrExpected( @Nullable Object o); private static String base16( byte[] bytes); private static final char[] hexDigits="0123456789ABCDEF".toCharArray(); private static @Nullable Object arrayAsListRecursively( @Nullable Object input); /** * The result of comparing two objects for equality. This includes both the "equal"/"not-equal" bit and, in the case of "not equal," optional facts describing the difference. */ private static final class ComparisonResult { /** * If {@code equal} is true, returns an equal result; if false, a non-equal result with nodescription. */ static ComparisonResult fromEqualsResult( boolean equal); /** * Returns a non-equal result with the given description. */ static ComparisonResult differentWithDescription( Fact... facts); /** * Returns an equal result. */ static ComparisonResult equal(); /** * Returns a non-equal result with no description. */ static ComparisonResult differentNoDescription(); private static final ComparisonResult EQUAL=new ComparisonResult(null); private static final ComparisonResult DIFFERENT_NO_DESCRIPTION=new ComparisonResult(ImmutableList.<Fact>of()); private final @Nullable ImmutableList<Fact> facts; private ComparisonResult( @Nullable ImmutableList<Fact> facts); boolean valuesAreEqual(); ImmutableList<Fact> factsOrEmpty(); /** * Returns an instance with the same "equal"/"not-equal" bit but with no description. */ ComparisonResult withoutDescription(); } /** * Returns null if the arrays are equal. If not equal, returns a string comparing the two arrays, displaying them in the style "[1, 2, 3]" to supplement the main failure message, which uses the style "010203." */ private static ComparisonResult checkByteArrayEquals( byte[] expected, byte[] actual); /** * Returns null if the arrays are equal, recursively. If not equal, returns the string of the index at which they're different. */ private static ComparisonResult checkArrayEqualsRecursive( Object expectedArray, Object actualArray, String lastIndex); private static String arrayType( Object array); private static boolean gwtSafeObjectEquals( @Nullable Object actual, @Nullable Object expected); private static List<String> doubleArrayAsString( double[] items); private static List<String> floatArrayAsString( float[] items); /** * Returns a builder for creating a derived subject but without providing information about how the derived subject will relate to the current subject. In most cases, you should provide such information by using {@linkplain #check(String,Object...) the other overload}. * @deprecated Use {@linkplain #check(String,Object...) the other overload}, which requires you to supply more information to include in any failure messages. */ @Deprecated final StandardSubjectBuilder check(); /** * Returns a builder for creating a derived subject. <p>Derived subjects retain the {@link FailureStrategy} and {@linkplain StandardSubjectBuilder#withMessage messages} of the current subject, and in some cases, theyautomatically supplement their failure message with information about the original subject. <p>For example, {@link ThrowableSubject#hasMessageThat}, which returns a {@link StringSubject}, is implemented with {@code check("getMessage()").that(actual.getMessage())}. <p>The arguments to {@code check} describe how the new subject was derived from the old,formatted like a chained method call. This allows Truth to include that information in its failure messages. For example, {@code assertThat(caught).hasCauseThat().hasMessageThat()} willproduce a failure message that includes the string "throwable.getCause().getMessage()," thanks to internal {@code check} calls that supplied "getCause()" and "getMessage()" as arguments.<p>If the method you're delegating to accepts parameters, you can pass {@code check} a formatstring. For example, {@link MultimapSubject#valuesForKey} calls {@code check("valuesForKey(%s)", key)}. <p>If you aren't really delegating to an instance method on the actual value -- maybe you're calling a static method, or you're calling a chain of several methods -- you can supply whatever string will be most useful to users. For example, if you're delegating to {@code getOnlyElement(actual.colors())}, you might call {@code check("onlyColor()")}. * @param format a template with {@code %s} placeholders * @param args the arguments to be inserted into those placeholders */ protected final StandardSubjectBuilder check( String format, @Nullable Object... args); final StandardSubjectBuilder checkNoNeedToDisplayBothValues( String format, @Nullable Object... args); private StandardSubjectBuilder doCheck( OldAndNewValuesAreSimilar valuesAreSimilar, String format, @Nullable Object[] args); /** * Begins a new call chain that ignores any failures. This is useful for subjects that normally delegate with to other subjects by using {@link #check} but have already reported a failure. Insuch cases it may still be necessary to return a {@code Subject} instance even though anysubsequent assertions are meaningless. For example, if a user chains together more {@link ThrowableSubject#hasCauseThat} calls than the actual exception has causes, {@code hasCauseThat}returns {@code ignoreCheck().that(... a dummy exception ...)}. */ protected final StandardSubjectBuilder ignoreCheck(); /** * Fails, reporting a message with two " {@linkplain Fact facts}": <ul> <li><i>key</i>: <i>value</i> <li>but was: <i>actual value</i>. </ul> <p>This is the simplest failure API. For more advanced needs, see {@linkplain #failWithActual(Fact,Fact...) the other overload} and {@link #failWithoutActual(Fact,Fact...) failWithoutActual}. <p>Example usage: The check {@code contains(String)} calls {@code failWithActual("expected tocontain", string)}. */ protected final void failWithActual( String key, @Nullable Object value); /** * Fails, reporting a message with the given facts, followed by an automatically added fact of the form: <ul> <li>but was: <i>actual value</i>. </ul> <p>If you have only one fact to report (and it's a {@linkplain Fact#fact key-value fact}), prefer {@linkplain #failWithActual(String,Object) the simpler overload}. <p>Example usage: The check {@code isEmpty()} calls {@code failWithActual(simpleFact("expectedto be empty"))}. */ protected final void failWithActual( Fact first, Fact... rest); final void failWithActual( Iterable<Fact> facts); /** * Reports a failure constructing a message from a simple verb. * @param check the check being asserted * @deprecated Prefer to construct {@link Fact}-style methods, typically by using {@link #failWithActual(Fact,Fact...) failWithActual}{@code (}{@link Fact#simpleFact simpleFact(...)}{@code )}. However, if you want to preserve your exact failure message as a migration aid, you can inline this method (and then inline the resulting method call, as well). */ @Deprecated final void fail( String check); /** * Assembles a failure message and passes such to the FailureStrategy * @param verb the check being asserted * @param other the value against which the subject is compared * @deprecated Prefer to construct {@link Fact}-style methods, typically by using {@link #failWithActual(String,Object)}. However, if you want to preserve your exact failure message as a migration aid, you can inline this method (and then inline the resulting method call, as well). */ @Deprecated final void fail( String verb, Object other); /** * Assembles a failure message and passes such to the FailureStrategy * @param verb the check being asserted * @param messageParts the expectations against which the subject is compared * @deprecated Prefer to construct {@link Fact}-style methods, typically by using {@link #failWithActual(Fact,Fact...)}. However, if you want to preserve your exact failure message as a migration aid, you can inline this method. */ @Deprecated final void fail( String verb, @Nullable Object... messageParts); enum EqualityCheck { EQUAL("expected"), SAME_INSTANCE("expected specific instance"); final String keyForExpected; EqualityCheck( String keyForExpected); } /** * Special version of {@link #failEqualityCheck} for use from {@link IterableSubject}, documented further there. */ final void failEqualityCheckForEqualsWithoutDescription( @Nullable Object expected); private void failEqualityCheck( EqualityCheck equalityCheck, @Nullable Object expected, ComparisonResult difference); /** * Checks whether the actual and expected values are strings that match except for trailing whitespace. If so, reports a failure and returns true. */ private boolean tryFailForTrailingWhitespaceOnly( @Nullable Object expected); private static String escapeWhitespace( String in); private static String escapeWhitespace( char c); /** * Checks whether the actual and expected values are empty strings. If so, reports a failure and returns true. */ private boolean tryFailForEmptyString(@Nullable Object expected); private static final char[] HEX_DIGITS="0123456789abcdef".toCharArray(); private static char[] asUnicodeHexEscape(char c); private void failEqualityCheckNoComparisonFailure(ComparisonResult difference,Fact... facts); /** * Assembles a failure message and passes it to the FailureStrategy * @param verb the check being asserted * @param expected the expectations against which the subject is compared * @param failVerb the failure of the check being asserted * @param actual the actual value the subject was compared against * @deprecated Prefer to construct {@link Fact}-style methods, typically by using {@link #failWithActual(Fact,Fact...)}. However, if you want to preserve your exact failure message as a migration aid, you can inline this method. */ @Deprecated final void failWithBadResults(String verb,Object expected,String failVerb,Object actual); /** * Assembles a failure message with an alternative representation of the wrapped subject and passes it to the FailureStrategy * @param verb the check being asserted * @param expected the expected value of the check * @param actual the custom representation of the subject to be reported in the failure. * @deprecated Prefer to construct {@link Fact}-style methods, typically by using {@link #failWithoutActual(Fact,Fact...)}. However, if you want to preserve your exact failure message as a migration aid, you can inline this method. */ @Deprecated final void failWithCustomSubject(String verb,Object expected,Object actual); /** * @deprecated Prefer to construct {@link Fact}-style methods, typically by using {@link #failWithoutActual(Fact,Fact...) failWithoutActual}{@code (}{@link Fact#simpleFact simpleFact(...)}{@code )}. However, if you want to preserve your exact failure message as a migration aid, you can inline this method. */ @Deprecated final void failWithoutSubject(String check); /** * Fails, reporting a message with the given facts, <i>without automatically adding the actual value.</i> <p>Most failure messages should report the actual value, so most checks should call {@link #failWithActual(Fact,Fact...) failWithActual} instead. However, {@code failWithoutActual} isuseful in some cases: <ul> <li>when the actual value is obvious from the rest of the message. For example, {@code isNotEmpty()} calls {@code failWithoutActual(simpleFact("expected not to be empty")}. <li>when the actual value shouldn't come last or should have a different key than the default of "but was." For example, {@code isNotWithin(...).of(...)} calls {@code failWithoutActual} so that it can put the expected and actual values together, followedby the tolerance. </ul> <p>Example usage: The check {@code isEmpty()} calls {@code failWithActual(simpleFact("expectedto be empty"))}. */ protected final void failWithoutActual(Fact first,Fact... rest); final void failWithoutActual(Iterable<Fact> facts); /** * Assembles a failure message without a given subject and passes it to the FailureStrategy * @param check the check being asserted * @deprecated Prefer to construct {@link Fact}-style methods, typically by using {@link #failWithoutActual(Fact,Fact...) failWithoutActual}{@code (}{@link Fact#simpleFact simpleFact(...)}{@code )}. However, if you want to preserve your exact failure message as a migration aid, you can inline this method (and then inline the resulting method call, as well). */ @Deprecated final void failWithoutActual(String check); /** * @throws UnsupportedOperationException always * @deprecated {@link Object#equals(Object)} is not supported on Truth subjects. If you arewriting a test assertion (actual vs. expected), use {@link #isEqualTo(Object)} instead. */ @DoNotCall("Subject.equals() is not supported. Did you mean to call" + " assertThat(actual).isEqualTo(expected) instead of" + " assertThat(actual).equals(expected)?") @Deprecated @Override public final boolean equals(@Nullable Object o); /** * @throws UnsupportedOperationException always * @deprecated {@link Object#hashCode()} is not supported on Truth subjects. */ @DoNotCall("Subject.hashCode() is not supported.") @Deprecated @Override public final int hashCode(); /** * @throws UnsupportedOperationException always * @deprecated {@link Object#toString()} is not supported on Truth subjects. */ @Deprecated @Override public String toString(); /** * Returns a "but was: <actual value>" string. This method should be rarely needed, since Truth inserts a "but was" fact by default for assertions. However, it's occasionally useful for calls to {@code failWithoutActual} that want a "but was" fact but don't want it to come last, whereTruth inserts it by default. */ final Fact butWas(); final String typeDescription(); private static String typeDescriptionOrGuess(Class<? extends Subject> clazz,@Nullable String typeDescriptionOverride); private void doFail(ImmutableList<Fact> facts); }
javamelody_javamelody
javamelody/javamelody-core/src/main/java/net/bull/javamelody/SpringDataSourceFactoryBean.java
SpringDataSourceFactoryBean
createInstance
class SpringDataSourceFactoryBean extends AbstractFactoryBean<DataSource> { private String targetName; // exemple : // <bean id="wrappedDataSource" class="net.bull.javamelody.SpringDataSourceFactoryBean"> // <property name="targetName" value="targetDataSource" /> // </bean> // // <bean id="targetDataSource" ... // </bean> /** * Name of target bean to instrument. * This should implement {@linkplain DataSource}. * @param targetName name of bean, not null. */ public void setTargetName(String targetName) { assert targetName != null; this.targetName = targetName; } /** * {@inheritDoc} */ @Override protected DataSource createInstance() {<FILL_FUNCTION_BODY>} /** * {@inheritDoc} */ @Override public Class<?> getObjectType() { return DataSource.class; } }
if (targetName == null) { throw new IllegalStateException("targetName must not be null"); } final BeanFactory beanFactory = getBeanFactory(); assert beanFactory != null; final DataSource dataSource = beanFactory.getBean(targetName, DataSource.class); JdbcWrapper.registerSpringDataSource(targetName, dataSource); final DataSource result = JdbcWrapper.SINGLETON.createDataSourceProxy(targetName, dataSource); LOG.debug("Spring target datasource wrapped: " + targetName); return result;
289
164
453
spring-cloud_spring-cloud-gateway
spring-cloud-gateway/spring-cloud-gateway-server/src/main/java/org/springframework/cloud/gateway/filter/factory/SecureHeadersProperties.java
SecureHeadersProperties
toString
class SecureHeadersProperties { /** * Xss-Protection header default. */ public static final String X_XSS_PROTECTION_HEADER_DEFAULT = "1 ; mode=block"; /** * Strict transport security header default. */ public static final String STRICT_TRANSPORT_SECURITY_HEADER_DEFAULT = "max-age=631138519"; /** * Frame Options header default. */ public static final String X_FRAME_OPTIONS_HEADER_DEFAULT = "DENY"; /** * Content-Type Options header default. */ public static final String X_CONTENT_TYPE_OPTIONS_HEADER_DEFAULT = "nosniff"; /** * Referrer Policy header default. */ public static final String REFERRER_POLICY_HEADER_DEFAULT = "no-referrer"; /** * Content-Security Policy header default. */ public static final String CONTENT_SECURITY_POLICY_HEADER_DEFAULT = "default-src 'self' https:; font-src 'self' https: data:; img-src 'self' https: data:; object-src 'none'; script-src https:; style-src 'self' https: 'unsafe-inline'"; /** * Download Options header default. */ public static final String X_DOWNLOAD_OPTIONS_HEADER_DEFAULT = "noopen"; /** * Permitted Cross-Domain Policies header default. */ public static final String X_PERMITTED_CROSS_DOMAIN_POLICIES_HEADER_DEFAULT = "none"; private String xssProtectionHeader = X_XSS_PROTECTION_HEADER_DEFAULT; private String strictTransportSecurity = STRICT_TRANSPORT_SECURITY_HEADER_DEFAULT; private String frameOptions = X_FRAME_OPTIONS_HEADER_DEFAULT; private String contentTypeOptions = X_CONTENT_TYPE_OPTIONS_HEADER_DEFAULT; private String referrerPolicy = REFERRER_POLICY_HEADER_DEFAULT; private String contentSecurityPolicy = CONTENT_SECURITY_POLICY_HEADER_DEFAULT; private String downloadOptions = X_DOWNLOAD_OPTIONS_HEADER_DEFAULT; private String permittedCrossDomainPolicies = X_PERMITTED_CROSS_DOMAIN_POLICIES_HEADER_DEFAULT; private List<String> disable = new ArrayList<>(); public String getXssProtectionHeader() { return xssProtectionHeader; } public void setXssProtectionHeader(String xssProtectionHeader) { this.xssProtectionHeader = xssProtectionHeader; } public String getStrictTransportSecurity() { return strictTransportSecurity; } public void setStrictTransportSecurity(String strictTransportSecurity) { this.strictTransportSecurity = strictTransportSecurity; } public String getFrameOptions() { return frameOptions; } public void setFrameOptions(String frameOptions) { this.frameOptions = frameOptions; } public String getContentTypeOptions() { return contentTypeOptions; } public void setContentTypeOptions(String contentTypeOptions) { this.contentTypeOptions = contentTypeOptions; } public String getReferrerPolicy() { return referrerPolicy; } public void setReferrerPolicy(String referrerPolicy) { this.referrerPolicy = referrerPolicy; } public String getContentSecurityPolicy() { return contentSecurityPolicy; } public void setContentSecurityPolicy(String contentSecurityPolicy) { this.contentSecurityPolicy = contentSecurityPolicy; } public String getDownloadOptions() { return downloadOptions; } public void setDownloadOptions(String downloadOptions) { this.downloadOptions = downloadOptions; } public String getPermittedCrossDomainPolicies() { return permittedCrossDomainPolicies; } public void setPermittedCrossDomainPolicies(String permittedCrossDomainPolicies) { this.permittedCrossDomainPolicies = permittedCrossDomainPolicies; } public List<String> getDisable() { return disable; } public void setDisable(List<String> disable) { this.disable = disable; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
final StringBuffer sb = new StringBuffer("SecureHeadersProperties{"); sb.append("xssProtectionHeader='").append(xssProtectionHeader).append('\''); sb.append(", strictTransportSecurity='").append(strictTransportSecurity).append('\''); sb.append(", frameOptions='").append(frameOptions).append('\''); sb.append(", contentTypeOptions='").append(contentTypeOptions).append('\''); sb.append(", referrerPolicy='").append(referrerPolicy).append('\''); sb.append(", contentSecurityPolicy='").append(contentSecurityPolicy).append('\''); sb.append(", downloadOptions='").append(downloadOptions).append('\''); sb.append(", permittedCrossDomainPolicies='").append(permittedCrossDomainPolicies).append('\''); sb.append(", disabled='").append(disable).append('\''); sb.append('}'); return sb.toString();
1,111
258
1,369
mapstruct_mapstruct
mapstruct/processor/src/main/java/org/mapstruct/ap/internal/model/BuilderFinisherMethodResolver.java
BuilderFinisherMethodResolver
getBuilderFinisherMethod
class BuilderFinisherMethodResolver { private static final String DEFAULT_BUILD_METHOD_NAME = "build"; private static final Extractor<ExecutableElement, String> EXECUTABLE_ELEMENT_NAME_EXTRACTOR = executableElement -> { StringBuilder sb = new StringBuilder( executableElement.getSimpleName() ); sb.append( '(' ); for ( VariableElement parameter : executableElement.getParameters() ) { sb.append( parameter ); } sb.append( ')' ); return sb.toString(); }; private BuilderFinisherMethodResolver() { } public static MethodReference getBuilderFinisherMethod(Method method, BuilderType builderType, MappingBuilderContext ctx) {<FILL_FUNCTION_BODY>} }
Collection<ExecutableElement> buildMethods = builderType.getBuildMethods(); if ( buildMethods.isEmpty() ) { //If we reach this method this should never happen return null; } BuilderGem builder = method.getOptions().getBeanMapping().getBuilder(); if ( builder == null && buildMethods.size() == 1 ) { return MethodReference.forMethodCall( first( buildMethods ).getSimpleName().toString() ); } else { String buildMethodPattern = DEFAULT_BUILD_METHOD_NAME; if ( builder != null ) { buildMethodPattern = builder.buildMethod().get(); } for ( ExecutableElement buildMethod : buildMethods ) { String methodName = buildMethod.getSimpleName().toString(); if ( methodName.matches( buildMethodPattern ) ) { return MethodReference.forMethodCall( methodName ); } } if ( builder == null ) { ctx.getMessager().printMessage( method.getExecutable(), Message.BUILDER_NO_BUILD_METHOD_FOUND_DEFAULT, buildMethodPattern, builderType.getBuilder(), builderType.getBuildingType(), Strings.join( buildMethods, ", ", EXECUTABLE_ELEMENT_NAME_EXTRACTOR ) ); } else { ctx.getMessager().printMessage( method.getExecutable(), builder.mirror(), Message.BUILDER_NO_BUILD_METHOD_FOUND, buildMethodPattern, builderType.getBuilder(), builderType.getBuildingType(), Strings.join( buildMethods, ", ", EXECUTABLE_ELEMENT_NAME_EXTRACTOR ) ); } } return null;
202
444
646
joelittlejohn_jsonschema2pojo
jsonschema2pojo/jsonschema2pojo-core/src/main/java/org/jsonschema2pojo/Jsonschema2Pojo.java
Jsonschema2Pojo
generate
class Jsonschema2Pojo { /** * Reads the contents of the given source and initiates schema generation. * * @param config * the configuration options (including source and target paths, * and other behavioural options) that will control code * generation * @param logger * a logger appropriate to the current context, usually a wrapper around the build platform logger * @throws FileNotFoundException * if the source path is not found * @throws IOException * if the application is unable to read data from the source */ public static void generate(GenerationConfig config, RuleLogger logger) throws IOException {<FILL_FUNCTION_BODY>} private static ContentResolver createContentResolver(GenerationConfig config) { if (config.getSourceType() == SourceType.YAMLSCHEMA || config.getSourceType() == SourceType.YAML) { return new ContentResolver(new YAMLFactory()); } else { return new ContentResolver(); } } private static SchemaGenerator createSchemaGenerator(GenerationConfig config) { if (config.getSourceType() == SourceType.YAMLSCHEMA || config.getSourceType() == SourceType.YAML) { return new SchemaGenerator(new YAMLFactory()); } else { return new SchemaGenerator(); } } private static RuleFactory createRuleFactory(GenerationConfig config) { Class<? extends RuleFactory> clazz = config.getCustomRuleFactory(); if (!RuleFactory.class.isAssignableFrom(clazz)) { throw new IllegalArgumentException("The class name given as a rule factory (" + clazz.getName() + ") does not refer to a class that implements " + RuleFactory.class.getName()); } try { return clazz.newInstance(); } catch (InstantiationException e) { throw new IllegalArgumentException("Failed to create a rule factory from the given class. An exception was thrown on trying to create a new instance.", e.getCause()); } catch (IllegalAccessException e) { throw new IllegalArgumentException("Failed to create a rule factory from the given class. It appears that we do not have access to this class - is both the class and its no-arg constructor marked public?", e); } } private static void generateRecursive(GenerationConfig config, SchemaMapper mapper, JCodeModel codeModel, String packageName, List<File> schemaFiles) throws IOException { Collections.sort(schemaFiles, config.getSourceSortOrder().getComparator()); for (File child : schemaFiles) { if (child.isFile()) { if (config.getSourceType() == SourceType.JSON || config.getSourceType() == SourceType.YAML) { // any cached schemas will have ids that are fragments, relative to the previous document (and shouldn't be reused) mapper.getRuleFactory().getSchemaStore().clearCache(); } mapper.generate(codeModel, getNodeName(child.toURI().toURL(), config), defaultString(packageName), child.toURI().toURL()); } else { generateRecursive(config, mapper, codeModel, childQualifiedName(packageName, child.getName()), Arrays.asList(child.listFiles(config.getFileFilter()))); } } } private static String childQualifiedName(String parentQualifiedName, String childSimpleName) { String safeChildName = childSimpleName.replaceAll(NameHelper.ILLEGAL_CHARACTER_REGEX, "_"); return isEmpty(parentQualifiedName) ? safeChildName : parentQualifiedName + "." + safeChildName; } private static void removeOldOutput(File targetDirectory) { if (targetDirectory.exists()) { for (File f : targetDirectory.listFiles()) { delete(f); } } } @edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "RV_RETURN_VALUE_IGNORED_BAD_PRACTICE") private static void delete(File f) { if (f.isDirectory()) { for (File child : f.listFiles()) { delete(child); } } f.delete(); } private static Annotator getAnnotator(GenerationConfig config) { AnnotatorFactory factory = new AnnotatorFactory(config); return factory.getAnnotator(factory.getAnnotator(config.getAnnotationStyle()), factory.getAnnotator(config.getCustomAnnotator())); } public static String getNodeName(URL file, GenerationConfig config) { return getNodeName(file.toString(), config); } public static String getNodeName(String filePath, GenerationConfig config) { try { String fileName = FilenameUtils.getName(URLDecoder.decode(filePath, StandardCharsets.UTF_8.toString())); String[] extensions = config.getFileExtensions() == null ? new String[] {} : config.getFileExtensions(); boolean extensionRemoved = false; for (int i = 0; i < extensions.length; i++) { String extension = extensions[i]; if (extension.length() == 0) { continue; } if (!extension.startsWith(".")) { extension = "." + extension; } if (fileName.endsWith(extension)) { fileName = removeEnd(fileName, extension); extensionRemoved = true; break; } } if (!extensionRemoved) { fileName = FilenameUtils.getBaseName(fileName); } return fileName; } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException(String.format("Unable to generate node name from URL: %s", filePath), e); } } }
Annotator annotator = getAnnotator(config); RuleFactory ruleFactory = createRuleFactory(config); ruleFactory.setAnnotator(annotator); ruleFactory.setGenerationConfig(config); ruleFactory.setLogger(logger); ruleFactory.setSchemaStore(new SchemaStore(createContentResolver(config), logger)); SchemaMapper mapper = new SchemaMapper(ruleFactory, createSchemaGenerator(config)); JCodeModel codeModel = new JCodeModel(); if (config.isRemoveOldOutput()) { removeOldOutput(config.getTargetDirectory()); } for (Iterator<URL> sources = config.getSource(); sources.hasNext();) { URL source = sources.next(); if (URLUtil.parseProtocol(source.toString()) == URLProtocol.FILE && URLUtil.getFileFromURL(source).isDirectory()) { generateRecursive(config, mapper, codeModel, defaultString(config.getTargetPackage()), Arrays.asList(URLUtil.getFileFromURL(source).listFiles(config.getFileFilter()))); } else { mapper.generate(codeModel, getNodeName(source, config), defaultString(config.getTargetPackage()), source); } } if (config.getTargetDirectory().exists() || config.getTargetDirectory().mkdirs()) { CodeWriter sourcesWriter = new FileCodeWriterWithEncoding(config.getTargetDirectory(), config.getOutputEncoding()); CodeWriter resourcesWriter = new FileCodeWriterWithEncoding(config.getTargetDirectory(), config.getOutputEncoding()); codeModel.build(sourcesWriter, resourcesWriter); } else { throw new GenerationException("Could not create or access target directory " + config.getTargetDirectory().getAbsolutePath()); }
1,483
438
1,921
jitsi_jitsi
jitsi/modules/service/desktop/src/main/java/net/java/sip/communicator/impl/osdependent/systemtray/awt/AWTSystemTray.java
AWTSystemTray
addTrayIcon
class AWTSystemTray extends SystemTray { private final java.awt.SystemTray impl; /** * Creates a new instance of this class. */ public AWTSystemTray() { impl = java.awt.SystemTray.getSystemTray(); } @Override public void addTrayIcon(TrayIcon trayIcon) throws IllegalArgumentException {<FILL_FUNCTION_BODY>} @Override public TrayIcon createTrayIcon(ImageIcon icon, String tooltip, Object popup) { return new AWTTrayIcon(icon.getImage(), tooltip, popup); } @Override public boolean useSwingPopupMenu() { // enable swing for Java 1.6 except for the mac version return !OSUtils.IS_MAC; } @Override public boolean supportsDynamicMenu() { return true; } }
try { impl.add(((AWTTrayIcon) trayIcon).getImpl()); } catch (AWTException e) { throw new IllegalArgumentException(e); }
253
54
307
/** * Base class for all wrappers of <tt>SystemTray</tt> implementations. */ public abstract class SystemTray { private static final org.slf4j.Logger logger=org.slf4j.LoggerFactory.getLogger(SystemTray.class); private static SystemTray systemTray; private static final String DISABLED_TRAY_MODE="disabled"; /** * Gets or creates the supported <tt>SystemTray</tt> implementations. * @return a <tt>SystemTray</tt> implementation for the current platform. */ public final static SystemTray getSystemTray(); public static String getSystemTrayMode(); /** * Adds a <tt>TrayIcon</tt> to this system tray implementation. * @param trayIcon the <tt>TrayIcon</tt> to add */ public abstract void addTrayIcon(TrayIcon trayIcon); /** * Creates an implementation specific <tt>TrayIcon</tt> that can later be added with {@link #addTrayIcon(TrayIcon)}. * @param image the <tt>Image</tt> to be used * @param tooltip the string to be used as tooltip text; if the value is<tt>null</tt> no tooltip is shown * @param popup the menu to be used for the tray icon's popup menu; if thevalue is <tt>null</tt> no popup menu is shown * @return a <tt>TrayIcon</tt> instance for this <tt>SystemTray</tt>implementation. */ public abstract TrayIcon createTrayIcon(ImageIcon icon,String tooltip,Object popup); /** * Determines if the popup menu for the icon is to be a Swing <tt>JPopupMenu</tt> or an AWT <tt>PopupMenu</tt> * @return <tt>true</tt> for a <tt>JPopupMenu</tt>, <tt>false</tt> for a<tt>PopupMenu</tt> */ public abstract boolean useSwingPopupMenu(); /** * Determines if the tray icon supports dynamic menus. * @return True if the menu can be changed while running, false otherwise. */ public abstract boolean supportsDynamicMenu(); }
docker-java_docker-java
docker-java/docker-java-core/src/main/java/com/github/dockerjava/core/command/BuildImageResultCallback.java
BuildImageResultCallback
getImageId
class BuildImageResultCallback extends ResultCallbackTemplate<BuildImageResultCallback, BuildResponseItem> { private static final Logger LOGGER = LoggerFactory.getLogger(BuildImageResultCallback.class); private String imageId; private String error; @Override public void onNext(BuildResponseItem item) { if (item.isBuildSuccessIndicated()) { this.imageId = item.getImageId(); } else if (item.isErrorIndicated()) { this.error = item.getError(); } LOGGER.debug(item.toString()); } /** * Awaits the image id from the response stream. * * @throws DockerClientException * if the build fails. */ public String awaitImageId() { try { awaitCompletion(); } catch (InterruptedException e) { throw new DockerClientException("", e); } return getImageId(); } /** * Awaits the image id from the response stream. * * @throws DockerClientException * if the build fails or the timeout occurs. */ public String awaitImageId(long timeout, TimeUnit timeUnit) { try { awaitCompletion(timeout, timeUnit); } catch (InterruptedException e) { throw new DockerClientException("Awaiting image id interrupted: ", e); } return getImageId(); } private String getImageId() {<FILL_FUNCTION_BODY>} }
if (imageId != null) { return imageId; } if (error == null) { throw new DockerClientException("Could not build image"); } throw new DockerClientException("Could not build image: " + error);
393
69
462
javamelody_javamelody
javamelody/javamelody-core/src/main/java/net/bull/javamelody/internal/model/CounterStorage.java
CounterOutputStream
deleteObsoleteCounterFiles
class CounterOutputStream extends OutputStream { int dataLength; private final OutputStream output; CounterOutputStream(OutputStream output) { super(); this.output = output; } @Override public void write(int b) throws IOException { output.write(b); dataLength++; } @Override public void write(byte[] b) throws IOException { output.write(b); dataLength += b.length; } @Override public void write(byte[] b, int off, int len) throws IOException { output.write(b, off, len); dataLength += len; } @Override public void flush() throws IOException { output.flush(); } @Override public void close() throws IOException { output.close(); } } /** * Constructeur. * @param counter Counter */ CounterStorage(Counter counter) { super(); assert counter != null; this.counter = counter; } /** * Enregistre le counter. * @return Taille sérialisée non compressée du counter (estimation pessimiste de l'occupation mémoire) * @throws IOException Exception d'entrée/sortie */ int writeToFile() throws IOException { if (storageDisabled) { return -1; } final File file = getFile(); if (counter.getRequestsCount() == 0 && counter.getErrorsCount() == 0 && !file.exists()) { // s'il n'y a pas de requête, inutile d'écrire des fichiers de compteurs vides // (par exemple pour le compteur ejb s'il n'y a pas d'ejb) return -1; } final File directory = file.getParentFile(); if (!directory.mkdirs() && !directory.exists()) { throw new IOException("JavaMelody directory can't be created: " + directory.getPath()); } return writeToFile(counter, file); } static int writeToFile(Counter counter, File file) throws IOException { try (FileOutputStream out = new FileOutputStream(file)) { final CounterOutputStream counterOutput = new CounterOutputStream( new GZIPOutputStream(new BufferedOutputStream(out))); try (ObjectOutputStream output = new ObjectOutputStream(counterOutput)) { output.writeObject(counter); // ce close libère les ressources du ObjectOutputStream et du GZIPOutputStream } // retourne la taille sérialisée non compressée, // qui est une estimation pessimiste de l'occupation mémoire return counterOutput.dataLength; } } /** * Lecture du counter depuis son fichier et retour du résultat. * @return Counter * @throws IOException e */ Counter readFromFile() throws IOException { if (storageDisabled) { return null; } final File file = getFile(); if (file.exists()) { return readFromFile(file); } // ou on retourne null si le fichier n'existe pas return null; } static Counter readFromFile(File file) throws IOException { try (FileInputStream in = new FileInputStream(file)) { try (ObjectInputStream input = TransportFormat .createObjectInputStream(new GZIPInputStream(new BufferedInputStream(in)))) { // on retourne l'instance du counter lue return (Counter) input.readObject(); // ce close libère les ressources du ObjectInputStream et du GZIPInputStream } } catch (final ClassNotFoundException e) { throw new IOException(e.getMessage(), e); } catch (final IllegalStateException | ClassCastException e) { LOG.warn("could not deserialize " + file.getName() + " , corrupted file will be deleted.", e); file.delete(); return null; } } private File getFile() { final File storageDirectory = Parameters.getStorageDirectory(counter.getApplication()); return new File(storageDirectory, counter.getStorageName() + ".ser.gz"); } static long deleteObsoleteCounterFiles(String application) {<FILL_FUNCTION_BODY>
final Calendar nowMinusOneYearAndADay = Calendar.getInstance(); nowMinusOneYearAndADay.add(Calendar.DAY_OF_YEAR, -getObsoleteStatsDays()); nowMinusOneYearAndADay.add(Calendar.DAY_OF_YEAR, -1); // filtre pour ne garder que les fichiers d'extension .ser.gz et pour éviter d'instancier des File inutiles long diskUsage = 0; for (final File file : listSerGzFiles(application)) { boolean deleted = false; if (file.lastModified() < nowMinusOneYearAndADay.getTimeInMillis()) { deleted = file.delete(); } if (!deleted) { diskUsage += file.length(); } } // on retourne true si tous les fichiers .ser.gz obsolètes ont été supprimés, false sinon return diskUsage;
1,241
277
1,518