hexsha
stringlengths
40
40
size
int64
3
1.05M
ext
stringclasses
1 value
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
5
1.02k
max_stars_repo_name
stringlengths
4
126
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
list
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
5
1.02k
max_issues_repo_name
stringlengths
4
114
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
list
max_issues_count
float64
1
92.2k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
5
1.02k
max_forks_repo_name
stringlengths
4
136
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
list
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
avg_line_length
float64
2.55
99.9
max_line_length
int64
3
1k
alphanum_fraction
float64
0.25
1
index
int64
0
1M
content
stringlengths
3
1.05M
9231f4475b3bf1e2c197c835ad9501abda16d76f
85
java
Java
server/src/test/java/com/breakersoft/plow/test/dispatcher/ProcDispatcherTests.java
Br3nda/plow
eea4468078df58d6798ceabe14c0d3e83f2c3a8d
[ "Apache-2.0" ]
36
2015-01-02T21:02:04.000Z
2021-09-07T12:01:06.000Z
server/src/test/java/com/breakersoft/plow/test/dispatcher/ProcDispatcherTests.java
Br3nda/plow
eea4468078df58d6798ceabe14c0d3e83f2c3a8d
[ "Apache-2.0" ]
3
2020-05-15T21:01:33.000Z
2021-12-09T20:25:17.000Z
server/src/test/java/com/breakersoft/plow/test/dispatcher/ProcDispatcherTests.java
onexeno/plow
5c19c78ce0579f624cc774ac260f3178286ccb07
[ "Apache-2.0" ]
11
2015-04-01T21:31:40.000Z
2022-03-30T17:55:27.000Z
14.166667
45
0.811765
996,051
package com.breakersoft.plow.test.dispatcher; public class ProcDispatcherTests { }
9231f4b7ff31adaea50a75afbbfabc3103bdea3a
72
java
Java
codes/src/exceptions/OnOffException1.java
jhwsx/Think4JavaExamples
bf912a14def15c11a9a5eada308ddaae8e31ff8f
[ "Apache-2.0" ]
null
null
null
codes/src/exceptions/OnOffException1.java
jhwsx/Think4JavaExamples
bf912a14def15c11a9a5eada308ddaae8e31ff8f
[ "Apache-2.0" ]
null
null
null
codes/src/exceptions/OnOffException1.java
jhwsx/Think4JavaExamples
bf912a14def15c11a9a5eada308ddaae8e31ff8f
[ "Apache-2.0" ]
1
2022-01-30T00:49:54.000Z
2022-01-30T00:49:54.000Z
14.4
48
0.819444
996,052
package exceptions; public class OnOffException1 extends Exception { }
9231f4feaf922a5de65aab43040b009d494152bb
1,196
java
Java
jrest/src/main/java/com/study/jrest/controller/ConsumesController.java
a18792721831/studyio
f2b182096dad302cd15b2be0d56f18bdb3675f09
[ "Apache-2.0" ]
null
null
null
jrest/src/main/java/com/study/jrest/controller/ConsumesController.java
a18792721831/studyio
f2b182096dad302cd15b2be0d56f18bdb3675f09
[ "Apache-2.0" ]
null
null
null
jrest/src/main/java/com/study/jrest/controller/ConsumesController.java
a18792721831/studyio
f2b182096dad302cd15b2be0d56f18bdb3675f09
[ "Apache-2.0" ]
null
null
null
22.566038
67
0.632943
996,053
package com.study.jrest.controller; import com.study.jrest.domain.Student; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; /** * @author jiayq * @Date 2021-04-03 */ @Path("consumes") public class ConsumesController { @GET @Consumes(MediaType.WILDCARD) public String consumeGet(@QueryParam("name") String name) { return "consume get , " + name; } @GET @Path("{name}") public String consumeGetPath(@PathParam("name") String name) { return "consume get path , " + name; } @POST public String consumePost(@MatrixParam("name") String name) { return "consume post , " + name; } @POST @Path("/post/{name}") public String consumePostPath(@PathParam("name") String name) { return "consume post path , " + name; } @Path("stu") @POST @Consumes(MediaType.APPLICATION_JSON) public String consumeStu(Student student) { return "consume student , " + student; } @Path("stu/bean") @POST @Consumes(MediaType.APPLICATION_FORM_URLENCODED) public String consumeStuBean(@BeanParam Student student) { return "consume student bean , " + student; } }
9231f61e83e6184384d916c072093a14d3b96b72
931
java
Java
src/main/java/com/mahogano/core/presta/mapper/CmsLangMapper.java
mahogano/mahogano
e4e8db4659946cd997b5aa34660c19749312e2a0
[ "MIT" ]
null
null
null
src/main/java/com/mahogano/core/presta/mapper/CmsLangMapper.java
mahogano/mahogano
e4e8db4659946cd997b5aa34660c19749312e2a0
[ "MIT" ]
null
null
null
src/main/java/com/mahogano/core/presta/mapper/CmsLangMapper.java
mahogano/mahogano
e4e8db4659946cd997b5aa34660c19749312e2a0
[ "MIT" ]
null
null
null
34.481481
69
0.713212
996,054
package com.mahogano.core.presta.mapper; import com.mahogano.core.presta.entity.CmsLang; import org.springframework.jdbc.core.RowMapper; import java.sql.ResultSet; import java.sql.SQLException; public class CmsLangMapper implements RowMapper<CmsLang> { @Override public CmsLang mapRow(ResultSet rs, int i) throws SQLException { CmsLang cmsLang = new CmsLang(); cmsLang.setIdCms(rs.getInt("id_cms")); cmsLang.setIdLang(rs.getInt("id_lang")); cmsLang.setIdShop(rs.getInt("id_shop")); cmsLang.setMetaTitle(rs.getString("meta_title")); cmsLang.setHeadSeoTitle(rs.getString("head_seo_title")); cmsLang.setMetaDescription(rs.getString("meta_description")); cmsLang.setMetaKeywords(rs.getString("meta_keywords")); cmsLang.setContent(rs.getString("content")); cmsLang.setLinkRewrite(rs.getString("link_rewrite")); return cmsLang; } }
9231f65879be293cf0efbf28d2178db881cee0c4
294
java
Java
spring-boot-rbac/spring-boot-rbac-jpa/src/main/java/com/example/lewjun/service/SysUserService.java
LewJun/spring-boot-demo
765b64e73eee99d4457dc644122726e8102f19ab
[ "MIT" ]
null
null
null
spring-boot-rbac/spring-boot-rbac-jpa/src/main/java/com/example/lewjun/service/SysUserService.java
LewJun/spring-boot-demo
765b64e73eee99d4457dc644122726e8102f19ab
[ "MIT" ]
null
null
null
spring-boot-rbac/spring-boot-rbac-jpa/src/main/java/com/example/lewjun/service/SysUserService.java
LewJun/spring-boot-demo
765b64e73eee99d4457dc644122726e8102f19ab
[ "MIT" ]
null
null
null
21
69
0.690476
996,055
package com.example.lewjun.service; import com.example.lewjun.domain.SysUser; public interface SysUserService extends IBaseService<SysUser, Long> { /** * 根据用户名判断是否存在 * * @param username * @return true if exists */ boolean existsByUsername(String username); }
9231f666a59f3d2ea409ba49990962eb4baa2263
1,094
java
Java
ES-system/src/main/java/com/es/manager/mapper/StuInterviewScoreMapper.java
dongyangfu/es
03f8761be66b3063fa740d38e8b62e9a3099a27e
[ "MIT" ]
1
2021-04-30T02:37:45.000Z
2021-04-30T02:37:45.000Z
ES-system/src/main/java/com/es/manager/mapper/StuInterviewScoreMapper.java
dongyangfu/es
03f8761be66b3063fa740d38e8b62e9a3099a27e
[ "MIT" ]
null
null
null
ES-system/src/main/java/com/es/manager/mapper/StuInterviewScoreMapper.java
dongyangfu/es
03f8761be66b3063fa740d38e8b62e9a3099a27e
[ "MIT" ]
null
null
null
22.326531
110
0.671846
996,056
package com.es.manager.mapper; import com.es.manager.domain.dto.StuInterviewScoreDTO; import com.es.manager.domain.vo.StuInterviewScoreVO; import org.apache.ibatis.annotations.Param; import java.util.List; /** * @author: fudy * @date: 2021/4/20 下午 09:54 * @Decription: 学生面试成绩表 **/ public interface StuInterviewScoreMapper { /** * 根据stuIds插入数据 * * @param stuInterviewScoreDTO 学生ids * @return int */ int insertByIds(@Param("dto") StuInterviewScoreDTO stuInterviewScoreDTO, @Param("period") Integer period); /** * 获取所有学生 * * @param stuInterviewScoreDTO 入参 * @return StuInterviewScoreVO */ List<StuInterviewScoreVO> getAll(StuInterviewScoreDTO stuInterviewScoreDTO); /** * 获取所有面试教师 * * @param stuInterviewScoreDTO 入参 * @return StuInterviewScoreVO */ List<StuInterviewScoreVO> getAllInterviewTea(StuInterviewScoreDTO stuInterviewScoreDTO); /** * 批量修改面试成绩表 * * @param dto 入参 * @return int */ int updateList(@Param("dto") List<StuInterviewScoreDTO> dto); }
9231f6da91a571351b2d06275b4b20413ccb6817
2,830
java
Java
geode-optimizer-fabric/src/main/java/net/lucraft/geodeoptimizer/fabric/generation/schematics/SchematicUtil.java
lucr4ft/geode-optimizer
94e83c4880d9b7f3d9067ce66397eb79fddff313
[ "MIT" ]
2
2021-08-14T17:40:32.000Z
2021-08-17T17:53:10.000Z
geode-optimizer-fabric/src/main/java/net/lucraft/geodeoptimizer/fabric/generation/schematics/SchematicUtil.java
lucr4ft/geode-optimizer
94e83c4880d9b7f3d9067ce66397eb79fddff313
[ "MIT" ]
1
2021-08-07T15:46:12.000Z
2021-08-14T17:16:27.000Z
geode-optimizer-fabric/src/main/java/net/lucraft/geodeoptimizer/fabric/generation/schematics/SchematicUtil.java
lucr4ft/geode-optimizer
94e83c4880d9b7f3d9067ce66397eb79fddff313
[ "MIT" ]
null
null
null
37.236842
107
0.577739
996,057
package net.lucraft.geodeoptimizer.fabric.generation.schematics; import net.minecraft.block.Block; import net.minecraft.block.BlockState; import net.minecraft.state.StateManager; import net.minecraft.state.property.Property; import net.minecraft.util.registry.Registry; import java.util.*; public final class SchematicUtil { /** * @see SchematicUtil#fromString(String) * @param blockState the {@link BlockState} to convert to a {@link String} * @return the {@link BlockState} as a {@link String} */ @SuppressWarnings({"rawtypes", "unchecked"}) public static String toString(BlockState blockState) { StringBuilder builder = new StringBuilder(); builder.append(Registry.BLOCK.getRawId(blockState.getBlock())); if (blockState.getEntries().size() > 0) { builder.append('['); boolean append = false; for (Map.Entry<Property<?>, Comparable<?>> entry : blockState.getEntries().entrySet()) { if (append) { builder.append(','); } append = true; Property p = entry.getKey(); Comparable c = entry.getValue(); builder.append(p.getName()).append('=').append(p.name(c)); } builder.append(']'); } return builder.toString(); } /** * @see SchematicUtil#toString(BlockState) * @param blockStr the blockstate as a string (created with {@link SchematicUtil#toString(BlockState)}) * @return the string as a {@link BlockState} */ @SuppressWarnings({"rawtypes", "unchecked"}) public static BlockState fromString(String blockStr) { Block block = Registry.BLOCK.get(Integer.parseInt(blockStr.split("\\[")[0])); StateManager<Block, BlockState> stateManager = block.getStateManager(); BlockState blockState = block.getDefaultState(); if (blockStr.indexOf('[') != -1) { // properties are specified String propsStr = blockStr.substring(blockStr.indexOf('[') + 1, blockStr.length() - 1); // check if properties array is not empty if (!propsStr.equals("")) { for (String prop : propsStr.split(",")) { String name = prop.split("=")[0]; String value = prop.split("=")[1]; Property<?> property = stateManager.getProperty(name); assert property != null; Optional<? extends Comparable<?>> optional = property.parse(value); if (optional.isPresent()) { blockState = blockState.with((Property) property, (Comparable) optional.get()); } } } } return blockState; } }
9231f914747737bfc2245e90626182953273fd7e
4,699
java
Java
src/main/java/com/github/mygreen/cellformatter/tokenizer/TokenStore.java
mygreen/excel-cellformatter
96d86e3ab6da50cbe86a82bf5ca87a9d17f93a5e
[ "Apache-2.0" ]
12
2016-05-28T08:32:29.000Z
2021-12-31T02:42:25.000Z
src/main/java/com/github/mygreen/cellformatter/tokenizer/TokenStore.java
mygreen/excel-cellformatter
96d86e3ab6da50cbe86a82bf5ca87a9d17f93a5e
[ "Apache-2.0" ]
22
2015-04-05T12:34:12.000Z
2021-02-22T05:43:20.000Z
src/main/java/com/github/mygreen/cellformatter/tokenizer/TokenStore.java
mygreen/excel-cellformatter
96d86e3ab6da50cbe86a82bf5ca87a9d17f93a5e
[ "Apache-2.0" ]
4
2015-07-14T06:45:19.000Z
2020-02-26T09:10:50.000Z
24.602094
96
0.482869
996,058
package com.github.mygreen.cellformatter.tokenizer; import java.util.ArrayList; import java.util.List; import com.github.mygreen.cellformatter.lang.ArgUtils; import com.github.mygreen.cellformatter.lang.Utils; /** * {@link Token}を保持するクラス。 * <p>検索機能などを提供する。 * @author T.TSUCHIE * */ public class TokenStore { private List<Token> tokens = new ArrayList<>(); public TokenStore() { } /** * トークンを追加する。 * @param token */ public void add(final Token token) { getTokens().add(token); } /** * トークンを取得する。 * @return */ public List<Token> getTokens() { return tokens; } /** * 記号でトークンを分割する。 * @param symbol 分割する記号 * @return * @throws IllegalArgumentException symbol == null. */ public List<TokenStore> split(final Token.Symbol symbol) { ArgUtils.notNull(symbol, "symbol"); final List<TokenStore> list = new ArrayList<>(); TokenStore store = new TokenStore(); list.add(store); for(Token token : tokens) { if(token.equals(symbol)) { store = new TokenStore(); list.add(store); } else { store.add(token); } } return list; } /** * トークンを全て結合した値を取得する。 * @return */ public String getConcatenatedToken() { StringBuilder sb = new StringBuilder(); for(Token token : tokens) { sb.append(token.getValue()); } return sb.toString(); } /** * {@link Token.Factor}中に指定した文字列を含むかどうか。 * @param search * @return */ public boolean containsInFactor(final String search) { return containsInFactor(search, false); } /** * 大文字・小文字を無視して{@link Token.Factor}中に指定した文字列を含むかどうか。 * @param search * @return */ public boolean containsInFactorIgnoreCase(final String search) { return containsInFactor(search, true); } public boolean containsInFactor(final String search, final boolean ignoreCase) { for(Token token : tokens) { if(!(token instanceof Token.Factor)) { continue; } final Token.Factor factor = token.asFactor(); if(ignoreCase) { if(Utils.containsIgnoreCase(factor.getValue(), search)) { return true; } } else { if(factor.getValue().contains(search)) { return true; } } } return false; } /** * {@link Token.Factor}中に指定した文字列の何れかを含むかどうか。 * @param searchChars * @return */ public boolean containsAnyInFactor(final String[] searchChars) { return containsAnyInFactor(searchChars, false); } /** * 大文字・小文字を無視して{@link Token.Factor}中に指定した文字列の何れかを含むかどうか。 * @param searchChars * @return */ public boolean containsAnyInFactorIgnoreCase(final String[] searchChars) { return containsAnyInFactor(searchChars, true); } /** * 大文字・小文字を無視して{@link Token.Factor}中に指定した文字列の何れかを含むかどうか。 * @param searchChars * @return */ private boolean containsAnyInFactor(final String[] searchChars, final boolean ignoreCase) { for(Token token : tokens) { if(!(token instanceof Token.Factor)) { continue; } final Token.Factor factor = token.asFactor(); if(Utils.containsAny(factor.getValue(), searchChars, ignoreCase)) { return true; } } return false; } @Override public String toString() { StringBuilder sb = new StringBuilder(); final int size = tokens.size(); for(int i=0; i < size; i++) { final Token token = tokens.get(i); sb.append(String.format("[%d]%s(%s)", i, token.getClass().getSimpleName(), token.getValue())); if(i < size-1) { sb.append(", "); } } return sb.toString(); } }
9231f99a7e41521936496a1a52546c2d3a383b3c
4,271
java
Java
src/main/java/com/hospitalmanagement/controller/AdminController.java
SrinathAkkem/HMS
f2880ba2aded9d97ab7a4f837f16dc177487bac5
[ "MIT" ]
null
null
null
src/main/java/com/hospitalmanagement/controller/AdminController.java
SrinathAkkem/HMS
f2880ba2aded9d97ab7a4f837f16dc177487bac5
[ "MIT" ]
null
null
null
src/main/java/com/hospitalmanagement/controller/AdminController.java
SrinathAkkem/HMS
f2880ba2aded9d97ab7a4f837f16dc177487bac5
[ "MIT" ]
null
null
null
31.637037
124
0.781316
996,059
package com.hospitalmanagement.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import com.hospitalmanagement.model.Admin; import com.hospitalmanagement.resource.AdminResource; import com.hospitalmanagement.resource.AppointmentResource; import com.hospitalmanagement.resource.DoctorResource; import com.hospitalmanagement.resource.MedicineCompanyResource; import com.hospitalmanagement.resource.MedicineDistributorResource; import com.hospitalmanagement.resource.MedicineResource; import com.hospitalmanagement.resource.PatientResource; import com.hospitalmanagement.resource.PharmacistResource; import com.hospitalmanagement.resource.ReceptionistResource; @Controller public class AdminController { private static Logger LOG = LogManager.getLogger(AdminController.class); @Autowired private AdminResource adminResource; @Autowired private AppointmentResource appointmentResource; @Autowired private MedicineResource medicineResource; @Autowired private MedicineCompanyResource companyResource; @Autowired private MedicineDistributorResource distributorResource; @Autowired private DoctorResource doctorResource; @Autowired private PatientResource patientResource; @Autowired private ReceptionistResource receptionistResource; @Autowired private PharmacistResource pharmacistResource; @GetMapping("/") public String goToHomeDuringStart() { LOG.info("In Home Page index.jsp"); return "index"; } @GetMapping("/adminlogin") public String goToAdminLoginPage() { LOG.info("Redirecting to Admin Login Page."); return "adminlogin"; } @GetMapping("/adminregister") public String goToAdminRegisterPage() { LOG.info("Redirecting to Admin Login Page."); return "adminregister"; } @PostMapping("/adminregister") public ModelAndView registerAdmin(@ModelAttribute Admin admin, Model model) { ModelAndView mv = new ModelAndView(); if(this.adminResource.addAdmin(admin)==true) { mv.addObject("status", admin.getFirstname()+" Successfully Registered as ADMIN"); mv.setViewName("adminlogin"); } else { mv.addObject("status", admin.getFirstname()+" Failed to Registered as ADMIN"); mv.setViewName("adminregister"); } return mv; } @PostMapping("/adminlogin") public ModelAndView loginAdmin(HttpServletRequest request, @RequestParam String username, @RequestParam String password ) { ModelAndView mv = new ModelAndView(); Admin admin=this.adminResource.loginAdmin(username, password); if(admin != null) { HttpSession session = request.getSession(); session.setAttribute("active-user", admin); session.setAttribute("user-login","admin"); mv.addObject("status", username+" Successfully Logged in as ADMIN"); mv.setViewName("index"); } else { mv.addObject("status"," Failed to Login as ADMIN"); mv.setViewName("adminlogin"); } return mv; } @GetMapping("/admindashboard") public ModelAndView adminDashboard(@RequestParam String view) { ModelAndView mv = new ModelAndView(); mv.addObject("view", view); mv.addObject("appointmentResource", appointmentResource); mv.addObject("medicineResource", medicineResource); mv.addObject("companyResource", companyResource); mv.addObject("distributorResource", distributorResource); mv.addObject("patientResource",patientResource ); mv.addObject("doctorResource", doctorResource); mv.addObject("distributorResource",distributorResource ); mv.addObject("companyResource", companyResource); mv.addObject("receptionistResource",receptionistResource); mv.addObject("pharmacistResource",pharmacistResource); mv.setViewName("admindashboard"); return mv; } }
9231f9b3bb7840c17a2a9134d81d5010dff82c77
1,096
java
Java
components/data-services/org.wso2.carbon.dataservices.core/src/main/java/org/wso2/carbon/dataservices/core/custom/datasource/CustomTabularDataSourceReader.java
SecondaryOrganization/carbon-data
187d0f3027e932534215bb038d1fc0560ba6031a
[ "Apache-2.0" ]
10
2016-05-17T10:01:22.000Z
2021-01-21T13:53:16.000Z
components/data-services/org.wso2.carbon.dataservices.core/src/main/java/org/wso2/carbon/dataservices/core/custom/datasource/CustomTabularDataSourceReader.java
SecondaryOrganization/carbon-data
187d0f3027e932534215bb038d1fc0560ba6031a
[ "Apache-2.0" ]
112
2015-01-06T03:32:29.000Z
2022-01-27T16:17:10.000Z
components/data-services/org.wso2.carbon.dataservices.core/src/main/java/org/wso2/carbon/dataservices/core/custom/datasource/CustomTabularDataSourceReader.java
SecondaryOrganization/carbon-data
187d0f3027e932534215bb038d1fc0560ba6031a
[ "Apache-2.0" ]
110
2015-01-30T17:40:44.000Z
2021-06-08T09:21:22.000Z
31.314286
83
0.740876
996,060
/* * Copyright (c) 2005-2012, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.wso2.carbon.dataservices.core.custom.datasource; /** * This class represents the data source reader implementation for * data services custom tabular data sources. */ public class CustomTabularDataSourceReader extends AbstractCustomDataSourceReader { public static String DATA_SOURCE_TYPE = "DS_CUSTOM_TABULAR"; @Override public String getType() { return DATA_SOURCE_TYPE; } }
9231fafcc734e7fe5d228c971e43d8e40e78c67c
7,910
java
Java
main/messaging-rabbitmq/src/test/java/org/elasticsoftware/elasticactors/rabbitmq/RabbitMQMessagingServiceTest.java
elasticsoftwarefoundation/elasticactors
803ddb05dc198f47fe3857ed5b17bb7f6dc5d9ae
[ "Apache-2.0" ]
30
2016-09-18T15:48:47.000Z
2022-02-16T10:13:05.000Z
main/messaging-rabbitmq/src/test/java/org/elasticsoftware/elasticactors/rabbitmq/RabbitMQMessagingServiceTest.java
elasticsoftwarefoundation/elasticactors
803ddb05dc198f47fe3857ed5b17bb7f6dc5d9ae
[ "Apache-2.0" ]
21
2017-09-28T11:29:50.000Z
2022-01-20T07:30:40.000Z
main/messaging-rabbitmq/src/test/java/org/elasticsoftware/elasticactors/rabbitmq/RabbitMQMessagingServiceTest.java
elasticsoftwarefoundation/elasticactors
803ddb05dc198f47fe3857ed5b17bb7f6dc5d9ae
[ "Apache-2.0" ]
11
2015-10-07T11:56:52.000Z
2021-12-01T18:32:58.000Z
38.965517
124
0.683439
996,062
/* * Copyright 2013 - 2019 The Original Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.elasticsoftware.elasticactors.rabbitmq; import org.elasticsoftware.elasticactors.ActorRef; import org.elasticsoftware.elasticactors.PhysicalNode; import org.elasticsoftware.elasticactors.cluster.ActorRefFactory; import org.elasticsoftware.elasticactors.cluster.InternalActorSystem; import org.elasticsoftware.elasticactors.messaging.DefaultInternalMessage; import org.elasticsoftware.elasticactors.messaging.InternalMessage; import org.elasticsoftware.elasticactors.messaging.MessageHandler; import org.elasticsoftware.elasticactors.messaging.MessageHandlerEventListener; import org.elasticsoftware.elasticactors.messaging.MessageQueue; import org.elasticsoftware.elasticactors.messaging.MessageQueueFactory; import org.elasticsoftware.elasticactors.rabbitmq.sc.SingleProducerRabbitMQMessagingService; import org.elasticsoftware.elasticactors.serialization.internal.ActorRefDeserializer; import org.elasticsoftware.elasticactors.serialization.internal.InternalMessageDeserializer; import org.elasticsoftware.elasticactors.util.concurrent.BlockingQueueThreadBoundExecutor; import org.elasticsoftware.elasticactors.util.concurrent.DaemonThreadFactory; import org.elasticsoftware.elasticactors.util.concurrent.ThreadBoundExecutor; import org.elasticsoftware.elasticactors.util.concurrent.ThreadBoundRunnable; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.LinkedList; import java.util.List; import java.util.Random; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.testng.Assert.assertTrue; import static java.lang.String.format; /** * @author Joost van de Wijgerd */ public class RabbitMQMessagingServiceTest { public final int NUM_PARTITIONS = 64; public final int NUM_MESSAGES = 10000; public final String CLUSTER_NAME = "test.vdwbv.com"; public static final String QUEUENAME_FORMAT = "default/shards/%d"; public static final String PAYLOAD_FORMAT = "This is message numero %d from %s"; public final Random random = new Random(); private ActorRef senderRef; private ActorRef receiverRef; private ActorRefFactory actorRefFactory; private InternalActorSystem internalActorSystem; @BeforeTest(alwaysRun = true) public void setUp() { senderRef = mock(ActorRef.class); receiverRef = mock(ActorRef.class); actorRefFactory = mock(ActorRefFactory.class); internalActorSystem = mock(InternalActorSystem.class); when(receiverRef.toString()).thenReturn("actor://test.vdwbv.com/test/shards/1/testReceiver"); when(senderRef.toString()).thenReturn("actor://test.vdwbv.com/test/shards/1/testSender"); when(actorRefFactory.create("actor://test.vdwbv.com/test/shards/1/testReceiver")).thenReturn(receiverRef); when(actorRefFactory.create("actor://test.vdwbv.com/test/shards/1/testSender")).thenReturn(senderRef); // not a very nice construction, but alas // ActorRefDeserializer.get().setActorRefFactory(actorRefFactory); } @Test(enabled = false) public void testAllLocal() throws Exception { int workers = Runtime.getRuntime().availableProcessors() * 3; ThreadBoundExecutor queueExecutor = new BlockingQueueThreadBoundExecutor( new DaemonThreadFactory("QUEUE-WORKER"), workers, null ); SingleProducerRabbitMQMessagingService messagingService = new SingleProducerRabbitMQMessagingService( CLUSTER_NAME, System.getProperty("host", "localhost"), 5672, System.getProperty("username", "guest"), System.getProperty("password", "guest"), MessageAcker.Type.DIRECT, queueExecutor, new InternalMessageDeserializer( new ActorRefDeserializer(actorRefFactory), internalActorSystem ), 10, null, null ); messagingService.start(); final CountDownLatch waitLatch = new CountDownLatch(NUM_MESSAGES); MessageHandler testHandler = new MessageHandler() { @Override public PhysicalNode getPhysicalNode() { return null; } @Override public void handleMessage(InternalMessage message, MessageHandlerEventListener messageHandlerEventListener) { /*byte[] buffer = new byte[message.getPayload().remaining()]; message.getPayload().get(buffer); System.out.println(new String(buffer,Charsets.UTF_8));*/ messageHandlerEventListener.onDone(message); waitLatch.countDown(); } }; List<MessageQueue> messageQueues = new LinkedList<>(); // simulate 8 partitions MessageQueueFactory localMessageQueueFactory = messagingService.getLocalMessageQueueFactory(); for (int i = 0; i < NUM_PARTITIONS; i++) { messageQueues.add(localMessageQueueFactory.create(format(QUEUENAME_FORMAT, i),testHandler)); } int NUMBER_OF_THREADS = 4; for (int i = 0; i < NUMBER_OF_THREADS; i++) { Thread t = new Thread(new MessageSender(NUM_MESSAGES/NUMBER_OF_THREADS,messageQueues),format("PRODUCER #%s",i)); t.setDaemon(true); t.start(); } try { assertTrue(waitLatch.await(60, TimeUnit.SECONDS)); } catch (InterruptedException e) { // ignore } for (MessageQueue messageQueue : messageQueues) { messageQueue.destroy(); } messagingService.stop(); } private final class MessageSender implements ThreadBoundRunnable<String> { private final Integer messagesToSend; private final List<MessageQueue> messageQueues; private MessageSender(Integer messagesToSend, List<MessageQueue> messageQueues) { this.messagesToSend = messagesToSend; this.messageQueues = messageQueues; } @Override public String getKey() { return messagesToSend.toString(); } @Override public void run() { final String name = Thread.currentThread().getName(); // send the messages for (int i = 0; i < messagesToSend ; i++) { // select a random queue messageQueues.get(random.nextInt(NUM_PARTITIONS)).offer(createInternalMessage(name,i+1)); try { Thread.sleep(1); } catch (InterruptedException e) { // ignore } } } } private InternalMessage createInternalMessage(String name,int count) { ByteBuffer payload = ByteBuffer.wrap(format(PAYLOAD_FORMAT, count, name).getBytes(StandardCharsets.UTF_8)); return new DefaultInternalMessage( senderRef, receiverRef, payload, String.class.getName(), null, true ); } }
9231fb04fc62e8562d1960ebdfe7aea4c0d04cb5
4,678
java
Java
src/item/Item.java
rottava/Draks
171011f8de1138f285e34b539fdff9d3051a4549
[ "MIT" ]
null
null
null
src/item/Item.java
rottava/Draks
171011f8de1138f285e34b539fdff9d3051a4549
[ "MIT" ]
null
null
null
src/item/Item.java
rottava/Draks
171011f8de1138f285e34b539fdff9d3051a4549
[ "MIT" ]
null
null
null
25.703297
117
0.498504
996,063
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package item; import java.io.Serializable; /** * Classe abstrata de Item * @author Junior */ public abstract class Item implements Serializable { //PARAMETRO DE CONFIGURACAO private byte id; //ID DO ITEM = LINHA DO ARQUIVO //PARAMETRO DE DEFINIÇÃO private String nome; //NOME DO ITEM private byte efeito; //EFEITO private byte peso; //PESO POR ITEM private final byte QUANTIDADEMAX = 100; //MAXIMO DE ITENS POR SLOT +1 //PARAMETRO VARIAVEL private byte quantidade; //QUANTIDADE //CONSTRUTOR /** * Construtor */ public Item(){ quantidade = 1; //QUANTIDADE MINIMA PARA EXISTIR = 1 } //GETTERS AND SETTERS //RETORNA NOME /** * Pega o nome do Item * @return String com o nome */ public String getNome(){ return nome; } //SETA NOME PARA /** * Configura nome do Item * @param nome String contendo o nome do item */ protected void setNome(String nome){ this.nome = nome; } //RETORNA ID /** * Pega a ID do tem * @return byte contendo a ID do ítem */ public byte getId(){ return id; } //SETA ID PARA /** * Configura ID do ítem * @param id ID do ítem */ protected void setId(byte id){ this.id = id; } //RETORNA EFEITO /** * Pega o efeito do ítem * @return byte com a ID do efeito */ public byte getEfeito(){ return efeito; } //SETA EFEITO PARA /** * Configura efeito * @param efeito Efeito do ítem */ protected void setEfeito(byte efeito){ this.efeito = efeito; } //RETORNA QUANTIDADE TOTAL /** * Pega a quantidade total de item * @return byte com a quantidade total de ítem */ public byte getQuantidade(){ return quantidade; } //RETORNA QUANTIDADE MAXIMA DO ITEM POR OBJETO /** * Pega a quantidade máximo de ítem * @return byte com a quantidade máxima de ítem */ public byte getQuantidadeMax(){ return QUANTIDADEMAX; } //SETA QUANTIDADE PARA /** * Configura a quantidade de ítem * @param quantidade byte com a quantidade do ítem * @return true se a operação foi realizada com sucesso, false caso contrário */ public boolean setQuantidade(byte quantidade){ if(quantidade <= QUANTIDADEMAX && quantidade > 0){ this.quantidade = quantidade; return true; } else return false; } //RETORNA PESO INDIVIDUAL DO ITEM /** * Pega peso individual do ite * @return byte com o peso individual do ítem */ public byte getPeso(){ return peso; } //SETA PESO ITEM PARA /** * Configura peso do ítem * @param peso byte com o peso do ítem */ protected void setPeso(byte peso){ this.peso = peso; } //RETORNA PESO TOTAL DO ITEM /** * Pega o peso total do item * @return byte com o peso total do item */ public byte getPesoTotal(){ float pesoTotal = peso; pesoTotal = ((pesoTotal * quantidade)); return (byte) pesoTotal; } /** * Decrementa a quantidade do ítem * @return true se foi decrementado, false caso contrário */ public boolean decrementa(){ if (quantidade > 1){ quantidade--; return true; } else return false; } /** * Incrementa na quantidade do ítem * @return true se foi incrementado, false caso contrário */ public boolean incrementa(){ if (quantidade < QUANTIDADEMAX){ quantidade++; return true; } else{ quantidade = (QUANTIDADEMAX); return false; } } }
9231fb1876896e6638069e06df91ae2e835d7c83
584
java
Java
src/main/java/com/wmi/spizarnia_domowa/model/ShoppingList.java
MonikaKuczkowska/spizarnia_domowa_backend
67a22648a2570cced82d3af271d1a421cb3dce34
[ "BSD-3-Clause" ]
null
null
null
src/main/java/com/wmi/spizarnia_domowa/model/ShoppingList.java
MonikaKuczkowska/spizarnia_domowa_backend
67a22648a2570cced82d3af271d1a421cb3dce34
[ "BSD-3-Clause" ]
null
null
null
src/main/java/com/wmi/spizarnia_domowa/model/ShoppingList.java
MonikaKuczkowska/spizarnia_domowa_backend
67a22648a2570cced82d3af271d1a421cb3dce34
[ "BSD-3-Clause" ]
null
null
null
20.137931
51
0.758562
996,064
package com.wmi.spizarnia_domowa.model; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import org.hibernate.annotations.Type; import javax.persistence.*; import java.util.UUID; @Entity @Getter @Setter @NoArgsConstructor @AllArgsConstructor @Table(name = "Shopping_List") public class ShoppingList { @Id @Type(type = "org.hibernate.type.UUIDCharType") private UUID id = UUID.randomUUID(); private int quantityToBuy; @ManyToOne private Group group; @OneToOne private Product product; }
9231fb40bd9fb78f54194317df8853d1a9965c90
2,657
java
Java
core/src/main/java/jenkins/model/BuildDiscarderProperty.java
ydubreuil/jenkins
0c991dec38800adabacd8a56349bd61575c1d7e5
[ "MIT" ]
17,275
2015-01-01T21:08:25.000Z
2022-03-31T17:26:18.000Z
core/src/main/java/jenkins/model/BuildDiscarderProperty.java
ydubreuil/jenkins
0c991dec38800adabacd8a56349bd61575c1d7e5
[ "MIT" ]
4,230
2015-01-01T14:07:24.000Z
2022-03-31T22:58:42.000Z
core/src/main/java/jenkins/model/BuildDiscarderProperty.java
ydubreuil/jenkins
0c991dec38800adabacd8a56349bd61575c1d7e5
[ "MIT" ]
7,471
2015-01-01T03:11:41.000Z
2022-03-31T21:01:51.000Z
32.402439
151
0.721867
996,065
/* * The MIT License * * Copyright 2015 CloudBees, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package jenkins.model; import hudson.Extension; import hudson.model.Descriptor; import hudson.model.DescriptorVisibilityFilter; import hudson.model.Items; import hudson.model.Job; import org.jenkinsci.Symbol; import org.kohsuke.stapler.DataBoundConstructor; /** * Defines a {@link BuildDiscarder}. * @since 1.637 */ public class BuildDiscarderProperty extends OptionalJobProperty<Job<?,?>> { private final BuildDiscarder strategy; @DataBoundConstructor public BuildDiscarderProperty(BuildDiscarder strategy) { this.strategy = strategy; } public BuildDiscarder getStrategy() { return strategy; } @Extension @Symbol("buildDiscarder") public static class DescriptorImpl extends OptionalJobPropertyDescriptor { @Override public String getDisplayName() { return Messages.BuildDiscarderProperty_displayName(); } static { Items.XSTREAM2.addCompatibilityAlias("org.jenkinsci.plugins.workflow.job.properties.BuildDiscarderProperty", BuildDiscarderProperty.class); } } @Extension public static class ConditionallyHidden extends DescriptorVisibilityFilter { @SuppressWarnings("rawtypes") @Override public boolean filter(Object context, Descriptor descriptor) { if (descriptor instanceof DescriptorImpl && context instanceof Job) { return ((Job) context).supportsLogRotator(); } return true; } } }
9231fb5c774f15a3093cf99995b69cac260573df
7,635
java
Java
engine/src/test/java/org/camunda/bpm/engine/test/api/multitenancy/tenantcheck/MultiTenancyTaskVariableCmdsTenantCheckTest.java
AndreaGiardini/camunda-bpm-platform
ce60b6799ab381f817f1b6f39883576678a43cfa
[ "Apache-2.0" ]
1
2020-05-20T19:15:09.000Z
2020-05-20T19:15:09.000Z
engine/src/test/java/org/camunda/bpm/engine/test/api/multitenancy/tenantcheck/MultiTenancyTaskVariableCmdsTenantCheckTest.java
AndreaGiardini/camunda-bpm-platform
ce60b6799ab381f817f1b6f39883576678a43cfa
[ "Apache-2.0" ]
1
2022-03-31T21:02:16.000Z
2022-03-31T21:02:16.000Z
engine/src/test/java/org/camunda/bpm/engine/test/api/multitenancy/tenantcheck/MultiTenancyTaskVariableCmdsTenantCheckTest.java
AndreaGiardini/camunda-bpm-platform
ce60b6799ab381f817f1b6f39883576678a43cfa
[ "Apache-2.0" ]
1
2019-09-07T01:31:19.000Z
2019-09-07T01:31:19.000Z
31.945607
114
0.744859
996,066
package org.camunda.bpm.engine.test.api.multitenancy.tenantcheck; import static org.junit.Assert.assertEquals; import java.util.Arrays; import org.camunda.bpm.engine.ProcessEngineException; import org.camunda.bpm.engine.test.ProcessEngineRule; import org.camunda.bpm.engine.test.util.ProcessEngineTestRule; import org.camunda.bpm.engine.test.util.ProvidedProcessEngineRule; import org.camunda.bpm.engine.variable.Variables; import org.camunda.bpm.model.bpmn.Bpmn; import org.camunda.bpm.model.bpmn.BpmnModelInstance; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.rules.RuleChain; /** * * @author Deivarayan Azhagappan * */ public class MultiTenancyTaskVariableCmdsTenantCheckTest { protected static final String TENANT_ONE = "tenant1"; protected static final String VARIABLE_1 = "testVariable1"; protected static final String VARIABLE_2 = "testVariable2"; protected static final String VARIABLE_VALUE_1 = "test1"; protected static final String VARIABLE_VALUE_2 = "test2"; protected static final String PROCESS_DEFINITION_KEY = "oneTaskProcess"; protected static final BpmnModelInstance ONE_TASK_PROCESS = Bpmn.createExecutableProcess(PROCESS_DEFINITION_KEY) .startEvent() .userTask("task") .endEvent() .done(); protected ProcessEngineRule engineRule = new ProvidedProcessEngineRule(); protected ProcessEngineTestRule testRule = new ProcessEngineTestRule(engineRule); @Rule public RuleChain ruleChain = RuleChain.outerRule(engineRule).around(testRule); protected String taskId; @Rule public ExpectedException thrown= ExpectedException.none(); @Before public void init() { // deploy tenants testRule.deployForTenant(TENANT_ONE, ONE_TASK_PROCESS); engineRule.getRuntimeService() .startProcessInstanceByKey(PROCESS_DEFINITION_KEY, Variables.createVariables() .putValue(VARIABLE_1, VARIABLE_VALUE_1) .putValue(VARIABLE_2, VARIABLE_VALUE_2)) .getId(); taskId = engineRule.getTaskService().createTaskQuery().singleResult().getId(); } // get task variable @Test public void getTaskVariableWithAuthenticatedTenant() { engineRule.getIdentityService().setAuthentication("aUserId", null, Arrays.asList(TENANT_ONE)); assertEquals(VARIABLE_VALUE_1, engineRule.getTaskService().getVariable(taskId, VARIABLE_1)); } @Test public void getTaskVariableWithNoAuthenticatedTenant() { engineRule.getIdentityService().setAuthentication("aUserId", null); // then thrown.expect(ProcessEngineException.class); thrown.expectMessage("Cannot read the task '" + taskId +"' because it belongs to no authenticated tenant."); engineRule.getTaskService().getVariable(taskId, VARIABLE_1); } @Test public void getTaskVariableWithDisabledTenantCheck() { engineRule.getIdentityService().setAuthentication("aUserId", null); engineRule.getProcessEngineConfiguration().setTenantCheckEnabled(false); // then assertEquals(VARIABLE_VALUE_1, engineRule.getTaskService().getVariable(taskId, VARIABLE_1)); } // get task variable typed @Test public void getTaskVariableTypedWithAuthenticatedTenant() { engineRule.getIdentityService().setAuthentication("aUserId", null, Arrays.asList(TENANT_ONE)); // then assertEquals(VARIABLE_VALUE_1, engineRule.getTaskService().getVariableTyped(taskId, VARIABLE_1).getValue()); } @Test public void getTaskVariableTypedWithNoAuthenticatedTenant() { engineRule.getIdentityService().setAuthentication("aUserId", null); // then thrown.expect(ProcessEngineException.class); thrown.expectMessage("Cannot read the task '" + taskId +"' because it belongs to no authenticated tenant."); engineRule.getTaskService().getVariableTyped(taskId, VARIABLE_1).getValue(); } @Test public void getTaskVariableTypedWithDisableTenantCheck() { engineRule.getIdentityService().setAuthentication("aUserId", null); engineRule.getProcessEngineConfiguration().setTenantCheckEnabled(false); // then assertEquals(VARIABLE_VALUE_1, engineRule.getTaskService().getVariableTyped(taskId, VARIABLE_1).getValue()); } // get task variables @Test public void getTaskVariablesWithAuthenticatedTenant() { engineRule.getIdentityService().setAuthentication("aUserId", null, Arrays.asList(TENANT_ONE)); // then assertEquals(2, engineRule.getTaskService().getVariables(taskId).size()); } @Test public void getTaskVariablesWithNoAuthenticatedTenant() { engineRule.getIdentityService().setAuthentication("aUserId", null); // then thrown.expect(ProcessEngineException.class); thrown.expectMessage("Cannot read the task '" + taskId +"' because it belongs to no authenticated tenant."); engineRule.getTaskService().getVariables(taskId).size(); } @Test public void getTaskVariablesWithDisabledTenantCheck() { engineRule.getIdentityService().setAuthentication("aUserId", null); engineRule.getProcessEngineConfiguration().setTenantCheckEnabled(false); assertEquals(2, engineRule.getTaskService().getVariables(taskId).size()); } // set variable test @Test public void setTaskVariableWithAuthenticatedTenant() { engineRule.getIdentityService().setAuthentication("aUserId", null, Arrays.asList(TENANT_ONE)); engineRule.getTaskService().setVariable(taskId, "newVariable", "newValue"); assertEquals(3, engineRule.getTaskService().getVariables(taskId).size()); } @Test public void setTaskVariableWithNoAuthenticatedTenant() { engineRule.getIdentityService().setAuthentication("aUserId", null); thrown.expect(ProcessEngineException.class); thrown.expectMessage("Cannot update the task '" + taskId +"' because it belongs to no authenticated tenant."); engineRule.getTaskService().setVariable(taskId, "newVariable", "newValue"); } @Test public void setTaskVariableWithDisabledTenantCheck() { engineRule.getIdentityService().setAuthentication("aUserId", null); engineRule.getProcessEngineConfiguration().setTenantCheckEnabled(false); engineRule.getTaskService().setVariable(taskId, "newVariable", "newValue"); assertEquals(3, engineRule.getTaskService().getVariables(taskId).size()); } // remove variable test @Test public void removeTaskVariableWithAuthenticatedTenant() { engineRule.getIdentityService().setAuthentication("aUserId", null, Arrays.asList(TENANT_ONE)); engineRule.getTaskService().removeVariable(taskId, VARIABLE_1); // then assertEquals(1, engineRule.getTaskService().getVariables(taskId).size()); } @Test public void removeTaskVariablesWithNoAuthenticatedTenant() { engineRule.getIdentityService().setAuthentication("aUserId", null); // then thrown.expect(ProcessEngineException.class); thrown.expectMessage("Cannot update the task '" + taskId +"' because it belongs to no authenticated tenant."); engineRule.getTaskService().removeVariable(taskId, VARIABLE_1); } @Test public void removeTaskVariablesWithDisabledTenantCheck() { engineRule.getIdentityService().setAuthentication("aUserId", null); engineRule.getProcessEngineConfiguration().setTenantCheckEnabled(false); // then engineRule.getTaskService().removeVariable(taskId, VARIABLE_1); assertEquals(1, engineRule.getTaskService().getVariables(taskId).size()); } }
9231fb96873b5f1fca65129b34fbdb75c27ef5a1
2,784
java
Java
src/java/spl/com.ibm.streams.operator.impl/src/main/java/com/ibm/streams/spl/model/RuntimeConstantsType.java
IBMStreams/OSStreams
c6287bd9ec4323f567d2faf59125baba8604e1db
[ "Apache-2.0" ]
10
2021-02-19T20:19:24.000Z
2021-09-16T05:11:50.000Z
src/java/spl/com.ibm.streams.operator.impl/src/main/java/com/ibm/streams/spl/model/RuntimeConstantsType.java
xguerin/openstreams
7000370b81a7f8778db283b2ba9f9ead984b7439
[ "Apache-2.0" ]
7
2021-02-20T01:17:12.000Z
2021-06-08T14:56:34.000Z
src/java/spl/com.ibm.streams.operator.impl/src/main/java/com/ibm/streams/spl/model/RuntimeConstantsType.java
IBMStreams/OSStreams
c6287bd9ec4323f567d2faf59125baba8604e1db
[ "Apache-2.0" ]
4
2021-02-19T18:43:10.000Z
2022-02-23T14:18:16.000Z
34.37037
171
0.714799
996,067
/* * Copyright 2021 IBM Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference // Implementation, // v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2017.05.17 at 12:19:00 PM EDT // package com.ibm.streams.spl.model; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * Java class for runtimeConstantsType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="runtimeConstantsType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="runtimeConstant" type="{http://www.ibm.com/xmlns/prod/streams/spl/operator/instance}runtimeConstantType" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType( name = "runtimeConstantsType", propOrder = {"runtimeConstant"}) public class RuntimeConstantsType { protected List<RuntimeConstantType> runtimeConstant; /** * Gets the value of the runtimeConstant property. * * <p>This accessor method returns a reference to the live list, not a snapshot. Therefore any * modification you make to the returned list will be present inside the JAXB object. This is why * there is not a <CODE>set</CODE> method for the runtimeConstant property. * * <p>For example, to add a new item, do as follows: * * <pre> * getRuntimeConstant().add(newItem); * </pre> * * <p>Objects of the following type(s) are allowed in the list {@link RuntimeConstantType } */ public List<RuntimeConstantType> getRuntimeConstant() { if (runtimeConstant == null) { runtimeConstant = new ArrayList<RuntimeConstantType>(); } return this.runtimeConstant; } }
9231fd978f021bfa8e47b0120491d9f8975d330f
1,482
java
Java
smqtt-common/src/main/java/io/github/quickmsg/common/metric/WindowCounter.java
quickmsg/smqtt
a29e51672143cc2093cefdca0c11c95ae867c2e9
[ "Apache-2.0" ]
332
2021-04-29T08:13:06.000Z
2022-03-31T03:35:23.000Z
smqtt-common/src/main/java/io/github/quickmsg/common/metric/WindowCounter.java
luckyDTF/smqtt
a29e51672143cc2093cefdca0c11c95ae867c2e9
[ "Apache-2.0" ]
8
2021-06-07T04:11:09.000Z
2021-10-30T07:56:14.000Z
smqtt-common/src/main/java/io/github/quickmsg/common/metric/WindowCounter.java
luckyDTF/smqtt
a29e51672143cc2093cefdca0c11c95ae867c2e9
[ "Apache-2.0" ]
110
2021-04-30T02:36:40.000Z
2022-03-30T08:11:12.000Z
20.873239
103
0.667341
996,068
package io.github.quickmsg.common.metric; import reactor.core.scheduler.Scheduler; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.LongAdder; /** * @author luxurong */ public abstract class WindowCounter implements MetricCounter, Runnable { private final LongAdder sumCountAdder = new LongAdder(); private final LongAdder windowCountAdder = new LongAdder(); private final MetricBean metricBean; @Override public MetricBean getMetricBean() { return this.metricBean; } public WindowCounter(MetricBean metricBean, Integer time, TimeUnit timeUnit, Scheduler scheduler) { this.metricBean = metricBean; scheduler.schedulePeriodically(this, time, time, timeUnit); scheduler.start(); } @Override public void reset() { sumCountAdder.reset(); windowCountAdder.reset(); } public void run() { windowCountAdder.reset(); } @Override public long getCounter() { return this.sumCountAdder.sum(); } public long getAllCount() { return this.sumCountAdder.sum(); } @Override public void increment() { sumCountAdder.increment(); callMeter(sumCountAdder.sum()); } @Override public void decrement() { throw new UnsupportedOperationException("WindowCounter not support decrement"); } public long getWindowCount() { return windowCountAdder.sum(); } }
9231fdd05b8c8755f1b3403451508b6fa0299c74
4,324
java
Java
vividus-plugin-csv/src/test/java/org/vividus/csv/CsvFileCreatorTests.java
EDbarvinsky/vividus
0203a40f826b477f95c29291c6a5bf0d3a898923
[ "Apache-2.0" ]
335
2019-06-24T06:43:45.000Z
2022-03-26T08:26:23.000Z
vividus-plugin-csv/src/test/java/org/vividus/csv/CsvFileCreatorTests.java
EDbarvinsky/vividus
0203a40f826b477f95c29291c6a5bf0d3a898923
[ "Apache-2.0" ]
2,414
2019-08-15T15:24:31.000Z
2022-03-31T14:38:26.000Z
vividus-plugin-csv/src/test/java/org/vividus/csv/CsvFileCreatorTests.java
EDbarvinsky/vividus
0203a40f826b477f95c29291c6a5bf0d3a898923
[ "Apache-2.0" ]
64
2019-08-16T11:32:48.000Z
2022-03-12T06:15:18.000Z
41.180952
120
0.740749
996,069
/* * Copyright 2019-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.vividus.csv; import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.io.TempDir; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) class CsvFileCreatorTests { private static final String SUB_DIRECTORY = "subDirectory"; private static final String NO_SUB_DIRECTORY = ""; private static final String FILE_NAME = "fileName"; private static final String[] HEADER = { "header1", "header2" }; private static final String[] DATA = { "text1", "text2" }; private static final String[] DATA_2 = { "text3", "text4" }; private static String dataToCsvLine(String... data) { return String.join(",", data); } @ParameterizedTest @ValueSource(strings = { SUB_DIRECTORY, NO_SUB_DIRECTORY }) void shouldCreateCsvFilesInAnyDirectory(String subDirectory, @TempDir Path outputDirectory) throws IOException { new CsvFileCreator(outputDirectory.toFile()).createCsvFiles(subDirectory, createCsvFileData(DATA)); verifyCsvFile(outputDirectory, subDirectory, List.of(dataToCsvLine(HEADER), dataToCsvLine(DATA))); } @Test void shouldCreateCsvFilesWithAppendToNonExistingFile(@TempDir Path outputDirectory) throws IOException { CsvFileCreator csvFileCreator = new CsvFileCreator(outputDirectory.toFile()); String subDirectory = NO_SUB_DIRECTORY; csvFileCreator.createCsvFiles(subDirectory, createCsvFileData(DATA), true); verifyCsvFile(outputDirectory, subDirectory, List.of(dataToCsvLine(HEADER), dataToCsvLine(DATA))); } @Test void shouldCreateCsvFilesWithAppend(@TempDir Path outputDirectory) throws IOException { CsvFileCreator csvFileCreator = new CsvFileCreator(outputDirectory.toFile()); String subDirectory = NO_SUB_DIRECTORY; csvFileCreator.createCsvFiles(subDirectory, createCsvFileData(DATA), false); List<CsvFileData> csvFileData2 = createCsvFileData(DATA_2); csvFileCreator.createCsvFiles(subDirectory, csvFileData2, true); verifyCsvFile(outputDirectory, subDirectory, List.of(dataToCsvLine(HEADER), dataToCsvLine(DATA), dataToCsvLine(DATA_2))); } @Test void shouldCreateCsvFilesWithOverwrite(@TempDir Path outputDirectory) throws IOException { CsvFileCreator csvFileCreator = new CsvFileCreator(outputDirectory.toFile()); String subDirectory = NO_SUB_DIRECTORY; csvFileCreator.createCsvFiles(subDirectory, createCsvFileData(DATA), false); List<CsvFileData> csvFileData2 = createCsvFileData(DATA_2); csvFileCreator.createCsvFiles(subDirectory, csvFileData2, false); verifyCsvFile(outputDirectory, subDirectory, List.of(dataToCsvLine(HEADER), dataToCsvLine(DATA_2))); } private List<CsvFileData> createCsvFileData(String... data) { CsvFileData csvFileData = new CsvFileData(); csvFileData.setFileName(FILE_NAME); csvFileData.setHeader(HEADER); csvFileData.setData(List.<Object[]>of(data)); return List.of(csvFileData); } private void verifyCsvFile(Path outputDirectory, String subDirectory, List<String> expectedLines) throws IOException { Path csvFile = outputDirectory.resolve(subDirectory).resolve(FILE_NAME); assertEquals(expectedLines, Files.readAllLines(csvFile)); } }
923200280ad5d506a4ba80b4df80cf376da178e8
3,172
java
Java
src/test/java/org/attendantsoffice/eventmanager/event/team/EventTeamMapperTest.java
alfonsobonso/attendantsoffice
b2a4c8d1fea7ce82e607cb36558ae7187d153876
[ "MIT" ]
1
2018-08-15T17:38:39.000Z
2018-08-15T17:38:39.000Z
src/test/java/org/attendantsoffice/eventmanager/event/team/EventTeamMapperTest.java
alfonsobonso/attendantsoffice
b2a4c8d1fea7ce82e607cb36558ae7187d153876
[ "MIT" ]
null
null
null
src/test/java/org/attendantsoffice/eventmanager/event/team/EventTeamMapperTest.java
alfonsobonso/attendantsoffice
b2a4c8d1fea7ce82e607cb36558ae7187d153876
[ "MIT" ]
null
null
null
32.701031
93
0.691047
996,070
package org.attendantsoffice.eventmanager.event.team; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.mockito.Mockito.when; import java.time.Instant; import java.util.Arrays; import java.util.Collections; import org.attendantsoffice.eventmanager.event.EventApplicationService; import org.attendantsoffice.eventmanager.event.EventEntity; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; /** * Test the {@code EventTeamMapper} class. */ @RunWith(MockitoJUnitRunner.class) public class EventTeamMapperTest { @Mock private EventApplicationService eventApplicationService; private EventTeamMapper mapper; @Before public void setUp() { mapper = new EventTeamMapper(eventApplicationService); } @Test public void testMapNoParent() { // all attributes are mandatory EventTeamEntity entity = entity(1, 10, null); when(eventApplicationService.findName(10)).thenReturn("Event#10"); EventTeamOutput output = mapper.map(entity, Collections.singletonList(entity)); assertEquals(1, output.getEventTeamId().intValue()); assertEquals("EventTeam#1", output.getName()); assertEquals("EventTeam#1 (Billy Bob)", output.getNameWithCaptain()); assertEquals(10, output.getEvent().getId().intValue()); assertEquals("Event#10", output.getEvent().getName()); assertFalse(output.getParentEventTeam().isPresent()); } @Test public void testMapWithParent() { // all attributes are mandatory EventTeamEntity entity = entity(1, 10, null); EventTeamEntity entity2 = entity(2, 10, entity); when(eventApplicationService.findName(10)).thenReturn("Event#10"); EventTeamOutput output = mapper.map(entity2, Arrays.asList(entity, entity2)); assertEquals(2, output.getEventTeamId().intValue()); assertEquals("EventTeam#2", output.getName()); assertEquals("EventTeam#2 (Billy Bob)", output.getNameWithCaptain()); assertEquals(10, output.getEvent().getId().intValue()); assertEquals("Event#10", output.getEvent().getName()); assertEquals(1, output.getParentEventTeam().get().getId().intValue()); assertEquals("EventTeam#1 (Billy Bob)", output.getParentEventTeam().get().getName()); } private EventTeamEntity entity(int id, int eventId, EventTeamEntity parent) { EventTeamEntity entity = new EventTeamEntity(); entity.setEventTeamId(id); EventEntity event = new EventEntity(); event.setEventId(eventId); entity.setEvent(event); entity.setCreatedByUserId(0); entity.setCreatedDateTime(Instant.now()); entity.setUpdatedByUserId(1); entity.setUpdatedDateTime(Instant.now()); entity.setName("EventTeam#" + id); entity.setNameWithCaptain("EventTeam#" + id + " (Billy Bob)"); if (parent != null) { entity.setParentEventTeamId(parent.getEventTeamId()); } return entity; } }
923201a6cac79b137c8a3fd6d61ab80f461782f6
1,034
java
Java
app/src/main/java/com/velvetpearl/lottery/dataaccess/models/Prize.java
denDAY04/velvet-pearl-lottery-app
9b63df082decb97a68bed536d30e111b7a4d6796
[ "MIT" ]
1
2018-09-25T08:37:14.000Z
2018-09-25T08:37:14.000Z
app/src/main/java/com/velvetpearl/lottery/dataaccess/models/Prize.java
denDAY04/velvet-pearl-lottery-app
9b63df082decb97a68bed536d30e111b7a4d6796
[ "MIT" ]
null
null
null
app/src/main/java/com/velvetpearl/lottery/dataaccess/models/Prize.java
denDAY04/velvet-pearl-lottery-app
9b63df082decb97a68bed536d30e111b7a4d6796
[ "MIT" ]
1
2018-09-25T08:37:17.000Z
2018-09-25T08:37:17.000Z
18.8
52
0.598646
996,071
package com.velvetPearl.lottery.dataAccess.models; /** * Created by Andreas "denDAY" Stensig on 20-Sep-16. */ public class Prize { // Entity member fields private Object id; private String name; // Navigational member fields private Object numberId; private Object lotteryId; public void copy(Prize other) { id = other.id; name = other.name; numberId = other.numberId; lotteryId = other.lotteryId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Object getId() { return id; } public void setId(Object id) { this.id = id; } public Object getNumberId() { return numberId; } public void setNumberId(Object numberId) { this.numberId = numberId; } public Object getLotteryId() { return lotteryId; } public void setLotteryId(Object lotteryId) { this.lotteryId = lotteryId; } }
923202c652b9d3e0cc854346d4b3ca3d1f1b8d65
2,890
java
Java
ambari-server/src/main/java/org/apache/ambari/server/controller/internal/DefaultProviderModule.java
wbear2/ambari
a1891193984da47015cd5483b5b95e040677d7df
[ "Apache-2.0" ]
5
2018-06-03T05:19:40.000Z
2021-04-16T17:10:49.000Z
ambari-server/src/main/java/org/apache/ambari/server/controller/internal/DefaultProviderModule.java
wbear2/ambari
a1891193984da47015cd5483b5b95e040677d7df
[ "Apache-2.0" ]
null
null
null
ambari-server/src/main/java/org/apache/ambari/server/controller/internal/DefaultProviderModule.java
wbear2/ambari
a1891193984da47015cd5483b5b95e040677d7df
[ "Apache-2.0" ]
6
2019-05-07T13:24:39.000Z
2021-02-15T14:12:37.000Z
37.051282
88
0.719723
996,072
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ambari.server.controller.internal; import java.util.Map; import java.util.Set; import com.google.inject.Inject; import org.apache.ambari.server.controller.AmbariManagementController; import org.apache.ambari.server.controller.AmbariServer; import org.apache.ambari.server.controller.spi.Resource; import org.apache.ambari.server.controller.spi.ResourceProvider; import org.apache.ambari.server.controller.utilities.PropertyHelper; /** * The default provider module implementation. */ public class DefaultProviderModule extends AbstractProviderModule { @Inject private AmbariManagementController managementController; // ----- Constructors ------------------------------------------------------ /** * Create a default provider module. */ public DefaultProviderModule() { if (managementController == null) { managementController = AmbariServer.getController(); } } // ----- utility methods --------------------------------------------------- @Override protected ResourceProvider createResourceProvider(Resource.Type type) { Set<String> propertyIds = PropertyHelper.getPropertyIds(type); Map<Resource.Type,String> keyPropertyIds = PropertyHelper.getKeyPropertyIds(type); switch (type.getInternalType()) { case Workflow: return new WorkflowResourceProvider(propertyIds, keyPropertyIds); case Job: return new JobResourceProvider(propertyIds, keyPropertyIds); case TaskAttempt: return new TaskAttemptResourceProvider(propertyIds, keyPropertyIds); case View: return new ViewResourceProvider(); case ViewVersion: return new ViewVersionResourceProvider(); case ViewInstance: return new ViewInstanceResourceProvider(); case StackServiceComponentDependency: return new StackDependencyResourceProvider(propertyIds, keyPropertyIds); default: return AbstractControllerResourceProvider.getResourceProvider(type, propertyIds, keyPropertyIds, managementController); } } }
92320398690e8aca96eef4cfd0483080b473d059
807
java
Java
src/main/java/net/robinfriedli/botify/function/FunctionInvoker.java
sch3p/botify
89d07fec269a074de17bcd0da4b22927c2ae685a
[ "Apache-2.0" ]
178
2019-07-01T16:36:58.000Z
2021-11-12T17:37:36.000Z
src/main/java/net/robinfriedli/botify/function/FunctionInvoker.java
sch3p/botify
89d07fec269a074de17bcd0da4b22927c2ae685a
[ "Apache-2.0" ]
45
2019-11-27T00:28:22.000Z
2021-11-14T15:02:14.000Z
src/main/java/net/robinfriedli/botify/function/FunctionInvoker.java
sch3p/botify
89d07fec269a074de17bcd0da4b22927c2ae685a
[ "Apache-2.0" ]
64
2019-07-01T16:36:59.000Z
2021-11-09T16:13:15.000Z
23.735294
97
0.643123
996,073
package net.robinfriedli.botify.function; import java.util.function.Consumer; import java.util.function.Function; import net.robinfriedli.exec.Mode; /** * Implementations may manage calling a function in a certain way, e.g. setting up a transaction. * * @param <P> the type of the function parameter */ public interface FunctionInvoker<P> { <V> V invokeFunction(Function<P, V> function); default void invokeConsumer(Consumer<P> consumer) { invokeFunction(p -> { consumer.accept(p); return null; }); } <V> V invokeFunction(Mode mode, Function<P, V> function); default void invokeConsumer(Mode mode, Consumer<P> consumer) { invokeFunction(mode, p -> { consumer.accept(p); return null; }); } }
92320643038e12de8522b56d9c1647028bb65c0a
353
java
Java
chapter_002/src/main/java/ru/job4j/tracker/StubInput.java
VicBaykov89/job4j
769b1941feca3d4b05c0941422ada0b4ebb007dc
[ "Apache-2.0" ]
null
null
null
chapter_002/src/main/java/ru/job4j/tracker/StubInput.java
VicBaykov89/job4j
769b1941feca3d4b05c0941422ada0b4ebb007dc
[ "Apache-2.0" ]
null
null
null
chapter_002/src/main/java/ru/job4j/tracker/StubInput.java
VicBaykov89/job4j
769b1941feca3d4b05c0941422ada0b4ebb007dc
[ "Apache-2.0" ]
null
null
null
17.65
41
0.631728
996,074
package ru.job4j.tracker; /** * Created by vicba on 21.08.2018. */ public class StubInput implements Input { private String[] answers; private int position = 0; public StubInput(String[] answers) { this.answers = answers; } @Override public String ask(String question) { return answers[position++]; } }
92320749edf195430d2ef1a9f7e2b75cd5cd7432
27,396
java
Java
components/esb-tools/plugins/org.wso2.integrationstudio.gmf.esb/src/org/wso2/integrationstudio/gmf/esb/impl/LoadBalanceEndPointImpl.java
chanikag/integration-studio
860542074068146e95960889e281d9dbdeeaeaba
[ "Apache-2.0" ]
23
2020-12-09T09:52:23.000Z
2022-03-23T03:59:39.000Z
components/esb-tools/plugins/org.wso2.integrationstudio.gmf.esb/src/org/wso2/integrationstudio/gmf/esb/impl/LoadBalanceEndPointImpl.java
chanikag/integration-studio
860542074068146e95960889e281d9dbdeeaeaba
[ "Apache-2.0" ]
751
2020-12-16T12:30:50.000Z
2022-03-31T07:53:21.000Z
components/esb-tools/plugins/org.wso2.integrationstudio.gmf.esb/src/org/wso2/integrationstudio/gmf/esb/impl/LoadBalanceEndPointImpl.java
chanikag/integration-studio
860542074068146e95960889e281d9dbdeeaeaba
[ "Apache-2.0" ]
25
2020-12-09T09:52:29.000Z
2022-03-16T06:18:08.000Z
37.071719
197
0.630968
996,075
/** * <copyright> * </copyright> * * $Id$ */ package org.wso2.integrationstudio.gmf.esb.impl; import java.util.Collection; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.util.EObjectContainmentEList; import org.eclipse.emf.ecore.util.InternalEList; import org.wso2.integrationstudio.gmf.esb.EsbPackage; import org.wso2.integrationstudio.gmf.esb.LoadBalanceAlgorithm; import org.wso2.integrationstudio.gmf.esb.LoadBalanceEndPoint; import org.wso2.integrationstudio.gmf.esb.LoadBalanceEndPointInputConnector; import org.wso2.integrationstudio.gmf.esb.LoadBalanceEndPointOutputConnector; import org.wso2.integrationstudio.gmf.esb.LoadBalanceEndPointWestOutputConnector; import org.wso2.integrationstudio.gmf.esb.LoadBalanceSessionType; import org.wso2.integrationstudio.gmf.esb.MediatorFlow; import org.wso2.integrationstudio.gmf.esb.Member; import org.wso2.integrationstudio.gmf.esb.Session; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Load Balance End Point</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link org.wso2.integrationstudio.gmf.esb.impl.LoadBalanceEndPointImpl#isFailover <em>Failover</em>}</li> * <li>{@link org.wso2.integrationstudio.gmf.esb.impl.LoadBalanceEndPointImpl#getPolicy <em>Policy</em>}</li> * <li>{@link org.wso2.integrationstudio.gmf.esb.impl.LoadBalanceEndPointImpl#getInputConnector <em>Input Connector</em>}</li> * <li>{@link org.wso2.integrationstudio.gmf.esb.impl.LoadBalanceEndPointImpl#getOutputConnector <em>Output Connector</em>}</li> * <li>{@link org.wso2.integrationstudio.gmf.esb.impl.LoadBalanceEndPointImpl#getWestOutputConnector <em>West Output Connector</em>}</li> * <li>{@link org.wso2.integrationstudio.gmf.esb.impl.LoadBalanceEndPointImpl#getMember <em>Member</em>}</li> * <li>{@link org.wso2.integrationstudio.gmf.esb.impl.LoadBalanceEndPointImpl#getSessionType <em>Session Type</em>}</li> * <li>{@link org.wso2.integrationstudio.gmf.esb.impl.LoadBalanceEndPointImpl#getAlgorithm <em>Algorithm</em>}</li> * <li>{@link org.wso2.integrationstudio.gmf.esb.impl.LoadBalanceEndPointImpl#getSessionTimeout <em>Session Timeout</em>}</li> * <li>{@link org.wso2.integrationstudio.gmf.esb.impl.LoadBalanceEndPointImpl#getMediatorFlow <em>Mediator Flow</em>}</li> * <li>{@link org.wso2.integrationstudio.gmf.esb.impl.LoadBalanceEndPointImpl#isBuildMessage <em>Build Message</em>}</li> * </ul> * * @generated */ public class LoadBalanceEndPointImpl extends ParentEndPointImpl implements LoadBalanceEndPoint { /** * The default value of the '{@link #isFailover() <em>Failover</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isFailover() * @generated * @ordered */ protected static final boolean FAILOVER_EDEFAULT = false; /** * The cached value of the '{@link #isFailover() <em>Failover</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isFailover() * @generated * @ordered */ protected boolean failover = FAILOVER_EDEFAULT; /** * The default value of the '{@link #getPolicy() <em>Policy</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getPolicy() * @generated * @ordered */ protected static final String POLICY_EDEFAULT = null; /** * The cached value of the '{@link #getPolicy() <em>Policy</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getPolicy() * @generated * @ordered */ protected String policy = POLICY_EDEFAULT; /** * The cached value of the '{@link #getInputConnector() <em>Input Connector</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getInputConnector() * @generated * @ordered */ protected LoadBalanceEndPointInputConnector inputConnector; /** * The cached value of the '{@link #getOutputConnector() <em>Output Connector</em>}' containment reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getOutputConnector() * @generated * @ordered */ protected EList<LoadBalanceEndPointOutputConnector> outputConnector; /** * The cached value of the '{@link #getWestOutputConnector() <em>West Output Connector</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getWestOutputConnector() * @generated * @ordered */ protected LoadBalanceEndPointWestOutputConnector westOutputConnector; /** * The cached value of the '{@link #getMember() <em>Member</em>}' containment reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getMember() * @generated * @ordered */ protected EList<Member> member; /** * The default value of the '{@link #getSessionType() <em>Session Type</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getSessionType() * @generated * @ordered */ protected static final LoadBalanceSessionType SESSION_TYPE_EDEFAULT = LoadBalanceSessionType.NONE; /** * The cached value of the '{@link #getSessionType() <em>Session Type</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getSessionType() * @generated * @ordered */ protected LoadBalanceSessionType sessionType = SESSION_TYPE_EDEFAULT; /** * The default value of the '{@link #getAlgorithm() <em>Algorithm</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getAlgorithm() * @generated * @ordered */ protected static final String ALGORITHM_EDEFAULT = "org.apache.synapse.endpoints.algorithms.RoundRobin"; /** * The cached value of the '{@link #getAlgorithm() <em>Algorithm</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getAlgorithm() * @generated * @ordered */ protected String algorithm = ALGORITHM_EDEFAULT; /** * The default value of the '{@link #getSessionTimeout() <em>Session Timeout</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getSessionTimeout() * @generated * @ordered */ protected static final long SESSION_TIMEOUT_EDEFAULT = 0L; /** * The cached value of the '{@link #getSessionTimeout() <em>Session Timeout</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getSessionTimeout() * @generated * @ordered */ protected long sessionTimeout = SESSION_TIMEOUT_EDEFAULT; /** * The cached value of the '{@link #getMediatorFlow() <em>Mediator Flow</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getMediatorFlow() * @generated * @ordered */ protected MediatorFlow mediatorFlow; /** * The default value of the '{@link #isBuildMessage() <em>Build Message</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isBuildMessage() * @generated * @ordered */ protected static final boolean BUILD_MESSAGE_EDEFAULT = false; /** * The cached value of the '{@link #isBuildMessage() <em>Build Message</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isBuildMessage() * @generated * @ordered */ protected boolean buildMessage = BUILD_MESSAGE_EDEFAULT; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected LoadBalanceEndPointImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return EsbPackage.Literals.LOAD_BALANCE_END_POINT; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public boolean isFailover() { return failover; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setFailover(boolean newFailover) { boolean oldFailover = failover; failover = newFailover; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, EsbPackage.LOAD_BALANCE_END_POINT__FAILOVER, oldFailover, failover)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getPolicy() { return policy; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setPolicy(String newPolicy) { String oldPolicy = policy; policy = newPolicy; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, EsbPackage.LOAD_BALANCE_END_POINT__POLICY, oldPolicy, policy)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public LoadBalanceEndPointInputConnector getInputConnector() { return inputConnector; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetInputConnector(LoadBalanceEndPointInputConnector newInputConnector, NotificationChain msgs) { LoadBalanceEndPointInputConnector oldInputConnector = inputConnector; inputConnector = newInputConnector; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, EsbPackage.LOAD_BALANCE_END_POINT__INPUT_CONNECTOR, oldInputConnector, newInputConnector); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setInputConnector(LoadBalanceEndPointInputConnector newInputConnector) { if (newInputConnector != inputConnector) { NotificationChain msgs = null; if (inputConnector != null) msgs = ((InternalEObject)inputConnector).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - EsbPackage.LOAD_BALANCE_END_POINT__INPUT_CONNECTOR, null, msgs); if (newInputConnector != null) msgs = ((InternalEObject)newInputConnector).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - EsbPackage.LOAD_BALANCE_END_POINT__INPUT_CONNECTOR, null, msgs); msgs = basicSetInputConnector(newInputConnector, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, EsbPackage.LOAD_BALANCE_END_POINT__INPUT_CONNECTOR, newInputConnector, newInputConnector)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<LoadBalanceEndPointOutputConnector> getOutputConnector() { if (outputConnector == null) { outputConnector = new EObjectContainmentEList<LoadBalanceEndPointOutputConnector>(LoadBalanceEndPointOutputConnector.class, this, EsbPackage.LOAD_BALANCE_END_POINT__OUTPUT_CONNECTOR); } return outputConnector; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public LoadBalanceEndPointWestOutputConnector getWestOutputConnector() { return westOutputConnector; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetWestOutputConnector(LoadBalanceEndPointWestOutputConnector newWestOutputConnector, NotificationChain msgs) { LoadBalanceEndPointWestOutputConnector oldWestOutputConnector = westOutputConnector; westOutputConnector = newWestOutputConnector; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, EsbPackage.LOAD_BALANCE_END_POINT__WEST_OUTPUT_CONNECTOR, oldWestOutputConnector, newWestOutputConnector); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setWestOutputConnector(LoadBalanceEndPointWestOutputConnector newWestOutputConnector) { if (newWestOutputConnector != westOutputConnector) { NotificationChain msgs = null; if (westOutputConnector != null) msgs = ((InternalEObject)westOutputConnector).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - EsbPackage.LOAD_BALANCE_END_POINT__WEST_OUTPUT_CONNECTOR, null, msgs); if (newWestOutputConnector != null) msgs = ((InternalEObject)newWestOutputConnector).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - EsbPackage.LOAD_BALANCE_END_POINT__WEST_OUTPUT_CONNECTOR, null, msgs); msgs = basicSetWestOutputConnector(newWestOutputConnector, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, EsbPackage.LOAD_BALANCE_END_POINT__WEST_OUTPUT_CONNECTOR, newWestOutputConnector, newWestOutputConnector)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<Member> getMember() { if (member == null) { member = new EObjectContainmentEList<Member>(Member.class, this, EsbPackage.LOAD_BALANCE_END_POINT__MEMBER); } return member; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public LoadBalanceSessionType getSessionType() { return sessionType; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setSessionType(LoadBalanceSessionType newSessionType) { LoadBalanceSessionType oldSessionType = sessionType; sessionType = newSessionType == null ? SESSION_TYPE_EDEFAULT : newSessionType; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, EsbPackage.LOAD_BALANCE_END_POINT__SESSION_TYPE, oldSessionType, sessionType)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getAlgorithm() { return algorithm; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setAlgorithm(String newAlgorithm) { String oldAlgorithm = algorithm; algorithm = newAlgorithm; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, EsbPackage.LOAD_BALANCE_END_POINT__ALGORITHM, oldAlgorithm, algorithm)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public long getSessionTimeout() { return sessionTimeout; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setSessionTimeout(long newSessionTimeout) { long oldSessionTimeout = sessionTimeout; sessionTimeout = newSessionTimeout; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, EsbPackage.LOAD_BALANCE_END_POINT__SESSION_TIMEOUT, oldSessionTimeout, sessionTimeout)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public MediatorFlow getMediatorFlow() { return mediatorFlow; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetMediatorFlow(MediatorFlow newMediatorFlow, NotificationChain msgs) { MediatorFlow oldMediatorFlow = mediatorFlow; mediatorFlow = newMediatorFlow; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, EsbPackage.LOAD_BALANCE_END_POINT__MEDIATOR_FLOW, oldMediatorFlow, newMediatorFlow); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setMediatorFlow(MediatorFlow newMediatorFlow) { if (newMediatorFlow != mediatorFlow) { NotificationChain msgs = null; if (mediatorFlow != null) msgs = ((InternalEObject)mediatorFlow).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - EsbPackage.LOAD_BALANCE_END_POINT__MEDIATOR_FLOW, null, msgs); if (newMediatorFlow != null) msgs = ((InternalEObject)newMediatorFlow).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - EsbPackage.LOAD_BALANCE_END_POINT__MEDIATOR_FLOW, null, msgs); msgs = basicSetMediatorFlow(newMediatorFlow, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, EsbPackage.LOAD_BALANCE_END_POINT__MEDIATOR_FLOW, newMediatorFlow, newMediatorFlow)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public boolean isBuildMessage() { return buildMessage; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setBuildMessage(boolean newBuildMessage) { boolean oldBuildMessage = buildMessage; buildMessage = newBuildMessage; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, EsbPackage.LOAD_BALANCE_END_POINT__BUILD_MESSAGE, oldBuildMessage, buildMessage)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case EsbPackage.LOAD_BALANCE_END_POINT__INPUT_CONNECTOR: return basicSetInputConnector(null, msgs); case EsbPackage.LOAD_BALANCE_END_POINT__OUTPUT_CONNECTOR: return ((InternalEList<?>)getOutputConnector()).basicRemove(otherEnd, msgs); case EsbPackage.LOAD_BALANCE_END_POINT__WEST_OUTPUT_CONNECTOR: return basicSetWestOutputConnector(null, msgs); case EsbPackage.LOAD_BALANCE_END_POINT__MEMBER: return ((InternalEList<?>)getMember()).basicRemove(otherEnd, msgs); case EsbPackage.LOAD_BALANCE_END_POINT__MEDIATOR_FLOW: return basicSetMediatorFlow(null, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case EsbPackage.LOAD_BALANCE_END_POINT__FAILOVER: return isFailover(); case EsbPackage.LOAD_BALANCE_END_POINT__POLICY: return getPolicy(); case EsbPackage.LOAD_BALANCE_END_POINT__INPUT_CONNECTOR: return getInputConnector(); case EsbPackage.LOAD_BALANCE_END_POINT__OUTPUT_CONNECTOR: return getOutputConnector(); case EsbPackage.LOAD_BALANCE_END_POINT__WEST_OUTPUT_CONNECTOR: return getWestOutputConnector(); case EsbPackage.LOAD_BALANCE_END_POINT__MEMBER: return getMember(); case EsbPackage.LOAD_BALANCE_END_POINT__SESSION_TYPE: return getSessionType(); case EsbPackage.LOAD_BALANCE_END_POINT__ALGORITHM: return getAlgorithm(); case EsbPackage.LOAD_BALANCE_END_POINT__SESSION_TIMEOUT: return getSessionTimeout(); case EsbPackage.LOAD_BALANCE_END_POINT__MEDIATOR_FLOW: return getMediatorFlow(); case EsbPackage.LOAD_BALANCE_END_POINT__BUILD_MESSAGE: return isBuildMessage(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case EsbPackage.LOAD_BALANCE_END_POINT__FAILOVER: setFailover((Boolean)newValue); return; case EsbPackage.LOAD_BALANCE_END_POINT__POLICY: setPolicy((String)newValue); return; case EsbPackage.LOAD_BALANCE_END_POINT__INPUT_CONNECTOR: setInputConnector((LoadBalanceEndPointInputConnector)newValue); return; case EsbPackage.LOAD_BALANCE_END_POINT__OUTPUT_CONNECTOR: getOutputConnector().clear(); getOutputConnector().addAll((Collection<? extends LoadBalanceEndPointOutputConnector>)newValue); return; case EsbPackage.LOAD_BALANCE_END_POINT__WEST_OUTPUT_CONNECTOR: setWestOutputConnector((LoadBalanceEndPointWestOutputConnector)newValue); return; case EsbPackage.LOAD_BALANCE_END_POINT__MEMBER: getMember().clear(); getMember().addAll((Collection<? extends Member>)newValue); return; case EsbPackage.LOAD_BALANCE_END_POINT__SESSION_TYPE: setSessionType((LoadBalanceSessionType)newValue); return; case EsbPackage.LOAD_BALANCE_END_POINT__ALGORITHM: setAlgorithm((String)newValue); return; case EsbPackage.LOAD_BALANCE_END_POINT__SESSION_TIMEOUT: setSessionTimeout((Long)newValue); return; case EsbPackage.LOAD_BALANCE_END_POINT__MEDIATOR_FLOW: setMediatorFlow((MediatorFlow)newValue); return; case EsbPackage.LOAD_BALANCE_END_POINT__BUILD_MESSAGE: setBuildMessage((Boolean)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case EsbPackage.LOAD_BALANCE_END_POINT__FAILOVER: setFailover(FAILOVER_EDEFAULT); return; case EsbPackage.LOAD_BALANCE_END_POINT__POLICY: setPolicy(POLICY_EDEFAULT); return; case EsbPackage.LOAD_BALANCE_END_POINT__INPUT_CONNECTOR: setInputConnector((LoadBalanceEndPointInputConnector)null); return; case EsbPackage.LOAD_BALANCE_END_POINT__OUTPUT_CONNECTOR: getOutputConnector().clear(); return; case EsbPackage.LOAD_BALANCE_END_POINT__WEST_OUTPUT_CONNECTOR: setWestOutputConnector((LoadBalanceEndPointWestOutputConnector)null); return; case EsbPackage.LOAD_BALANCE_END_POINT__MEMBER: getMember().clear(); return; case EsbPackage.LOAD_BALANCE_END_POINT__SESSION_TYPE: setSessionType(SESSION_TYPE_EDEFAULT); return; case EsbPackage.LOAD_BALANCE_END_POINT__ALGORITHM: setAlgorithm(ALGORITHM_EDEFAULT); return; case EsbPackage.LOAD_BALANCE_END_POINT__SESSION_TIMEOUT: setSessionTimeout(SESSION_TIMEOUT_EDEFAULT); return; case EsbPackage.LOAD_BALANCE_END_POINT__MEDIATOR_FLOW: setMediatorFlow((MediatorFlow)null); return; case EsbPackage.LOAD_BALANCE_END_POINT__BUILD_MESSAGE: setBuildMessage(BUILD_MESSAGE_EDEFAULT); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case EsbPackage.LOAD_BALANCE_END_POINT__FAILOVER: return failover != FAILOVER_EDEFAULT; case EsbPackage.LOAD_BALANCE_END_POINT__POLICY: return POLICY_EDEFAULT == null ? policy != null : !POLICY_EDEFAULT.equals(policy); case EsbPackage.LOAD_BALANCE_END_POINT__INPUT_CONNECTOR: return inputConnector != null; case EsbPackage.LOAD_BALANCE_END_POINT__OUTPUT_CONNECTOR: return outputConnector != null && !outputConnector.isEmpty(); case EsbPackage.LOAD_BALANCE_END_POINT__WEST_OUTPUT_CONNECTOR: return westOutputConnector != null; case EsbPackage.LOAD_BALANCE_END_POINT__MEMBER: return member != null && !member.isEmpty(); case EsbPackage.LOAD_BALANCE_END_POINT__SESSION_TYPE: return sessionType != SESSION_TYPE_EDEFAULT; case EsbPackage.LOAD_BALANCE_END_POINT__ALGORITHM: return ALGORITHM_EDEFAULT == null ? algorithm != null : !ALGORITHM_EDEFAULT.equals(algorithm); case EsbPackage.LOAD_BALANCE_END_POINT__SESSION_TIMEOUT: return sessionTimeout != SESSION_TIMEOUT_EDEFAULT; case EsbPackage.LOAD_BALANCE_END_POINT__MEDIATOR_FLOW: return mediatorFlow != null; case EsbPackage.LOAD_BALANCE_END_POINT__BUILD_MESSAGE: return buildMessage != BUILD_MESSAGE_EDEFAULT; } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuilder result = new StringBuilder(super.toString()); result.append(" (failover: "); result.append(failover); result.append(", policy: "); result.append(policy); result.append(", sessionType: "); result.append(sessionType); result.append(", algorithm: "); result.append(algorithm); result.append(", sessionTimeout: "); result.append(sessionTimeout); result.append(", buildMessage: "); result.append(buildMessage); result.append(')'); return result.toString(); } } // LoadBalanceEndPointImpl
923208cc0d4d5d23aa452af163a688949fab9476
24,286
java
Java
apps/Contacts/src/com/android/contacts/list/ContactBrowseListFragment.java
Keneral/apackages
af6a7ffde2e52d8d4e073b4030244551246248ad
[ "Unlicense" ]
8
2018-08-15T09:07:29.000Z
2021-04-15T08:16:52.000Z
apps/Contacts/src/com/android/contacts/list/ContactBrowseListFragment.java
Keneral/apackages
af6a7ffde2e52d8d4e073b4030244551246248ad
[ "Unlicense" ]
null
null
null
apps/Contacts/src/com/android/contacts/list/ContactBrowseListFragment.java
Keneral/apackages
af6a7ffde2e52d8d4e073b4030244551246248ad
[ "Unlicense" ]
4
2019-04-28T06:40:24.000Z
2020-08-05T02:45:09.000Z
36.032641
100
0.623404
996,076
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.contacts.list; import android.app.Activity; import android.content.ContentResolver; import android.content.ContentUris; import android.content.Loader; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.database.Cursor; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.preference.PreferenceManager; import android.provider.ContactsContract; import android.provider.ContactsContract.Contacts; import android.provider.ContactsContract.Directory; import android.text.TextUtils; import android.util.Log; import com.android.common.widget.CompositeCursorAdapter.Partition; import com.android.contacts.common.list.AutoScrollListView; import com.android.contacts.common.list.ContactEntryListFragment; import com.android.contacts.common.list.ContactListAdapter; import com.android.contacts.common.list.ContactListFilter; import com.android.contacts.common.list.DirectoryPartition; import com.android.contacts.common.util.ContactLoaderUtils; import java.util.List; /** * Fragment containing a contact list used for browsing (as compared to * picking a contact with one of the PICK intents). */ public abstract class ContactBrowseListFragment extends ContactEntryListFragment<ContactListAdapter> { private static final String TAG = "ContactList"; private static final String KEY_SELECTED_URI = "selectedUri"; private static final String KEY_SELECTION_VERIFIED = "selectionVerified"; private static final String KEY_FILTER = "filter"; private static final String KEY_LAST_SELECTED_POSITION = "lastSelected"; private static final String PERSISTENT_SELECTION_PREFIX = "defaultContactBrowserSelection"; /** * The id for a delayed message that triggers automatic selection of the first * found contact in search mode. */ private static final int MESSAGE_AUTOSELECT_FIRST_FOUND_CONTACT = 1; /** * The delay that is used for automatically selecting the first found contact. */ private static final int DELAY_AUTOSELECT_FIRST_FOUND_CONTACT_MILLIS = 500; /** * The minimum number of characters in the search query that is required * before we automatically select the first found contact. */ private static final int AUTOSELECT_FIRST_FOUND_CONTACT_MIN_QUERY_LENGTH = 2; private SharedPreferences mPrefs; private Handler mHandler; private boolean mStartedLoading; private boolean mSelectionRequired; private boolean mSelectionToScreenRequested; private boolean mSmoothScrollRequested; private boolean mSelectionPersistenceRequested; private Uri mSelectedContactUri; private long mSelectedContactDirectoryId; private String mSelectedContactLookupKey; private long mSelectedContactId; private boolean mSelectionVerified; private int mLastSelectedPosition = -1; private boolean mRefreshingContactUri; private ContactListFilter mFilter; private String mPersistentSelectionPrefix = PERSISTENT_SELECTION_PREFIX; protected OnContactBrowserActionListener mListener; private ContactLookupTask mContactLookupTask; private final class ContactLookupTask extends AsyncTask<Void, Void, Uri> { private final Uri mUri; private boolean mIsCancelled; public ContactLookupTask(Uri uri) { mUri = uri; } @Override protected Uri doInBackground(Void... args) { Cursor cursor = null; try { final ContentResolver resolver = getContext().getContentResolver(); final Uri uriCurrentFormat = ContactLoaderUtils.ensureIsContactUri(resolver, mUri); cursor = resolver.query(uriCurrentFormat, new String[] { Contacts._ID, Contacts.LOOKUP_KEY }, null, null, null); if (cursor != null && cursor.moveToFirst()) { final long contactId = cursor.getLong(0); final String lookupKey = cursor.getString(1); if (contactId != 0 && !TextUtils.isEmpty(lookupKey)) { return Contacts.getLookupUri(contactId, lookupKey); } } Log.e(TAG, "Error: No contact ID or lookup key for contact " + mUri); return null; } catch (Exception e) { Log.e(TAG, "Error loading the contact: " + mUri, e); return null; } finally { if (cursor != null) { cursor.close(); } } } public void cancel() { super.cancel(true); // Use a flag to keep track of whether the {@link AsyncTask} was cancelled or not in // order to ensure onPostExecute() is not executed after the cancel request. The flag is // necessary because {@link AsyncTask} still calls onPostExecute() if the cancel request // came after the worker thread was finished. mIsCancelled = true; } @Override protected void onPostExecute(Uri uri) { // Make sure the {@link Fragment} is at least still attached to the {@link Activity} // before continuing. Null URIs should still be allowed so that the list can be // refreshed and a default contact can be selected (i.e. the case of deleted // contacts). if (mIsCancelled || !isAdded()) { return; } onContactUriQueryFinished(uri); } } private boolean mDelaySelection; private Handler getHandler() { if (mHandler == null) { mHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case MESSAGE_AUTOSELECT_FIRST_FOUND_CONTACT: selectDefaultContact(); break; } } }; } return mHandler; } @Override public void onAttach(Activity activity) { super.onAttach(activity); mPrefs = PreferenceManager.getDefaultSharedPreferences(activity); restoreFilter(); restoreSelectedUri(false); } @Override protected void setSearchMode(boolean flag) { if (isSearchMode() != flag) { if (!flag) { restoreSelectedUri(true); } super.setSearchMode(flag); } } public void setFilter(ContactListFilter filter) { setFilter(filter, true); } public void setFilter(ContactListFilter filter, boolean restoreSelectedUri) { if (mFilter == null && filter == null) { return; } if (mFilter != null && mFilter.equals(filter)) { return; } Log.v(TAG, "New filter: " + filter); mFilter = filter; mLastSelectedPosition = -1; saveFilter(); if (restoreSelectedUri) { mSelectedContactUri = null; restoreSelectedUri(true); } reloadData(); } public ContactListFilter getFilter() { return mFilter; } @Override public void restoreSavedState(Bundle savedState) { super.restoreSavedState(savedState); if (savedState == null) { return; } mFilter = savedState.getParcelable(KEY_FILTER); mSelectedContactUri = savedState.getParcelable(KEY_SELECTED_URI); mSelectionVerified = savedState.getBoolean(KEY_SELECTION_VERIFIED); mLastSelectedPosition = savedState.getInt(KEY_LAST_SELECTED_POSITION); parseSelectedContactUri(); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putParcelable(KEY_FILTER, mFilter); outState.putParcelable(KEY_SELECTED_URI, mSelectedContactUri); outState.putBoolean(KEY_SELECTION_VERIFIED, mSelectionVerified); outState.putInt(KEY_LAST_SELECTED_POSITION, mLastSelectedPosition); } protected void refreshSelectedContactUri() { if (mContactLookupTask != null) { mContactLookupTask.cancel(); } if (!isSelectionVisible()) { return; } mRefreshingContactUri = true; if (mSelectedContactUri == null) { onContactUriQueryFinished(null); return; } if (mSelectedContactDirectoryId != Directory.DEFAULT && mSelectedContactDirectoryId != Directory.LOCAL_INVISIBLE) { onContactUriQueryFinished(mSelectedContactUri); } else { mContactLookupTask = new ContactLookupTask(mSelectedContactUri); mContactLookupTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[])null); } } protected void onContactUriQueryFinished(Uri uri) { mRefreshingContactUri = false; mSelectedContactUri = uri; parseSelectedContactUri(); checkSelection(); } public Uri getSelectedContactUri() { return mSelectedContactUri; } /** * Sets the new selection for the list. */ public void setSelectedContactUri(Uri uri) { setSelectedContactUri(uri, true, false /* no smooth scroll */, true, false); } @Override public void setQueryString(String queryString, boolean delaySelection) { mDelaySelection = delaySelection; super.setQueryString(queryString, delaySelection); } /** * Sets whether or not a contact selection must be made. * @param required if true, we need to check if the selection is present in * the list and if not notify the listener so that it can load a * different list. * TODO: Figure out how to reconcile this with {@link #setSelectedContactUri}, * without causing unnecessary loading of the list if the selected contact URI is * the same as before. */ public void setSelectionRequired(boolean required) { mSelectionRequired = required; } /** * Sets the new contact selection. * * @param uri the new selection * @param required if true, we need to check if the selection is present in * the list and if not notify the listener so that it can load a * different list * @param smoothScroll if true, the UI will roll smoothly to the new * selection * @param persistent if true, the selection will be stored in shared * preferences. * @param willReloadData if true, the selection will be remembered but not * actually shown, because we are expecting that the data will be * reloaded momentarily */ private void setSelectedContactUri(Uri uri, boolean required, boolean smoothScroll, boolean persistent, boolean willReloadData) { mSmoothScrollRequested = smoothScroll; mSelectionToScreenRequested = true; if ((mSelectedContactUri == null && uri != null) || (mSelectedContactUri != null && !mSelectedContactUri.equals(uri))) { mSelectionVerified = false; mSelectionRequired = required; mSelectionPersistenceRequested = persistent; mSelectedContactUri = uri; parseSelectedContactUri(); if (!willReloadData) { // Configure the adapter to show the selection based on the // lookup key extracted from the URI ContactListAdapter adapter = getAdapter(); if (adapter != null) { adapter.setSelectedContact(mSelectedContactDirectoryId, mSelectedContactLookupKey, mSelectedContactId); getListView().invalidateViews(); } } // Also, launch a loader to pick up a new lookup URI in case it has changed refreshSelectedContactUri(); } } private void parseSelectedContactUri() { if (mSelectedContactUri != null) { String directoryParam = mSelectedContactUri.getQueryParameter(ContactsContract.DIRECTORY_PARAM_KEY); mSelectedContactDirectoryId = TextUtils.isEmpty(directoryParam) ? Directory.DEFAULT : Long.parseLong(directoryParam); if (mSelectedContactUri.toString().startsWith(Contacts.CONTENT_LOOKUP_URI.toString())) { List<String> pathSegments = mSelectedContactUri.getPathSegments(); mSelectedContactLookupKey = Uri.encode(pathSegments.get(2)); if (pathSegments.size() == 4) { mSelectedContactId = ContentUris.parseId(mSelectedContactUri); } } else if (mSelectedContactUri.toString().startsWith(Contacts.CONTENT_URI.toString()) && mSelectedContactUri.getPathSegments().size() >= 2) { mSelectedContactLookupKey = null; mSelectedContactId = ContentUris.parseId(mSelectedContactUri); } else { Log.e(TAG, "Unsupported contact URI: " + mSelectedContactUri); mSelectedContactLookupKey = null; mSelectedContactId = 0; } } else { mSelectedContactDirectoryId = Directory.DEFAULT; mSelectedContactLookupKey = null; mSelectedContactId = 0; } } @Override protected void configureAdapter() { super.configureAdapter(); ContactListAdapter adapter = getAdapter(); if (adapter == null) { return; } boolean searchMode = isSearchMode(); if (!searchMode && mFilter != null) { adapter.setFilter(mFilter); if (mSelectionRequired || mFilter.filterType == ContactListFilter.FILTER_TYPE_SINGLE_CONTACT) { adapter.setSelectedContact( mSelectedContactDirectoryId, mSelectedContactLookupKey, mSelectedContactId); } } // Display the user's profile if not in search mode adapter.setIncludeProfile(!searchMode); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { super.onLoadFinished(loader, data); mSelectionVerified = false; // Refresh the currently selected lookup in case it changed while we were sleeping refreshSelectedContactUri(); } @Override public void onLoaderReset(Loader<Cursor> loader) { } private void checkSelection() { if (mSelectionVerified) { return; } if (mRefreshingContactUri) { return; } if (isLoadingDirectoryList()) { return; } ContactListAdapter adapter = getAdapter(); if (adapter == null) { return; } boolean directoryLoading = true; int count = adapter.getPartitionCount(); for (int i = 0; i < count; i++) { Partition partition = adapter.getPartition(i); if (partition instanceof DirectoryPartition) { DirectoryPartition directory = (DirectoryPartition) partition; if (directory.getDirectoryId() == mSelectedContactDirectoryId) { directoryLoading = directory.isLoading(); break; } } } if (directoryLoading) { return; } adapter.setSelectedContact( mSelectedContactDirectoryId, mSelectedContactLookupKey, mSelectedContactId); final int selectedPosition = adapter.getSelectedContactPosition(); if (selectedPosition != -1) { mLastSelectedPosition = selectedPosition; } else { if (isSearchMode()) { if (mDelaySelection) { selectFirstFoundContactAfterDelay(); if (mListener != null) { mListener.onSelectionChange(); } return; } } else if (mSelectionRequired) { // A specific contact was requested, but it's not in the loaded list. // Try reconfiguring and reloading the list that will hopefully contain // the requested contact. Only take one attempt to avoid an infinite loop // in case the contact cannot be found at all. mSelectionRequired = false; // If we were looking at a different specific contact, just reload // FILTER_TYPE_ALL_ACCOUNTS is needed for the case where a new contact is added // on a tablet and the loader is returning a stale list. In this case, the contact // will not be found until the next load. b/7621855 This will only fix the most // common case where all accounts are shown. It will not fix the one account case. // TODO: we may want to add more FILTER_TYPEs or relax this check to fix all other // FILTER_TYPE cases. if (mFilter != null && (mFilter.filterType == ContactListFilter.FILTER_TYPE_SINGLE_CONTACT || mFilter.filterType == ContactListFilter.FILTER_TYPE_ALL_ACCOUNTS)) { reloadData(); } else { // Otherwise, call the listener, which will adjust the filter. notifyInvalidSelection(); } return; } else if (mFilter != null && mFilter.filterType == ContactListFilter.FILTER_TYPE_SINGLE_CONTACT) { // If we were trying to load a specific contact, but that contact no longer // exists, call the listener, which will adjust the filter. notifyInvalidSelection(); return; } saveSelectedUri(null); selectDefaultContact(); } mSelectionRequired = false; mSelectionVerified = true; if (mSelectionPersistenceRequested) { saveSelectedUri(mSelectedContactUri); mSelectionPersistenceRequested = false; } if (mSelectionToScreenRequested) { requestSelectionToScreen(selectedPosition); } getListView().invalidateViews(); if (mListener != null) { mListener.onSelectionChange(); } } /** * Automatically selects the first found contact in search mode. The selection * is updated after a delay to allow the user to type without to much UI churn * and to save bandwidth on directory queries. */ public void selectFirstFoundContactAfterDelay() { Handler handler = getHandler(); handler.removeMessages(MESSAGE_AUTOSELECT_FIRST_FOUND_CONTACT); String queryString = getQueryString(); if (queryString != null && queryString.length() >= AUTOSELECT_FIRST_FOUND_CONTACT_MIN_QUERY_LENGTH) { handler.sendEmptyMessageDelayed(MESSAGE_AUTOSELECT_FIRST_FOUND_CONTACT, DELAY_AUTOSELECT_FIRST_FOUND_CONTACT_MILLIS); } else { setSelectedContactUri(null, false, false, false, false); } } protected void selectDefaultContact() { Uri contactUri = null; ContactListAdapter adapter = getAdapter(); if (mLastSelectedPosition != -1) { int count = adapter.getCount(); int pos = mLastSelectedPosition; if (pos >= count && count > 0) { pos = count - 1; } contactUri = adapter.getContactUri(pos); } if (contactUri == null) { contactUri = adapter.getFirstContactUri(); } setSelectedContactUri(contactUri, false, mSmoothScrollRequested, false, false); } protected void requestSelectionToScreen(int selectedPosition) { if (selectedPosition != -1) { AutoScrollListView listView = (AutoScrollListView)getListView(); listView.requestPositionToScreen( selectedPosition + listView.getHeaderViewsCount(), mSmoothScrollRequested); mSelectionToScreenRequested = false; } } @Override public boolean isLoading() { return mRefreshingContactUri || super.isLoading(); } @Override protected void startLoading() { mStartedLoading = true; mSelectionVerified = false; super.startLoading(); } public void reloadDataAndSetSelectedUri(Uri uri) { setSelectedContactUri(uri, true, true, true, true); reloadData(); } @Override public void reloadData() { if (mStartedLoading) { mSelectionVerified = false; mLastSelectedPosition = -1; super.reloadData(); } } public void setOnContactListActionListener(OnContactBrowserActionListener listener) { mListener = listener; } public void viewContact(Uri contactUri, boolean isEnterpriseContact) { setSelectedContactUri(contactUri, false, false, true, false); if (mListener != null) mListener.onViewContactAction(contactUri, isEnterpriseContact); } public void deleteContact(Uri contactUri) { if (mListener != null) mListener.onDeleteContactAction(contactUri); } private void notifyInvalidSelection() { if (mListener != null) mListener.onInvalidSelection(); } @Override protected void finish() { super.finish(); if (mListener != null) mListener.onFinishAction(); } private void saveSelectedUri(Uri contactUri) { if (isSearchMode()) { return; } ContactListFilter.storeToPreferences(mPrefs, mFilter); Editor editor = mPrefs.edit(); if (contactUri == null) { editor.remove(getPersistentSelectionKey()); } else { editor.putString(getPersistentSelectionKey(), contactUri.toString()); } editor.apply(); } private void restoreSelectedUri(boolean willReloadData) { // The meaning of mSelectionRequired is that we need to show some // selection other than the previous selection saved in shared preferences if (mSelectionRequired) { return; } String selectedUri = mPrefs.getString(getPersistentSelectionKey(), null); if (selectedUri == null) { setSelectedContactUri(null, false, false, false, willReloadData); } else { setSelectedContactUri(Uri.parse(selectedUri), false, false, false, willReloadData); } } private void saveFilter() { ContactListFilter.storeToPreferences(mPrefs, mFilter); } private void restoreFilter() { mFilter = ContactListFilter.restoreDefaultPreferences(mPrefs); } private String getPersistentSelectionKey() { if (mFilter == null) { return mPersistentSelectionPrefix; } else { return mPersistentSelectionPrefix + "-" + mFilter.getId(); } } public boolean isOptionsMenuChanged() { // This fragment does not have an option menu of its own return false; } }
92320a0f94da620d60225c12d08a1a2e90f6d814
2,845
java
Java
src/main/java/com/jozufozu/flywheel/core/WorldContext.java
TheEpicBlock/Flywheel
4c0df23702a6720d11c911542df70e4d5bf794cd
[ "MIT" ]
77
2021-06-23T08:50:07.000Z
2022-03-22T09:44:07.000Z
src/main/java/com/jozufozu/flywheel/core/WorldContext.java
TheEpicBlock/Flywheel
4c0df23702a6720d11c911542df70e4d5bf794cd
[ "MIT" ]
116
2021-07-02T17:51:43.000Z
2022-03-26T23:49:03.000Z
src/main/java/com/jozufozu/flywheel/core/WorldContext.java
TheEpicBlock/Flywheel
4c0df23702a6720d11c911542df70e4d5bf794cd
[ "MIT" ]
24
2021-06-23T17:36:30.000Z
2022-03-18T14:53:18.000Z
28.45
137
0.744815
996,077
package com.jozufozu.flywheel.core; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.function.Supplier; import java.util.stream.Stream; import com.jozufozu.flywheel.api.struct.Instanced; import com.jozufozu.flywheel.backend.Backend; import com.jozufozu.flywheel.backend.ShaderContext; import com.jozufozu.flywheel.backend.pipeline.ShaderPipeline; import com.jozufozu.flywheel.core.shader.ContextAwareProgram; import com.jozufozu.flywheel.core.shader.WorldProgram; import com.jozufozu.flywheel.core.shader.spec.ProgramSpec; import net.minecraft.resources.ResourceLocation; public class WorldContext<P extends WorldProgram> implements ShaderContext<P> { public final Backend backend; protected final Map<ResourceLocation, ContextAwareProgram<P>> programs = new HashMap<>(); protected final ResourceLocation name; protected final Supplier<Stream<ResourceLocation>> specStream; public final ShaderPipeline<P> pipeline; public WorldContext(Backend backend, ResourceLocation name, Supplier<Stream<ResourceLocation>> specStream, ShaderPipeline<P> pipeline) { this.backend = backend; this.name = name; this.specStream = specStream; this.pipeline = pipeline; } @Override public void load() { Backend.LOGGER.info("Loading context '{}'", name); specStream.get() .map(backend::getSpec) .forEach(this::loadSpec); } private void loadSpec(ProgramSpec spec) { try { programs.put(spec.name, pipeline.compile(spec)); Backend.LOGGER.debug("Loaded program {}", spec.name); } catch (Exception e) { Backend.LOGGER.error("Error loading program {}", spec.name); Backend.LOGGER.error("", e); backend.loader.notifyError(); } } @Override public Supplier<P> getProgramSupplier(ResourceLocation spec) { return programs.get(spec); } @Override public void delete() { programs.values() .forEach(ContextAwareProgram::delete); programs.clear(); } public static Builder builder(Backend backend, ResourceLocation name) { return new Builder(backend, name); } public static class Builder { private final Backend backend; private final ResourceLocation name; private Supplier<Stream<ResourceLocation>> specStream; public Builder(Backend backend, ResourceLocation name) { this.backend = backend; this.name = name; } public Builder setSpecStream(Supplier<Stream<ResourceLocation>> specStream) { this.specStream = specStream; return this; } public <P extends WorldProgram> WorldContext<P> build(ShaderPipeline<P> pipeline) { if (specStream == null) { specStream = () -> backend.allMaterials() .stream() .map(t -> t instanceof Instanced<?> i ? i : null) .filter(Objects::nonNull) .map(Instanced::getProgramSpec); } return new WorldContext<>(backend, name, specStream, pipeline); } } }
92320c03e34a1cabf495501650fed443dcac4883
1,940
java
Java
src/main/java/org/primefaces/component/rowtoggler/RowTogglerBase.java
efrenperez/primefaces
567cf913f6e5e48946f145dafcc798f97681c41b
[ "Apache-2.0" ]
1
2018-08-27T13:42:27.000Z
2018-08-27T13:42:27.000Z
src/main/java/org/primefaces/component/rowtoggler/RowTogglerBase.java
efrenperez/primefaces
567cf913f6e5e48946f145dafcc798f97681c41b
[ "Apache-2.0" ]
null
null
null
src/main/java/org/primefaces/component/rowtoggler/RowTogglerBase.java
efrenperez/primefaces
567cf913f6e5e48946f145dafcc798f97681c41b
[ "Apache-2.0" ]
null
null
null
28.955224
96
0.711856
996,078
/** * Copyright 2009-2018 PrimeTek. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.primefaces.component.rowtoggler; import javax.faces.component.UIComponentBase; abstract class RowTogglerBase extends UIComponentBase { public static final String COMPONENT_FAMILY = "org.primefaces.component"; public static final String DEFAULT_RENDERER = "org.primefaces.component.RowTogglerRenderer"; public enum PropertyKeys { expandLabel, collapseLabel, tabindex; } public RowTogglerBase() { setRendererType(DEFAULT_RENDERER); } @Override public String getFamily() { return COMPONENT_FAMILY; } public String getExpandLabel() { return (String) getStateHelper().eval(PropertyKeys.expandLabel, null); } public void setExpandLabel(String expandLabel) { getStateHelper().put(PropertyKeys.expandLabel, expandLabel); } public String getCollapseLabel() { return (String) getStateHelper().eval(PropertyKeys.collapseLabel, null); } public void setCollapseLabel(String collapseLabel) { getStateHelper().put(PropertyKeys.collapseLabel, collapseLabel); } public String getTabindex() { return (String) getStateHelper().eval(PropertyKeys.tabindex, "0"); } public void setTabindex(String tabindex) { getStateHelper().put(PropertyKeys.tabindex, tabindex); } }
92320c0b387dcea851cfc4f6ca7eb3eb5f93351e
1,245
java
Java
src/main/java/de/dmueller/statistics/tennis/atp/domain/match/ATPMatchPlayer.java
mway-dmueller/ATPWorldTourCrawler
33fca012f4211a2bf3d5e88476e5429f92f34dbf
[ "Apache-2.0" ]
1
2017-05-07T17:55:42.000Z
2017-05-07T17:55:42.000Z
src/main/java/de/dmueller/statistics/tennis/atp/domain/match/ATPMatchPlayer.java
mway-dmueller/ATPWorldTourCrawler
33fca012f4211a2bf3d5e88476e5429f92f34dbf
[ "Apache-2.0" ]
null
null
null
src/main/java/de/dmueller/statistics/tennis/atp/domain/match/ATPMatchPlayer.java
mway-dmueller/ATPWorldTourCrawler
33fca012f4211a2bf3d5e88476e5429f92f34dbf
[ "Apache-2.0" ]
null
null
null
18.308824
55
0.696386
996,079
package de.dmueller.statistics.tennis.atp.domain.match; public class ATPMatchPlayer { private String code; private String link; private String seed; private String nationality; private String name; public String getCode() { return code; } public void setCode(final String code) { this.code = code; } public String getLink() { return link; } public void setLink(final String link) { this.link = link; } public String getSeed() { return seed; } public void setSeed(final String seed) { this.seed = seed; } public String getNationality() { return nationality; } public void setNationality(final String nationality) { this.nationality = nationality; } public String getName() { return name; } public void setName(final String name) { this.name = name; } @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("ATPPlayer [code="); builder.append(code); builder.append(", link="); builder.append(link); builder.append(", seed="); builder.append(seed); builder.append(", nationality="); builder.append(nationality); builder.append(", name="); builder.append(name); builder.append("]"); return builder.toString(); } }
92320d2df18e8477a981b1d1aac40d6ebbe6adb8
698
java
Java
log/src/main/java/com/ggj/java/Sl4jBindLogBack.java
ggj2010/javabase
f7d1d113d82bd50b735b5ba834a288901383d404
[ "Apache-2.0" ]
89
2016-08-12T03:27:24.000Z
2022-01-26T18:06:37.000Z
log/src/main/java/com/ggj/java/Sl4jBindLogBack.java
ggj2010/javabase
f7d1d113d82bd50b735b5ba834a288901383d404
[ "Apache-2.0" ]
6
2016-10-12T08:19:31.000Z
2021-12-14T21:12:48.000Z
log/src/main/java/com/ggj/java/Sl4jBindLogBack.java
ggj2010/javabase
f7d1d113d82bd50b735b5ba834a288901383d404
[ "Apache-2.0" ]
96
2016-06-27T03:44:31.000Z
2022-02-19T02:44:19.000Z
21.151515
84
0.648997
996,080
package com.ggj.java; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; import java.util.UUID; /** * 最基础的logback * * 直接引入 * <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> </dependency> * sl4j绑定logback * @author:gaoguangjin * @date:2018/5/25 */ public class Sl4jBindLogBack { private static final Logger log= LoggerFactory.getLogger(Sl4jBindLogBack.class); public static void main(String[] args) { log.warn("a"); log.debug("b"); log.info("c"); // 增加traceId 追踪请求的日志 MDC.put("TRACE_ID", UUID.randomUUID().toString().replace("-", "")); log.error("e"); } }
92320dcec68c97dc1fcabe6dab8cc3b1ad7df212
290
java
Java
ovh-java-sdk-licensewindows/src/main/java/net/minidev/ovh/api/license/OvhOrderableWindowsCompatibilityInfos.java
marstona/ovh-java-sdk
b574fbbac59832fda7a4fedaf3cb1f074135f714
[ "BSD-3-Clause" ]
12
2017-04-04T07:20:48.000Z
2021-04-20T07:54:21.000Z
ovh-java-sdk-licensewindows/src/main/java/net/minidev/ovh/api/license/OvhOrderableWindowsCompatibilityInfos.java
marstona/ovh-java-sdk
b574fbbac59832fda7a4fedaf3cb1f074135f714
[ "BSD-3-Clause" ]
7
2017-04-05T04:54:16.000Z
2019-09-24T11:17:05.000Z
ovh-java-sdk-licensewindows/src/main/java/net/minidev/ovh/api/license/OvhOrderableWindowsCompatibilityInfos.java
marstona/ovh-java-sdk
b574fbbac59832fda7a4fedaf3cb1f074135f714
[ "BSD-3-Clause" ]
3
2019-10-10T13:51:22.000Z
2020-11-13T14:30:45.000Z
17.058824
52
0.737931
996,081
package net.minidev.ovh.api.license; /** * All SQL options available for Windows products */ public class OvhOrderableWindowsCompatibilityInfos { /** * canBeNull */ public OvhWindowsSqlVersionEnum[] compliantSql; /** * canBeNull */ public OvhWindowsOsVersionEnum version; }
92320e6b6151d8deda4ad07b8592b2ba74eeb80f
3,414
java
Java
eventuate-client-java-event-handling/src/main/java/io/eventuate/javaclient/domain/SwimlaneDispatcher.java
dialtahi/eventuate-client-java
62b8ae6f41894b582429704467325076a236a485
[ "Apache-2.0" ]
764
2016-08-08T18:31:17.000Z
2022-03-31T11:45:40.000Z
eventuate-client-java-event-handling/src/main/java/io/eventuate/javaclient/domain/SwimlaneDispatcher.java
dialtahi/eventuate-client-java
62b8ae6f41894b582429704467325076a236a485
[ "Apache-2.0" ]
85
2016-10-14T16:40:15.000Z
2022-03-15T19:11:18.000Z
eventuate-client-java-event-handling/src/main/java/io/eventuate/javaclient/domain/SwimlaneDispatcher.java
dialtahi/eventuate-client-java
62b8ae6f41894b582429704467325076a236a485
[ "Apache-2.0" ]
243
2016-08-21T03:19:43.000Z
2022-03-28T06:13:31.000Z
34.14
130
0.678383
996,082
package io.eventuate.javaclient.domain; import io.eventuate.DispatchedEvent; import io.eventuate.Event; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Function; public class SwimlaneDispatcher { private static Logger logger = LoggerFactory.getLogger(SwimlaneDispatcher.class); private String subscriberId; private Integer swimlane; private Executor executor; private final LinkedBlockingQueue<QueuedEvent> queue = new LinkedBlockingQueue<>(); private AtomicBoolean running = new AtomicBoolean(false); public SwimlaneDispatcher(String subscriberId, Integer swimlane, Executor executor) { this.subscriberId = subscriberId; this.swimlane = swimlane; this.executor = executor; } public CompletableFuture<?> dispatch(DispatchedEvent<Event> de, Function<DispatchedEvent<Event>, CompletableFuture<?>> target) { synchronized (queue) { QueuedEvent qe = new QueuedEvent(de, target); queue.add(qe); logger.trace("added event to queue: {} {} {}", subscriberId, swimlane, de); if (running.compareAndSet(false, true)) { logger.trace("Stopped - attempting to process newly queued event: {} {}", subscriberId, swimlane); processNextQueuedEvent(); } else logger.trace("Running - Not attempting to process newly queued event: {} {}", subscriberId, swimlane); return qe.future; } } private void processNextQueuedEvent() { executor.execute(this::processQueuedEvent); } class QueuedEvent { DispatchedEvent<Event> event; private Function<DispatchedEvent<Event>, CompletableFuture<?>> target; CompletableFuture<Object> future = new CompletableFuture<>(); public QueuedEvent(DispatchedEvent<Event> event, Function<DispatchedEvent<Event>, CompletableFuture<?>> target) { this.event = event; this.target = target; } } public void processQueuedEvent() { QueuedEvent qe = getNextEvent(); if (qe == null) logger.trace("No queued event for {} {}", subscriberId, swimlane); else { logger.trace("Invoking handler for event for {} {} {}", subscriberId, swimlane, qe.event); qe.target.apply(qe.event).handle((success, throwable) -> { if (throwable == null) { logger.debug("Handler succeeded for event for {} {} {}", subscriberId, swimlane, qe.event); boolean x = qe.future.complete(success); logger.trace("Completed future success {}", x); logger.trace("Maybe processing next queued event {} {}", subscriberId, swimlane); processNextQueuedEvent(); } else { logger.error(String.format("handler for %s %s %s failed: ", subscriberId, swimlane, qe.event), throwable); boolean x = qe.future.completeExceptionally(throwable); logger.trace("Completed future failed{}", x); // TODO - what to do here??? } return null; }); } } private QueuedEvent getNextEvent() { QueuedEvent qe1 = queue.poll(); if (qe1 != null) return qe1; synchronized (queue) { QueuedEvent qe = queue.poll(); if (qe == null) { running.compareAndSet(true, false); } return qe; } } }
92320f1656b4a255e4fb9a59500be297b5e51a75
311
java
Java
src/org/coc/tools/server/dao/PermissionListDao.java
John-Chan/coc-admin
2275209190db67db4b0a38d4ce2acdbfe570460f
[ "Apache-2.0" ]
null
null
null
src/org/coc/tools/server/dao/PermissionListDao.java
John-Chan/coc-admin
2275209190db67db4b0a38d4ce2acdbfe570460f
[ "Apache-2.0" ]
null
null
null
src/org/coc/tools/server/dao/PermissionListDao.java
John-Chan/coc-admin
2275209190db67db4b0a38d4ce2acdbfe570460f
[ "Apache-2.0" ]
null
null
null
22.214286
71
0.749196
996,083
package org.coc.tools.server.dao; import org.coc.tools.shared.model.PermissionList; import com.googlecode.objectify.Objectify; public class PermissionListDao extends ObjectifyDao<PermissionList>{ public PermissionListDao(){ // } public PermissionListDao(Objectify ofy){ super(ofy); } }
92320fde470687fe285e020545d0956b47c9633a
362
java
Java
src/main/java/com/lknmproduction/messengerrest/domain/redis/DeviceConfirmRedis.java
kirill-kundik/RESTful-messenger
799f9c35e8da838c2bf74bffeace128a70f93ac1
[ "MIT" ]
1
2020-04-04T09:44:59.000Z
2020-04-04T09:44:59.000Z
src/main/java/com/lknmproduction/messengerrest/domain/redis/DeviceConfirmRedis.java
kirill-kundik/RESTful-messenger
799f9c35e8da838c2bf74bffeace128a70f93ac1
[ "MIT" ]
null
null
null
src/main/java/com/lknmproduction/messengerrest/domain/redis/DeviceConfirmRedis.java
kirill-kundik/RESTful-messenger
799f9c35e8da838c2bf74bffeace128a70f93ac1
[ "MIT" ]
null
null
null
20.111111
57
0.792818
996,084
package com.lknmproduction.messengerrest.domain.redis; import lombok.Data; import org.springframework.data.annotation.Id; import org.springframework.data.redis.core.RedisHash; import java.io.Serializable; @Data @RedisHash("Device") public class DeviceConfirmRedis implements Serializable { @Id private String deviceId; private String pinCode; }
92320feddd67c0463f527acc6746c2830ac58c6f
2,006
java
Java
src/main/java/com/ppdai/atlas/dao/UserRepository.java
ppdaicorp/atlas
332ed82cee0f90e67f4ce47189dd3717a1be91d8
[ "Apache-2.0" ]
16
2020-07-30T10:35:21.000Z
2021-12-24T06:17:16.000Z
src/main/java/com/ppdai/atlas/dao/UserRepository.java
ppdaicorp/atlas
332ed82cee0f90e67f4ce47189dd3717a1be91d8
[ "Apache-2.0" ]
null
null
null
src/main/java/com/ppdai/atlas/dao/UserRepository.java
ppdaicorp/atlas
332ed82cee0f90e67f4ce47189dd3717a1be91d8
[ "Apache-2.0" ]
16
2020-08-11T13:55:57.000Z
2022-03-08T05:22:07.000Z
42.680851
145
0.761216
996,085
package com.ppdai.atlas.dao; import com.ppdai.atlas.entity.UserEntity; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.domain.Specification; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import java.util.List; public interface UserRepository extends BaseJpaRepository<UserEntity, Long> { @Override @Query("select a from UserEntity a where a.isActive=true order by a.id") List<UserEntity> findAll(); @Query("select a from UserEntity a where a.isActive=true and a.id=?1") UserEntity findOneById(Long id); @Query("select a from UserEntity a where a.isActive=true and a.workNumber=?1") List<UserEntity> findByWorkNumber(String workNumber); @Query("select a from UserEntity a where a.isActive=true order by a.id") @Override Page<UserEntity> findAll(Pageable pageable); @Query("select a from UserEntity a where a.userName=?1") UserEntity findByUserName(String userName); @Query("select a from UserEntity a where a.isActive=true and a.workNumber <> '' and a.userName LIKE CONCAT('%',:userName,'%') order by a.id") Page<UserEntity> fuzzyFindByUserName(@Param("userName") String userName, Pageable pageable); @Query("select a from UserEntity a where a.isActive=true and a.source=?1 order by a.ldapUpdateTime desc") Page<UserEntity> findLdapLastUpdateFromSource(String source, Pageable pageable); @Query("select a from UserEntity a where a.isActive=false and a.source=?1 order by a.ldapUpdateTime desc") Page<UserEntity> findLdapLastDeleteFromSource(String source, Pageable pageable); @Modifying(clearAutomatically = true) @Query("update UserEntity a set a.isActive=false where a.id=?1") void removeOneEntityById(Long id); Page<UserEntity> findAll(Specification<UserEntity> specification, Pageable pageable); }
9232103f3941a8d94302a518a3228c573e00f2e6
151
java
Java
cosmetic-modules/cosmetic-module-feed/src/main/java/com/cyberlink/cosmetic/modules/feed/service/FeedInitializer.java
datree-demo/bcserver_demo
852a8d4780d3724236e1d5069cccf2dbe7a4dce9
[ "Apache-2.0" ]
1
2019-01-08T15:53:01.000Z
2019-01-08T15:53:01.000Z
cosmetic-modules/cosmetic-module-feed/src/main/java/com/cyberlink/cosmetic/modules/feed/service/FeedInitializer.java
datree-demo/bcserver_demo
852a8d4780d3724236e1d5069cccf2dbe7a4dce9
[ "Apache-2.0" ]
null
null
null
cosmetic-modules/cosmetic-module-feed/src/main/java/com/cyberlink/cosmetic/modules/feed/service/FeedInitializer.java
datree-demo/bcserver_demo
852a8d4780d3724236e1d5069cccf2dbe7a4dce9
[ "Apache-2.0" ]
null
null
null
21.571429
52
0.774834
996,086
package com.cyberlink.cosmetic.modules.feed.service; public interface FeedInitializer { void fillAnonymousFeeds(); void fillOfficialFeed(); }
923210806235961d7871e55a9d8fdf5b962d484f
4,949
java
Java
src/java/fr/paris/lutece/portal/web/xpages/XPageApplicationEntry.java
rzara/lutece-core
2b2adb79a778389f0e768237b6264a110a245898
[ "BSD-3-Clause" ]
46
2015-01-23T00:45:32.000Z
2021-11-20T00:51:08.000Z
src/java/fr/paris/lutece/portal/web/xpages/XPageApplicationEntry.java
rzara/lutece-core
2b2adb79a778389f0e768237b6264a110a245898
[ "BSD-3-Clause" ]
105
2015-02-05T18:05:12.000Z
2022-02-11T14:57:28.000Z
src/java/fr/paris/lutece/portal/web/xpages/XPageApplicationEntry.java
rzara/lutece-core
2b2adb79a778389f0e768237b6264a110a245898
[ "BSD-3-Clause" ]
46
2015-06-08T07:22:54.000Z
2022-01-14T12:59:10.000Z
25.910995
101
0.626793
996,087
/* * Copyright (c) 2002-2021, City of Paris * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright notice * and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice * and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * 3. Neither the name of 'Mairie de Paris' nor 'Lutece' nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * License 1.0 */ package fr.paris.lutece.portal.web.xpages; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; import fr.paris.lutece.portal.service.plugin.Plugin; import fr.paris.lutece.portal.service.plugin.PluginService; /** * XPageApplication Entry */ public class XPageApplicationEntry { // Variables declarations private String _strId; private String _strClassName; private String _strPluginName; private List<String> _listRoles = new ArrayList<>( ); private boolean _bEnabled = true; // defaults to enabled /** * Returns the Id * * @return The Id */ public String getId( ) { return _strId; } /** * Sets the Id * * @param strId * The Id */ public void setId( String strId ) { _strId = strId; } /** * Returns the ClassName * * @return The ClassName */ public String getClassName( ) { return _strClassName; } /** * Sets the ClassName * * @param strClassName * The ClassName */ public void setClassName( String strClassName ) { _strClassName = strClassName; } /** * Returns the Roles * * @return The Roles */ public List<String> getRoles( ) { return _listRoles; } /** * Sets the Roles * * @param strRoles * The Roles */ public void setRoles( String strRoles ) { // extracts each role (separated by a comma) from the String if ( strRoles != null ) { StringTokenizer strTokens = new StringTokenizer( strRoles, "," ); while ( strTokens.hasMoreTokens( ) ) { _listRoles.add( strTokens.nextToken( ) ); } } } /** * Return the name of the plugin * * @return The name of the plugin */ public String getPluginName( ) { return _strPluginName; } /** * Set the plugin name of the insert service * * @param strPluginName * the plugin name */ public void setPluginName( String strPluginName ) { _strPluginName = strPluginName; } /** * Tells if the application is enable (plugin enabled) * * @return True if the application is enable, otherwise false */ public boolean isEnable( ) { return _bEnabled && PluginService.isPluginEnable( _strPluginName ); } /** * Tells if the XPageApplication is enabled, independently of the plugin's status * * @return <code>true</code> if this XPageApplication is enabled, <code>false</code> otherwise * @since 5.1 */ public boolean isEnabled( ) { return _bEnabled; } /** * Sets the enabled state of this XPageApplication * * @param bEnabled * <code>true</code> if this XPageApplication is enabled, <code>false</code> otherwise * @since 5.1 */ public void setEnabled( boolean bEnabled ) { _bEnabled = bEnabled; } /** * Gets the plugin instance associated to the application * * @return the plugin */ public Plugin getPlugin( ) { return PluginService.getPlugin( _strPluginName ); } }
9232109a3b998889199ea25e3c578366e96ea6e3
739
java
Java
src/designpatterns/creational/singleton/ThreadSafeSingleton.java
mrtmrtmlck/design-patterns-with-java
161c899274062ff00271051abad045a5fc3e2da6
[ "MIT" ]
null
null
null
src/designpatterns/creational/singleton/ThreadSafeSingleton.java
mrtmrtmlck/design-patterns-with-java
161c899274062ff00271051abad045a5fc3e2da6
[ "MIT" ]
null
null
null
src/designpatterns/creational/singleton/ThreadSafeSingleton.java
mrtmrtmlck/design-patterns-with-java
161c899274062ff00271051abad045a5fc3e2da6
[ "MIT" ]
null
null
null
29.56
78
0.634641
996,088
package designpatterns.creational.singleton; public final class ThreadSafeSingleton { // threads reads the most recent instance value thanks to volatile keyword private static volatile ThreadSafeSingleton instance; public String value; private ThreadSafeSingleton(String value) { this.value = value; } public static ThreadSafeSingleton getInstance(String value) { if (instance == null) { // threads wait each other before entering synchronized block synchronized (ThreadSafeSingleton.class) { if (instance == null) { instance = new ThreadSafeSingleton(value); } } } return instance; } }
9232109a89b5ddfdcadf7fcf204691761fa774a9
5,795
java
Java
configserver/src/test/java/com/yahoo/vespa/config/server/session/LocalSessionRepoTest.java
leisureshadow/vespa
28a35b8d53cbd6dda54eb141e29b12584b297410
[ "Apache-2.0" ]
null
null
null
configserver/src/test/java/com/yahoo/vespa/config/server/session/LocalSessionRepoTest.java
leisureshadow/vespa
28a35b8d53cbd6dda54eb141e29b12584b297410
[ "Apache-2.0" ]
null
null
null
configserver/src/test/java/com/yahoo/vespa/config/server/session/LocalSessionRepoTest.java
leisureshadow/vespa
28a35b8d53cbd6dda54eb141e29b12584b297410
[ "Apache-2.0" ]
null
null
null
40.809859
147
0.669025
996,089
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.config.server.session; import com.yahoo.cloud.config.ConfigserverConfig; import com.yahoo.config.model.application.provider.FilesApplicationPackage; import com.yahoo.test.ManualClock; import com.yahoo.config.provision.TenantName; import com.yahoo.vespa.config.server.GlobalComponentRegistry; import com.yahoo.vespa.config.server.MockReloadHandler; import com.yahoo.vespa.config.server.TestComponentRegistry; import com.yahoo.vespa.config.server.application.TenantApplications; import com.yahoo.io.IOUtils; import com.yahoo.vespa.config.server.host.HostRegistry; import com.yahoo.vespa.config.server.http.SessionHandlerTest; import com.yahoo.vespa.curator.mock.MockCurator; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import java.io.File; import java.nio.file.Path; import java.nio.file.Paths; import java.time.Duration; import java.time.Instant; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; /** * @author Ulf Lilleengen */ public class LocalSessionRepoTest { private File testApp = new File("src/test/apps/app"); private LocalSessionRepo repo; private ManualClock clock; private static final TenantName tenantName = TenantName.defaultName(); @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); @Before public void setupSessions() throws Exception { setupSessions(tenantName, true); } private void setupSessions(TenantName tenantName, boolean createInitialSessions) throws Exception { File configserverDbDir = temporaryFolder.newFolder().getAbsoluteFile(); if (createInitialSessions) { Path sessionsPath = Paths.get(configserverDbDir.getAbsolutePath(), "tenants", tenantName.value(), "sessions"); IOUtils.copyDirectory(testApp, sessionsPath.resolve("1").toFile()); IOUtils.copyDirectory(testApp, sessionsPath.resolve("2").toFile()); IOUtils.copyDirectory(testApp, sessionsPath.resolve("3").toFile()); } clock = new ManualClock(Instant.ofEpochSecond(1)); GlobalComponentRegistry globalComponentRegistry = new TestComponentRegistry.Builder() .curator(new MockCurator()) .clock(clock) .configServerConfig(new ConfigserverConfig.Builder() .configServerDBDir(configserverDbDir.getAbsolutePath()) .configDefinitionsDir(temporaryFolder.newFolder().getAbsolutePath()) .sessionLifetime(5) .build()) .build(); LocalSessionLoader loader = new SessionFactoryImpl(globalComponentRegistry, TenantApplications.create(globalComponentRegistry, new MockReloadHandler(), tenantName), new HostRegistry<>(), tenantName); repo = new LocalSessionRepo(tenantName, globalComponentRegistry, loader); } @Test public void require_that_sessions_can_be_loaded_from_disk() { assertNotNull(repo.getSession(1L)); assertNotNull(repo.getSession(2L)); assertNotNull(repo.getSession(3L)); assertNull(repo.getSession(4L)); } @Test public void require_that_old_sessions_are_purged() { clock.advance(Duration.ofSeconds(1)); assertNotNull(repo.getSession(1L)); assertNotNull(repo.getSession(2L)); assertNotNull(repo.getSession(3L)); clock.advance(Duration.ofSeconds(1)); assertNotNull(repo.getSession(1L)); assertNotNull(repo.getSession(2L)); assertNotNull(repo.getSession(3L)); clock.advance(Duration.ofSeconds(1)); addSession(4L, 6); assertNotNull(repo.getSession(1L)); assertNotNull(repo.getSession(2L)); assertNotNull(repo.getSession(3L)); assertNotNull(repo.getSession(4L)); clock.advance(Duration.ofSeconds(1)); addSession(5L, 10); repo.purgeOldSessions(); assertNull(repo.getSession(1L)); assertNull(repo.getSession(2L)); assertNull(repo.getSession(3L)); } @Test public void require_that_all_sessions_are_deleted() { repo.close(); assertNull(repo.getSession(1L)); assertNull(repo.getSession(2L)); assertNull(repo.getSession(3L)); } private void addSession(long sessionId, long createTime) { repo.addSession(new SessionHandlerTest.MockSession(sessionId, FilesApplicationPackage.fromFile(testApp), createTime)); } @Test public void require_that_sessions_belong_to_a_tenant() { // tenant is "default" assertNotNull(repo.getSession(1L)); assertNotNull(repo.getSession(2L)); assertNotNull(repo.getSession(3L)); assertNull(repo.getSession(4L)); // tenant is "newTenant" try { setupSessions(TenantName.from("newTenant"), false); } catch (Exception e) { fail(); } assertNull(repo.getSession(1L)); repo.addSession(new SessionHandlerTest.MockSession(1L, FilesApplicationPackage.fromFile(testApp))); repo.addSession(new SessionHandlerTest.MockSession(2L, FilesApplicationPackage.fromFile(testApp))); assertNotNull(repo.getSession(1L)); assertNotNull(repo.getSession(2L)); assertNull(repo.getSession(3L)); } }
923210bb0779303342c019738befdab69e5bfdec
2,374
java
Java
lucene/analysis/uima/src/test/org/apache/lucene/analysis/uima/ae/OverridingParamsAEProviderTest.java
theninjawoohoo/CMPT456-CourseProject
34cb169669362361550481dfc399aa89609d44b2
[ "Apache-2.0" ]
5
2017-03-17T04:35:39.000Z
2021-04-06T07:20:04.000Z
lucene/analysis/uima/src/test/org/apache/lucene/analysis/uima/ae/OverridingParamsAEProviderTest.java
theninjawoohoo/CMPT456-CourseProject
34cb169669362361550481dfc399aa89609d44b2
[ "Apache-2.0" ]
null
null
null
lucene/analysis/uima/src/test/org/apache/lucene/analysis/uima/ae/OverridingParamsAEProviderTest.java
theninjawoohoo/CMPT456-CourseProject
34cb169669362361550481dfc399aa89609d44b2
[ "Apache-2.0" ]
2
2019-09-05T09:55:45.000Z
2020-11-14T18:32:19.000Z
39.566667
125
0.767481
996,090
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.lucene.analysis.uima.ae; import org.apache.lucene.util.LuceneTestCase; import org.apache.uima.analysis_engine.AnalysisEngine; import org.apache.uima.resource.ResourceInitializationException; import org.junit.Test; import java.util.HashMap; import java.util.Map; /** * TestCase for {@link OverridingParamsAEProvider} */ public class OverridingParamsAEProviderTest extends LuceneTestCase { @Test public void testNullMapInitialization() throws Exception { expectThrows(ResourceInitializationException.class, () -> { AEProvider aeProvider = new OverridingParamsAEProvider("/uima/TestEntityAnnotatorAE.xml", null); aeProvider.getAE(); }); } @Test public void testEmptyMapInitialization() throws Exception { AEProvider aeProvider = new OverridingParamsAEProvider("/uima/TestEntityAnnotatorAE.xml", new HashMap<String, Object>()); AnalysisEngine analysisEngine = aeProvider.getAE(); assertNotNull(analysisEngine); } @Test public void testOverridingParamsInitialization() throws Exception { Map<String, Object> runtimeParameters = new HashMap<>(); runtimeParameters.put("ngramsize", "3"); AEProvider aeProvider = new OverridingParamsAEProvider("/uima/AggregateSentenceAE.xml", runtimeParameters); AnalysisEngine analysisEngine = aeProvider.getAE(); assertNotNull(analysisEngine); Object parameterValue = analysisEngine.getConfigParameterValue("ngramsize"); assertNotNull(parameterValue); assertEquals(Integer.valueOf(3), Integer.valueOf(parameterValue.toString())); } }
923211712141ca49c924448e81d9205b3975d308
2,689
java
Java
samples/server/petstore/java-pkmst/src/test/java/com/prokarma/pkmst/controller/StoreApiTest.java
mgrojo/openapi-generator
a9216ba4f715eab77ae4444e4916d1de003f8c5b
[ "Apache-2.0" ]
11,868
2018-05-12T02:58:07.000Z
2022-03-31T21:19:39.000Z
samples/server/petstore/java-pkmst/src/test/java/com/prokarma/pkmst/controller/StoreApiTest.java
mgrojo/openapi-generator
a9216ba4f715eab77ae4444e4916d1de003f8c5b
[ "Apache-2.0" ]
9,672
2018-05-12T14:25:43.000Z
2022-03-31T23:59:30.000Z
samples/server/petstore/java-pkmst/src/test/java/com/prokarma/pkmst/controller/StoreApiTest.java
mgrojo/openapi-generator
a9216ba4f715eab77ae4444e4916d1de003f8c5b
[ "Apache-2.0" ]
4,776
2018-05-12T12:06:08.000Z
2022-03-31T19:52:51.000Z
25.130841
133
0.651171
996,091
/* * OpenAPI Petstore * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. * * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package com.prokarma.pkmst.controller; import com.fasterxml.jackson.databind.ObjectMapper; import java.util.Map; import com.prokarma.pkmst.model.Order; import org.junit.Test; import org.junit.Ignore; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.http.ResponseEntity; import org.springframework.web.multipart.MultipartFile; /** * API tests for StoreApi */ @Ignore public class StoreApiTest { private final ObjectMapper objectMapper = new ObjectMapper(); private final StoreApi api = new StoreApiController(objectMapper); private final String accept = "application/json"; /** * Delete purchase order by ID * * For valid response try integer IDs with value &lt; 1000. Anything above 1000 or nonintegers will generate API errors * * @throws Exception * if the Api call fails */ @Test public void deleteOrderTest() throws Exception { String orderId = null; ResponseEntity<Void> response = api.deleteOrder(orderId , accept); // TODO: test validations } /** * Returns pet inventories by status * * Returns a map of status codes to quantities * * @throws Exception * if the Api call fails */ @Test public void getInventoryTest() throws Exception { ResponseEntity<Map<String, Integer>> response = api.getInventory( accept); // TODO: test validations } /** * Find purchase order by ID * * For valid response try integer IDs with value &lt;&#x3D; 5 or &gt; 10. Other values will generated exceptions * * @throws Exception * if the Api call fails */ @Test public void getOrderByIdTest() throws Exception { Long orderId = null; ResponseEntity<Order> response = api.getOrderById(orderId , accept); // TODO: test validations } /** * Place an order for a pet * * * * @throws Exception * if the Api call fails */ @Test public void placeOrderTest() throws Exception { Order body = null; ResponseEntity<Order> response = api.placeOrder(body , accept); // TODO: test validations } }
923212f5b4ea1481e788d75a0c0f3524e01b80f6
4,423
java
Java
sap-common-jco/src/main/java/com/google/cloud/datafusion/plugin/sap/connection/out/SapDestinationDataProvider.java
shivamVarCS/cdf-sap-batch-plugin-feature-sap-odata-connectionManager
59630be526dad60c8191b74838b1c4b664f800d9
[ "Apache-2.0" ]
null
null
null
sap-common-jco/src/main/java/com/google/cloud/datafusion/plugin/sap/connection/out/SapDestinationDataProvider.java
shivamVarCS/cdf-sap-batch-plugin-feature-sap-odata-connectionManager
59630be526dad60c8191b74838b1c4b664f800d9
[ "Apache-2.0" ]
null
null
null
sap-common-jco/src/main/java/com/google/cloud/datafusion/plugin/sap/connection/out/SapDestinationDataProvider.java
shivamVarCS/cdf-sap-batch-plugin-feature-sap-odata-connectionManager
59630be526dad60c8191b74838b1c4b664f800d9
[ "Apache-2.0" ]
null
null
null
31.820144
120
0.718517
996,092
/* * Copyright © 2021 Cask Data, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.cloud.datafusion.plugin.sap.connection.out; import com.google.cloud.datafusion.plugin.sap.connection.SapDefinition; import com.sap.conn.jco.ext.DestinationDataEventListener; import com.sap.conn.jco.ext.DestinationDataProvider; import com.sap.conn.jco.ext.Environment; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.Map; import java.util.Properties; /** * Implements the JCo Destination Data Provider to initialize and utilize JCo * Runtime for connecting to SAP, without the requirement of a physical * connection file. * * @author sankalpbapat */ public class SapDestinationDataProvider implements DestinationDataProvider { private static final Logger LOGGER = LoggerFactory.getLogger(SapDestinationDataProvider.class); private static final SapDestinationDataProvider DEST_DATA_PROVIDER = new SapDestinationDataProvider(); private final Map<String, SapDefinition> defs; private DestinationDataEventListener eventListener; private SapDestinationDataProvider() { this.defs = new HashMap<>(); } public static final SapDestinationDataProvider getInstance() { return DEST_DATA_PROVIDER; } /* * (non-Javadoc) * * @see * com.sap.conn.jco.ext.DestinationDataProvider#getDestinationProperties(java. * lang.String) */ @Override public Properties getDestinationProperties(String name) { SapDefinition def = this.defs.get(name); if (def != null && def.getProviderKey(false).equalsIgnoreCase(name)) { return def.getProperties(); } return null; } /* * (non-Javadoc) * * @see * com.sap.conn.jco.ext.DestinationDataProvider#setDestinationDataEventListener( * com.sap.conn.jco.ext.DestinationDataEventListener) */ @Override public void setDestinationDataEventListener(DestinationDataEventListener eventListener) { this.eventListener = eventListener; } /* * (non-Javadoc) * * @see com.sap.conn.jco.ext.DestinationDataProvider#supportsEvents() */ @Override public boolean supportsEvents() { return true; } /** * Registers the {@link DestinationDataProvider} in SAP JCo Runtime Environment, * and updates connection parameters definition. Expected to be called for every * new SapConnection. * * @param def Connection parameters */ public void register(SapDefinition def) { LOGGER.debug("Destination Data Provider already registered? {}", Environment.isDestinationDataProviderRegistered()); synchronized (this) { // This check passes only the first time upon JVM start. if (this.defs.isEmpty() && !Environment.isDestinationDataProviderRegistered()) { LOGGER.debug("Registering Destination Data Provider in JCo environment"); // This activity is needed once during the whole JVM life cycle, before the // first SAP call over network. Environment.registerDestinationDataProvider(this); } String destKey = def.getProviderKey(false); SapDefinition previousDef = this.defs.put(destKey, def); if (previousDef != null) { LOGGER.debug("Updating Destination Data Event Listener to the latest destination name '{}'", destKey); eventListener.updated(destKey); } } } /** * Removes connection parameters definition from JCo destination manager. * * @param destKey Connection parameters identifier */ public void removeDefinition(String destKey) { synchronized (this) { if (this.defs != null && !defs.isEmpty()) { SapDefinition def = this.defs.remove(destKey); if (def != null) { LOGGER.debug("Deleting the destination name '{}' from Destination Data Event Listener", destKey); eventListener.deleted(destKey); } } } } }
923213108551beaee7468a0c4ae05968620602eb
1,800
java
Java
referencemodels/src/test/java/org/openehr/referencemodels/ModelDifference.java
jakesmolka/archie
dc0964219353b5baeedf816191a079537e530b45
[ "Apache-2.0" ]
44
2018-02-01T07:19:51.000Z
2022-02-21T12:13:35.000Z
referencemodels/src/test/java/org/openehr/referencemodels/ModelDifference.java
jakesmolka/archie
dc0964219353b5baeedf816191a079537e530b45
[ "Apache-2.0" ]
337
2017-11-03T15:21:10.000Z
2022-03-31T12:19:45.000Z
referencemodels/src/test/java/org/openehr/referencemodels/ModelDifference.java
jakesmolka/archie
dc0964219353b5baeedf816191a079537e530b45
[ "Apache-2.0" ]
28
2017-12-08T06:23:17.000Z
2022-03-03T01:19:30.000Z
26.086957
109
0.603333
996,093
package org.openehr.referencemodels; import java.util.Objects; public class ModelDifference { private ModelDifferenceType type; private String className; private String propertyName; private String message; public ModelDifference(ModelDifferenceType type, String message) { this(type, message, null, null); } public ModelDifference(ModelDifferenceType type, String message, String className) { this(type, message, className, null); } public ModelDifference(ModelDifferenceType type, String message, String className, String propertyName) { this.type = type; this.message = message; this.className = className; this.propertyName = propertyName; } public String getMessage() { return message; } @Override public String toString() { return "ModelDifference{" + "type=" + type + ", className='" + className + '\'' + ", propertyName='" + propertyName + '\'' + ", message='" + message + '\'' + '}'; } public ModelDifferenceType getType() { return type; } public String getClassName() { return className; } public String getPropertyName() { return propertyName; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof ModelDifference)) return false; ModelDifference that = (ModelDifference) o; return type == that.type && Objects.equals(className, that.className) && Objects.equals(propertyName, that.propertyName); } @Override public int hashCode() { return Objects.hash(type, className, propertyName); } }
923213755855a4c5ed7111b882bbd629ea523df8
3,819
java
Java
zipkin-server/src/test/java/zipkin2/server/internal/rabbitmq/ZipkinRabbitMQCollectorConfigurationTest.java
jgallimore/incubator-zipkin
f2d9cc8c7e874bae7531cdc94c11eb5cc23f987d
[ "Apache-2.0" ]
null
null
null
zipkin-server/src/test/java/zipkin2/server/internal/rabbitmq/ZipkinRabbitMQCollectorConfigurationTest.java
jgallimore/incubator-zipkin
f2d9cc8c7e874bae7531cdc94c11eb5cc23f987d
[ "Apache-2.0" ]
null
null
null
zipkin-server/src/test/java/zipkin2/server/internal/rabbitmq/ZipkinRabbitMQCollectorConfigurationTest.java
jgallimore/incubator-zipkin
f2d9cc8c7e874bae7531cdc94c11eb5cc23f987d
[ "Apache-2.0" ]
null
null
null
33.79646
97
0.77193
996,094
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package zipkin2.server.internal.rabbitmq; import org.junit.After; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; import org.springframework.boot.test.util.TestPropertyValues; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import zipkin2.collector.CollectorMetrics; import zipkin2.collector.CollectorSampler; import zipkin2.collector.rabbitmq.RabbitMQCollector; import zipkin2.storage.InMemoryStorage; import zipkin2.storage.StorageComponent; import static org.assertj.core.api.Assertions.assertThat; public class ZipkinRabbitMQCollectorConfigurationTest { @Rule public ExpectedException thrown = ExpectedException.none(); private AnnotationConfigApplicationContext context; @After public void close() { if (context != null) { context.close(); } } @Test public void doesNotProvideCollectorComponent_whenAddressAndUriNotSet() { context = new AnnotationConfigApplicationContext(); context.register( PropertyPlaceholderAutoConfiguration.class, ZipkinRabbitMQCollectorConfiguration.class, InMemoryConfiguration.class); context.refresh(); thrown.expect(NoSuchBeanDefinitionException.class); context.getBean(RabbitMQCollector.class); } @Test public void doesNotProvideCollectorComponent_whenAddressesAndUriIsEmptyString() { context = new AnnotationConfigApplicationContext(); TestPropertyValues.of( "zipkin.collector.rabbitmq.addresses:", "zipkin.collector.rabbitmq.uri:") .applyTo(context); context.register( PropertyPlaceholderAutoConfiguration.class, ZipkinRabbitMQCollectorConfiguration.class, InMemoryConfiguration.class); context.refresh(); thrown.expect(NoSuchBeanDefinitionException.class); context.getBean(RabbitMQCollector.class); } @Test @Ignore public void providesCollectorComponent_whenAddressesSet() { context = new AnnotationConfigApplicationContext(); TestPropertyValues.of("zipkin.collector.rabbitmq.addresses=localhost:5672").applyTo(context); context.register( PropertyPlaceholderAutoConfiguration.class, ZipkinRabbitMQCollectorConfiguration.class, InMemoryConfiguration.class); context.refresh(); assertThat(context.getBean(RabbitMQCollector.class)).isNotNull(); } @Configuration static class InMemoryConfiguration { @Bean CollectorSampler sampler() { return CollectorSampler.ALWAYS_SAMPLE; } @Bean CollectorMetrics metrics() { return CollectorMetrics.NOOP_METRICS; } @Bean StorageComponent storage() { return InMemoryStorage.newBuilder().build(); } } }
923213f9448a3bd6d1457eb86aa52a14707caf02
4,456
java
Java
experiment/backend/src/AdapterWorldSocket.java
cuehs/transmissionchains_independentsolvers
3d349dd479d2f8d6c7b9d84e26c2be5c2077007b
[ "MIT" ]
null
null
null
experiment/backend/src/AdapterWorldSocket.java
cuehs/transmissionchains_independentsolvers
3d349dd479d2f8d6c7b9d84e26c2be5c2077007b
[ "MIT" ]
null
null
null
experiment/backend/src/AdapterWorldSocket.java
cuehs/transmissionchains_independentsolvers
3d349dd479d2f8d6c7b9d84e26c2be5c2077007b
[ "MIT" ]
null
null
null
39.087719
119
0.563959
996,095
import com.google.gson.Gson; import org.eclipse.jetty.websocket.api.RemoteEndpoint; import org.eclipse.jetty.websocket.api.Session; import org.eclipse.jetty.websocket.api.WebSocketAdapter; import java.util.ArrayList; public class AdapterWorldSocket extends WebSocketAdapter { private World world = World.initialize(); private Gson gson = new Gson(); @Override public void onWebSocketConnect(Session session) { super.onWebSocketConnect(session); world.addUser(session); System.out.println("Added user: " + session.toString()); if (isConnected()) { User currentUser = world.getUser(getSession()); System.out.println("Added user: " + currentUser.getId()); } } @Override public void onWebSocketText(String message) { if (isConnected()) { System.out.println(message); User currentUser = world.getUser(getSession()); RemoteEndpoint currentEndpoint = currentUser.getSession().getRemote(); if(message.startsWith("state")){ currentUser.createState(); currentUser.getSession().getRemote(). sendStringByFuture(gson.toJson(currentUser.getState())); } if (message.startsWith("position")) { //msg processing String[] splitted = message.split(":"); String level = splitted[1]; String field = splitted[2]; writeMovementString(getSession(), "position",level, field); } if (message.startsWith("payoff")) { //msg processing String[] splitted = message.split(":"); String level = splitted[1]; String field = splitted[2]; writeMovementString(getSession(), "payoff",level, field); } if (message.startsWith("mask")) { //msg processing String[] splitted = message.split(":"); String level = splitted[1]; String field = splitted[2]; writeMovementString(getSession(), "mask",level, field); } if (message.startsWith("endPosition")) { World.getLogger().flushMovementFile(); String[] splitted = message.split(":"); String level = splitted[1]; String position = splitted[2]; currentUser.getState().getLandscapes().get(Integer.parseInt(level)).receivedFromParticipant(); String[] newPositionString = position.split(","); ArrayList<Integer> newPosition = new ArrayList<>(); for(String s : newPositionString){ newPosition.add(Integer.parseInt(s)); } currentUser.getState().getLandscapes().get(Integer.parseInt(level)).setSequentialPosition(newPosition); } if (message.startsWith("participant")) { String[] splitted = message.split(":"); writeParticipantString(getSession(), splitted[1]); world.getLogger().flushParticipantFile(); } if (message.startsWith("remove")) { for (User u : world.getAllUsers()) { u.getSession().close(); world.removeUser(u.getSession()); } world.getLogger().restartFiles(world.getPathPrefix()); } if (message.startsWith("endExperiment")) { world.getLogger().flushMovementFile(); currentUser.setFinished(true); } } } private void writeMovementString(Session session, String type, String level, String message) { User currentUser = world.getUser(session); world.getLogger().writeToMovementFile(world.getTime() + "," + currentUser.getId() + "," + level + "," +type +"," + message + "\n"); } private void writeParticipantString(Session session, String text) { User currentUser = world.getUser(session); world.getLogger().writeToParticipantFile(world.getTime() + "," + currentUser.getId() + "," + text + "\n"); } @Override public void onWebSocketClose(int statusCode, String reason) { world.getLogger().flushMovementFile(); world.removeUser(getSession()); } }
9232149f7e859b6b53170e8358a6c1b220a35d32
2,003
java
Java
main/plugins/org.talend.presentation.onboarding/src/org/talend/presentation/onboarding/listeners/BrowserDynamicPartLocationListener.java
coheigea/tcommon-studio-se
681d9a8240b120f5633d751590ac09d31ea8879b
[ "Apache-2.0" ]
75
2015-01-29T03:23:32.000Z
2022-02-26T07:05:40.000Z
main/plugins/org.talend.presentation.onboarding/src/org/talend/presentation/onboarding/listeners/BrowserDynamicPartLocationListener.java
coheigea/tcommon-studio-se
681d9a8240b120f5633d751590ac09d31ea8879b
[ "Apache-2.0" ]
813
2015-01-21T09:36:31.000Z
2022-03-30T01:15:29.000Z
main/plugins/org.talend.presentation.onboarding/src/org/talend/presentation/onboarding/listeners/BrowserDynamicPartLocationListener.java
coheigea/tcommon-studio-se
681d9a8240b120f5633d751590ac09d31ea8879b
[ "Apache-2.0" ]
272
2015-01-08T06:47:46.000Z
2022-02-09T23:22:27.000Z
32.306452
95
0.579131
996,096
// ============================================================================ // // Copyright (C) 2006-2021 Talend Inc. - www.talend.com // // This source code is available under agreement available at // %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt // // You should have received a copy of the agreement // along with this program; if not, write to Talend SA // 9 rue Pages 92150 Suresnes, France // // ============================================================================ package org.talend.presentation.onboarding.listeners; import org.eclipse.swt.browser.Browser; import org.eclipse.swt.browser.LocationEvent; import org.eclipse.swt.browser.LocationListener; import org.talend.presentation.onboarding.ui.html.DynamicHtmlURL; import org.talend.presentation.onboarding.ui.html.DynamicURLParser; /** * created by cmeng on Sep 18, 2015 Detailled comment * */ public class BrowserDynamicPartLocationListener implements LocationListener { @Override public void changing(LocationEvent event) { String url = event.location; if (url == null) { return; } DynamicURLParser parser = new DynamicURLParser(url); if (parser.hasIntroUrl()) { // stop URL first. event.doit = false; // execute the action embedded in the IntroURL DynamicHtmlURL introURL = parser.getIntroURL(); introURL.execute(); } } @Override public void changed(LocationEvent event) { String url = event.location; if (url == null) { return; } // guard against unnecessary History updates. Browser browser = (Browser) event.getSource(); if (browser.getData("navigation") != null //$NON-NLS-1$ && browser.getData("navigation").equals("true")) { //$NON-NLS-1$ //$NON-NLS-2$ return; } } }
923214ac91b805b2b25d81d880cc7157292a6381
8,396
java
Java
exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/scan/v3/FixedReceiver.java
idvp-project/drill
94e86d19407b0a66cfe432f45fb91a880eae4ea9
[ "Apache-2.0" ]
1,510
2015-01-04T01:35:19.000Z
2022-03-28T23:36:02.000Z
exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/scan/v3/FixedReceiver.java
idvp-project/drill
94e86d19407b0a66cfe432f45fb91a880eae4ea9
[ "Apache-2.0" ]
1,979
2015-01-28T03:18:38.000Z
2022-03-31T13:49:32.000Z
exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/scan/v3/FixedReceiver.java
idvp-project/drill
94e86d19407b0a66cfe432f45fb91a880eae4ea9
[ "Apache-2.0" ]
940
2015-01-01T01:39:39.000Z
2022-03-25T08:46:59.000Z
40.172249
97
0.711887
996,097
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.drill.exec.physical.impl.scan.v3; import org.apache.drill.common.exceptions.CustomErrorContext; import org.apache.drill.common.exceptions.UserException; import org.apache.drill.common.types.TypeProtos.DataMode; import org.apache.drill.exec.physical.impl.scan.convert.StandardConversions; import org.apache.drill.exec.physical.resultSet.ResultSetLoader; import org.apache.drill.exec.physical.resultSet.RowSetLoader; import org.apache.drill.exec.record.metadata.ColumnMetadata; import org.apache.drill.exec.record.metadata.MetadataUtils; import org.apache.drill.exec.record.metadata.TupleMetadata; import org.apache.drill.exec.record.metadata.TupleNameSpace; import org.apache.drill.exec.record.metadata.TupleSchema; import org.apache.drill.exec.vector.accessor.ScalarWriter; import org.apache.drill.exec.vector.accessor.ValueWriter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Layer above the {@code ResultSetLoader} which handles standard conversions * for scalar columns where the schema is known up front (i.e. "early schema".) * Columns access is by both name and position, though access by position is * faster and is preferred where possible for performance. */ public class FixedReceiver { private static final Logger logger = LoggerFactory.getLogger(FixedReceiver.class); public static class Builder { private final SchemaNegotiator negotiator; private final TupleMetadata providedSchema; private final StandardConversions.Builder conversionBuilder = StandardConversions.builder(); private boolean isComplete; private RowSetLoader rowWriter; public Builder(SchemaNegotiator negotiator) { this.negotiator = negotiator; this.providedSchema = negotiator.providedSchema(); } /** * Provides access to the conversion builder to add custom properties. */ public StandardConversions.Builder conversionBuilder() { return conversionBuilder; } /** * Mark that the reader schema provided to {@link #build(TupleMetadata)} * contains all columns that this reader will deliver. Allows some * optimizations. See {@link SchemaNegotiator#schemaIsComplete(boolean)}. */ public Builder schemaIsComplete() { isComplete = true; return this; } /** * Create a fixed receiver for the provided schema (if any) in the * scan plan, and the given reader schema. Assumes no new columns will * be added later in the read. */ public FixedReceiver build(TupleMetadata readerSchema) { StandardConversions conversions = conversionBuilder.build(); TupleMetadata writerSchema = mergeSchemas(negotiator.providedSchema(), readerSchema); negotiator.tableSchema(writerSchema); negotiator.schemaIsComplete(isComplete); ResultSetLoader loader = negotiator.build(); rowWriter = loader.writer(); TupleNameSpace<ValueWriter> writers = new TupleNameSpace<>(); for (ColumnMetadata col : readerSchema) { writers.add(col.name(), writerFor(col, conversions)); } return new FixedReceiver(rowWriter, writers); } /** * Given a desired provided schema and an actual reader schema, create a merged * schema that contains the provided column where available, but the reader * column otherwise. Copies provided properties to the output schema. * <p> * The result is the schema to use when creating column writers: it reflects * the type of the target vector. The reader is responsible for converting from * the (possibly different) reader column type to the provided column type. * <p> * Note: the provided schema should only contain types that the reader is prepared * to offer: there is no requirement that the reader support every possible conversion, * only those that make sense for that one reader. * * @param providedSchema the provided schema from {@code CREATE SCHEMA} * @param readerSchema the set of column types that the reader can provide * "natively" * @return a merged schema to use when creating the {@code ResultSetLoader} */ public static TupleMetadata mergeSchemas(TupleMetadata providedSchema, TupleMetadata readerSchema) { if (providedSchema == null) { return readerSchema; } final TupleMetadata tableSchema = new TupleSchema(); for (ColumnMetadata readerCol : readerSchema) { final ColumnMetadata providedCol = providedSchema.metadata(readerCol.name()); tableSchema.addColumn(providedCol == null ? readerCol : providedCol); } if (providedSchema.hasProperties()) { tableSchema.properties().putAll(providedSchema.properties()); } return tableSchema; } private ValueWriter writerFor(ColumnMetadata readerCol, StandardConversions conversions) { if (!MetadataUtils.isScalar(readerCol)) { throw UserException.internalError() .message("FixedReceiver only works with scalar columns, reader column is not scalar") .addContext("Column name", readerCol.name()) .addContext("Column type", readerCol.type().name()) .addContext(errorContext()) .build(logger); } ScalarWriter baseWriter = rowWriter.scalar(readerCol.name()); if (!rowWriter.isProjected(readerCol.name())) { return baseWriter; } ColumnMetadata providedCol = providedCol(readerCol.name()); if (providedCol == null) { return baseWriter; } if (!MetadataUtils.isScalar(providedCol)) { throw UserException.validationError() .message("FixedReceiver only works with scalar columns, provided column is not scalar") .addContext("Provided column name", providedCol.name()) .addContext("Provided column type", providedCol.type().name()) .addContext(errorContext()) .build(logger); } if (!compatibleModes(readerCol.mode(), providedCol.mode())) { throw UserException.validationError() .message("Reader and provided columns have incompatible cardinality") .addContext("Column name", providedCol.name()) .addContext("Provided column mode", providedCol.mode().name()) .addContext("Reader column mode", readerCol.mode().name()) .addContext(errorContext()) .build(logger); } return conversions.converterFor(baseWriter, readerCol.type()); } private boolean compatibleModes(DataMode source, DataMode dest) { return source == dest || dest == DataMode.OPTIONAL && source == DataMode.REQUIRED; } private ColumnMetadata providedCol(String name) { return providedSchema == null ? null : providedSchema.metadata(name); } private CustomErrorContext errorContext( ) { return negotiator.errorContext(); } } private final RowSetLoader rowWriter; private final TupleNameSpace<ValueWriter> writers; private FixedReceiver(RowSetLoader rowWriter, TupleNameSpace<ValueWriter> writers) { this.rowWriter = rowWriter; this.writers = writers; } public static Builder builderFor(SchemaNegotiator negotiator) { return new Builder(negotiator); } public boolean start() { return rowWriter.start(); } public ValueWriter scalar(int index) { return writers.get(index); } public ValueWriter scalar(String name) { return writers.get(name); } public void save() { rowWriter.save(); } public RowSetLoader rowWriter() { return rowWriter; } }
9232152b5b8bcd3e32d68f3b815b78cacd375e4f
317
java
Java
spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/apiswagger/Application.java
adrhc/tutorials
84cd9d8fdc23beb4fa552ba9c5fd8d9df292c4c4
[ "MIT" ]
32,544
2015-01-02T16:59:22.000Z
2022-03-31T21:04:05.000Z
spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/apiswagger/Application.java
adrhc/tutorials
84cd9d8fdc23beb4fa552ba9c5fd8d9df292c4c4
[ "MIT" ]
1,577
2015-02-21T17:47:03.000Z
2022-03-31T14:25:58.000Z
spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/apiswagger/Application.java
adrhc/tutorials
84cd9d8fdc23beb4fa552ba9c5fd8d9df292c4c4
[ "MIT" ]
55,853
2015-01-01T07:52:09.000Z
2022-03-31T21:08:15.000Z
24.384615
68
0.782334
996,098
package com.baeldung.apiswagger; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication() public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
9232154da8bb33036fae32983148eb6d82a5f0c6
1,873
java
Java
examples/com/vmware/lmock/example/geek/Geek.java
xioxoz/lmock
c3bca0a8af361177fc11255a4943a86bc2dc1f2f
[ "Apache-2.0" ]
null
null
null
examples/com/vmware/lmock/example/geek/Geek.java
xioxoz/lmock
c3bca0a8af361177fc11255a4943a86bc2dc1f2f
[ "Apache-2.0" ]
null
null
null
examples/com/vmware/lmock/example/geek/Geek.java
xioxoz/lmock
c3bca0a8af361177fc11255a4943a86bc2dc1f2f
[ "Apache-2.0" ]
null
null
null
26.013889
81
0.552056
996,099
/* ************************************************************************** * Copyright (C) 2010-2011 VMware, Inc. All rights reserved. * * This product is licensed to you under the Apache License, Version 2.0. * Please see the LICENSE file to review the full text of the Apache License 2.0. * You may not use this product except in compliance with the License. * ************************************************************************** */ package com.vmware.lmock.example.geek; /** * Interface representing a geek. */ public interface Geek { /** * Exception thrown when the geek cannot eat anymore. */ public class StomachOverflowException extends Exception { private static final long serialVersionUID = 3061385086334819193L; } /** * Drinks coffee. */ public void drinksCoffee(); /** * Eats some cookies. * * @param count * the number of cookies eaten * @throws StomachOverflowException * When the geek ate too much cookies. */ public void eatsCookies(int count) throws StomachOverflowException; /** * @return An array containing all the stuff on the geek's desk. */ public Object[] getsStuffOnDesk(); /** * Puts a variable number of objects on the geek's desk. * * @param misc * the varargs list of objects */ public void putsStuffOnDesk(Object... misc); /** * Reads /. news. * * @param newTitles * the array of news titles */ public void readsSlashDot(String[] newTitles); /** * Chats on IRC. * * @return Another geek if any, so can be null. * */ public Geek chatsOnIRC(); /** * Writes some code. * * @return The number of written lines. */ public int writesCode(); }
923216eed6a3b43e545dd6100a56fffd073255a8
431
java
Java
testsuite/integration-tests/src/test/java/org/jboss/resteasy/test/client/ClientTestBase.java
iweiss/Resteasy
254e74f84806534f8a2b57cc73693428a2a9fcca
[ "Apache-2.0" ]
841
2015-01-01T10:13:52.000Z
2021-09-17T03:41:49.000Z
testsuite/integration-tests/src/test/java/org/jboss/resteasy/test/client/ClientTestBase.java
iweiss/Resteasy
254e74f84806534f8a2b57cc73693428a2a9fcca
[ "Apache-2.0" ]
974
2015-01-23T02:42:23.000Z
2021-09-17T03:35:22.000Z
testsuite/integration-tests/src/test/java/org/jboss/resteasy/test/client/ClientTestBase.java
iweiss/Resteasy
254e74f84806534f8a2b57cc73693428a2a9fcca
[ "Apache-2.0" ]
747
2015-01-08T22:48:05.000Z
2021-09-02T15:56:08.000Z
19.590909
56
0.675174
996,100
package org.jboss.resteasy.test.client; import java.net.URI; import org.jboss.arquillian.test.api.ArquillianResource; /** * @author Tomaz Cerar (c) 2016 Red Hat Inc. */ public abstract class ClientTestBase { @ArquillianResource URI baseUri; protected String generateURL(String path) { if (path.startsWith("/")){ path = path.substring(1); } return baseUri.resolve(path).toString(); } }
9232175c34b08cfc40f1761dad4bcfd9008631e3
1,173
java
Java
src/main/java/org/barrelmc/barrel/network/translator/bedrock/TextPacket.java
BarrelMC/Barrel
511a2238fe93a3625f7b4b6a1810057f15d2a15d
[ "MIT" ]
24
2021-06-14T12:51:06.000Z
2021-12-03T01:38:03.000Z
src/main/java/org/barrelmc/barrel/network/translator/bedrock/TextPacket.java
BarrelMC/Barrel
511a2238fe93a3625f7b4b6a1810057f15d2a15d
[ "MIT" ]
null
null
null
src/main/java/org/barrelmc/barrel/network/translator/bedrock/TextPacket.java
BarrelMC/Barrel
511a2238fe93a3625f7b4b6a1810057f15d2a15d
[ "MIT" ]
5
2021-06-23T13:21:33.000Z
2022-02-06T09:17:56.000Z
35.545455
124
0.660699
996,101
package org.barrelmc.barrel.network.translator.bedrock; import com.github.steveice10.mc.protocol.data.game.MessageType; import com.github.steveice10.mc.protocol.packet.ingame.server.ServerChatPacket; import com.nukkitx.protocol.bedrock.BedrockPacket; import net.kyori.adventure.text.Component; import org.barrelmc.barrel.network.translator.interfaces.BedrockPacketTranslator; import org.barrelmc.barrel.player.Player; public class TextPacket implements BedrockPacketTranslator { @Override public void translate(BedrockPacket pk, Player player) { com.nukkitx.protocol.bedrock.packet.TextPacket packet = (com.nukkitx.protocol.bedrock.packet.TextPacket) pk; switch (packet.getType()) { case TIP: case POPUP: { player.sendTip(packet.getMessage()); break; } case SYSTEM: { player.getJavaSession().send(new ServerChatPacket(Component.text(packet.getMessage()), MessageType.SYSTEM)); break; } default: { player.sendMessage(packet.getMessage()); break; } } } }
92321807fe4f5d79f674629da30682757be9d9d5
2,438
java
Java
app/src/main/java/com/raresconea/bakingapp/data/models/Step.java
Raresh996/BakingApp
5b12adc416affbea90e438734df4001e50c516b6
[ "Apache-2.0" ]
2
2018-06-12T11:40:39.000Z
2018-06-23T14:43:26.000Z
app/src/main/java/com/raresconea/bakingapp/data/models/Step.java
Raresh996/BakingApp
5b12adc416affbea90e438734df4001e50c516b6
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/raresconea/bakingapp/data/models/Step.java
Raresh996/BakingApp
5b12adc416affbea90e438734df4001e50c516b6
[ "Apache-2.0" ]
null
null
null
22.785047
69
0.587777
996,102
package com.raresconea.bakingapp.data.models; import android.os.Parcel; import android.os.Parcelable; /** * Created by Rares on 5/5/2018. */ public class Step implements Parcelable { private Integer id; private String shortDescription; private String description; private String videoURL; private String thumbnailURL; public Step() {} protected Step(Parcel in) { shortDescription = in.readString(); description = in.readString(); videoURL = in.readString(); thumbnailURL = in.readString(); } public static final Creator<Step> CREATOR = new Creator<Step>() { @Override public Step createFromParcel(Parcel in) { return new Step(in); } @Override public Step[] newArray(int size) { return new Step[size]; } }; @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(shortDescription); dest.writeString(description); dest.writeString(videoURL); dest.writeString(thumbnailURL); } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getShortDescription() { return shortDescription; } public void setShortDescription(String shortDescription) { this.shortDescription = shortDescription; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getVideoURL() { return videoURL; } public void setVideoURL(String videoURL) { this.videoURL = videoURL; } public String getThumbnailURL() { return thumbnailURL; } public void setThumbnailURL(String thumbnailURL) { this.thumbnailURL = thumbnailURL; } public static Creator<Step> getCREATOR() { return CREATOR; } @Override public String toString() { return "Step{" + "id=" + id + ", shortDescription='" + shortDescription + '\'' + ", description='" + description + '\'' + ", videoURL='" + videoURL + '\'' + ", thumbnailURL='" + thumbnailURL + '\'' + '}'; } }
92321881525fb4d8d44177320fbad6449cd87b37
50,894
java
Java
modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearLockFuture.java
DirectXceriD/apache-ignite
7972da93f7ca851642fe1fb52723b661e3c3933b
[ "Apache-2.0" ]
36
2015-11-05T04:46:27.000Z
2021-12-29T08:26:02.000Z
modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearLockFuture.java
gridgain/incubator-ignite
7972da93f7ca851642fe1fb52723b661e3c3933b
[ "Apache-2.0" ]
13
2016-08-29T11:54:08.000Z
2020-12-08T08:47:04.000Z
modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearLockFuture.java
gridgain/incubator-ignite
7972da93f7ca851642fe1fb52723b661e3c3933b
[ "Apache-2.0" ]
15
2016-03-18T09:25:39.000Z
2021-10-01T05:49:39.000Z
35.416841
121
0.466931
996,103
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.internal.processors.cache.distributed.near; import org.apache.ignite.*; import org.apache.ignite.cluster.*; import org.apache.ignite.internal.*; import org.apache.ignite.internal.cluster.*; import org.apache.ignite.internal.managers.discovery.*; import org.apache.ignite.internal.processors.cache.*; import org.apache.ignite.internal.processors.cache.distributed.*; import org.apache.ignite.internal.processors.cache.distributed.dht.*; import org.apache.ignite.internal.processors.cache.transactions.*; import org.apache.ignite.internal.processors.cache.version.*; import org.apache.ignite.internal.processors.timeout.*; import org.apache.ignite.internal.util.future.*; import org.apache.ignite.internal.util.tostring.*; import org.apache.ignite.internal.util.typedef.*; import org.apache.ignite.internal.util.typedef.internal.*; import org.apache.ignite.lang.*; import org.apache.ignite.transactions.*; import org.jdk8.backport.*; import org.jetbrains.annotations.*; import java.util.*; import java.util.concurrent.atomic.*; import static org.apache.ignite.events.EventType.*; /** * Cache lock future. */ public final class GridNearLockFuture<K, V> extends GridCompoundIdentityFuture<Boolean> implements GridCacheMvccFuture<Boolean> { /** */ private static final long serialVersionUID = 0L; /** Logger reference. */ private static final AtomicReference<IgniteLogger> logRef = new AtomicReference<>(); /** */ private static IgniteLogger log; /** Cache registry. */ @GridToStringExclude private GridCacheContext<K, V> cctx; /** Lock owner thread. */ @GridToStringInclude private long threadId; /** Keys to lock. */ private Collection<KeyCacheObject> keys; /** Future ID. */ private IgniteUuid futId; /** Lock version. */ private GridCacheVersion lockVer; /** Read flag. */ private boolean read; /** Flag to return value. */ private boolean retval; /** Error. */ private AtomicReference<Throwable> err = new AtomicReference<>(null); /** Timed out flag. */ private volatile boolean timedOut; /** Timeout object. */ @GridToStringExclude private LockTimeoutObject timeoutObj; /** Lock timeout. */ private long timeout; /** Filter. */ private CacheEntryPredicate[] filter; /** Transaction. */ @GridToStringExclude private GridNearTxLocal tx; /** Topology snapshot to operate on. */ private AtomicReference<GridDiscoveryTopologySnapshot> topSnapshot = new AtomicReference<>(); /** Map of current values. */ private Map<KeyCacheObject, IgniteBiTuple<GridCacheVersion, CacheObject>> valMap; /** Trackable flag. */ private boolean trackable = true; /** Mutex. */ private final Object mux = new Object(); /** Keys locked so far. */ @SuppressWarnings({"FieldAccessedSynchronizedAndUnsynchronized"}) @GridToStringExclude private List<GridDistributedCacheEntry> entries; /** TTL for read operation. */ private long accessTtl; /** * @param cctx Registry. * @param keys Keys to lock. * @param tx Transaction. * @param read Read flag. * @param retval Flag to return value or not. * @param timeout Lock acquisition timeout. * @param accessTtl TTL for read operation. * @param filter Filter. */ public GridNearLockFuture( GridCacheContext<K, V> cctx, Collection<KeyCacheObject> keys, @Nullable GridNearTxLocal tx, boolean read, boolean retval, long timeout, long accessTtl, CacheEntryPredicate[] filter) { super(cctx.kernalContext(), CU.boolReducer()); assert keys != null; this.cctx = cctx; this.keys = keys; this.tx = tx; this.read = read; this.retval = retval; this.timeout = timeout; this.accessTtl = accessTtl; this.filter = filter; threadId = tx == null ? Thread.currentThread().getId() : tx.threadId(); lockVer = tx != null ? tx.xidVersion() : cctx.versions().next(); futId = IgniteUuid.randomUuid(); entries = new ArrayList<>(keys.size()); if (log == null) log = U.logger(cctx.kernalContext(), logRef, GridNearLockFuture.class); if (timeout > 0) { timeoutObj = new LockTimeoutObject(); cctx.time().addTimeoutObject(timeoutObj); } valMap = new ConcurrentHashMap8<>(keys.size(), 1f); } /** * @return Participating nodes. */ @Override public Collection<? extends ClusterNode> nodes() { return F.viewReadOnly(futures(), new IgniteClosure<IgniteInternalFuture<?>, ClusterNode>() { @Nullable @Override public ClusterNode apply(IgniteInternalFuture<?> f) { if (isMini(f)) return ((MiniFuture)f).node(); return cctx.discovery().localNode(); } }); } /** {@inheritDoc} */ @Override public GridCacheVersion version() { return lockVer; } /** * @return Entries. */ public List<GridDistributedCacheEntry> entriesCopy() { synchronized (mux) { return new ArrayList<>(entries); } } /** * @return Future ID. */ @Override public IgniteUuid futureId() { return futId; } /** {@inheritDoc} */ @Override public boolean trackable() { return trackable; } /** {@inheritDoc} */ @Override public void markNotTrackable() { trackable = false; } /** * @return {@code True} if transaction is not {@code null}. */ private boolean inTx() { return tx != null; } /** * @return {@code True} if implicit-single-tx flag is set. */ private boolean implicitSingleTx() { return tx != null && tx.implicitSingle(); } /** * @return {@code True} if transaction is not {@code null} and has invalidate flag set. */ private boolean isInvalidate() { return tx != null && tx.isInvalidate(); } /** * @return {@code True} if commit is synchronous. */ private boolean syncCommit() { return tx != null && tx.syncCommit(); } /** * @return {@code True} if rollback is synchronous. */ private boolean syncRollback() { return tx != null && tx.syncRollback(); } /** * @return Transaction isolation or {@code null} if no transaction. */ @Nullable private TransactionIsolation isolation() { return tx == null ? null : tx.isolation(); } /** * @return {@code true} if related transaction is implicit. */ private boolean implicitTx() { return tx != null && tx.implicit(); } /** * @param cached Entry. * @return {@code True} if locked. * @throws GridCacheEntryRemovedException If removed. */ private boolean locked(GridCacheEntryEx cached) throws GridCacheEntryRemovedException { // Reentry-aware check (If filter failed, lock is failed). return cached.lockedLocallyByIdOrThread(lockVer, threadId) && filter(cached); } /** * Adds entry to future. * * @param topVer Topology version. * @param entry Entry to add. * @param dhtNodeId DHT node ID. * @return Lock candidate. * @throws GridCacheEntryRemovedException If entry was removed. */ @Nullable private GridCacheMvccCandidate addEntry(long topVer, GridNearCacheEntry entry, UUID dhtNodeId) throws GridCacheEntryRemovedException { // Check if lock acquisition is timed out. if (timedOut) return null; // Add local lock first, as it may throw GridCacheEntryRemovedException. GridCacheMvccCandidate c = entry.addNearLocal( dhtNodeId, threadId, lockVer, timeout, !inTx(), inTx(), implicitSingleTx() ); if (inTx()) { IgniteTxEntry txEntry = tx.entry(entry.txKey()); txEntry.cached(entry); } if (c != null) c.topologyVersion(topVer); synchronized (mux) { entries.add(entry); } if (c == null && timeout < 0) { if (log.isDebugEnabled()) log.debug("Failed to acquire lock with negative timeout: " + entry); onFailed(false); return null; } // Double check if lock acquisition has already timed out. if (timedOut) { entry.removeLock(lockVer); return null; } return c; } /** * Undoes all locks. * * @param dist If {@code true}, then remove locks from remote nodes as well. */ private void undoLocks(boolean dist) { // Transactions will undo during rollback. if (dist && tx == null) cctx.nearTx().removeLocks(lockVer, keys); else { if (tx != null) { if (tx.setRollbackOnly()) { if (log.isDebugEnabled()) log.debug("Marked transaction as rollback only because locks could not be acquired: " + tx); } else if (log.isDebugEnabled()) log.debug("Transaction was not marked rollback-only while locks were not acquired: " + tx); } for (GridCacheEntryEx e : entriesCopy()) { try { e.removeLock(lockVer); } catch (GridCacheEntryRemovedException ignored) { while (true) { try { e = cctx.cache().peekEx(e.key()); if (e != null) e.removeLock(lockVer); break; } catch (GridCacheEntryRemovedException ignore) { if (log.isDebugEnabled()) log.debug("Attempted to remove lock on removed entry (will retry) [ver=" + lockVer + ", entry=" + e + ']'); } } } } } cctx.mvcc().recheckPendingLocks(); } /** * * @param dist {@code True} if need to distribute lock release. */ private void onFailed(boolean dist) { undoLocks(dist); complete(false); } /** * @param success Success flag. */ public void complete(boolean success) { onComplete(success, true); } /** * @param nodeId Left node ID * @return {@code True} if node was in the list. */ @SuppressWarnings({"ThrowableInstanceNeverThrown"}) @Override public boolean onNodeLeft(UUID nodeId) { boolean found = false; for (IgniteInternalFuture<?> fut : futures()) { if (isMini(fut)) { MiniFuture f = (MiniFuture)fut; if (f.node().id().equals(nodeId)) { if (log.isDebugEnabled()) log.debug("Found mini-future for left node [nodeId=" + nodeId + ", mini=" + f + ", fut=" + this + ']'); f.onResult(newTopologyException(null, nodeId)); found = true; } } } if (!found) { if (log.isDebugEnabled()) log.debug("Near lock future does not have mapping for left node (ignoring) [nodeId=" + nodeId + ", fut=" + this + ']'); } return found; } /** * @param nodeId Sender. * @param res Result. */ void onResult(UUID nodeId, GridNearLockResponse res) { if (!isDone()) { if (log.isDebugEnabled()) log.debug("Received lock response from node [nodeId=" + nodeId + ", res=" + res + ", fut=" + this + ']'); for (IgniteInternalFuture<Boolean> fut : pending()) { if (isMini(fut)) { MiniFuture mini = (MiniFuture)fut; if (mini.futureId().equals(res.miniId())) { assert mini.node().id().equals(nodeId); if (log.isDebugEnabled()) log.debug("Found mini future for response [mini=" + mini + ", res=" + res + ']'); mini.onResult(res); if (log.isDebugEnabled()) log.debug("Future after processed lock response [fut=" + this + ", mini=" + mini + ", res=" + res + ']'); return; } } } U.warn(log, "Failed to find mini future for response (perhaps due to stale message) [res=" + res + ", fut=" + this + ']'); } else if (log.isDebugEnabled()) log.debug("Ignoring lock response from node (future is done) [nodeId=" + nodeId + ", res=" + res + ", fut=" + this + ']'); } /** * @param t Error. */ private void onError(Throwable t) { err.compareAndSet(null, t instanceof GridCacheLockTimeoutException ? null : t); } /** * @param cached Entry to check. * @return {@code True} if filter passed. */ private boolean filter(GridCacheEntryEx cached) { try { if (!cctx.isAll(cached, filter)) { if (log.isDebugEnabled()) log.debug("Filter didn't pass for entry (will fail lock): " + cached); onFailed(true); return false; } return true; } catch (IgniteCheckedException e) { onError(e); return false; } } /** * Callback for whenever entry lock ownership changes. * * @param entry Entry whose lock ownership changed. */ @Override public boolean onOwnerChanged(GridCacheEntryEx entry, GridCacheMvccCandidate owner) { if (owner != null && owner.version().equals(lockVer)) { onDone(true); return true; } return false; } /** * @return {@code True} if locks have been acquired. */ private boolean checkLocks() { if (!isDone() && initialized() && !hasPending()) { for (int i = 0; i < entries.size(); i++) { while (true) { GridCacheEntryEx cached = entries.get(i); try { if (!locked(cached)) { if (log.isDebugEnabled()) log.debug("Lock is still not acquired for entry (will keep waiting) [entry=" + cached + ", fut=" + this + ']'); return false; } break; } // Possible in concurrent cases, when owner is changed after locks // have been released or cancelled. catch (GridCacheEntryRemovedException ignore) { if (log.isDebugEnabled()) log.debug("Got removed entry in onOwnerChanged method (will retry): " + cached); // Replace old entry with new one. entries.set(i, (GridDistributedCacheEntry)cctx.cache().entryEx(cached.key())); } } } if (log.isDebugEnabled()) log.debug("Local lock acquired for entries [fut=" + this + ", entries=" + entries + "]"); onComplete(true, true); return true; } return false; } /** {@inheritDoc} */ @Override public boolean cancel() { if (onCancelled()) onComplete(false, true); return isCancelled(); } /** {@inheritDoc} */ @Override public boolean onDone(Boolean success, Throwable err) { if (log.isDebugEnabled()) log.debug("Received onDone(..) callback [success=" + success + ", err=" + err + ", fut=" + this + ']'); // If locks were not acquired yet, delay completion. if (isDone() || (err == null && success && !checkLocks())) return false; this.err.compareAndSet(null, err instanceof GridCacheLockTimeoutException ? null : err); if (err != null) success = false; return onComplete(success, true); } /** * Completeness callback. * * @param success {@code True} if lock was acquired. * @param distribute {@code True} if need to distribute lock removal in case of failure. * @return {@code True} if complete by this operation. */ private boolean onComplete(boolean success, boolean distribute) { if (log.isDebugEnabled()) log.debug("Received onComplete(..) callback [success=" + success + ", distribute=" + distribute + ", fut=" + this + ']'); if (!success) undoLocks(distribute); if (tx != null) cctx.tm().txContext(tx); if (super.onDone(success, err.get())) { if (log.isDebugEnabled()) log.debug("Completing future: " + this); // Clean up. cctx.mvcc().removeFuture(this); if (timeoutObj != null) cctx.time().removeTimeoutObject(timeoutObj); return true; } return false; } /** {@inheritDoc} */ @Override public int hashCode() { return futId.hashCode(); } /** {@inheritDoc} */ @Override public String toString() { return S.toString(GridNearLockFuture.class, this, "inTx", inTx(), "super", super.toString()); } /** * @param f Future. * @return {@code True} if mini-future. */ private boolean isMini(IgniteInternalFuture<?> f) { return f.getClass().equals(MiniFuture.class); } /** * Basically, future mapping consists from two parts. First, we must determine the topology version this future * will map on. Locking is performed within a user transaction, we must continue to map keys on the same * topology version as it started. If topology version is undefined, we get current topology future and wait * until it completes so the topology is ready to use. * <p/> * During the second part we map keys to primary nodes using topology snapshot we obtained during the first * part. Note that if primary node leaves grid, the future will fail and transaction will be rolled back. */ void map() { // Obtain the topology version to use. GridDiscoveryTopologySnapshot snapshot = tx != null ? tx.topologySnapshot() : cctx.mvcc().lastExplicitLockTopologySnapshot(Thread.currentThread().getId()); if (snapshot != null) { // Continue mapping on the same topology version as it was before. topSnapshot.compareAndSet(null, snapshot); map(keys); markInitialized(); return; } // Must get topology snapshot and map on that version. mapOnTopology(); } /** * Acquires topology future and checks it completeness under the read lock. If it is not complete, * will asynchronously wait for it's completeness and then try again. */ void mapOnTopology() { // We must acquire topology snapshot from the topology version future. try { cctx.topology().readLock(); try { GridDhtTopologyFuture fut = cctx.topologyVersionFuture(); if (fut.isDone()) { GridDiscoveryTopologySnapshot snapshot = fut.topologySnapshot(); if (tx != null) { tx.topologyVersion(snapshot.topologyVersion()); tx.topologySnapshot(snapshot); } topSnapshot.compareAndSet(null, snapshot); map(keys); markInitialized(); } else { fut.listen(new CI1<IgniteInternalFuture<Long>>() { @Override public void apply(IgniteInternalFuture<Long> t) { mapOnTopology(); } }); } } finally { cctx.topology().readUnlock(); } } catch (IgniteCheckedException e) { onDone(e); } } /** * Maps keys to nodes. Note that we can not simply group keys by nodes and send lock request as * such approach does not preserve order of lock acquisition. Instead, keys are split in continuous * groups belonging to one primary node and locks for these groups are acquired sequentially. * * @param keys Keys. */ private void map(Iterable<KeyCacheObject> keys) { try { GridDiscoveryTopologySnapshot snapshot = topSnapshot.get(); assert snapshot != null; long topVer = snapshot.topologyVersion(); assert topVer > 0; if (CU.affinityNodes(cctx, topVer).isEmpty()) { onDone(new ClusterTopologyCheckedException("Failed to map keys for near-only cache (all " + "partition nodes left the grid).")); return; } ConcurrentLinkedDeque8<GridNearLockMapping> mappings = new ConcurrentLinkedDeque8<>(); // Assign keys to primary nodes. GridNearLockMapping map = null; for (KeyCacheObject key : keys) { GridNearLockMapping updated = map(key, map, topVer); // If new mapping was created, add to collection. if (updated != map) { mappings.add(updated); if (tx != null && updated.node().isLocal()) tx.nearLocallyMapped(true); } map = updated; } if (isDone()) { if (log.isDebugEnabled()) log.debug("Abandoning (re)map because future is done: " + this); return; } if (log.isDebugEnabled()) log.debug("Starting (re)map for mappings [mappings=" + mappings + ", fut=" + this + ']'); // Create mini futures. for (Iterator<GridNearLockMapping> iter = mappings.iterator(); iter.hasNext(); ) { GridNearLockMapping mapping = iter.next(); ClusterNode node = mapping.node(); Collection<KeyCacheObject> mappedKeys = mapping.mappedKeys(); assert !mappedKeys.isEmpty(); GridNearLockRequest req = null; Collection<KeyCacheObject> distributedKeys = new ArrayList<>(mappedKeys.size()); boolean explicit = false; for (KeyCacheObject key : mappedKeys) { IgniteTxKey txKey = cctx.txKey(key); while (true) { GridNearCacheEntry entry = null; try { entry = cctx.near().entryExx(key, topVer); if (!cctx.isAll(entry, filter)) { if (log.isDebugEnabled()) log.debug("Entry being locked did not pass filter (will not lock): " + entry); onComplete(false, false); return; } // Removed exception may be thrown here. GridCacheMvccCandidate cand = addEntry(topVer, entry, node.id()); if (isDone()) { if (log.isDebugEnabled()) log.debug("Abandoning (re)map because future is done after addEntry attempt " + "[fut=" + this + ", entry=" + entry + ']'); return; } if (cand != null) { if (tx == null && !cand.reentry()) cctx.mvcc().addExplicitLock(threadId, cand, snapshot); IgniteBiTuple<GridCacheVersion, CacheObject> val = entry.versionedValue(); if (val == null) { GridDhtCacheEntry dhtEntry = dht().peekExx(key); try { if (dhtEntry != null) val = dhtEntry.versionedValue(topVer); } catch (GridCacheEntryRemovedException ignored) { assert dhtEntry.obsolete() : " Got removed exception for non-obsolete entry: " + dhtEntry; if (log.isDebugEnabled()) log.debug("Got removed exception for DHT entry in map (will ignore): " + dhtEntry); } } GridCacheVersion dhtVer = null; if (val != null) { dhtVer = val.get1(); valMap.put(key, val); } if (!cand.reentry()) { if (req == null) { req = new GridNearLockRequest( cctx.cacheId(), topVer, cctx.nodeId(), threadId, futId, lockVer, inTx(), implicitTx(), implicitSingleTx(), read, isolation(), isInvalidate(), timeout, mappedKeys.size(), inTx() ? tx.size() : mappedKeys.size(), inTx() && tx.syncCommit(), inTx() ? tx.groupLockKey() : null, inTx() && tx.partitionLock(), inTx() ? tx.subjectId() : null, inTx() ? tx.taskNameHash() : 0, read ? accessTtl : -1L); mapping.request(req); } distributedKeys.add(key); if (tx != null) tx.addKeyMapping(txKey, mapping.node()); req.addKeyBytes( key, retval && dhtVer == null, dhtVer, // Include DHT version to match remote DHT entry. cctx); } if (cand.reentry()) explicit = tx != null && !entry.hasLockCandidate(tx.xidVersion()); } else // Ignore reentries within transactions. explicit = tx != null && !entry.hasLockCandidate(tx.xidVersion()); if (explicit) tx.addKeyMapping(txKey, mapping.node()); break; } catch (GridCacheEntryRemovedException ignored) { assert entry.obsolete() : "Got removed exception on non-obsolete entry: " + entry; if (log.isDebugEnabled()) log.debug("Got removed entry in lockAsync(..) method (will retry): " + entry); } } // Mark mapping explicit lock flag. if (explicit) { boolean marked = tx != null && tx.markExplicit(node.id()); assert tx == null || marked; } } if (!distributedKeys.isEmpty()) mapping.distributedKeys(distributedKeys); else { assert mapping.request() == null; iter.remove(); } } cctx.mvcc().recheckPendingLocks(); proceedMapping(mappings); } catch (IgniteCheckedException ex) { onError(ex); } } /** * Gets next near lock mapping and either acquires dht locks locally or sends near lock request to * remote primary node. * * @param mappings Queue of mappings. * @throws IgniteCheckedException If mapping can not be completed. */ @SuppressWarnings("unchecked") private void proceedMapping(final ConcurrentLinkedDeque8<GridNearLockMapping> mappings) throws IgniteCheckedException { GridNearLockMapping map = mappings.poll(); // If there are no more mappings to process, complete the future. if (map == null) return; final GridNearLockRequest req = map.request(); final Collection<KeyCacheObject> mappedKeys = map.distributedKeys(); final ClusterNode node = map.node(); if (filter != null && filter.length != 0) req.filter(filter, cctx); if (node.isLocal()) { req.miniId(IgniteUuid.randomUuid()); if (log.isDebugEnabled()) log.debug("Before locally locking near request: " + req); IgniteInternalFuture<GridNearLockResponse> fut = dht().lockAllAsync(cctx, cctx.localNode(), req, filter); // Add new future. add(new GridEmbeddedFuture<>( new C2<GridNearLockResponse, Exception, Boolean>() { @Override public Boolean apply(GridNearLockResponse res, Exception e) { if (CU.isLockTimeoutOrCancelled(e) || (res != null && CU.isLockTimeoutOrCancelled(res.error()))) return false; if (e != null) { onError(e); return false; } if (res == null) { onError(new IgniteCheckedException("Lock response is null for future: " + this)); return false; } if (res.error() != null) { onError(res.error()); return false; } if (log.isDebugEnabled()) log.debug("Acquired lock for local DHT mapping [locId=" + cctx.nodeId() + ", mappedKeys=" + mappedKeys + ", fut=" + GridNearLockFuture.this + ']'); try { int i = 0; for (KeyCacheObject k : mappedKeys) { while (true) { GridNearCacheEntry entry = cctx.near().entryExx(k, req.topologyVersion()); try { IgniteBiTuple<GridCacheVersion, CacheObject> oldValTup = valMap.get(entry.key()); boolean hasBytes = entry.hasValue(); CacheObject oldVal = entry.rawGet(); CacheObject newVal = res.value(i); GridCacheVersion dhtVer = res.dhtVersion(i); GridCacheVersion mappedVer = res.mappedVersion(i); // On local node don't record twice if DHT cache already recorded. boolean record = retval && oldValTup != null && oldValTup.get1().equals(dhtVer); if (newVal == null) { if (oldValTup != null) { if (oldValTup.get1().equals(dhtVer)) newVal = oldValTup.get2(); oldVal = oldValTup.get2(); } } // Lock is held at this point, so we can set the // returned value if any. entry.resetFromPrimary(newVal, lockVer, dhtVer, node.id()); entry.readyNearLock(lockVer, mappedVer, res.committedVersions(), res.rolledbackVersions(), res.pending()); if (inTx() && implicitTx() && tx.onePhaseCommit()) { boolean pass = res.filterResult(i); tx.entry(cctx.txKey(k)).filters(pass ? CU.empty0() : CU.alwaysFalse0Arr()); } if (record) { if (cctx.events().isRecordable(EVT_CACHE_OBJECT_READ)) cctx.events().addEvent( entry.partition(), entry.key(), tx, null, EVT_CACHE_OBJECT_READ, newVal, newVal != null, oldVal, hasBytes, CU.subjectId(tx, cctx.shared()), null, inTx() ? tx.resolveTaskName() : null); if (cctx.cache().configuration().isStatisticsEnabled()) cctx.cache().metrics0().onRead(oldVal != null); } if (log.isDebugEnabled()) log.debug("Processed response for entry [res=" + res + ", entry=" + entry + ']'); break; // Inner while loop. } catch (GridCacheEntryRemovedException ignored) { if (log.isDebugEnabled()) log.debug("Failed to add candidates because entry was " + "removed (will renew)."); // Replace old entry with new one. entries.set(i, (GridDistributedCacheEntry) cctx.cache().entryEx(entry.key())); } } i++; // Increment outside of while loop. } // Proceed and add new future (if any) before completing embedded future. proceedMapping(mappings); } catch (IgniteCheckedException ex) { onError(ex); return false; } return true; } }, fut)); } else { final MiniFuture fut = new MiniFuture(node, mappedKeys, mappings); req.miniId(fut.futureId()); add(fut); // Append new future. IgniteInternalFuture<?> txSync = null; if (inTx()) txSync = cctx.tm().awaitFinishAckAsync(node.id(), tx.threadId()); if (txSync == null || txSync.isDone()) { try { if (log.isDebugEnabled()) log.debug("Sending near lock request [node=" + node.id() + ", req=" + req + ']'); cctx.io().send(node, req, cctx.ioPolicy()); } catch (ClusterTopologyCheckedException ex) { assert fut != null; fut.onResult(ex); } } else { txSync.listen(new CI1<IgniteInternalFuture<?>>() { @Override public void apply(IgniteInternalFuture<?> t) { try { if (log.isDebugEnabled()) log.debug("Sending near lock request [node=" + node.id() + ", req=" + req + ']'); cctx.io().send(node, req, cctx.ioPolicy()); } catch (ClusterTopologyCheckedException ex) { assert fut != null; fut.onResult(ex); } catch (IgniteCheckedException e) { onError(e); } } }); } } } /** * @param mapping Mappings. * @param key Key to map. * @param topVer Topology version. * @return Near lock mapping. * @throws IgniteCheckedException If mapping for key failed. */ private GridNearLockMapping map(KeyCacheObject key, @Nullable GridNearLockMapping mapping, long topVer) throws IgniteCheckedException { assert mapping == null || mapping.node() != null; ClusterNode primary = cctx.affinity().primary(key, topVer); if (cctx.discovery().node(primary.id()) == null) // If primary node left the grid before lock acquisition, fail the whole future. throw newTopologyException(null, primary.id()); if (inTx() && tx.groupLock() && !primary.isLocal()) throw new IgniteCheckedException("Failed to start group lock transaction (local node is not primary for " + " key) [key=" + key + ", primaryNodeId=" + primary.id() + ']'); if (mapping == null || !primary.id().equals(mapping.node().id())) mapping = new GridNearLockMapping(primary, key); else mapping.addKey(key); return mapping; } /** * @return DHT cache. */ private GridDhtTransactionalCacheAdapter<K, V> dht() { return cctx.nearTx().dht(); } /** * Creates new topology exception for cases when primary node leaves grid during mapping. * * @param nested Optional nested exception. * @param nodeId Node ID. * @return Topology exception with user-friendly message. */ private ClusterTopologyCheckedException newTopologyException(@Nullable Throwable nested, UUID nodeId) { return new ClusterTopologyCheckedException("Failed to acquire lock for keys (primary node left grid, " + "retry transaction if possible) [keys=" + keys + ", node=" + nodeId + ']', nested); } /** * Lock request timeout object. */ private class LockTimeoutObject extends GridTimeoutObjectAdapter { /** * Default constructor. */ LockTimeoutObject() { super(timeout); } /** {@inheritDoc} */ @SuppressWarnings({"ThrowableInstanceNeverThrown"}) @Override public void onTimeout() { if (log.isDebugEnabled()) log.debug("Timed out waiting for lock response: " + this); timedOut = true; onComplete(false, true); } /** {@inheritDoc} */ @Override public String toString() { return S.toString(LockTimeoutObject.class, this); } } /** * Mini-future for get operations. Mini-futures are only waiting on a single * node as opposed to multiple nodes. */ private class MiniFuture extends GridFutureAdapter<Boolean> { /** */ private static final long serialVersionUID = 0L; /** */ private final IgniteUuid futId = IgniteUuid.randomUuid(); /** Node ID. */ @GridToStringExclude private ClusterNode node; /** Keys. */ @GridToStringInclude private Collection<KeyCacheObject> keys; /** Mappings to proceed. */ @GridToStringExclude private ConcurrentLinkedDeque8<GridNearLockMapping> mappings; /** */ private AtomicBoolean rcvRes = new AtomicBoolean(false); /** * @param node Node. * @param keys Keys. * @param mappings Mappings to proceed. */ MiniFuture(ClusterNode node, Collection<KeyCacheObject> keys, ConcurrentLinkedDeque8<GridNearLockMapping> mappings) { this.node = node; this.keys = keys; this.mappings = mappings; } /** * @return Future ID. */ IgniteUuid futureId() { return futId; } /** * @return Node ID. */ public ClusterNode node() { return node; } /** * @return Keys. */ public Collection<KeyCacheObject> keys() { return keys; } /** * @param e Error. */ void onResult(Throwable e) { if (rcvRes.compareAndSet(false, true)) { if (log.isDebugEnabled()) log.debug("Failed to get future result [fut=" + this + ", err=" + e + ']'); // Fail. onDone(e); } else U.warn(log, "Received error after another result has been processed [fut=" + GridNearLockFuture.this + ", mini=" + this + ']', e); } /** * @param e Node left exception. */ void onResult(ClusterTopologyCheckedException e) { if (isDone()) return; if (rcvRes.compareAndSet(false, true)) { if (log.isDebugEnabled()) log.debug("Remote node left grid while sending or waiting for reply (will fail): " + this); if (tx != null) tx.removeMapping(node.id()); // Primary node left the grid, so fail the future. GridNearLockFuture.this.onDone(newTopologyException(e, node.id())); onDone(true); } } /** * @param res Result callback. */ void onResult(GridNearLockResponse res) { if (rcvRes.compareAndSet(false, true)) { if (res.error() != null) { if (log.isDebugEnabled()) log.debug("Finishing mini future with an error due to error in response [miniFut=" + this + ", res=" + res + ']'); // Fail. if (res.error() instanceof GridCacheLockTimeoutException) onDone(false); else onDone(res.error()); return; } int i = 0; long topVer = topSnapshot.get().topologyVersion(); for (KeyCacheObject k : keys) { while (true) { GridNearCacheEntry entry = cctx.near().entryExx(k, topVer); try { if (res.dhtVersion(i) == null) { onDone(new IgniteCheckedException("Failed to receive DHT version from remote node " + "(will fail the lock): " + res)); return; } IgniteBiTuple<GridCacheVersion, CacheObject> oldValTup = valMap.get(entry.key()); CacheObject oldVal = entry.rawGet(); boolean hasOldVal = false; CacheObject newVal = res.value(i); boolean readRecordable = false; if (retval) { readRecordable = cctx.events().isRecordable(EVT_CACHE_OBJECT_READ); if (readRecordable) hasOldVal = entry.hasValue(); } GridCacheVersion dhtVer = res.dhtVersion(i); GridCacheVersion mappedVer = res.mappedVersion(i); if (newVal == null) { if (oldValTup != null) { if (oldValTup.get1().equals(dhtVer)) newVal = oldValTup.get2(); oldVal = oldValTup.get2(); } } // Lock is held at this point, so we can set the // returned value if any. entry.resetFromPrimary(newVal, lockVer, dhtVer, node.id()); if (inTx() && implicitTx() && tx.onePhaseCommit()) { boolean pass = res.filterResult(i); tx.entry(cctx.txKey(k)).filters(pass ? CU.empty0() : CU.alwaysFalse0Arr()); } entry.readyNearLock(lockVer, mappedVer, res.committedVersions(), res.rolledbackVersions(), res.pending()); if (retval) { if (readRecordable) cctx.events().addEvent( entry.partition(), entry.key(), tx, null, EVT_CACHE_OBJECT_READ, newVal, newVal != null, oldVal, hasOldVal, CU.subjectId(tx, cctx.shared()), null, inTx() ? tx.resolveTaskName() : null); if (cctx.cache().configuration().isStatisticsEnabled()) cctx.cache().metrics0().onRead(false); } if (log.isDebugEnabled()) log.debug("Processed response for entry [res=" + res + ", entry=" + entry + ']'); break; // Inner while loop. } catch (GridCacheEntryRemovedException ignored) { if (log.isDebugEnabled()) log.debug("Failed to add candidates because entry was removed (will renew)."); // Replace old entry with new one. entries.set(i, (GridDistributedCacheEntry)cctx.cache().entryEx(entry.key())); } catch (IgniteCheckedException e) { onDone(e); return; } } i++; } try { proceedMapping(mappings); } catch (IgniteCheckedException e) { onDone(e); } onDone(true); } } /** {@inheritDoc} */ @Override public String toString() { return S.toString(MiniFuture.class, this, "node", node.id(), "super", super.toString()); } } }
923219d8944f21d3a6abe93629f9132cbd6aedfe
3,273
java
Java
qe/ql/src/java/org/apache/hadoop/hive/ql/udf/UDFWeek.java
tonycody/tencent-tdw
92357724319bbc24f3f0d5563d68d299d237a17f
[ "Apache-1.1" ]
3
2019-11-08T12:47:19.000Z
2021-06-10T19:46:01.000Z
qe/ql/src/java/org/apache/hadoop/hive/ql/udf/UDFWeek.java
tonycody/tencent-tdw
92357724319bbc24f3f0d5563d68d299d237a17f
[ "Apache-1.1" ]
null
null
null
qe/ql/src/java/org/apache/hadoop/hive/ql/udf/UDFWeek.java
tonycody/tencent-tdw
92357724319bbc24f3f0d5563d68d299d237a17f
[ "Apache-1.1" ]
8
2020-03-12T13:42:59.000Z
2021-05-27T06:34:33.000Z
34.452632
151
0.6685
996,104
/** * Tencent is pleased to support the open source community by making TDW available. * Copyright (C) 2014 THL A29 Limited, a Tencent company. All rights reserved. * Licensed under the Apache License, Version 2.0 (the "License"); you may not use * this file except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS * OF ANY KIND, either express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package org.apache.hadoop.hive.ql.udf; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.hive.ql.exec.UDF; import org.apache.hadoop.hive.ql.exec.description; import org.apache.hadoop.hive.serde2.io.TimestampWritable; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; @description(name = "week", value = "_FUNC_(date) - Returns the week of date", extended = "date is a string in the format of 'yyyy-MM-dd HH:mm:ss' or " + "'yyyy-MM-dd','yyyyMMdd'.\n" + "Example:\n " + " > SELECT _FUNC_('2012-05-28 12:58:59') FROM src LIMIT 1;\n" + " 2\n" + " > SELECT _FUNC_('2012-05-28') FROM src LIMIT 1;\n" + " 2" + " > SELECT _FUNC_(20120528) FROM src LIMIT 1;\n" + " 2") public class UDFWeek extends UDF { private static Log LOG = LogFactory.getLog(UDFWeek.class.getName()); private SimpleDateFormat formatter1 = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss"); private SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy-MM-dd"); private Calendar calendar = Calendar.getInstance(); IntWritable result = new IntWritable(); public IntWritable evaluate(Text dateString) { if (dateString == null) { return null; } try { Date date = null; try { date = formatter1.parse(dateString.toString()); } catch (ParseException e1) { try { date = formatter2.parse(dateString.toString()); } catch (ParseException e2) { String time = dateString.toString().trim(); if (time.length() != 8) return null; calendar.set(Calendar.YEAR, Integer.valueOf(time.substring(0, 4))); calendar.set(Calendar.MONTH, Integer.valueOf(time.substring(4, 6)) - 1); calendar.set(Calendar.DAY_OF_MONTH, Integer.valueOf(time.substring(6, 8))); result.set(calendar.get(Calendar.DAY_OF_WEEK)); return result; } } calendar.setTime(date); result.set(calendar.get(Calendar.DAY_OF_WEEK)); return result; } catch (Exception e3) { return null; } } public IntWritable evaluate(TimestampWritable t) { if (t == null) { return null; } try { calendar.setTime(t.getTimestamp()); result.set(calendar.get(Calendar.DAY_OF_WEEK)); return result; } catch (Exception x) { return null; } } }
92321a0d555a5ec124da29f9bb75bcf84add28d3
4,857
java
Java
java/classes/cn/jiguang/b/b.java
gaoht/house
b9e63db1a4975b614c422fed3b5b33ee57ea23fd
[ "Apache-2.0" ]
1
2020-05-08T05:35:32.000Z
2020-05-08T05:35:32.000Z
java/classes/cn/jiguang/b/b.java
gaoht/house
b9e63db1a4975b614c422fed3b5b33ee57ea23fd
[ "Apache-2.0" ]
null
null
null
java/classes/cn/jiguang/b/b.java
gaoht/house
b9e63db1a4975b614c422fed3b5b33ee57ea23fd
[ "Apache-2.0" ]
3
2018-09-07T08:15:08.000Z
2020-05-22T03:59:12.000Z
25.165803
109
0.597282
996,105
package cn.jiguang.b; import android.os.Binder; import android.os.IBinder; import android.os.IInterface; import android.os.Parcel; public abstract class b extends Binder implements a { private static final String z; static { Object localObject1 = "o\0230#&k\b'(\"\034p-=c\024zg\006H\034j(\034d\034l,".toCharArray(); int j = localObject1.length; int m = 0; int i = 0; Object localObject2 = localObject1; int k = j; label30: int n; if (j <= 1) { m = i; k = i; localObject2 = localObject1; n = localObject2[k]; switch (m % 5) { default: i = 79; } } for (;;) { localObject2[k] = ((char)(i ^ n)); m += 1; if (j == 0) { k = j; break label30; } k = j; localObject2 = localObject1; localObject1 = localObject2; j = k; i = m; if (k > m) { break; } z = new String((char[])localObject2).intern(); return; i = 12; continue; i = 125; continue; i = 30; continue; i = 73; } } public b() { attachInterface(this, z); } public static a a(IBinder paramIBinder) { if (paramIBinder == null) { return null; } IInterface localIInterface = paramIBinder.queryLocalInterface(z); if ((localIInterface != null) && ((localIInterface instanceof a))) { return (a)localIInterface; } return new c(paramIBinder); } public IBinder asBinder() { return this; } public boolean onTransact(int paramInt1, Parcel paramParcel1, Parcel paramParcel2, int paramInt2) { int i = 0; boolean bool2 = false; int j = 0; boolean bool1 = false; long l; String str; switch (paramInt1) { default: return super.onTransact(paramInt1, paramParcel1, paramParcel2, paramInt2); case 1598968902: paramParcel2.writeString(z); return true; case 1: paramParcel1.enforceInterface(z); paramInt1 = paramParcel1.readInt(); l = paramParcel1.readLong(); if (paramParcel1.readInt() != 0) { bool1 = true; } a(paramInt1, l, bool1, paramParcel1.readFloat(), paramParcel1.readDouble(), paramParcel1.readString()); paramParcel2.writeNoException(); return true; case 2: paramParcel1.enforceInterface(z); paramInt1 = a(paramParcel1.readString(), paramParcel1.readInt()); paramParcel2.writeNoException(); paramParcel2.writeInt(paramInt1); return true; case 3: paramParcel1.enforceInterface(z); b(paramParcel1.readString(), paramParcel1.readInt()); paramParcel2.writeNoException(); return true; case 4: paramParcel1.enforceInterface(z); l = a(paramParcel1.readString(), paramParcel1.readLong()); paramParcel2.writeNoException(); paramParcel2.writeLong(l); return true; case 5: paramParcel1.enforceInterface(z); b(paramParcel1.readString(), paramParcel1.readLong()); paramParcel2.writeNoException(); return true; case 6: paramParcel1.enforceInterface(z); str = paramParcel1.readString(); if (paramParcel1.readInt() != 0) {} for (bool1 = true;; bool1 = false) { bool1 = a(str, bool1); paramParcel2.writeNoException(); paramInt1 = i; if (bool1) { paramInt1 = 1; } paramParcel2.writeInt(paramInt1); return true; } case 7: paramParcel1.enforceInterface(z); str = paramParcel1.readString(); bool1 = bool2; if (paramParcel1.readInt() != 0) { bool1 = true; } b(str, bool1); paramParcel2.writeNoException(); return true; case 8: paramParcel1.enforceInterface(z); paramParcel1 = a(paramParcel1.readString(), paramParcel1.readString()); paramParcel2.writeNoException(); paramParcel2.writeString(paramParcel1); return true; case 9: paramParcel1.enforceInterface(z); b(paramParcel1.readString(), paramParcel1.readString()); paramParcel2.writeNoException(); return true; case 10: paramParcel1.enforceInterface(z); bool1 = a(); paramParcel2.writeNoException(); paramInt1 = j; if (bool1) { paramInt1 = 1; } paramParcel2.writeInt(paramInt1); return true; } paramParcel1.enforceInterface(z); paramParcel1 = c(paramParcel1.readString(), paramParcel1.readString()); paramParcel2.writeNoException(); paramParcel2.writeStrongBinder(paramParcel1); return true; } } /* Location: /Users/gaoht/Downloads/zirom/classes-dex2jar.jar!/cn/jiguang/b/b.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */
92321a34e2c0cefccb5a1af313420815f13b58f3
1,966
java
Java
cyclops/src/test/java/com/oath/cyclops/util/stream/reactivestreams/TckWhiteBoxSubscriberTest.java
andyglick/cyclops-react
dc26bdad0f2b8a5aa87de4aa946ed52a0dbf00de
[ "ECL-2.0", "Apache-2.0" ]
937
2015-06-02T10:36:23.000Z
2022-03-28T11:16:22.000Z
cyclops/src/test/java/com/oath/cyclops/util/stream/reactivestreams/TckWhiteBoxSubscriberTest.java
preuss/cyclops
0be977662db87d2aaeac391a458ab3de0fe70d9b
[ "Apache-2.0" ]
631
2016-02-23T14:55:57.000Z
2018-09-27T16:57:13.000Z
cyclops/src/test/java/com/oath/cyclops/util/stream/reactivestreams/TckWhiteBoxSubscriberTest.java
preuss/cyclops
0be977662db87d2aaeac391a458ab3de0fe70d9b
[ "Apache-2.0" ]
118
2015-06-08T14:14:52.000Z
2022-03-18T18:43:32.000Z
28.911765
96
0.587487
996,106
package com.oath.cyclops.util.stream.reactivestreams; import com.oath.cyclops.types.reactive.QueueBasedSubscriber; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import org.reactivestreams.tck.SubscriberWhiteboxVerification; import org.reactivestreams.tck.TestEnvironment; import org.testng.annotations.Test; @Test public class TckWhiteBoxSubscriberTest extends SubscriberWhiteboxVerification<Long>{ public TckWhiteBoxSubscriberTest() { super(new TestEnvironment(300L)); } @Override public Long createElement(int element) { return new Long(element); } @Override public Subscriber<Long> createSubscriber( org.reactivestreams.tck.SubscriberWhiteboxVerification.WhiteboxSubscriberProbe<Long> probe) { return new QueueBasedSubscriber<Long>(new QueueBasedSubscriber.Counter(),500) { @Override public void onSubscribe(final Subscription rsSubscription) { probe.registerOnSubscribe(new SubscriberPuppet() { @Override public void triggerRequest(long elements) { rsSubscription.request(elements); } @Override public void signalCancel() { rsSubscription.cancel(); } }); super.onSubscribe(rsSubscription); } @Override public void onNext(Long aLong) { probe.registerOnNext(aLong); super.onNext(aLong); } @Override public void onError(Throwable t) { probe.registerOnError(t); super.onError(t); } @Override public void onComplete() { probe.registerOnComplete(); super.onComplete(); } }; } }
92321bf97cc5705ba3890e40b0a9a6af50148234
917
java
Java
app/src/main/java/com/example/pkmntr/greatweatherapp/models/WeatherModels/Response.java
PKMNTR/simple-weather-app
61ba68fba6c25a8722ae716e5caa9012099d97c1
[ "MIT" ]
null
null
null
app/src/main/java/com/example/pkmntr/greatweatherapp/models/WeatherModels/Response.java
PKMNTR/simple-weather-app
61ba68fba6c25a8722ae716e5caa9012099d97c1
[ "MIT" ]
null
null
null
app/src/main/java/com/example/pkmntr/greatweatherapp/models/WeatherModels/Response.java
PKMNTR/simple-weather-app
61ba68fba6c25a8722ae716e5caa9012099d97c1
[ "MIT" ]
null
null
null
20.840909
64
0.68157
996,107
package com.example.pkmntr.greatweatherapp.models.WeatherModels; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class Response { @SerializedName("version") @Expose private String version; @SerializedName("termsofService") @Expose private String termsofService; @SerializedName("features") @Expose private Features features; public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public String getTermsofService() { return termsofService; } public void setTermsofService(String termsofService) { this.termsofService = termsofService; } public Features getFeatures() { return features; } public void setFeatures(Features features) { this.features = features; } }
92321d0fd37ff15ec19f1576a863f3d7cc7ab36b
6,170
java
Java
heros-api-web/src/main/java/name/anonymous/heros/api/web/repository/ProductLineItemRepository.java
anonymous9876/heros-api
ec8996e6ceeb5daf0ea5fb42a83135c92f329ed1
[ "MIT" ]
null
null
null
heros-api-web/src/main/java/name/anonymous/heros/api/web/repository/ProductLineItemRepository.java
anonymous9876/heros-api
ec8996e6ceeb5daf0ea5fb42a83135c92f329ed1
[ "MIT" ]
null
null
null
heros-api-web/src/main/java/name/anonymous/heros/api/web/repository/ProductLineItemRepository.java
anonymous9876/heros-api
ec8996e6ceeb5daf0ea5fb42a83135c92f329ed1
[ "MIT" ]
null
null
null
44.710145
129
0.759157
996,108
package name.anonymous.heros.api.web.repository; import java.time.LocalDate; import java.util.List; import java.util.UUID; import javax.persistence.EntityManager; import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.JoinType; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.fasterxml.jackson.databind.ObjectMapper; import name.anonymous.heros.api.web.model.entity.Mission; import name.anonymous.heros.api.web.model.entity.ProductLineItem; import name.anonymous.heros.api.web.pagination.query.builder.jpa.criteria.model.result.JpaQueryResult; import name.anonymous.heros.api.web.pagination.rest.RestPaginationCriteria; import name.anonymous.heros.api.web.pagination.rest.util.hibernate.HibernatePaginationService; import name.anonymous.heros.api.web.repository.configuration.hibernate.integrator.MetadataExtractorIntegrator; @Repository public class ProductLineItemRepository {// extends CrudRepository<ProductLineItem, UUID> @Autowired private EntityManager em; @Autowired private HibernatePaginationService hpc; @Autowired private ObjectMapper objectMapper; private static final String ALIAS_ORDER = "o"; private static final String ALIAS_PRODUCT = "p"; private static final String QUERY_FROM = " FROM " + ProductLineItem.class.getName() + " " + ALIAS_PRODUCT + " "; private static final String QUERY_WHERE = ALIAS_PRODUCT + ".mission.num = :idMission "; // public Iterable<ProductLineItem> findAll(String buCode, String hero, UUID idMission, // RestPaginationCriteria restPaginationCriteria) { // TypedQuery<ProductLineItem> typedQuery = em // .createQuery("select " + ALIAS_PRODUCT // + QUERY_FROM // + " JOIN FETCH " + ALIAS_PRODUCT +".mission" + " " + ALIAS_ORDER + " " // + hpc.formatWhere(hpc.and(QUERY_WHERE, // hpc.getWhereQuery(ALIAS_PRODUCT, restPaginationCriteria), // hpc.getGlobalSearchQuery(ALIAS_ORDER, restPaginationCriteria, // getSelectProductLineItemEntityPropertyPaths())) // ) // + hpc.getOrderBy(ALIAS_PRODUCT, restPaginationCriteria), // ProductLineItem.class); // hpc.addWhereParams(ALIAS_PRODUCT, restPaginationCriteria, typedQuery); // hpc.addGlobalSearchParams(restPaginationCriteria, typedQuery); // return typedQuery // .setParameter("idMission", idMission) // .setFirstResult(restPaginationCriteria.getOffset()) // .setMaxResults(restPaginationCriteria.getLimit()) // .getResultList(); // } public Iterable<ProductLineItem> findAll(String buCode, String hero, UUID idMission, RestPaginationCriteria restPaginationCriteria) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<ProductLineItem> cq = cb.createQuery(ProductLineItem.class); Root<ProductLineItem> r = cq.from(ProductLineItem.class); r.fetch("mission", JoinType.LEFT); JpaQueryResult jpaQueryResult = restPaginationCriteria.getJpaQueryResult(cb, r, cq, objectMapper); Predicate where = cb.conjunction(); where.getExpressions().add(cb.equal(r.get("mission"), em.getReference(Mission.class, idMission))); if (jpaQueryResult != null) { where.getExpressions().add(jpaQueryResult.getPredicate()); } cq.where(where); TypedQuery<ProductLineItem> q = em.createQuery(cq) .setFirstResult(restPaginationCriteria.getOffset()) .setMaxResults(restPaginationCriteria.getLimit()); return q.getResultList(); } public Long getCountBeforeFiltering(String buCode, String hero, UUID idMission, RestPaginationCriteria restPaginationCriteria) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Long> cq = cb.createQuery(Long.class); Root<ProductLineItem> r = cq.from(ProductLineItem.class); cq.select(cb.count(r)); Predicate where = cb.conjunction(); cq.where(where); where.getExpressions().add(cb.equal(r.get("mission"), em.getReference(Mission.class, idMission))); return em.createQuery(cq) .getSingleResult(); } // public Long getCountAfterFiltering(String buCode, String hero, UUID idMission, // RestPaginationCriteria restPaginationCriteria) { // TypedQuery<Long> typedQuery = em.createQuery("select count(*)" + QUERY_FROM + // hpc.formatWhere(hpc.and(QUERY_WHERE, // hpc.getWhereQuery(ALIAS_PRODUCT, restPaginationCriteria), // hpc.getGlobalSearchQuery(ALIAS_ORDER, restPaginationCriteria, // getSelectProductLineItemEntityPropertyPaths())) // ), Long.class); // hpc.addWhereParams(ALIAS_PRODUCT, restPaginationCriteria, typedQuery); // hpc.addGlobalSearchParams(restPaginationCriteria, typedQuery); // return typedQuery.setParameter("idMission", idMission) // .getSingleResult(); // } public Long getCountAfterFiltering(String buCode, String hero, UUID idMission, RestPaginationCriteria restPaginationCriteria) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Long> cq = cb.createQuery(Long.class); Root<ProductLineItem> r = cq.from(ProductLineItem.class); cq.select(cb.count(r)); JpaQueryResult jpaQueryResult = restPaginationCriteria.getJpaQueryResult(cb, r, cq, objectMapper); Predicate where = cb.conjunction(); cq.where(where); where.getExpressions().add(cb.equal(r.get("mission"), em.getReference(Mission.class, idMission))); if (jpaQueryResult != null) { where.getExpressions().add(jpaQueryResult.getPredicate()); } return em.createQuery(cq).getSingleResult(); } public List<String> getSelectProductLineItemEntityPropertyPaths() { return MetadataExtractorIntegrator.INSTANCE.getEntityPropertyPaths(ProductLineItem.class); } public void changeProductLineItemShippingAddress(UUID ProductLineItemId, LocalDate shippingAddress) { ProductLineItem ProductLineItem = em.find(ProductLineItem.class, ProductLineItemId); ProductLineItem.setDateLivAnnon(shippingAddress); em.merge(ProductLineItem); } }
92321d59e1f60f04e6da564bde7126b7bbb61186
44,688
java
Java
javafx-sdk-11.0.2/lib/src/javafx.controls/javafx/scene/chart/StackedAreaChart.java
carlcastillo9818/JavaFXBankApp
38a785e97dadcad1c9851b70680704a6d58cf875
[ "MIT" ]
3
2021-04-11T16:24:41.000Z
2021-06-16T09:09:28.000Z
javafx-sdk-11.0.2/lib/src/javafx.controls/javafx/scene/chart/StackedAreaChart.java
carlcastillo9818/JavaFXBankApp
38a785e97dadcad1c9851b70680704a6d58cf875
[ "MIT" ]
null
null
null
javafx-sdk-11.0.2/lib/src/javafx.controls/javafx/scene/chart/StackedAreaChart.java
carlcastillo9818/JavaFXBankApp
38a785e97dadcad1c9851b70680704a6d58cf875
[ "MIT" ]
1
2021-07-22T19:45:22.000Z
2021-07-22T19:45:22.000Z
49.270121
158
0.532112
996,109
/* * Copyright (c) 2011, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javafx.scene.chart; import java.util.*; import javafx.animation.*; import javafx.application.Platform; import javafx.beans.NamedArg; import javafx.beans.property.DoubleProperty; import javafx.beans.property.SimpleDoubleProperty; import javafx.collections.FXCollections; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import javafx.scene.AccessibleRole; import javafx.scene.Group; import javafx.scene.Node; import javafx.scene.layout.StackPane; import javafx.scene.shape.*; import javafx.util.Duration; import com.sun.javafx.charts.Legend.LegendItem; import javafx.css.converter.BooleanConverter; import javafx.beans.property.BooleanProperty; import javafx.beans.value.WritableValue; import javafx.css.CssMetaData; import javafx.css.Styleable; import javafx.css.StyleableBooleanProperty; import javafx.css.StyleableProperty; /** * StackedAreaChart is a variation of {@link AreaChart} that displays trends of the * contribution of each value. (over time e.g.) The areas are stacked so that each * series adjoins but does not overlap the preceding series. This contrasts with * the Area chart where each series overlays the preceding series. * * The cumulative nature of the StackedAreaChart gives an idea of the total Y data * value at any given point along the X axis. * * Since data points across multiple series may not be common, StackedAreaChart * interpolates values along the line joining the data points whenever necessary. * * @since JavaFX 2.1 */ public class StackedAreaChart<X,Y> extends XYChart<X,Y> { // -------------- PRIVATE FIELDS ------------------------------------------ /** A multiplier for teh Y values that we store for each series, it is used to animate in a new series */ private Map<Series<X,Y>, DoubleProperty> seriesYMultiplierMap = new HashMap<>(); // -------------- PUBLIC PROPERTIES ---------------------------------------- /** * When true, CSS styleable symbols are created for any data items that * don't have a symbol node specified. * @since JavaFX 8.0 */ private BooleanProperty createSymbols = new StyleableBooleanProperty(true) { @Override protected void invalidated() { for (int seriesIndex = 0; seriesIndex < getData().size(); seriesIndex++) { Series<X, Y> series = getData().get(seriesIndex); for (int itemIndex = 0; itemIndex < series.getData().size(); itemIndex++) { Data<X, Y> item = series.getData().get(itemIndex); Node symbol = item.getNode(); if (get() && symbol == null) { // create any symbols symbol = createSymbol(series, getData().indexOf(series), item, itemIndex); if (null != symbol) { getPlotChildren().add(symbol); } } else if (!get() && symbol != null) { // remove symbols getPlotChildren().remove(symbol); symbol = null; item.setNode(null); } } } requestChartLayout(); } public Object getBean() { return this; } public String getName() { return "createSymbols"; } public CssMetaData<StackedAreaChart<?, ?>,Boolean> getCssMetaData() { return StyleableProperties.CREATE_SYMBOLS; } }; /** * Indicates whether symbols for data points will be created or not. * * @return true if symbols for data points will be created and false otherwise. * @since JavaFX 8.0 */ public final boolean getCreateSymbols() { return createSymbols.getValue(); } public final void setCreateSymbols(boolean value) { createSymbols.setValue(value); } public final BooleanProperty createSymbolsProperty() { return createSymbols; } // -------------- CONSTRUCTORS ---------------------------------------------- /** * Construct a new Area Chart with the given axis * * @param xAxis The x axis to use * @param yAxis The y axis to use */ public StackedAreaChart(@NamedArg("xAxis") Axis<X> xAxis, @NamedArg("yAxis") Axis<Y> yAxis) { this(xAxis,yAxis, FXCollections.<Series<X,Y>>observableArrayList()); } /** * Construct a new Area Chart with the given axis and data. * <p> * Note: yAxis must be a ValueAxis, otherwise {@code IllegalArgumentException} is thrown. * * @param xAxis The x axis to use * @param yAxis The y axis to use * @param data The data to use, this is the actual list used so any changes to it will be reflected in the chart * * @throws java.lang.IllegalArgumentException if yAxis is not a ValueAxis */ public StackedAreaChart(@NamedArg("xAxis") Axis<X> xAxis, @NamedArg("yAxis") Axis<Y> yAxis, @NamedArg("data") ObservableList<Series<X,Y>> data) { super(xAxis,yAxis); if (!(yAxis instanceof ValueAxis)) { throw new IllegalArgumentException("Axis type incorrect, yAxis must be of ValueAxis type."); } setData(data); } // -------------- METHODS ------------------------------------------------------------------------------------------ private static double doubleValue(Number number) { return doubleValue(number, 0); } private static double doubleValue(Number number, double nullDefault) { return (number == null) ? nullDefault : number.doubleValue(); } @Override protected void dataItemAdded(Series<X,Y> series, int itemIndex, Data<X,Y> item) { final Node symbol = createSymbol(series, getData().indexOf(series), item, itemIndex); if (shouldAnimate()) { boolean animate = false; if (itemIndex > 0 && itemIndex < (series.getData().size()-1)) { animate = true; Data<X,Y> p1 = series.getData().get(itemIndex - 1); Data<X,Y> p2 = series.getData().get(itemIndex + 1); double x1 = getXAxis().toNumericValue(p1.getXValue()); double y1 = getYAxis().toNumericValue(p1.getYValue()); double x3 = getXAxis().toNumericValue(p2.getXValue()); double y3 = getYAxis().toNumericValue(p2.getYValue()); double x2 = getXAxis().toNumericValue(item.getXValue()); double y2 = getYAxis().toNumericValue(item.getYValue()); // //1. y intercept of the line : y = ((y3-y1)/(x3-x1)) * x2 + (x3y1 - y3x1)/(x3 -x1) double y = ((y3-y1)/(x3-x1)) * x2 + (x3*y1 - y3*x1)/(x3-x1); item.setCurrentY(getYAxis().toRealValue(y)); item.setCurrentX(getXAxis().toRealValue(x2)); //2. we can simply use the midpoint on the line as well.. // double x = (x3 + x1)/2; // double y = (y3 + y1)/2; // item.setCurrentX(x); // item.setCurrentY(y); } else if (itemIndex == 0 && series.getData().size() > 1) { animate = true; item.setCurrentX(series.getData().get(1).getXValue()); item.setCurrentY(series.getData().get(1).getYValue()); } else if (itemIndex == (series.getData().size() - 1) && series.getData().size() > 1) { animate = true; int last = series.getData().size() - 2; item.setCurrentX(series.getData().get(last).getXValue()); item.setCurrentY(series.getData().get(last).getYValue()); } else if (symbol != null) { // fade in new symbol symbol.setOpacity(0); getPlotChildren().add(symbol); FadeTransition ft = new FadeTransition(Duration.millis(500),symbol); ft.setToValue(1); ft.play(); } if (animate) { animate( new KeyFrame(Duration.ZERO, (e) -> { if (symbol != null && !getPlotChildren().contains(symbol)) { getPlotChildren().add(symbol); } }, new KeyValue(item.currentYProperty(), item.getCurrentY()), new KeyValue(item.currentXProperty(), item.getCurrentX()) ), new KeyFrame(Duration.millis(800), new KeyValue(item.currentYProperty(), item.getYValue(), Interpolator.EASE_BOTH), new KeyValue(item.currentXProperty(), item.getXValue(), Interpolator.EASE_BOTH)) ); } } else if (symbol != null) { getPlotChildren().add(symbol); } } @Override protected void dataItemRemoved(final Data<X,Y> item, final Series<X,Y> series) { final Node symbol = item.getNode(); if (symbol != null) { symbol.focusTraversableProperty().unbind(); } // remove item from sorted list int itemIndex = series.getItemIndex(item); if (shouldAnimate()) { boolean animate = false; // dataSize represents size of currently visible data. After this operation, the number will decrement by 1 final int dataSize = series.getDataSize(); // This is the size of current data list in Series. Note that it might be totaly different from dataSize as // some big operation might have happened on the list. final int dataListSize = series.getData().size(); if (itemIndex > 0 && itemIndex < dataSize - 1) { animate = true; Data<X,Y> p1 = series.getItem(itemIndex - 1); Data<X,Y> p2 = series.getItem(itemIndex + 1); double x1 = getXAxis().toNumericValue(p1.getXValue()); double y1 = getYAxis().toNumericValue(p1.getYValue()); double x3 = getXAxis().toNumericValue(p2.getXValue()); double y3 = getYAxis().toNumericValue(p2.getYValue()); double x2 = getXAxis().toNumericValue(item.getXValue()); double y2 = getYAxis().toNumericValue(item.getYValue()); // //1. y intercept of the line : y = ((y3-y1)/(x3-x1)) * x2 + (x3y1 - y3x1)/(x3 -x1) double y = ((y3-y1)/(x3-x1)) * x2 + (x3*y1 - y3*x1)/(x3-x1); item.setCurrentX(getXAxis().toRealValue(x2)); item.setCurrentY(getYAxis().toRealValue(y2)); item.setXValue(getXAxis().toRealValue(x2)); item.setYValue(getYAxis().toRealValue(y)); //2. we can simply use the midpoint on the line as well.. // double x = (x3 + x1)/2; // double y = (y3 + y1)/2; // item.setCurrentX(x); // item.setCurrentY(y); } else if (itemIndex == 0 && dataListSize > 1) { animate = true; item.setXValue(series.getData().get(0).getXValue()); item.setYValue(series.getData().get(0).getYValue()); } else if (itemIndex == (dataSize - 1) && dataListSize > 1) { animate = true; int last = dataListSize - 1; item.setXValue(series.getData().get(last).getXValue()); item.setYValue(series.getData().get(last).getYValue()); } else if (symbol != null) { // fade out symbol symbol.setOpacity(0); FadeTransition ft = new FadeTransition(Duration.millis(500),symbol); ft.setToValue(0); ft.setOnFinished(actionEvent -> { getPlotChildren().remove(symbol); removeDataItemFromDisplay(series, item); symbol.setOpacity(1.0); }); ft.play(); } else { item.setSeries(null); removeDataItemFromDisplay(series, item); } if (animate) { animate( new KeyFrame(Duration.ZERO, new KeyValue(item.currentYProperty(), item.getCurrentY()), new KeyValue(item.currentXProperty(), item.getCurrentX())), new KeyFrame(Duration.millis(800), actionEvent -> { getPlotChildren().remove(symbol); removeDataItemFromDisplay(series, item); }, new KeyValue(item.currentYProperty(), item.getYValue(), Interpolator.EASE_BOTH), new KeyValue(item.currentXProperty(), item.getXValue(), Interpolator.EASE_BOTH)) ); } } else { getPlotChildren().remove(symbol); removeDataItemFromDisplay(series, item); } //Note: better animation here, point should move from old position to new position at center point between prev and next symbols } /** {@inheritDoc} */ @Override protected void dataItemChanged(Data<X, Y> item) { } @Override protected void seriesChanged(ListChangeListener.Change<? extends Series> c) { // Update style classes for all series lines and symbols for (int i = 0; i < getDataSize(); i++) { final Series<X,Y> s = getData().get(i); Path seriesLine = (Path)((Group)s.getNode()).getChildren().get(1); Path fillPath = (Path)((Group)s.getNode()).getChildren().get(0); seriesLine.getStyleClass().setAll("chart-series-area-line", "series" + i, s.defaultColorStyleClass); fillPath.getStyleClass().setAll("chart-series-area-fill", "series" + i, s.defaultColorStyleClass); for (int j=0; j < s.getData().size(); j++) { final Data<X,Y> item = s.getData().get(j); final Node node = item.getNode(); if(node!=null) node.getStyleClass().setAll("chart-area-symbol", "series" + i, "data" + j, s.defaultColorStyleClass); } } } @Override protected void seriesAdded(Series<X,Y> series, int seriesIndex) { // create new paths for series Path seriesLine = new Path(); Path fillPath = new Path(); seriesLine.setStrokeLineJoin(StrokeLineJoin.BEVEL); fillPath.setStrokeLineJoin(StrokeLineJoin.BEVEL); Group areaGroup = new Group(fillPath,seriesLine); series.setNode(areaGroup); // create series Y multiplier DoubleProperty seriesYAnimMultiplier = new SimpleDoubleProperty(this, "seriesYMultiplier"); seriesYMultiplierMap.put(series, seriesYAnimMultiplier); // handle any data already in series if (shouldAnimate()) { seriesYAnimMultiplier.setValue(0d); } else { seriesYAnimMultiplier.setValue(1d); } getPlotChildren().add(areaGroup); List<KeyFrame> keyFrames = new ArrayList<KeyFrame>(); if (shouldAnimate()) { // animate in new series keyFrames.add(new KeyFrame(Duration.ZERO, new KeyValue(areaGroup.opacityProperty(), 0), new KeyValue(seriesYAnimMultiplier, 0) )); keyFrames.add(new KeyFrame(Duration.millis(200), new KeyValue(areaGroup.opacityProperty(), 1) )); keyFrames.add(new KeyFrame(Duration.millis(500), new KeyValue(seriesYAnimMultiplier, 1) )); } for (int j=0; j<series.getData().size(); j++) { Data<X,Y> item = series.getData().get(j); final Node symbol = createSymbol(series, seriesIndex, item, j); if (symbol != null) { if (shouldAnimate()) symbol.setOpacity(0); getPlotChildren().add(symbol); if (shouldAnimate()) { // fade in new symbol keyFrames.add(new KeyFrame(Duration.ZERO, new KeyValue(symbol.opacityProperty(), 0))); keyFrames.add(new KeyFrame(Duration.millis(200), new KeyValue(symbol.opacityProperty(), 1))); } } } if (shouldAnimate()) animate(keyFrames.toArray(new KeyFrame[keyFrames.size()])); } @Override protected void seriesRemoved(final Series<X,Y> series) { // remove series Y multiplier seriesYMultiplierMap.remove(series); // remove all symbol nodes if (shouldAnimate()) { Timeline tl = new Timeline(createSeriesRemoveTimeLine(series, 400)); tl.play(); } else { getPlotChildren().remove(series.getNode()); for (Data<X,Y> d:series.getData()) getPlotChildren().remove(d.getNode()); removeSeriesFromDisplay(series); } } /** {@inheritDoc} */ @Override protected void updateAxisRange() { // This override is necessary to update axis range based on cumulative Y value for the // Y axis instead of the normal way where max value in the data range is used. final Axis<X> xa = getXAxis(); final Axis<Y> ya = getYAxis(); if (xa.isAutoRanging()) { List xData = new ArrayList<Number>(); for(Series<X,Y> series : getData()) { for(Data<X,Y> data: series.getData()) { xData.add(data.getXValue()); } } xa.invalidateRange(xData); } if (ya.isAutoRanging()) { double totalMinY = Double.MAX_VALUE; Iterator<Series<X, Y>> seriesIterator = getDisplayedSeriesIterator(); boolean first = true; NavigableMap<Double, Double> accum = new TreeMap<>(); NavigableMap<Double, Double> prevAccum = new TreeMap<>(); NavigableMap<Double, Double> currentValues = new TreeMap<>(); while (seriesIterator.hasNext()) { currentValues.clear(); Series<X, Y> series = seriesIterator.next(); for(Data<X,Y> item : series.getData()) { if(item != null) { final double xv = xa.toNumericValue(item.getXValue()); final double yv = ya.toNumericValue(item.getYValue()); currentValues.put(xv, yv); if (first) { // On the first pass, just fill the map accum.put(xv, yv); // minimum is applicable only in the first series totalMinY = Math.min(totalMinY, yv); } else { if (prevAccum.containsKey(xv)) { accum.put(xv, prevAccum.get(xv) + yv); } else { // If the point wasn't yet in the previous (accumulated) series Map.Entry<Double, Double> he = prevAccum.higherEntry(xv); Map.Entry<Double, Double> le = prevAccum.lowerEntry(xv); if (he != null && le != null) { // If there's both point above and below this point, interpolate accum.put(xv, ((xv - le.getKey()) / (he.getKey() - le.getKey())) * (le.getValue() + he.getValue()) + yv); } else if (he != null) { // The point is before the first point in the previously accumulated series accum.put(xv, he.getValue() + yv); } else if (le != null) { // The point is after the last point in the previously accumulated series accum.put(xv, le.getValue() + yv); } else { // The previously accumulated series is empty accum.put(xv, yv); } } } } } // Now update all the keys that were in the previous series, but not in the new one for (Map.Entry<Double, Double> e : prevAccum.entrySet()) { if (accum.keySet().contains(e.getKey())) { continue; } Double k = e.getKey(); final Double v = e.getValue(); // Look at the values of the current series Map.Entry<Double, Double> he = currentValues.higherEntry(k); Map.Entry<Double, Double> le = currentValues.lowerEntry(k); if (he != null && le != null) { // Interpolate the for the point from current series and add the accumulated value accum.put(k, ((k - le.getKey()) / (he.getKey() - le.getKey())) * (le.getValue() + he.getValue()) + v); } else if (he != null) { // There accumulated value is before the first value in the current series accum.put(k, he.getValue() + v); } else if (le != null) { // There accumulated value is after the last value in the current series accum.put(k, le.getValue() + v); } else { // The current series are empty accum.put(k, v); } } prevAccum.clear(); prevAccum.putAll(accum); accum.clear(); first = (totalMinY == Double.MAX_VALUE); // If there was already some value in the series, we can consider as // being past the first series } if(totalMinY != Double.MAX_VALUE) ya.invalidateRange(Arrays.asList(ya.toRealValue(totalMinY), ya.toRealValue(Collections.max(prevAccum.values())))); } } /** {@inheritDoc} */ @Override protected void layoutPlotChildren() { ArrayList<DataPointInfo<X, Y>> currentSeriesData = new ArrayList<>(); // AggregateData hold the data points of both the current and the previous series. // The goal is to collect all the data, sort it and iterate. ArrayList<DataPointInfo<X, Y>> aggregateData = new ArrayList<>(); for (int seriesIndex=0; seriesIndex < getDataSize(); seriesIndex++) { // for every series Series<X, Y> series = getData().get(seriesIndex); aggregateData.clear(); // copy currentSeriesData accumulated in the previous iteration to aggregate. for(DataPointInfo<X, Y> data : currentSeriesData) { data.partOf = PartOf.PREVIOUS; aggregateData.add(data); } currentSeriesData.clear(); // now copy actual data of the current series. for (Iterator<Data<X, Y>> it = getDisplayedDataIterator(series); it.hasNext(); ) { Data<X, Y> item = it.next(); DataPointInfo<X, Y> itemInfo = new DataPointInfo<>(item, item.getXValue(), item.getYValue(), PartOf.CURRENT); aggregateData.add(itemInfo); } DoubleProperty seriesYAnimMultiplier = seriesYMultiplierMap.get(series); Path seriesLine = (Path)((Group)series.getNode()).getChildren().get(1); Path fillPath = (Path)((Group)series.getNode()).getChildren().get(0); seriesLine.getElements().clear(); fillPath.getElements().clear(); int dataIndex = 0; // Sort data points from prev and current series sortAggregateList(aggregateData); Axis<Y> yAxis = getYAxis(); Axis<X> xAxis = getXAxis(); boolean firstCurrent = false; boolean lastCurrent = false; int firstCurrentIndex = findNextCurrent(aggregateData, -1); int lastCurrentIndex = findPreviousCurrent(aggregateData, aggregateData.size()); double basePosition = yAxis.getZeroPosition(); if (Double.isNaN(basePosition)) { ValueAxis<Number> valueYAxis = (ValueAxis<Number>) yAxis; if (valueYAxis.getLowerBound() > 0) { basePosition = valueYAxis.getDisplayPosition(valueYAxis.getLowerBound()); } else { basePosition = valueYAxis.getDisplayPosition(valueYAxis.getUpperBound()); } } // Iterate over the aggregate data : this process accumulates data points // cumulatively from the bottom to top of stack for (DataPointInfo<X, Y> dataInfo : aggregateData) { if (dataIndex == lastCurrentIndex) lastCurrent = true; if (dataIndex == firstCurrentIndex) firstCurrent = true; final Data<X,Y> item = dataInfo.dataItem; if (dataInfo.partOf.equals(PartOf.CURRENT)) { // handle data from current series int pIndex = findPreviousPrevious(aggregateData, dataIndex); int nIndex = findNextPrevious(aggregateData, dataIndex); DataPointInfo<X, Y> prevPoint; DataPointInfo<X, Y> nextPoint; if (pIndex == -1 || (nIndex == -1 && !(aggregateData.get(pIndex).x.equals(dataInfo.x)))) { if (firstCurrent) { // Need to add the drop down point. Data<X, Y> ddItem = new Data(dataInfo.x, 0); addDropDown(currentSeriesData, ddItem, ddItem.getXValue(), ddItem.getYValue(), xAxis.getDisplayPosition(ddItem.getCurrentX()), basePosition); } double x = xAxis.getDisplayPosition(item.getCurrentX()); double y = yAxis.getDisplayPosition( yAxis.toRealValue(yAxis.toNumericValue(item.getCurrentY()) * seriesYAnimMultiplier.getValue())); addPoint(currentSeriesData, item, item.getXValue(), item.getYValue(), x, y, PartOf.CURRENT, false, (firstCurrent) ? false : true); if (dataIndex == lastCurrentIndex) { // need to add drop down point Data<X, Y> ddItem = new Data(dataInfo.x, 0); addDropDown(currentSeriesData, ddItem, ddItem.getXValue(), ddItem.getYValue(), xAxis.getDisplayPosition(ddItem.getCurrentX()), basePosition); } } else { prevPoint = aggregateData.get(pIndex); if (prevPoint.x.equals(dataInfo.x)) { // Need to add Y values // Check if prevPoint is a dropdown - as the stable sort preserves the order. // If so, find the non dropdown previous point on previous series. if (prevPoint.dropDown) { pIndex = findPreviousPrevious(aggregateData, pIndex); prevPoint = aggregateData.get(pIndex); // If lastCurrent - add this drop down } if (prevPoint.x.equals(dataInfo.x)) { // simply add double x = xAxis.getDisplayPosition(item.getCurrentX()); final double yv = yAxis.toNumericValue(item.getCurrentY()) + yAxis.toNumericValue(prevPoint.y); double y = yAxis.getDisplayPosition( yAxis.toRealValue(yv * seriesYAnimMultiplier.getValue())); addPoint(currentSeriesData, item, dataInfo.x, yAxis.toRealValue(yv), x, y, PartOf.CURRENT, false, (firstCurrent) ? false : true); } if (lastCurrent) { addDropDown(currentSeriesData, item, prevPoint.x, prevPoint.y, prevPoint.displayX, prevPoint.displayY); } } else { // interpolate nextPoint = (nIndex == -1) ? null : aggregateData.get(nIndex); prevPoint = (pIndex == -1) ? null : aggregateData.get(pIndex); final double yValue = yAxis.toNumericValue(item.getCurrentY()); if (prevPoint != null && nextPoint != null) { double x = xAxis.getDisplayPosition(item.getCurrentX()); double displayY = interpolate(prevPoint.displayX, prevPoint.displayY, nextPoint.displayX, nextPoint.displayY, x); double dataY = interpolate(xAxis.toNumericValue(prevPoint.x), yAxis.toNumericValue(prevPoint.y), xAxis.toNumericValue(nextPoint.x), yAxis.toNumericValue(nextPoint.y), xAxis.toNumericValue(dataInfo.x)); if (firstCurrent) { // now create the drop down point Data<X, Y> ddItem = new Data(dataInfo.x, dataY); addDropDown(currentSeriesData, ddItem, dataInfo.x, yAxis.toRealValue(dataY), x, displayY); } double y = yAxis.getDisplayPosition(yAxis.toRealValue((yValue + dataY) * seriesYAnimMultiplier.getValue())); // Add the current point addPoint(currentSeriesData, item, dataInfo.x, yAxis.toRealValue(yValue + dataY), x, y, PartOf.CURRENT, false, (firstCurrent) ? false : true); if (dataIndex == lastCurrentIndex) { // add drop down point Data<X, Y> ddItem = new Data(dataInfo.x, dataY); addDropDown(currentSeriesData, ddItem, dataInfo.x, yAxis.toRealValue(dataY), x, displayY); } // Note: add drop down if last current } else { // we do not need to take care of this as it is // already handled above with check of if(pIndex == -1 or nIndex == -1) } } } } else { // handle data from Previous series. int pIndex = findPreviousCurrent(aggregateData, dataIndex); int nIndex = findNextCurrent(aggregateData, dataIndex); DataPointInfo<X, Y> prevPoint; DataPointInfo<X, Y> nextPoint; if (dataInfo.dropDown) { if (xAxis.toNumericValue(dataInfo.x) <= xAxis.toNumericValue(aggregateData.get(firstCurrentIndex).x) || xAxis.toNumericValue(dataInfo.x) > xAxis.toNumericValue(aggregateData.get(lastCurrentIndex).x)) { addDropDown(currentSeriesData, item, dataInfo.x, dataInfo.y, dataInfo.displayX, dataInfo.displayY); } } else { if (pIndex == -1 || nIndex == -1) { addPoint(currentSeriesData, item, dataInfo.x, dataInfo.y, dataInfo.displayX, dataInfo.displayY, PartOf.CURRENT, true, false); } else { nextPoint = aggregateData.get(nIndex); if (nextPoint.x.equals(dataInfo.x)) { // do nothing as the current point is already there. } else { // interpolate on the current series. prevPoint = aggregateData.get(pIndex); double x = xAxis.getDisplayPosition(item.getCurrentX()); double dataY = interpolate(xAxis.toNumericValue(prevPoint.x), yAxis.toNumericValue(prevPoint.y), xAxis.toNumericValue(nextPoint.x), yAxis.toNumericValue(nextPoint.y), xAxis.toNumericValue(dataInfo.x)); final double yv = yAxis.toNumericValue(dataInfo.y) + dataY; double y = yAxis.getDisplayPosition( yAxis.toRealValue(yv * seriesYAnimMultiplier.getValue())); addPoint(currentSeriesData, new Data(dataInfo.x, dataY), dataInfo.x, yAxis.toRealValue(yv), x, y, PartOf.CURRENT, true, true); } } } } dataIndex++; if (firstCurrent) firstCurrent = false; if (lastCurrent) lastCurrent = false; } // end of inner for loop // Draw the SeriesLine and Series fill if (!currentSeriesData.isEmpty()) { seriesLine.getElements().add(new MoveTo(currentSeriesData.get(0).displayX, currentSeriesData.get(0).displayY)); fillPath.getElements().add(new MoveTo(currentSeriesData.get(0).displayX, currentSeriesData.get(0).displayY)); } for (DataPointInfo<X, Y> point : currentSeriesData) { if (point.lineTo) { seriesLine.getElements().add(new LineTo(point.displayX, point.displayY)); } else { seriesLine.getElements().add(new MoveTo(point.displayX, point.displayY)); } fillPath.getElements().add(new LineTo(point.displayX, point.displayY)); // draw symbols only for actual data points and skip for interpolated points. if (!point.skipSymbol) { Node symbol = point.dataItem.getNode(); if (symbol != null) { final double w = symbol.prefWidth(-1); final double h = symbol.prefHeight(-1); symbol.resizeRelocate(point.displayX-(w/2), point.displayY-(h/2),w,h); } } } for(int i = aggregateData.size()-1; i > 0; i--) { DataPointInfo<X, Y> point = aggregateData.get(i); if (PartOf.PREVIOUS.equals(point.partOf)) { fillPath.getElements().add(new LineTo(point.displayX, point.displayY)); } } if (!fillPath.getElements().isEmpty()) { fillPath.getElements().add(new ClosePath()); } } // end of out for loop } private void addDropDown(ArrayList<DataPointInfo<X, Y>> currentSeriesData, Data<X, Y> item, X xValue, Y yValue, double x, double y) { DataPointInfo<X, Y> dropDownDataPoint = new DataPointInfo<>(true); dropDownDataPoint.setValues(item, xValue, yValue, x, y, PartOf.CURRENT, true, false); currentSeriesData.add(dropDownDataPoint); } private void addPoint(ArrayList<DataPointInfo<X, Y>> currentSeriesData, Data<X, Y> item, X xValue, Y yValue, double x, double y, PartOf partof, boolean symbol, boolean lineTo) { DataPointInfo<X, Y> currentDataPoint = new DataPointInfo<>(); currentDataPoint.setValues(item, xValue, yValue, x, y, partof, symbol, lineTo); currentSeriesData.add(currentDataPoint); } //-------------------- helper methods to retrieve data points from the previous // or current data series. private int findNextCurrent(ArrayList<DataPointInfo<X, Y>> points, int index) { for(int i = index+1; i < points.size(); i++) { if (points.get(i).partOf.equals(PartOf.CURRENT)) { return i; } } return -1; } private int findPreviousCurrent(ArrayList<DataPointInfo<X, Y>> points, int index) { for(int i = index-1; i >= 0; i--) { if (points.get(i).partOf.equals(PartOf.CURRENT)) { return i; } } return -1; } private int findPreviousPrevious(ArrayList<DataPointInfo<X, Y>> points, int index) { for(int i = index-1; i >= 0; i--) { if (points.get(i).partOf.equals(PartOf.PREVIOUS)) { return i; } } return -1; } private int findNextPrevious(ArrayList<DataPointInfo<X, Y>> points, int index) { for(int i = index+1; i < points.size(); i++) { if (points.get(i).partOf.equals(PartOf.PREVIOUS)) { return i; } } return -1; } private void sortAggregateList(ArrayList<DataPointInfo<X, Y>> aggregateList) { Collections.sort(aggregateList, (o1, o2) -> { Data<X,Y> d1 = o1.dataItem; Data<X,Y> d2 = o2.dataItem; double val1 = getXAxis().toNumericValue(d1.getXValue()); double val2 = getXAxis().toNumericValue(d2.getXValue()); return (val1 < val2 ? -1 : ( val1 == val2) ? 0 : 1); }); } private double interpolate(double lowX, double lowY, double highX, double highY, double x) { // using y = mx+c find the y for the given x. return (((highY - lowY)/(highX - lowX))*(x - lowX))+lowY; } private Node createSymbol(Series<X,Y> series, int seriesIndex, final Data<X,Y> item, int itemIndex) { Node symbol = item.getNode(); // check if symbol has already been created if (symbol == null && getCreateSymbols()) { symbol = new StackPane(); symbol.setAccessibleRole(AccessibleRole.TEXT); symbol.setAccessibleRoleDescription("Point"); symbol.focusTraversableProperty().bind(Platform.accessibilityActiveProperty()); item.setNode(symbol); } // set symbol styles // Note not sure if we want to add or check, ie be more careful and efficient here if (symbol != null) symbol.getStyleClass().setAll("chart-area-symbol", "series" + seriesIndex, "data" + itemIndex, series.defaultColorStyleClass); return symbol; } @Override LegendItem createLegendItemForSeries(Series<X, Y> series, int seriesIndex) { LegendItem legendItem = new LegendItem(series.getName()); legendItem.getSymbol().getStyleClass().addAll("chart-area-symbol", "series" + seriesIndex, "area-legend-symbol", series.defaultColorStyleClass); return legendItem; } // -------------- INNER CLASSES -------------------------------------------- /* * Helper class to hold data and display and other information for each * data point */ final static class DataPointInfo<X, Y> { X x; Y y; double displayX; double displayY; Data<X,Y> dataItem; PartOf partOf; boolean skipSymbol = false; // interpolated point - skip drawing symbol boolean lineTo = false; // should there be a lineTo to this point on SeriesLine. boolean dropDown = false; // Is this a drop down point ( non data point). //----- Constructors -------------------- DataPointInfo() {} DataPointInfo(Data<X,Y> item, X x, Y y, PartOf partOf) { this.dataItem = item; this.x = x; this.y = y; this.partOf = partOf; } DataPointInfo(boolean dropDown) { this.dropDown = dropDown; } void setValues(Data<X,Y> item, X x, Y y, double dx, double dy, PartOf partOf, boolean skipSymbol, boolean lineTo) { this.dataItem = item; this.x = x; this.y = y; this.displayX = dx; this.displayY = dy; this.partOf = partOf; this.skipSymbol = skipSymbol; this.lineTo = lineTo; } public final X getX() { return x; } public final Y getY() { return y; } } // To indicate if the data point belongs to the current or the previous series. private static enum PartOf { CURRENT, PREVIOUS } // -------------- STYLESHEET HANDLING -------------------------------------- private static class StyleableProperties { private static final CssMetaData<StackedAreaChart<?, ?>, Boolean> CREATE_SYMBOLS = new CssMetaData<StackedAreaChart<?, ?>, Boolean>("-fx-create-symbols", BooleanConverter.getInstance(), Boolean.TRUE) { @Override public boolean isSettable(StackedAreaChart<?,?> node) { return node.createSymbols == null || !node.createSymbols.isBound(); } @Override public StyleableProperty<Boolean> getStyleableProperty(StackedAreaChart<?,?> node) { return (StyleableProperty<Boolean>)(WritableValue<Boolean>)node.createSymbolsProperty(); } }; private static final List<CssMetaData<? extends Styleable, ?>> STYLEABLES; static { final List<CssMetaData<? extends Styleable, ?>> styleables = new ArrayList<CssMetaData<? extends Styleable, ?>>(XYChart.getClassCssMetaData()); styleables.add(CREATE_SYMBOLS); STYLEABLES = Collections.unmodifiableList(styleables); } } /** * @return The CssMetaData associated with this class, which may include the * CssMetaData of its superclasses. * @since JavaFX 8.0 */ public static List<CssMetaData<? extends Styleable, ?>> getClassCssMetaData() { return StyleableProperties.STYLEABLES; } /** * {@inheritDoc} * @since JavaFX 8.0 */ @Override public List<CssMetaData<? extends Styleable, ?>> getCssMetaData() { return getClassCssMetaData(); } }
92321eddbe6100438d9e324de1300e76d23c093c
5,085
java
Java
platform-core/src/test/java/com/webank/wecube/platform/core/parser/PluginPackageDataModelDtoValidatorTest.java
yyri/wecube-platform
6d38648b64018512fc6ff1b5a12e74bdb3a51e95
[ "Apache-2.0" ]
1
2020-09-11T03:14:52.000Z
2020-09-11T03:14:52.000Z
platform-core/src/test/java/com/webank/wecube/platform/core/parser/PluginPackageDataModelDtoValidatorTest.java
shixm123123/wecube-platform
efac55aa1a6920c310e85d462b28b6e7b11b8e01
[ "Apache-2.0" ]
null
null
null
platform-core/src/test/java/com/webank/wecube/platform/core/parser/PluginPackageDataModelDtoValidatorTest.java
shixm123123/wecube-platform
efac55aa1a6920c310e85d462b28b6e7b11b8e01
[ "Apache-2.0" ]
1
2020-03-12T08:44:10.000Z
2020-03-12T08:44:10.000Z
52.96875
179
0.737463
996,110
package com.webank.wecube.platform.core.parser; import com.google.common.io.Resources; import com.webank.wecube.platform.core.commons.WecubeCoreException; import com.webank.wecube.platform.core.dto.PluginPackageDto; import org.junit.Test; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPathExpressionException; import java.io.IOException; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; public class PluginPackageDataModelDtoValidatorTest { @Test public void givenPluginPackageWithoutDataModelWhenValidateThenShouldSucceed() { try { InputSource inputSource = new InputSource(Resources.getResource("plugin/sample-plugin-config-without-data-model-entity.xml").openStream()); PluginPackageDto pluginPackageDto = PluginPackageXmlParser.newInstance(inputSource).parsePluginPackage(); new PluginPackageDataModelDtoValidator().validate(pluginPackageDto.getPluginPackageDataModelDto()); } catch (Exception e) { fail("Validator should succeed here but got error message: " + e.getMessage()); } } @Test public void givenPluginPackageParameterWithMappingTypeWhenValidateThenShouldSucceed() { try { InputSource inputSource = new InputSource(Resources.getResource("plugin/sample-plugin-config-output-parameter-with-mappingtype.xml").openStream()); PluginPackageDto pluginPackageDto = PluginPackageXmlParser.newInstance(inputSource).parsePluginPackage(); new PluginPackageDataModelDtoValidator().validate(pluginPackageDto.getPluginPackageDataModelDto()); } catch (Exception e) { fail("Validator should succeed here but got error message: " + e.getMessage()); } } @Test public void givenPluginPackageWithDataModelButAttributeWithoutDataTypeWhenValidateThenShouldThrowException() { try { InputSource inputSource = new InputSource(Resources.getResource("plugin/sample-plugin-config-with-data-model-entity-attribute-without-datatype.xml").openStream()); PluginPackageDto pluginPackageDto = PluginPackageXmlParser.newInstance(inputSource).parsePluginPackage(); new PluginPackageDataModelDtoValidator().validate(pluginPackageDto.getPluginPackageDataModelDto()); fail("Validator should throw exception but succeed"); } catch (WecubeCoreException e) { assertThat(e.getMessage().contains("The DataType should not be empty or null")).isTrue(); } catch (SAXException | IOException | XPathExpressionException | ParserConfigurationException e) { fail("Xml should be correct without exception"); } } @Test public void givenPluginPackageWithDataModelButAttributeWithoutDescriptionWhenValidateThenShouldSucceed() { try { InputSource inputSource = new InputSource(Resources.getResource("plugin/sample-plugin-config-with-data-model-entity-attribute-without-description.xml").openStream()); PluginPackageDto pluginPackageDto = PluginPackageXmlParser.newInstance(inputSource).parsePluginPackage(); new PluginPackageDataModelDtoValidator().validate(pluginPackageDto.getPluginPackageDataModelDto()); } catch (Exception e) { fail("Xml should be correct without exception"); } } @Test public void givenPluginPackageWithDataModelButRefAttributeNameMissingWhenValidateThenShouldThrowException() { try { InputSource inputSource = new InputSource(Resources.getResource("plugin/sample-plugin-config-with-data-model-entity-but-ref-attribute-name-missing.xml").openStream()); PluginPackageDto pluginPackageDto = PluginPackageXmlParser.newInstance(inputSource).parsePluginPackage(); new PluginPackageDataModelDtoValidator().validate(pluginPackageDto.getPluginPackageDataModelDto()); fail("Validator should throw exception but succeed"); } catch (WecubeCoreException e) { assertThat(e.getMessage().contains("Field [ref] should be specified when [dataType] is set to [\"ref\"]")).isTrue(); } catch (SAXException | IOException | XPathExpressionException | ParserConfigurationException e) { fail("Xml should be correct without exception"); } } @Test public void givenPluginPackageWithCorrectDataModelWhenValidateThenShouldSucceed() { try { InputSource inputSource = new InputSource(Resources.getResource("plugin/sample-plugin-config-with-data-model-entity.xml").openStream()); PluginPackageDto pluginPackageDto = PluginPackageXmlParser.newInstance(inputSource).parsePluginPackage(); new PluginPackageDataModelDtoValidator().validate(pluginPackageDto.getPluginPackageDataModelDto()); } catch (Exception e) { fail("Validator should succeed here but got error message: " + e.getMessage()); } } }
923220b8c9e931fbb275539bb0294f57e45ed645
1,785
java
Java
streamsuite/src/main/java/com/huawei/streaming/util/datatype/StringParser.java
ucarGroup/poseidonX
fec90db846cf829fd1d608fe628cfa7b896b5dc4
[ "Apache-2.0" ]
71
2018-07-18T03:00:41.000Z
2021-11-19T09:23:34.000Z
streaming/src/main/java/com/huawei/streaming/util/datatype/StringParser.java
QiangCai/StreamCQL
f5a809c97cb6599ab0e18beb88fb98264c588b39
[ "Apache-2.0" ]
2
2019-02-12T05:04:13.000Z
2019-03-07T07:41:27.000Z
streaming/src/main/java/com/huawei/streaming/util/datatype/StringParser.java
QiangCai/StreamCQL
f5a809c97cb6599ab0e18beb88fb98264c588b39
[ "Apache-2.0" ]
44
2018-07-18T03:00:47.000Z
2021-11-19T09:23:36.000Z
27.045455
82
0.691317
996,111
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.huawei.streaming.util.datatype; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Strings; import com.huawei.streaming.exception.StreamingException; /** * 数据类型解析 * Created by h00183771 on 2015/11/18. */ public class StringParser implements DataTypeParser { private static final long serialVersionUID = -8396210249144953425L; private static final Logger LOG = LoggerFactory.getLogger(StringParser.class); /** * {@inheritDoc} */ @Override public Object createValue(String value) throws StreamingException { if (Strings.isNullOrEmpty(value)) { return null; } return String.valueOf(value); } /** * {@inheritDoc} */ @Override public String toStringValue(Object value) throws StreamingException { if (null == value) { return null; } return value.toString(); } }
923220c549881daefc88cb6bb7ff964c16a4f19f
5,745
java
Java
GameObj.java
WakaFlockaFlam2/Java-Chess
b79f8df08fa384b708f63405d969f4dfad0a1f2f
[ "MIT" ]
null
null
null
GameObj.java
WakaFlockaFlam2/Java-Chess
b79f8df08fa384b708f63405d969f4dfad0a1f2f
[ "MIT" ]
null
null
null
GameObj.java
WakaFlockaFlam2/Java-Chess
b79f8df08fa384b708f63405d969f4dfad0a1f2f
[ "MIT" ]
null
null
null
27.753623
72
0.658138
996,112
/** * CIS 120 Game HW * (c) University of Pennsylvania * @version 2.0, Mar 2013 */ import java.awt.Graphics; /** An object in the game. * * Game objects exist in the game court. They have a position, * velocity, size and bounds. Their velocity controls how they * move; their position should always be within their bounds. */ public class GameObj { /** Current position of the object (in terms of graphics coordinates) * * Coordinates are given by the upper-left hand corner of the object. * This position should always be within bounds. * 0 <= pos_x <= max_x * 0 <= pos_y <= max_y */ public int pos_x; public int pos_y; /** Size of object, in pixels */ public int width; public int height; /** Velocity: number of pixels to move every time move() is called */ public int v_x; public int v_y; /** Upper bounds of the area in which the object can be positioned. * Maximum permissible x, y positions for the upper-left * hand corner of the object */ public int max_x; public int max_y; /** * Constructor */ public GameObj(int v_x, int v_y, int pos_x, int pos_y, int width, int height, int court_width, int court_height){ this.v_x = v_x; this.v_y = v_y; this.pos_x = pos_x; this.pos_y = pos_y; this.width = width; this.height = height; // take the width and height into account when setting the // bounds for the upper left corner of the object. this.max_x = court_width - width; this.max_y = court_height - height; } /** * Moves the object by its velocity. Ensures that the object does * not go outside its bounds by clipping. */ public void move(){ pos_x += v_x; pos_y += v_y; clip(); } /** * Prevents the object from going outside of the bounds of the area * designated for the object. (i.e. Object cannot go outside of the * active area the user defines for it). */ public void clip(){ if (pos_x < 0) pos_x = 0; else if (pos_x > max_x) pos_x = max_x; if (pos_y < 0) pos_y = 0; else if (pos_y > max_y) pos_y = max_y; } /** * Determine whether this game object is currently intersecting * another object. * * Intersection is determined by comparing bounding boxes. If the * bounding boxes overlap, then an intersection is considered to occur. * * @param obj : other object * @return whether this object intersects the other object. */ public boolean intersects(GameObj obj){ return (pos_x + width >= obj.pos_x && pos_y + height >= obj.pos_y && obj.pos_x + obj.width >= pos_x && obj.pos_y + obj.height >= pos_y); } /** * Determine whether this game object will intersect another in the * next time step, assuming that both objects continue with their * current velocity. * * Intersection is determined by comparing bounding boxes. If the * bounding boxes (for the next time step) overlap, then an * intersection is considered to occur. * * @param obj : other object * @return whether an intersection will occur. */ public boolean willIntersect(GameObj obj){ int next_x = pos_x + v_x; int next_y = pos_y + v_y; int next_obj_x = obj.pos_x + obj.v_x; int next_obj_y = obj.pos_y + obj.v_y; return (next_x + width >= next_obj_x && next_y + height >= next_obj_y && next_obj_x + obj.width >= next_x && next_obj_y + obj.height >= next_y); } /** Update the velocity of the object in response to hitting * an obstacle in the given direction. If the direction is * null, this method has no effect on the object. */ public void bounce(Direction d) { if (d == null) return; switch (d) { case UP: v_y = Math.abs(v_y); break; case DOWN: v_y = -Math.abs(v_y); break; case LEFT: v_x = Math.abs(v_x); break; case RIGHT: v_x = -Math.abs(v_x); break; } } /** Determine whether the game object will hit a * wall in the next time step. If so, return the direction * of the wall in relation to this game object. * * @return direction of impending wall, null if all clear. */ public Direction hitWall() { if (pos_x + v_x < 0) return Direction.LEFT; else if (pos_x + v_x > max_x) return Direction.RIGHT; if (pos_y + v_y < 0) return Direction.UP; else if (pos_y + v_y > max_y) return Direction.DOWN; else return null; } /** Determine whether the game object will hit another * object in the next time step. If so, return the direction * of the other object in relation to this game object. * * @return direction of impending object, null if all clear. */ public Direction hitObj(GameObj other) { if (this.willIntersect(other)) { double dx = other.pos_x + other.width /2 - (pos_x + width /2); double dy = other.pos_y + other.height/2 - (pos_y + height/2); double theta = Math.acos(dx / (Math.sqrt(dx * dx + dy *dy))); double diagTheta = Math.atan2(height / 2, width / 2); if (theta <= diagTheta ) { return Direction.RIGHT; } else if ( theta > diagTheta && theta <= Math.PI - diagTheta ) { if ( dy > 0 ) { // Coordinate system for GUIs is switched return Direction.DOWN; } else { return Direction.UP; } } else { return Direction.LEFT; } } else { return null; } } /** * Default draw method that provides how the object should be drawn * in the GUI. This method does not draw anything. Subclass should * override this method based on how their object should appear. * * @param g * The <code>Graphics</code> context used for drawing the object. * Remember graphics contexts that we used in OCaml, it gives the * context in which the object should be drawn (a canvas, a frame, * etc.) */ public void draw(Graphics g) { } }
9232220b6947a947a9492dcdc3736b71277a6895
261
java
Java
latest-global/src/main/java/com/github/jartisan/latest/global/utils/dingding/message/Message.java
jartisan2001/latest
df2e4929855f922a3a127c39aa2109bf716faca7
[ "Apache-2.0" ]
6
2019-02-27T11:22:04.000Z
2020-08-27T11:26:13.000Z
latest-global/src/main/java/com/github/jartisan/latest/global/utils/dingding/message/Message.java
jartisan2001/latest
df2e4929855f922a3a127c39aa2109bf716faca7
[ "Apache-2.0" ]
null
null
null
latest-global/src/main/java/com/github/jartisan/latest/global/utils/dingding/message/Message.java
jartisan2001/latest
df2e4929855f922a3a127c39aa2109bf716faca7
[ "Apache-2.0" ]
null
null
null
15.352941
66
0.578544
996,113
package com.github.jartisan.latest.global.utils.dingding.message; /** * * @author dustin * @date 2017/3/17 */ public interface Message { /** * 返回消息的Json格式字符串 * * @return 消息的Json格式字符串 */ String toJsonString(); }
9232220d98ce4a08ca54b4f4d7efdc2e0eca2bbb
684
java
Java
src/main/java/com/wseemann/tbawebscraper/models/BracketWithCompetitors.java
wseemann/TBAWebScraper
47ea2754b839a71823c4bae84359140dbc536d62
[ "Apache-2.0" ]
1
2022-03-09T18:18:56.000Z
2022-03-09T18:18:56.000Z
src/main/java/com/wseemann/tbawebscraper/models/BracketWithCompetitors.java
wseemann/TBAWebScraper
47ea2754b839a71823c4bae84359140dbc536d62
[ "Apache-2.0" ]
null
null
null
src/main/java/com/wseemann/tbawebscraper/models/BracketWithCompetitors.java
wseemann/TBAWebScraper
47ea2754b839a71823c4bae84359140dbc536d62
[ "Apache-2.0" ]
null
null
null
22.064516
82
0.681287
996,114
package com.wseemann.tbawebscraper.models; import java.util.List; public class BracketWithCompetitors { private Bracket bracket; private List<Competitor> competitors; public BracketWithCompetitors(Bracket bracket, List<Competitor> competitors) { this.bracket = bracket; this.competitors = competitors; } public Bracket getBracket() { return bracket; } public void setBracket(Bracket bracket) { this.bracket = bracket; } public List<Competitor> getCompetitors() { return competitors; } public void setCompetitors(List<Competitor> competitors) { this.competitors = competitors; } }
92322213d70c0ba59a7a052d487c9a14c44a4440
3,819
java
Java
app/src/main/java/com/codepath/tiago/nytimessearch/utils/ItemClickSupport.java
Tiago11/nyt-article-search-codepath
2e617969ad5052e5d3bb44796f658bfe7cfef0e8
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/codepath/tiago/nytimessearch/utils/ItemClickSupport.java
Tiago11/nyt-article-search-codepath
2e617969ad5052e5d3bb44796f658bfe7cfef0e8
[ "Apache-2.0" ]
1
2017-09-25T05:40:18.000Z
2017-09-25T05:40:18.000Z
app/src/main/java/com/codepath/tiago/nytimessearch/utils/ItemClickSupport.java
Tiago11/nyt-article-search-codepath
2e617969ad5052e5d3bb44796f658bfe7cfef0e8
[ "Apache-2.0" ]
null
null
null
33.208696
113
0.68133
996,115
package com.codepath.tiago.nytimessearch.utils; import android.support.v7.widget.RecyclerView; import android.view.View; import com.codepath.tiago.nytimessearch.R; /** * Created by tiago on 9/22/17. */ /* Source: http://www.littlerobots.nl/blog/Handle-Android-RecyclerView-Clicks/ USAGE: ItemClickSupport.addTo(mRecyclerView).setOnItemClickListener(new ItemClickSupport.OnItemClickListener() { @Override public void onItemClicked(RecyclerView recyclerView, int position, View v) { // do it } }); */ public class ItemClickSupport { // Tag for logging. private final String TAG = ItemClickSupport.class.toString(); private final RecyclerView mRecyclerView; private OnItemClickListener mOnItemClickListener; private OnItemLongClickListener mOnItemLongClickListener; private View.OnClickListener mOnClickListener = new View.OnClickListener() { @Override public void onClick(View v) { if (mOnItemClickListener != null) { RecyclerView.ViewHolder holder = mRecyclerView.getChildViewHolder(v); mOnItemClickListener.onItemClicked(mRecyclerView, holder.getAdapterPosition(), v); } } }; private View.OnLongClickListener mOnLongClickListener = new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { if (mOnItemLongClickListener != null) { RecyclerView.ViewHolder holder = mRecyclerView.getChildViewHolder(v); return mOnItemLongClickListener.onItemLongClicked(mRecyclerView, holder.getAdapterPosition(), v); } return false; } }; private RecyclerView.OnChildAttachStateChangeListener mAttachListener = new RecyclerView.OnChildAttachStateChangeListener() { @Override public void onChildViewAttachedToWindow(View view) { if (mOnItemClickListener != null) { view.setOnClickListener(mOnClickListener); } if (mOnItemLongClickListener != null) { view.setOnLongClickListener(mOnLongClickListener); } } @Override public void onChildViewDetachedFromWindow(View view) { } }; private ItemClickSupport(RecyclerView recyclerView) { mRecyclerView = recyclerView; mRecyclerView.setTag(R.id.item_click_support, this); mRecyclerView.addOnChildAttachStateChangeListener(mAttachListener); } public static ItemClickSupport addTo(RecyclerView view) { ItemClickSupport support = (ItemClickSupport) view.getTag(R.id.item_click_support); if (support == null) { support = new ItemClickSupport(view); } return support; } public static ItemClickSupport removeFrom(RecyclerView view) { ItemClickSupport support = (ItemClickSupport) view.getTag(R.id.item_click_support); if (support != null) { support.detach(view); } return support; } public ItemClickSupport setOnItemClickListener(OnItemClickListener listener) { mOnItemClickListener = listener; return this; } public ItemClickSupport setOnItemLongClickListener(OnItemLongClickListener listener) { mOnItemLongClickListener = listener; return this; } private void detach(RecyclerView view) { view.removeOnChildAttachStateChangeListener(mAttachListener); view.setTag(R.id.item_click_support, null); } public interface OnItemClickListener { void onItemClicked(RecyclerView recyclerView, int position, View v); } public interface OnItemLongClickListener { boolean onItemLongClicked(RecyclerView recyclerView, int position, View v); } }
92322259fd9a57760ff5a2c99e972f891c89bb98
1,076
java
Java
flowable-extension/src/main/java/rwbykit/flowable/extension/calculator/artificial/approval/HalfVetoMultiJoinSignRuleCalculator.java
rwbykit/flowable
c9a8de39c636892f7b95cdf2fbd7b0adc855ea95
[ "Apache-2.0" ]
null
null
null
flowable-extension/src/main/java/rwbykit/flowable/extension/calculator/artificial/approval/HalfVetoMultiJoinSignRuleCalculator.java
rwbykit/flowable
c9a8de39c636892f7b95cdf2fbd7b0adc855ea95
[ "Apache-2.0" ]
1
2022-03-31T20:56:01.000Z
2022-03-31T20:56:01.000Z
flowable-extension/src/main/java/rwbykit/flowable/extension/calculator/artificial/approval/HalfVetoMultiJoinSignRuleCalculator.java
rwbykit/flowable
c9a8de39c636892f7b95cdf2fbd7b0adc855ea95
[ "Apache-2.0" ]
null
null
null
35.866667
135
0.791822
996,116
package rwbykit.flowable.extension.calculator.artificial.approval; import rwbykit.flowable.core.Result; import rwbykit.flowable.core.model.runtime.ApprovalInstance; import rwbykit.flowable.extension.actuator.artificial.approval.MultiJoinSignParameter; import rwbykit.flowableTemp.core.ProcessConstants; import rwbykit.flowable.extension.BooleanResult; import rwbykit.flowableTemp.core.util.Numbers; import java.math.BigDecimal; import java.util.List; /** * 半数否决 * * @author Cytus_ * @version 1.0 * @since 2018年12月28日 下午6:02:15 */ public class HalfVetoMultiJoinSignRuleCalculator implements CustomizedMultiJoinSignRuleCalculator { @Override public Result<Boolean> calculate(MultiJoinSignParameter parameter) { List<ApprovalInstance> approvals = parameter.getApprovalInstances(); long refuseNum = approvals.parallelStream().filter(s -> ProcessConstants.ARRV_RESULT_REFUSE.equals(s.getAprvResult())).count(); return BooleanResult.createSuccess(Numbers.divide(refuseNum, approvals.size(), 2).compareTo(new BigDecimal(0.5)) < 0); } }
92322291bc95caee4afe6a7dbebff061f5055fea
1,282
java
Java
Code/src/main/java/br/com/mmw/pontosystem/api/assembler/PontoModelAssembler.java
lucoso/PontoSystem-API
1fe498b4096fab2e0efc1de03bfa4e73deac38ee
[ "MIT" ]
null
null
null
Code/src/main/java/br/com/mmw/pontosystem/api/assembler/PontoModelAssembler.java
lucoso/PontoSystem-API
1fe498b4096fab2e0efc1de03bfa4e73deac38ee
[ "MIT" ]
null
null
null
Code/src/main/java/br/com/mmw/pontosystem/api/assembler/PontoModelAssembler.java
lucoso/PontoSystem-API
1fe498b4096fab2e0efc1de03bfa4e73deac38ee
[ "MIT" ]
null
null
null
36.628571
139
0.793292
996,117
package br.com.mmw.pontosystem.api.assembler; import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo; import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.methodOn; import java.util.List; import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.server.RepresentationModelAssembler; import org.springframework.stereotype.Component; import br.com.mmw.pontosystem.api.controller.PontoController; import br.com.mmw.pontosystem.api.model.PontoDTO; import br.com.mmw.pontosystem.api.model.PontoOutputDTO; @Component public class PontoModelAssembler implements RepresentationModelAssembler<PontoOutputDTO, EntityModel<PontoOutputDTO>> { @Override public EntityModel<PontoOutputDTO> toModel(PontoOutputDTO pontoDto) { EntityModel<PontoOutputDTO> pontoModel = EntityModel.of(pontoDto, // linkTo(methodOn(PontoController.class).BuscarTodosPontosDoFuncionario(pontoDto.getFuncionarioID())).withRel("pontos")); List<PontoDTO> pontosDtos = pontoDto.getPontos(); for(PontoDTO p : pontosDtos) { pontoModel.add(linkTo(methodOn(PontoController.class).BuscarPontoDoFuncionario(pontoDto.getFuncionarioID(), p.getId())).withSelfRel()); } return pontoModel; } }
9232229fdd950ebe7517492e8ff2a20a0d1e71c8
784
java
Java
src/main/java/com/tt/threaddemo/utils/date/DateTimeTest.java
Hansiyuan131/thread-demo
abb06666b39670ce1bf37d7b4cc4bd65bb26d522
[ "Apache-2.0" ]
null
null
null
src/main/java/com/tt/threaddemo/utils/date/DateTimeTest.java
Hansiyuan131/thread-demo
abb06666b39670ce1bf37d7b4cc4bd65bb26d522
[ "Apache-2.0" ]
null
null
null
src/main/java/com/tt/threaddemo/utils/date/DateTimeTest.java
Hansiyuan131/thread-demo
abb06666b39670ce1bf37d7b4cc4bd65bb26d522
[ "Apache-2.0" ]
null
null
null
29.037037
76
0.696429
996,118
package com.tt.threaddemo.utils.date; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.Instant; import java.time.LocalDate; import java.time.ZoneId; import java.util.Date; /** * @author hansiyuan * @date 2021年06月21日 14:48 */ public class DateTimeTest { public static void main(String[] args) throws ParseException { String birthday = "1997年-04月-04日"; SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年-MM月-dd日"); Date date = dateFormat.parse(birthday); Instant instant = date.toInstant(); ZoneId zoneId = ZoneId.systemDefault(); LocalDate localDate = instant.atZone(zoneId).toLocalDate(); System.out.println("LocalDate = " + localDate); System.out.println(); } }
923223d06a4f126434260e4f0faa0b95c740319d
5,146
java
Java
core/src/main/java/prng/utility/NonceFactory.java
simon-greatrix/prng
6d41a871406360e8295a6c18c5f39d58863f997a
[ "MIT" ]
null
null
null
core/src/main/java/prng/utility/NonceFactory.java
simon-greatrix/prng
6d41a871406360e8295a6c18c5f39d58863f997a
[ "MIT" ]
2
2017-12-11T11:34:04.000Z
2019-11-16T16:18:09.000Z
core/src/main/java/prng/utility/NonceFactory.java
simon-greatrix/sec-prng
6d41a871406360e8295a6c18c5f39d58863f997a
[ "MIT" ]
null
null
null
33.855263
160
0.656821
996,119
package prng.utility; import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.UUID; import prng.SecureRandomProvider; /** * A factory for nonces where 256-bit security is required. <p> * * For such usage a nonce should not be expected to repeat more often than a (0.5 * security-strength)-bit random number is expected to repeat. Due to the * birthday problem a (0.5 * 256)-bit or 128 bit random number is expected to repeat within 2^64 values. <p> The time-based UUID comprises a 60 bit clock time, * a 16 bit sequence number and a 96 bit network ID. The combination of clock time and sequence exceeds the required values before repetition on a particular * network address. <p> In order to create nonces that are unique across different processes on the same machine, it is necessary to combine the type 1 UUID * with a process identifier. */ public class NonceFactory { /** Identifier for this JVM instance (256 bits/32 bytes) */ private static final byte[] IDENTIFIER; /** Personalization string (256 bit/32 bytes) */ private static final byte[] PERSONALIZATION; /** * Create a 256-bit nonce. * * @return a 256-bit nonce. */ public static byte[] create() { UUID uuid = TimeBasedUUID.create(); DigestDataOutput dig = new DigestDataOutput("SHA-256"); dig.writeLong(uuid.getMostSignificantBits()); dig.writeLong(uuid.getLeastSignificantBits()); dig.write(IDENTIFIER); return dig.digest(); } /** * Get the application personalization string * * @return the personalization string */ public static byte[] personalization() { return PERSONALIZATION.clone(); } static { DigestDataOutput dig = new DigestDataOutput("SHA-256"); final RuntimeMXBean runBean = ManagementFactory.getRuntimeMXBean(); // The "name" often contains the process ID, making name and start time // a unique identifier for this VM. dig.writeUTF(runBean.getName()); dig.writeLong(runBean.getStartTime()); // If multiple applications are running in the same JVM, the class // loader and load time will make it unique dig.writeUTF(NonceFactory.class.getClassLoader().getClass().getName()); dig.writeInt( System.identityHashCode(NonceFactory.class.getClassLoader())); dig.writeLong(System.nanoTime()); dig.writeLong(Thread.currentThread().getId()); IDENTIFIER = dig.digest(); // Now create a personalization string. Start with the identifier info dig = new DigestDataOutput("SHA-512"); dig.writeUTF(runBean.getName()); dig.writeLong(runBean.getStartTime()); dig.writeUTF(NonceFactory.class.getClassLoader().getClass().getName()); dig.writeInt( System.identityHashCode(NonceFactory.class.getClassLoader())); dig.writeLong(System.nanoTime()); dig.writeLong(Thread.currentThread().getId()); // input arguments to this instance List<String> args; try { // requires ManagementPermission monitor args = AccessController.doPrivileged( (PrivilegedAction<List<String>>) runBean::getInputArguments); } catch (SecurityException e) { SecureRandomProvider.LOG.warn( "Lacking permission \"ManagementPermission monitor\" - cannot fully personalize nonce factory"); args = null; } if (args == null) { dig.writeInt(-1); } else { dig.writeInt(args.size()); for (String s : args) { dig.writeUTF(s); } } // system and environment properties Map<String, String> env; try { // requires PropertyPermission * read,write env = AccessController.doPrivileged( (PrivilegedAction<Map<String, String>>) runBean::getSystemProperties); } catch (SecurityException se) { SecureRandomProvider.LOG.warn( "Lacking permission \"PropertyPermission * read,write\" - cannot fully personalize nonce factory"); env = null; } if (env == null) { dig.writeInt(-1); } else { dig.writeInt(env.size()); for (Entry<String, String> e : env.entrySet()) { dig.writeUTF(e.getKey()); dig.writeUTF(e.getValue()); } } try { // requires RuntimePermission getenv.* env = AccessController.doPrivileged( (PrivilegedAction<Map<String, String>>) System::getenv); } catch (SecurityException se) { SecureRandomProvider.LOG.warn( "Lacking permission \"RuntimePermission getenv.*\" - cannot fully personalize nonce factory"); env = null; } if (env == null) { dig.writeInt(-1); } else { dig.writeInt(env.size()); for (Entry<String, String> e : env.entrySet()) { dig.writeUTF(e.getKey()); dig.writeUTF(e.getValue()); } } PERSONALIZATION = dig.digest(); } }
9232246f18863092cf94eb350bf24e5a1b9c28ca
1,632
java
Java
src/test/java/org/basinmc/stormdrain/resource/DeploymentStatusResourceTest.java
BasinMC/Stormdrain
b2760ff56f6f7d77d5de85bc9e0ce7902ef7a405
[ "Apache-2.0" ]
null
null
null
src/test/java/org/basinmc/stormdrain/resource/DeploymentStatusResourceTest.java
BasinMC/Stormdrain
b2760ff56f6f7d77d5de85bc9e0ce7902ef7a405
[ "Apache-2.0" ]
null
null
null
src/test/java/org/basinmc/stormdrain/resource/DeploymentStatusResourceTest.java
BasinMC/Stormdrain
b2760ff56f6f7d77d5de85bc9e0ce7902ef7a405
[ "Apache-2.0" ]
null
null
null
36.533333
96
0.75365
996,120
/* * Copyright 2018 Johannes Donath <nnheo@example.com> * and other copyright owners as documented in the project's IP log. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.basinmc.stormdrain.resource; import edu.umd.cs.findbugs.annotations.NonNull; import org.basinmc.stormdrain.resource.DeploymentStatus.State; import org.junit.Assert; /** * @author <a href="mailto:nnheo@example.com">Johannes Donath</a> */ public class DeploymentStatusResourceTest extends AbstractResourceParserTest<DeploymentStatus> { public DeploymentStatusResourceTest() { super("deployment_status", DeploymentStatus.class); } /** * {@inheritDoc} */ @Override protected void doTest(@NonNull DeploymentStatus model) { Assert.assertEquals("1115122", model.getId()); Assert.assertEquals(State.SUCCESS, model.getState()); Assert.assertFalse(model.getDescription().isPresent()); Assert.assertFalse(model.getTargetUrl().isPresent()); Assert.assertEquals(1430869239L, model.getCreationTimestamp().getEpochSecond()); Assert.assertFalse(model.getModificationTimestamp().isPresent()); } }
92322720103d03b20e02622ce316fea6d82830c0
3,239
java
Java
src/main/java/com/goku/webservice/service/impl/commServiceImpl.java
nbfujx/Goku.WebService.Bus
785fd09d6371df01fe2f205d8a364a7773584f27
[ "MIT" ]
17
2017-10-29T11:43:32.000Z
2021-12-30T06:37:07.000Z
src/main/java/com/goku/webservice/service/impl/commServiceImpl.java
nbfujx/Goku.WebService.Bus
785fd09d6371df01fe2f205d8a364a7773584f27
[ "MIT" ]
null
null
null
src/main/java/com/goku/webservice/service/impl/commServiceImpl.java
nbfujx/Goku.WebService.Bus
785fd09d6371df01fe2f205d8a364a7773584f27
[ "MIT" ]
7
2018-05-14T06:33:13.000Z
2020-05-11T06:48:08.000Z
28.663717
76
0.569003
996,121
package com.goku.webservice.service.impl; import com.goku.webservice.config.druid.DataSource; import com.goku.webservice.service.commService; import org.apache.ibatis.session.SqlSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by nbfujx on 2017-10-26. */ @Service @DataSource("business") public class commServiceImpl implements commService { @Autowired private SqlSession sqlSession; @Transactional public Object doProess(String BsCode,String Operation, Object Para) { StringBuilder methodsb = new StringBuilder(); methodsb.append(BsCode.trim()).append(".").append(Operation.trim()); String method=methodsb.toString(); switch (Operation) { case "SelectOne": return SelectOne(method, Para); case "SelectList": return SelectList(method, Para); case "SelectProc": return SelectProc(method, Para); case "insert": insert(method, Para); return 1; case "update": update(method, Para); return 1; case "delete": delete(method, Para); return 1; default: return "error"; } } public Map<String, String> SelectOne(String method,Object Para) { return sqlSession.selectOne(method, Para); } public List<Map<String, String>> SelectList(String method,Object Para){ return sqlSession.selectList(method, Para); } public List<Map<String, String>> SelectProc(String method,Object Para){ return sqlSession.selectList(method, Para); } public void insert(String method,Object Para){ if(Para.getClass().getName().equals("java.util.ArrayList")) { ArrayList list = (ArrayList) Para; for (int i = 0; i < list.size(); i++) { HashMap hm = (HashMap) list.get(i); sqlSession.insert(method, hm); } } else { sqlSession.insert(method, Para); } } public void update(String method,Object Para){ if(Para.getClass().getName().equals("java.util.ArrayList")) { ArrayList list = (ArrayList) Para; for (int i = 0; i < list.size(); i++) { HashMap hm = (HashMap) list.get(i); sqlSession.update(method, hm); } } else { sqlSession.update(method, Para); } } public void delete(String method,Object Para){ if(Para.getClass().getName().equals("java.util.ArrayList")) { ArrayList list = (ArrayList) Para; for (int i = 0; i < list.size(); i++) { HashMap hm = (HashMap) list.get(i); sqlSession.delete(method, hm); } } else { sqlSession.delete(method, Para); } } }
923227b7f528367b970744fd61e4bdaa593e2aaf
4,508
java
Java
app/src/main/java/com/azr/homework/MainActivity.java
ashiquzzaman/AndroidTestApp
c8a0470adf8dcfefbb083e05363254ef5e8b635f
[ "MIT" ]
1
2020-05-06T13:44:00.000Z
2020-05-06T13:44:00.000Z
app/src/main/java/com/azr/homework/MainActivity.java
ashiquzzaman/AndroidTestApp
c8a0470adf8dcfefbb083e05363254ef5e8b635f
[ "MIT" ]
null
null
null
app/src/main/java/com/azr/homework/MainActivity.java
ashiquzzaman/AndroidTestApp
c8a0470adf8dcfefbb083e05363254ef5e8b635f
[ "MIT" ]
null
null
null
34.151515
96
0.63709
996,122
package com.azr.homework; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.os.SystemClock; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener{ Spinner s1,s2; TextView txtView; Button newActivityBtn; Button newAppBtn; Button stopWatchBtn; EditText txtAmount; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_spinner); s1 = (Spinner)findViewById(R.id.spinner1); s2 = (Spinner)findViewById(R.id.spinner2); s1.setOnItemSelectedListener(this); txtView=(TextView)findViewById(R.id.textViewMain); // txtView.setText(result); newActivityBtn = (Button)findViewById(R.id.newActivityBtn); newActivityBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //show result in a new activity => Implicit Intent newIntent = new Intent(MainActivity.this, NewWindowActivity.class); newIntent.putExtra("txtValue", getResult()); MainActivity.this.startActivity(newIntent); } }); newAppBtn = (Button)findViewById(R.id.newAppBtn); newAppBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //show result in a new application => Explicit Intent myIntent = new Intent(Intent.ACTION_SEND); myIntent.setType("text/plain"); myIntent.putExtra(Intent.EXTRA_TEXT, getResult()); MainActivity.this.startActivity(myIntent); } }); stopWatchBtn = (Button)findViewById(R.id.stopWatchBtn); stopWatchBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent stIntent = new Intent(MainActivity.this, StopWatchActivity.class); stIntent.putExtra("txtValue", getResult()); MainActivity.this.startActivity(stIntent); } }); } @Override public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,long arg3) { String sp1= String.valueOf(s1.getSelectedItem()); Toast.makeText(this, sp1, Toast.LENGTH_SHORT).show(); if(sp1.contentEquals("Income")) { List<String> list = new ArrayList<String>(); list.add("Salary"); list.add("Sales"); list.add("Others"); ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list); dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); dataAdapter.notifyDataSetChanged(); s2.setAdapter(dataAdapter); } if(sp1.contentEquals("Expense")) { List<String> list = new ArrayList<String>(); list.add("Conveyance"); list.add("Breakfast"); list.add("Purchase"); ArrayAdapter<String> dataAdapter2 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list); dataAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); dataAdapter2.notifyDataSetChanged(); s2.setAdapter(dataAdapter2); } } @Override public void onNothingSelected(AdapterView<?> arg0) { } public String getResult(){ String acc = getResources().getString(R.string.suAcc); String sacc = getResources().getString(R.string.suSubAcc); String sp2= String.valueOf(s2.getSelectedItem()); String sp1= String.valueOf(s1.getSelectedItem()); txtAmount = (EditText)findViewById(R.id.txtAmount); String result= "You are selected \n\n"+acc +": "+sp1 +"\n"+sacc+": "+sp2 +"\n"+"Amount"+": "+txtAmount.getText().toString(); return result; } }
92322853855c5cf809ea2e24d980d794850d5ed5
7,009
java
Java
Aria/src/main/java/com/arialyy/aria/core/common/controller/FeatureController.java
helloliuyf/Aria
368dd1f32afaf6a2206b20c71ccd42025e4489cc
[ "Apache-2.0" ]
5,193
2016-12-10T16:17:59.000Z
2022-03-31T15:22:36.000Z
Aria/src/main/java/com/arialyy/aria/core/common/controller/FeatureController.java
helloliuyf/Aria
368dd1f32afaf6a2206b20c71ccd42025e4489cc
[ "Apache-2.0" ]
940
2016-12-19T03:05:15.000Z
2022-03-19T15:31:55.000Z
Aria/src/main/java/com/arialyy/aria/core/common/controller/FeatureController.java
helloliuyf/Aria
368dd1f32afaf6a2206b20c71ccd42025e4489cc
[ "Apache-2.0" ]
808
2016-12-12T20:41:02.000Z
2022-03-30T03:47:37.000Z
33.061321
97
0.715366
996,123
/* * Copyright (C) 2016 AriaLyy(https://github.com/AriaLyy/Aria) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.arialyy.aria.core.common.controller; import android.Manifest; import android.content.pm.PackageManager; import android.os.Handler; import android.os.Looper; import com.arialyy.aria.core.AriaConfig; import com.arialyy.aria.core.common.AbsEntity; import com.arialyy.aria.core.download.CheckDEntityUtil; import com.arialyy.aria.core.download.CheckDGEntityUtil; import com.arialyy.aria.core.download.CheckFtpDirEntityUtil; import com.arialyy.aria.core.download.DGTaskWrapper; import com.arialyy.aria.core.download.DTaskWrapper; import com.arialyy.aria.core.inf.ICheckEntityUtil; import com.arialyy.aria.core.listener.ISchedulers; import com.arialyy.aria.core.scheduler.TaskSchedulers; import com.arialyy.aria.core.task.ITask; import com.arialyy.aria.core.upload.CheckUEntityUtil; import com.arialyy.aria.core.upload.UTaskWrapper; import com.arialyy.aria.core.wrapper.AbsTaskWrapper; import com.arialyy.aria.core.wrapper.ITaskWrapper; import com.arialyy.aria.util.ALog; import com.arialyy.aria.util.CommonUtil; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; /** * 功能控制器 */ public abstract class FeatureController { private static final int ACTION_DEF = 0; public static final int ACTION_CREATE = 1; public static final int ACTION_RESUME = 2; public static final int ACTION_STOP = 3; public static final int ACTION_CANCEL = 4; public static final int ACTION_ADD = 5; public static final int ACTION_PRIORITY = 6; public static final int ACTION_RETRY = 7; public static final int ACTION_RESTART = 8; public static final int ACTION_SAVE = 9; private final String TAG; private AbsTaskWrapper mTaskWrapper; /** * 是否忽略权限检查 true 忽略权限检查 */ private boolean ignoreCheckPermissions = false; private int action = ACTION_DEF; FeatureController(AbsTaskWrapper wrapper) { mTaskWrapper = wrapper; TAG = CommonUtil.getClassName(getClass()); } /** * 使用对应等控制器,注意: * 1、对于不存在的任务(第一次下载),只能使用{@link ControllerType#CREATE_CONTROLLER} * 2、对于已存在的任务,只能使用{@link ControllerType#TASK_CONTROLLER} * * @param clazz {@link ControllerType#CREATE_CONTROLLER}、{@link ControllerType#TASK_CONTROLLER} */ public static <T extends FeatureController> T newInstance(@ControllerType Class<T> clazz, AbsTaskWrapper wrapper) { if (wrapper.getEntity().getId() == -1 && clazz != ControllerType.CREATE_CONTROLLER) { throw new IllegalArgumentException( "对于不存在的任务(第一次下载),只能使用\"ControllerType.CREATE_CONTROLLER\""); } if (wrapper.getEntity().getId() != -1 && clazz != ControllerType.TASK_CONTROLLER) { throw new IllegalArgumentException( "对于已存在的任务,只能使用\" ControllerType.TASK_CONTROLLER\",请检查是否重复调用#create()方法"); } Class[] paramTypes = { AbsTaskWrapper.class }; Object[] params = { wrapper }; try { Constructor<T> con = clazz.getConstructor(paramTypes); return con.newInstance(params); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return null; } void setAction(int action) { this.action = action; } /** * 是否忽略权限检查 */ public void ignoreCheckPermissions() { this.ignoreCheckPermissions = true; } /** * 强制执行任务,不管文件路径是否被占用 */ public void ignoreFilePathOccupy() { mTaskWrapper.setIgnoreFilePathOccupy(true); } protected AbsTaskWrapper getTaskWrapper() { return mTaskWrapper; } protected AbsEntity getEntity() { return mTaskWrapper.getEntity(); } int checkTaskType() { int taskType = 0; if (mTaskWrapper instanceof DTaskWrapper) { taskType = ITask.DOWNLOAD; } else if (mTaskWrapper instanceof DGTaskWrapper) { taskType = ITask.DOWNLOAD_GROUP; } else if (mTaskWrapper instanceof UTaskWrapper) { taskType = ITask.UPLOAD; } return taskType; } /** * 如果检查实体失败,将错误回调 */ boolean checkConfig() { if (!ignoreCheckPermissions && !checkPermission()) { return false; } boolean b = checkEntity(); TaskSchedulers schedulers = TaskSchedulers.getInstance(); if (!b && schedulers != null) { new Handler(Looper.getMainLooper(), schedulers).obtainMessage(ISchedulers.CHECK_FAIL, checkTaskType(), -1, null).sendToTarget(); } return b; } /** * 检查权限,需要的权限有 * {@link Manifest.permission#WRITE_EXTERNAL_STORAGE} * {@link Manifest.permission#READ_EXTERNAL_STORAGE} * {@link Manifest.permission#INTERNET} * * @return {@code false} 缺少权限 */ private boolean checkPermission() { if (AriaConfig.getInstance() .getAPP() .checkCallingOrSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ALog.e(TAG, "启动失败,缺少权限:Manifest.permission.WRITE_EXTERNAL_STORAGE"); return false; } if (AriaConfig.getInstance() .getAPP() .checkCallingOrSelfPermission(Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED) { ALog.e(TAG, "启动失败,缺少权限:Manifest.permission.INTERNET"); return false; } if (AriaConfig.getInstance() .getAPP() .checkCallingOrSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ALog.e(TAG, "启动失败,缺少权限:Manifest.permission.READ_EXTERNAL_STORAGE"); return false; } return true; } private boolean checkEntity() { ICheckEntityUtil checkUtil = null; if (mTaskWrapper instanceof DTaskWrapper) { checkUtil = CheckDEntityUtil.newInstance((DTaskWrapper) mTaskWrapper, action); } else if (mTaskWrapper instanceof DGTaskWrapper) { if (mTaskWrapper.getRequestType() == ITaskWrapper.D_FTP_DIR) { checkUtil = CheckFtpDirEntityUtil.newInstance((DGTaskWrapper) mTaskWrapper, action); } else if (mTaskWrapper.getRequestType() == ITaskWrapper.DG_HTTP) { checkUtil = CheckDGEntityUtil.newInstance((DGTaskWrapper) mTaskWrapper, action); } } else if (mTaskWrapper instanceof UTaskWrapper) { checkUtil = CheckUEntityUtil.newInstance((UTaskWrapper) mTaskWrapper, action); } return checkUtil != null && checkUtil.checkEntity(); } }
923228892b7dc2a63258e41984e8aa6e8d374752
243
java
Java
src/main/java/com/mongodb/starter/repositories/RegulationRepository.java
nhnam1105/hackcovy-backend
d4892d3f3656dcdc9a11c8d21871d116963c6132
[ "Apache-2.0" ]
null
null
null
src/main/java/com/mongodb/starter/repositories/RegulationRepository.java
nhnam1105/hackcovy-backend
d4892d3f3656dcdc9a11c8d21871d116963c6132
[ "Apache-2.0" ]
null
null
null
src/main/java/com/mongodb/starter/repositories/RegulationRepository.java
nhnam1105/hackcovy-backend
d4892d3f3656dcdc9a11c8d21871d116963c6132
[ "Apache-2.0" ]
null
null
null
22.090909
86
0.851852
996,124
package com.mongodb.starter.repositories; import com.mongodb.starter.models.Regulation; import org.springframework.stereotype.Repository; @Repository public interface RegulationRepository extends GenericComponentRepository<Regulation> { }
9232288a240775b45b55a5074bd8a7763d47cd10
2,995
java
Java
src/main/java/org/synyx/urlaubsverwaltung/workingtime/WorkingTimeForm.java
nikoszagk/urlaubsverwaltung
5d5d5283c1d55756835ad25b7919526ec88ab233
[ "Apache-2.0" ]
null
null
null
src/main/java/org/synyx/urlaubsverwaltung/workingtime/WorkingTimeForm.java
nikoszagk/urlaubsverwaltung
5d5d5283c1d55756835ad25b7919526ec88ab233
[ "Apache-2.0" ]
null
null
null
src/main/java/org/synyx/urlaubsverwaltung/workingtime/WorkingTimeForm.java
nikoszagk/urlaubsverwaltung
5d5d5283c1d55756835ad25b7919526ec88ab233
[ "Apache-2.0" ]
null
null
null
29.95
89
0.692487
996,125
package org.synyx.urlaubsverwaltung.workingtime; import org.springframework.format.annotation.DateTimeFormat; import org.synyx.urlaubsverwaltung.period.DayLength; import java.time.DayOfWeek; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; import java.util.Objects; import static java.time.format.DateTimeFormatter.ISO_DATE; import static org.synyx.urlaubsverwaltung.period.DayLength.ZERO; import static org.synyx.urlaubsverwaltung.util.DateAndTimeFormat.DD_MM_YYYY; import static org.synyx.urlaubsverwaltung.util.DateAndTimeFormat.D_M_YY; import static org.synyx.urlaubsverwaltung.util.DateAndTimeFormat.D_M_YYYY; public class WorkingTimeForm { @DateTimeFormat(pattern = DD_MM_YYYY, fallbackPatterns = {D_M_YY, D_M_YYYY}) private LocalDate validFrom; private List<Integer> workingDays = new ArrayList<>(); private FederalState federalState; private boolean isDefaultFederalState; WorkingTimeForm() { // OK } WorkingTimeForm(WorkingTime workingTime) { for (DayOfWeek dayOfWeek : DayOfWeek.values()) { final DayLength dayLength = workingTime.getDayLengthForWeekDay(dayOfWeek); if (dayLength != ZERO) { workingDays.add(dayOfWeek.getValue()); } } this.validFrom = workingTime.getValidFrom(); this.federalState = workingTime.getFederalState(); this.isDefaultFederalState = workingTime.isDefaultFederalState(); } public String getValidFromIsoValue() { if (validFrom == null) { return ""; } return validFrom.format(ISO_DATE); } public LocalDate getValidFrom() { return validFrom; } public void setValidFrom(LocalDate validFrom) { this.validFrom = validFrom; } public List<Integer> getWorkingDays() { return workingDays; } public void setWorkingDays(List<Integer> workingDays) { this.workingDays = workingDays; } public FederalState getFederalState() { return federalState; } public void setFederalState(FederalState federalState) { this.federalState = federalState; } public boolean isDefaultFederalState() { return isDefaultFederalState; } public void setDefaultFederalState(boolean defaultFederalState) { isDefaultFederalState = defaultFederalState; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; WorkingTimeForm that = (WorkingTimeForm) o; return isDefaultFederalState == that.isDefaultFederalState && Objects.equals(validFrom, that.validFrom) && Objects.equals(workingDays, that.workingDays) && federalState == that.federalState; } @Override public int hashCode() { return Objects.hash(validFrom, workingDays, federalState, isDefaultFederalState); } }
923228c7180aa5dda0c73e96261a818f2bad5991
640
java
Java
drift-jdbc/drift-jdbc-springboot/src/main/java/io/drift/plugin/jdbc/ui/app/flux/snapshot/viewpart/RootsViewPart.java
drift-io/drift-server
8d4fc8db9e746c7b4cd9ef5c4b0688cb71bbf601
[ "Apache-2.0" ]
17
2019-07-31T10:04:29.000Z
2019-10-19T21:22:06.000Z
drift-jdbc/drift-jdbc-springboot/src/main/java/io/drift/plugin/jdbc/ui/app/flux/snapshot/viewpart/RootsViewPart.java
driftserver/drift-server
4b2eeaf7d1737da8480e5620718a6e0caacfa3bf
[ "Apache-2.0" ]
2
2019-11-14T13:27:33.000Z
2019-11-14T15:31:21.000Z
drift-jdbc/drift-jdbc-springboot/src/main/java/io/drift/plugin/jdbc/ui/app/flux/snapshot/viewpart/RootsViewPart.java
drift-io/drift-server
8d4fc8db9e746c7b4cd9ef5c4b0688cb71bbf601
[ "Apache-2.0" ]
1
2019-08-11T06:25:57.000Z
2019-08-11T06:25:57.000Z
24.615385
83
0.726563
996,126
package io.drift.plugin.jdbc.ui.app.flux.snapshot.viewpart; import io.drift.plugin.jdbc.ui.app.flux.snapshot.graphmodel.TableRoot; import java.io.Serializable; import java.util.List; public class RootsViewPart extends ViewPart implements Serializable { private List<TableRoot> roots; public RootsViewPart(List<TableRoot> roots) { this.roots = roots; } public List<TableRoot> getRoots() { return roots; } public void select(TableRoot rootDescriptor) { DBSnapshotMainViewPart mainViewPart = (DBSnapshotMainViewPart) getParent(); mainViewPart.selectRoot(rootDescriptor); } }
92322a7fbbfc5f9e091593021656c48723072e78
4,227
java
Java
whois-update/src/main/java/net/ripe/db/whois/update/mail/MailGatewaySmtp.java
acidburn0zzz/whois-1
7e32ae63294e74274e825a7e54a5446893abc260
[ "BSD-3-Clause" ]
1
2016-04-19T16:56:20.000Z
2016-04-19T16:56:20.000Z
whois-update/src/main/java/net/ripe/db/whois/update/mail/MailGatewaySmtp.java
Acidburn0zzz/whois-1
7e32ae63294e74274e825a7e54a5446893abc260
[ "BSD-3-Clause" ]
1
2021-08-02T17:24:50.000Z
2021-08-02T17:24:50.000Z
whois-update/src/main/java/net/ripe/db/whois/update/mail/MailGatewaySmtp.java
Acidburn0zzz/whois-1
7e32ae63294e74274e825a7e54a5446893abc260
[ "BSD-3-Clause" ]
null
null
null
39.504673
139
0.636858
996,127
package net.ripe.db.whois.update.mail; import net.ripe.db.whois.common.Message; import net.ripe.db.whois.common.Messages; import net.ripe.db.whois.common.aspects.RetryFor; import net.ripe.db.whois.update.domain.ResponseMessage; import net.ripe.db.whois.update.log.LoggerContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.mail.MailException; import org.springframework.mail.MailSendException; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.mail.javamail.MimeMessagePreparator; import org.springframework.stereotype.Component; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import java.util.regex.Matcher; import java.util.regex.Pattern; @Component public class MailGatewaySmtp implements MailGateway { private static final Pattern INVALID_EMAIL_PATTERN = Pattern.compile("(?i)((?:auto|test)efpyi@example.com)"); private static final Logger LOGGER = LoggerFactory.getLogger(MailGatewaySmtp.class); private final LoggerContext loggerContext; private final MailConfiguration mailConfiguration; private final JavaMailSender mailSender; @Value("${mail.smtp.enabled}") private boolean outgoingMailEnabled; @Value("${mail.smtp.retrySending:true}") private boolean retrySending; @Autowired public MailGatewaySmtp(final LoggerContext loggerContext, final MailConfiguration mailConfiguration, final JavaMailSender mailSender) { this.loggerContext = loggerContext; this.mailConfiguration = mailConfiguration; this.mailSender = mailSender; } @Override public void sendEmail(final String to, final ResponseMessage responseMessage) { sendEmail(to, responseMessage.getSubject(), responseMessage.getMessage()); } @Override public void sendEmail(final String to, final String subject, final String text) { if (!outgoingMailEnabled) { LOGGER.debug("" + "Outgoing mail disabled\n" + "\n" + "to : {}\n" + "subject : {}\n" + "\n" + "{}\n" + "\n" + "\n", to, subject, text); return; } try { final Matcher matcher = INVALID_EMAIL_PATTERN.matcher(to); if (matcher.find()) { throw new MailSendException("Refusing outgoing email: " + text); } sendEmailAttempt(to, subject, text); } catch (MailException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to send mail to {} with subject {}", to, subject), e); LOGGER.error("Unable to send mail message to: {}", to, e); } } @RetryFor(value = MailSendException.class, attempts = 20, intervalMs = 10000) private void sendEmailAttempt(final String to, final String subject, final String text) { try { mailSender.send(new MimeMessagePreparator() { @Override public void prepare(final MimeMessage mimeMessage) throws MessagingException { final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, MimeMessageHelper.MULTIPART_MODE_NO, "UTF-8"); message.setFrom(mailConfiguration.getFrom()); message.setTo(to); message.setSubject(subject); message.setText(text); mimeMessage.addHeader("Precedence", "bulk"); mimeMessage.addHeader("Auto-Submitted", "auto-generated"); loggerContext.log("msg-out.txt", new MailMessageLogCallback(mimeMessage)); } }); } catch (MailSendException e) { if (retrySending) { throw e; } else { LOGGER.info("not retrying sending mail to {}", to); } } } }
92322c2cad1087f9ad37ede6f7478e1540141502
4,650
java
Java
base.app.backoffice.console/src/main/java/eapli/base/app/backoffice/console/presentation/colaborator/AdicionarColaboratorUI.java
rafael-ribeiro1/lapr4-isep
80ed93bcf377b70e23a0c41ee332dd6666244611
[ "MIT" ]
null
null
null
base.app.backoffice.console/src/main/java/eapli/base/app/backoffice/console/presentation/colaborator/AdicionarColaboratorUI.java
rafael-ribeiro1/lapr4-isep
80ed93bcf377b70e23a0c41ee332dd6666244611
[ "MIT" ]
null
null
null
base.app.backoffice.console/src/main/java/eapli/base/app/backoffice/console/presentation/colaborator/AdicionarColaboratorUI.java
rafael-ribeiro1/lapr4-isep
80ed93bcf377b70e23a0c41ee332dd6666244611
[ "MIT" ]
null
null
null
46.969697
190
0.733548
996,128
package eapli.base.app.backoffice.console.presentation.colaborator; import eapli.base.app.common.console.presentation.menuselect.MultipleSelectionWidget; import eapli.base.app.common.console.presentation.menuselect.SingleSelectionWidget; import eapli.base.colaboratormanagement.application.AdicionarColaboradorController; import eapli.base.colaboratormanagement.domain.Colaborador; import eapli.base.colaboratormanagement.domain.Funcao; import eapli.base.colaboratormanagement.dto.ColaboradorDTO; import eapli.base.teammanagement.domain.Equipa; import eapli.framework.domain.repositories.ConcurrencyException; import eapli.framework.domain.repositories.IntegrityViolationException; import eapli.framework.io.util.Console; import eapli.framework.presentation.console.AbstractUI; import eapli.framework.time.util.Calendars; import javax.persistence.RollbackException; import java.util.Calendar; import java.util.HashSet; import java.util.Set; /** * UI for adding a colaborator to the application. Created by Eduardo Couto (1190549). */ public class AdicionarColaboratorUI extends AbstractUI { private final AdicionarColaboradorController controller = new AdicionarColaboradorController(); @Override protected boolean doShow() { final String username = Console.readNonEmptyLine("Name of the username:","Write a non empty username"); final String numMecano = Console.readNonEmptyLine("Mecanographic Number:","Write a non empty mecanographic number"); final String institucionalEmail = Console.readNonEmptyLine("Institucional Email:","Write a non empty email"); final String firstName = Console.readNonEmptyLine("First name:","Write a non empty first name"); final String lastName = Console.readNonEmptyLine("Last name:","Write a non empty last name"); final String completeName = Console.readNonEmptyLine("Full name:","Write a non empty full name"); final Calendar birthDate = Console.readCalendar("Birthday date(dd-MM-yyyy):"); final String district = Console.readNonEmptyLine("Current District:","Write a non empty district"); final String county = Console.readNonEmptyLine("Current County:","Write a non empty county"); final String contactNumber = Console.readNonEmptyLine("Contact Number","Write a non empty contact"); Funcao function = doSelectionFunction(); ColaboradorDTO responsavel = doSelectColaborator(); Set<Equipa> selectedEquipas = doSelectEquips(); if(!Console.readBoolean("Confirm Register (y/n) ?")) return false; try{ controller.registerColaborator(username,institucionalEmail,numMecano,firstName,lastName,completeName,birthDate,district,county,contactNumber,function,responsavel,selectedEquipas); System.out.println("Colaborator registered with sucess"); }catch (final IntegrityViolationException | ConcurrencyException |RollbackException e){ System.out.println("Error adding colaborator"); } catch (IllegalArgumentException e) { System.out.println("Error: " + e); } return false; } private Funcao doSelectionFunction(){ System.out.println("----Select Function----"); Iterable<Funcao> funcoes = controller.listFunctions(); SingleSelectionWidget<Funcao> funcaoSelector = new SingleSelectionWidget<>(funcoes); funcaoSelector.doSelection(); return funcaoSelector.selectedItem(); } private ColaboradorDTO doSelectColaborator(){ System.out.println("----Select hierarchical responsible----"); Iterable<ColaboradorDTO> colaboradores = controller.listColaboradores(); SingleSelectionWidget<ColaboradorDTO> selecaoResponsavel = new SingleSelectionWidget<>(colaboradores); selecaoResponsavel.doSelection(); return selecaoResponsavel.selectedItem(); } private Set<Equipa> doSelectEquips(){ System.out.println("----Select Teams ----"); Set<Equipa> selectedEquipas = new HashSet<>(); Iterable<Equipa> equipa = controller.listEquipas(); MultipleSelectionWidget<Equipa> equipaSelect = new MultipleSelectionWidget<>(equipa,selectedEquipas); boolean showError; do { selectedEquipas.clear(); equipaSelect.doSelection(); showError=controller.validateEquipasColaborador(selectedEquipas); if(!showError) System.out.println("Cant select teams with same type"); } while(!showError); return selectedEquipas; } @Override public String headline() { return "Specify new Collaborator"; } }
92322c55f917d00d594495150b34da71f5d20182
1,907
java
Java
src/main/java/com/misternerd/djiax/IaxPeerFactory.java
misternerd/djiax
02e2b317c7541e2caea520df94477eae98413f26
[ "Apache-2.0" ]
3
2015-07-19T11:32:00.000Z
2020-04-15T23:25:18.000Z
src/main/java/com/misternerd/djiax/IaxPeerFactory.java
misternerd/djiax
02e2b317c7541e2caea520df94477eae98413f26
[ "Apache-2.0" ]
1
2016-09-05T11:37:34.000Z
2016-10-13T18:34:42.000Z
src/main/java/com/misternerd/djiax/IaxPeerFactory.java
misternerd/djiax
02e2b317c7541e2caea520df94477eae98413f26
[ "Apache-2.0" ]
4
2016-12-26T00:08:10.000Z
2021-05-04T19:14:46.000Z
26.486111
113
0.766125
996,129
package com.misternerd.djiax; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.misternerd.djiax.exception.NoPeerAvailableException; public class IaxPeerFactory { private static final Logger logger = LoggerFactory.getLogger(IaxPeerFactory.class); private static final Map<Short, IaxPeer> activePeers = new HashMap<>(); private static Short nextPeerSourceCallNumber = 1; private static int maxNumberOfCallsPerPeer = 50; public static synchronized IaxPeer createNewPeer(String host, int port, String username, String password, IaxClientObserver peerObserver) throws IOException, NoPeerAvailableException { for (int j = 0; j < PeerConstants.PEER_MAX_SOURCE_CALL_NUMBER; j++) { nextPeerSourceCallNumber++; if (nextPeerSourceCallNumber > PeerConstants.PEER_MAX_SOURCE_CALL_NUMBER) { nextPeerSourceCallNumber = 1; } if (!activePeers.containsKey(nextPeerSourceCallNumber)) { IaxPeer iaxPeer = new IaxPeer(host, port, username, password, maxNumberOfCallsPerPeer, peerObserver, nextPeerSourceCallNumber); activePeers.put(nextPeerSourceCallNumber, iaxPeer); return iaxPeer; } } logger.error("Failed to create new IaxPeer after {} tries, stopped at index {}", PeerConstants.PEER_MAX_SOURCE_CALL_NUMBER, nextPeerSourceCallNumber); throw new NoPeerAvailableException(); } protected synchronized void removePeer(IaxPeer peer) { IaxPeer peerInMap = activePeers.get(peer.getSourceCallNumber()); if (peerInMap == null || peer != peerInMap) { logger.warn("Tried to remove peer with sourceCallNumber={}, but is not in list!", peer.getSourceCallNumber()); } activePeers.remove(peer.getSourceCallNumber()); } public static void setMaxNumberOfCallsPerPeer(int numberOfCalls) { maxNumberOfCallsPerPeer = numberOfCalls; } }
92322d0dcbce94a91c091c5d78d9a7a1f23125ae
273
java
Java
tangtianup-thinking-in-java-concurrency/src/main/java/top/tangtian/basic/VolatileExample.java
tangtian8/tangtian_up
879c7943e64b524dbc7801a0016d500a47c4ffb6
[ "Apache-2.0" ]
1
2021-06-22T07:08:42.000Z
2021-06-22T07:08:42.000Z
tangtianup-thinking-in-java-concurrency/src/main/java/top/tangtian/basic/VolatileExample.java
tangtian8/tangtian_up
879c7943e64b524dbc7801a0016d500a47c4ffb6
[ "Apache-2.0" ]
null
null
null
tangtianup-thinking-in-java-concurrency/src/main/java/top/tangtian/basic/VolatileExample.java
tangtian8/tangtian_up
879c7943e64b524dbc7801a0016d500a47c4ffb6
[ "Apache-2.0" ]
null
null
null
16.058824
49
0.586081
996,130
package top.tangtian.basic; /** * @author tangtian * @description * @date 2021/8/2 7:03 */ public class VolatileExample implements Runnable{ int x = 0; volatile boolean v = false; @Override public void run() { x = 42; v = true; } }
92322e42ab1e56de7ab2b4f7c957b71c57954708
4,802
java
Java
app/src/main/java/com/jmtad/jftt/adapter/CollectionAdapter.java
flappy8023/jftt
5a6ed260283935476aedfc9fb778c0a54db2de41
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/jmtad/jftt/adapter/CollectionAdapter.java
flappy8023/jftt
5a6ed260283935476aedfc9fb778c0a54db2de41
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/jmtad/jftt/adapter/CollectionAdapter.java
flappy8023/jftt
5a6ed260283935476aedfc9fb778c0a54db2de41
[ "Apache-2.0" ]
null
null
null
32.013333
106
0.619325
996,131
package com.jmtad.jftt.adapter; import android.content.Context; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.jmtad.jftt.R; import com.jmtad.jftt.http.bean.node.Banner; import com.jmtad.jftt.manager.BannerManager; import com.jmtad.jftt.util.GlideUtil; import java.util.ArrayList; import java.util.List; /** * @description:收藏页面图文列表适配器 * @author: luweiming * @create: 2018-11-26 11:24 **/ public class CollectionAdapter extends RecyclerView.Adapter<CollectionAdapter.MyHolder> { Context mContext; List<Banner> mDatas; private boolean isDeleteMode = false;//是否处于选择删除状态下 private List<Banner> deletingBanners = new ArrayList<>();//待删除列表 public CollectionAdapter(Context context, List<Banner> bannerList) { mContext = context; mDatas = bannerList; } public void setDeleteMode(boolean deleteMode) { isDeleteMode = deleteMode; } public boolean isDeleteMode() { return isDeleteMode; } @NonNull @Override public MyHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(mContext).inflate(R.layout.item_collections, parent, false); return new MyHolder(view); } @Override public void onBindViewHolder(@NonNull MyHolder holder, int position, @NonNull List<Object> payloads) { super.onBindViewHolder(holder, position, payloads); } @Override public void onBindViewHolder(@NonNull MyHolder holder, int position) { Banner banner = mDatas.get(position); holder.tvTitle.setText(banner.getTitle()); holder.tvDes.setText(banner.getSummary()); GlideUtil.loadImage(mContext, banner.getImgUrl(), holder.ivPoster); if (isDeleteMode) { holder.cbSelect.setVisibility(View.VISIBLE); if (banner.isSelected) { holder.cbSelect.setImageResource(R.drawable.select_1); } else { holder.cbSelect.setImageResource(R.drawable.select_0); } } else { holder.cbSelect.setVisibility(View.GONE); } holder.itemView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View view) { //长按item进入删除模式 if (!isDeleteMode) { isDeleteMode = true; notifyDataSetChanged(); banner.isSelected = true; deletingBanners.add(banner); holder.cbSelect.setImageResource(R.drawable.select_1); if (null != itemListener) { itemListener.onDeleteMode(); } } return true; } }); holder.itemView.setOnClickListener(view -> { //点击item时,如果当前处于删除状态,判断该item还未被选中,将该item添加到待删除列表,已选中则从待删除列表移除;如果未处于删除状态,则直接进入图文详情 if (isDeleteMode) { if (!banner.isSelected) { banner.isSelected = true; deletingBanners.add(banner); holder.cbSelect.setImageResource(R.drawable.select_1); } else { banner.isSelected = false; deletingBanners.remove(banner); holder.cbSelect.setImageResource(R.drawable.select_0); } } else { BannerManager.clickBanner(banner, mContext); } }); } /** * 或取待删除的图文列表 * * @return */ public List<Banner> getDeletingBanners() { return deletingBanners; } @Override public int getItemCount() { return null == mDatas ? 0 : mDatas.size(); } class MyHolder extends RecyclerView.ViewHolder { TextView tvTitle, tvDes; ImageView ivPoster; ImageView cbSelect; public MyHolder(View itemView) { super(itemView); initView(itemView); } private void initView(View itemView) { tvDes = itemView.findViewById(R.id.tv_item_collection_des); tvTitle = itemView.findViewById(R.id.tv_item_collection_title); ivPoster = itemView.findViewById(R.id.iv_item_collection_poster); cbSelect = itemView.findViewById(R.id.iv_item_collection_select); } } private OnItemListener itemListener; public void setItemListener(OnItemListener itemListener) { this.itemListener = itemListener; } public interface OnItemListener { void onDeleteMode(); } }
92322ff8e10471d2db7555be569974453c367764
4,309
java
Java
ops4j-base-io/src/main/java/org/ops4j/io/ZipLister.java
coheigea/org.ops4j.base
c2d9e31d846a75c9314dadce4f5cc75a4cfb89e3
[ "Apache-2.0" ]
2
2018-02-05T10:09:15.000Z
2022-01-08T06:20:54.000Z
ops4j-base-io/src/main/java/org/ops4j/io/ZipLister.java
coheigea/org.ops4j.base
c2d9e31d846a75c9314dadce4f5cc75a4cfb89e3
[ "Apache-2.0" ]
2
2016-03-08T20:33:05.000Z
2019-02-22T10:19:05.000Z
ops4j-base-io/src/main/java/org/ops4j/io/ZipLister.java
coheigea/org.ops4j.base
c2d9e31d846a75c9314dadce4f5cc75a4cfb89e3
[ "Apache-2.0" ]
5
2015-12-24T14:57:47.000Z
2019-09-26T09:07:25.000Z
28.919463
96
0.592017
996,132
package org.ops4j.io; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.regex.Pattern; import java.util.zip.ZipEntry; import org.ops4j.lang.NullArgumentException; /** * Implementation of lister that list content of a zip file. * * @author Alin Dreghiciu * @since September 04, 2007 */ public class ZipLister implements Lister { /** * The url of the file from which the zip file was constructed. */ private URL m_baseURL; /** * The root zip entries to be listed. */ private final Enumeration<? extends ZipEntry> m_zipEntries; /** * File path include filters. */ private final Pattern[] m_includes; /** * File path exclude filters. */ private final Pattern[] m_excludes; /** * Creates a zip lister. * * @param baseURL the url from which the zip file was created * @param zipEntries the zip file to be listed. * @param filter filter to be used to filter entries from the zip */ public ZipLister( final URL baseURL, final Enumeration<? extends ZipEntry> zipEntries, final Pattern filter ) { NullArgumentException.validateNotNull( baseURL, "Base url" ); NullArgumentException.validateNotNull( zipEntries, "Zip entries" ); NullArgumentException.validateNotNull( filter, "Filter" ); m_baseURL = baseURL; m_zipEntries = zipEntries; m_includes = new Pattern[]{ filter }; m_excludes = new Pattern[0]; } /** * Creates a zip lister. * * @param baseURL the url from which the zip file was created * @param zipEntries the zip file to be listed. * @param includes filters to be used to include entries from the directory * @param excludes filters to be used to exclude entries from the directory */ public ZipLister( final URL baseURL, final Enumeration<? extends ZipEntry> zipEntries, final Pattern[] includes, final Pattern[] excludes ) { NullArgumentException.validateNotNull( baseURL, "Base url" ); NullArgumentException.validateNotNull( zipEntries, "Zip entries" ); NullArgumentException.validateNotNull( includes, "Include filters" ); NullArgumentException.validateNotNull( includes, "Exclude filters" ); m_baseURL = baseURL; m_zipEntries = zipEntries; m_includes = includes; m_excludes = excludes; } /** * {@inheritDoc} */ public List<URL> list() throws MalformedURLException { final List<URL> content = new ArrayList<URL>(); // then we filter them based on configured filter while( m_zipEntries.hasMoreElements() ) { final ZipEntry entry = m_zipEntries.nextElement(); final String fileName = entry.getName(); if( !entry.isDirectory() && matchesIncludes( fileName ) && !matchesExcludes( fileName ) ) { content.add( new URL( "jar:" + m_baseURL.toExternalForm() + "!/" + fileName ) ); } } return content; } /** * Checks if the file name matches inclusion patterns. * * @param fileName file name to be matched * * @return true if matches, false otherwise */ private boolean matchesIncludes( final String fileName ) { if( m_includes.length == 0 ) { return true; } for( Pattern include : m_includes ) { if( include.matcher( fileName ).matches() ) { return true; } } return false; } /** * Checks if the file name matches exclusion patterns. * * @param fileName file name to be matched * * @return true if matches, false otherwise */ private boolean matchesExcludes( final String fileName ) { for( Pattern include : m_excludes ) { if( include.matcher( fileName ).matches() ) { return true; } } return false; } }
9232301b4138fb694dc1f06367f312d567da2940
3,343
java
Java
maven/org.jflux.spec.discovery/src/main/java/org/jflux/spec/discovery/Beacon.java
stub22/glue-ai-v1_jflux
e664651a68a9f488a774a3003dde7176dc734772
[ "Apache-2.0" ]
null
null
null
maven/org.jflux.spec.discovery/src/main/java/org/jflux/spec/discovery/Beacon.java
stub22/glue-ai-v1_jflux
e664651a68a9f488a774a3003dde7176dc734772
[ "Apache-2.0" ]
null
null
null
maven/org.jflux.spec.discovery/src/main/java/org/jflux/spec/discovery/Beacon.java
stub22/glue-ai-v1_jflux
e664651a68a9f488a774a3003dde7176dc734772
[ "Apache-2.0" ]
null
null
null
30.990741
77
0.600538
996,133
/* * Copyright 2014 the Friendularity Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jflux.spec.discovery; import java.io.IOException; import java.net.DatagramPacket; import java.net.InetAddress; import java.net.MulticastSocket; import java.net.UnknownHostException; import org.jflux.api.common.rk.utils.TimeUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author Amy Jessica Book <anpch@example.com> */ public class Beacon implements Runnable { private final static String theSsdpAddr = "192.168.127.12"; private final static int theSsdpPort = 1900; private final static Logger theLogger = LoggerFactory.getLogger(Beacon.class); private SerialNumberSpec mySerialNumber; private boolean myRunning; public Beacon(SerialNumberSpec serialNumber) { mySerialNumber = serialNumber; myRunning = false; } public Beacon() { mySerialNumber = new SerialNumberSpec(); mySerialNumber.setSerialNumber("000001"); } @Override public void run() { InetAddress group; MulticastSocket sock; try { group = InetAddress.getByName(theSsdpAddr); } catch(UnknownHostException ex) { theLogger.error( "Unknown host " + theSsdpAddr + ": " + ex.getMessage()); return; } try { sock = new MulticastSocket(theSsdpPort); sock.joinGroup(group); } catch(IOException ex) { theLogger.error("Error creating socket: " + ex.getMessage()); return; } StringBuilder sb = new StringBuilder(); sb.append("NOTIFY * HTTP/1.1\r\n"); sb.append("HOST: 192.168.127.12:1900\r\n"); sb.append("NTS: ssdp:alive\r\n"); sb.append("EXT: \r\n"); sb.append("USN: JFlux\r\n"); sb.append("CACHE-CONTROL: max-age=1800\r\n"); sb.append("SERVER: Linux,"); sb.append(System.getProperty("os.version")); sb.append(",GLUE-AI\r\n"); sb.append("LOCATION: "); sb.append(mySerialNumber.getBroadcastId()); sb.append("\r\n"); sb.append("NT: upnp:rootdevice\r\n"); String http = sb.toString(); myRunning = true; while(myRunning) { DatagramPacket message = new DatagramPacket( http.getBytes(), http.length(), group, 1900); try { sock.send(message); } catch(IOException ex) { theLogger.error("Error sending message: " + ex.getMessage()); } TimeUtils.sleep(10000); } } public void stop() { myRunning = false; } }
9232301d29f9e206bbc1a996810ad23acc6142fd
1,280
java
Java
src/main/CharacterNote.java
RodneyMcQuain/Melee-Notes
3ee9a6210a2436548b8f30c2a31da954ad6b38ae
[ "MIT" ]
1
2021-01-12T07:32:20.000Z
2021-01-12T07:32:20.000Z
src/main/CharacterNote.java
RodneyMcQuain/Melee-Notes
3ee9a6210a2436548b8f30c2a31da954ad6b38ae
[ "MIT" ]
null
null
null
src/main/CharacterNote.java
RodneyMcQuain/Melee-Notes
3ee9a6210a2436548b8f30c2a31da954ad6b38ae
[ "MIT" ]
null
null
null
19.692308
104
0.728906
996,134
package main; public class CharacterNote { private int characterNoteID; private int characterID; private int userID; private String subject; private String notes; public CharacterNote (int characterNoteID, int characterID, int userID, String subject, String notes) { this.characterNoteID = characterNoteID; this.characterID = characterID; this.userID = userID; this.subject = subject; this.notes = notes; } public CharacterNote (int characterID, int userID, String subject, String notes) { this.characterID = characterID; this.userID = userID; this.subject = subject; this.notes = notes; } public int getCharacterNoteID() { return characterNoteID; } public void setCharacterNoteID(int characterNoteID) { this.characterNoteID = characterNoteID; } public int getCharacterID() { return characterID; } public void setCharacterID(int characterID) { this.characterID = characterID; } public int getUserID() { return userID; } public void setUserID(int userID) { this.userID = userID; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getNotes() { return notes; } public void setNotes(String notes) { this.notes = notes; } }
92323149af8ee7d97e795e0def19bd6749f41e44
1,085
java
Java
src/main/java/com/sap/api/workflow/controller/WorkflowController.java
SAP-samples/cloud-workflow-spring-sample
dce22adae6c4bdbc858069f605a488902a191e85
[ "Apache-2.0" ]
2
2020-06-20T00:36:04.000Z
2020-07-07T17:04:14.000Z
src/main/java/com/sap/api/workflow/controller/WorkflowController.java
SAP-samples/cloud-workflow-spring-sample
dce22adae6c4bdbc858069f605a488902a191e85
[ "Apache-2.0" ]
null
null
null
src/main/java/com/sap/api/workflow/controller/WorkflowController.java
SAP-samples/cloud-workflow-spring-sample
dce22adae6c4bdbc858069f605a488902a191e85
[ "Apache-2.0" ]
2
2020-07-07T17:04:16.000Z
2021-04-01T22:18:19.000Z
36.166667
122
0.796313
996,135
package com.sap.api.workflow.controller; import com.sap.api.workflow.domain.workflow.definition.WorkflowDefinition; import com.sap.api.workflow.domain.workflow.instance.WorkflowInstanceRequest; import com.sap.api.workflow.domain.workflow.instance.WorkflowInstanceResponse; import com.sap.api.workflow.service.WorkflowService; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping(value = "/workflow") public class WorkflowController { private final WorkflowService workflowService; public WorkflowController(WorkflowService workflowService) { this.workflowService = workflowService; } @GetMapping(value = "/definition/list") public List<WorkflowDefinition> getWorkflowDefinitions() { return workflowService.getWorkflowDefinitions(); } @PostMapping(value = "/instance/new") public WorkflowInstanceResponse createWorkflowInstance(@RequestBody WorkflowInstanceRequest workflowInstanceRequest) { return workflowService.createWorkflowInstance(workflowInstanceRequest); } }
923231712e03a3c0c021d15e0f61aae91013ddf5
602
java
Java
src/main/java/isa/adventuretime/Entity/Rating.java
todorcevicM/ftn-isa-adventure-time
c4a486922f0e7f76a650c06af0e792f2ad87db50
[ "MIT" ]
1
2022-03-24T07:45:22.000Z
2022-03-24T07:45:22.000Z
src/main/java/isa/adventuretime/Entity/Rating.java
todorcevicM/ftn-isa-adventure-time
c4a486922f0e7f76a650c06af0e792f2ad87db50
[ "MIT" ]
null
null
null
src/main/java/isa/adventuretime/Entity/Rating.java
todorcevicM/ftn-isa-adventure-time
c4a486922f0e7f76a650c06af0e792f2ad87db50
[ "MIT" ]
null
null
null
22.296296
64
0.785714
996,136
package isa.adventuretime.Entity; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.Getter; import lombok.Setter; @Entity @Getter @Setter @JsonIgnoreProperties({ "hibernateLazyInitializer", "handler" }) public class Rating { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) protected Long id; private Long raterId; private Long ratedId; private HeadEntityEnum forEntity; private int rating; }
923232daec4db68881fe45f90ffae9c84d8d8507
290
java
Java
source/main/java/com/avereon/zenna/icon/ArrowDownIcon.java
avereon/rossa
f3f921cb7635cff2c1ae084d70c096a472a93d4e
[ "MIT" ]
null
null
null
source/main/java/com/avereon/zenna/icon/ArrowDownIcon.java
avereon/rossa
f3f921cb7635cff2c1ae084d70c096a472a93d4e
[ "MIT" ]
2
2020-03-25T17:53:20.000Z
2020-07-01T22:05:28.000Z
source/main/java/com/avereon/zenna/icon/ArrowDownIcon.java
avereon/zenna
75e2845fb5c52432c6e4633da7d644b250749199
[ "MIT" ]
null
null
null
18.125
47
0.7
996,137
package com.avereon.zenna.icon; import com.avereon.zarra.image.RenderedIcon; public class ArrowDownIcon extends ArrowIcon { protected void rotate() { spin( g( 16 ), g( 16 ), 180 ); } public static void main( String[] commands ) { RenderedIcon.proof( new ArrowDownIcon() ); } }
9232340dc897d4fdf8e278c7904d58670d74db8c
11,576
java
Java
uberfire-extensions/uberfire-wires/uberfire-wires-bpmn/uberfire-wires-bpmn-client/src/test/java/org/uberfire/ext/wires/bpmn/client/AbstractBaseRuleTest.java
LeonidLapshin/appformer
2cf15393aeb922cab813938aee2c665d51ede57f
[ "Apache-2.0" ]
157
2017-09-26T17:42:08.000Z
2022-03-11T06:48:15.000Z
uberfire-extensions/uberfire-wires/uberfire-wires-bpmn/uberfire-wires-bpmn-client/src/test/java/org/uberfire/ext/wires/bpmn/client/AbstractBaseRuleTest.java
LeonidLapshin/appformer
2cf15393aeb922cab813938aee2c665d51ede57f
[ "Apache-2.0" ]
940
2017-03-21T08:15:36.000Z
2022-03-25T13:18:36.000Z
uberfire-extensions/uberfire-wires/uberfire-wires-bpmn/uberfire-wires-bpmn-client/src/test/java/org/uberfire/ext/wires/bpmn/client/AbstractBaseRuleTest.java
LeonidLapshin/appformer
2cf15393aeb922cab813938aee2c665d51ede57f
[ "Apache-2.0" ]
178
2017-03-14T10:44:31.000Z
2022-03-28T23:02:29.000Z
48.233333
120
0.410591
996,138
/* * Copyright 2015 JBoss, by Red Hat, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.uberfire.ext.wires.bpmn.client; import java.util.Collections; import java.util.HashSet; import java.util.Set; import org.uberfire.ext.wires.bpmn.api.model.BpmnEdge; import org.uberfire.ext.wires.bpmn.api.model.BpmnGraph; import org.uberfire.ext.wires.bpmn.api.model.BpmnGraphNode; import org.uberfire.ext.wires.bpmn.api.model.Role; import org.uberfire.ext.wires.bpmn.api.model.impl.nodes.ProcessNode; import org.uberfire.ext.wires.bpmn.api.model.impl.roles.DefaultRoleImpl; import org.uberfire.ext.wires.bpmn.api.model.impl.rules.CardinalityRuleImpl; import org.uberfire.ext.wires.bpmn.api.model.impl.rules.ConnectionRuleImpl; import org.uberfire.ext.wires.bpmn.api.model.impl.rules.ContainmentRuleImpl; import org.uberfire.ext.wires.bpmn.api.model.rules.CardinalityRule; import org.uberfire.ext.wires.bpmn.api.model.rules.ConnectionRule; import org.uberfire.ext.wires.bpmn.api.model.rules.Rule; import static org.junit.Assert.*; /** * Base for Rule related tests */ public abstract class AbstractBaseRuleTest { protected Set<Rule> getContainmentRules() { final Set<Rule> rules = new HashSet<Rule>(); rules.add(new ContainmentRuleImpl("Process Node Containment Rule", new ProcessNode().getContent().getId(), new HashSet<Role>() {{ add(new DefaultRoleImpl("all")); }})); return rules; } protected Set<Rule> getCardinalityRules() { final Set<Rule> rules = new HashSet<Rule>(); rules.add(new CardinalityRuleImpl("Start Node Cardinality Rule", new DefaultRoleImpl("sequence_start"), 0, 1, Collections.EMPTY_SET, new HashSet<CardinalityRule.ConnectorRule>() {{ add(new CardinalityRule.ConnectorRule() { @Override public long getMinOccurrences() { return 0; } @Override public long getMaxOccurrences() { return 1; } @Override public Role getRole() { return new DefaultRoleImpl("general_edge"); } @Override public String getName() { return "Start Node Outgoing Connector Rule 1"; } }); }})); rules.add(new CardinalityRuleImpl("End Node Cardinality Rule", new DefaultRoleImpl("sequence_end"), 0, 1, new HashSet<CardinalityRule.ConnectorRule>() {{ add(new CardinalityRule.ConnectorRule() { @Override public long getMinOccurrences() { return 0; } @Override public long getMaxOccurrences() { return 1; } @Override public Role getRole() { return new DefaultRoleImpl("general_edge"); } @Override public String getName() { return "End Node Incoming Connector Rule 1"; } }); }}, Collections.EMPTY_SET)); return rules; } protected Set<Rule> getConnectionRules() { final Set<Rule> rules = new HashSet<Rule>(); rules.add(new ConnectionRuleImpl("StartNode to TestDummyNode Connector Rule", new DefaultRoleImpl("general_edge"), new HashSet<ConnectionRule.PermittedConnection>() {{ add(new ConnectionRule.PermittedConnection() { @Override public Role getStartRole() { return new DefaultRoleImpl("sequence_start"); } @Override public Role getEndRole() { return new DefaultRoleImpl("dummy"); } }); add(new ConnectionRule.PermittedConnection() { @Override public Role getStartRole() { return new DefaultRoleImpl("dummy"); } @Override public Role getEndRole() { return new DefaultRoleImpl("sequence_end"); } }); add(new ConnectionRule.PermittedConnection() { @Override public Role getStartRole() { return new DefaultRoleImpl("dummy"); } @Override public Role getEndRole() { return new DefaultRoleImpl("dummy"); } }); }})); return rules; } protected void assertProcessContainsNodes(final BpmnGraph graph, final BpmnGraphNode... nodes) { final Set<BpmnGraphNode> nodesToExist = new HashSet<BpmnGraphNode>(); for (BpmnGraphNode node : nodes) { nodesToExist.add(node); } for (BpmnGraphNode gn : graph) { for (BpmnGraphNode node : nodes) { if (gn.equals(node)) { nodesToExist.remove(node); } } } if (!nodesToExist.isEmpty()) { final StringBuffer sb = new StringBuffer("Not all GraphNodes were present in Graph.\n"); for (BpmnGraphNode node : nodesToExist) { sb.append("--> Not present: GraphNode [" + node.toString() + "].\n"); } fail(sb.toString()); } } protected void assertProcessNotContainsNodes(final BpmnGraph graph, final BpmnGraphNode... nodes) { final Set<BpmnGraphNode> nodesToNotExist = new HashSet<BpmnGraphNode>(); for (BpmnGraphNode gn : graph) { for (BpmnGraphNode node : nodes) { if (gn.equals(node)) { nodesToNotExist.add(node); } } } if (!nodesToNotExist.isEmpty()) { final StringBuffer sb = new StringBuffer("One or more GraphNodes were present in Graph.\n"); for (BpmnGraphNode node : nodesToNotExist) { sb.append("--> Present: GraphNode [" + node.toString() + "].\n"); } fail(sb.toString()); } } protected void assertNodeContainsOutgoingEdges(final BpmnGraphNode node, final BpmnEdge... edges) { final Set<BpmnEdge> edgesToExist = new HashSet<BpmnEdge>(); for (BpmnEdge edge : edges) { edgesToExist.add(edge); } for (BpmnEdge edge : node.getOutEdges()) { for (BpmnEdge be : edges) { if (be.equals(edge)) { edgesToExist.remove(edge); } } } if (!edgesToExist.isEmpty()) { final StringBuffer sb = new StringBuffer("Not all Edges were present in GraphNode Outgoing connections.\n"); for (BpmnEdge edge : edgesToExist) { sb.append("--> Not present: Edge [" + edge.toString() + "].\n"); } fail(sb.toString()); } } protected void assertNodeContainsIncomingEdges(final BpmnGraphNode node, final BpmnEdge... edges) { final Set<BpmnEdge> edgesToExist = new HashSet<BpmnEdge>(); for (BpmnEdge edge : edges) { edgesToExist.add(edge); } for (BpmnEdge edge : node.getInEdges()) { for (BpmnEdge be : edges) { if (be.equals(edge)) { edgesToExist.remove(edge); } } } if (!edgesToExist.isEmpty()) { final StringBuffer sb = new StringBuffer("Not all Edges were present in GraphNode Incoming connections.\n"); for (BpmnEdge edge : edgesToExist) { sb.append("--> Not present: Edge [" + edge.toString() + "].\n"); } fail(sb.toString()); } } }
92323443c1925f2a9db511387f65939bf65c6ccf
1,591
java
Java
retail/retail-java-applications/data-engineering-dept/business-logic/src/main/java/com/google/dataflow/sample/retail/businesslogic/core/options/RetailPipelineOptions.java
danp11/dataflow-sample-applications
a4005f9603391dec9578fcd60050927c880c31c8
[ "Apache-2.0" ]
80
2020-08-07T16:25:22.000Z
2022-03-14T01:01:18.000Z
retail/retail-java-applications/data-engineering-dept/business-logic/src/main/java/com/google/dataflow/sample/retail/businesslogic/core/options/RetailPipelineOptions.java
danp11/dataflow-sample-applications
a4005f9603391dec9578fcd60050927c880c31c8
[ "Apache-2.0" ]
28
2020-08-12T03:15:21.000Z
2021-09-27T07:36:34.000Z
retail/retail-java-applications/data-engineering-dept/business-logic/src/main/java/com/google/dataflow/sample/retail/businesslogic/core/options/RetailPipelineOptions.java
danp11/dataflow-sample-applications
a4005f9603391dec9578fcd60050927c880c31c8
[ "Apache-2.0" ]
49
2020-08-08T05:16:22.000Z
2022-03-23T08:58:40.000Z
36.159091
75
0.774356
996,139
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.dataflow.sample.retail.businesslogic.core.options; import org.apache.beam.runners.dataflow.options.DataflowPipelineOptions; import org.apache.beam.sdk.annotations.Experimental; import org.apache.beam.sdk.options.Default; @Experimental public interface RetailPipelineOptions extends DataflowPipelineOptions, RetailPipelineAggregationOptions, RetailPipelineClickStreamOptions, RetailPipelineInventoryOptions, RetailPipelineTransactionsOptions, RetailPipelineStoresOptions, RetailPipelineReportingOptions { @Default.Boolean(false) Boolean getDebugMode(); void setDebugMode(Boolean debugMode); @Default.Boolean(false) Boolean getTestModeEnabled(); void setTestModeEnabled(Boolean testModeEnabled); }
923234498c358519f0ee7bf8402ee17727e2a34e
75,699
java
Java
rt/frontend/jaxrs/src/test/java/org/apache/cxf/jaxrs/impl/UriBuilderImplTest.java
nrickles3/cxf
72abe7416755fcba5943a64299d5e687661cb4c1
[ "Apache-2.0" ]
839
2015-01-01T15:33:21.000Z
2022-03-31T02:40:34.000Z
rt/frontend/jaxrs/src/test/java/org/apache/cxf/jaxrs/impl/UriBuilderImplTest.java
nrickles3/cxf
72abe7416755fcba5943a64299d5e687661cb4c1
[ "Apache-2.0" ]
399
2015-01-07T19:59:38.000Z
2022-03-30T21:56:27.000Z
rt/frontend/jaxrs/src/test/java/org/apache/cxf/jaxrs/impl/UriBuilderImplTest.java
nrickles3/cxf
72abe7416755fcba5943a64299d5e687661cb4c1
[ "Apache-2.0" ]
1,581
2015-01-01T02:22:05.000Z
2022-03-31T13:29:27.000Z
38.271486
190
0.590098
996,140
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.jaxrs.impl; import java.lang.reflect.Method; import java.net.URI; import java.net.URLEncoder; import java.util.Collections; import java.util.HashMap; import java.util.Map; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriBuilder; import org.apache.cxf.jaxrs.resources.Book; import org.apache.cxf.jaxrs.resources.BookStore; import org.apache.cxf.jaxrs.resources.UriBuilderWrongAnnotations; import org.apache.cxf.jaxrs.utils.JAXRSUtils; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; public class UriBuilderImplTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void testFromUriRelativePath() throws Exception { UriBuilder builder = UriBuilder.fromUri("path"); URI uri = builder.queryParam("a", "b").build(); assertEquals("path?a=b", uri.toString()); } @Test public void testUriTemplate() throws Exception { UriBuilder builder = UriBuilder.fromUri("http://localhost:8080/{a}/{b}"); URI uri = builder.build("1", "2"); assertEquals("http://localhost:8080/1/2", uri.toString()); } @Test public void testUriTemplate2() throws Exception { UriBuilder builder = UriBuilder.fromUri("http://localhost/{a}/{b}"); URI uri = builder.build("1", "2"); assertEquals("http://localhost/1/2", uri.toString()); } @Test public void testBuildWithNonEncodedSubstitutionValue() { URI uri; uri = UriBuilder.fromPath("/{a}").build("{}"); assertEquals("/%7B%7D", uri.toString()); } @Test public void testBuildWithNonEncodedSubstitutionValue2() { URI uri; uri = UriBuilder.fromPath("/{a}").buildFromEncoded("{}"); assertEquals("/%7B%7D", uri.toString()); } @Test public void testBuildWithNonEncodedSubstitutionValue3() { UriBuilder ub = UriBuilder.fromPath("/"); URI uri = ub.path("{a}").buildFromEncoded("%"); assertEquals("/%25", uri.toString()); uri = ub.path("{token}").buildFromEncoded("%", "{}"); assertEquals("/%25/%7B%7D", uri.toString()); } @Test public void testBuildWithNonEncodedSubstitutionValue4() { UriBuilder ub = UriBuilder.fromPath("/"); URI uri = ub.path("{a}").build("%"); assertEquals("/%25", uri.toString()); uri = ub.path("{token}").build("%", "{}"); assertEquals("/%25/%7B%7D", uri.toString()); } @Test public void testBuildWithNonEncodedSubstitutionValue5() { UriBuilder ub = UriBuilder.fromUri("/%25"); URI uri = ub.build(); assertEquals("/%25", uri.toString()); uri = ub.replacePath("/%/{token}").build("{}"); assertEquals("/%25/%7B%7D", uri.toString()); } @Test public void testBuildWithNonEncodedSubstitutionValue6() { UriBuilder ub = UriBuilder.fromPath("/"); URI uri = ub.path("%").build(); assertEquals("/%25", uri.toString()); uri = ub.replacePath("/%/{token}").build("{}"); assertEquals("/%25/%7B%7D", uri.toString()); } @Test public void testBuildWithNonEncodedSubstitutionValue7() { UriBuilder ub = UriBuilder.fromPath("/"); URI uri = ub.replaceQueryParam("a", "%").buildFromEncoded(); assertEquals("/?a=%25", uri.toString()); uri = ub.replaceQueryParam("a2", "{token}").buildFromEncoded("{}"); assertEquals("/?a=%25&a2=%7B%7D", uri.toString()); } @Test public void testBuildWithNonEncodedSubstitutionValue8() { UriBuilder ub = UriBuilder.fromPath("/"); URI uri = ub.replaceQueryParam("a", "%").build(); assertEquals("/?a=%25", uri.toString()); uri = ub.replaceQueryParam("a2", "{token}").build("{}"); assertEquals("/?a=%25&a2=%7B%7D", uri.toString()); } @Test public void testResolveTemplate() { URI uri; uri = UriBuilder.fromPath("/{a}").resolveTemplate("a", "1").build(); assertEquals("/1", uri.toString()); } @Test public void testResolveTemplate2() { URI uri; uri = UriBuilder.fromPath("/{a}/{b}").resolveTemplate("a", "1").build("2"); assertEquals("/1/2", uri.toString()); } @Test public void testResolveTemplate3() { URI uri; uri = UriBuilder.fromPath("/{a}/{b}").resolveTemplate("b", "1").build("2"); assertEquals("/2/1", uri.toString()); } @Test public void testResolveTemplate4() { URI uri; uri = UriBuilder.fromPath("/{a}/{b}").queryParam("c", "{c}") .resolveTemplate("a", "1").build("2", "3"); assertEquals("/1/2?c=3", uri.toString()); } @Test public void testResolveTemplate5() { Map<String, Object> templs = new HashMap<>(); templs.put("a", "1"); templs.put("b", "2"); URI uri; uri = UriBuilder.fromPath("/{a}/{b}").queryParam("c", "{c}") .resolveTemplates(templs).build("3"); assertEquals("/1/2?c=3", uri.toString()); } @Test public void testResolveTemplateFromEncoded() { URI uri; uri = UriBuilder.fromPath("/{a}").resolveTemplate("a", "%20 ").buildFromEncoded(); assertEquals("/%20%20", uri.toString()); } @Test public void testResolveTemplateFromEncodedMap() { String expected = "path-rootless%2Ftest2/x%25yz/%2Fpath-absolute%2F%2525test1/fred@example.com/x%25yz"; Map<String, Object> map = new HashMap<>(); map.put("v", new StringBuilder("path-rootless%2Ftest2")); map.put("w", new StringBuilder("x%yz")); map.put("x", new Object() { public String toString() { return "%2Fpath-absolute%2F%2525test1"; } }); map.put("y", "upchh@example.com"); UriBuilder builder = UriBuilder.fromPath("").path("{v}/{w}/{x}/{y}/{w}"); builder = builder.resolveTemplatesFromEncoded(map); URI uri = builder.build(); assertEquals(expected, uri.getRawPath()); } @Test public void testResolveTemplateFromMap() { URI uri; uri = UriBuilder.fromPath("/{a}/{b}").resolveTemplate("a", "1") .buildFromMap(Collections.singletonMap("b", "2")); assertEquals("/1/2", uri.toString()); } @Test public void testResolveTemplateFromMap2() { String expected = "path-rootless%2Ftest2/x%25yz/%2Fpath-absolute%2F%2525test1/fred@example.com/x%25yz"; Map<String, Object> map = new HashMap<>(); map.put("x", new StringBuilder("x%yz")); map.put("y", new StringBuffer("/path-absolute/%25test1")); map.put("z", new Object() { public String toString() { return "upchh@example.com"; } }); map.put("w", "path-rootless/test2"); UriBuilder builder = UriBuilder.fromPath("").path("{w}/{x}/{y}/{z}/{x}"); URI uri = builder.resolveTemplates(map).build(); assertEquals(expected, uri.getRawPath()); } @Test public void testResolveTemplatesMapBooleanSlashEncoded() throws Exception { String expected = "path-rootless%2Ftest2/x%25yz/%2Fpath-absolute%2F%2525test1/fred@example.com/x%25yz"; Map<String, Object> map = new HashMap<>(); map.put("x", new StringBuilder("x%yz")); map.put("y", new StringBuffer("/path-absolute/%25test1")); map.put("z", new Object() { public String toString() { return "upchh@example.com"; } }); map.put("w", "path-rootless/test2"); UriBuilder builder = UriBuilder.fromPath("").path("{w}/{x}/{y}/{z}/{x}"); URI uri = builder.resolveTemplates(map, true).build(); assertEquals(expected, uri.getRawPath()); } @Test public void testResolveTemplatesMapBooleanSlashNotEncoded() throws Exception { String expected = "path-rootless/test2/x%25yz//path-absolute/test1/fred@example.com/x%25yz"; Map<String, Object> map = new HashMap<>(); map.put("x", new StringBuilder("x%yz")); map.put("y", new StringBuffer("/path-absolute/test1")); map.put("z", new Object() { public String toString() { return "upchh@example.com"; } }); map.put("w", "path-rootless/test2"); UriBuilder builder = UriBuilder.fromPath("").path("{w}/{x}/{y}/{z}/{x}"); URI uri = builder.resolveTemplates(map, false).build(); assertEquals(expected, uri.getRawPath()); } @Test public void testQueryParamWithTemplateValues() { URI uri; uri = UriBuilder.fromPath("/index.jsp").queryParam("a", "{a}").queryParam("b", "{b}") .build("valueA", "valueB"); assertEquals("/index.jsp?a=valueA&b=valueB", uri.toString()); } @Test public void testResolveTemplateInQuery() { String uri = UriBuilder.fromPath("my/path").queryParam("qp", "{param}").resolveTemplate("param", "value").toTemplate(); assertEquals("my/path?qp=value", uri); } @Test public void testResolveTemplateInQuery2() { String uri = UriBuilder.fromUri("my/path?qp={param}").resolveTemplate("param", "value").toTemplate(); assertEquals("my/path?qp=value", uri); } @Test(expected = IllegalArgumentException.class) public void testQueryParamWithMissingTemplateValues() { UriBuilder.fromPath("/index.jsp").queryParam("a", "{a}").queryParam("b", "{b}") .build("valueA"); } @Test(expected = IllegalArgumentException.class) public void testQueryParamWithMissingTemplateValues2() { UriBuilder.fromPath("/index.jsp").queryParam("a", "{a}").build(); } @Test public void testPathAndQueryParamWithTemplateValues() { URI uri; uri = UriBuilder.fromPath("/index{ind}.jsp").queryParam("a", "{a}").queryParam("b", "{b}") .build("1", "valueA", "valueB"); assertEquals("/index1.jsp?a=valueA&b=valueB", uri.toString()); } @Test public void testReplaceQueryStringWithTemplateValues() { URI uri; uri = UriBuilder.fromUri("/index.jsp").replaceQuery("a={a}&b={b}") .build("valueA", "valueB"); assertEquals("/index.jsp?a=valueA&b=valueB", uri.toString()); } @Test public void testQueryParamUsingMapWithTemplateValues() { Map<String, String> values = new HashMap<>(); values.put("a", "valueA"); values.put("b", "valueB"); URI uri; uri = UriBuilder.fromPath("/index.jsp") .queryParam("a", "{a}") .queryParam("b", "{b}") .buildFromMap(values); assertEquals("/index.jsp?a=valueA&b=valueB", uri.toString()); } @Test public void testPathAndQueryParamUsingMapWithTemplateValues() { Map<String, String> values = new HashMap<>(); values.put("a", "valueA"); values.put("b", "valueB"); values.put("ind", "1"); URI uri; uri = UriBuilder.fromPath("/index{ind}.jsp") .queryParam("a", "{a}") .queryParam("b", "{b}") .buildFromMap(values); assertEquals("/index1.jsp?a=valueA&b=valueB", uri.toString()); } @Test(expected = IllegalArgumentException.class) public void testCtorNull() throws Exception { new UriBuilderImpl((URI)null); } @Test(expected = IllegalArgumentException.class) public void testPathStringNull() throws Exception { new UriBuilderImpl().path((String)null); } @Test public void testCtorAndBuild() throws Exception { URI uri = new URI("http://foo/bar/baz?query=1#fragment"); URI newUri = new UriBuilderImpl(uri).build(); assertEquals("URI is not built correctly", uri, newUri); } @Test public void testTrailingSlash() throws Exception { URI uri = new URI("http://bar/"); URI newUri = new UriBuilderImpl(uri).build(); assertEquals("URI is not built correctly", "http://bar/", newUri.toString()); } @Test public void testPathTrailingSlash() throws Exception { URI uri = new URI("http://bar"); URI newUri = new UriBuilderImpl(uri).path("/").build(); assertEquals("URI is not built correctly", "http://bar/", newUri.toString()); } @Test(expected = IllegalArgumentException.class) public void testNullPathWithBuildEncoded() throws Exception { URI uri = new URI("http://bar"); new UriBuilderImpl(uri).path("{bar}").buildFromEncoded((Object[])null); } @Test(expected = IllegalArgumentException.class) public void testNullPathWithBuildEncoded2() throws Exception { URI uri = new URI("http://bar"); new UriBuilderImpl(uri).path("{bar}").buildFromEncoded(new Object[] {null}); } @Test public void testPathTrailingSlash2() throws Exception { URI uri = new URI("http://bar"); URI newUri = new UriBuilderImpl(uri).path("/").path("/").build(); assertEquals("URI is not built correctly", "http://bar/", newUri.toString()); } @Test public void testClone() throws Exception { URI uri = new URI("http://bar"); URI newUri = new UriBuilderImpl(uri).clone().build(); assertEquals("URI is not built correctly", "http://bar", newUri.toString()); } @Test public void testCloneWithoutLeadingSlash() throws Exception { URI uri = new URI("bar/foo"); URI newUri = new UriBuilderImpl(uri).clone().build(); assertEquals("URI is not built correctly", "bar/foo", newUri.toString()); } @Test public void testCloneWithLeadingSlash() throws Exception { URI uri = new URI("/bar/foo"); URI newUri = new UriBuilderImpl(uri).clone().build(); assertEquals("URI is not built correctly", "/bar/foo", newUri.toString()); } @Test public void testBuildWithLeadingSlash() throws Exception { URI uri = new URI("/bar/foo"); URI newUri = UriBuilder.fromUri(uri).build(); assertEquals("URI is not built correctly", "/bar/foo", newUri.toString()); } @Test public void testClonePctEncodedFromUri() throws Exception { URI uri = new URI("http://bar/foo%20"); URI newUri = new UriBuilderImpl(uri).clone().buildFromEncoded(); assertEquals("URI is not built correctly", "http://bar/foo%20", newUri.toString()); } @Test public void testClonePctEncoded() throws Exception { URI uri = new URI("http://bar"); URI newUri = new UriBuilderImpl(uri) .path("{a}").path("{b}") .matrixParam("m", "m1 ", "m2+%20") .queryParam("q", "q1 ", "q2+q3%20").clone().buildFromEncoded("a+ ", "b%2B%20 "); assertEquals("URI is not built correctly", "http://bar/a+%20/b%2B%20%20;m=m1%20;m=m2+%20?q=q1+&q=q2%2Bq3%20", newUri.toString()); } @Test public void testEncodedPathQueryFromExistingURI() throws Exception { URI uri = new URI("http://bar/foo+%20%2B?q=a+b%20%2B"); URI newUri = new UriBuilderImpl(uri).buildFromEncoded(); assertEquals("URI is not built correctly", "http://bar/foo+%20%2B?q=a+b%20%2B", newUri.toString()); } @Test public void testEncodedPathWithAsteriscs() throws Exception { URI uri = new URI("http://bar/foo/"); URI newUri = new UriBuilderImpl(uri).path("*").buildFromEncoded(); assertEquals("URI is not built correctly", "http://bar/foo/*", newUri.toString()); } @Test public void testPathWithAsteriscs() throws Exception { URI uri = new URI("http://bar/foo/"); URI newUri = new UriBuilderImpl(uri).path("*").build(); assertEquals("URI is not built correctly", "http://bar/foo/*", newUri.toString()); } @Test public void testEncodedPathWithTwoAsteriscs() throws Exception { URI uri = new URI("http://bar/foo/"); URI newUri = new UriBuilderImpl(uri).path("**").buildFromEncoded(); assertEquals("URI is not built correctly", "http://bar/foo/**", newUri.toString()); } @Test public void testPathWithTwoAsteriscs() throws Exception { URI uri = new URI("http://bar/foo/"); URI newUri = new UriBuilderImpl(uri).path("**").build(); assertEquals("URI is not built correctly", "http://bar/foo/**", newUri.toString()); } @Test public void testEncodedAddedQuery() throws Exception { URI uri = new URI("http://bar"); URI newUri = new UriBuilderImpl(uri).queryParam("q", "a+b%20%2B").buildFromEncoded(); assertEquals("URI is not built correctly", "http://bar?q=a%2Bb%20%2B", newUri.toString()); } @Test public void testQueryWithNoValue() throws Exception { URI uri = new URI("http://bar"); URI newUri = new UriBuilderImpl(uri).queryParam("q").build(); assertEquals("URI is not built correctly", "http://bar?q", newUri.toString()); } @Test public void testMatrixWithNoValue() throws Exception { URI uri = new URI("http://bar/foo"); URI newUri = new UriBuilderImpl(uri).matrixParam("q").build(); assertEquals("URI is not built correctly", "http://bar/foo;q", newUri.toString()); } @Test public void testMatrixWithSlash() throws Exception { URI uri = new URI("http://bar/foo"); URI newUri = new UriBuilderImpl(uri).matrixParam("q", "1/2").build(); assertEquals("URI is not built correctly", "http://bar/foo;q=1%2F2", newUri.toString()); } @Test public void replaceMatrixParamWithEmptyPathTest() throws Exception { String name = "name"; String expected = "http://localhost:8080;name=x;name=y;name=y%20x;name=x%25y;name=%20"; URI uri = UriBuilder.fromPath("http://localhost:8080;name=x=;name=y?;name=x y;name=&") .replaceMatrixParam(name, "x", "y", "y x", "x%y", "%20") .build(); assertEquals(expected, uri.toString()); } @Test public void replaceMatrixWithEmptyPathTest() throws Exception { String expected = "http://localhost:8080;name=x;name=y;name=y%20x;name=x%25y;name=%20"; String value = "name=x;name=y;name=y x;name=x%y;name= "; URI uri = UriBuilder.fromPath("http://localhost:8080;name=x=;name=y?;name=x y;name=&") .replaceMatrix(value).build(); assertEquals(expected, uri.toString()); } @Test public void testAddMatrixToEmptyPath() throws Exception { String name = "name"; String expected = "http://localhost:8080;name=x;name=y"; URI uri = UriBuilder.fromPath("http://localhost:8080").matrixParam(name, "x", "y") .build(); assertEquals(expected, uri.toString()); } @Test public void testSchemeSpecificPart() throws Exception { URI uri = new URI("http://bar"); URI newUri = new UriBuilderImpl(uri).scheme("https").schemeSpecificPart("//localhost:8080/foo/bar") .build(); assertEquals("URI is not built correctly", "https://localhost:8080/foo/bar", newUri.toString()); } @Test public void testOpaqueSchemeSpecificPart() throws Exception { URI expectedUri = new URI("mailto:efpyi@example.com"); URI newUri = new UriBuilderImpl().scheme("mailto") .schemeSpecificPart("efpyi@example.com").build(); assertEquals("URI is not built correctly", expectedUri, newUri); } @Test public void testReplacePath() throws Exception { URI uri = new URI("http://foo/bar/baz;m1=m1value"); URI newUri = new UriBuilderImpl(uri).replacePath("/newpath").build(); assertEquals("URI is not built correctly", "http://foo/newpath", newUri.toString()); } @Test public void testReplacePathHttpString() throws Exception { URI uri = new URI("http://foo/bar/baz;m1=m1value"); URI newUri = new UriBuilderImpl(uri).replacePath("httppnewpath").build(); assertEquals("URI is not built correctly", "http://foo/httppnewpath", newUri.toString()); } @Test public void testReplaceNullPath() throws Exception { URI uri = new URI("http://foo/bar/baz;m1=m1value"); URI newUri = new UriBuilderImpl(uri).replacePath(null).build(); assertEquals("URI is not built correctly", "http://foo", newUri.toString()); } @Test(expected = IllegalArgumentException.class) public void testUriNull() throws Exception { new UriBuilderImpl().uri((URI)null); } @Test public void testUri() throws Exception { URI uri = new URI("http://foo/bar/baz?query=1#fragment"); URI newUri = new UriBuilderImpl().uri(uri).build(); assertEquals("URI is not built correctly", uri, newUri); } @Test public void testBuildValues() throws Exception { URI uri = new URI("http://zzz"); URI newUri = new UriBuilderImpl(uri).path("/{b}/{a}/{b}").build("foo", "bar", "baz"); assertEquals("URI is not built correctly", new URI("http://zzz/foo/bar/foo"), newUri); } @Test(expected = IllegalArgumentException.class) public void testBuildMissingValues() throws Exception { URI uri = new URI("http://zzz"); new UriBuilderImpl(uri).path("/{b}/{a}/{b}").build("foo"); } @Test(expected = IllegalArgumentException.class) public void testBuildMissingValues2() throws Exception { URI uri = new URI("http://zzz"); new UriBuilderImpl(uri).path("/{b}").build(); } @Test public void testBuildValueWithBrackets() throws Exception { URI uri = new URI("http://zzz"); URI newUri = new UriBuilderImpl(uri).path("/{a}").build("{foo}"); assertEquals("URI is not built correctly", new URI("http://zzz/%7Bfoo%7D"), newUri); } @Test public void testBuildValuesPct() throws Exception { URI uri = new URI("http://zzz"); URI newUri = new UriBuilderImpl(uri).path("/{a}").build("foo%25/bar%"); assertEquals("URI is not built correctly", new URI("http://zzz/foo%2525%2Fbar%25"), newUri); } @Test public void testBuildValuesPctEncoded() throws Exception { URI uri = new URI("http://zzz"); URI newUri = new UriBuilderImpl(uri).path("/{a}/{b}/{c}") .buildFromEncoded("foo%25", "bar%", "baz%20"); assertEquals("URI is not built correctly", new URI("http://zzz/foo%25/bar%25/baz%20"), newUri); } @Test public void testBuildFromMapValues() throws Exception { URI uri = new URI("http://zzz"); Map<String, String> map = new HashMap<>(); map.put("b", "foo"); map.put("a", "bar"); Map<String, String> immutable = Collections.unmodifiableMap(map); URI newUri = new UriBuilderImpl(uri).path("/{b}/{a}/{b}").buildFromMap(immutable); assertEquals("URI is not built correctly", new URI("http://zzz/foo/bar/foo"), newUri); } @Test(expected = IllegalArgumentException.class) public void testBuildFromMapMissingValues() throws Exception { URI uri = new URI("http://zzz"); Map<String, String> map = new HashMap<>(); map.put("b", "foo"); Map<String, String> immutable = Collections.unmodifiableMap(map); new UriBuilderImpl(uri).path("/{b}/{a}/{b}").buildFromMap(immutable); } @Test public void testBuildFromMapValueWithBrackets() throws Exception { URI uri = new URI("http://zzz"); Map<String, String> map = new HashMap<>(); map.put("a", "{foo}"); Map<String, String> immutable = Collections.unmodifiableMap(map); URI newUri = new UriBuilderImpl(uri).path("/{a}").buildFromMap(immutable); assertEquals("URI is not built correctly", new URI("http://zzz/%7Bfoo%7D"), newUri); } @Test public void testBuildFromMapValuesPct() throws Exception { URI uri = new URI("http://zzz"); Map<String, String> map = new HashMap<>(); map.put("a", "foo%25/bar%"); Map<String, String> immutable = Collections.unmodifiableMap(map); URI newUri = new UriBuilderImpl(uri).path("/{a}").buildFromMap(immutable); assertEquals("URI is not built correctly", new URI("http://zzz/foo%2525%2Fbar%25"), newUri); } @Test public void testBuildFromMapValuesPctEncoded() throws Exception { URI uri = new URI("http://zzz"); Map<String, String> map = new HashMap<>(); map.put("a", "foo%25"); map.put("b", "bar%"); Map<String, String> immutable = Collections.unmodifiableMap(map); URI newUri = new UriBuilderImpl(uri).path("/{a}/{b}").buildFromEncodedMap(immutable); assertEquals("URI is not built correctly", new URI("http://zzz/foo%25/bar%25"), newUri); } @Test public void testBuildFromEncodedMapComplex() throws Exception { Map<String, Object> maps = new HashMap<>(); maps.put("x", "x%20yz"); maps.put("y", "/path-absolute/%test1"); maps.put("z", "upchh@example.com"); maps.put("w", "path-rootless/test2"); String expectedPath = "path-rootless/test2/x%20yz//path-absolute/%25test1/fred@example.com/x%20yz"; URI uri = UriBuilder.fromPath("").path("{w}/{x}/{y}/{z}/{x}") .buildFromEncodedMap(maps); String rawPath = uri.getRawPath(); assertEquals(expectedPath, rawPath); } @Test public void testBuildFromEncodedMapComplex2() throws Exception { Map<String, Object> maps = new HashMap<>(); maps.put("x", "x%yz"); maps.put("y", "/path-absolute/test1"); maps.put("z", "upchh@example.com"); maps.put("w", "path-rootless/test2"); maps.put("u", "extra"); String expectedPath = "path-rootless/test2/x%25yz//path-absolute/test1/fred@example.com/x%25yz"; URI uri = UriBuilder.fromPath("").path("{w}/{x}/{y}/{z}/{x}") .buildFromEncodedMap(maps); String rawPath = uri.getRawPath(); assertEquals(expectedPath, rawPath); } @Test public void testBuildFromEncodedMapMultipleTimes() throws Exception { Map<String, Object> maps = new HashMap<>(); maps.put("x", "x%yz"); maps.put("y", "/path-absolute/test1"); maps.put("z", "upchh@example.com"); maps.put("w", "path-rootless/test2"); Map<String, Object> maps1 = new HashMap<>(); maps1.put("x", "x%20yz"); maps1.put("y", "/path-absolute/test1"); maps1.put("z", "upchh@example.com"); maps1.put("w", "path-rootless/test2"); Map<String, Object> maps2 = new HashMap<>(); maps2.put("x", "x%yz"); maps2.put("y", "/path-absolute/test1"); maps2.put("z", "upchh@example.com"); maps2.put("w", "path-rootless/test2"); maps2.put("v", "xyz"); String expectedPath = "path-rootless/test2/x%25yz//path-absolute/test1/fred@example.com/x%25yz"; String expectedPath1 = "path-rootless/test2/x%20yz//path-absolute/test1/fred@example.com/x%20yz"; String expectedPath2 = "path-rootless/test2/x%25yz//path-absolute/test1/fred@example.com/x%25yz"; UriBuilder ub = UriBuilder.fromPath("").path("{w}/{x}/{y}/{z}/{x}"); URI uri = ub.buildFromEncodedMap(maps); assertEquals(expectedPath, uri.getRawPath()); uri = ub.buildFromEncodedMap(maps1); assertEquals(expectedPath1, uri.getRawPath()); uri = ub.buildFromEncodedMap(maps2); assertEquals(expectedPath2, uri.getRawPath()); } @Test(expected = IllegalArgumentException.class) public void testBuildFromEncodedMapWithNullValue() throws Exception { Map<String, Object> maps = new HashMap<>(); maps.put("x", null); maps.put("y", "bar"); UriBuilder.fromPath("").path("{x}/{y}").buildFromEncodedMap(maps); } @Test public void testAddPath() throws Exception { URI uri = new URI("http://foo/bar"); URI newUri = new UriBuilderImpl().uri(uri).path("baz").build(); assertEquals("URI is not built correctly", new URI("http://foo/bar/baz"), newUri); newUri = new UriBuilderImpl().uri(uri).path("baz").path("1").path("2").build(); assertEquals("URI is not built correctly", new URI("http://foo/bar/baz/1/2"), newUri); } @Test public void testAddPathSlashes() throws Exception { URI uri = new URI("http://foo/"); URI newUri = new UriBuilderImpl().uri(uri).path("/bar").path("baz/").path("/blah/").build(); assertEquals("URI is not built correctly", new URI("http://foo/bar/baz/blah/"), newUri); } @Test public void testAddPathSlashes2() throws Exception { URI uri = new URI("http://foo/"); URI newUri = new UriBuilderImpl().uri(uri).path("/bar///baz").path("blah//").build(); assertEquals("URI is not built correctly", new URI("http://foo/bar/baz/blah/"), newUri); } @Test public void testAddPathSlashes3() throws Exception { URI uri = new URI("http://foo/"); URI newUri = new UriBuilderImpl().uri(uri).path("/bar/").path("").path("baz").build(); assertEquals("URI is not built correctly", new URI("http://foo/bar/baz"), newUri); } @Test public void testAddPathClass() throws Exception { URI uri = new URI("http://foo/"); URI newUri = new UriBuilderImpl().uri(uri).path(BookStore.class).path("/").build(); assertEquals("URI is not built correctly", new URI("http://foo/bookstore/"), newUri); } @Test(expected = IllegalArgumentException.class) public void testAddPathClassNull() throws Exception { new UriBuilderImpl().path((Class<?>)null).build(); } @Test(expected = IllegalArgumentException.class) public void testAddPathClassNoAnnotation() throws Exception { new UriBuilderImpl().path(this.getClass()).build(); } @Test public void testAddPathClassMethod() throws Exception { URI uri = new URI("http://foo/"); URI newUri = new UriBuilderImpl().uri(uri).path(BookStore.class) .path(BookStore.class, "updateBook").path("bar").build(); assertEquals("URI is not built correctly", new URI("http://foo/bookstore/books/bar"), newUri); } @Test(expected = IllegalArgumentException.class) public void testAddPathClassMethodNull1() throws Exception { new UriBuilderImpl().path(null, "methName").build(); } @Test(expected = IllegalArgumentException.class) public void testAddPathClassMethodNull2() throws Exception { new UriBuilderImpl().path(BookStore.class, null).build(); } @Test(expected = IllegalArgumentException.class) public void testAddPathClassMethodTooMany() throws Exception { new UriBuilderImpl().path(UriBuilderWrongAnnotations.class, "overloaded").build(); } @Test(expected = IllegalArgumentException.class) public void testAddPathClassMethodTooLess() throws Exception { new UriBuilderImpl().path(BookStore.class, "nonexistingMethod").build(); } @Test public void testAddPathMethod() throws Exception { Method meth = BookStore.class.getMethod("updateBook", Book.class); URI uri = new URI("http://foo/"); URI newUri = new UriBuilderImpl().uri(uri).path(meth).path("bar").build(); assertEquals("URI is not built correctly", new URI("http://foo/books/bar"), newUri); } @Test(expected = IllegalArgumentException.class) public void testAddPathMethodNull() throws Exception { new UriBuilderImpl().path((Method)null).build(); } @Test public void testAddPathMethodNoAnnotation() throws Exception { thrown.expect(IllegalArgumentException.class); thrown.expectMessage( String.format("Method '%s.getBook' is not annotated with Path", BookStore.class.getCanonicalName())); Method noAnnot = BookStore.class.getMethod("getBook", String.class); new UriBuilderImpl().path(noAnnot).build(); } @Test public void testSchemeHostPortQueryFragment() throws Exception { URI uri = new URI("http://foo:1234/bar?n1=v1&n2=v2#fragment"); URI newUri = new UriBuilderImpl().scheme("http").host("foo").port(1234).path("bar").queryParam("n1", "v1") .queryParam("n2", "v2").fragment("fragment").build(); compareURIs(uri, newUri); } @Test public void testReplaceQueryNull() throws Exception { URI uri = new URI("http://foo/bar?p1=v1&p2=v2"); URI newUri = new UriBuilderImpl(uri).replaceQuery(null).build(); assertEquals("URI is not built correctly", new URI("http://foo/bar"), newUri); } @Test public void testReplaceQueryWithNull2() { String expected = "http://localhost:8080"; URI uri = UriBuilder.fromPath("http://localhost:8080") .queryParam("name", "x=", "y?", "x y", "&").replaceQuery(null).build(); assertEquals(expected, uri.toString()); } @Test public void testReplaceQueryEmpty() throws Exception { URI uri = new URI("http://foo/bar?p1=v1&p2=v2"); URI newUri = new UriBuilderImpl(uri).replaceQuery("").build(); assertEquals("URI is not built correctly", new URI("http://foo/bar"), newUri); } @Test public void testReplaceQuery() throws Exception { URI uri = new URI("http://foo/bar?p1=v1"); URI newUri = new UriBuilderImpl(uri).replaceQuery("p1=nv1").build(); assertEquals("URI is not built correctly", new URI("http://foo/bar?p1=nv1"), newUri); } @Test public void testReplaceQuery2() throws Exception { URI uri = new URI("http://foo/bar"); URI newUri = new UriBuilderImpl(uri).replaceQuery("p1=nv1").build(); assertEquals("URI is not built correctly", new URI("http://foo/bar?p1=nv1"), newUri); } @Test public void testReplaceQuery3() { String expected = "http://localhost:8080?name1=xyz"; URI uri = UriBuilder.fromPath("http://localhost:8080") .queryParam("name", "x=", "y?", "x y", "&").replaceQuery("name1=xyz").build(); assertEquals(expected, uri.toString()); } @Test public void testFromPathUriOnly() { String expected = "http://localhost:8080"; URI uri = UriBuilder.fromPath("http://localhost:8080").build(); assertEquals(expected, uri.toString()); } @Test(expected = IllegalArgumentException.class) public void testQueryParamNameNull() throws Exception { new UriBuilderImpl().queryParam(null, "baz"); } @Test(expected = IllegalArgumentException.class) public void testQueryParamNullVal() throws Exception { new UriBuilderImpl().queryParam("foo", "bar", null, "baz"); } @Test public void testNullQueryParamValues() { try { UriBuilder.fromPath("http://localhost:8080").queryParam("hello", (Object[])null); fail("Should be IllegalArgumentException"); } catch (IllegalArgumentException ex) { //expected } } @Test public void testQueryParamSameNameAndVal() throws Exception { URI uri = new URI("http://foo/bar?p1=v1"); URI newUri = new UriBuilderImpl(uri).queryParam("p1", "v1").build(); assertEquals("URI is not built correctly", new URI("http://foo/bar?p1=v1&p1=v1"), newUri); } @Test public void testQueryParamVal() throws Exception { URI uri = new URI("http://foo/bar?p1=v1"); URI newUri = new UriBuilderImpl(uri).queryParam("p2", "v2").build(); assertEquals("URI is not built correctly", new URI("http://foo/bar?p1=v1&p2=v2"), newUri); } @Test public void testQueryParamSameNameDiffVal() throws Exception { URI uri = new URI("http://foo/bar?p1=v1"); URI newUri = new UriBuilderImpl(uri).queryParam("p1", "v2").build(); assertEquals("URI is not built correctly", new URI("http://foo/bar?p1=v1&p1=v2"), newUri); } @Test public void testQueryParamMultiVal() throws Exception { URI uri = new URI("http://foo/bar?p1=v1"); URI newUri = new UriBuilderImpl(uri).queryParam("p1", "v2", "v3").build(); assertEquals("URI is not built correctly", new URI("http://foo/bar?p1=v1&p1=v2&p1=v3"), newUri); } @Test(expected = IllegalArgumentException.class) public void testReplaceQueryParamNameNull() throws Exception { new UriBuilderImpl().replaceQueryParam(null, "baz"); } @Test public void testReplaceQueryParamValNull() throws Exception { URI uri = new URI("http://foo/bar?p1=v1&p2=v2&p1=v3"); URI newUri = new UriBuilderImpl(uri).replaceQueryParam("p1", (Object)null).build(); assertEquals("URI is not built correctly", new URI("http://foo/bar?p2=v2"), newUri); } @Test public void testReplaceQueryParamValEmpty() throws Exception { URI uri = new URI("http://foo/bar?p1=v1&p2=v2&p1=v3"); URI newUri = new UriBuilderImpl(uri).replaceQueryParam("p1").build(); assertEquals("URI is not built correctly", new URI("http://foo/bar?p2=v2"), newUri); } @Test public void testReplaceQueryParamExisting() throws Exception { URI uri = new URI("http://foo/bar?p1=v1"); URI newUri = new UriBuilderImpl(uri).replaceQueryParam("p1", "nv1").build(); assertEquals("URI is not built correctly", new URI("http://foo/bar?p1=nv1"), newUri); } @Test public void testReplaceQueryParamExistingMulti() throws Exception { URI uri = new URI("http://foo/bar?p1=v1&p2=v2"); URI newUri = new UriBuilderImpl(uri).replaceQueryParam("p1", "nv1", "nv2").build(); assertEquals("URI is not built correctly", new URI("http://foo/bar?p1=nv1&p1=nv2&p2=v2"), newUri); } @Test public void testReplaceMatrixNull() throws Exception { URI uri = new URI("http://foo/bar;p1=v1;p2=v2"); URI newUri = new UriBuilderImpl(uri).replaceMatrix(null).build(); assertEquals("URI is not built correctly", new URI("http://foo/bar"), newUri); } @Test public void testReplaceMatrixEmpty() throws Exception { URI uri = new URI("http://foo/bar;p1=v1;p2=v2"); URI newUri = new UriBuilderImpl(uri).replaceMatrix("").build(); assertEquals("URI is not built correctly", new URI("http://foo/bar"), newUri); } @Test public void testReplaceMatrix() throws Exception { URI uri = new URI("http://foo/bar;p1=v1;p2=v2"); URI newUri = new UriBuilderImpl(uri).replaceMatrix("p1=nv1").build(); assertEquals("URI is not built correctly", new URI("http://foo/bar;p1=nv1"), newUri); } @Test public void testReplaceMatrix2() throws Exception { URI uri = new URI("http://foo/bar/"); URI newUri = new UriBuilderImpl(uri).replaceMatrix("p1=nv1").build(); assertEquals("URI is not built correctly", new URI("http://foo/bar/;p1=nv1"), newUri); } @Test(expected = IllegalArgumentException.class) public void testMatrixParamNameNull() throws Exception { new UriBuilderImpl().matrixParam(null, "baz"); } @Test(expected = IllegalArgumentException.class) public void testMatrixParamNullVal() throws Exception { new UriBuilderImpl().matrixParam("foo", "bar", null, "baz"); } @Test public void testMatrixParamSameNameAndVal() throws Exception { URI uri = new URI("http://foo/bar;p1=v1"); URI newUri = new UriBuilderImpl(uri).matrixParam("p1", "v1").build(); assertEquals("URI is not built correctly", new URI("http://foo/bar;p1=v1;p1=v1"), newUri); } @Test public void testMatrixParamNewNameAndVal() throws Exception { URI uri = new URI("http://foo/bar;p1=v1"); URI newUri = new UriBuilderImpl(uri).matrixParam("p2", "v2").build(); assertEquals("URI is not built correctly", new URI("http://foo/bar;p1=v1;p2=v2"), newUri); } @Test public void testMatrixParamSameNameDiffVal() throws Exception { URI uri = new URI("http://foo/bar;p1=v1"); URI newUri = new UriBuilderImpl(uri).matrixParam("p1", "v2").build(); assertEquals("URI is not built correctly", new URI("http://foo/bar;p1=v1;p1=v2"), newUri); } @Test public void testMatrixParamMultiSameNameNewVals() throws Exception { URI uri = new URI("http://foo/bar;p1=v1"); URI newUri = new UriBuilderImpl(uri).matrixParam("p1", "v2", "v3").build(); assertEquals("URI is not built correctly", new URI("http://foo/bar;p1=v1;p1=v2;p1=v3"), newUri); } @Test public void testPctEncodedMatrixParam() throws Exception { URI uri = new URI("http://foo/bar"); URI newUri = new UriBuilderImpl(uri).matrixParam("p1", "v1%20").buildFromEncoded(); assertEquals("URI is not built correctly", new URI("http://foo/bar;p1=v1%20"), newUri); } @Test(expected = IllegalArgumentException.class) public void testReplaceMatrixParamNameNull() throws Exception { new UriBuilderImpl().replaceMatrixParam(null, "baz"); } @Test public void testReplaceMatrixParamValNull() throws Exception { URI uri = new URI("http://foo/bar;p1=v1;p2=v2;p1=v3?noise=bazzz"); URI newUri = new UriBuilderImpl(uri).replaceMatrixParam("p1", (Object)null).build(); assertEquals("URI is not built correctly", new URI("http://foo/bar;p2=v2?noise=bazzz"), newUri); } @Test public void testReplaceMatrixParamValEmpty() throws Exception { URI uri = new URI("http://foo/bar;p1=v1;p2=v2;p1=v3?noise=bazzz"); URI newUri = new UriBuilderImpl(uri).replaceMatrixParam("p1").build(); assertEquals("URI is not built correctly", new URI("http://foo/bar;p2=v2?noise=bazzz"), newUri); } @Test public void testReplaceMatrixParamExisting() throws Exception { URI uri = new URI("http://foo/bar;p1=v1"); URI newUri = new UriBuilderImpl(uri).replaceMatrixParam("p1", "nv1").build(); assertEquals("URI is not built correctly", new URI("http://foo/bar;p1=nv1"), newUri); } @Test public void testReplaceMatrixParamExistingMulti() throws Exception { URI uri = new URI("http://foo/bar;p1=v1;p2=v2"); URI newUri = new UriBuilderImpl(uri).replaceMatrixParam("p1", "nv1", "nv2").build(); assertEquals("URI is not built correctly", new URI("http://foo/bar;p1=nv1;p1=nv2;p2=v2"), newUri); } @Test public void testMatrixNonFinalPathSegment() throws Exception { URI uri = new URI("http://blah/foo;p1=v1/bar"); URI newUri = new UriBuilderImpl(uri).build(); assertEquals("URI is not built correctly", new URI("http://blah/foo;p1=v1/bar"), newUri); } @Test public void testMatrixFinalPathSegment() throws Exception { URI uri = new URI("http://blah/foo;p1=v1/bar;p2=v2"); URI newUri = new UriBuilderImpl(uri).build(); assertEquals("URI is not built correctly", new URI("http://blah/foo;p1=v1/bar;p2=v2"), newUri); } @Test public void testAddPathWithMatrix() throws Exception { URI uri = new URI("http://blah/foo/bar;p1=v1"); URI newUri = new UriBuilderImpl(uri).path("baz;p2=v2").build(); assertEquals("URI is not built correctly", new URI("http://blah/foo/bar;p1=v1/baz;p2=v2"), newUri); } @Test public void testNonHttpSchemes() { String[] uris = {"ftp://ftp.is.co.za/rfc/rfc1808.txt", "mailto:envkt@example.com", "news:comp.lang.java", "urn:isbn:096139212y", "ldap://[2001:db8::7]/c=GB?objectClass?one", "telnet://194.1.2.17:81/", "tel:+1-816-555-1212", "foo://bar.com:8042/there/here?name=baz#brr"}; int expectedCount = 0; for (int i = 0; i < uris.length; i++) { URI uri = UriBuilder.fromUri(uris[i]).build(); assertEquals("Strange", uri.toString(), uris[i]); expectedCount++; } assertEquals(8, expectedCount); } private void compareURIs(URI uri1, URI uri2) { assertEquals("Unexpected scheme", uri1.getScheme(), uri2.getScheme()); assertEquals("Unexpected host", uri1.getHost(), uri2.getHost()); assertEquals("Unexpected port", uri1.getPort(), uri2.getPort()); assertEquals("Unexpected path", uri1.getPath(), uri2.getPath()); assertEquals("Unexpected fragment", uri1.getFragment(), uri2.getFragment()); MultivaluedMap<String, String> queries1 = JAXRSUtils.getStructuredParams(uri1.getRawQuery(), "&", false, false); MultivaluedMap<String, String> queries2 = JAXRSUtils.getStructuredParams(uri2.getRawQuery(), "&", false, false); assertEquals("Unexpected queries", queries1, queries2); } @Test public void testTck1() { String value = "test1#test2"; String expected = "test1%23test2"; String path = "{arg1}"; URI uri = UriBuilder.fromPath(path).build(value); assertEquals(expected, uri.toString()); } @Test public void testNullPathValue() { String value = null; String path = "{arg1}"; try { UriBuilder.fromPath(path).build(value); fail("Should be IllegalArgumentException"); } catch (IllegalArgumentException ex) { //expected } } @Test public void testFragment() { String expected = "test#abc"; String path = "test"; URI uri = UriBuilder.fromPath(path).fragment("abc").build(); assertEquals(expected, uri.toString()); } @Test public void testFragmentTemplate() { String expected = "abc#xyz"; URI uri = UriBuilder .fromPath("{arg1}") .fragment("{arg2}") .build("abc", "xyz"); assertEquals(expected, uri.toString()); } @Test public void testSegments() { String path1 = "ab"; String[] path2 = {"a1", "x/y", "3b "}; String expected = "ab/a1/x%2Fy/3b%20"; URI uri = UriBuilder.fromPath(path1).segment(path2).build(); assertEquals(expected, uri.toString()); } @Test public void testSegments2() { String path1 = ""; String[] path2 = {"a1", "/", "3b "}; String expected = "a1/%2F/3b%20"; URI uri = UriBuilder.fromPath(path1).segment(path2).build(); assertEquals(expected, uri.toString()); } @Test public void testSegments3() { String path1 = "ab"; String[] path2 = {"a1", "{xy}", "3b "}; String expected = "ab/a1/x%2Fy/3b%20"; URI uri = UriBuilder.fromPath(path1).segment(path2).build("x/y"); assertEquals(uri.toString(), expected); } @Test public void testToTemplate() { String path1 = "ab"; String[] path2 = {"a1", "{xy}", "3b "}; String expected = "ab/a1/{xy}/3b%20"; String template = UriBuilder.fromPath(path1).segment(path2).toTemplate(); assertEquals(template, expected); } @Test public void testToTemplateAndResolved() { Map<String, Object> templs = new HashMap<>(); templs.put("a", "1"); templs.put("b", "2"); String template = ((UriBuilderImpl)UriBuilder.fromPath("/{a}/{b}").queryParam("c", "{c}")) .resolveTemplates(templs).toTemplate(); assertEquals("/1/2?c={c}", template); } @Test public void testSegments4() { String path1 = "ab"; String[] path2 = {"a1", "{xy}", "3b "}; String expected = "ab/a1/x/y/3b%20"; URI uri = UriBuilder.fromPath(path1).segment(path2).build(new Object[]{"x/y"}, false); assertEquals(uri.toString(), expected); } @Test public void testPathEncodedSlash() { String path1 = "ab"; String path2 = "{xy}"; String expected = "ab/x%2Fy"; URI uri = UriBuilder.fromPath(path1).path(path2).build(new Object[]{"x/y"}, true); assertEquals(uri.toString(), expected); } @Test public void testPathEncodedSlashNot() { String path1 = "ab"; String path2 = "{xy}"; String expected = "ab/x/y"; URI uri = UriBuilder.fromPath(path1).path(path2).build(new Object[]{"x/y"}, false); assertEquals(uri.toString(), expected); } @Test public void testInvalidUriReplacement() throws Exception { UriBuilder builder = UriBuilder.fromUri(new URI("news:comp.lang.java")); try { builder.uri("").build(); fail("IAE exception is expected"); } catch (IllegalArgumentException e) { // expected } } @Test public void testNullSegment() { try { UriBuilder.fromPath("/").segment((String)null).build(); fail("Should be IllegalArgumentException"); } catch (IllegalArgumentException ex) { //expected } } @Test public void testInvalidPort() { try { UriBuilder.fromUri("http://localhost:8080/some/path?name=foo").port(-10).build(); fail("Should be IllegalArgumentException"); } catch (IllegalArgumentException ex) { //expected } } @Test public void testResetPort() { URI uri = UriBuilder.fromUri("http://localhost:8080/some/path").port(-1).build(); assertEquals("http://localhost/some/path", uri.toString()); } @Test public void testInvalidHost() { try { UriBuilder.fromUri("http://localhost:8080/some/path?name=foo").host("").build(); fail("Should be IllegalArgumentException"); } catch (IllegalArgumentException ex) { //expected } } @Test public void testFromEncodedDuplicateVar2() { String expected = "http://localhost:8080/xy/%20/%25/xy"; URI uri = UriBuilder.fromPath("http://localhost:8080") .path("/{x}/{y}/{z}/{x}") .buildFromEncoded("xy", " ", "%"); assertEquals(expected, uri.toString()); } @Test public void testFromEncodedDuplicateVar3() { String expected = "http://localhost:8080/1/2/3/1"; URI uri = UriBuilder.fromPath("http://localhost:8080") .path("/{a}/{b}/{c}/{a}") .buildFromEncoded("1", "2", "3"); assertEquals(expected, uri.toString()); } @Test public void testFromEncodedDuplicateVarReplacePath() { String expected = "http://localhost:8080/1/2/3/1"; URI uri = UriBuilder.fromPath("") .replacePath("http://localhost:8080") .path("/{a}/{b}/{c}/{a}") .buildFromEncoded("1", "2", "3"); assertEquals(expected, uri.toString()); } @Test public void testNullScheme() { String expected = "localhost:8080"; URI uri = UriBuilder.fromUri("http://localhost:8080") .scheme(null) .build(); assertEquals(expected, uri.toString()); } @Test public void testNullMapValue() { try { Map<String, String> maps = new HashMap<>(); maps.put("x", null); maps.put("y", "/path-absolute/test1"); maps.put("z", "upchh@example.com"); maps.put("w", "path-rootless/test2"); maps.put("u", "extra"); URI uri = UriBuilder.fromPath("") .path("{w}/{x}/{y}/{z}/{x}") .buildFromMap(maps); fail("Should be IllegalArgumentException. Not return " + uri.toString()); } catch (IllegalArgumentException ex) { //expected } } @Test public void testMissingMapValue() { try { Map<String, String> maps = new HashMap<>(); maps.put("x", null); maps.put("y", "/path-absolute/test1"); maps.put("z", "upchh@example.com"); maps.put("w", "path-rootless/test2"); maps.put("u", "extra"); URI uri = UriBuilder.fromPath("") .path("{w}/{v}/{x}/{y}/{z}/{x}") .buildFromMap(maps); fail("Should be IllegalArgumentException. Not return " + uri.toString()); } catch (IllegalArgumentException ex) { //expected } } @Test public void testFromEncodedDuplicateVar() { String expected = "http://localhost:8080/a/%25/=/%25G0/%25/="; URI uri = UriBuilder.fromPath("http://localhost:8080") .path("/{v}/{w}/{x}/{y}/{z}/{x}") .buildFromEncoded("a", "%25", "=", "%G0", "%", "23"); assertEquals(expected, uri.toString()); } @Test public void testMultipleUriSchemes() throws Exception { URI uri; String[] urisOriginal = { "ftp://ftp.is.co.za/rfc/rfc1808.txt", "ftp://ftp.is.co.za/rfc/rfc1808.txt", "mailto:envkt@example.com", "mailto:envkt@example.com", "news:comp.lang.java", "news:comp.lang.java", "urn:isbn:096139210x", "http://www.ietf.org/rfc/rfc2396.txt", "http://www.ietf.org/rfc/rfc2396.txt", "ldap://[2001:db8::7]/c=GB?objectClass?one", "ldap://[2001:db8::7]/c=GB?objectClass?one", "tel:+1-816-555-1212", "tel:+1-816-555-1212", "telnet://192.0.2.16:80/", "telnet://192.0.2.16:80/", "foo://example.com:8042/over/there?name=ferret#nose", "foo://example.com:8042/over/there?name=ferret#nose" }; URI[] urisReplace = new URI[urisOriginal.length]; urisReplace[0] = new URI("http", "//ftp.is.co.za/rfc/rfc1808.txt", null); urisReplace[1] = new URI(null, "ftp.is.co.za", "/test/rfc1808.txt", null, null); urisReplace[2] = new URI("mailto", "envkt@example.com", null); urisReplace[3] = new URI(null, "efpyi@example.com", null); urisReplace[4] = new URI("http", "//comp.lang.java", null); urisReplace[5] = new URI(null, "news.lang.java", null); urisReplace[6] = new URI("urn:isbn:096139210x"); urisReplace[7] = new URI(null, "//www.ietf.org/rfc/rfc2396.txt", null); urisReplace[8] = new URI(null, "www.ietf.org", "/rfc/rfc2396.txt", null, null); urisReplace[9] = new URI("ldap", "//[2001:db8::7]/c=GB?objectClass?one", null); urisReplace[10] = new URI(null, "//[2001:db8::7]/c=GB?objectClass?one", null); urisReplace[11] = new URI("tel", "+1-816-555-1212", null); urisReplace[12] = new URI(null, "+1-866-555-1212", null); urisReplace[13] = new URI("telnet", "//192.0.2.16:80/", null); urisReplace[14] = new URI(null, "//192.0.2.16:81/", null); urisReplace[15] = new URI("http", "//example.com:8042/over/there?name=ferret", null); urisReplace[16] = new URI(null, "//example.com:8042/over/there?name=ferret", "mouth"); String[] urisExpected = { "http://ftp.is.co.za/rfc/rfc1808.txt", "ftp://ftp.is.co.za/test/rfc1808.txt", "mailto:envkt@example.com", "mailto:efpyi@example.com", "http://comp.lang.java", "news:news.lang.java", "urn:isbn:096139210x", "http://www.ietf.org/rfc/rfc2396.txt", "http://www.ietf.org/rfc/rfc2396.txt", "ldap://[2001:db8::7]/c=GB?objectClass?one", "ldap://[2001:db8::7]/c=GB?objectClass?one", "tel:+1-816-555-1212", "tel:+1-866-555-1212", "telnet://192.0.2.16:80/", "telnet://192.0.2.16:81/", "http://example.com:8042/over/there?name=ferret#nose", "foo://example.com:8042/over/there?name=ferret#mouth" }; for (int i = 0; i < urisOriginal.length; i++) { uri = UriBuilder.fromUri(new URI(urisOriginal[i])).uri(urisReplace[i]). build(); if (uri.toString().trim().compareToIgnoreCase(urisExpected[i]) != 0) { fail("Problem replacing " + urisOriginal[i] + " with " + urisReplace[i] + ", index " + i); } } } @Test public void testEncodingQueryParamFromBuild() throws Exception { String expectedValue = "http://localhost:8080?name=x%3D&name=y?&name=x+y&name=%26"; URI uri = UriBuilder.fromPath("http://localhost:8080").queryParam("name", "x=", "y?", "x y", "&").build(); assertEquals(expectedValue, uri.toString()); } @Test public void testReplaceParamAndEncodeQueryParamFromBuild() throws Exception { String expectedValue = "http://localhost:8080?name=x&name=y&name=y+x&name=x%25y&name=%20"; URI uri = UriBuilder.fromPath("http://localhost:8080").queryParam("name", "x=", "y?", "x y", "&").replaceQueryParam("name", "x", "y", "y x", "x%y", "%20").build(); assertEquals(expectedValue, uri.toString()); } @Test public void testReplaceStringAndEncodeQueryParamFromBuild() { String expected = "http://localhost:8080?name1=x&name2=%20&name3=x+y&name4=23&name5=x%20y"; URI uri = UriBuilder.fromPath("http://localhost:8080") .queryParam("name", "x=", "y?", "x y", "&") .replaceQuery("name1=x&name2=%20&name3=x+y&name4=23&name5=x y").build(); assertEquals(expected, uri.toString()); } @Test public void testPathParamSpaceBuild() { String expected = "http://localhost:8080/name/%20"; URI uri = UriBuilder.fromUri("http://localhost:8080").path("name/%20").build(); assertEquals(expected, uri.toString()); } @Test public void testPathParamSpaceBuild2() { String expected = "http://localhost:8080/name/%2520"; URI uri = UriBuilder.fromUri("http://localhost:8080").path("name/{value}").build("%20"); assertEquals(expected, uri.toString()); } @Test public void testPathParamSpaceBuild3() { String expected = "http://localhost:8080/name%20space"; URI uri = UriBuilder.fromUri("http://localhost:8080").path("name space").build(); assertEquals(expected, uri.toString()); } @Test public void testPathParamSpaceBuild4() { String expected = "http://localhost:8080/name%20space"; URI uri = UriBuilder.fromUri("http://localhost:8080").path("name space").buildFromEncoded(); assertEquals(expected, uri.toString()); } @Test public void testFromUriWithMatrix() { String expected = "http://localhost:8080/name;a=b"; URI uri = UriBuilder.fromUri("http://localhost:8080/name;a=b").build(); assertEquals(expected, uri.toString()); } @Test public void testPathParamSpaceBuildEncoded() { String expected = "http://localhost:8080/name/%20"; URI uri = UriBuilder.fromUri("http://localhost:8080").path("name/%20").buildFromEncoded(); assertEquals(expected, uri.toString()); } @Test public void testPathParamSpaceBuildEncoded2() { String expected = "http://localhost:8080/name/%20"; URI uri = UriBuilder.fromUri("http://localhost:8080").path("name/{value}").buildFromEncoded("%20"); assertEquals(expected, uri.toString()); } @Test public void testQueryParamSpaceBuild() { String expected = "http://localhost:8080?name=%20"; URI uri = UriBuilder.fromUri("http://localhost:8080").queryParam("name", "%20").build(); assertEquals(expected, uri.toString()); } @Test public void testQueryParamSpaceBuild2() { String expected = "http://localhost:8080?name=%2520"; URI uri = UriBuilder.fromUri("http://localhost:8080").queryParam("name", "{value}").build("%20"); assertEquals(expected, uri.toString()); } @Test public void testFromMethod() { URI uri = UriBuilder.fromMethod(TestPath.class, "headSub").build(); assertEquals(uri.toString(), "/sub"); } @Test public void testURItoStringMatchesOriginalURI() { String[] uriStrings = new String[]{"mailto:nnheo@example.com", "news:comp.lang.java", "urn:isbn:096139210x", "docs/guide/collections/designfaq.html#28", "../../../demo/jfc/SwingSet2/src/SwingSet2.java", "file:///~/calendar", "hzdkv@example.com", "http://localhost/somePath", "http://localhost:1234/someOtherPath", "http://127.0.0.1", "http://127.0.0.1/", "http://127.0.0.1/index.html", "myscheme://a.host:7575/", "myscheme://not.really.a.host:fakePort/" }; for (String uriString :uriStrings) { URI uri = UriBuilder.fromUri(uriString).build(); assertEquals(uriString, uri.toString()); } } @Test public void testURIWithExtraPathMatchesOriginalURIPlusPath() { assertEquals("mailto:nnheo@example.com", UriBuilder.fromUri("mailto:nnheo@example.com").path("extra").build().toString()); assertEquals("news:comp.lang.java", UriBuilder.fromUri("news:comp.lang.java").path("extra").build().toString()); assertEquals("urn:isbn:096139210x", UriBuilder.fromUri("urn:isbn:096139210x").path("extra").build().toString()); assertEquals("docs/guide/collections/designfaq.html/extra#28", UriBuilder.fromUri("docs/guide/collections/designfaq.html#28").path("extra").build().toString()); assertEquals("../../../demo/jfc/SwingSet2/src/SwingSet2.java/extra", UriBuilder.fromUri("../../../demo/jfc/SwingSet2/src/SwingSet2.java").path("extra").build().toString()); assertEquals("file:///~/calendar/extra", UriBuilder.fromUri("file:///~/calendar").path("extra").build().toString()); assertEquals("bob@somehost.com/extra", UriBuilder.fromUri("hzdkv@example.com").path("extra").build().toString()); assertEquals("http://localhost/somePath/extra", UriBuilder.fromUri("http://localhost/somePath").path("extra").build().toString()); assertEquals("http://localhost:1234/someOtherPath/extra", UriBuilder.fromUri("http://localhost:1234/someOtherPath").path("extra").build().toString()); assertEquals("http://127.0.0.1/extra", UriBuilder.fromUri("http://127.0.0.1").path("extra").build().toString()); assertEquals("http://127.0.0.1/extra", UriBuilder.fromUri("http://127.0.0.1/").path("extra").build().toString()); assertEquals("http://127.0.0.1/index.html/extra", UriBuilder.fromUri("http://127.0.0.1/index.html").path("extra").build().toString()); assertEquals("myscheme://a.host:7575/extra", UriBuilder.fromUri("myscheme://a.host:7575/").path("extra").build().toString()); // note that this will use the scheme specific part of the URI, as opposed to host, port and path, // and therefore the extra path will not be appended. URI uses an int for the port, and therefore // will not parse the "fakePort" part of this URI as a port. assertEquals("myscheme://not.really.a.host:fakePort/", UriBuilder.fromUri("myscheme://not.really.a.host:fakePort/").path("extra").build().toString()); } @Test public void testURIWithNonIntegerPort() { String url = "myscheme://not.really.a.host:port/"; UriBuilder builder = UriBuilder.fromUri(url); URI uri = builder.build(); assertEquals(url, uri.toString()); } @Test public void testExpandQueryValueAsCollection() { Map<String, Object> props = Collections.singletonMap("expand.query.value.as.collection", true); URI uri = new UriBuilderImpl(props).queryParam("foo", "v1", "v2", "v3").build(); assertEquals("foo=v1,v2,v3", uri.getQuery()); } @Test public void testUseArraySyntaxForQueryParams() { Map<String, Object> props = Collections.singletonMap("use.array.syntax.for.query.values", true); URI uri = new UriBuilderImpl(props).queryParam("foo", "v1", "v2", "v3").build(); assertEquals("foo[]=v1&foo[]=v2&foo[]=v3", uri.getQuery()); } @Test public void testUseArraySyntaxForQueryParamsBuildFromEncodedNormalize() { Map<String, Object> props = Collections.singletonMap("use.array.syntax.for.query.values", true); URI uri = new UriBuilderImpl(props).queryParam("foo", "v1") .queryParam("foo", "v2") .queryParam("foo", "v3") .buildFromEncoded().normalize(); assertEquals("foo[]=v1&foo[]=v2&foo[]=v3", uri.getQuery()); } @Path(value = "/TestPath") public static class TestPath { @GET public Response getPlain() { return Response.ok().build(); } @Path(value = "/sub") public Response headSub() { return Response.ok().build(); } @Path(value = "sub1") public Response test1() { return Response.ok().build(); } @Path(value = "/sub2") public Response test1(@QueryParam("testName") String test) { return Response.ok(test).build(); } } @Test public void testURIWithSpecialCharacters() { final String expected = "http://localhost:8080/xy%22"; final URI uri = UriBuilder .fromUri("http://localhost:8080") .path(URLEncoder.encode("xy\"")).build(); assertEquals(expected, uri.toString()); } @Test public void testURIWithSpecialCharacters2() { final String expected = "http://localhost:8080/xy%09"; final URI uri = UriBuilder .fromUri("http://localhost:8080") .path(URLEncoder.encode("xy\t")) .buildFromEncoded(); assertEquals(expected, uri.toString()); } @Test public void testURIWithSpecialCharactersPreservePath() { final String expected = "http://localhost:8080/xy/%22/abc"; final URI uri = UriBuilder.fromPath("") .replacePath("http://localhost:8080") .path("/{a}/{b}/{c}") .buildFromEncoded("xy", "\"", "abc"); assertEquals(expected, uri.toString()); } @Test public void testURIWithSpecialCharactersPreservePath2() { final String expected = "http://localhost:8080/xy/%09/abc"; final URI uri = UriBuilder.fromPath("") .replacePath("http://localhost:8080") .path("/{a}/{b}/{c}") .buildFromEncoded("xy", "\t", "abc"); assertEquals(expected, uri.toString()); } @Test public void testIllegalURI() { final String path = "invalidpath"; final URI uri = UriBuilder .fromPath(path) .build(); assertEquals(path, uri.toString()); } @Test @SuppressWarnings({"checkstyle:linelength"}) public void queryParamSpecialCharacters() { final String expected = "http://localhost:8080?%2F%3FabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._%7E%251A%21%24%27%28%29*%2B%2C%3B%3A%40=apiKeyQueryParam1Value"; final URI uri = UriBuilder .fromUri("http://localhost:8080") .queryParam(URLEncoder.encode("/?abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~%1A!$'()*+,;:@"), "apiKeyQueryParam1Value") .build(); assertEquals(expected, uri.toString()); } @Test @SuppressWarnings({"checkstyle:linelength"}) public void queryParamSpecialCharactersFromEncoded() { final String expected = "http://localhost:8080?%2F%3FabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._%7E%251A%21%24%27%28%29*%2B%2C%3B%3A%40=apiKeyQueryParam1Value"; final URI uri = UriBuilder .fromUri("http://localhost:8080") .queryParam(URLEncoder.encode("/?abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~%1A!$'()*+,;:@"), "apiKeyQueryParam1Value") .buildFromEncoded(); assertEquals(expected, uri.toString()); } @Test @SuppressWarnings({"checkstyle:linelength"}) public void queryParamSpecialCharactersFromEncodedTemplate() { final String expected = "http://localhost:8080?%2F%3FabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._%7E%251A%21%24%27%28%29*%2B%2C%3B%3A%40=apiKeyQueryParam1Value"; final URI uri = UriBuilder .fromUri("http://localhost:8080") .queryParam("{a}", "{b}") .buildFromEncoded(URLEncoder.encode("/?abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~%1A!$'()*+,;:@"), "apiKeyQueryParam1Value"); assertEquals(expected, uri.toString()); } @Test @SuppressWarnings({"checkstyle:linelength"}) public void queryParamSpecialCharactersFromTemplate() { final String expected = "http://localhost:8080?/?abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._%7E%251A%21%24%27%28%29*%2B,%3B%3A%40=apiKeyQueryParam1Value"; final URI uri = UriBuilder .fromUri("http://localhost:8080") .queryParam("{a}", "{b}") .build("/?abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~%1A!$'()*+,;:@", "apiKeyQueryParam1Value"); assertEquals(expected, uri.toString()); } @Test public void queryParamToTemplatePartiallyEncoded() { final String template = UriBuilder .fromUri("my/path") .queryParam("p", "%250%") .toTemplate(); assertEquals("my/path?p=%250%25", template); } @Test public void queryParamToTemplateNotEncoded() { final String template = UriBuilder .fromUri("my/path") .queryParam("p", "{p}") .resolveTemplate("p", "%250%") .toTemplate(); assertEquals("my/path?p=%25250%25", template); } @Test public void pathParamFromTemplateWithOrRegex() { final URI uri = UriBuilder .fromUri("my/path") .path("{p:my|his}") .build("my"); assertEquals("my/path/my", uri.toString()); } @Test public void pathParamFromTemplateWithRegex() { final URI uri = UriBuilder .fromUri("my/path") .path("{p:his/him}") .buildFromEncoded("his/him"); assertEquals("my/path/his/him", uri.toString()); } @Test public void pathParamFromNestedTemplateWithRegex() { // The nested templates are not supported and are not detected final URI uri = UriBuilder .fromUri("my/path") .path("{{p:his/him}}") .build(); assertEquals("my/path/%7B%7Bp:his/him%7D%7D", uri.toString()); } @Test public void pathParamFromBadTemplateNested() { final URI uri = UriBuilder .fromUri("my/path") .path("{p{d}}") .build("my"); assertEquals("my/path/%7Bp%7Bd%7D%7D", uri.toString()); } @Test public void pathParamFromBadTemplateUnopened() { final URI uri = UriBuilder .fromUri("my/path") .path("p{d}/}") .build("my"); assertEquals("my/path/pmy/%7D", uri.toString()); } @Test public void pathParamFromBadTemplateUnclosed() { final URI uri = UriBuilder .fromUri("my/path") .path("{p/{d}") .build("my"); assertEquals("my/path/%7Bp/my", uri.toString()); } @Test public void pathParamFromEmpty() { final URI uri = UriBuilder .fromUri("/") .path("/") .build(); assertEquals("/", uri.toString()); } @Test public void pathParamFromEmptyWithSpaces() { final URI uri = UriBuilder .fromUri("/") .path(" / ") .build(); assertEquals("/%20%20%20/%20%20%20", uri.toString()); } @Test public void pathParamFromBadTemplateUnopenedAndEnclosedSlash() { final URI uri = UriBuilder .fromUri("my/path") .path("p{d:my/day}/}") .buildFromEncoded("my/day"); assertEquals("my/path/pmy/day/%7D", uri.toString()); } @Test public void pathParamFromBadTemplateUnclosedAndEnclosedSlash() { final URI uri = UriBuilder .fromUri("my/path") .path("{p/{d:my/day}") .build(); assertEquals("my/path/%7Bp/%7Bd:my/day%7D", uri.toString()); } @Test public void pathParamFromBadTemplate() { final URI uri = UriBuilder .fromUri("/") .path("{") .build(); assertEquals("/%7B", uri.toString()); } }
9232366f82ff30e06bfe06e3dbdb0a1be4450f7d
2,912
java
Java
metaobj/metaobj-impl/api-impl/src/java/org/sakaiproject/metaobj/utils/xml/impl/UriElementType.java
sadupally/Dev
ead9de3993b7a805199ac254c6fa99d3dda48adf
[ "ECL-2.0" ]
null
null
null
metaobj/metaobj-impl/api-impl/src/java/org/sakaiproject/metaobj/utils/xml/impl/UriElementType.java
sadupally/Dev
ead9de3993b7a805199ac254c6fa99d3dda48adf
[ "ECL-2.0" ]
null
null
null
metaobj/metaobj-impl/api-impl/src/java/org/sakaiproject/metaobj/utils/xml/impl/UriElementType.java
sadupally/Dev
ead9de3993b7a805199ac254c6fa99d3dda48adf
[ "ECL-2.0" ]
null
null
null
33.930233
161
0.634681
996,141
/********************************************************************************** * $URL: https://source.sakaiproject.org/svn/metaobj/tags/sakai-10.4/metaobj-impl/api-impl/src/java/org/sakaiproject/metaobj/utils/xml/impl/UriElementType.java $ * $Id: UriElementType.java 105079 2012-02-24 23:08:11Z ychag@example.com $ *********************************************************************************** * * Copyright (c) 2004, 2005, 2006, 2008 The Sakai Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ECL-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **********************************************************************************/ package org.sakaiproject.metaobj.utils.xml.impl; import java.net.URI; import java.net.URISyntaxException; import org.jdom.Element; import org.jdom.Namespace; import org.sakaiproject.metaobj.utils.xml.NormalizationException; import org.sakaiproject.metaobj.utils.xml.SchemaNode; /** * Created by IntelliJ IDEA. * User: John Ellis * Date: Jan 25, 2006 * Time: 10:33:36 AM * To change this template use File | Settings | File Templates. */ public class UriElementType extends BaseElementType { private static final String SAKAI_REF_SCHEME = "sakairef"; public UriElementType(String typeName, Element schemaElement, SchemaNode parentNode, Namespace xsdNamespace) { super(typeName, schemaElement, parentNode, xsdNamespace); } public Class getObjectType() { return URI.class; } public Object getActualNormalizedValue(String value) { try { if (value.startsWith("/")) { return new URI(SAKAI_REF_SCHEME, value, null); } else { return new URI(value); } } catch (URISyntaxException e) { throw new NormalizationException("Invalid URI", NormalizationException.INVALID_URI, new Object[]{value}); } } public String getSchemaNormalizedValue(String value) throws NormalizationException { return getSchemaNormalizedValue(getActualNormalizedValue(value)); } public String getSchemaNormalizedValue(Object value) throws NormalizationException { if (value != null) { URI uri = (URI) value; if (uri.getScheme().equals(SAKAI_REF_SCHEME)) { return uri.getSchemeSpecificPart(); } else { return uri.toString(); } } else { return null; } } }
923236729d752ddfa43e44879fe94bb3ff8901cb
2,991
java
Java
ast/src/main/java/com/graphicsfuzz/common/ast/expr/TernaryExpr.java
mc-imperial/graphicsfuzz
ad360ab03246d87dab66727ebf85836a8937236f
[ "MIT" ]
1
2020-01-09T05:55:17.000Z
2020-01-09T05:55:17.000Z
ast/src/main/java/com/graphicsfuzz/common/ast/expr/TernaryExpr.java
mc-imperial/graphicsfuzz
ad360ab03246d87dab66727ebf85836a8937236f
[ "MIT" ]
null
null
null
ast/src/main/java/com/graphicsfuzz/common/ast/expr/TernaryExpr.java
mc-imperial/graphicsfuzz
ad360ab03246d87dab66727ebf85836a8937236f
[ "MIT" ]
null
null
null
27.440367
94
0.690739
996,142
// Copyright (c) 2018 Imperial College London // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. package com.graphicsfuzz.common.ast.expr; import com.graphicsfuzz.common.ast.IAstNode; import com.graphicsfuzz.common.ast.visitors.IAstVisitor; public class TernaryExpr extends Expr { private Expr test; private Expr thenExpr; private Expr elseExpr; /** * Makes a ternary expression from the given test and options. * @param test Boolean to be tested * @param thenExpr Result if the boolean is true * @param elseExpr Result if the boolean is false */ public TernaryExpr(Expr test, Expr thenExpr, Expr elseExpr) { this.test = test; this.thenExpr = thenExpr; this.elseExpr = elseExpr; } public Expr getTest() { return test; } public Expr getThenExpr() { return thenExpr; } public Expr getElseExpr() { return elseExpr; } @Override public void accept(IAstVisitor visitor) { visitor.visitTernaryExpr(this); } @Override public TernaryExpr clone() { return new TernaryExpr(test.clone(), thenExpr.clone(), elseExpr.clone()); } @Override public boolean hasChild(IAstNode candidateChild) { return candidateChild == test || candidateChild == thenExpr || candidateChild == elseExpr; } @Override public Expr getChild(int index) { if (index == 0) { return test; } if (index == 1) { return thenExpr; } if (index == 2) { return elseExpr; } throw new IndexOutOfBoundsException("Index for TernaryExpr must be 0, 1 or 2"); } @Override public void setChild(int index, Expr expr) { if (index == 0) { test = expr; return; } if (index == 1) { thenExpr = expr; return; } if (index == 2) { elseExpr = expr; return; } throw new IndexOutOfBoundsException("Index for TernaryExpr must be 0, 1 or 2"); } @Override public int getNumChildren() { return 3; } }
923237626c40f9fc4fca6fe965ba17b4760a71d2
8,693
java
Java
streams/src/main/java/org/apache/kafka/streams/kstream/internals/KStreamWindowAggregate.java
sudoa/kafka
22868e2a700fabed7ad7ddc3c2780d9fb6d336a3
[ "Apache-2.0" ]
126
2018-08-31T21:47:30.000Z
2022-03-11T10:01:31.000Z
streams/src/main/java/org/apache/kafka/streams/kstream/internals/KStreamWindowAggregate.java
sudoa/kafka
22868e2a700fabed7ad7ddc3c2780d9fb6d336a3
[ "Apache-2.0" ]
75
2019-03-07T20:24:18.000Z
2022-03-31T02:14:37.000Z
streams/src/main/java/org/apache/kafka/streams/kstream/internals/KStreamWindowAggregate.java
sudoa/kafka
22868e2a700fabed7ad7ddc3c2780d9fb6d336a3
[ "Apache-2.0" ]
46
2018-09-13T07:27:19.000Z
2022-03-23T17:49:13.000Z
41.004717
129
0.606005
996,143
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.kafka.streams.kstream.internals; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.apache.kafka.common.metrics.Sensor; import org.apache.kafka.streams.kstream.Aggregator; import org.apache.kafka.streams.kstream.Initializer; import org.apache.kafka.streams.kstream.Window; import org.apache.kafka.streams.kstream.Windowed; import org.apache.kafka.streams.kstream.Windows; import org.apache.kafka.streams.kstream.internals.metrics.Sensors; import org.apache.kafka.streams.processor.AbstractProcessor; import org.apache.kafka.streams.processor.Processor; import org.apache.kafka.streams.processor.ProcessorContext; import org.apache.kafka.streams.processor.internals.InternalProcessorContext; import org.apache.kafka.streams.processor.internals.metrics.StreamsMetricsImpl; import org.apache.kafka.streams.processor.internals.metrics.ThreadMetrics; import org.apache.kafka.streams.state.TimestampedWindowStore; import org.apache.kafka.streams.state.ValueAndTimestamp; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map; import static org.apache.kafka.streams.state.ValueAndTimestamp.getValueOrNull; public class KStreamWindowAggregate<K, V, Agg, W extends Window> implements KStreamAggProcessorSupplier<K, Windowed<K>, V, Agg> { private final Logger log = LoggerFactory.getLogger(getClass()); private final String storeName; private final Windows<W> windows; private final Initializer<Agg> initializer; private final Aggregator<? super K, ? super V, Agg> aggregator; private boolean sendOldValues = false; public KStreamWindowAggregate(final Windows<W> windows, final String storeName, final Initializer<Agg> initializer, final Aggregator<? super K, ? super V, Agg> aggregator) { this.windows = windows; this.storeName = storeName; this.initializer = initializer; this.aggregator = aggregator; } @Override public Processor<K, V> get() { return new KStreamWindowAggregateProcessor(); } public Windows<W> windows() { return windows; } @Override public void enableSendingOldValues() { sendOldValues = true; } private class KStreamWindowAggregateProcessor extends AbstractProcessor<K, V> { private TimestampedWindowStore<K, Agg> windowStore; private TimestampedTupleForwarder<Windowed<K>, Agg> tupleForwarder; private StreamsMetricsImpl metrics; private InternalProcessorContext internalProcessorContext; private Sensor lateRecordDropSensor; private Sensor skippedRecordsSensor; private long observedStreamTime = ConsumerRecord.NO_TIMESTAMP; @SuppressWarnings("unchecked") @Override public void init(final ProcessorContext context) { super.init(context); internalProcessorContext = (InternalProcessorContext) context; metrics = internalProcessorContext.metrics(); lateRecordDropSensor = Sensors.lateRecordDropSensor(internalProcessorContext); skippedRecordsSensor = ThreadMetrics.skipRecordSensor(Thread.currentThread().getName(), metrics); windowStore = (TimestampedWindowStore<K, Agg>) context.getStateStore(storeName); tupleForwarder = new TimestampedTupleForwarder<>( windowStore, context, new TimestampedCacheFlushListener<>(context), sendOldValues); } @Override public void process(final K key, final V value) { if (key == null) { log.warn( "Skipping record due to null key. value=[{}] topic=[{}] partition=[{}] offset=[{}]", value, context().topic(), context().partition(), context().offset() ); skippedRecordsSensor.record(); return; } // first get the matching windows final long timestamp = context().timestamp(); observedStreamTime = Math.max(observedStreamTime, timestamp); final long closeTime = observedStreamTime - windows.gracePeriodMs(); final Map<Long, W> matchedWindows = windows.windowsFor(timestamp); // try update the window, and create the new window for the rest of unmatched window that do not exist yet for (final Map.Entry<Long, W> entry : matchedWindows.entrySet()) { final Long windowStart = entry.getKey(); final long windowEnd = entry.getValue().end(); if (windowEnd > closeTime) { final ValueAndTimestamp<Agg> oldAggAndTimestamp = windowStore.fetch(key, windowStart); Agg oldAgg = getValueOrNull(oldAggAndTimestamp); final Agg newAgg; final long newTimestamp; if (oldAgg == null) { oldAgg = initializer.apply(); newTimestamp = context().timestamp(); } else { newTimestamp = Math.max(context().timestamp(), oldAggAndTimestamp.timestamp()); } newAgg = aggregator.apply(key, value, oldAgg); // update the store with the new value windowStore.put(key, ValueAndTimestamp.make(newAgg, newTimestamp), windowStart); tupleForwarder.maybeForward( new Windowed<>(key, entry.getValue()), newAgg, sendOldValues ? oldAgg : null, newTimestamp); } else { log.debug( "Skipping record for expired window. " + "key=[{}] " + "topic=[{}] " + "partition=[{}] " + "offset=[{}] " + "timestamp=[{}] " + "window=[{},{}) " + "expiration=[{}] " + "streamTime=[{}]", key, context().topic(), context().partition(), context().offset(), context().timestamp(), windowStart, windowEnd, closeTime, observedStreamTime ); lateRecordDropSensor.record(); } } } } @Override public KTableValueGetterSupplier<Windowed<K>, Agg> view() { return new KTableValueGetterSupplier<Windowed<K>, Agg>() { public KTableValueGetter<Windowed<K>, Agg> get() { return new KStreamWindowAggregateValueGetter(); } @Override public String[] storeNames() { return new String[] {storeName}; } }; } private class KStreamWindowAggregateValueGetter implements KTableValueGetter<Windowed<K>, Agg> { private TimestampedWindowStore<K, Agg> windowStore; @SuppressWarnings("unchecked") @Override public void init(final ProcessorContext context) { windowStore = (TimestampedWindowStore<K, Agg>) context.getStateStore(storeName); } @SuppressWarnings("unchecked") @Override public ValueAndTimestamp<Agg> get(final Windowed<K> windowedKey) { final K key = windowedKey.key(); final W window = (W) windowedKey.window(); return windowStore.fetch(key, window.start()); } @Override public void close() {} } }
9232388afe7bd320ac46e9b2194bd751e5c76976
614
java
Java
src/main/java/com/technode/terranovus/core/world/ChunkGeneratorOverworldTN.java
Bunsan/TerraNovus
5eed7df39fe70714813d1775bdf0cc4ac5900b17
[ "MIT", "BSD-3-Clause" ]
1
2017-10-19T04:48:31.000Z
2017-10-19T04:48:31.000Z
src/main/java/com/technode/terranovus/core/world/ChunkGeneratorOverworldTN.java
Bunsan/TerraNovus
5eed7df39fe70714813d1775bdf0cc4ac5900b17
[ "MIT", "BSD-3-Clause" ]
null
null
null
src/main/java/com/technode/terranovus/core/world/ChunkGeneratorOverworldTN.java
Bunsan/TerraNovus
5eed7df39fe70714813d1775bdf0cc4ac5900b17
[ "MIT", "BSD-3-Clause" ]
null
null
null
32.315789
116
0.838762
996,144
package com.technode.terranovus.core.world; import net.minecraft.world.World; import net.minecraft.world.gen.ChunkGeneratorSettings; import net.minecraft.world.gen.IChunkGenerator; import net.minecraft.world.gen.ChunkGeneratorOverworld; public class ChunkGeneratorOverworldTN extends ChunkGeneratorOverworld implements IChunkGenerator { private ChunkGeneratorSettings settings; public ChunkGeneratorOverworldTN(World worldIn, long seed, boolean mapFeaturesEnabledIn, String generatorOptions) { super(worldIn, seed, mapFeaturesEnabledIn, generatorOptions); // TODO Auto-generated constructor stub } }
92323892f874cd9d7413fd10c96935132655d84f
2,134
java
Java
event-hisaige/src/main/java/com/hisiage/event/config/IEventConfiguration.java
hisaige/springboot-hisaige
a2e6b6e2340ae572c79ee85af250fc54f311a946
[ "MIT" ]
null
null
null
event-hisaige/src/main/java/com/hisiage/event/config/IEventConfiguration.java
hisaige/springboot-hisaige
a2e6b6e2340ae572c79ee85af250fc54f311a946
[ "MIT" ]
null
null
null
event-hisaige/src/main/java/com/hisiage/event/config/IEventConfiguration.java
hisaige/springboot-hisaige
a2e6b6e2340ae572c79ee85af250fc54f311a946
[ "MIT" ]
null
null
null
33.873016
149
0.742268
996,145
package com.hisiage.event.config; import com.hisiage.event.factory.EventRegister; import com.hisiage.event.launcher.CustomEventLauncher; import com.hisiage.event.launcher.NotifyEventLauncher; import com.hisiage.event.processor.IEventListenerPostProcessor; import com.hisiage.event.serevice.EventService; import com.hisiage.event.serevice.EventServiceImpl; import com.hisiage.event.task.delayed.DelayMsgDispatcher; import com.hisiage.event.task.delayed.DelayMsgService; import org.springframework.beans.factory.ObjectProvider; import org.springframework.context.annotation.Bean; import java.util.List; /** * @author chenyj * 2020/1/15 - 14:48. **/ public class IEventConfiguration { private List<CustomEventLauncher> customEventLaunchers; private List<NotifyEventLauncher> notifyEventLaunchers; private EventRegister eventRegister; /** * ObjectProvider<List<CustomEventLauncher>> customEventLaunchers, * ObjectProvider<List<NotifyEventLauncher>> notifyEventLaunchers, * @param eventRegister 事件注册器 */ public IEventConfiguration(ObjectProvider<List<CustomEventLauncher>> customEventLaunchers, ObjectProvider<List<NotifyEventLauncher>> notifyEventLaunchers, ObjectProvider<EventRegister> eventRegister){ this.customEventLaunchers = customEventLaunchers.getIfAvailable(); this.notifyEventLaunchers = notifyEventLaunchers.getIfAvailable(); this.eventRegister = eventRegister.getIfAvailable(); } /** * 初始化事件发射器 * @return IEventLauncher */ @Bean public EventService iEventService(){ return new EventServiceImpl(customEventLaunchers, notifyEventLaunchers, eventRegister); } @Bean public DelayMsgDispatcher delayMsgDispatcher(){ return new DelayMsgDispatcher(iEventService()); } @Bean public DelayMsgService delayMsgService(){ return new DelayMsgService(); } @Bean public IEventListenerPostProcessor IEventListenerPostProcessor(){ return new IEventListenerPostProcessor(eventRegister); } }
923239b1ea4b2822d81158756dd5d6baf09cc3b8
903
java
Java
hw2/src/main/java/ru/spbau/mit/oquechy/ttt/bot/RandomBot.java
oquechy/java-II
7c949bb273152a5cc370c2a365caefafbfbc8eec
[ "MIT" ]
null
null
null
hw2/src/main/java/ru/spbau/mit/oquechy/ttt/bot/RandomBot.java
oquechy/java-II
7c949bb273152a5cc370c2a365caefafbfbc8eec
[ "MIT" ]
1
2018-05-24T17:42:22.000Z
2018-05-24T17:42:22.000Z
hw2/src/main/java/ru/spbau/mit/oquechy/ttt/bot/RandomBot.java
oquechy/java-II
7c949bb273152a5cc370c2a365caefafbfbc8eec
[ "MIT" ]
null
null
null
23.153846
86
0.65227
996,146
package ru.spbau.mit.oquechy.ttt.bot; import org.jetbrains.annotations.NotNull; import ru.spbau.mit.oquechy.ttt.logic.Model; import ru.spbau.mit.oquechy.ttt.logic.Position; import java.util.Random; /** * Implementation of {@link Bot} interface, which * generates random moves until suitable one is found. */ public class RandomBot implements Bot { final private Model model; final private @NotNull Random random = new Random(); /** * Takes a model to ask it about current field state. */ public RandomBot(Model model) { this.model = model; } /** * Returns the first possible move of random generated. */ @Override public Position newMove() { Position move; do { move = new Position(random.nextInt(Model.ROW), random.nextInt(Model.ROW)); } while (model.isBusy(move)); return move; } }
923239e3b486f977c172d0915f041103a7279c29
71,247
java
Java
org/apache/xmlgraphics/image/codec/png/PNGRed.java
MewX/contendo-viewer-v1.6.3
69fba3cea4f9a43e48f43148774cfa61b388e7de
[ "Apache-2.0" ]
2
2021-07-16T10:43:25.000Z
2021-12-15T13:54:10.000Z
org/apache/xmlgraphics/image/codec/png/PNGRed.java
MewX/contendo-viewer-v1.6.3
69fba3cea4f9a43e48f43148774cfa61b388e7de
[ "Apache-2.0" ]
1
2021-10-12T22:24:55.000Z
2021-10-12T22:24:55.000Z
org/apache/xmlgraphics/image/codec/png/PNGRed.java
MewX/contendo-viewer-v1.6.3
69fba3cea4f9a43e48f43148774cfa61b388e7de
[ "Apache-2.0" ]
null
null
null
38.120385
186
0.456258
996,147
/* */ package org.apache.xmlgraphics.image.codec.png; /* */ /* */ import java.awt.Color; /* */ import java.awt.Point; /* */ import java.awt.Rectangle; /* */ import java.awt.color.ColorSpace; /* */ import java.awt.image.ColorModel; /* */ import java.awt.image.ComponentColorModel; /* */ import java.awt.image.DataBuffer; /* */ import java.awt.image.DataBufferByte; /* */ import java.awt.image.DataBufferUShort; /* */ import java.awt.image.IndexColorModel; /* */ import java.awt.image.Raster; /* */ import java.awt.image.SampleModel; /* */ import java.awt.image.WritableRaster; /* */ import java.io.BufferedInputStream; /* */ import java.io.ByteArrayInputStream; /* */ import java.io.DataInputStream; /* */ import java.io.IOException; /* */ import java.io.InputStream; /* */ import java.io.SequenceInputStream; /* */ import java.util.ArrayList; /* */ import java.util.Collections; /* */ import java.util.Date; /* */ import java.util.GregorianCalendar; /* */ import java.util.HashMap; /* */ import java.util.List; /* */ import java.util.Locale; /* */ import java.util.Map; /* */ import java.util.TimeZone; /* */ import java.util.zip.Inflater; /* */ import java.util.zip.InflaterInputStream; /* */ import org.apache.xmlgraphics.image.GraphicsUtil; /* */ import org.apache.xmlgraphics.image.codec.util.PropertyUtil; /* */ import org.apache.xmlgraphics.image.rendered.AbstractRed; /* */ import org.apache.xmlgraphics.image.rendered.CachableRed; /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public class PNGRed /* */ extends AbstractRed /* */ { /* */ public static final int PNG_COLOR_GRAY = 0; /* */ public static final int PNG_COLOR_RGB = 2; /* */ public static final int PNG_COLOR_PALETTE = 3; /* */ public static final int PNG_COLOR_GRAY_ALPHA = 4; /* */ public static final int PNG_COLOR_RGB_ALPHA = 6; /* */ /* */ static class PNGChunk /* */ { /* */ int length; /* */ int type; /* */ byte[] data; /* */ String typeString; /* */ /* */ public PNGChunk(int length, int type, byte[] data, int crc) { /* 81 */ this.length = length; /* 82 */ this.type = type; /* 83 */ this.data = data; /* */ /* 85 */ this.typeString = ""; /* 86 */ this.typeString += (char)(type >> 24); /* 87 */ this.typeString += (char)(type >> 16 & 0xFF); /* 88 */ this.typeString += (char)(type >> 8 & 0xFF); /* 89 */ this.typeString += (char)(type & 0xFF); /* */ } /* */ /* */ public int getLength() { /* 93 */ return this.length; /* */ } /* */ /* */ public int getType() { /* 97 */ return this.type; /* */ } /* */ /* */ public String getTypeString() { /* 101 */ return this.typeString; /* */ } /* */ /* */ public byte[] getData() { /* 105 */ return this.data; /* */ } /* */ /* */ public byte getByte(int offset) { /* 109 */ return this.data[offset]; /* */ } /* */ /* */ public int getInt1(int offset) { /* 113 */ return this.data[offset] & 0xFF; /* */ } /* */ /* */ public int getInt2(int offset) { /* 117 */ return (this.data[offset] & 0xFF) << 8 | this.data[offset + 1] & 0xFF; /* */ } /* */ /* */ /* */ public int getInt4(int offset) { /* 122 */ return (this.data[offset] & 0xFF) << 24 | (this.data[offset + 1] & 0xFF) << 16 | (this.data[offset + 2] & 0xFF) << 8 | this.data[offset + 3] & 0xFF; /* */ } /* */ /* */ /* */ /* */ /* */ public String getString4(int offset) { /* 129 */ String s = ""; /* 130 */ s = s + (char)this.data[offset]; /* 131 */ s = s + (char)this.data[offset + 1]; /* 132 */ s = s + (char)this.data[offset + 2]; /* 133 */ s = s + (char)this.data[offset + 3]; /* 134 */ return s; /* */ } /* */ /* */ public boolean isType(String typeName) { /* 138 */ return this.typeString.equals(typeName); /* */ } /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* 148 */ private static final String[] colorTypeNames = new String[] { "Grayscale", "Error", "Truecolor", "Index", "Grayscale with alpha", "Error", "Truecolor with alpha" }; /* */ /* */ public static final int PNG_FILTER_NONE = 0; /* */ /* */ public static final int PNG_FILTER_SUB = 1; /* */ /* */ public static final int PNG_FILTER_UP = 2; /* */ /* */ public static final int PNG_FILTER_AVERAGE = 3; /* */ /* */ public static final int PNG_FILTER_PAETH = 4; /* 159 */ private int[][] bandOffsets = new int[][] { null, { 0 }, { 0, 1 }, { 0, 1, 2 }, { 0, 1, 2, 3 } }; /* */ /* */ /* */ private int bitDepth; /* */ /* */ /* */ private int colorType; /* */ /* */ /* */ private int compressionMethod; /* */ /* */ /* */ private int filterMethod; /* */ /* */ /* */ private int interlaceMethod; /* */ /* */ private int paletteEntries; /* */ /* */ private byte[] redPalette; /* */ /* */ private byte[] greenPalette; /* */ /* */ private byte[] bluePalette; /* */ /* */ private byte[] alphaPalette; /* */ /* */ private int bkgdRed; /* */ /* */ private int bkgdGreen; /* */ /* */ private int bkgdBlue; /* */ /* */ private int grayTransparentAlpha; /* */ /* */ private int redTransparentAlpha; /* */ /* */ private int greenTransparentAlpha; /* */ /* */ private int blueTransparentAlpha; /* */ /* */ private int maxOpacity; /* */ /* */ private int[] significantBits; /* */ /* */ private boolean suppressAlpha; /* */ /* */ private boolean expandPalette; /* */ /* */ private boolean output8BitGray; /* */ /* */ private boolean outputHasAlphaPalette; /* */ /* */ private boolean performGammaCorrection; /* */ /* */ private boolean expandGrayAlpha; /* */ /* */ private boolean generateEncodeParam; /* */ /* */ private PNGDecodeParam decodeParam; /* */ /* */ private PNGEncodeParam encodeParam; /* */ /* */ private boolean emitProperties = true; /* */ /* 224 */ private float fileGamma = 0.45455F; /* */ /* 226 */ private float userExponent = 1.0F; /* */ /* 228 */ private float displayExponent = 2.2F; /* */ /* */ private float[] chromaticity; /* */ /* 232 */ private int sRGBRenderingIntent = -1; /* */ /* */ /* 235 */ private int postProcess = 0; /* */ /* */ /* */ /* */ private static final int POST_NONE = 0; /* */ /* */ /* */ /* */ private static final int POST_GAMMA = 1; /* */ /* */ /* */ /* */ private static final int POST_GRAY_LUT = 2; /* */ /* */ /* */ /* */ private static final int POST_GRAY_LUT_ADD_TRANS = 3; /* */ /* */ /* */ /* */ private static final int POST_PALETTE_TO_RGB = 4; /* */ /* */ /* */ private static final int POST_PALETTE_TO_RGBA = 5; /* */ /* */ /* */ private static final int POST_ADD_GRAY_TRANS = 6; /* */ /* */ /* */ private static final int POST_ADD_RGB_TRANS = 7; /* */ /* */ /* */ private static final int POST_REMOVE_GRAY_TRANS = 8; /* */ /* */ /* */ private static final int POST_REMOVE_RGB_TRANS = 9; /* */ /* */ /* */ private static final int POST_EXP_MASK = 16; /* */ /* */ /* */ private static final int POST_GRAY_ALPHA_EXP = 16; /* */ /* */ /* */ private static final int POST_GAMMA_EXP = 17; /* */ /* */ /* */ private static final int POST_GRAY_LUT_ADD_TRANS_EXP = 19; /* */ /* */ /* */ private static final int POST_ADD_GRAY_TRANS_EXP = 22; /* */ /* */ /* 288 */ private List<InputStream> streamVec = new ArrayList<InputStream>(); /* */ /* */ private DataInputStream dataStream; /* */ /* */ private int bytesPerPixel; /* */ /* */ private int inputBands; /* */ /* */ private int outputBands; /* */ private int chunkIndex; /* 298 */ private List textKeys = new ArrayList(); /* 299 */ private List textStrings = new ArrayList(); /* */ /* 301 */ private List ztextKeys = new ArrayList(); /* 302 */ private List ztextStrings = new ArrayList(); /* */ /* */ private WritableRaster theTile; /* */ /* */ private Rectangle bounds; /* */ /* 308 */ private Map<String, Object> properties = new HashMap<String, Object>(); /* */ /* */ private int[] gammaLut; /* */ /* */ /* */ private void initGammaLut(int bits) { /* 314 */ double exp = this.userExponent / (this.fileGamma * this.displayExponent); /* 315 */ int numSamples = 1 << bits; /* 316 */ int maxOutSample = (bits == 16) ? 65535 : 255; /* */ /* 318 */ this.gammaLut = new int[numSamples]; /* 319 */ for (int i = 0; i < numSamples; i++) { /* 320 */ double gbright = i / (numSamples - 1); /* 321 */ double gamma = Math.pow(gbright, exp); /* 322 */ int igamma = (int)(gamma * maxOutSample + 0.5D); /* 323 */ if (igamma > maxOutSample) { /* 324 */ igamma = maxOutSample; /* */ } /* 326 */ this.gammaLut[i] = igamma; /* */ } /* */ } /* */ /* 330 */ private final byte[][] expandBits = new byte[][] { null, { 0, -1 }, { 0, 85, -86, -1 }, null, { 0, 17, 34, 51, 68, 85, 102, 119, -120, -103, -86, -69, -52, -35, -18, -1 } }; /* */ /* */ /* */ /* */ /* */ /* */ private int[] grayLut; /* */ /* */ /* */ /* */ /* */ /* */ /* */ private void initGrayLut(int bits) { /* 344 */ int len = 1 << bits; /* 345 */ this.grayLut = new int[len]; /* */ /* 347 */ if (this.performGammaCorrection) { /* 348 */ System.arraycopy(this.gammaLut, 0, this.grayLut, 0, len); /* */ } else { /* 350 */ for (int i = 0; i < len; i++) { /* 351 */ this.grayLut[i] = this.expandBits[bits][i]; /* */ } /* */ } /* */ } /* */ /* */ public PNGRed(InputStream stream) throws IOException { /* 357 */ this(stream, null); /* */ } /* */ /* */ /* */ /* */ public PNGRed(InputStream stream, PNGDecodeParam decodeParam) throws IOException { /* 363 */ if (!stream.markSupported()) { /* 364 */ stream = new BufferedInputStream(stream); /* */ } /* 366 */ DataInputStream distream = new DataInputStream(stream); /* */ /* 368 */ if (decodeParam == null) { /* 369 */ decodeParam = new PNGDecodeParam(); /* */ } /* 371 */ this.decodeParam = decodeParam; /* */ /* */ /* 374 */ this.suppressAlpha = decodeParam.getSuppressAlpha(); /* 375 */ this.expandPalette = decodeParam.getExpandPalette(); /* 376 */ this.output8BitGray = decodeParam.getOutput8BitGray(); /* 377 */ this.expandGrayAlpha = decodeParam.getExpandGrayAlpha(); /* 378 */ if (decodeParam.getPerformGammaCorrection()) { /* 379 */ this.userExponent = decodeParam.getUserExponent(); /* 380 */ this.displayExponent = decodeParam.getDisplayExponent(); /* 381 */ this.performGammaCorrection = true; /* 382 */ this.output8BitGray = true; /* */ } /* 384 */ this.generateEncodeParam = decodeParam.getGenerateEncodeParam(); /* */ /* 386 */ if (this.emitProperties) { /* 387 */ this.properties.put("file_type", "PNG v. 1.0"); /* */ } /* */ /* 390 */ long magic = distream.readLong(); /* 391 */ if (magic != -8552249625308161526L) { /* 392 */ String msg = PropertyUtil.getString("PNGImageDecoder0"); /* 393 */ throw new RuntimeException(msg); /* */ } /* */ /* */ /* */ /* */ while (true) { /* 399 */ String chunkType = getChunkType(distream); /* 400 */ if (chunkType.equals("IHDR")) { /* 401 */ PNGChunk pNGChunk = readChunk(distream); /* 402 */ parse_IHDR_chunk(pNGChunk); continue; /* 403 */ } if (chunkType.equals("PLTE")) { /* 404 */ PNGChunk pNGChunk = readChunk(distream); /* 405 */ parse_PLTE_chunk(pNGChunk); continue; /* 406 */ } if (chunkType.equals("IDAT")) { /* 407 */ PNGChunk pNGChunk = readChunk(distream); /* 408 */ this.streamVec.add(new ByteArrayInputStream(pNGChunk.getData())); continue; /* 409 */ } if (chunkType.equals("IEND")) { /* 410 */ PNGChunk pNGChunk = readChunk(distream); /* */ try { /* 412 */ parse_IEND_chunk(pNGChunk); /* 413 */ } catch (Exception e) { /* 414 */ e.printStackTrace(); /* 415 */ String msg = PropertyUtil.getString("PNGImageDecoder2"); /* 416 */ throw new RuntimeException(msg); /* */ } break; /* */ } /* 419 */ if (chunkType.equals("bKGD")) { /* 420 */ PNGChunk pNGChunk = readChunk(distream); /* 421 */ parse_bKGD_chunk(pNGChunk); continue; /* 422 */ } if (chunkType.equals("cHRM")) { /* 423 */ PNGChunk pNGChunk = readChunk(distream); /* 424 */ parse_cHRM_chunk(pNGChunk); continue; /* 425 */ } if (chunkType.equals("gAMA")) { /* 426 */ PNGChunk pNGChunk = readChunk(distream); /* 427 */ parse_gAMA_chunk(pNGChunk); continue; /* 428 */ } if (chunkType.equals("hIST")) { /* 429 */ PNGChunk pNGChunk = readChunk(distream); /* 430 */ parse_hIST_chunk(pNGChunk); continue; /* 431 */ } if (chunkType.equals("iCCP")) { /* 432 */ PNGChunk pNGChunk = readChunk(distream); continue; /* 433 */ } if (chunkType.equals("pHYs")) { /* 434 */ PNGChunk pNGChunk = readChunk(distream); /* 435 */ parse_pHYs_chunk(pNGChunk); continue; /* 436 */ } if (chunkType.equals("sBIT")) { /* 437 */ PNGChunk pNGChunk = readChunk(distream); /* 438 */ parse_sBIT_chunk(pNGChunk); continue; /* 439 */ } if (chunkType.equals("sRGB")) { /* 440 */ PNGChunk pNGChunk = readChunk(distream); /* 441 */ parse_sRGB_chunk(pNGChunk); continue; /* 442 */ } if (chunkType.equals("tEXt")) { /* 443 */ PNGChunk pNGChunk = readChunk(distream); /* 444 */ parse_tEXt_chunk(pNGChunk); continue; /* 445 */ } if (chunkType.equals("tIME")) { /* 446 */ PNGChunk pNGChunk = readChunk(distream); /* 447 */ parse_tIME_chunk(pNGChunk); continue; /* 448 */ } if (chunkType.equals("tRNS")) { /* 449 */ PNGChunk pNGChunk = readChunk(distream); /* 450 */ parse_tRNS_chunk(pNGChunk); continue; /* 451 */ } if (chunkType.equals("zTXt")) { /* 452 */ PNGChunk pNGChunk = readChunk(distream); /* 453 */ parse_zTXt_chunk(pNGChunk); continue; /* */ } /* 455 */ PNGChunk chunk = readChunk(distream); /* */ /* */ /* 458 */ String type = chunk.getTypeString(); /* 459 */ byte[] data = chunk.getData(); /* 460 */ if (this.encodeParam != null) { /* 461 */ this.encodeParam.addPrivateChunk(type, data); /* */ } /* 463 */ if (this.emitProperties) { /* 464 */ String key = "chunk_" + this.chunkIndex++ + ':' + type; /* 465 */ this.properties.put(key.toLowerCase(Locale.getDefault()), data); /* */ } /* */ } /* */ /* */ /* */ /* */ /* 472 */ if (this.significantBits == null) { /* 473 */ this.significantBits = new int[this.inputBands]; /* 474 */ for (int i = 0; i < this.inputBands; i++) { /* 475 */ this.significantBits[i] = this.bitDepth; /* */ } /* */ /* 478 */ if (this.emitProperties) { /* 479 */ this.properties.put("significant_bits", this.significantBits); /* */ } /* */ } /* 482 */ distream.close(); /* 483 */ stream.close(); /* */ } /* */ /* */ private static String getChunkType(DataInputStream distream) { /* */ try { /* 488 */ distream.mark(8); /* 489 */ distream.readInt(); /* 490 */ int type = distream.readInt(); /* 491 */ distream.reset(); /* */ /* 493 */ String typeString = "" + (char)(type >> 24 & 0xFF) + (char)(type >> 16 & 0xFF) + (char)(type >> 8 & 0xFF) + (char)(type & 0xFF); /* */ /* */ /* */ /* */ /* 498 */ return typeString; /* 499 */ } catch (Exception e) { /* 500 */ e.printStackTrace(); /* 501 */ return null; /* */ } /* */ } /* */ /* */ private static PNGChunk readChunk(DataInputStream distream) { /* */ try { /* 507 */ int length = distream.readInt(); /* 508 */ int type = distream.readInt(); /* 509 */ byte[] data = new byte[length]; /* 510 */ distream.readFully(data); /* 511 */ int crc = distream.readInt(); /* */ /* 513 */ return new PNGChunk(length, type, data, crc); /* 514 */ } catch (Exception e) { /* 515 */ e.printStackTrace(); /* 516 */ return null; /* */ } /* */ } /* */ /* */ private void parse_IHDR_chunk(PNGChunk chunk) { /* 521 */ int width = chunk.getInt4(0); /* 522 */ int height = chunk.getInt4(4); /* */ /* 524 */ this.bounds = new Rectangle(0, 0, width, height); /* */ /* 526 */ this.bitDepth = chunk.getInt1(8); /* */ /* 528 */ int validMask = 65814; /* 529 */ if ((1 << this.bitDepth & validMask) == 0) { /* */ /* 531 */ String msg = PropertyUtil.getString("PNGImageDecoder3"); /* 532 */ throw new RuntimeException(msg); /* */ } /* 534 */ this.maxOpacity = (1 << this.bitDepth) - 1; /* */ /* 536 */ this.colorType = chunk.getInt1(9); /* 537 */ if (this.colorType != 0 && this.colorType != 2 && this.colorType != 3 && this.colorType != 4 && this.colorType != 6) /* */ { /* */ /* */ /* */ /* 542 */ System.out.println(PropertyUtil.getString("PNGImageDecoder4")); /* */ } /* */ /* 545 */ if (this.colorType == 2 && this.bitDepth < 8) { /* */ /* 547 */ String msg = PropertyUtil.getString("PNGImageDecoder5"); /* 548 */ throw new RuntimeException(msg); /* */ } /* */ /* 551 */ if (this.colorType == 3 && this.bitDepth == 16) { /* */ /* 553 */ String msg = PropertyUtil.getString("PNGImageDecoder6"); /* 554 */ throw new RuntimeException(msg); /* */ } /* */ /* 557 */ if (this.colorType == 4 && this.bitDepth < 8) { /* */ /* 559 */ String msg = PropertyUtil.getString("PNGImageDecoder7"); /* 560 */ throw new RuntimeException(msg); /* */ } /* */ /* 563 */ if (this.colorType == 6 && this.bitDepth < 8) { /* */ /* 565 */ String msg = PropertyUtil.getString("PNGImageDecoder8"); /* 566 */ throw new RuntimeException(msg); /* */ } /* */ /* 569 */ if (this.emitProperties) { /* 570 */ this.properties.put("color_type", colorTypeNames[this.colorType]); /* */ } /* */ /* 573 */ if (this.generateEncodeParam) { /* 574 */ if (this.colorType == 3) { /* 575 */ this.encodeParam = new PNGEncodeParam.Palette(); /* 576 */ } else if (this.colorType == 0 || this.colorType == 4) { /* */ /* 578 */ this.encodeParam = new PNGEncodeParam.Gray(); /* */ } else { /* 580 */ this.encodeParam = new PNGEncodeParam.RGB(); /* */ } /* 582 */ this.decodeParam.setEncodeParam(this.encodeParam); /* */ } /* */ /* 585 */ if (this.encodeParam != null) { /* 586 */ this.encodeParam.setBitDepth(this.bitDepth); /* */ } /* 588 */ if (this.emitProperties) { /* 589 */ this.properties.put("bit_depth", Integer.valueOf(this.bitDepth)); /* */ } /* */ /* 592 */ if (this.performGammaCorrection) { /* */ /* 594 */ float gamma = 0.45454544F * this.displayExponent / this.userExponent; /* 595 */ if (this.encodeParam != null) { /* 596 */ this.encodeParam.setGamma(gamma); /* */ } /* 598 */ if (this.emitProperties) { /* 599 */ this.properties.put("gamma", Float.valueOf(gamma)); /* */ } /* */ } /* */ /* 603 */ this.compressionMethod = chunk.getInt1(10); /* 604 */ if (this.compressionMethod != 0) { /* */ /* 606 */ String msg = PropertyUtil.getString("PNGImageDecoder9"); /* 607 */ throw new RuntimeException(msg); /* */ } /* */ /* 610 */ this.filterMethod = chunk.getInt1(11); /* 611 */ if (this.filterMethod != 0) { /* */ /* 613 */ String msg = PropertyUtil.getString("PNGImageDecoder10"); /* 614 */ throw new RuntimeException(msg); /* */ } /* */ /* 617 */ this.interlaceMethod = chunk.getInt1(12); /* 618 */ if (this.interlaceMethod == 0) { /* 619 */ if (this.encodeParam != null) { /* 620 */ this.encodeParam.setInterlacing(false); /* */ } /* 622 */ if (this.emitProperties) { /* 623 */ this.properties.put("interlace_method", "None"); /* */ } /* 625 */ } else if (this.interlaceMethod == 1) { /* 626 */ if (this.encodeParam != null) { /* 627 */ this.encodeParam.setInterlacing(true); /* */ } /* 629 */ if (this.emitProperties) { /* 630 */ this.properties.put("interlace_method", "Adam7"); /* */ } /* */ } else { /* */ /* 634 */ String msg = PropertyUtil.getString("PNGImageDecoder11"); /* 635 */ throw new RuntimeException(msg); /* */ } /* */ /* 638 */ this.bytesPerPixel = (this.bitDepth == 16) ? 2 : 1; /* */ /* 640 */ switch (this.colorType) { /* */ case 0: /* 642 */ this.inputBands = 1; /* 643 */ this.outputBands = 1; /* */ /* 645 */ if (this.output8BitGray && this.bitDepth < 8) { /* 646 */ this.postProcess = 2; break; /* 647 */ } if (this.performGammaCorrection) { /* 648 */ this.postProcess = 1; break; /* */ } /* 650 */ this.postProcess = 0; /* */ break; /* */ /* */ /* */ case 2: /* 655 */ this.inputBands = 3; /* 656 */ this.bytesPerPixel *= 3; /* 657 */ this.outputBands = 3; /* */ /* 659 */ if (this.performGammaCorrection) { /* 660 */ this.postProcess = 1; break; /* */ } /* 662 */ this.postProcess = 0; /* */ break; /* */ /* */ /* */ case 3: /* 667 */ this.inputBands = 1; /* 668 */ this.bytesPerPixel = 1; /* 669 */ this.outputBands = this.expandPalette ? 3 : 1; /* */ /* 671 */ if (this.expandPalette) { /* 672 */ this.postProcess = 4; break; /* */ } /* 674 */ this.postProcess = 0; /* */ break; /* */ /* */ /* */ case 4: /* 679 */ this.inputBands = 2; /* 680 */ this.bytesPerPixel *= 2; /* */ /* 682 */ if (this.suppressAlpha) { /* 683 */ this.outputBands = 1; /* 684 */ this.postProcess = 8; break; /* */ } /* 686 */ if (this.performGammaCorrection) { /* 687 */ this.postProcess = 1; /* */ } else { /* 689 */ this.postProcess = 0; /* */ } /* 691 */ if (this.expandGrayAlpha) { /* 692 */ this.postProcess |= 0x10; /* 693 */ this.outputBands = 4; break; /* */ } /* 695 */ this.outputBands = 2; /* */ break; /* */ /* */ /* */ /* */ case 6: /* 701 */ this.inputBands = 4; /* 702 */ this.bytesPerPixel *= 4; /* 703 */ this.outputBands = !this.suppressAlpha ? 4 : 3; /* */ /* 705 */ if (this.suppressAlpha) { /* 706 */ this.postProcess = 9; break; /* 707 */ } if (this.performGammaCorrection) { /* 708 */ this.postProcess = 1; break; /* */ } /* 710 */ this.postProcess = 0; /* */ break; /* */ } /* */ } /* */ /* */ /* */ private void parse_IEND_chunk(PNGChunk chunk) throws Exception { /* */ ColorModel cm; /* 718 */ int textLen = this.textKeys.size(); /* 719 */ String[] textArray = new String[2 * textLen]; /* 720 */ for (int i = 0; i < textLen; i++) { /* 721 */ String key = this.textKeys.get(i); /* 722 */ String val = this.textStrings.get(i); /* 723 */ textArray[2 * i] = key; /* 724 */ textArray[2 * i + 1] = val; /* 725 */ if (this.emitProperties) { /* 726 */ String uniqueKey = "text_" + i + ':' + key; /* 727 */ this.properties.put(uniqueKey.toLowerCase(Locale.getDefault()), val); /* */ } /* */ } /* 730 */ if (this.encodeParam != null) { /* 731 */ this.encodeParam.setText(textArray); /* */ } /* */ /* */ /* 735 */ int ztextLen = this.ztextKeys.size(); /* 736 */ String[] ztextArray = new String[2 * ztextLen]; /* 737 */ for (int j = 0; j < ztextLen; j++) { /* 738 */ String key = this.ztextKeys.get(j); /* 739 */ String val = this.ztextStrings.get(j); /* 740 */ ztextArray[2 * j] = key; /* 741 */ ztextArray[2 * j + 1] = val; /* 742 */ if (this.emitProperties) { /* 743 */ String uniqueKey = "ztext_" + j + ':' + key; /* 744 */ this.properties.put(uniqueKey.toLowerCase(Locale.getDefault()), val); /* */ } /* */ } /* 747 */ if (this.encodeParam != null) { /* 748 */ this.encodeParam.setCompressedText(ztextArray); /* */ } /* */ /* */ /* 752 */ InputStream seqStream = new SequenceInputStream(Collections.enumeration(this.streamVec)); /* */ /* 754 */ InputStream infStream = new InflaterInputStream(seqStream, new Inflater()); /* */ /* 756 */ this.dataStream = new DataInputStream(infStream); /* */ /* */ /* 759 */ int depth = this.bitDepth; /* 760 */ if (this.colorType == 0 && this.bitDepth < 8 && this.output8BitGray) /* */ { /* 762 */ depth = 8; /* */ } /* 764 */ if (this.colorType == 3 && this.expandPalette) { /* 765 */ depth = 8; /* */ } /* 767 */ int width = this.bounds.width; /* 768 */ int height = this.bounds.height; /* */ /* 770 */ int bytesPerRow = (this.outputBands * width * depth + 7) / 8; /* 771 */ int scanlineStride = (depth == 16) ? (bytesPerRow / 2) : bytesPerRow; /* */ /* */ /* 774 */ this.theTile = createRaster(width, height, this.outputBands, scanlineStride, depth); /* */ /* */ /* */ /* 778 */ if (this.performGammaCorrection && this.gammaLut == null) { /* 779 */ initGammaLut(this.bitDepth); /* */ } /* 781 */ if (this.postProcess == 2 || this.postProcess == 3 || this.postProcess == 19) /* */ { /* */ /* 784 */ initGrayLut(this.bitDepth); /* */ } /* */ /* 787 */ decodeImage((this.interlaceMethod == 1)); /* */ /* */ /* 790 */ this.dataStream.close(); /* 791 */ infStream.close(); /* 792 */ seqStream.close(); /* 793 */ this.streamVec = null; /* */ /* 795 */ SampleModel sm = this.theTile.getSampleModel(); /* */ /* */ /* 798 */ if (this.colorType == 3 && !this.expandPalette) { /* 799 */ if (this.outputHasAlphaPalette) { /* 800 */ cm = new IndexColorModel(this.bitDepth, this.paletteEntries, this.redPalette, this.greenPalette, this.bluePalette, this.alphaPalette); /* */ /* */ /* */ } /* */ else { /* */ /* */ /* 807 */ cm = new IndexColorModel(this.bitDepth, this.paletteEntries, this.redPalette, this.greenPalette, this.bluePalette); /* */ /* */ } /* */ /* */ /* */ } /* 813 */ else if (this.colorType == 0 && this.bitDepth < 8 && !this.output8BitGray) { /* */ /* 815 */ byte[] palette = this.expandBits[this.bitDepth]; /* 816 */ cm = new IndexColorModel(this.bitDepth, palette.length, palette, palette, palette); /* */ /* */ } /* */ else { /* */ /* */ /* 822 */ cm = createComponentColorModel(sm); /* */ } /* */ /* */ /* 826 */ init((CachableRed)null, this.bounds, cm, sm, 0, 0, this.properties); /* */ } /* */ /* 829 */ private static final int[] GrayBits8 = new int[] { 8 }; /* 830 */ private static final ComponentColorModel colorModelGray8 = new ComponentColorModel(ColorSpace.getInstance(1003), GrayBits8, false, false, 1, 0); /* */ /* */ /* */ /* */ /* */ /* 836 */ private static final int[] GrayAlphaBits8 = new int[] { 8, 8 }; /* 837 */ private static final ComponentColorModel colorModelGrayAlpha8 = new ComponentColorModel(ColorSpace.getInstance(1003), GrayAlphaBits8, true, false, 3, 0); /* */ /* */ /* */ /* */ /* */ /* 843 */ private static final int[] GrayBits16 = new int[] { 16 }; /* 844 */ private static final ComponentColorModel colorModelGray16 = new ComponentColorModel(ColorSpace.getInstance(1003), GrayBits16, false, false, 1, 1); /* */ /* */ /* */ /* */ /* */ /* 850 */ private static final int[] GrayAlphaBits16 = new int[] { 16, 16 }; /* 851 */ private static final ComponentColorModel colorModelGrayAlpha16 = new ComponentColorModel(ColorSpace.getInstance(1003), GrayAlphaBits16, true, false, 3, 1); /* */ /* */ /* */ /* */ /* */ /* 857 */ private static final int[] GrayBits32 = new int[] { 32 }; /* 858 */ private static final ComponentColorModel colorModelGray32 = new ComponentColorModel(ColorSpace.getInstance(1003), GrayBits32, false, false, 1, 3); /* */ /* */ /* */ /* */ /* */ /* 864 */ private static final int[] GrayAlphaBits32 = new int[] { 32, 32 }; /* 865 */ private static final ComponentColorModel colorModelGrayAlpha32 = new ComponentColorModel(ColorSpace.getInstance(1003), GrayAlphaBits32, true, false, 3, 3); /* */ /* */ /* */ /* */ /* */ /* 871 */ private static final int[] RGBBits8 = new int[] { 8, 8, 8 }; /* 872 */ private static final ComponentColorModel colorModelRGB8 = new ComponentColorModel(ColorSpace.getInstance(1000), RGBBits8, false, false, 1, 0); /* */ /* */ /* */ /* */ /* */ /* 878 */ private static final int[] RGBABits8 = new int[] { 8, 8, 8, 8 }; /* 879 */ private static final ComponentColorModel colorModelRGBA8 = new ComponentColorModel(ColorSpace.getInstance(1000), RGBABits8, true, false, 3, 0); /* */ /* */ /* */ /* */ /* */ /* 885 */ private static final int[] RGBBits16 = new int[] { 16, 16, 16 }; /* 886 */ private static final ComponentColorModel colorModelRGB16 = new ComponentColorModel(ColorSpace.getInstance(1000), RGBBits16, false, false, 1, 1); /* */ /* */ /* */ /* */ /* */ /* 892 */ private static final int[] RGBABits16 = new int[] { 16, 16, 16, 16 }; /* 893 */ private static final ComponentColorModel colorModelRGBA16 = new ComponentColorModel(ColorSpace.getInstance(1000), RGBABits16, true, false, 3, 1); /* */ /* */ /* */ /* */ /* */ /* 899 */ private static final int[] RGBBits32 = new int[] { 32, 32, 32 }; /* 900 */ private static final ComponentColorModel colorModelRGB32 = new ComponentColorModel(ColorSpace.getInstance(1000), RGBBits32, false, false, 1, 3); /* */ /* */ /* */ /* */ /* */ /* 906 */ private static final int[] RGBABits32 = new int[] { 32, 32, 32, 32 }; /* 907 */ private static final ComponentColorModel colorModelRGBA32 = new ComponentColorModel(ColorSpace.getInstance(1000), RGBABits32, true, false, 3, 3); /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public static ColorModel createComponentColorModel(SampleModel sm) { /* 923 */ int type = sm.getDataType(); /* 924 */ int bands = sm.getNumBands(); /* 925 */ ComponentColorModel cm = null; /* */ /* 927 */ if (type == 0) { /* 928 */ switch (bands) { /* */ case 1: /* 930 */ cm = colorModelGray8; /* */ break; /* */ case 2: /* 933 */ cm = colorModelGrayAlpha8; /* */ break; /* */ case 3: /* 936 */ cm = colorModelRGB8; /* */ break; /* */ case 4: /* 939 */ cm = colorModelRGBA8; /* */ break; /* */ } /* 942 */ } else if (type == 1) { /* 943 */ switch (bands) { /* */ case 1: /* 945 */ cm = colorModelGray16; /* */ break; /* */ case 2: /* 948 */ cm = colorModelGrayAlpha16; /* */ break; /* */ case 3: /* 951 */ cm = colorModelRGB16; /* */ break; /* */ case 4: /* 954 */ cm = colorModelRGBA16; /* */ break; /* */ } /* 957 */ } else if (type == 3) { /* 958 */ switch (bands) { /* */ case 1: /* 960 */ cm = colorModelGray32; /* */ break; /* */ case 2: /* 963 */ cm = colorModelGrayAlpha32; /* */ break; /* */ case 3: /* 966 */ cm = colorModelRGB32; /* */ break; /* */ case 4: /* 969 */ cm = colorModelRGBA32; /* */ break; /* */ } /* */ /* */ } /* 974 */ return cm; /* */ } /* */ /* */ private void parse_PLTE_chunk(PNGChunk chunk) { /* 978 */ this.paletteEntries = chunk.getLength() / 3; /* 979 */ this.redPalette = new byte[this.paletteEntries]; /* 980 */ this.greenPalette = new byte[this.paletteEntries]; /* 981 */ this.bluePalette = new byte[this.paletteEntries]; /* */ /* 983 */ int pltIndex = 0; /* */ /* */ /* 986 */ if (this.performGammaCorrection) { /* 987 */ if (this.gammaLut == null) { /* 988 */ initGammaLut((this.bitDepth == 16) ? 16 : 8); /* */ } /* */ /* 991 */ for (int i = 0; i < this.paletteEntries; i++) { /* 992 */ byte r = chunk.getByte(pltIndex++); /* 993 */ byte g = chunk.getByte(pltIndex++); /* 994 */ byte b = chunk.getByte(pltIndex++); /* */ /* 996 */ this.redPalette[i] = (byte)this.gammaLut[r & 0xFF]; /* 997 */ this.greenPalette[i] = (byte)this.gammaLut[g & 0xFF]; /* 998 */ this.bluePalette[i] = (byte)this.gammaLut[b & 0xFF]; /* */ } /* */ } else { /* 1001 */ for (int i = 0; i < this.paletteEntries; i++) { /* 1002 */ this.redPalette[i] = chunk.getByte(pltIndex++); /* 1003 */ this.greenPalette[i] = chunk.getByte(pltIndex++); /* 1004 */ this.bluePalette[i] = chunk.getByte(pltIndex++); /* */ } /* */ } } private void parse_bKGD_chunk(PNGChunk chunk) { /* */ int bkgdIndex; /* */ int bkgdGray; /* */ int[] bkgdRGB; /* 1010 */ switch (this.colorType) { /* */ case 3: /* 1012 */ bkgdIndex = chunk.getByte(0) & 0xFF; /* */ /* 1014 */ this.bkgdRed = this.redPalette[bkgdIndex] & 0xFF; /* 1015 */ this.bkgdGreen = this.greenPalette[bkgdIndex] & 0xFF; /* 1016 */ this.bkgdBlue = this.bluePalette[bkgdIndex] & 0xFF; /* */ /* 1018 */ if (this.encodeParam != null) /* 1019 */ ((PNGEncodeParam.Palette)this.encodeParam).setBackgroundPaletteIndex(bkgdIndex); /* */ break; /* */ case 0: /* */ case 4: /* 1023 */ bkgdGray = chunk.getInt2(0); /* 1024 */ this.bkgdRed = this.bkgdGreen = this.bkgdBlue = bkgdGray; /* */ /* 1026 */ if (this.encodeParam != null) /* 1027 */ ((PNGEncodeParam.Gray)this.encodeParam).setBackgroundGray(bkgdGray); /* */ break; /* */ case 2: /* */ case 6: /* 1031 */ this.bkgdRed = chunk.getInt2(0); /* 1032 */ this.bkgdGreen = chunk.getInt2(2); /* 1033 */ this.bkgdBlue = chunk.getInt2(4); /* */ /* 1035 */ bkgdRGB = new int[3]; /* 1036 */ bkgdRGB[0] = this.bkgdRed; /* 1037 */ bkgdRGB[1] = this.bkgdGreen; /* 1038 */ bkgdRGB[2] = this.bkgdBlue; /* 1039 */ if (this.encodeParam != null) { /* 1040 */ ((PNGEncodeParam.RGB)this.encodeParam).setBackgroundRGB(bkgdRGB); /* */ } /* */ break; /* */ } /* */ /* 1045 */ if (this.emitProperties) { /* 1046 */ int r = 0; /* 1047 */ int g = 0; /* 1048 */ int b = 0; /* 1049 */ if (this.colorType == 3 || this.bitDepth == 8) { /* 1050 */ r = this.bkgdRed; /* 1051 */ g = this.bkgdGreen; /* 1052 */ b = this.bkgdBlue; /* 1053 */ } else if (this.bitDepth < 8) { /* 1054 */ r = this.expandBits[this.bitDepth][this.bkgdRed]; /* 1055 */ g = this.expandBits[this.bitDepth][this.bkgdGreen]; /* 1056 */ b = this.expandBits[this.bitDepth][this.bkgdBlue]; /* 1057 */ } else if (this.bitDepth == 16) { /* 1058 */ r = this.bkgdRed >> 8; /* 1059 */ g = this.bkgdGreen >> 8; /* 1060 */ b = this.bkgdBlue >> 8; /* */ } /* 1062 */ this.properties.put("background_color", new Color(r, g, b)); /* */ } /* */ } /* */ /* */ /* */ private void parse_cHRM_chunk(PNGChunk chunk) { /* 1068 */ if (this.sRGBRenderingIntent != -1) { /* */ return; /* */ } /* */ /* 1072 */ this.chromaticity = new float[8]; /* 1073 */ this.chromaticity[0] = chunk.getInt4(0) / 100000.0F; /* 1074 */ this.chromaticity[1] = chunk.getInt4(4) / 100000.0F; /* 1075 */ this.chromaticity[2] = chunk.getInt4(8) / 100000.0F; /* 1076 */ this.chromaticity[3] = chunk.getInt4(12) / 100000.0F; /* 1077 */ this.chromaticity[4] = chunk.getInt4(16) / 100000.0F; /* 1078 */ this.chromaticity[5] = chunk.getInt4(20) / 100000.0F; /* 1079 */ this.chromaticity[6] = chunk.getInt4(24) / 100000.0F; /* 1080 */ this.chromaticity[7] = chunk.getInt4(28) / 100000.0F; /* */ /* 1082 */ if (this.encodeParam != null) { /* 1083 */ this.encodeParam.setChromaticity(this.chromaticity); /* */ } /* 1085 */ if (this.emitProperties) { /* 1086 */ this.properties.put("white_point_x", Float.valueOf(this.chromaticity[0])); /* 1087 */ this.properties.put("white_point_y", Float.valueOf(this.chromaticity[1])); /* 1088 */ this.properties.put("red_x", Float.valueOf(this.chromaticity[2])); /* 1089 */ this.properties.put("red_y", Float.valueOf(this.chromaticity[3])); /* 1090 */ this.properties.put("green_x", Float.valueOf(this.chromaticity[4])); /* 1091 */ this.properties.put("green_y", Float.valueOf(this.chromaticity[5])); /* 1092 */ this.properties.put("blue_x", Float.valueOf(this.chromaticity[6])); /* 1093 */ this.properties.put("blue_y", Float.valueOf(this.chromaticity[7])); /* */ } /* */ } /* */ /* */ /* */ private void parse_gAMA_chunk(PNGChunk chunk) { /* 1099 */ if (this.sRGBRenderingIntent != -1) { /* */ return; /* */ } /* */ /* 1103 */ this.fileGamma = chunk.getInt4(0) / 100000.0F; /* */ /* 1105 */ float exp = this.performGammaCorrection ? (this.displayExponent / this.userExponent) : 1.0F; /* */ /* 1107 */ if (this.encodeParam != null) { /* 1108 */ this.encodeParam.setGamma(this.fileGamma * exp); /* */ } /* 1110 */ if (this.emitProperties) { /* 1111 */ this.properties.put("gamma", Float.valueOf(this.fileGamma * exp)); /* */ } /* */ } /* */ /* */ private void parse_hIST_chunk(PNGChunk chunk) { /* 1116 */ if (this.redPalette == null) { /* 1117 */ String msg = PropertyUtil.getString("PNGImageDecoder18"); /* 1118 */ throw new RuntimeException(msg); /* */ } /* */ /* 1121 */ int length = this.redPalette.length; /* 1122 */ int[] hist = new int[length]; /* 1123 */ for (int i = 0; i < length; i++) { /* 1124 */ hist[i] = chunk.getInt2(2 * i); /* */ } /* */ /* 1127 */ if (this.encodeParam != null) { /* 1128 */ this.encodeParam.setPaletteHistogram(hist); /* */ } /* */ } /* */ /* */ private void parse_pHYs_chunk(PNGChunk chunk) { /* 1133 */ int xPixelsPerUnit = chunk.getInt4(0); /* 1134 */ int yPixelsPerUnit = chunk.getInt4(4); /* 1135 */ int unitSpecifier = chunk.getInt1(8); /* */ /* 1137 */ if (this.encodeParam != null) { /* 1138 */ this.encodeParam.setPhysicalDimension(xPixelsPerUnit, yPixelsPerUnit, unitSpecifier); /* */ } /* */ /* */ /* 1142 */ if (this.emitProperties) { /* 1143 */ this.properties.put("x_pixels_per_unit", Integer.valueOf(xPixelsPerUnit)); /* 1144 */ this.properties.put("y_pixels_per_unit", Integer.valueOf(yPixelsPerUnit)); /* 1145 */ this.properties.put("pixel_aspect_ratio", Float.valueOf(xPixelsPerUnit / yPixelsPerUnit)); /* */ /* 1147 */ if (unitSpecifier == 1) { /* 1148 */ this.properties.put("pixel_units", "Meters"); /* 1149 */ } else if (unitSpecifier != 0) { /* */ /* 1151 */ String msg = PropertyUtil.getString("PNGImageDecoder12"); /* 1152 */ throw new RuntimeException(msg); /* */ } /* */ } /* */ } /* */ /* */ private void parse_sBIT_chunk(PNGChunk chunk) { /* 1158 */ if (this.colorType == 3) { /* 1159 */ this.significantBits = new int[3]; /* */ } else { /* 1161 */ this.significantBits = new int[this.inputBands]; /* */ } /* 1163 */ for (int i = 0; i < this.significantBits.length; i++) { /* 1164 */ int bits = chunk.getByte(i); /* 1165 */ int depth = (this.colorType == 3) ? 8 : this.bitDepth; /* 1166 */ if (bits <= 0 || bits > depth) { /* */ /* */ /* 1169 */ String msg = PropertyUtil.getString("PNGImageDecoder13"); /* 1170 */ throw new RuntimeException(msg); /* */ } /* 1172 */ this.significantBits[i] = bits; /* */ } /* */ /* 1175 */ if (this.encodeParam != null) { /* 1176 */ this.encodeParam.setSignificantBits(this.significantBits); /* */ } /* 1178 */ if (this.emitProperties) { /* 1179 */ this.properties.put("significant_bits", this.significantBits); /* */ } /* */ } /* */ /* */ private void parse_sRGB_chunk(PNGChunk chunk) { /* 1184 */ this.sRGBRenderingIntent = chunk.getByte(0); /* */ /* */ /* */ /* 1188 */ this.fileGamma = 0.45455F; /* */ /* 1190 */ this.chromaticity = new float[8]; /* 1191 */ this.chromaticity[0] = 3.127F; /* 1192 */ this.chromaticity[1] = 3.29F; /* 1193 */ this.chromaticity[2] = 6.4F; /* 1194 */ this.chromaticity[3] = 3.3F; /* 1195 */ this.chromaticity[4] = 3.0F; /* 1196 */ this.chromaticity[5] = 6.0F; /* 1197 */ this.chromaticity[6] = 1.5F; /* 1198 */ this.chromaticity[7] = 0.6F; /* */ /* 1200 */ if (this.performGammaCorrection) { /* */ /* 1202 */ float gamma = this.fileGamma * this.displayExponent / this.userExponent; /* 1203 */ if (this.encodeParam != null) { /* 1204 */ this.encodeParam.setGamma(gamma); /* 1205 */ this.encodeParam.setChromaticity(this.chromaticity); /* */ } /* 1207 */ if (this.emitProperties) { /* 1208 */ this.properties.put("gamma", Float.valueOf(gamma)); /* 1209 */ this.properties.put("white_point_x", Float.valueOf(this.chromaticity[0])); /* 1210 */ this.properties.put("white_point_y", Float.valueOf(this.chromaticity[1])); /* 1211 */ this.properties.put("red_x", Float.valueOf(this.chromaticity[2])); /* 1212 */ this.properties.put("red_y", Float.valueOf(this.chromaticity[3])); /* 1213 */ this.properties.put("green_x", Float.valueOf(this.chromaticity[4])); /* 1214 */ this.properties.put("green_y", Float.valueOf(this.chromaticity[5])); /* 1215 */ this.properties.put("blue_x", Float.valueOf(this.chromaticity[6])); /* 1216 */ this.properties.put("blue_y", Float.valueOf(this.chromaticity[7])); /* */ } /* */ } /* */ } /* */ /* */ private void parse_tEXt_chunk(PNGChunk chunk) { /* 1222 */ StringBuffer key = new StringBuffer(); /* 1223 */ StringBuffer value = new StringBuffer(); /* */ /* */ /* 1226 */ int textIndex = 0; byte b; /* 1227 */ while ((b = chunk.getByte(textIndex++)) != 0) { /* 1228 */ key.append((char)b); /* */ } /* */ /* 1231 */ for (int i = textIndex; i < chunk.getLength(); i++) { /* 1232 */ value.append((char)chunk.getByte(i)); /* */ } /* */ /* 1235 */ this.textKeys.add(key.toString()); /* 1236 */ this.textStrings.add(value.toString()); /* */ } /* */ /* */ private void parse_tIME_chunk(PNGChunk chunk) { /* 1240 */ int year = chunk.getInt2(0); /* 1241 */ int month = chunk.getInt1(2) - 1; /* 1242 */ int day = chunk.getInt1(3); /* 1243 */ int hour = chunk.getInt1(4); /* 1244 */ int minute = chunk.getInt1(5); /* 1245 */ int second = chunk.getInt1(6); /* */ /* 1247 */ TimeZone gmt = TimeZone.getTimeZone("GMT"); /* */ /* 1249 */ GregorianCalendar cal = new GregorianCalendar(gmt); /* 1250 */ cal.set(year, month, day, hour, minute, second); /* */ /* 1252 */ Date date = cal.getTime(); /* */ /* 1254 */ if (this.encodeParam != null) { /* 1255 */ this.encodeParam.setModificationTime(date); /* */ } /* 1257 */ if (this.emitProperties) { /* 1258 */ this.properties.put("timestamp", date); /* */ } /* */ } /* */ /* */ private void parse_tRNS_chunk(PNGChunk chunk) { /* 1263 */ if (this.colorType == 3) { /* 1264 */ int entries = chunk.getLength(); /* 1265 */ if (entries > this.paletteEntries) { /* */ /* 1267 */ String msg = PropertyUtil.getString("PNGImageDecoder14"); /* 1268 */ throw new RuntimeException(msg); /* */ } /* */ /* */ /* 1272 */ this.alphaPalette = new byte[this.paletteEntries]; int i; /* 1273 */ for (i = 0; i < entries; i++) { /* 1274 */ this.alphaPalette[i] = chunk.getByte(i); /* */ } /* */ /* */ /* 1278 */ for (i = entries; i < this.paletteEntries; i++) { /* 1279 */ this.alphaPalette[i] = -1; /* */ } /* */ /* 1282 */ if (!this.suppressAlpha) { /* 1283 */ if (this.expandPalette) { /* 1284 */ this.postProcess = 5; /* 1285 */ this.outputBands = 4; /* */ } else { /* 1287 */ this.outputHasAlphaPalette = true; /* */ } /* */ } /* 1290 */ } else if (this.colorType == 0) { /* 1291 */ this.grayTransparentAlpha = chunk.getInt2(0); /* */ /* 1293 */ if (!this.suppressAlpha) { /* 1294 */ if (this.bitDepth < 8) { /* 1295 */ this.output8BitGray = true; /* 1296 */ this.maxOpacity = 255; /* 1297 */ this.postProcess = 3; /* */ } else { /* 1299 */ this.postProcess = 6; /* */ } /* */ /* 1302 */ if (this.expandGrayAlpha) { /* 1303 */ this.outputBands = 4; /* 1304 */ this.postProcess |= 0x10; /* */ } else { /* 1306 */ this.outputBands = 2; /* */ } /* */ /* 1309 */ if (this.encodeParam != null) { /* 1310 */ ((PNGEncodeParam.Gray)this.encodeParam).setTransparentGray(this.grayTransparentAlpha); /* */ } /* */ } /* 1313 */ } else if (this.colorType == 2) { /* 1314 */ this.redTransparentAlpha = chunk.getInt2(0); /* 1315 */ this.greenTransparentAlpha = chunk.getInt2(2); /* 1316 */ this.blueTransparentAlpha = chunk.getInt2(4); /* */ /* 1318 */ if (!this.suppressAlpha) { /* 1319 */ this.outputBands = 4; /* 1320 */ this.postProcess = 7; /* */ /* 1322 */ if (this.encodeParam != null) { /* 1323 */ int[] rgbTrans = new int[3]; /* 1324 */ rgbTrans[0] = this.redTransparentAlpha; /* 1325 */ rgbTrans[1] = this.greenTransparentAlpha; /* 1326 */ rgbTrans[2] = this.blueTransparentAlpha; /* 1327 */ ((PNGEncodeParam.RGB)this.encodeParam).setTransparentRGB(rgbTrans); /* */ } /* */ } /* 1330 */ } else if (this.colorType == 4 || this.colorType == 6) { /* */ /* */ /* 1333 */ String msg = PropertyUtil.getString("PNGImageDecoder15"); /* 1334 */ throw new RuntimeException(msg); /* */ } /* */ } /* */ /* */ private void parse_zTXt_chunk(PNGChunk chunk) { /* 1339 */ StringBuffer key = new StringBuffer(); /* 1340 */ StringBuffer value = new StringBuffer(); /* */ /* */ /* 1343 */ int textIndex = 0; byte b; /* 1344 */ while ((b = chunk.getByte(textIndex++)) != 0) { /* 1345 */ key.append((char)b); /* */ } /* */ /* */ /* 1349 */ textIndex++; /* */ /* */ try { /* 1352 */ int length = chunk.getLength() - textIndex; /* 1353 */ byte[] data = chunk.getData(); /* 1354 */ InputStream cis = new ByteArrayInputStream(data, textIndex, length); /* */ /* 1356 */ InputStream iis = new InflaterInputStream(cis); /* */ /* */ int c; /* 1359 */ while ((c = iis.read()) != -1) { /* 1360 */ value.append((char)c); /* */ } /* */ /* 1363 */ this.ztextKeys.add(key.toString()); /* 1364 */ this.ztextStrings.add(value.toString()); /* 1365 */ } catch (Exception e) { /* 1366 */ e.printStackTrace(); /* */ } /* */ } /* */ /* */ /* */ /* */ /* */ /* */ private WritableRaster createRaster(int width, int height, int bands, int scanlineStride, int bitDepth) { /* 1375 */ WritableRaster ras = null; /* 1376 */ Point origin = new Point(0, 0); /* 1377 */ if (bitDepth < 8 && bands == 1) { /* 1378 */ DataBuffer dataBuffer = new DataBufferByte(height * scanlineStride); /* 1379 */ ras = Raster.createPackedRaster(dataBuffer, width, height, bitDepth, origin); /* */ /* */ /* */ } /* 1383 */ else if (bitDepth <= 8) { /* 1384 */ DataBuffer dataBuffer = new DataBufferByte(height * scanlineStride); /* 1385 */ ras = Raster.createInterleavedRaster(dataBuffer, width, height, scanlineStride, bands, this.bandOffsets[bands], origin); /* */ /* */ /* */ } /* */ else { /* */ /* */ /* 1392 */ DataBuffer dataBuffer = new DataBufferUShort(height * scanlineStride); /* 1393 */ ras = Raster.createInterleavedRaster(dataBuffer, width, height, scanlineStride, bands, this.bandOffsets[bands], origin); /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* 1401 */ return ras; /* */ } /* */ /* */ /* */ /* */ private static void decodeSubFilter(byte[] curr, int count, int bpp) { /* 1407 */ for (int i = bpp; i < count; i++) { /* */ /* */ /* 1410 */ int val = curr[i] & 0xFF; /* 1411 */ val += curr[i - bpp] & 0xFF; /* */ /* 1413 */ curr[i] = (byte)val; /* */ } /* */ } /* */ /* */ /* */ private static void decodeUpFilter(byte[] curr, byte[] prev, int count) { /* 1419 */ for (int i = 0; i < count; i++) { /* 1420 */ int raw = curr[i] & 0xFF; /* 1421 */ int prior = prev[i] & 0xFF; /* */ /* 1423 */ curr[i] = (byte)(raw + prior); /* */ } /* */ } /* */ /* */ private static void decodeAverageFilter(byte[] curr, byte[] prev, int count, int bpp) { /* */ int i; /* 1429 */ for (i = 0; i < bpp; i++) { /* 1430 */ int raw = curr[i] & 0xFF; /* 1431 */ int priorRow = prev[i] & 0xFF; /* */ /* 1433 */ curr[i] = (byte)(raw + priorRow / 2); /* */ } /* */ /* 1436 */ for (i = bpp; i < count; i++) { /* 1437 */ int raw = curr[i] & 0xFF; /* 1438 */ int priorPixel = curr[i - bpp] & 0xFF; /* 1439 */ int priorRow = prev[i] & 0xFF; /* */ /* 1441 */ curr[i] = (byte)(raw + (priorPixel + priorRow) / 2); /* */ } /* */ } /* */ /* */ private static int paethPredictor(int a, int b, int c) { /* 1446 */ int p = a + b - c; /* 1447 */ int pa = Math.abs(p - a); /* 1448 */ int pb = Math.abs(p - b); /* 1449 */ int pc = Math.abs(p - c); /* */ /* 1451 */ if (pa <= pb && pa <= pc) /* 1452 */ return a; /* 1453 */ if (pb <= pc) { /* 1454 */ return b; /* */ } /* 1456 */ return c; /* */ } /* */ /* */ /* */ /* */ /* */ /* */ private static void decodePaethFilter(byte[] curr, byte[] prev, int count, int bpp) { /* */ int i; /* 1465 */ for (i = 0; i < bpp; i++) { /* 1466 */ int raw = curr[i] & 0xFF; /* 1467 */ int priorRow = prev[i] & 0xFF; /* */ /* 1469 */ curr[i] = (byte)(raw + priorRow); /* */ } /* */ /* 1472 */ for (i = bpp; i < count; i++) { /* 1473 */ int raw = curr[i] & 0xFF; /* 1474 */ int priorPixel = curr[i - bpp] & 0xFF; /* 1475 */ int priorRow = prev[i] & 0xFF; /* 1476 */ int priorRowPixel = prev[i - bpp] & 0xFF; /* */ /* 1478 */ curr[i] = (byte)(raw + paethPredictor(priorPixel, priorRow, priorRowPixel)); /* */ } /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ private void processPixels(int process, Raster src, WritableRaster dst, int xOffset, int step, int y, int width) { /* */ int srcX; /* */ boolean flagGammaCorrection; /* 1491 */ int[] workGammaLut, ps = src.getPixel(0, 0, (int[])null); /* 1492 */ int[] pd = dst.getPixel(0, 0, (int[])null); /* */ /* 1494 */ int dstX = xOffset; /* 1495 */ switch (process) { /* */ case 0: /* 1497 */ for (srcX = 0; srcX < width; srcX++) { /* 1498 */ src.getPixel(srcX, 0, ps); /* 1499 */ dst.setPixel(dstX, y, ps); /* 1500 */ dstX += step; /* */ } /* */ break; /* */ /* */ case 1: /* 1505 */ for (srcX = 0; srcX < width; srcX++) { /* 1506 */ src.getPixel(srcX, 0, ps); /* */ /* 1508 */ for (int i = 0; i < this.inputBands; i++) { /* 1509 */ int x = ps[i]; /* 1510 */ ps[i] = this.gammaLut[x]; /* */ } /* */ /* 1513 */ dst.setPixel(dstX, y, ps); /* 1514 */ dstX += step; /* */ } /* */ break; /* */ /* */ case 2: /* 1519 */ for (srcX = 0; srcX < width; srcX++) { /* 1520 */ src.getPixel(srcX, 0, ps); /* */ /* 1522 */ pd[0] = this.grayLut[ps[0]]; /* */ /* 1524 */ dst.setPixel(dstX, y, pd); /* 1525 */ dstX += step; /* */ } /* */ break; /* */ /* */ case 3: /* 1530 */ for (srcX = 0; srcX < width; srcX++) { /* 1531 */ src.getPixel(srcX, 0, ps); /* */ /* 1533 */ int val = ps[0]; /* 1534 */ pd[0] = this.grayLut[val]; /* 1535 */ if (val == this.grayTransparentAlpha) { /* 1536 */ pd[1] = 0; /* */ } else { /* 1538 */ pd[1] = this.maxOpacity; /* */ } /* */ /* 1541 */ dst.setPixel(dstX, y, pd); /* 1542 */ dstX += step; /* */ } /* */ break; /* */ /* */ case 4: /* 1547 */ for (srcX = 0; srcX < width; srcX++) { /* 1548 */ src.getPixel(srcX, 0, ps); /* */ /* 1550 */ int val = ps[0]; /* 1551 */ pd[0] = this.redPalette[val]; /* 1552 */ pd[1] = this.greenPalette[val]; /* 1553 */ pd[2] = this.bluePalette[val]; /* */ /* 1555 */ dst.setPixel(dstX, y, pd); /* 1556 */ dstX += step; /* */ } /* */ break; /* */ /* */ case 5: /* 1561 */ for (srcX = 0; srcX < width; srcX++) { /* 1562 */ src.getPixel(srcX, 0, ps); /* */ /* 1564 */ int val = ps[0]; /* 1565 */ pd[0] = this.redPalette[val]; /* 1566 */ pd[1] = this.greenPalette[val]; /* 1567 */ pd[2] = this.bluePalette[val]; /* 1568 */ pd[3] = this.alphaPalette[val]; /* */ /* 1570 */ dst.setPixel(dstX, y, pd); /* 1571 */ dstX += step; /* */ } /* */ break; /* */ /* */ case 6: /* 1576 */ for (srcX = 0; srcX < width; srcX++) { /* 1577 */ src.getPixel(srcX, 0, ps); /* */ /* 1579 */ int val = ps[0]; /* 1580 */ if (this.performGammaCorrection) { /* 1581 */ val = this.gammaLut[val]; /* */ } /* 1583 */ pd[0] = val; /* 1584 */ if (val == this.grayTransparentAlpha) { /* 1585 */ pd[1] = 0; /* */ } else { /* 1587 */ pd[1] = this.maxOpacity; /* */ } /* */ /* 1590 */ dst.setPixel(dstX, y, pd); /* 1591 */ dstX += step; /* */ } /* */ break; /* */ /* */ case 7: /* 1596 */ flagGammaCorrection = this.performGammaCorrection; /* 1597 */ workGammaLut = this.gammaLut; /* 1598 */ for (srcX = 0; srcX < width; srcX++) { /* 1599 */ src.getPixel(srcX, 0, ps); /* */ /* 1601 */ int r = ps[0]; /* 1602 */ int g = ps[1]; /* 1603 */ int b = ps[2]; /* 1604 */ if (flagGammaCorrection) { /* 1605 */ pd[0] = workGammaLut[r]; /* 1606 */ pd[1] = workGammaLut[g]; /* 1607 */ pd[2] = workGammaLut[b]; /* */ } else { /* 1609 */ pd[0] = r; /* 1610 */ pd[1] = g; /* 1611 */ pd[2] = b; /* */ } /* 1613 */ if (r == this.redTransparentAlpha && g == this.greenTransparentAlpha && b == this.blueTransparentAlpha) { /* */ /* */ /* 1616 */ pd[3] = 0; /* */ } else { /* 1618 */ pd[3] = this.maxOpacity; /* */ } /* */ /* 1621 */ dst.setPixel(dstX, y, pd); /* 1622 */ dstX += step; /* */ } /* */ break; /* */ /* */ case 8: /* 1627 */ for (srcX = 0; srcX < width; srcX++) { /* 1628 */ src.getPixel(srcX, 0, ps); /* */ /* 1630 */ int g = ps[0]; /* 1631 */ if (this.performGammaCorrection) { /* 1632 */ pd[0] = this.gammaLut[g]; /* */ } else { /* 1634 */ pd[0] = g; /* */ } /* */ /* 1637 */ dst.setPixel(dstX, y, pd); /* 1638 */ dstX += step; /* */ } /* */ break; /* */ /* */ case 9: /* 1643 */ for (srcX = 0; srcX < width; srcX++) { /* 1644 */ src.getPixel(srcX, 0, ps); /* */ /* 1646 */ int r = ps[0]; /* 1647 */ int g = ps[1]; /* 1648 */ int b = ps[2]; /* 1649 */ if (this.performGammaCorrection) { /* 1650 */ pd[0] = this.gammaLut[r]; /* 1651 */ pd[1] = this.gammaLut[g]; /* 1652 */ pd[2] = this.gammaLut[b]; /* */ } else { /* 1654 */ pd[0] = r; /* 1655 */ pd[1] = g; /* 1656 */ pd[2] = b; /* */ } /* */ /* 1659 */ dst.setPixel(dstX, y, pd); /* 1660 */ dstX += step; /* */ } /* */ break; /* */ /* */ case 17: /* 1665 */ for (srcX = 0; srcX < width; srcX++) { /* 1666 */ src.getPixel(srcX, 0, ps); /* */ /* 1668 */ int val = ps[0]; /* 1669 */ int alpha = ps[1]; /* 1670 */ int gamma = this.gammaLut[val]; /* 1671 */ pd[0] = gamma; /* 1672 */ pd[1] = gamma; /* 1673 */ pd[2] = gamma; /* 1674 */ pd[3] = alpha; /* */ /* 1676 */ dst.setPixel(dstX, y, pd); /* 1677 */ dstX += step; /* */ } /* */ break; /* */ /* */ case 16: /* 1682 */ for (srcX = 0; srcX < width; srcX++) { /* 1683 */ src.getPixel(srcX, 0, ps); /* */ /* 1685 */ int val = ps[0]; /* 1686 */ int alpha = ps[1]; /* 1687 */ pd[0] = val; /* 1688 */ pd[1] = val; /* 1689 */ pd[2] = val; /* 1690 */ pd[3] = alpha; /* */ /* 1692 */ dst.setPixel(dstX, y, pd); /* 1693 */ dstX += step; /* */ } /* */ break; /* */ /* */ case 22: /* 1698 */ for (srcX = 0; srcX < width; srcX++) { /* 1699 */ src.getPixel(srcX, 0, ps); /* */ /* 1701 */ int val = ps[0]; /* 1702 */ if (this.performGammaCorrection) { /* 1703 */ val = this.gammaLut[val]; /* */ } /* 1705 */ pd[0] = val; /* 1706 */ pd[1] = val; /* 1707 */ pd[2] = val; /* 1708 */ if (val == this.grayTransparentAlpha) { /* 1709 */ pd[3] = 0; /* */ } else { /* 1711 */ pd[3] = this.maxOpacity; /* */ } /* */ /* 1714 */ dst.setPixel(dstX, y, pd); /* 1715 */ dstX += step; /* */ } /* */ break; /* */ /* */ case 19: /* 1720 */ for (srcX = 0; srcX < width; srcX++) { /* 1721 */ src.getPixel(srcX, 0, ps); /* */ /* 1723 */ int val = ps[0]; /* 1724 */ int val2 = this.grayLut[val]; /* 1725 */ pd[0] = val2; /* 1726 */ pd[1] = val2; /* 1727 */ pd[2] = val2; /* 1728 */ if (val == this.grayTransparentAlpha) { /* 1729 */ pd[3] = 0; /* */ } else { /* 1731 */ pd[3] = this.maxOpacity; /* */ } /* */ /* 1734 */ dst.setPixel(dstX, y, pd); /* 1735 */ dstX += step; /* */ } /* */ break; /* */ } /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ private void decodePass(WritableRaster imRas, int xOffset, int yOffset, int xStep, int yStep, int passWidth, int passHeight) { /* 1749 */ if (passWidth == 0 || passHeight == 0) { /* */ return; /* */ } /* */ /* 1753 */ int bytesPerRow = (this.inputBands * passWidth * this.bitDepth + 7) / 8; /* 1754 */ int eltsPerRow = (this.bitDepth == 16) ? (bytesPerRow / 2) : bytesPerRow; /* 1755 */ byte[] curr = new byte[bytesPerRow]; /* 1756 */ byte[] prior = new byte[bytesPerRow]; /* */ /* */ /* 1759 */ WritableRaster passRow = createRaster(passWidth, 1, this.inputBands, eltsPerRow, this.bitDepth); /* */ /* */ /* */ /* 1763 */ DataBuffer dataBuffer = passRow.getDataBuffer(); /* 1764 */ int type = dataBuffer.getDataType(); /* 1765 */ byte[] byteData = null; /* 1766 */ short[] shortData = null; /* 1767 */ if (type == 0) { /* 1768 */ byteData = ((DataBufferByte)dataBuffer).getData(); /* */ } else { /* 1770 */ shortData = ((DataBufferUShort)dataBuffer).getData(); /* */ } /* */ /* */ /* */ /* */ /* 1776 */ int srcY = 0, dstY = yOffset; /* 1777 */ for (; srcY < passHeight; /* 1778 */ srcY++, dstY += yStep) { /* */ String msg; /* 1780 */ int filter = 0; /* */ try { /* 1782 */ filter = this.dataStream.read(); /* 1783 */ this.dataStream.readFully(curr, 0, bytesPerRow); /* 1784 */ } catch (Exception e) { /* 1785 */ e.printStackTrace(); /* */ } /* */ /* 1788 */ switch (filter) { /* */ case 0: /* */ break; /* */ case 1: /* 1792 */ decodeSubFilter(curr, bytesPerRow, this.bytesPerPixel); /* */ break; /* */ case 2: /* 1795 */ decodeUpFilter(curr, prior, bytesPerRow); /* */ break; /* */ case 3: /* 1798 */ decodeAverageFilter(curr, prior, bytesPerRow, this.bytesPerPixel); /* */ break; /* */ case 4: /* 1801 */ decodePaethFilter(curr, prior, bytesPerRow, this.bytesPerPixel); /* */ break; /* */ /* */ default: /* 1805 */ msg = PropertyUtil.getString("PNGImageDecoder16"); /* 1806 */ throw new RuntimeException(msg); /* */ } /* */ /* */ /* 1810 */ if (this.bitDepth < 16) { /* 1811 */ System.arraycopy(curr, 0, byteData, 0, bytesPerRow); /* */ } else { /* 1813 */ int idx = 0; /* 1814 */ for (int j = 0; j < eltsPerRow; j++) { /* 1815 */ shortData[j] = (short)(curr[idx] << 8 | curr[idx + 1] & 0xFF); /* */ /* 1817 */ idx += 2; /* */ } /* */ } /* */ /* 1821 */ processPixels(this.postProcess, passRow, imRas, xOffset, xStep, dstY, passWidth); /* */ /* */ /* */ /* 1825 */ byte[] tmp = prior; /* 1826 */ prior = curr; /* 1827 */ curr = tmp; /* */ } /* */ } /* */ /* */ private void decodeImage(boolean useInterlacing) { /* 1832 */ int width = this.bounds.width; /* 1833 */ int height = this.bounds.height; /* */ /* 1835 */ if (!useInterlacing) { /* 1836 */ decodePass(this.theTile, 0, 0, 1, 1, width, height); /* */ } else { /* 1838 */ decodePass(this.theTile, 0, 0, 8, 8, (width + 7) / 8, (height + 7) / 8); /* 1839 */ decodePass(this.theTile, 4, 0, 8, 8, (width + 3) / 8, (height + 7) / 8); /* 1840 */ decodePass(this.theTile, 0, 4, 4, 8, (width + 3) / 4, (height + 3) / 8); /* 1841 */ decodePass(this.theTile, 2, 0, 4, 4, (width + 1) / 4, (height + 3) / 4); /* 1842 */ decodePass(this.theTile, 0, 2, 2, 4, (width + 1) / 2, (height + 1) / 4); /* 1843 */ decodePass(this.theTile, 1, 0, 2, 2, width / 2, (height + 1) / 2); /* 1844 */ decodePass(this.theTile, 0, 1, 1, 2, width, height / 2); /* */ } /* */ } /* */ /* */ public WritableRaster copyData(WritableRaster wr) { /* 1849 */ GraphicsUtil.copyData(this.theTile, wr); /* 1850 */ return wr; /* */ } /* */ /* */ /* */ /* */ public Raster getTile(int tileX, int tileY) { /* 1856 */ if (tileX != 0 || tileY != 0) { /* */ /* 1858 */ String msg = PropertyUtil.getString("PNGImageDecoder17"); /* 1859 */ throw new IllegalArgumentException(msg); /* */ } /* 1861 */ return this.theTile; /* */ } /* */ } /* Location: /mnt/r/ConTenDoViewer.jar!/org/apache/xmlgraphics/image/codec/png/PNGRed.class * Java compiler version: 5 (49.0) * JD-Core Version: 1.1.3 */
92323a3d59223c950ab07b14ec079da7840144a1
1,599
java
Java
java/j8study/src/main/java/net/x841bc/j8study/asm/ClassPrinter.java
sillyemperor/langstudy
937a11d97984e10e4ead54f3b7b7d6a1f2ef24a1
[ "MIT" ]
null
null
null
java/j8study/src/main/java/net/x841bc/j8study/asm/ClassPrinter.java
sillyemperor/langstudy
937a11d97984e10e4ead54f3b7b7d6a1f2ef24a1
[ "MIT" ]
null
null
null
java/j8study/src/main/java/net/x841bc/j8study/asm/ClassPrinter.java
sillyemperor/langstudy
937a11d97984e10e4ead54f3b7b7d6a1f2ef24a1
[ "MIT" ]
null
null
null
26.65
115
0.739212
996,148
package net.x841bc.j8study.asm; import java.io.IOException; import org.objectweb.asm.AnnotationVisitor; import org.objectweb.asm.Attribute; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.FieldVisitor; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; public class ClassPrinter extends ClassVisitor { public ClassPrinter() { super(Opcodes.ASM4); } public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { System.out.println(name + " extends " + superName + " {"); } public void visitSource(String source, String debug) { } public void visitOuterClass(String owner, String name, String desc) { } public AnnotationVisitor visitAnnotation(String desc, boolean visible) { return null; } public void visitAttribute(Attribute attr) { } public void visitInnerClass(String name, String outerName, String innerName, int access) { } public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) { System.out.println(" " + desc + " " + name); return null; } public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { System.out.println(" " + name + desc); return null; } public void visitEnd() { System.out.println("}"); } public static void main(String[] args) throws IOException { ClassPrinter cp = new ClassPrinter(); ClassReader cr = new ClassReader("net.x841bc.j8study.asm.ClassPrinter"); cr.accept(cp, 0); } }
92323b3d3af22ce4165b1ee70590cd727d257155
820
java
Java
swt/src/internal/win32/SHACTIVATEINFO.java
NIL-zhuang/IRBL
4f787e2bf065f728f086dfad07d71ef6210dd159
[ "MIT" ]
null
null
null
swt/src/internal/win32/SHACTIVATEINFO.java
NIL-zhuang/IRBL
4f787e2bf065f728f086dfad07d71ef6210dd159
[ "MIT" ]
null
null
null
swt/src/internal/win32/SHACTIVATEINFO.java
NIL-zhuang/IRBL
4f787e2bf065f728f086dfad07d71ef6210dd159
[ "MIT" ]
null
null
null
37.272727
81
0.597561
996,149
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.swt.internal.win32; public class SHACTIVATEINFO { public int cbSize; public int hwndLastFocus; public int fSipUp; // :1 public int fSipOnDeactivation; // :1 public int fActive; // :1 public int fReserved; // :29 public static final int sizeof = 12; }
92323cf297293e5753d61cb05e6c4adc6e1080a3
26,938
java
Java
sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java
Priyalc/Gcloud
e6252c0e9191aef4c8bea98bdeb8340dd09d9695
[ "Apache-2.0" ]
3
2015-04-18T18:51:49.000Z
2015-10-15T03:34:03.000Z
sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java
Priyalc/Gcloud
e6252c0e9191aef4c8bea98bdeb8340dd09d9695
[ "Apache-2.0" ]
null
null
null
sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java
Priyalc/Gcloud
e6252c0e9191aef4c8bea98bdeb8340dd09d9695
[ "Apache-2.0" ]
2
2015-04-18T18:51:41.000Z
2015-05-27T07:02:36.000Z
36.402703
100
0.647041
996,150
/* * Copyright (C) 2015 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.cloud.dataflow.sdk.io; import com.google.api.client.util.Preconditions; import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; import com.google.cloud.dataflow.sdk.coders.VoidCoder; import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; import com.google.cloud.dataflow.sdk.runners.worker.FileBasedReader; import com.google.cloud.dataflow.sdk.runners.worker.TextReader; import com.google.cloud.dataflow.sdk.runners.worker.TextSink; import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.util.ReaderUtils; import com.google.cloud.dataflow.sdk.util.WindowedValue; import com.google.cloud.dataflow.sdk.util.WindowingStrategy; import com.google.cloud.dataflow.sdk.util.common.worker.Sink; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.PDone; import com.google.cloud.dataflow.sdk.values.PInput; import com.google.common.primitives.Ints; import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PushbackInputStream; import java.util.List; import java.util.regex.Pattern; import java.util.zip.GZIPInputStream; import javax.annotation.Nullable; /** * Transforms for reading and writing text files. * * <p> To read a {@link PCollection} from one or more text files, use * {@link TextIO.Read}, specifying {@link TextIO.Read#from} to specify * the path of the file(s) to read from (e.g., a local filename or * filename pattern if running locally, or a Google Cloud Storage * filename or filename pattern of the form * {@code "gs://<bucket>/<filepath>"}), and optionally * {@link TextIO.Read#named} to specify the name of the pipeline step * and/or {@link TextIO.Read#withCoder} to specify the Coder to use to * decode the text lines into Java values. For example: * * <pre> {@code * Pipeline p = ...; * * // A simple Read of a local file (only runs locally): * PCollection<String> lines = * p.apply(TextIO.Read.from("/path/to/file.txt")); * * // A fully-specified Read from a GCS file (runs locally and via the * // Google Cloud Dataflow service): * PCollection<Integer> numbers = * p.apply(TextIO.Read.named("ReadNumbers") * .from("gs://my_bucket/path/to/numbers-*.txt") * .withCoder(TextualIntegerCoder.of())); * } </pre> * * <p> To write a {@link PCollection} to one or more text files, use * {@link TextIO.Write}, specifying {@link TextIO.Write#to} to specify * the path of the file to write to (e.g., a local filename or sharded * filename pattern if running locally, or a Google Cloud Storage * filename or sharded filename pattern of the form * {@code "gs://<bucket>/<filepath>"}), and optionally * {@link TextIO.Write#named} to specify the name of the pipeline step * and/or {@link TextIO.Write#withCoder} to specify the Coder to use * to encode the Java values into text lines. For example: * * <pre> {@code * // A simple Write to a local file (only runs locally): * PCollection<String> lines = ...; * lines.apply(TextIO.Write.to("/path/to/file.txt")); * * // A fully-specified Write to a sharded GCS file (runs locally and via the * // Google Cloud Dataflow service): * PCollection<Integer> numbers = ...; * numbers.apply(TextIO.Write.named("WriteNumbers") * .to("gs://my_bucket/path/to/numbers") * .withSuffix(".txt") * .withCoder(TextualIntegerCoder.of())); * } </pre> */ public class TextIO { public static final Coder<String> DEFAULT_TEXT_CODER = StringUtf8Coder.of(); /** * A root PTransform that reads from a text file (or multiple text * files matching a pattern) and returns a PCollection containing * the decoding of each of the lines of the text file(s). The * default decoding just returns the lines. */ public static class Read { /** * Returns a TextIO.Read PTransform with the given step name. */ public static Bound<String> named(String name) { return new Bound<>(DEFAULT_TEXT_CODER).named(name); } /** * Returns a TextIO.Read PTransform that reads from the file(s) * with the given name or pattern. This can be a local filename * or filename pattern (if running locally), or a Google Cloud * Storage filename or filename pattern of the form * {@code "gs://<bucket>/<filepath>"}) (if running locally or via * the Google Cloud Dataflow service). Standard * <a href="http://docs.oracle.com/javase/tutorial/essential/io/find.html" * >Java Filesystem glob patterns</a> ("*", "?", "[..]") are supported. */ public static Bound<String> from(String filepattern) { return new Bound<>(DEFAULT_TEXT_CODER).from(filepattern); } /** * Returns a TextIO.Read PTransform that uses the given * {@code Coder<T>} to decode each of the lines of the file into a * value of type {@code T}. * * <p> By default, uses {@link StringUtf8Coder}, which just * returns the text lines as Java strings. * * @param <T> the type of the decoded elements, and the elements * of the resulting PCollection */ public static <T> Bound<T> withCoder(Coder<T> coder) { return new Bound<>(coder); } /** * Returns a TextIO.Read PTransform that has GCS path validation on * pipeline creation disabled. * * <p> This can be useful in the case where the GCS input does not * exist at the pipeline creation time, but is expected to be * available at execution time. */ public static Bound<String> withoutValidation() { return new Bound<>(DEFAULT_TEXT_CODER).withoutValidation(); } /** * Returns a TextIO.Read PTransform that reads from a file with the * specified compression type. * * <p> If no compression type is specified, the default is AUTO. In this * mode, the compression type of the file is determined by its extension * (e.g., *.gz is gzipped, *.bz2 is bzipped, all other extensions are * uncompressed). */ public static Bound<String> withCompressionType(TextIO.CompressionType compressionType) { return new Bound<>(DEFAULT_TEXT_CODER).withCompressionType(compressionType); } // TODO: strippingNewlines, etc. /** * A root PTransform that reads from a text file (or multiple text files * matching a pattern) and returns a bounded PCollection containing the * decoding of each of the lines of the text file(s). The default * decoding just returns the lines. * * @param <T> the type of each of the elements of the resulting * PCollection, decoded from the lines of the text file */ public static class Bound<T> extends PTransform<PInput, PCollection<T>> { private static final long serialVersionUID = 0; /** The filepattern to read from. */ @Nullable final String filepattern; /** The Coder to use to decode each line. */ @Nullable final Coder<T> coder; /** An option to indicate if input validation is desired. Default is true. */ final boolean validate; /** Option to indicate the input source's compression type. Default is AUTO. */ final TextIO.CompressionType compressionType; Bound(Coder<T> coder) { this(null, null, coder, true, TextIO.CompressionType.AUTO); } Bound(String name, String filepattern, Coder<T> coder, boolean validate, TextIO.CompressionType compressionType) { super(name); this.coder = coder; this.filepattern = filepattern; this.validate = validate; this.compressionType = compressionType; } /** * Returns a new TextIO.Read PTransform that's like this one but * with the given step name. Does not modify this object. */ public Bound<T> named(String name) { return new Bound<>(name, filepattern, coder, validate, compressionType); } /** * Returns a new TextIO.Read PTransform that's like this one but * that reads from the file(s) with the given name or pattern. * (See {@link TextIO.Read#from} for a description of * filepatterns.) Does not modify this object. */ public Bound<T> from(String filepattern) { return new Bound<>(name, filepattern, coder, validate, compressionType); } /** * Returns a new TextIO.Read PTransform that's like this one but * that uses the given {@code Coder<T1>} to decode each of the * lines of the file into a value of type {@code T1}. Does not * modify this object. * * @param <T1> the type of the decoded elements, and the * elements of the resulting PCollection */ public <T1> Bound<T1> withCoder(Coder<T1> coder) { return new Bound<>(name, filepattern, coder, validate, compressionType); } /** * Returns a new TextIO.Read PTransform that's like this one but * that has GCS path validation on pipeline creation disabled. * Does not modify this object. * * <p> This can be useful in the case where the GCS input does not * exist at the pipeline creation time, but is expected to be * available at execution time. */ public Bound<T> withoutValidation() { return new Bound<>(name, filepattern, coder, false, compressionType); } /** * Returns a new TextIO.Read PTransform that's like this one but * reads from input sources using the specified compression type. * Does not modify this object. * * <p> If AUTO compression type is specified, a compression type is * selected on a per-file basis, based on the file's extension (e.g., * .gz will be processed as a gzipped file, .bz will be processed * as a bzipped file, other extensions with be treated as uncompressed * input). * * <p> If no compression type is specified, the default is AUTO. */ public Bound<T> withCompressionType(TextIO.CompressionType compressionType) { return new Bound<>(name, filepattern, coder, validate, compressionType); } @Override public PCollection<T> apply(PInput input) { if (filepattern == null) { throw new IllegalStateException("need to set the filepattern of a TextIO.Read transform"); } // Force the output's Coder to be what the read is using, and // unchangeable later, to ensure that we read the input in the // format specified by the Read transform. return PCollection.<T>createPrimitiveOutputInternal(WindowingStrategy.globalDefault()) .setCoder(coder); } @Override protected Coder<T> getDefaultOutputCoder() { return coder; } @Override protected String getKindString() { return "TextIO.Read"; } public String getFilepattern() { return filepattern; } public boolean needsValidation() { return validate; } public TextIO.CompressionType getCompressionType() { return compressionType; } static { DirectPipelineRunner.registerDefaultTransformEvaluator( Bound.class, new DirectPipelineRunner.TransformEvaluator<Bound>() { @Override public void evaluate( Bound transform, DirectPipelineRunner.EvaluationContext context) { evaluateReadHelper(transform, context); } }); } } } ///////////////////////////////////////////////////////////////////////////// /** * A PTransform that writes a PCollection to a text file (or * multiple text files matching a sharding pattern), with each * PCollection element being encoded into its own line. */ public static class Write { /** * Returns a TextIO.Write PTransform with the given step name. */ public static Bound<String> named(String name) { return new Bound<>(DEFAULT_TEXT_CODER).named(name); } /** * Returns a TextIO.Write PTransform that writes to the file(s) * with the given prefix. This can be a local filename * (if running locally), or a Google Cloud Storage filename of * the form {@code "gs://<bucket>/<filepath>"}) * (if running locally or via the Google Cloud Dataflow service). * * <p> The files written will begin with this prefix, followed by * a shard identifier (see {@link Bound#withNumShards}, and end * in a common extension, if given by {@link Bound#withSuffix}. */ public static Bound<String> to(String prefix) { return new Bound<>(DEFAULT_TEXT_CODER).to(prefix); } /** * Returns a TextIO.Write PTransform that writes to the file(s) with the * given filename suffix. */ public static Bound<String> withSuffix(String nameExtension) { return new Bound<>(DEFAULT_TEXT_CODER).withSuffix(nameExtension); } /** * Returns a TextIO.Write PTransform that uses the provided shard count. * * <p> Constraining the number of shards is likely to reduce * the performance of a pipeline. Setting this value is not recommended * unless you require a specific number of output files. * * @param numShards the number of shards to use, or 0 to let the system * decide. */ public static Bound<String> withNumShards(int numShards) { return new Bound<>(DEFAULT_TEXT_CODER).withNumShards(numShards); } /** * Returns a TextIO.Write PTransform that uses the given shard name * template. * * <p> See {@link ShardNameTemplate} for a description of shard templates. */ public static Bound<String> withShardNameTemplate(String shardTemplate) { return new Bound<>(DEFAULT_TEXT_CODER).withShardNameTemplate(shardTemplate); } /** * Returns a TextIO.Write PTransform that forces a single file as * output. */ public static Bound<String> withoutSharding() { return new Bound<>(DEFAULT_TEXT_CODER).withoutSharding(); } /** * Returns a TextIO.Write PTransform that uses the given * {@code Coder<T>} to encode each of the elements of the input * {@code PCollection<T>} into an output text line. * * <p> By default, uses {@link StringUtf8Coder}, which writes input * Java strings directly as output lines. * * @param <T> the type of the elements of the input PCollection */ public static <T> Bound<T> withCoder(Coder<T> coder) { return new Bound<>(coder); } /** * Returns a TextIO.Write PTransform that has GCS path validation on * pipeline creation disabled. * * <p> This can be useful in the case where the GCS output location does * not exist at the pipeline creation time, but is expected to be available * at execution time. */ public static Bound<String> withoutValidation() { return new Bound<>(DEFAULT_TEXT_CODER).withoutValidation(); } // TODO: appendingNewlines, header, footer, etc. /** * A PTransform that writes a bounded PCollection to a text file (or * multiple text files matching a sharding pattern), with each * PCollection element being encoded into its own line. * * @param <T> the type of the elements of the input PCollection */ public static class Bound<T> extends PTransform<PCollection<T>, PDone> { private static final long serialVersionUID = 0; /** The filename to write to. */ @Nullable final String filenamePrefix; /** Suffix to use for each filename. */ final String filenameSuffix; /** The Coder to use to decode each line. */ final Coder<T> coder; /** Requested number of shards. 0 for automatic. */ final int numShards; /** Shard template string. */ final String shardTemplate; /** An option to indicate if output validation is desired. Default is true. */ final boolean validate; Bound(Coder<T> coder) { this(null, null, "", coder, 0, ShardNameTemplate.INDEX_OF_MAX, true); } Bound(String name, String filenamePrefix, String filenameSuffix, Coder<T> coder, int numShards, String shardTemplate, boolean validate) { super(name); this.coder = coder; this.filenamePrefix = filenamePrefix; this.filenameSuffix = filenameSuffix; this.numShards = numShards; this.shardTemplate = shardTemplate; this.validate = validate; } /** * Returns a new TextIO.Write PTransform that's like this one but * with the given step name. Does not modify this object. */ public Bound<T> named(String name) { return new Bound<>(name, filenamePrefix, filenameSuffix, coder, numShards, shardTemplate, validate); } /** * Returns a new TextIO.Write PTransform that's like this one but * that writes to the file(s) with the given filename prefix. * * <p> See {@link Write#to(String) Write.to(String)} for more information. * * <p> Does not modify this object. */ public Bound<T> to(String filenamePrefix) { validateOutputComponent(filenamePrefix); return new Bound<>(name, filenamePrefix, filenameSuffix, coder, numShards, shardTemplate, validate); } /** * Returns a new TextIO.Write PTransform that's like this one but * that writes to the file(s) with the given filename suffix. * * <p> Does not modify this object. * * @see ShardNameTemplate */ public Bound<T> withSuffix(String nameExtension) { validateOutputComponent(nameExtension); return new Bound<>(name, filenamePrefix, nameExtension, coder, numShards, shardTemplate, validate); } /** * Returns a new TextIO.Write PTransform that's like this one but * that uses the provided shard count. * * <p> Constraining the number of shards is likely to reduce * the performance of a pipeline. Setting this value is not recommended * unless you require a specific number of output files. * * <p> Does not modify this object. * * @param numShards the number of shards to use, or 0 to let the system * decide. * @see ShardNameTemplate */ public Bound<T> withNumShards(int numShards) { Preconditions.checkArgument(numShards >= 0); return new Bound<>(name, filenamePrefix, filenameSuffix, coder, numShards, shardTemplate, validate); } /** * Returns a new TextIO.Write PTransform that's like this one but * that uses the given shard name template. * * <p> Does not modify this object. * * @see ShardNameTemplate */ public Bound<T> withShardNameTemplate(String shardTemplate) { return new Bound<>(name, filenamePrefix, filenameSuffix, coder, numShards, shardTemplate, validate); } /** * Returns a new TextIO.Write PTransform that's like this one but * that forces a single file as output. * * <p> This is a shortcut for * {@code .withNumShards(1).withShardNameTemplate("")} * * <p> Does not modify this object. */ public Bound<T> withoutSharding() { return new Bound<>(name, filenamePrefix, filenameSuffix, coder, 1, "", validate); } /** * Returns a new TextIO.Write PTransform that's like this one * but that uses the given {@code Coder<T1>} to encode each of * the elements of the input {@code PCollection<T1>} into an * output text line. Does not modify this object. * * @param <T1> the type of the elements of the input PCollection */ public <T1> Bound<T1> withCoder(Coder<T1> coder) { return new Bound<>(name, filenamePrefix, filenameSuffix, coder, numShards, shardTemplate, validate); } /** * Returns a new TextIO.Write PTransform that's like this one but * that has GCS output path validation on pipeline creation disabled. * Does not modify this object. * * <p> This can be useful in the case where the GCS output location does * not exist at the pipeline creation time, but is expected to be * available at execution time. */ public Bound<T> withoutValidation() { return new Bound<>(name, filenamePrefix, filenameSuffix, coder, numShards, shardTemplate, false); } @Override public PDone apply(PCollection<T> input) { if (filenamePrefix == null) { throw new IllegalStateException( "need to set the filename prefix of a TextIO.Write transform"); } return new PDone(); } /** * Returns the current shard name template string. */ public String getShardNameTemplate() { return shardTemplate; } @Override protected Coder<Void> getDefaultOutputCoder() { return VoidCoder.of(); } @Override protected String getKindString() { return "TextIO.Write"; } public String getFilenamePrefix() { return filenamePrefix; } public String getShardTemplate() { return shardTemplate; } public int getNumShards() { return numShards; } public String getFilenameSuffix() { return filenameSuffix; } public Coder<T> getCoder() { return coder; } public boolean needsValidation() { return validate; } static { DirectPipelineRunner.registerDefaultTransformEvaluator( Bound.class, new DirectPipelineRunner.TransformEvaluator<Bound>() { @Override public void evaluate( Bound transform, DirectPipelineRunner.EvaluationContext context) { evaluateWriteHelper(transform, context); } }); } } } /** * Possible text file compression types. */ public static enum CompressionType implements FileBasedReader.DecompressingStreamFactory { /** * Automatically determine the compression type based on filename extension. */ AUTO(""), /** * Uncompressed (i.e., may be split). */ UNCOMPRESSED(""), /** * GZipped. */ GZIP(".gz") { @Override public InputStream createInputStream(InputStream inputStream) throws IOException { // Determine if the input stream is gzipped. The input stream returned from the // GCS connector may already be decompressed, and no action is required. PushbackInputStream stream = new PushbackInputStream(inputStream, 2); byte[] headerBytes = new byte[2]; int bytesRead = stream.read(headerBytes); stream.unread(headerBytes, 0, bytesRead); int header = Ints.fromBytes((byte) 0, (byte) 0, headerBytes[1], headerBytes[0]); if (header == GZIPInputStream.GZIP_MAGIC) { return new GZIPInputStream(stream); } return stream; } }, /** * BZipped. */ BZIP2(".bz2") { @Override public InputStream createInputStream(InputStream inputStream) throws IOException { return new BZip2CompressorInputStream(inputStream); } }; private String filenameSuffix; private CompressionType(String suffix) { this.filenameSuffix = suffix; } /** * Determine if a given filename matches a compression type based on its extension. * @param filename the filename to match * @return true iff the filename ends with the compression type's known extension. */ public boolean matches(String filename) { return filename.toLowerCase().endsWith(filenameSuffix.toLowerCase()); } @Override public InputStream createInputStream(InputStream inputStream) throws IOException { return inputStream; } } // Pattern which matches old-style shard output patterns, which are now // disallowed. private static final Pattern SHARD_OUTPUT_PATTERN = Pattern.compile("@([0-9]+|\\*)"); private static void validateOutputComponent(String partialFilePattern) { Preconditions.checkArgument( !SHARD_OUTPUT_PATTERN.matcher(partialFilePattern).find(), "Output name components are not allowed to contain @* or @N patterns: " + partialFilePattern); } ////////////////////////////////////////////////////////////////////////////// private static <T> void evaluateReadHelper( Read.Bound<T> transform, DirectPipelineRunner.EvaluationContext context) { TextReader<T> reader = new TextReader<>(transform.filepattern, true, null, null, transform.coder, transform.getCompressionType()); List<T> elems = ReaderUtils.readElemsFromReader(reader); context.setPCollection(context.getOutput(transform), elems); } private static <T> void evaluateWriteHelper( Write.Bound<T> transform, DirectPipelineRunner.EvaluationContext context) { List<T> elems = context.getPCollection(context.getInput(transform)); int numShards = transform.numShards; if (numShards < 1) { // System gets to choose. For direct mode, choose 1. numShards = 1; } TextSink<WindowedValue<T>> writer = TextSink.createForDirectPipelineRunner( transform.filenamePrefix, transform.getShardNameTemplate(), transform.filenameSuffix, numShards, true, null, null, transform.coder); try (Sink.SinkWriter<WindowedValue<T>> sink = writer.writer()) { for (T elem : elems) { sink.add(WindowedValue.valueInGlobalWindow(elem)); } } catch (IOException exn) { throw new RuntimeException( "unable to write to output file \"" + transform.filenamePrefix + "\"", exn); } } }
92323d9bab23da8af81e7056b6b29749ce5999d7
529
java
Java
src/main/java/com/holmes/hoo/blackwatch/config/MybatisPlusConfig.java
keke-nan/hoo-blackwatch
01897793508038d73165e39b077da31b9626e7bc
[ "MIT" ]
null
null
null
src/main/java/com/holmes/hoo/blackwatch/config/MybatisPlusConfig.java
keke-nan/hoo-blackwatch
01897793508038d73165e39b077da31b9626e7bc
[ "MIT" ]
null
null
null
src/main/java/com/holmes/hoo/blackwatch/config/MybatisPlusConfig.java
keke-nan/hoo-blackwatch
01897793508038d73165e39b077da31b9626e7bc
[ "MIT" ]
null
null
null
33.0625
72
0.782609
996,151
package com.holmes.hoo.blackwatch.config; import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor; import org.mybatis.spring.annotation.MapperScan; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; //@Configuration //@MapperScan(basePackages = {"com.holmes.hoo.blackwatch.mapper"}) //public class MybatisPlusConfig { // @Bean // public PaginationInterceptor paginationInterceptor() { // return new PaginationInterceptor(); // } //}