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
922f8683084333a1d3e1a0fdf52a72b78dba5916
7,636
java
Java
src/mixedmodel/CausalRegions.java
theLongLab/mkTWAS
474e90add17b86226585e511ceb94fb361e85069
[ "Unlicense", "MIT" ]
null
null
null
src/mixedmodel/CausalRegions.java
theLongLab/mkTWAS
474e90add17b86226585e511ceb94fb361e85069
[ "Unlicense", "MIT" ]
null
null
null
src/mixedmodel/CausalRegions.java
theLongLab/mkTWAS
474e90add17b86226585e511ceb94fb361e85069
[ "Unlicense", "MIT" ]
null
null
null
41.275676
119
0.738738
995,147
package mixedmodel; import java.util.Arrays; import org.apache.commons.math3.linear.Array2DRowRealMatrix; public class CausalRegions { public int[][] regions;// [#regions][3]: chr,start, end double[] var_comp; public KinshipMatrix[] reginal_kinships; public RelationMatrix[] relational_matrixs; public KinshipMatrix global_kinship; public RelationMatrix global_relation; public KinshipMatrix combined_kinship; public RelationMatrix combined_relation; public CausalRegions(int[][] regions, double[] var_comp, String[] reginal_kinship_files, String[] relation_matrix_files, KinshipMatrix global_kinship, RelationMatrix global_relation, VariantsDouble data_obs, VariantsDouble data_pred){ this.regions=regions.clone(); this.var_comp=var_comp.clone(); for(int i=0;i<regions.length;i++)regions[i].clone(); this.reginal_kinships=new KinshipMatrix[this.regions.length]; this.relational_matrixs=new RelationMatrix[this.regions.length]; this.global_kinship=global_kinship; this.global_relation=global_relation; // calculate kinships for(int r=0;r<regions.length;r++){ this.reginal_kinships[r]=new KinshipMatrix(data_obs, regions[r]); this.reginal_kinships[r].write2file(reginal_kinship_files[r]); this.relational_matrixs[r]=new RelationMatrix(data_obs, data_pred, regions[r]); this.relational_matrixs[r].write2file(relation_matrix_files[r]); } } /* * for simualtion only, given a full data, generate the observed and predicted local kinships * * calculate and write local-kinships or load wrt whether geno_full==null */ public CausalRegions(int[][] regions, double[] var_comp, String[] reginal_full_kinship_files, KinshipMatrix global_kinship, RelationMatrix global_relation, String[] obs_ids, String[] pred_ids){ this.regions=regions.clone(); this.var_comp=var_comp.clone(); for(int i=0;i<regions.length;i++)regions[i].clone(); this.reginal_kinships=new KinshipMatrix[this.regions.length]; this.relational_matrixs=new RelationMatrix[this.regions.length]; this.global_kinship=global_kinship; this.global_relation=global_relation; // calculate kinships for(int r=0;r<regions.length;r++){ KinshipMatrix the_local_full=new KinshipMatrix(reginal_full_kinship_files[r]); this.reginal_kinships[r]=KinshipMatrix.submatrix(the_local_full, obs_ids); this.relational_matrixs[r]=RelationMatrix.submatrix(the_local_full, obs_ids, pred_ids); } } public CausalRegions(int[][] regions, double[] var_comp, String[] reginal_kinship_files, String[] relation_matrix_files, KinshipMatrix global_kinship, RelationMatrix global_relation){ this.regions=regions.clone(); this.var_comp=var_comp.clone(); for(int i=0;i<regions.length;i++)regions[i].clone(); this.reginal_kinships=new KinshipMatrix[this.regions.length]; this.relational_matrixs=new RelationMatrix[this.regions.length]; this.global_kinship=global_kinship; this.global_relation=global_relation; // load kinships for(int r=0;r<regions.length;r++){ this.reginal_kinships[r]=new KinshipMatrix(reginal_kinship_files[r]); this.relational_matrixs[r]=new RelationMatrix(relation_matrix_files[r]); } } public void generte_combined(double[] var_comp){ if(var_comp!=null){ if(var_comp.length!=regions.length){ System.out.println("var_comp.length!=regions.length"); } } this.combined_kinship=new KinshipMatrix(new Array2DRowRealMatrix( this.global_kinship.kinship_matrix.getData(),true), this.global_kinship.ids); this.combined_relation=new RelationMatrix(new Array2DRowRealMatrix( this.global_relation.relation_matrix.getData(),true), this.global_relation.obs_ids, this.global_relation.pred_ids); for(int r=0;r<this.reginal_kinships.length;r++){ this.combined_kinship.kinship_matrix= this.combined_kinship.kinship_matrix.add (this.reginal_kinships[r].kinship_matrix.scalarMultiply(var_comp[r])); this.combined_relation.relation_matrix= this.combined_relation.relation_matrix.add (this.relational_matrixs[r].relation_matrix.scalarMultiply(var_comp[r])); } } public void generte_combined_no_global(double[] var_comp){ if(var_comp!=null){ if(var_comp.length!=regions.length){ System.out.println("var_comp.length!=regions.length"); } } this.combined_kinship=new KinshipMatrix(new Array2DRowRealMatrix( new double[this.global_kinship.ids.length][this.global_kinship.ids.length]), this.global_kinship.ids); this.combined_relation=new RelationMatrix(new Array2DRowRealMatrix( new double[this.global_relation.pred_ids.length][this.global_relation.obs_ids.length]), this.global_relation.obs_ids, this.global_relation.pred_ids); for(int r=0;r<this.reginal_kinships.length;r++){ this.combined_kinship.kinship_matrix= this.combined_kinship.kinship_matrix.add (this.reginal_kinships[r].kinship_matrix.scalarMultiply(var_comp[r])); this.combined_relation.relation_matrix= this.combined_relation.relation_matrix.add (this.relational_matrixs[r].relation_matrix.scalarMultiply(var_comp[r])); } } public static int[][] generate_regions(String local_kinship_result_file, double[] var_comp){ int num_chr=22, win=100000; AssociationResults local=new AssociationResults(local_kinship_result_file, 0.9); int[][] regions=new int[num_chr][3]; double[] ps=new double[num_chr]; //double[] r2s=new double[num_chr]; Arrays.fill(ps, 1); Arrays.fill(var_comp, 1); for(int chr=0;chr<num_chr;chr++){ regions[chr][0]=chr; } for(int index=0;index<local.num_of_var;index++){ if(local.pvalue[index]<ps[local.chr[index]-1]){ ps[local.chr[index]-1]=local.pvalue[index]; var_comp[local.chr[index]-1]=local.AdjustedR2[index];//*(-Math.log(local.pvalue[index])); regions[local.chr[index]-1][1]=local.location[index]; regions[local.chr[index]-1][2]=local.location[index]+win; } } for(int chr=0;chr<num_chr;chr++){ System.out.println(regions[chr][0]+":"+regions[chr][1]+":"+regions[chr][2]+":"+var_comp[chr]+":"); } return regions; } public static void main(String[] args){ String geno_folder="/Users/quanlong/Documents/projects2/predictions/RA_data/genotypes/"; String local_K_folder=geno_folder+"local_RRM/"; String[] types={"etanercept","infliximab","adalimumab","all"}; int win=100000; int[][][] regions={ //"etanercept" {{0,160500001,160500001+win},{10,24350001,24350001+win}}, //"infliximab" {{15,26150001,26150001+win},{11,19950001,19950001+win}}, // "adalimumab" {{16,25500001,25500001+win},{2,82650001,82650001+win}}, // "all" {{12,95250001,95250001+win},{13,101500001,101500001+1}} }; for(int k=0;k<types.length;k++){ System.out.println("==============="+types[k]+"================="); VariantsDouble obs_geno=new VariantsDouble(geno_folder+types[k]+".train.hdf5"); VariantsDouble pred_geno=new VariantsDouble(geno_folder+types[k]+".test.hdf5"); int[][] the_regions=regions[k]; String[] reginal_kinship_files=new String[the_regions.length]; String[] relation_matrix_files=new String[the_regions.length]; for(int i=0;i<the_regions.length;i++){ reginal_kinship_files[i]=local_K_folder+types[k]+".train."+(the_regions[i][0]+1)+"."+ the_regions[i][1]+"."+the_regions[i][2]+".K.RRM"; relation_matrix_files[i]=local_K_folder+types[k]+".train.test."+(the_regions[i][0]+1)+"."+ the_regions[i][1]+"."+the_regions[i][2]+".K.RRM"; } CausalRegions cal=new CausalRegions(the_regions, null, reginal_kinship_files, relation_matrix_files, null, null, obs_geno, pred_geno); } } }
922f8757b442631c7f9385829cbe725e9fc398c3
4,227
java
Java
fhir-search/src/test/java/com/ibm/fhir/search/sort/test/SortUriTest.java
gggyi123/FHIR
3c10e6014c7c804732a6ce6f8200c32d3199bf55
[ "Apache-2.0" ]
209
2019-08-14T15:11:17.000Z
2022-03-25T10:30:35.000Z
fhir-search/src/test/java/com/ibm/fhir/search/sort/test/SortUriTest.java
gggyi123/FHIR
3c10e6014c7c804732a6ce6f8200c32d3199bf55
[ "Apache-2.0" ]
1,944
2019-08-29T20:03:24.000Z
2022-03-31T22:38:28.000Z
fhir-search/src/test/java/com/ibm/fhir/search/sort/test/SortUriTest.java
gggyi123/FHIR
3c10e6014c7c804732a6ce6f8200c32d3199bf55
[ "Apache-2.0" ]
134
2019-09-02T10:36:17.000Z
2022-03-06T15:08:07.000Z
42.69697
119
0.734327
995,148
/* * (C) Copyright IBM Corp. 2016,2019 * * SPDX-License-Identifier: Apache-2.0 */ package com.ibm.fhir.search.sort.test; import static org.testng.Assert.assertEquals; import java.net.URISyntaxException; import org.testng.annotations.Test; import com.ibm.fhir.search.SearchConstants; import com.ibm.fhir.search.context.FHIRSearchContext; import com.ibm.fhir.search.context.FHIRSearchContextFactory; import com.ibm.fhir.search.parameters.SortParameter; import com.ibm.fhir.search.sort.Sort; import com.ibm.fhir.search.uri.UriBuilder; /** * Tests the Sort with UriBuilder */ public class SortUriTest { @Test public void testSortUriSingleDescendingParameter() throws URISyntaxException { SortParameter parameter = new SortParameter("_id", SearchConstants.Type.NUMBER, Sort.Direction.DECREASING); FHIRSearchContext context = FHIRSearchContextFactory.createSearchContext(); context.getSortParameters().add(parameter); UriBuilder builder = UriBuilder.builder(); builder.requestUri("https://localhost/fhir-server"); builder.context(context); assertEquals(builder.toSearchSelfUri(), "https://localhost/fhir-server?_count=10&_sort=-_id&_page=1"); } @Test public void testSortUriSingleAscendingParameter() throws URISyntaxException { SortParameter parameter = new SortParameter("_id", SearchConstants.Type.NUMBER, Sort.Direction.INCREASING); FHIRSearchContext context = FHIRSearchContextFactory.createSearchContext(); context.getSortParameters().add(parameter); UriBuilder builder = UriBuilder.builder(); builder.requestUri("https://localhost/fhir-server"); builder.context(context); assertEquals(builder.toSearchSelfUri(), "https://localhost/fhir-server?_count=10&_sort=_id&_page=1"); } @Test public void testSortUriDoubleDescendingParameter() throws URISyntaxException { SortParameter parameter1 = new SortParameter("test1", SearchConstants.Type.NUMBER, Sort.Direction.DECREASING); SortParameter parameter2 = new SortParameter("test2", SearchConstants.Type.NUMBER, Sort.Direction.DECREASING); FHIRSearchContext context = FHIRSearchContextFactory.createSearchContext(); context.getSortParameters().add(parameter1); context.getSortParameters().add(parameter2); UriBuilder builder = UriBuilder.builder(); builder.requestUri("https://localhost/fhir-server"); builder.context(context); assertEquals(builder.toSearchSelfUri(), "https://localhost/fhir-server?_count=10&_sort=-test1,-test2&_page=1"); } @Test public void testSortUriDoubleMixingParameter() throws URISyntaxException { SortParameter parameter1 = new SortParameter("test1", SearchConstants.Type.NUMBER, Sort.Direction.DECREASING); SortParameter parameter2 = new SortParameter("test2", SearchConstants.Type.NUMBER, Sort.Direction.INCREASING); FHIRSearchContext context = FHIRSearchContextFactory.createSearchContext(); context.getSortParameters().add(parameter1); context.getSortParameters().add(parameter2); UriBuilder builder = UriBuilder.builder(); builder.requestUri("https://localhost/fhir-server"); builder.context(context); assertEquals(builder.toSearchSelfUri(), "https://localhost/fhir-server?_count=10&_sort=-test1,test2&_page=1"); } @Test public void testSortUriDoubleIncreasingParameter() throws URISyntaxException { SortParameter parameter1 = new SortParameter("test1", SearchConstants.Type.NUMBER, Sort.Direction.INCREASING); SortParameter parameter2 = new SortParameter("test2", SearchConstants.Type.NUMBER, Sort.Direction.INCREASING); FHIRSearchContext context = FHIRSearchContextFactory.createSearchContext(); context.getSortParameters().add(parameter1); context.getSortParameters().add(parameter2); UriBuilder builder = UriBuilder.builder(); builder.requestUri("https://localhost/fhir-server"); builder.context(context); assertEquals(builder.toSearchSelfUri(), "https://localhost/fhir-server?_count=10&_sort=test1,test2&_page=1"); } }
922f897b128d93a1423b3eea4c3157eeb0b2d482
1,111
java
Java
spring-geode/src/main/java/org/springframework/geode/core/util/function/FunctionUtils.java
jujoramos/spring-boot-data-geode
b21f4af0e910ddf11e3956ecb6ee3018d808c2db
[ "Apache-2.0" ]
45
2017-06-20T13:26:49.000Z
2022-03-30T06:03:35.000Z
spring-geode/src/main/java/org/springframework/geode/core/util/function/FunctionUtils.java
jujoramos/spring-boot-data-geode
b21f4af0e910ddf11e3956ecb6ee3018d808c2db
[ "Apache-2.0" ]
108
2018-02-06T23:52:06.000Z
2022-03-08T20:08:07.000Z
spring-geode/src/main/java/org/springframework/geode/core/util/function/FunctionUtils.java
jujoramos/spring-boot-data-geode
b21f4af0e910ddf11e3956ecb6ee3018d808c2db
[ "Apache-2.0" ]
45
2017-06-13T20:31:40.000Z
2022-03-03T12:21:45.000Z
28.487179
85
0.721872
995,149
/* * Copyright 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.springframework.geode.core.util.function; import java.util.function.Consumer; import java.util.function.Function; /** * Utility methods for using Java {@link Function Functions}. * * @author John Blum * @see Function * @since 1.1.0 */ @SuppressWarnings("unused") public abstract class FunctionUtils { public static <T, R> Function<T, R> toNullReturningFunction(Consumer<T> consumer) { return object -> { consumer.accept(object); return null; }; } }
922f8a2dc05459d21331839384a5d189265b0eab
425
java
Java
src/main/java/com/yummy/multiple/multipleproject/ServletInitializer.java
bgym/multipleproject
722e3e85ac92ee7700407e6ad995e53c8e987a4c
[ "MIT" ]
null
null
null
src/main/java/com/yummy/multiple/multipleproject/ServletInitializer.java
bgym/multipleproject
722e3e85ac92ee7700407e6ad995e53c8e987a4c
[ "MIT" ]
null
null
null
src/main/java/com/yummy/multiple/multipleproject/ServletInitializer.java
bgym/multipleproject
722e3e85ac92ee7700407e6ad995e53c8e987a4c
[ "MIT" ]
null
null
null
30.357143
85
0.863529
995,150
package com.yummy.multiple.multipleproject; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.support.SpringBootServletInitializer; public class ServletInitializer extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(MultipleprojectApplication.class); } }
922f8ab7b2f493474db45078ae296795d3f2d832
1,248
java
Java
faceunity/src/main/java/com/faceunity/nama/entity/MakeupCombinationBean.java
Faceunity/FUAgoraDemoDroid
cff187366f9a3b4fb4ade29b44c8ba5c4ed489b0
[ "MIT" ]
55
2017-02-06T06:17:41.000Z
2022-03-30T06:18:24.000Z
faceunity/src/main/java/com/faceunity/nama/entity/MakeupCombinationBean.java
Faceunity/FUAgoraDemoDroid
cff187366f9a3b4fb4ade29b44c8ba5c4ed489b0
[ "MIT" ]
9
2017-02-04T12:09:08.000Z
2021-12-31T05:48:02.000Z
faceunity/src/main/java/com/faceunity/nama/entity/MakeupCombinationBean.java
Faceunity/FUAgoraDemoDroid
cff187366f9a3b4fb4ade29b44c8ba5c4ed489b0
[ "MIT" ]
20
2017-02-07T01:46:23.000Z
2022-03-14T12:14:48.000Z
20.129032
91
0.612179
995,151
package com.faceunity.nama.entity; /** * DESC:美妆-组合妆容 * Created on 2021/4/26 */ public class MakeupCombinationBean { private String key;//名称标识 private int imageRes;//图片 private int desRes;//描述 private String bundlePath;//资源句柄 private double intensity = 1.0;//强度 public MakeupCombinationBean(String key, int imageRes, int desRes, String bundlePath) { this.key = key; this.imageRes = imageRes; this.desRes = desRes; this.bundlePath = bundlePath; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public int getImageRes() { return imageRes; } public void setImageRes(int imageRes) { this.imageRes = imageRes; } public int getDesRes() { return desRes; } public void setDesRes(int desRes) { this.desRes = desRes; } public String getBundlePath() { return bundlePath; } public void setBundlePath(String bundlePath) { this.bundlePath = bundlePath; } public double getIntensity() { return intensity; } public void setIntensity(double intensity) { this.intensity = intensity; } }
922f8aea0224ca99c62e7fe4220fbdce9c27051f
3,073
java
Java
src/main/java/org/springframework/social/evernote/connect/EvernoteOAuthToken.java
szilard-nemeth/spring-social-evernote
e8f654329b75414d56f903436c80a92573618b3a
[ "Apache-2.0" ]
6
2015-06-16T06:38:59.000Z
2020-12-06T19:50:55.000Z
src/main/java/org/springframework/social/evernote/connect/EvernoteOAuthToken.java
szilard-nemeth/spring-social-evernote
e8f654329b75414d56f903436c80a92573618b3a
[ "Apache-2.0" ]
2
2016-01-22T12:24:49.000Z
2020-12-08T08:17:22.000Z
src/main/java/org/springframework/social/evernote/connect/EvernoteOAuthToken.java
szilard-nemeth/spring-social-evernote
e8f654329b75414d56f903436c80a92573618b3a
[ "Apache-2.0" ]
4
2015-06-18T12:22:54.000Z
2020-12-06T19:51:04.000Z
26.721739
87
0.769281
995,152
package org.springframework.social.evernote.connect; import org.springframework.social.oauth1.OAuthToken; /** * Sample access-token response params: * {oauth_token=[....], * oauth_token_secret=[], * edam_shard=[s1], * edam_userId=[123456], * edam_expires=[1418253288396], * edam_noteStoreUrl=[https://sandbox.evernote.com/shard/s1/notestore], * edam_webApiUrlPrefix=[https://sandbox.evernote.com/shard/s1/]} * * @author Tadaya Tsuyukubo */ public class EvernoteOAuthToken extends OAuthToken { public static final String KEY_OAUTH_TOKEN = "oauth_token"; public static final String KEY_OAUTH_TOKEN_SECRET = "oauth_token_secret"; public static final String EDAM_SHARD = "edam_shard"; public static final String EDAM_USER_ID = "edam_userId"; public static final String EDAM_EXPIRES = "edam_expires"; public static final String EDAM_NOTE_STORE_URL = "edam_noteStoreUrl"; public static final String EDAM_WEB_API_URL_PREFIX = "edam_webApiUrlPrefix"; private String edamShard; private String edamUserId; private String edamExpires; private String edamNoteStoreUrl; private String edamWebApiUrlPrefix; private EvernoteOAuthToken(String value, String secret) { super(value, secret); } public String getEdamShard() { return edamShard; } public String getEdamUserId() { return edamUserId; } public String getEdamExpires() { return edamExpires; } public String getEdamNoteStoreUrl() { return edamNoteStoreUrl; } public String getEdamWebApiUrlPrefix() { return edamWebApiUrlPrefix; } public static class EvernoteOAuthTokenBuilder { private String value; private String secret; private String edamShard; private String edamUserId; private String edamExpires; private String edamNoteStoreUrl; private String edamWebApiUrlPrefix; public EvernoteOAuthToken build() { // TODO: assert null EvernoteOAuthToken token = new EvernoteOAuthToken(this.value, this.secret); token.edamShard = this.edamShard; token.edamUserId = this.edamUserId; token.edamExpires = this.edamExpires; token.edamNoteStoreUrl = this.edamNoteStoreUrl; token.edamWebApiUrlPrefix = this.edamWebApiUrlPrefix; return token; } public EvernoteOAuthTokenBuilder setToken(String value) { this.value = value; return this; } public EvernoteOAuthTokenBuilder setSecret(String secret) { this.secret = secret; return this; } public EvernoteOAuthTokenBuilder setEdamShard(String edamShard) { this.edamShard = edamShard; return this; } public EvernoteOAuthTokenBuilder setEdamUserId(String edamUserId) { this.edamUserId = edamUserId; return this; } public EvernoteOAuthTokenBuilder setEdamExpires(String edamExpires) { this.edamExpires = edamExpires; return this; } public EvernoteOAuthTokenBuilder setEdamNoteStoreUrl(String edamNoteStoreUrl) { this.edamNoteStoreUrl = edamNoteStoreUrl; return this; } public EvernoteOAuthTokenBuilder setEdamWebApiUrlPrefix(String edamWebApiUrlPrefix) { this.edamWebApiUrlPrefix = edamWebApiUrlPrefix; return this; } } }
922f8ba3d4570c54a2b9b6c817509817d241a41b
190
java
Java
chapter_003/src/main/java/ru/job4j/threads/Test.java
Logg1X/job4j
cb1091ada845ed7eba7092994e350e14dc4f31e4
[ "Apache-2.0" ]
null
null
null
chapter_003/src/main/java/ru/job4j/threads/Test.java
Logg1X/job4j
cb1091ada845ed7eba7092994e350e14dc4f31e4
[ "Apache-2.0" ]
null
null
null
chapter_003/src/main/java/ru/job4j/threads/Test.java
Logg1X/job4j
cb1091ada845ed7eba7092994e350e14dc4f31e4
[ "Apache-2.0" ]
null
null
null
21.111111
68
0.742105
995,153
package ru.job4j.threads; import java.util.concurrent.locks.ReentrantLock; public class Test { private int size; private ReentrantLock[][] board = new ReentrantLock[size][size]; }
922f8bc3a5f4d01a9464433ecc901c452a9a0e8f
1,669
java
Java
Classes/WrapLabelView.java
Vinschers/Chat
6b092aaee321d62e35b9fc471baa5f7418a92902
[ "MIT" ]
null
null
null
Classes/WrapLabelView.java
Vinschers/Chat
6b092aaee321d62e35b9fc471baa5f7418a92902
[ "MIT" ]
null
null
null
Classes/WrapLabelView.java
Vinschers/Chat
6b092aaee321d62e35b9fc471baa5f7418a92902
[ "MIT" ]
null
null
null
35.510638
81
0.4997
995,154
import javax.swing.text.*; public class WrapLabelView extends LabelView { public WrapLabelView(Element elem) { super(elem); } public int getBreakWeight(int axis, float pos, float len) { if (axis == View.X_AXIS) { checkPainter(); int p0 = getStartOffset(); int p1 = getGlyphPainter().getBoundedPosition(this, p0, pos, len); if (p1 == p0) { // can't even fit a single character return View.BadBreakWeight; } try { //if the view contains line break char return forced break if (getDocument().getText(p0, p1 - p0).indexOf("\r") >= 0) { return View.ForcedBreakWeight; } } catch (BadLocationException ex) { //should never happen } } return super.getBreakWeight(axis, pos, len); } public View breakView(int axis, int p0, float pos, float len) { if (axis == View.X_AXIS) { checkPainter(); int p1 = getGlyphPainter().getBoundedPosition(this, p0, pos, len); try { //if the view contains line break char break the view int index = getDocument().getText(p0, p1 - p0).indexOf("\r"); if (index >= 0) { GlyphView v = (GlyphView) createFragment(p0, p0 + index + 1); return v; } } catch (BadLocationException ex) { //should never happen } } return super.breakView(axis, p0, pos, len); } }
922f8c020519af5312b0e2e0405c3c6761b0fc9e
118
java
Java
examples/Server/src/tNet/events/OnReceiveDataListener.java
tiagoccosta/tNet
c0eab1e4cfc9d458086c375b13f3086cd524f683
[ "Apache-2.0" ]
1
2019-03-18T06:05:23.000Z
2019-03-18T06:05:23.000Z
source/tNet/events/OnReceiveDataListener.java
tiagoccosta/tNet
c0eab1e4cfc9d458086c375b13f3086cd524f683
[ "Apache-2.0" ]
null
null
null
source/tNet/events/OnReceiveDataListener.java
tiagoccosta/tNet
c0eab1e4cfc9d458086c375b13f3086cd524f683
[ "Apache-2.0" ]
null
null
null
14.75
38
0.788136
995,155
package tNet.events; import tNet.*; public interface OnReceiveDataListener { public void run(NetworkMessage msg); }
922f8c63af35bddebaa963fa7628810c8b1cab42
2,965
java
Java
app/backend/src/main/java/pl/lodz/p/it/inz/sgruda/multiStore/entities/moz/OrderEntity.java
sgruda/multiStore
61a4941fce4624e6b96cbbd973798fe1ed4cb602
[ "MIT" ]
1
2021-07-06T16:24:41.000Z
2021-07-06T16:24:41.000Z
app/backend/src/main/java/pl/lodz/p/it/inz/sgruda/multiStore/entities/moz/OrderEntity.java
sgruda/multiStore
61a4941fce4624e6b96cbbd973798fe1ed4cb602
[ "MIT" ]
null
null
null
app/backend/src/main/java/pl/lodz/p/it/inz/sgruda/multiStore/entities/moz/OrderEntity.java
sgruda/multiStore
61a4941fce4624e6b96cbbd973798fe1ed4cb602
[ "MIT" ]
null
null
null
35.722892
108
0.705902
995,156
package pl.lodz.p.it.inz.sgruda.multiStore.entities.moz; import lombok.Getter; import lombok.Setter; import lombok.ToString; import pl.lodz.p.it.inz.sgruda.multiStore.entities.mok.AccountEntity; import pl.lodz.p.it.inz.sgruda.multiStore.utils.interfaces.VersionGetter; import javax.persistence.*; import javax.validation.constraints.Digits; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import javax.validation.constraints.Size; import java.io.Serializable; import java.time.LocalDateTime; import java.util.HashSet; import java.util.Set; import java.util.UUID; @ToString @Getter @Setter @Entity @Table(name = "order", schema = "public") @TableGenerator(name = "OrderIdGen", table = "id_generator", schema = "public", pkColumnName = "class_name", valueColumnName = "id_range", pkColumnValue = "order") public class OrderEntity implements Serializable, VersionGetter { @Id @Column(name = "id", nullable = false) @GeneratedValue(strategy = GenerationType.TABLE, generator = "OrderIdGen") private long id; @Basic(optional = false) @NotNull(message = "validation.notnull") @Size(min = 36, max = 36, message = "validation.size") @Pattern(regexp = "[0-9A-Za-z-]+", message = "validation.pattern") @Column(name = "identifier", nullable = false, length = 32) private String identifier; @Basic(optional = false) @NotNull(message = "validation.notnull") @Column(name = "order_date", nullable = false) private LocalDateTime orderDate; @NotNull(message = "validation.notnull") @JoinColumn(name = "account_id", referencedColumnName = "id", nullable = false, updatable = false) @ManyToOne(optional = false) private AccountEntity accountEntity; @ManyToMany(fetch = FetchType.EAGER) @JoinTable(name = "ordered_item_order_mapping", joinColumns = @JoinColumn(name = "order_id"), inverseJoinColumns = @JoinColumn(name = "ordered_item_id")) private Set<OrderedItemEntity> orderedItemEntities = new HashSet<>(); @Digits(integer = 7, fraction = 2, message = "validation.digits") @Basic(optional = false) @NotNull(message = "validation.notnull") @Column(name = "total_price", nullable = false) private double totalPrice; @NotNull(message = "validation.notnull") @JoinColumn(name = "status_id", referencedColumnName = "id", nullable = false) @ManyToOne(optional = false) private StatusEntity statusEntity; @NotNull(message = "validation.notnull") @Size(max = 64, message = "validation.size") @Pattern(regexp = "[-0-9A-ZĄĆĘŁŃÓŚŹŻa-ząćęłńóśźżĄĆĘŁŃÓŚŹŻ/,.' ]+", message = "validation.pattern") @Column(name = "address", nullable = false, length = 64) private String address; @Version @Basic @Column(name = "version", nullable = false) private long version; public OrderEntity() { this.identifier = UUID.randomUUID().toString(); } }
922f8d1d47279a714765eab3ea4ab61765f0279a
1,367
java
Java
src/main/java/com/monst/bankingplugin/repository/EntityMap.java
FreshLlamanade/BankingPlugin
b183fec3d08e1b09ee468a4cd8dd0f05aa9bfbda
[ "MIT" ]
1
2020-07-10T07:46:20.000Z
2020-07-10T07:46:20.000Z
src/main/java/com/monst/bankingplugin/repository/EntityMap.java
FreshLlamanade/BankingPlugin
b183fec3d08e1b09ee468a4cd8dd0f05aa9bfbda
[ "MIT" ]
null
null
null
src/main/java/com/monst/bankingplugin/repository/EntityMap.java
FreshLlamanade/BankingPlugin
b183fec3d08e1b09ee468a4cd8dd0f05aa9bfbda
[ "MIT" ]
null
null
null
23.169492
88
0.646672
995,157
package com.monst.bankingplugin.repository; import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; import com.monst.bankingplugin.banking.BankingEntity; import com.monst.bankingplugin.gui.GUI; import com.monst.bankingplugin.utils.Observable; import java.util.HashSet; import java.util.Map; import java.util.Set; abstract class EntityMap<Location, Entity extends BankingEntity> implements Observable { private final BiMap<Location, Entity> biMap; private final Set<GUI<?>> observers; EntityMap() { this.biMap = HashBiMap.create(); this.observers = new HashSet<>(); } abstract Location getLocation(Entity entity); void put(Entity entity) { Entity a = biMap.forcePut(getLocation(entity), entity); if (a != null) notifyObservers(); } void remove(Entity entity) { Entity a = biMap.remove(getLocation(entity)); if (a != null) notifyObservers(); } Set<Location> keySet() { return biMap.keySet(); } Set<Entity> values() { return biMap.values(); } Entity get(Location key) { return biMap.get(key); } Set<Map.Entry<Location, Entity>> entrySet() { return biMap.entrySet(); } @Override public Set<GUI<?>> getObservers() { return observers; } }
922f8d330f31b4f68c4d2b78cf2f7612b55ba7d3
5,719
java
Java
animation-builder/src/main/java/net/jspiner/animation/AnimationBuilder.java
JSpiner/AnimationBuilder
23a81de6c175fdafaf7d34b9d5d4bd6e16a2d901
[ "Apache-2.0" ]
8
2018-04-16T04:44:41.000Z
2019-03-15T13:15:30.000Z
animation-builder/src/main/java/net/jspiner/animation/AnimationBuilder.java
JSpiner/AnimationBuilder
23a81de6c175fdafaf7d34b9d5d4bd6e16a2d901
[ "Apache-2.0" ]
null
null
null
animation-builder/src/main/java/net/jspiner/animation/AnimationBuilder.java
JSpiner/AnimationBuilder
23a81de6c175fdafaf7d34b9d5d4bd6e16a2d901
[ "Apache-2.0" ]
null
null
null
30.420213
116
0.63665
995,158
package net.jspiner.animation; import android.animation.Animator; import android.animation.ValueAnimator; import android.view.View; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.Interpolator; import android.view.animation.LinearInterpolator; import android.view.animation.ScaleAnimation; import android.view.animation.TranslateAnimation; public class AnimationBuilder { public static AnimationBuilder builder() { return new AnimationBuilder(); } private AnimationBuilder() { } private static final int DEFAULT_DURATION = 500; private static final Interpolator DEFAULT_INTERPOLATOR = new LinearInterpolator(); private AnimationWrapper targetAnimation; private long startDelay = 0; private long duration = DEFAULT_DURATION; private Runnable startListener; private Runnable endListener; private UpdateListener updateListener; private Interpolator animationInterpolator = DEFAULT_INTERPOLATOR; private View targetView; private int repeatCount; public AnimationBuilder alphaAnimation(float startAlpha, float endAlpha) { this.targetAnimation = new AnimationWrapper( new AlphaAnimation( startAlpha, endAlpha ) ); return this; } public AnimationBuilder translateAnimation(float fromXDelta, float toXDelta, float fromYDelta, float toYDelta) { this.targetAnimation = new AnimationWrapper( new TranslateAnimation( fromXDelta, toXDelta, fromYDelta, toYDelta ) ); return this; } public AnimationBuilder scaleAnimation(float fromX, float toX, float fromY, float toY) { this.targetAnimation = new AnimationWrapper( new ScaleAnimation( fromX, toX, fromY, toY ) ); return this; } public AnimationBuilder valueAnimator(int... values) { this.targetAnimation = new AnimationWrapper( ValueAnimator.ofInt(values) ); return this; } public AnimationBuilder startDelay(long startDelay) { this.startDelay = startDelay; return this; } public AnimationBuilder duration(long duration) { this.duration = duration; return this; } public AnimationBuilder onUpdate(UpdateListener updateListener) { this.updateListener = updateListener; return this; } public AnimationBuilder onStart(Runnable startListener) { this.startListener = startListener; return this; } public AnimationBuilder onEnd(Runnable endListener) { this.endListener = endListener; return this; } public AnimationBuilder interpolator(Interpolator interpolator) { this.animationInterpolator = interpolator; return this; } public AnimationBuilder repeat(int repeatCount) { this.repeatCount = repeatCount; return this; } public AnimationBuilder targetView(View targetView) { this.targetView = targetView; return this; } public void start() { if (targetAnimation.isViewAnimation()) { startViewAnimation(); } else { startAnimator(); } } private void startViewAnimation() { initAnimation(); this.targetView.startAnimation(targetAnimation.getViewAnimation()); } private void initAnimation() { targetAnimation.getViewAnimation().setInterpolator(animationInterpolator); targetAnimation.getViewAnimation().setDuration(duration); targetAnimation.getViewAnimation().setStartOffset(startDelay); targetAnimation.getViewAnimation().setRepeatCount(repeatCount); targetAnimation.getViewAnimation().setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { if (startListener != null) startListener.run(); } @Override public void onAnimationEnd(Animation animation) { if (endListener != null) endListener.run(); } @Override public void onAnimationRepeat(Animation animation) { } }); } private void startAnimator() { initAnimator(); targetAnimation.getAnimator().start(); } private void initAnimator() { targetAnimation.getAnimator().setInterpolator(animationInterpolator); targetAnimation.getAnimator().setDuration(duration); targetAnimation.getAnimator().setStartDelay(startDelay); targetAnimation.getAnimator().setRepeatCount(repeatCount); targetAnimation.getAnimator().addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animator) { if (startListener != null) startListener.run(); } @Override public void onAnimationEnd(Animator animator) { if (endListener != null) endListener.run(); } @Override public void onAnimationCancel(Animator animator) { } @Override public void onAnimationRepeat(Animator animator) { } }); targetAnimation.getAnimator().addUpdateListener(valueAnimator -> { updateListener.onUpdate((Integer) valueAnimator.getAnimatedValue()); }); } }
922f8d69b17d2a0151d2491f91d16150d819cb76
3,570
java
Java
src/Utils/FileHandler.java
Simba-Cream/SCARF
aa8d9720eb8d262c30cd868b3ae11286cfec30d6
[ "MIT" ]
1
2015-04-14T00:33:58.000Z
2015-04-14T00:33:58.000Z
src/Utils/FileHandler.java
Simba-Cream/SCARF
aa8d9720eb8d262c30cd868b3ae11286cfec30d6
[ "MIT" ]
null
null
null
src/Utils/FileHandler.java
Simba-Cream/SCARF
aa8d9720eb8d262c30cd868b3ae11286cfec30d6
[ "MIT" ]
null
null
null
31.043478
109
0.681513
995,159
/* * The MIT License * * Copyright 2015 michaeldowdle. * * 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 Utils; import Checker.Checker; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.nio.charset.Charset; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Paths; /** * FileHandler class to handle writting and reading from files * * @author michaeldowdle */ public class FileHandler { /** * * @param fileName * @return * @throws FileNotFoundException * @throws IOException */ public static String FileToString(String fileName) throws FileNotFoundException, IOException { String contents = ""; //read in file to string stream FileInputStream scfis = new FileInputStream(fileName); BufferedReader reader = new BufferedReader(new InputStreamReader(scfis)); //get first line of string stream int lineNo = 1; String line = reader.readLine(); while (line != null) { contents += line; line = reader.readLine(); lineNo++; } return contents; } /** * * @param data * @param fileName * @throws FileNotFoundException * @throws IOException */ public static void StringToFile(String data, String fileName) throws FileNotFoundException, IOException { //write String to File try (FileOutputStream scfos = new FileOutputStream(fileName); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(scfos))) { writer.write(data); } } /** * * @param path * @param encoding * @return * @throws IOException */ public static String readFile(String path, Charset encoding) throws IOException { byte[] encoded = Files.readAllBytes(Paths.get(path)); return new String(encoded, encoding); } /** * * @param fileName * @throws IOException */ public static void deleteFile(String fileName) throws IOException { //check file is not orginal source code file if (!fileName.equals(Checker.sourceCodeFile)) { //delete file Files.deleteIfExists(FileSystems.getDefault().getPath(fileName)); } } }
922f91f9cd67751addbc2ade5f5ae690386ced7d
7,412
java
Java
src/main/java/com/github/relucent/base/common/crypto/signature/SignatureCrypto.java
Relucent/yyl-base-lib
44fab61fb37bc398b4955952bf4327e90efc7eb8
[ "Apache-2.0" ]
3
2019-01-06T12:57:05.000Z
2019-09-26T03:24:16.000Z
src/main/java/com/github/relucent/base/common/crypto/signature/SignatureCrypto.java
Relucent/yyl-base-lib
44fab61fb37bc398b4955952bf4327e90efc7eb8
[ "Apache-2.0" ]
11
2019-09-23T05:22:56.000Z
2022-02-07T03:48:55.000Z
src/main/java/com/github/relucent/base/common/crypto/signature/SignatureCrypto.java
Relucent/yyl-base-lib
44fab61fb37bc398b4955952bf4327e90efc7eb8
[ "Apache-2.0" ]
1
2018-12-29T04:02:39.000Z
2018-12-29T04:02:39.000Z
29.284585
103
0.533
995,160
package com.github.relucent.base.common.crypto.signature; import java.security.InvalidAlgorithmParameterException; import java.security.KeyPair; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.Signature; import java.security.cert.Certificate; import java.security.cert.X509Certificate; import java.security.spec.AlgorithmParameterSpec; import java.util.Set; import com.github.relucent.base.common.crypto.CryptoException; import com.github.relucent.base.common.crypto.asymmetric.KeyUtil; /** * 数字签名算法类,提供数据的签名与验证方法(私钥数字签名,公钥验证)<br> * 注意:该类的实例不保证线程安全,应当避免多线程同时调用同一个实例(每个线程使用独立的实例,或者在调用时候增加同步锁)。<br> * @see java.security.Signature */ public class SignatureCrypto { // =================================Fields================================================ /** KeyUsage扩展的对象标识符 (Object Identifier,OID) */ private static final String KEY_USAGE_OID = "192.168.3.11"; /** 算法名称 */ protected String algorithm; /** 公钥 */ protected PublicKey publicKey; /** 私钥 */ protected PrivateKey privateKey; /** 签名,提供数字签名算法功能(签名和验证) */ protected Signature signature; // =================================Constructors=========================================== /** * 构造函数<br> * 使用随机的密钥对(私钥和公钥)<br> * @param algorithm 签名算法 */ public SignatureCrypto(SignatureAlgorithm algorithm) { this(algorithm, null, null); } /** * 构造函数<br> * 传入私钥,只能用于生成数字签名<br> * @param algorithm 签名算法 * @param privateKey 私钥 */ public SignatureCrypto(SignatureAlgorithm algorithm, PrivateKey privateKey) { this(algorithm, privateKey, null); } /** * 构造函数<br> * 传入公钥,只能用于做数字签名的合法性验证<br> * @param algorithm 签名算法 * @param publicKey 公钥 */ public SignatureCrypto(SignatureAlgorithm algorithm, PublicKey publicKey) { this(algorithm, null, publicKey); } /** * 构造函数<br> * 私钥和公钥同时为null时,使用随机的密钥对(私钥和公钥)。 <br> * 私钥和公钥可以只传入一个,只能用来做签名或者验证一种操作。 <br> * @param algorithm 签名算法 * @param privateKey 私钥 * @param publicKey 公钥 */ public SignatureCrypto(SignatureAlgorithm algorithm, PrivateKey privateKey, PublicKey publicKey) { this(algorithm.getValue(), privateKey, publicKey); } /** * 构造函数<br> * 私钥和公钥同时为null时,使用随机的密钥对(私钥和公钥)。 <br> * 私钥和公钥可以只传入一个,只能用来做签名或者验证一种操作。 <br> * @param algorithm 签名算法 * @param privateKey 私钥 * @param publicKey 公钥 */ protected SignatureCrypto(String algorithm, PrivateKey privateKey, PublicKey publicKey) { initialize(algorithm, privateKey, publicKey); } // =================================InitializeMethods====================================== /** * 初始化 * @param algorithm 算法 * @param privateKey 私钥 * @param publicKey 公钥 */ protected void initialize(String algorithm, PrivateKey privateKey, PublicKey publicKey) { this.algorithm = algorithm; try { this.signature = Signature.getInstance(algorithm); } catch (NoSuchAlgorithmException e) { throw new CryptoException(e); } if (privateKey == null && publicKey == null) { KeyPair keyPair = generateKeyPair(); this.privateKey = keyPair.getPrivate(); this.publicKey = keyPair.getPublic(); } else { this.privateKey = privateKey; this.publicKey = publicKey; } } /** * 生成用于密钥对(非对称加密的公钥和私钥)<br> * @return 密钥对 */ protected KeyPair generateKeyPair() { return KeyUtil.generateKeyPair(algorithm); } // =================================Methods================================================ /** * 用私钥对信息生成数字签名 * @param data 加密数据 * @return 签名 */ public byte[] sign(byte[] data) { try { signature.initSign(privateKey); signature.update(data); return signature.sign(); } catch (Exception e) { throw new CryptoException(e); } } /** * 用公钥检验数字签名的合法性 * @param data 数据 * @param sign 签名 * @return 是否验证通过 */ public boolean verify(byte[] data, byte[] sign) { try { signature.initVerify(publicKey); signature.update(data); return signature.verify(sign); } catch (Exception e) { throw new CryptoException(e); } } // =================================SetMethods============================================= /** * 设置身份证书{@link Certificate} 为PublicKey<br> * @param certificate 身份证{@link Certificate} * @return this */ public SignatureCrypto setCertificate(Certificate certificate) { // 检查是否有密钥扩展 if (certificate instanceof X509Certificate) { final X509Certificate x509 = (X509Certificate) certificate; final Set<String> oids = x509.getCriticalExtensionOIDs(); if (oids != null && oids.contains(KEY_USAGE_OID)) { final boolean[] keyUsage = x509.getKeyUsage(); // KeyUsage ::= BIT STRING // [0] digitalSignature // [1] nonRepudiation // [2] keyEncipherment // [3] dataEncipherment // [4] keyAgreement // [5] keyCertSign // [6] cRLSign // [7] encipherOnly // [8] decipherOnly if (keyUsage != null && !keyUsage[0]) { throw new CryptoException("Certificate keyUsage Error"); } } } this.publicKey = certificate.getPublicKey(); return this; } /** * 使用指定的参数集初始化此签名引擎 * @param params 算法参数 * @return this */ public SignatureCrypto setParameter(AlgorithmParameterSpec params) { try { signature.setParameter(params); } catch (InvalidAlgorithmParameterException e) { throw new CryptoException(e); } return this; } /** * 设置私钥 * @param privateKey 私钥 * @return this */ public SignatureCrypto setPrivateKey(PrivateKey privateKey) { this.privateKey = privateKey; return this; } /** * 设置公钥 * @param publicKey 公钥 * @return this */ public SignatureCrypto setPublicKey(PublicKey publicKey) { this.publicKey = publicKey; return this; } // =================================GetMethods============================================= /** * 返回算法名称(字符串表示) * @return 算法名称 */ public String getAlgorithm() { return algorithm; } /** * 获得签名对象 {@link Signature} * @return 签名对象 */ public Signature getSignature() { return signature; } /** * 获得私钥 * @return 获得私钥 */ public PrivateKey getPrivateKey() { return this.privateKey; } /** * 获得公钥 * @return 获得公钥 */ public PublicKey getPublicKey() { return this.publicKey; } }
922f92b22128f4f7bfe418c54af2b58cbdec72f5
419
java
Java
_src/Chapter13/ch04/src/main/java/org/packt/secured/mvc/core/password/DbEncPasswordGen.java
paullewallencom/spring-978-1-7871-2831-6
57e8b58a34ebedde97f5b73aae99096be55c1c49
[ "Apache-2.0" ]
42
2017-10-07T20:51:50.000Z
2022-03-12T19:49:04.000Z
_src/Chapter13/ch04/src/main/java/org/packt/secured/mvc/core/password/DbEncPasswordGen.java
paullewallencom/spring-978-1-7871-2831-6
57e8b58a34ebedde97f5b73aae99096be55c1c49
[ "Apache-2.0" ]
null
null
null
_src/Chapter13/ch04/src/main/java/org/packt/secured/mvc/core/password/DbEncPasswordGen.java
paullewallencom/spring-978-1-7871-2831-6
57e8b58a34ebedde97f5b73aae99096be55c1c49
[ "Apache-2.0" ]
41
2017-10-09T01:24:28.000Z
2021-04-10T12:21:15.000Z
27.933333
80
0.713604
995,161
package org.packt.secured.mvc.core.password; public class DbEncPasswordGen { public static void main(String[] args) { AppPasswordEncoder encoder = new AppPasswordEncoder(); System.out.println("sjctrags: " + encoder.md5Encoder("sjctrags", "sjctrags")); System.out.println("admin: " + encoder.md5Encoder("admin", "admin")); System.out.println("hradmin: " + encoder.md5Encoder("hradmin", "hradmin")); } }
922f93070e8ab9c4008c34654dc61cd51588896e
661
java
Java
Programming Fundamentals/10 Regex-Lab/4.Match Dates/src/com/softuni/techmodule/Main.java
VelinDimitrov/TechModule-SoftUni-Java
b82fa9c62e69f61c84a97d8a4dc914ff9ec7a628
[ "MIT" ]
null
null
null
Programming Fundamentals/10 Regex-Lab/4.Match Dates/src/com/softuni/techmodule/Main.java
VelinDimitrov/TechModule-SoftUni-Java
b82fa9c62e69f61c84a97d8a4dc914ff9ec7a628
[ "MIT" ]
null
null
null
Programming Fundamentals/10 Regex-Lab/4.Match Dates/src/com/softuni/techmodule/Main.java
VelinDimitrov/TechModule-SoftUni-Java
b82fa9c62e69f61c84a97d8a4dc914ff9ec7a628
[ "MIT" ]
null
null
null
30.045455
94
0.596067
995,162
package com.softuni.techmodule; import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { public static void main(String[] args) { Scanner input =new Scanner(System.in); String datesText=input.nextLine(); String regex="\\b(?<day>\\d{2})([.\\/-])(?<month>[A-Z][a-z]{2})\\2(?<year>\\d{4})\\b"; Pattern pattern=Pattern.compile(regex); Matcher matcher=pattern.matcher(datesText); while (matcher.find()) { System.out.printf("Day: %s, Month: %s, Year: %s%n",matcher.group(1) ,matcher.group(3),matcher.group(4)); } } }
922f9380d4a11cac6521b74dad43e4e08d159813
177
java
Java
app/src/main/java/com/onewind/android/gson/LifeStyle.java
bin0166/OneWind
73e84642e002e86c4ceb27fe829097038c540fdc
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/onewind/android/gson/LifeStyle.java
bin0166/OneWind
73e84642e002e86c4ceb27fe829097038c540fdc
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/onewind/android/gson/LifeStyle.java
bin0166/OneWind
73e84642e002e86c4ceb27fe829097038c540fdc
[ "Apache-2.0" ]
null
null
null
11.0625
33
0.649718
995,163
package com.onewind.android.gson; /** * Created by bin on 2017/11/5. */ public class LifeStyle { public String brf; public String txt; public String type; }
922f93a58d7ee252059490092f94c86580ebe42e
8,694
java
Java
src/test/java/seedu/address/logic/commands/CreateGroupCommandTest.java
clara1234566/main
990d5834d06fb2064255c88d558f31eec9007451
[ "MIT" ]
1
2019-02-12T05:20:34.000Z
2019-02-12T05:20:34.000Z
src/test/java/seedu/address/logic/commands/CreateGroupCommandTest.java
Tsuweiquan/main
dd676ea42f49690c56b30d3521bf5a4208fdcda5
[ "MIT" ]
null
null
null
src/test/java/seedu/address/logic/commands/CreateGroupCommandTest.java
Tsuweiquan/main
dd676ea42f49690c56b30d3521bf5a4208fdcda5
[ "MIT" ]
null
null
null
33.438462
114
0.666322
995,164
package seedu.address.logic.commands; import static java.util.Objects.requireNonNull; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.Arrays; import java.util.function.Predicate; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import javafx.collections.ObservableList; import seedu.address.logic.CommandHistory; import seedu.address.logic.commands.exceptions.CommandException; import seedu.address.model.AddressBook; import seedu.address.model.Model; import seedu.address.model.ReadOnlyAddressBook; import seedu.address.model.distribute.Distribute; import seedu.address.model.group.AddGroup; import seedu.address.model.group.Group; import seedu.address.model.person.Person; import seedu.address.testutil.GroupBuilder; /** * Contains integration tests (interaction with the Model stub) and unit tests for CreateGroupCommand. */ public class CreateGroupCommandTest { private static final CommandHistory EMPTY_COMMAND_HISTORY = new CommandHistory(); @Rule public ExpectedException thrown = ExpectedException.none(); private CommandHistory commandHistory = new CommandHistory(); @Test public void constructor_nullGroup_throwsNullPointerException() { thrown.expect(NullPointerException.class); new CreateGroupCommand(null); } @Test public void execute_groupAcceptedByModel_addSuccessful() throws Exception { CreateGroupCommandTest.ModelStubAcceptingGroupCreated modelStub = new CreateGroupCommandTest.ModelStubAcceptingGroupCreated(); Group validGroup = new GroupBuilder().build(); CommandResult commandResult = new CreateGroupCommand(validGroup).execute(modelStub, commandHistory); assertEquals(String.format(CreateGroupCommand.MESSAGE_SUCCESS, validGroup), commandResult.feedbackToUser); assertEquals(Arrays.asList(validGroup), modelStub.groupsCreated); assertEquals(EMPTY_COMMAND_HISTORY, commandHistory); } @Test public void execute_duplicateGroup_throwsCommandException() throws Exception { Group validGroup = new GroupBuilder().build(); CreateGroupCommand createGroupCommand = new CreateGroupCommand(validGroup); CreateGroupCommandTest.ModelStub modelStub = new CreateGroupCommandTest.ModelStubWithGroup(validGroup); thrown.expect(CommandException.class); thrown.expectMessage(CreateGroupCommand.MESSAGE_DUPLICATE_GROUP); createGroupCommand.execute(modelStub, commandHistory); } @Test public void equals() { Group tut1 = new GroupBuilder().withGroupName("TUT[1]").build(); Group tut2 = new GroupBuilder().withGroupName("TUT[2]").build(); CreateGroupCommand createTut1Command = new CreateGroupCommand(tut1); CreateGroupCommand createTut2Command = new CreateGroupCommand(tut2); // same object -> returns true assertTrue(createTut1Command.equals(createTut1Command)); // same values -> returns true CreateGroupCommand createTut1CommandCopy = new CreateGroupCommand(tut1); assertTrue(createTut1Command.equals(createTut1CommandCopy)); // different types -> returns false assertFalse(createTut1Command.equals(1)); // null -> returns false assertFalse(createTut1Command.equals(null)); // different person -> returns false assertFalse(createTut1Command.equals(createTut2Command)); } /** * A default model stub that have all of the methods failing. */ private class ModelStub implements Model { @Override public void addPerson(Person person) { throw new AssertionError("This method should not be called."); } @Override public void resetData(ReadOnlyAddressBook newData) { throw new AssertionError("This method should not be called."); } @Override public ReadOnlyAddressBook getAddressBook() { throw new AssertionError("This method should not be called."); } @Override public boolean hasPerson(Person person) { throw new AssertionError("This method should not be called."); } @Override public void deletePerson(Person target) { throw new AssertionError("This method should not be called."); } @Override public void updatePerson(Person target, Person editedPerson) { throw new AssertionError("This method should not be called."); } @Override public ObservableList<Person> getFilteredPersonList() { throw new AssertionError("This method should not be called."); } @Override public ObservableList<Group> getFilteredGroupList() { throw new AssertionError("This method should not be called."); } @Override public void updateFilteredPersonList(Predicate<Person> predicate) { throw new AssertionError("This method should not be called."); } @Override public void updateFilteredGroupList(Predicate<Group> predicate) { throw new AssertionError("This method should not be called."); } @Override public boolean canUndoAddressBook() { throw new AssertionError("This method should not be called."); } @Override public boolean canRedoAddressBook() { throw new AssertionError("This method should not be called."); } @Override public void undoAddressBook() { throw new AssertionError("This method should not be called."); } @Override public void redoAddressBook() { throw new AssertionError("This method should not be called."); } @Override public void commitAddressBook() { throw new AssertionError("This method should not be called."); } @Override public void createGroup(Group createGroup) { throw new AssertionError("This method should not be called."); } @Override public boolean hasGroup(Group checkGroup) { throw new AssertionError("This method should not be called."); } @Override public void addGroup(AddGroup addGroup) { throw new AssertionError("This method should not be called."); } @Override public boolean hasPersonInGroup(AddGroup addGroup) { throw new AssertionError("This method should not be called."); } @Override public void deleteGroup(Group target) { throw new AssertionError("This method should not be called."); } @Override public void deleteGroupPerson(Group group, Person target) { throw new AssertionError("This method should not be called."); } @Override public String getScriptFolderLocation() { throw new AssertionError("This method should not be called."); } @Override public void executeDistributeAlgorithm(Model mode, Distribute distribute) { throw new AssertionError("This method should not be called."); } } /** * A Model stub that contains a single group. */ private class ModelStubWithGroup extends CreateGroupCommandTest.ModelStub { private final Group group; ModelStubWithGroup(Group group) { requireNonNull(group); this.group = group; } @Override public boolean hasGroup(Group group) { requireNonNull(group); return this.group.isSameGroup(group); } } /** * A Model stub that always accepts the group being added. */ private class ModelStubAcceptingGroupCreated extends CreateGroupCommandTest.ModelStub { final ArrayList<Group> groupsCreated = new ArrayList<>(); @Override public boolean hasGroup(Group group) { requireNonNull(group); return groupsCreated.stream().anyMatch(group::isSameGroup); } @Override public void createGroup(Group group) { requireNonNull(group); groupsCreated.add(group); } @Override public void commitAddressBook() { // called by {@code CreateGroupCommand#execute()} } @Override public ReadOnlyAddressBook getAddressBook() { return new AddressBook(); } } }
922f93d480fba96ce7ee330b86321d0913485776
1,970
java
Java
src/main/java/me/libraryaddict/Hungergames/Commands/ChunkCommand.java
xMarkSt/LibsHungergames
ef414177490b312e15b7d85743ed79d90f9c19db
[ "Unlicense" ]
2
2021-06-10T12:08:11.000Z
2021-12-01T16:06:50.000Z
src/main/java/me/libraryaddict/Hungergames/Commands/ChunkCommand.java
xMarkSt/LibsHungergames
ef414177490b312e15b7d85743ed79d90f9c19db
[ "Unlicense" ]
null
null
null
src/main/java/me/libraryaddict/Hungergames/Commands/ChunkCommand.java
xMarkSt/LibsHungergames
ef414177490b312e15b7d85743ed79d90f9c19db
[ "Unlicense" ]
2
2021-06-10T11:45:02.000Z
2021-08-21T22:36:24.000Z
49.25
102
0.664467
995,165
package me.libraryaddict.Hungergames.Commands; import me.libraryaddict.Hungergames.Configs.TranslationConfig; import me.libraryaddict.Hungergames.Managers.PlayerManager; import me.libraryaddict.Hungergames.Types.HungergamesApi; import me.libraryaddict.Hungergames.Types.Gamer; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class ChunkCommand implements CommandExecutor { public String[] aliases = new String[] { "stuck", "refresh" }; private TranslationConfig cm = HungergamesApi.getConfigManager().getTranslationsConfig(); public String description = "This command refreshes the chunk of the command user"; private PlayerManager pm = HungergamesApi.getPlayerManager(); public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { Gamer gamer = pm.getGamer(sender.getName()); if (gamer.getChunkCooldown() < System.currentTimeMillis() / 1000L) { Player p = gamer.getPlayer(); gamer.setChunkCooldown((System.currentTimeMillis() / 1000) + 10); System.out.println(String.format(cm.getCommandChunkLoggerReloadingChunks(), p.getName())); org.bukkit.Chunk chunk = p.getWorld().getChunkAt(p.getLocation()); for (int i = -16; i <= 16; i = i + 16) { for (int a = -16; a <= 16; a = a + 16) { chunk = p.getWorld().getChunkAt((p.getLocation().getBlockX() + i) >> 4, (p.getLocation().getBlockZ() + a) >> 4); HungergamesApi.getReflectionManager().sendChunk(p, chunk.getX(), chunk.getZ()); } } p.teleport(p.getLocation().add(0, 0.5, 0)); sender.sendMessage(cm.getCommandChunkReloadedChunks()); } else sender.sendMessage(cm.getCommandChunkCooldown()); return true; } }
922f94e7e09f3c197e79f9e9b6600dc4a53de55d
4,490
java
Java
implementations/java/OWAT-lib/src/main/java/com/ebp/owat/lib/utils/scramble/MoveValidator.java
KaushikIyer16/OWAT
12327914f1e1ebba10624da6dfcf37b97587dff7
[ "Apache-2.0" ]
11
2018-01-04T17:41:49.000Z
2021-03-15T17:25:50.000Z
implementations/java/OWAT-lib/src/main/java/com/ebp/owat/lib/utils/scramble/MoveValidator.java
KaushikIyer16/OWAT
12327914f1e1ebba10624da6dfcf37b97587dff7
[ "Apache-2.0" ]
5
2018-03-31T23:02:06.000Z
2019-10-26T22:51:10.000Z
implementations/java/OWAT-lib/src/main/java/com/ebp/owat/lib/utils/scramble/MoveValidator.java
KaushikIyer16/OWAT
12327914f1e1ebba10624da6dfcf37b97587dff7
[ "Apache-2.0" ]
9
2018-03-31T22:54:09.000Z
2020-06-18T22:16:01.000Z
45.816327
179
0.749666
995,166
package com.ebp.owat.lib.utils.scramble; import com.ebp.owat.lib.datastructure.matrix.Matrix; import com.ebp.owat.lib.datastructure.matrix.utils.MatrixValidator; import com.ebp.owat.lib.datastructure.matrix.utils.Plane; public class MoveValidator { /** The minimum size of a matrix for scrambling. */ public static final long MIN_SIZE_FOR_SCRAMBLING = 4; /** The minimum size of a matrix to be rotated. */ public static final long MIN_SIZE_FOR_ROTATION = 2; /** * Determines if the matrix given is too small for scrambling. * @param matrix The matrix to use. * @return If the matrix given is too small for scrambling. */ public static boolean matrixIsTooSmallForScrambling(Matrix matrix) { return matrix.getNumCols() < MIN_SIZE_FOR_SCRAMBLING || matrix.getNumRows() < MIN_SIZE_FOR_SCRAMBLING; } /** * Throws an exception if the matrix is too small for scrambling. * @param matrix The matrix to use. * @throws IllegalStateException If the matrix is too small for scrambling. */ public static void throwIfMatrixTooSmallForScrambling(Matrix matrix) { if (matrixIsTooSmallForScrambling(matrix)) { throw new IllegalStateException("Matrix too small for scrambling."); } } /** * Throws an exception of the move given is invalid. * @param matrix The matrix to use. * @param move The move to test. */ public static void throwIfInvalidMove(Matrix matrix, ScrambleMove move) { switch (move.move) { case SWAP: MatrixValidator.throwIfBadIndex(matrix, move.getArg(ScrambleConstants.Swap.X1), Plane.X); MatrixValidator.throwIfBadIndex(matrix, move.getArg(ScrambleConstants.Swap.Y1), Plane.Y); MatrixValidator.throwIfBadIndex(matrix, move.getArg(ScrambleConstants.Swap.X2), Plane.X); MatrixValidator.throwIfBadIndex(matrix, move.getArg(ScrambleConstants.Swap.Y2), Plane.Y); if ( move.getArg(ScrambleConstants.Swap.X1) == move.getArg(ScrambleConstants.Swap.X2) && move.getArg(ScrambleConstants.Swap.Y1) == move.getArg(ScrambleConstants.Swap.Y2) ) { throw new IllegalArgumentException("Can't swap a node's value with itself."); } break; case SWAP_ROW: MatrixValidator.throwIfBadIndex(matrix, move.getArg(ScrambleConstants.SwapRow.ROWCOL1), Plane.Y); MatrixValidator.throwIfBadIndex(matrix, move.getArg(ScrambleConstants.SwapRow.ROWCOL2), Plane.Y); break; case SWAP_COL: MatrixValidator.throwIfBadIndex(matrix, move.getArg(ScrambleConstants.SwapCol.ROWCOL1), Plane.X); MatrixValidator.throwIfBadIndex(matrix, move.getArg(ScrambleConstants.SwapCol.ROWCOL2), Plane.X); break; case SLIDE_ROW: MatrixValidator.throwIfBadIndex(matrix, move.getArg(ScrambleConstants.SlideRow.ROWCOL), Plane.Y); break; case SLIDE_COL: MatrixValidator.throwIfBadIndex(matrix, move.getArg(ScrambleConstants.SlideCol.ROWCOL), Plane.X); break; case ROT_BOX: if (!(move.getArg(ScrambleConstants.RotateBox.ROTNUM) >= -3 && move.getArg(ScrambleConstants.RotateBox.ROTNUM) <= 3 && move.getArg(ScrambleConstants.RotateBox.ROTNUM) != 0)) { throw new IllegalArgumentException("Invalid number of rotations given. Given: " + move.getArg(ScrambleConstants.RotateBox.ROTNUM)); } MatrixValidator.throwIfBadIndex(matrix, move.getArg(ScrambleConstants.RotateBox.X), Plane.X); MatrixValidator.throwIfBadIndex(matrix, move.getArg(ScrambleConstants.RotateBox.Y), Plane.Y); MatrixValidator.throwIfBadIndex(matrix, move.getArg(ScrambleConstants.RotateBox.SIZE) + move.getArg(ScrambleConstants.RotateBox.X) - 1, Plane.X); MatrixValidator.throwIfBadIndex(matrix, move.getArg(ScrambleConstants.RotateBox.SIZE) + move.getArg(ScrambleConstants.RotateBox.Y) - 1, Plane.Y); if (move.getArg(ScrambleConstants.RotateBox.SIZE) < MIN_SIZE_FOR_ROTATION) { throw new IllegalArgumentException("Invalid size of sub matrix."); } break; default: throw new IllegalArgumentException("Unsupported move passed to validator."); } } /** * Throws an exception if the move given is invalid, expecting it to be a certain type. * @param matrix The matrix to use. * @param move The move to test * @param moveToBe The move to expect it to be. */ public static void throwIfInvalidMove(Matrix matrix, ScrambleMove move, ScrambleMoves moveToBe) { if(move.move != moveToBe){ throw new IllegalArgumentException("Move given was not what was expected. Expected: " + moveToBe + ", Got: " + move.move); } throwIfInvalidMove(matrix, move); } }
922f95142c2580b46653be9f8823aa2be55169cb
1,914
java
Java
spring-boot-playground-demo/src/main/java/it/sebastianosuraci/springboot/demo/repository/StudentRepository.java
ssuraci/spring-boot-playground
7027ec0642f483d3ddf41cdb65b766f0787c7e14
[ "MIT" ]
4
2021-07-09T05:31:50.000Z
2022-01-22T20:24:36.000Z
spring-boot-playground-demo/src/main/java/it/sebastianosuraci/springboot/demo/repository/StudentRepository.java
ssuraci/spring-boot-playground
7027ec0642f483d3ddf41cdb65b766f0787c7e14
[ "MIT" ]
3
2021-11-13T16:56:53.000Z
2021-12-05T18:31:57.000Z
spring-boot-playground-demo/src/main/java/it/sebastianosuraci/springboot/demo/repository/StudentRepository.java
ssuraci/spring-boot-playground
7027ec0642f483d3ddf41cdb65b766f0787c7e14
[ "MIT" ]
1
2021-10-04T15:18:50.000Z
2021-10-04T15:18:50.000Z
31.9
101
0.643678
995,167
package it.sebastianosuraci.springboot.demo.repository; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import com.querydsl.core.BooleanBuilder; import it.sebastianosuraci.springboot.core.domain.QBaseEntity; import it.sebastianosuraci.springboot.core.dto.PageModel; import it.sebastianosuraci.springboot.core.repository.BaseRepository; import it.sebastianosuraci.springboot.demo.domain.QStudent; import it.sebastianosuraci.springboot.demo.domain.Student; public interface StudentRepository extends BaseRepository<Student, Integer> { // QueryDSL default List<Student> qdslFindByLastName(String lastName) { QStudent student = QStudent.student; List<Student> result = new ArrayList<>(); findAll(student.lastName.like(lastName)).forEach(result::add); return result; } @Override default List<String> getAllowedOrderByList() { String[] s = { "id", "lastName", "birthDate" }; return Arrays.asList(s); } @Override default BooleanBuilder addPageModelFilterPredicate(BooleanBuilder builder, PageModel pageModel) { QStudent student = QStudent.student; if (pageModel != null && pageModel.getF() != null) { for (Map.Entry<String, String> entry : pageModel.getF().entrySet()) { switch (entry.getKey()) { case "q": case "lastNameLike": builder.and(student.lastName.likeIgnoreCase(entry.getValue() + '%')); break; case "schoolEq": builder.and(student.school.id.eq(Integer.parseInt(entry.getValue()))); break; default: break; } } } return builder; } default QBaseEntity getQBaseEntity() { return QStudent.student._super._super; } }
922f9582db79f964fd71f9f2171fd76541d340cc
470
java
Java
etiyaCamp/reCapProject/reCapProject/src/main/java/com/etiya/reCapProject/entities/requests/additionalRequest/AddAdditionalServiceRequest.java
ibrahimdoss/JavaApps
92089736396e66414cb13c4512e690351b98d426
[ "MIT" ]
null
null
null
etiyaCamp/reCapProject/reCapProject/src/main/java/com/etiya/reCapProject/entities/requests/additionalRequest/AddAdditionalServiceRequest.java
ibrahimdoss/JavaApps
92089736396e66414cb13c4512e690351b98d426
[ "MIT" ]
null
null
null
etiyaCamp/reCapProject/reCapProject/src/main/java/com/etiya/reCapProject/entities/requests/additionalRequest/AddAdditionalServiceRequest.java
ibrahimdoss/JavaApps
92089736396e66414cb13c4512e690351b98d426
[ "MIT" ]
null
null
null
21.363636
67
0.821277
995,168
package com.etiya.reCapProject.entities.requests.additionalRequest; import javax.validation.constraints.NotNull; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @Getter @Setter @AllArgsConstructor @NoArgsConstructor public class AddAdditionalServiceRequest { @NotNull(message = "Boş Geçilemez!") private String additionalName; @NotNull(message = "Boş Geçilemez!") private double additionalPrice; }
922f959165dd4dc3f590a120e43d34af72fef50a
6,347
java
Java
src/main/java/cn/stylefeng/guns/core/util/HttpUtils.java
chenyqgithub/choujiangadmin
7c5a51c433aa5d9f7f1bcda99802400f9dd75640
[ "Apache-2.0" ]
null
null
null
src/main/java/cn/stylefeng/guns/core/util/HttpUtils.java
chenyqgithub/choujiangadmin
7c5a51c433aa5d9f7f1bcda99802400f9dd75640
[ "Apache-2.0" ]
null
null
null
src/main/java/cn/stylefeng/guns/core/util/HttpUtils.java
chenyqgithub/choujiangadmin
7c5a51c433aa5d9f7f1bcda99802400f9dd75640
[ "Apache-2.0" ]
null
null
null
34.68306
97
0.478966
995,169
package cn.stylefeng.guns.core.util; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 用于模拟HTTP请求中GET/POST方式 * @author landa * */ public class HttpUtils { /** * 发送GET请求 * * @param url * 目的地址 * @param parameters * 请求参数,Map类型。 * @return 远程响应结果 */ public static String sendGet(String url, Map<String, String> parameters) { String result=""; BufferedReader in = null;// 读取响应输入流 StringBuffer sb = new StringBuffer();// 存储参数 String params = "";// 编码之后的参数 try { // 编码请求参数 if(parameters.size()==1){ for(String name:parameters.keySet()){ sb.append(name).append("=").append( java.net.URLEncoder.encode(parameters.get(name), "UTF-8")); } params=sb.toString(); }else if (parameters.size() > 1){ for (String name : parameters.keySet()) { sb.append(name).append("=").append( java.net.URLEncoder.encode(parameters.get(name), "UTF-8")).append("&"); } String temp_params = sb.toString(); params = temp_params.substring(0, temp_params.length() - 1); } String full_url = url + "?" + params; System.out.println(full_url); // 创建URL对象 java.net.URL connURL = new java.net.URL(full_url); // 打开URL连接 java.net.HttpURLConnection httpConn = (java.net.HttpURLConnection) connURL .openConnection(); // 设置通用属性 httpConn.setRequestProperty("Accept", "*/*"); httpConn.setRequestProperty("Connection", "Keep-Alive"); httpConn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)"); // 建立实际的连接 httpConn.connect(); // 响应头部获取 Map<String, List<String>> headers = httpConn.getHeaderFields(); // 遍历所有的响应头字段 for (String key : headers.keySet()) { System.out.println(key + "\t:\t" + headers.get(key)); } // 定义BufferedReader输入流来读取URL的响应,并设置编码方式 in = new BufferedReader(new InputStreamReader(httpConn .getInputStream(), "UTF-8")); String line; // 读取返回的内容 while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { e.printStackTrace(); }finally{ try { if (in != null) { in.close(); } } catch (IOException ex) { ex.printStackTrace(); } } return result ; } /** * 发送POST请求 * * @param url * 目的地址 * @param parameters * 请求参数,Map类型。 * @return 远程响应结果 */ public static String sendPost(String url, Map<String, String> parameters) { String result = "";// 返回的结果 BufferedReader in = null;// 读取响应输入流 PrintWriter out = null; StringBuffer sb = new StringBuffer();// 处理请求参数 String params = "";// 编码之后的参数 try { // 编码请求参数 if (parameters.size() == 1) { for (String name : parameters.keySet()) { sb.append(name).append("=").append( java.net.URLEncoder.encode(parameters.get(name), "UTF-8")); } params = sb.toString(); } else if (parameters.size() > 1){ for (String name : parameters.keySet()) { sb.append(name).append("=").append( java.net.URLEncoder.encode(parameters.get(name), "UTF-8")).append("&"); } String temp_params = sb.toString(); params = temp_params.substring(0, temp_params.length() - 1); } // 创建URL对象 java.net.URL connURL = new java.net.URL(url); // 打开URL连接 java.net.HttpURLConnection httpConn = (java.net.HttpURLConnection) connURL .openConnection(); // 设置通用属性 httpConn.setRequestProperty("Accept", "*/*"); httpConn.setRequestProperty("Connection", "Keep-Alive"); httpConn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)"); // 设置POST方式 httpConn.setDoInput(true); httpConn.setDoOutput(true); // 获取HttpURLConnection对象对应的输出流 out = new PrintWriter(httpConn.getOutputStream()); // 发送请求参数 out.write(params); // flush输出流的缓冲 out.flush(); // 定义BufferedReader输入流来读取URL的响应,设置编码方式 in = new BufferedReader(new InputStreamReader(httpConn .getInputStream(), "UTF-8")); String line; // 读取返回的内容 while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { e.printStackTrace(); } finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (IOException ex) { ex.printStackTrace(); } } return result; } /** * 主函数,测试请求 * * @param args */ public static void main(String[] args) { Map<String, String> parameters = new HashMap<String, String>(); String result =sendPost("https://hybc.ikeek.cn:8443/api/code/getResultInfo", parameters); System.out.println(result); String s = HttpUtils.sendPost("http://127.0.0.1:8080/api/getabcd", new HashMap<>()); System.out.println("---------"+s); } }
922f9744432440e466cb72873b9241621c527758
5,102
java
Java
src/org/probe/rls/test/algo/TestEnsembleBayesianRuleLearning.java
jeyabbalas/Bayesian-Rule-Learning
8ae126319c3bc54f3dcf2030f673fd88fadfd409
[ "MIT" ]
1
2022-02-04T19:38:00.000Z
2022-02-04T19:38:00.000Z
src/org/probe/rls/test/algo/TestEnsembleBayesianRuleLearning.java
jeyabbalas/Bayesian-Rule-Learning
8ae126319c3bc54f3dcf2030f673fd88fadfd409
[ "MIT" ]
null
null
null
src/org/probe/rls/test/algo/TestEnsembleBayesianRuleLearning.java
jeyabbalas/Bayesian-Rule-Learning
8ae126319c3bc54f3dcf2030f673fd88fadfd409
[ "MIT" ]
null
null
null
39.550388
111
0.78675
995,170
package org.probe.rls.test.algo; import org.junit.Test; import org.probe.rls.algo.evaluator.Evaluator; import org.probe.rls.algo.rule.BRLRuleLearner; import org.probe.rls.algo.rule.brl.BRLSearchParameters; import org.probe.rls.algo.rule.brl.parameters.BRLSearchType; import org.probe.rls.algo.rule.brl.parameters.CPTRepresentationType; import org.probe.rls.algo.rule.brl.parameters.EnsembleAggregationType; import org.probe.rls.data.DataModel; import org.probe.rls.data.FileDataManager; import org.probe.rls.data.FileType; import org.probe.rls.models.rulemodel.ensemble.EnsembleRuleModel; public class TestEnsembleBayesianRuleLearning { @Test public void testBrlLc() throws Exception{ // Running Bagged-BRL-LC // Input the training dataset FileDataManager dataManager = new FileDataManager(); dataManager.loadFromFile("Test//id3dataset.csv", FileType.CSV.getSeparator()); // Get data DataModel dataModel = dataManager.getDataModel(); // Get EBRL classifier and set learner parameters for Bagged-BRL-LC BRLSearchParameters params = new BRLSearchParameters(); params.setCptRepresentation(CPTRepresentationType.Local_CB); // Learn local decision trees params.setSearchAlgorithm(BRLSearchType.GreedyBestFirstWithComplexityPenalty); // Greedy best-first search params.setUseComplexityPenaltyPrior(true); // use kappa structure prior params.setKappa(0.01); // kappa value params.setSearchAlgorithm(BRLSearchType.Bagging); // Base models generation method params.setAggregationType(EnsembleAggregationType.DefaultLinearCombination); //LC aggregation method params.setNumBaseModels(10); // number of base models // Learn EBRL model BRLRuleLearner ruleLearner = new BRLRuleLearner(params, dataModel); ruleLearner.runAlgo(); EnsembleRuleModel eRM = ruleLearner.getEnsembleRuleModel(); // Evaluate BRL model on training data itself Evaluator eval = new Evaluator(dataModel); eval.evaluateClassifierOnTest(eRM, dataModel); // Show learned model System.out.println(eRM.toString()); // Show performance metrics System.out.println(eval.toString()); } @Test public void testBrlBma() throws Exception{ // Running Bagged-BRL-BMA // Input the training dataset FileDataManager dataManager = new FileDataManager(); dataManager.loadFromFile("Test//id3dataset.csv", FileType.CSV.getSeparator()); // Get data DataModel dataModel = dataManager.getDataModel(); // Get EBRL classifier and set learner parameters for Bagged-BRL-LC BRLSearchParameters params = new BRLSearchParameters(); params.setCptRepresentation(CPTRepresentationType.Local_CB); // Learn local decision trees params.setSearchAlgorithm(BRLSearchType.GreedyBestFirstWithComplexityPenalty); // Greedy best-first search params.setUseComplexityPenaltyPrior(true); // use kappa structure prior params.setKappa(0.01); // kappa value params.setSearchAlgorithm(BRLSearchType.Bagging); // Base models generation method params.setAggregationType(EnsembleAggregationType.SelectiveBayesianModelAveraging); //BMA aggregation method params.setNumBaseModels(10); // number of base models // Learn EBRL model BRLRuleLearner ruleLearner = new BRLRuleLearner(params, dataModel); ruleLearner.runAlgo(); EnsembleRuleModel eRM = ruleLearner.getEnsembleRuleModel(); // Evaluate BRL model on training data itself Evaluator eval = new Evaluator(dataModel); eval.evaluateClassifierOnTest(eRM, dataModel); // Show learned model System.out.println(eRM.toString()); // Show performance metrics System.out.println(eval.toString()); } @Test public void testBrlBmc() throws Exception{ // Running Bagged-BRL-BMC // Input the training dataset FileDataManager dataManager = new FileDataManager(); dataManager.loadFromFile("Test//id3dataset.csv", FileType.CSV.getSeparator()); // Get data DataModel dataModel = dataManager.getDataModel(); // Get EBRL classifier and set learner parameters for Bagged-BRL-LC BRLSearchParameters params = new BRLSearchParameters(); params.setCptRepresentation(CPTRepresentationType.Local_CB); // Learn local decision trees params.setSearchAlgorithm(BRLSearchType.GreedyBestFirstWithComplexityPenalty); // Greedy best-first search params.setUseComplexityPenaltyPrior(true); // use kappa structure prior params.setKappa(0.01); // kappa value params.setSearchAlgorithm(BRLSearchType.Bagging); // Base models generation method params.setAggregationType(EnsembleAggregationType.SelectiveBayesianModelCombination); //LC aggregation method params.setNumEnsembles(100); // Number of ensembles params.setNumBaseModels(10); // number of base models // Learn EBRL model BRLRuleLearner ruleLearner = new BRLRuleLearner(params, dataModel); ruleLearner.runAlgo(); EnsembleRuleModel eRM = ruleLearner.getEnsembleRuleModel(); // Evaluate BRL model on training data itself Evaluator eval = new Evaluator(dataModel); eval.evaluateClassifierOnTest(eRM, dataModel); // Show learned model System.out.println(eRM.toString()); // Show performance metrics System.out.println(eval.toString()); } }
922f97c9950ebd4ee530b62fcf89faf1324a8d03
150
java
Java
modules/flyweight/src/main/java/nju/kunduin/flyweight/Flyweight.java
Kunduin/aspectj-design-pattern
7f6310233cefd17b566e2965d6b42a7461e6ecbc
[ "MIT" ]
null
null
null
modules/flyweight/src/main/java/nju/kunduin/flyweight/Flyweight.java
Kunduin/aspectj-design-pattern
7f6310233cefd17b566e2965d6b42a7461e6ecbc
[ "MIT" ]
null
null
null
modules/flyweight/src/main/java/nju/kunduin/flyweight/Flyweight.java
Kunduin/aspectj-design-pattern
7f6310233cefd17b566e2965d6b42a7461e6ecbc
[ "MIT" ]
1
2021-12-27T23:34:55.000Z
2021-12-27T23:34:55.000Z
21.428571
63
0.773333
995,171
package nju.kunduin.flyweight; /** @author kunduin */ public interface Flyweight { public void operation(UnsharedFlyweight unsharedFlyweight); }
922f97e25d59a3d7d1fb2d9f39c741d3851bd860
1,353
java
Java
proFL-plugin-2.0.3/org/pitest/reloc/antlr/common/collections/impl/IndexedVector.java
ycj123/Research-Project
08296e0075ba0c13204944b1bc1a96a7b8d2f023
[ "MIT" ]
null
null
null
proFL-plugin-2.0.3/org/pitest/reloc/antlr/common/collections/impl/IndexedVector.java
ycj123/Research-Project
08296e0075ba0c13204944b1bc1a96a7b8d2f023
[ "MIT" ]
null
null
null
proFL-plugin-2.0.3/org/pitest/reloc/antlr/common/collections/impl/IndexedVector.java
ycj123/Research-Project
08296e0075ba0c13204944b1bc1a96a7b8d2f023
[ "MIT" ]
null
null
null
24.160714
82
0.622321
995,172
// // Decompiled by Procyon v0.5.36 // package org.pitest.reloc.antlr.common.collections.impl; import java.util.Enumeration; import java.util.Hashtable; public class IndexedVector { protected Vector elements; protected Hashtable index; public IndexedVector() { this.elements = new Vector(10); this.index = new Hashtable(10); } public IndexedVector(final int initialCapacity) { this.elements = new Vector(initialCapacity); this.index = new Hashtable(initialCapacity); } public synchronized void appendElement(final Object key, final Object value) { this.elements.appendElement(value); this.index.put(key, value); } public Object elementAt(final int n) { return this.elements.elementAt(n); } public Enumeration elements() { return this.elements.elements(); } public Object getElement(final Object key) { return this.index.get(key); } public synchronized boolean removeElement(final Object o) { final Object value = this.index.get(o); if (value == null) { return false; } this.index.remove(o); this.elements.removeElement(value); return false; } public int size() { return this.elements.size(); } }
922f9911041cb720143ae87d0fe6bf12e4063860
2,562
java
Java
src/main/java/net/covers1624/tconsole/log4j/TailConsoleAppender.java
covers1624/TailConsole
5ca78fa3a044c1017dcaef01ef934f80f59fed8e
[ "MIT" ]
null
null
null
src/main/java/net/covers1624/tconsole/log4j/TailConsoleAppender.java
covers1624/TailConsole
5ca78fa3a044c1017dcaef01ef934f80f59fed8e
[ "MIT" ]
null
null
null
src/main/java/net/covers1624/tconsole/log4j/TailConsoleAppender.java
covers1624/TailConsole
5ca78fa3a044c1017dcaef01ef934f80f59fed8e
[ "MIT" ]
null
null
null
38.238806
128
0.711553
995,174
/* * This file is part of TailConsole and is Licensed under the MIT License. * * Copyright (c) 2018-2021 covers1624 <https://github.com/covers1624> */ package net.covers1624.tconsole.log4j; import net.covers1624.tconsole.api.TailConsole; import org.apache.logging.log4j.core.*; import org.apache.logging.log4j.core.appender.AbstractAppender; import org.apache.logging.log4j.core.config.plugins.Plugin; import org.apache.logging.log4j.core.config.plugins.PluginAttribute; import org.apache.logging.log4j.core.config.plugins.PluginElement; import org.apache.logging.log4j.core.config.plugins.PluginFactory; import org.apache.logging.log4j.core.config.plugins.validation.constraints.Required; import org.apache.logging.log4j.core.layout.PatternLayout; import java.io.PrintStream; import java.io.Serializable; /** * Created by covers1624 on 9/8/19. */ @Plugin (name = "TailConsoleAppender", category = Core.CATEGORY_NAME, elementType = Appender.ELEMENT_TYPE, printObject = true) public class TailConsoleAppender extends AbstractAppender { private static final PrintStream sysOut = System.out; private static boolean initialized; private static TailConsole tailConsole; protected TailConsoleAppender(String name, Filter filter, Layout<? extends Serializable> layout, boolean ignoreExceptions) { super(name, filter, layout, ignoreExceptions); if (!initialized) { initialized = true; tailConsole = TailConsole.create(); } } public static TailConsole getTailConsole() { return tailConsole; } @Override public void append(LogEvent event) { String str = getLayout().toSerializable(event).toString(); if (tailConsole != null && !tailConsole.isShutdown() && tailConsole.isSupported(TailConsole.Output.STDOUT)) { tailConsole.scheduleStdout(str); } else { sysOut.print(str); } } @PluginFactory public static TailConsoleAppender createAppender( @Required (message = "No name provided for AnsiTailConsoleAppender") @PluginAttribute ("name") String name, @PluginElement ("Filter") Filter filter, @PluginElement ("Layout") Layout<? extends Serializable> layout, @PluginAttribute (value = "ignoreExceptions", defaultBoolean = true) boolean ignoreExceptions) { if (layout == null) { layout = PatternLayout.createDefaultLayout(); } return new TailConsoleAppender(name, filter, layout, ignoreExceptions); } }
922f9933e78faefc4194b18062682bb1b2079fae
13,910
java
Java
src/test/java/org/broadinstitute/hellbender/tools/exome/plotting/PlotACNVResultsIntegrationTest.java
YTLogos/gatk
9dab6d2e95e25d19c35243bd04a71551d97b8316
[ "BSD-3-Clause" ]
null
null
null
src/test/java/org/broadinstitute/hellbender/tools/exome/plotting/PlotACNVResultsIntegrationTest.java
YTLogos/gatk
9dab6d2e95e25d19c35243bd04a71551d97b8316
[ "BSD-3-Clause" ]
null
null
null
src/test/java/org/broadinstitute/hellbender/tools/exome/plotting/PlotACNVResultsIntegrationTest.java
YTLogos/gatk
9dab6d2e95e25d19c35243bd04a71551d97b8316
[ "BSD-3-Clause" ]
1
2019-07-02T09:49:11.000Z
2019-07-02T09:49:11.000Z
67.853659
185
0.73307
995,175
package org.broadinstitute.hellbender.tools.exome.plotting; import org.broadinstitute.hellbender.CommandLineProgramTest; import org.broadinstitute.hellbender.cmdline.ExomeStandardArgumentDefinitions; import org.broadinstitute.hellbender.cmdline.StandardArgumentDefinitions; import org.broadinstitute.hellbender.exceptions.UserException; import org.testng.Assert; import org.testng.annotations.Test; import java.io.File; import java.io.IOException; public class PlotACNVResultsIntegrationTest extends CommandLineProgramTest { private static final String TEST_SUB_DIR = publicTestDir + "org/broadinstitute/hellbender/tools/exome/"; //test files private static final File SNP_COUNTS_FILE = new File(TEST_SUB_DIR, "snps-for-plotting.tsv"); private static final File TANGENT_NORMALIZED_COUNTS_FILE = new File(TEST_SUB_DIR, "coverages-for-plotting.tsv"); private static final File SEGMENTS_FILE = new File(TEST_SUB_DIR, "acnv-segments-for-plotting.seg"); private static final File SEQUENCE_DICTIONARY_FILE = new File(TEST_SUB_DIR, "sequence-dictionary-for-plotting.dict"); //test files for invalid configurations private static final File SEQUENCE_DICTIONARY_NO_CONTIGS_ABOVE_MINIMUM_LENGTH_FILE = new File(TEST_SUB_DIR, "sequence-dictionary-for-plotting-no-contigs-above-minimum-length.dict"); private static final File COUNTS_BAD_SAMPLE_NAME_FILE = new File(TEST_SUB_DIR, "coverages-for-plotting-bad-sample-name.tsv"); private static final File SEGMENTS_BAD_SAMPLE_NAME_FILE = new File(TEST_SUB_DIR, "acnv-segments-for-plotting-bad-sample-name.seg"); private static final File SNP_COUNTS_DATA_OUT_OF_BOUNDS_FILE = new File(TEST_SUB_DIR, "snps-for-plotting-data-out-of-bounds.tsv"); private static final File COUNTS_DATA_OUT_OF_BOUNDS_FILE = new File(TEST_SUB_DIR, "coverages-for-plotting-data-out-of-bounds.tsv"); private static final File SEGMENTS_DATA_OUT_OF_BOUNDS_FILE = new File(TEST_SUB_DIR, "acnv-segments-for-plotting-data-out-of-bounds.seg"); private static final String OUTPUT_PREFIX = "test"; private static final int THRESHOLD_PLOT_FILE_SIZE_IN_BYTES = 50000; //test that data points are plotted (not just background/axes) //checks that output files with reasonable file sizes are generated, but correctness of output is not checked @Test public void testACNVPlotting() { final File outputDir = createTempDir("testDir"); final String[] arguments = { "-" + ExomeStandardArgumentDefinitions.ALLELIC_COUNTS_FILE_SHORT_NAME, SNP_COUNTS_FILE.getAbsolutePath(), "-" + ExomeStandardArgumentDefinitions.TANGENT_NORMALIZED_COUNTS_FILE_SHORT_NAME, TANGENT_NORMALIZED_COUNTS_FILE.getAbsolutePath(), "-" + ExomeStandardArgumentDefinitions.SEGMENT_FILE_SHORT_NAME, SEGMENTS_FILE.getAbsolutePath(), "-" + StandardArgumentDefinitions.SEQUENCE_DICTIONARY_SHORT_NAME, SEQUENCE_DICTIONARY_FILE.getAbsolutePath(), "-" + StandardArgumentDefinitions.OUTPUT_SHORT_NAME, outputDir.getAbsolutePath(), "-" + PlotACNVResults.OUTPUT_PREFIX_LONG_NAME, OUTPUT_PREFIX, "--verbosity", "INFO" }; runCommandLine(arguments); Assert.assertTrue(new File(outputDir, OUTPUT_PREFIX + "_ACNV.png").exists()); Assert.assertTrue(new File(outputDir, OUTPUT_PREFIX + "_ACNV.png").length() > THRESHOLD_PLOT_FILE_SIZE_IN_BYTES); } @Test(expectedExceptions = IllegalArgumentException.class) public void testMinimumContigLength() { final File outputDir = createTempDir("testDir"); final String[] arguments = { "-" + ExomeStandardArgumentDefinitions.ALLELIC_COUNTS_FILE_SHORT_NAME, SNP_COUNTS_FILE.getAbsolutePath(), "-" + ExomeStandardArgumentDefinitions.TANGENT_NORMALIZED_COUNTS_FILE_SHORT_NAME, TANGENT_NORMALIZED_COUNTS_FILE.getAbsolutePath(), "-" + ExomeStandardArgumentDefinitions.SEGMENT_FILE_SHORT_NAME, SEGMENTS_FILE.getAbsolutePath(), "-" + StandardArgumentDefinitions.SEQUENCE_DICTIONARY_SHORT_NAME, SEQUENCE_DICTIONARY_NO_CONTIGS_ABOVE_MINIMUM_LENGTH_FILE.getAbsolutePath(), "-" + StandardArgumentDefinitions.OUTPUT_SHORT_NAME, outputDir.getAbsolutePath(), "-" + PlotACNVResults.OUTPUT_PREFIX_LONG_NAME, OUTPUT_PREFIX }; runCommandLine(arguments); } @Test(expectedExceptions = UserException.class) public void testOutputDirExists() throws IOException { final String[] arguments = { "-" + ExomeStandardArgumentDefinitions.ALLELIC_COUNTS_FILE_SHORT_NAME, SNP_COUNTS_FILE.getAbsolutePath(), "-" + ExomeStandardArgumentDefinitions.TANGENT_NORMALIZED_COUNTS_FILE_SHORT_NAME, TANGENT_NORMALIZED_COUNTS_FILE.getAbsolutePath(), "-" + ExomeStandardArgumentDefinitions.SEGMENT_FILE_SHORT_NAME, SEGMENTS_FILE.getAbsolutePath(), "-" + StandardArgumentDefinitions.SEQUENCE_DICTIONARY_SHORT_NAME, SEQUENCE_DICTIONARY_FILE.getAbsolutePath(), "-" + StandardArgumentDefinitions.OUTPUT_SHORT_NAME, "Non-existent-path", "-" + PlotACNVResults.OUTPUT_PREFIX_LONG_NAME, OUTPUT_PREFIX }; runCommandLine(arguments); } @Test(expectedExceptions = UserException.class) public void testMissingSNPCountsFile() throws IOException { final File outputDir = createTempDir("testDir"); final String[] arguments = { "-" + ExomeStandardArgumentDefinitions.ALLELIC_COUNTS_FILE_SHORT_NAME, "Non-existent-file", "-" + ExomeStandardArgumentDefinitions.TANGENT_NORMALIZED_COUNTS_FILE_SHORT_NAME, TANGENT_NORMALIZED_COUNTS_FILE.getAbsolutePath(), "-" + ExomeStandardArgumentDefinitions.SEGMENT_FILE_SHORT_NAME, SEGMENTS_FILE.getAbsolutePath(), "-" + StandardArgumentDefinitions.SEQUENCE_DICTIONARY_SHORT_NAME, SEQUENCE_DICTIONARY_FILE.getAbsolutePath(), "-" + StandardArgumentDefinitions.OUTPUT_SHORT_NAME, outputDir.getAbsolutePath(), "-" + PlotACNVResults.OUTPUT_PREFIX_LONG_NAME, OUTPUT_PREFIX }; runCommandLine(arguments); } @Test(expectedExceptions = UserException.class) public void testMissingTangentFile() throws IOException { final File outputDir = createTempDir("testDir"); final String[] arguments = { "-" + ExomeStandardArgumentDefinitions.ALLELIC_COUNTS_FILE_SHORT_NAME, SNP_COUNTS_FILE.getAbsolutePath(), "-" + ExomeStandardArgumentDefinitions.TANGENT_NORMALIZED_COUNTS_FILE_SHORT_NAME, "Non-existent-file", "-" + ExomeStandardArgumentDefinitions.SEGMENT_FILE_SHORT_NAME, SEGMENTS_FILE.getAbsolutePath(), "-" + StandardArgumentDefinitions.SEQUENCE_DICTIONARY_SHORT_NAME, SEQUENCE_DICTIONARY_FILE.getAbsolutePath(), "-" + StandardArgumentDefinitions.OUTPUT_SHORT_NAME, outputDir.getAbsolutePath(), "-" + PlotACNVResults.OUTPUT_PREFIX_LONG_NAME, OUTPUT_PREFIX }; runCommandLine(arguments); } @Test(expectedExceptions = UserException.class) public void testMissingSegmentsFile() throws IOException { final File outputDir = createTempDir("testDir"); final String[] arguments = { "-" + ExomeStandardArgumentDefinitions.ALLELIC_COUNTS_FILE_SHORT_NAME, SNP_COUNTS_FILE.getAbsolutePath(), "-" + ExomeStandardArgumentDefinitions.TANGENT_NORMALIZED_COUNTS_FILE_SHORT_NAME, TANGENT_NORMALIZED_COUNTS_FILE.getAbsolutePath(), "-" + ExomeStandardArgumentDefinitions.SEGMENT_FILE_SHORT_NAME, "Non-existent-file", "-" + StandardArgumentDefinitions.SEQUENCE_DICTIONARY_SHORT_NAME, SEQUENCE_DICTIONARY_FILE.getAbsolutePath(), "-" + StandardArgumentDefinitions.OUTPUT_SHORT_NAME, outputDir.getAbsolutePath(), "-" + PlotACNVResults.OUTPUT_PREFIX_LONG_NAME, OUTPUT_PREFIX }; runCommandLine(arguments); } @Test(expectedExceptions = UserException.class) public void testMissingSequenceDictionaryFile() throws IOException { final File outputDir = createTempDir("testDir"); final String[] arguments = { "-" + ExomeStandardArgumentDefinitions.ALLELIC_COUNTS_FILE_SHORT_NAME, SNP_COUNTS_FILE.getAbsolutePath(), "-" + ExomeStandardArgumentDefinitions.TANGENT_NORMALIZED_COUNTS_FILE_SHORT_NAME, TANGENT_NORMALIZED_COUNTS_FILE.getAbsolutePath(), "-" + ExomeStandardArgumentDefinitions.SEGMENT_FILE_SHORT_NAME, SEGMENTS_FILE.getAbsolutePath(), "-" + StandardArgumentDefinitions.SEQUENCE_DICTIONARY_SHORT_NAME, "Non-existent-file", "-" + StandardArgumentDefinitions.OUTPUT_SHORT_NAME, outputDir.getAbsolutePath(), "-" + PlotACNVResults.OUTPUT_PREFIX_LONG_NAME, OUTPUT_PREFIX }; runCommandLine(arguments); } @Test(expectedExceptions = IllegalArgumentException.class) public void testTangentSampleNameMismatch() throws IOException { final File outputDir = createTempDir("testDir"); final String[] arguments = { "-" + ExomeStandardArgumentDefinitions.ALLELIC_COUNTS_FILE_SHORT_NAME, SNP_COUNTS_FILE.getAbsolutePath(), "-" + ExomeStandardArgumentDefinitions.TANGENT_NORMALIZED_COUNTS_FILE_SHORT_NAME, COUNTS_BAD_SAMPLE_NAME_FILE.getAbsolutePath(), "-" + ExomeStandardArgumentDefinitions.SEGMENT_FILE_SHORT_NAME, SEGMENTS_FILE.getAbsolutePath(), "-" + StandardArgumentDefinitions.SEQUENCE_DICTIONARY_SHORT_NAME, SEQUENCE_DICTIONARY_FILE.getAbsolutePath(), "-" + StandardArgumentDefinitions.OUTPUT_SHORT_NAME, outputDir.getAbsolutePath(), "-" + PlotSegmentedCopyRatio.OUTPUT_PREFIX_LONG_NAME, OUTPUT_PREFIX }; runCommandLine(arguments); } @Test(expectedExceptions = IllegalArgumentException.class) public void testSegmentsSampleNameMismatch() throws IOException { final File outputDir = createTempDir("testDir"); final String[] arguments = { "-" + ExomeStandardArgumentDefinitions.ALLELIC_COUNTS_FILE_SHORT_NAME, SNP_COUNTS_FILE.getAbsolutePath(), "-" + ExomeStandardArgumentDefinitions.TANGENT_NORMALIZED_COUNTS_FILE_SHORT_NAME, TANGENT_NORMALIZED_COUNTS_FILE.getAbsolutePath(), "-" + ExomeStandardArgumentDefinitions.SEGMENT_FILE_SHORT_NAME, SEGMENTS_BAD_SAMPLE_NAME_FILE.getAbsolutePath(), "-" + StandardArgumentDefinitions.SEQUENCE_DICTIONARY_SHORT_NAME, SEQUENCE_DICTIONARY_FILE.getAbsolutePath(), "-" + StandardArgumentDefinitions.OUTPUT_SHORT_NAME, outputDir.getAbsolutePath(), "-" + PlotSegmentedCopyRatio.OUTPUT_PREFIX_LONG_NAME, OUTPUT_PREFIX }; runCommandLine(arguments); } @Test(expectedExceptions = IllegalArgumentException.class) public void testSNPCountsDataOutOfBounds() throws IOException { final File outputDir = createTempDir("testDir"); final String[] arguments = { "-" + ExomeStandardArgumentDefinitions.ALLELIC_COUNTS_FILE_SHORT_NAME, SNP_COUNTS_DATA_OUT_OF_BOUNDS_FILE.getAbsolutePath(), "-" + ExomeStandardArgumentDefinitions.TANGENT_NORMALIZED_COUNTS_FILE_SHORT_NAME, TANGENT_NORMALIZED_COUNTS_FILE.getAbsolutePath(), "-" + ExomeStandardArgumentDefinitions.SEGMENT_FILE_SHORT_NAME, SEGMENTS_FILE.getAbsolutePath(), "-" + StandardArgumentDefinitions.SEQUENCE_DICTIONARY_SHORT_NAME, SEQUENCE_DICTIONARY_FILE.getAbsolutePath(), "-" + StandardArgumentDefinitions.OUTPUT_SHORT_NAME, outputDir.getAbsolutePath(), "-" + PlotSegmentedCopyRatio.OUTPUT_PREFIX_LONG_NAME, OUTPUT_PREFIX }; runCommandLine(arguments); } @Test(expectedExceptions = IllegalArgumentException.class) public void testTangentDataOutOfBounds() throws IOException { final File outputDir = createTempDir("testDir"); final String[] arguments = { "-" + ExomeStandardArgumentDefinitions.ALLELIC_COUNTS_FILE_SHORT_NAME, SNP_COUNTS_FILE.getAbsolutePath(), "-" + ExomeStandardArgumentDefinitions.TANGENT_NORMALIZED_COUNTS_FILE_SHORT_NAME, COUNTS_DATA_OUT_OF_BOUNDS_FILE.getAbsolutePath(), "-" + ExomeStandardArgumentDefinitions.SEGMENT_FILE_SHORT_NAME, SEGMENTS_FILE.getAbsolutePath(), "-" + StandardArgumentDefinitions.SEQUENCE_DICTIONARY_SHORT_NAME, SEQUENCE_DICTIONARY_FILE.getAbsolutePath(), "-" + StandardArgumentDefinitions.OUTPUT_SHORT_NAME, outputDir.getAbsolutePath(), "-" + PlotSegmentedCopyRatio.OUTPUT_PREFIX_LONG_NAME, OUTPUT_PREFIX }; runCommandLine(arguments); } @Test(expectedExceptions = IllegalArgumentException.class) public void testSegmentsDataOutOfBounds() throws IOException { final File outputDir = createTempDir("testDir"); final String[] arguments = { "-" + ExomeStandardArgumentDefinitions.ALLELIC_COUNTS_FILE_SHORT_NAME, SNP_COUNTS_FILE.getAbsolutePath(), "-" + ExomeStandardArgumentDefinitions.TANGENT_NORMALIZED_COUNTS_FILE_SHORT_NAME, TANGENT_NORMALIZED_COUNTS_FILE.getAbsolutePath(), "-" + ExomeStandardArgumentDefinitions.SEGMENT_FILE_SHORT_NAME, SEGMENTS_DATA_OUT_OF_BOUNDS_FILE.getAbsolutePath(), "-" + StandardArgumentDefinitions.SEQUENCE_DICTIONARY_SHORT_NAME, SEQUENCE_DICTIONARY_FILE.getAbsolutePath(), "-" + StandardArgumentDefinitions.OUTPUT_SHORT_NAME, outputDir.getAbsolutePath(), "-" + PlotSegmentedCopyRatio.OUTPUT_PREFIX_LONG_NAME, OUTPUT_PREFIX }; runCommandLine(arguments); } }
922f99a290b002e426a4963d313df11aa05a8da0
3,677
java
Java
android/app/src/main/java/host/exp/exponent/plugin/tasker/PluginBundleValues.java
dskline/smart-home-hub
2447dd4144047a8c83b8fba2c01485e914f3a4b5
[ "MIT" ]
null
null
null
android/app/src/main/java/host/exp/exponent/plugin/tasker/PluginBundleValues.java
dskline/smart-home-hub
2447dd4144047a8c83b8fba2c01485e914f3a4b5
[ "MIT" ]
null
null
null
android/app/src/main/java/host/exp/exponent/plugin/tasker/PluginBundleValues.java
dskline/smart-home-hub
2447dd4144047a8c83b8fba2c01485e914f3a4b5
[ "MIT" ]
null
null
null
34.364486
101
0.675823
995,176
package host.exp.exponent.plugin.tasker; import android.content.Context; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import com.twofortyfouram.assertion.BundleAssertions; import com.twofortyfouram.log.Lumberjack; import com.twofortyfouram.spackle.AppBuildInfo; import net.jcip.annotations.ThreadSafe; import static com.twofortyfouram.assertion.Assertions.assertNotEmpty; import static com.twofortyfouram.assertion.Assertions.assertNotNull; /** * Manages the {@link com.twofortyfouram.locale.api.Intent#EXTRA_BUNDLE EXTRA_BUNDLE} for this * plug-in. */ @ThreadSafe public final class PluginBundleValues { /** * Type: {@code String}. * <p> * String message to display in a Toast message. */ @NonNull public static final String BUNDLE_EXTRA_STRING_MESSAGE = "com.twofortyfouram.locale.example.setting.toast.extra.STRING_MESSAGE"; //$NON-NLS-1$ /** * Type: {@code int}. * <p> * versionCode of the plug-in that saved the Bundle. */ /* * This extra is not strictly required, however it makes backward and forward compatibility * significantly easier. For example, suppose a bug is found in how some version of the plug-in * stored its Bundle. By having the version, the plug-in can better detect when such bugs occur. */ @NonNull public static final String BUNDLE_EXTRA_INT_VERSION_CODE = "com.twofortyfouram.locale.example.setting.toast.extra.INT_VERSION_CODE"; //$NON-NLS-1$ /** * Method to verify the content of the bundle are correct. * <p> * This method will not mutate {@code bundle}. * * @param bundle bundle to verify. May be null, which will always return false. * @return true if the Bundle is valid, false if the bundle is invalid. */ public static boolean isBundleValid(@Nullable final Bundle bundle) { if (null == bundle) { return false; } try { BundleAssertions.assertHasString(bundle, BUNDLE_EXTRA_STRING_MESSAGE, false, false); BundleAssertions.assertHasInt(bundle, BUNDLE_EXTRA_INT_VERSION_CODE); BundleAssertions.assertKeyCount(bundle, 2); } catch (final AssertionError e) { Lumberjack.e("Bundle failed verification%s", e); //$NON-NLS-1$ return false; } return true; } /** * @param context Application context. * @param message The toast message to be displayed by the plug-in. * @return A plug-in bundle. */ @NonNull public static Bundle generateBundle(@NonNull final Context context, @NonNull final String message) { assertNotNull(context, "context"); //$NON-NLS-1$ assertNotEmpty(message, "message"); //$NON-NLS-1$ final Bundle result = new Bundle(); result.putInt(BUNDLE_EXTRA_INT_VERSION_CODE, AppBuildInfo.getVersionCode(context)); result.putString(BUNDLE_EXTRA_STRING_MESSAGE, message); return result; } /** * @param bundle A valid plug-in bundle. * @return The message inside the plug-in bundle. */ @NonNull public static String getMessage(@NonNull final Bundle bundle) { return bundle.getString(BUNDLE_EXTRA_STRING_MESSAGE); } /** * Private constructor prevents instantiation * * @throws UnsupportedOperationException because this class cannot be instantiated. */ private PluginBundleValues() { throw new UnsupportedOperationException("This class is non-instantiable"); //$NON-NLS-1$ } }
922f99f6dbbb23d1942fe11d91c4d61ee8993cac
213
java
Java
Benchmarks_with_Functional_Bugs/Java/Bears-72/src/src/test/java/spoon/test/targeted/testclasses/InternalSuperCall.java
kupl/starlab-benchmarks
1efc9efffad1b797f6a795da7e032041e230d900
[ "MIT" ]
null
null
null
Benchmarks_with_Functional_Bugs/Java/Bears-72/src/src/test/java/spoon/test/targeted/testclasses/InternalSuperCall.java
kupl/starlab-benchmarks
1efc9efffad1b797f6a795da7e032041e230d900
[ "MIT" ]
null
null
null
Benchmarks_with_Functional_Bugs/Java/Bears-72/src/src/test/java/spoon/test/targeted/testclasses/InternalSuperCall.java
kupl/starlab-benchmarks
1efc9efffad1b797f6a795da7e032041e230d900
[ "MIT" ]
2
2020-11-26T13:27:14.000Z
2022-03-20T02:12:55.000Z
14.2
40
0.737089
995,177
package spoon.test.targeted.testclasses; public class InternalSuperCall{ public void methode(){ InternalSuperCall.super.toString(); } @Override public String toString() { return super.toString(); } }
922f9b770436ec894b9851f2c3fa360950d747b4
3,098
java
Java
cdap-api/src/main/java/co/cask/cdap/api/schedule/ScheduleSpecification.java
wavyllama/cdap
e38e8b6b154e472e94b6f6db4eac4452df260641
[ "Apache-2.0" ]
3
2018-03-22T23:25:54.000Z
2018-03-22T23:36:44.000Z
cdap-api/src/main/java/co/cask/cdap/api/schedule/ScheduleSpecification.java
wavyllama/cdap
e38e8b6b154e472e94b6f6db4eac4452df260641
[ "Apache-2.0" ]
null
null
null
cdap-api/src/main/java/co/cask/cdap/api/schedule/ScheduleSpecification.java
wavyllama/cdap
e38e8b6b154e472e94b6f6db4eac4452df260641
[ "Apache-2.0" ]
null
null
null
28.163636
112
0.67592
995,178
/* * Copyright © 2015 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 co.cask.cdap.api.schedule; import co.cask.cdap.api.workflow.ScheduleProgramInfo; import co.cask.cdap.internal.schedule.ScheduleCreationSpec; import java.util.Collections; import java.util.HashMap; import java.util.Map; /** * Specification for {@link Schedule}. * * @deprecated as of 4.2.0. Use {@link ScheduleCreationSpec} instead. */ @Deprecated public final class ScheduleSpecification { private final Schedule schedule; private final ScheduleProgramInfo program; private final Map<String, String> properties; public ScheduleSpecification(Schedule schedule, ScheduleProgramInfo program, Map<String, String> properties) { this.schedule = schedule; this.program = program; this.properties = properties == null ? new HashMap<String, String>() : Collections.unmodifiableMap(new HashMap<>(properties)); } /** * @return the program associated with {@link ScheduleSpecification} */ public ScheduleProgramInfo getProgram() { return program; } /** * @return the {@link Schedule} associated with {@link ScheduleSpecification} */ public Schedule getSchedule() { return schedule; } /** * @return the properties associated with the schedule */ public Map<String, String> getProperties() { return properties; } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ScheduleSpecification that = (ScheduleSpecification) o; if (program != null ? !program.equals(that.program) : that.program != null) { return false; } if (properties != null ? !properties.equals(that.properties) : that.properties != null) { return false; } if (schedule != null ? !schedule.equals(that.schedule) : that.schedule != null) { return false; } return true; } @Override public int hashCode() { int result = schedule != null ? schedule.hashCode() : 0; result = 31 * result + (program != null ? program.hashCode() : 0); result = 31 * result + (properties != null ? properties.hashCode() : 0); return result; } @Override public String toString() { StringBuilder sb = new StringBuilder("ScheduleSpecification{"); sb.append("schedule=").append(schedule); sb.append(", program=").append(program); sb.append(", properties=").append(properties); sb.append('}'); return sb.toString(); } }
922f9b9681a5d4408ee8b528209f9ba2c4bd4e39
1,773
java
Java
cmdb-core/src/main/java/com/webank/cmdb/domain/AdmTemplate.java
HoweChen/we-cmdb
6482159367b0ce9b7334e60c790a50aba12febdb
[ "Apache-2.0" ]
1
2019-09-29T06:13:09.000Z
2019-09-29T06:13:09.000Z
cmdb-core/src/main/java/com/webank/cmdb/domain/AdmTemplate.java
HoweChen/we-cmdb
6482159367b0ce9b7334e60c790a50aba12febdb
[ "Apache-2.0" ]
1
2019-10-10T03:59:52.000Z
2019-10-10T03:59:52.000Z
cmdb-core/src/main/java/com/webank/cmdb/domain/AdmTemplate.java
HoweChen/we-cmdb
6482159367b0ce9b7334e60c790a50aba12febdb
[ "Apache-2.0" ]
1
2022-02-10T03:22:37.000Z
2022-02-10T03:22:37.000Z
24.971831
80
0.710096
995,179
package com.webank.cmdb.domain; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQuery; import javax.persistence.Table; /** * The persistent class for the adm_template database table. * */ @Entity @Table(name = "adm_template") @NamedQuery(name = "AdmTemplate.findAll", query = "SELECT a FROM AdmTemplate a") public class AdmTemplate implements Serializable { private static final long serialVersionUID = 1L; private Integer idAdmTemplate; private Integer isActive; private String name; private AdmCiType admCiType; public AdmTemplate() { } @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id_adm_template") public Integer getIdAdmTemplate() { return this.idAdmTemplate; } public void setIdAdmTemplate(Integer idAdmTemplate) { this.idAdmTemplate = idAdmTemplate; } public Integer getIsActive() { return this.isActive; } public void setIsActive(Integer isActive) { this.isActive = isActive; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } // bi-directional many-to-one association to AdmCiType @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "id_adm_ci_type") public AdmCiType getAdmCiType() { return this.admCiType; } public void setAdmCiType(AdmCiType admCiType) { this.admCiType = admCiType; } }
922f9c7ca38505dde6f846c763a24acfd6dc6e7e
638
java
Java
src/main/java/net/openid/conformance/condition/client/ExpectPkceMissingErrorPage.java
openid-certification/-conformance-suite
16aaf4ee7cf807c62bbb0ceb7d55aca4d4c0b3c0
[ "MIT" ]
2
2021-09-12T11:45:13.000Z
2022-01-24T14:56:44.000Z
src/main/java/net/openid/conformance/condition/client/ExpectPkceMissingErrorPage.java
openid-certification/-conformance-suite
16aaf4ee7cf807c62bbb0ceb7d55aca4d4c0b3c0
[ "MIT" ]
6
2019-10-29T18:16:34.000Z
2021-08-14T09:48:39.000Z
src/main/java/net/openid/conformance/condition/client/ExpectPkceMissingErrorPage.java
openid-certification/conformance-suite
86f25bd22837391e6639edfa55190588b9612422
[ "MIT" ]
null
null
null
31.9
164
0.822884
995,180
package net.openid.conformance.condition.client; import net.openid.conformance.condition.AbstractCondition; import net.openid.conformance.condition.PostEnvironment; import net.openid.conformance.testmodule.Environment; public class ExpectPkceMissingErrorPage extends AbstractCondition { @Override @PostEnvironment(strings = "pkce_missing_error") public Environment evaluate(Environment env) { String placeholder = createBrowserInteractionPlaceholder("Show an error page saying PKCE / code_challenge / code_challenge_method are missing from the request."); env.putString("pkce_missing_error", placeholder); return env; } }
922f9de18dd915931262b4e0bfccdb7b8d44e06b
8,381
java
Java
src/main/java/spatial_vrp/RoadFixedGeometry.java
vesavlad/somado
2aa8f8fcb68fff9d385e84242709708a099e7239
[ "MIT" ]
6
2017-10-20T02:35:49.000Z
2021-10-15T09:27:51.000Z
src/main/java/spatial_vrp/RoadFixedGeometry.java
vesavlad/somado
2aa8f8fcb68fff9d385e84242709708a099e7239
[ "MIT" ]
1
2018-03-24T08:55:25.000Z
2020-01-01T13:57:59.000Z
src/main/java/spatial_vrp/RoadFixedGeometry.java
vesavlad/somado
2aa8f8fcb68fff9d385e84242709708a099e7239
[ "MIT" ]
4
2019-01-09T07:55:53.000Z
2022-01-16T20:20:00.000Z
29
116
0.609593
995,181
/* * * Somado (System Optymalizacji Małych Dostaw) * Optymalizacja dostaw towarów, dane OSM, problem VRP * * Autor: Maciej Kawecki 2016 (praca inż. EE PW) * */ package spatial_vrp; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.io.ParseException; import com.vividsolutions.jts.io.WKTReader; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; /** * * Przygotowanie poprawionej geometrii drogi (z uwzględnieniem dodatkowych odcinków zawierających tylko jeden węzeł) * do wyświetlenia na mapie * * @author Maciej Kawecki * @version 1.0 * */ public class RoadFixedGeometry { /** Geometria głównych odcinków dróg (połączenia pomiędzy węzłami) dla ID punktów trasy */ private final Map<Integer, Geometry> geometry; /** Lista dodatkowych geometrii (pojedyncze fragmenty odcinków pomiędzy węzłami) dla ID punktów trasy */ private final Map<Integer, Geometry> additionalGeometry; /** Poprawiona długość odcinków */ private final Map<Integer, Double> fixedLength; /** Czy to obiekt dla macierzy kosztów */ private boolean forMatrix = false; /** * Konstruktor dla macierzy kosztów * @param elem Element macierzy kosztów * @param additionalGeometry1 Dodatkowa geometria odcinka drogi dla punktu 1 (map. indeks kolumny macierzy) * @param additionalGeometry2 Dodatkowa geometria odcinka drogi dla punktu 2 (map. indeks wiersza macierzy) */ public RoadFixedGeometry(CostMatrixElem elem, Geometry additionalGeometry1, Geometry additionalGeometry2) { this(new RoutePoint(1, 0.0, 0.0, null, elem.getGeometry(), additionalGeometry1), new RoutePoint(2, elem.getDistance(), 0.0, null, elem.getGeometry(), additionalGeometry2)); forMatrix = true; } /** * Konstruktor dla dwóch punktów (poj. odcinek) * @param p1 Pierwszy punkt * @param p2 Drugi punkt */ public RoadFixedGeometry(RoutePoint p1, RoutePoint p2) { this(new ArrayList<>(Arrays.asList(new RoutePoint[]{p1, p2}))); } /** * Konstruktor dla całej trasy (do wyświetlania na mapie) * @param routePoints Lista punktów trasy */ public RoadFixedGeometry(List<RoutePoint> routePoints) { geometry = new HashMap<>(); additionalGeometry = new HashMap<>(); fixedLength = new HashMap<>(); List<RoutePoint> route = new ArrayList<>(routePoints); Iterator<RoutePoint> iterator = route.iterator(); Geometry prevAdditionalGeometry = null; while (iterator.hasNext()) { RoutePoint point = iterator.next(); if (point.getGeometry() == null) continue; double addLength = 0.0; // najpierw poprzednia dodatkowa geometria (pierwszy punkt) if (prevAdditionalGeometry != null) { Coordinate c[] = prevAdditionalGeometry.getCoordinates(); if (testCoords(point.getGeometry(), c, false)) { point.setGeometry(point.getGeometry().difference(prevAdditionalGeometry)); addLength -= getRoadLen(prevAdditionalGeometry); } } // teraz aktualna dodatkowa geometria (drugi punkt) if (point.getAdditionalGeometry() != null) { boolean found = false; Coordinate c[] = point.getAdditionalGeometry().getCoordinates(); // jeżeli nie ostatni punkt, to czy następny także pokrywa dodatkową geometrię ? boolean containsNext = false; if (iterator.hasNext()) { RoutePoint tmp = null; Iterator<RoutePoint> iterator2 = new ArrayList<>(route).iterator(); while (iterator2.hasNext()) { tmp = iterator2.next(); if (tmp.getId().equals(point.getId())) break; } if (tmp != null && iterator2.hasNext() && testCoords(iterator2.next().getGeometry(), c, true)) { containsNext = true; } } // jeżeli ostatni (bez powrotu) lub powrót tą samą drogą if ((!iterator.hasNext() || containsNext) && testCoords(point.getGeometry(), c, false)) { point.setGeometry(point.getGeometry().difference(point.getAdditionalGeometry())); addLength -= getRoadLen(point.getAdditionalGeometry()); found = true; } if (!found && !testCoords(point.getGeometry(), c, false)) { additionalGeometry.put(point.getId(), point.getAdditionalGeometry()); addLength += getRoadLen(point.getAdditionalGeometry()); } } geometry.put(point.getId(), point.getGeometry()); fixedLength.put(point.getId(), addLength); prevAdditionalGeometry = point.getAdditionalGeometry(); } } /** * Sprawdzenie czy ciąg punktów zawiera się w danej geometrii * @param geom Geometria drogi * @param c Ciąg punktów (tablica) * @param reverse Czy kolejność ma być odwrócona (powrót) * @return True jeżeli ciąg punktów zawiera się w geometrii */ private boolean testCoords(Geometry geom, Coordinate[] c, boolean reverse) { int dk = reverse ? -1 : 1; for (int k=(reverse ? c.length-1 : 0); (reverse ? k>=0 : k<c.length); k+=dk) { try { String s = c[k].x + " " + c[k].y + "," + c[k+1].x + " " + c[k+1].y ; Geometry g = new WKTReader().read("LINESTRING(" + s + ")"); if (geom.contains(g)) return true; } catch (ParseException e) { System.out.println(e); } catch (ArrayIndexOutOfBoundsException | NullPointerException e) {} } return false; } /** * Metoda zwraca korektę długości drogi (w metrach) * @param pointId ID punktu trasy * @return Korekta długości drogi (w metrach) */ public double getFixedLength(int pointId) { return fixedLength.get(pointId); } /** * Metoda zwraca korektę długości drogi (w metrach) - wersja dla macierzy kosztów * @return Korekta długości drogi (w metrach) */ public double getFixedLength() { return forMatrix ? fixedLength.get(2) : 0.0; } /** * Metoda zwraca poprawioną geometrię podstawową (odcinka łączącego węzły) * @param pointId ID punktu trasy * @return Poprawiona geometria podstawowa */ public Geometry getFixedGeometry(int pointId) { return geometry.get(pointId); } /** * Metoda zwraca skorygowaną podstawową geometrię odcinka trasy - wersja dla macierzy kosztów * @return Skorygowana podstawowa geometria */ public Geometry getFixedGeometry() { return forMatrix ? getFixedGeometry(2) : null; } /** * Metoda zwraca skorygowaną podstawową geometrię odcinka trasy * @param pointId ID punktu trasy * @return Skorygowana podstawowa geometria */ public Geometry getFixedAdditionalGeometry(int pointId) { return additionalGeometry.get(pointId); } /** * Metoda zwraca poprawioną geometrię dodatkową - wersja dla macierzy kosztów * @return Poprawiona geometria dodatkowa */ public Geometry getFixedAdditionalGeometry() { return forMatrix ? getFixedAdditionalGeometry(2) : null; } /** * Metoda zwraca długość geometrii (w WGS-84) przekonwertowaną na metry (w przybliżeniu, dla małych obiektów) * @param geometry Geometria * @return Przybliżona długość geometrii w metrach */ private static double getRoadLen(Geometry geometry) { // 6378137.0 - oszacowanie promienia Ziemi w m (przy przybliżaniu bryły Ziemi jako elipsoidy) try { return Math.PI/180.0 * 6378137.0 * geometry.getLength(); } catch (NullPointerException e) { return 0.0; } } }
922f9e03c3fab2ce0ed4ec3779ab56c8a29cc421
294
java
Java
src/main/java/com/cleeng/api/domain/RentalOfferRequest.java
jesion/cleeng-java-sdk
b970875a767b85ab3e7265a5e146dd33f76dee93
[ "MIT" ]
2
2017-09-01T15:40:04.000Z
2019-01-31T13:49:02.000Z
src/main/java/com/cleeng/api/domain/RentalOfferRequest.java
Cleeng/cleeng-java-sdk
c275e6d86db3a739209695fb4c5027f10b8ff015
[ "MIT" ]
9
2017-03-26T15:25:23.000Z
2019-01-29T21:49:02.000Z
src/main/java/com/cleeng/api/domain/RentalOfferRequest.java
jesion/cleeng-java-sdk
b970875a767b85ab3e7265a5e146dd33f76dee93
[ "MIT" ]
7
2016-10-28T11:05:38.000Z
2021-11-24T18:42:02.000Z
22.615385
72
0.693878
995,182
package com.cleeng.api.domain; import org.jsonrpc.JSONRPCRequest; public class RentalOfferRequest extends JSONRPCRequest { public RentalOfferRequest(String method, RentalOfferParams params) { super("1", "2.0"); this.method = method; this.params = params; } }
922f9e2e639d94660c166a055c806562d76135cf
554
java
Java
paquetes/src/utilesGUI/tiposTextos/KeyEventCZ.java
Creativa3d/box3D
97f1caa24aef29a2d5c0191ee018215757d6f91d
[ "Apache-2.0" ]
null
null
null
paquetes/src/utilesGUI/tiposTextos/KeyEventCZ.java
Creativa3d/box3D
97f1caa24aef29a2d5c0191ee018215757d6f91d
[ "Apache-2.0" ]
null
null
null
paquetes/src/utilesGUI/tiposTextos/KeyEventCZ.java
Creativa3d/box3D
97f1caa24aef29a2d5c0191ee018215757d6f91d
[ "Apache-2.0" ]
null
null
null
17.870968
79
0.626354
995,183
/* * 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 utilesGUI.tiposTextos; /** * * @author eduardo */ public class KeyEventCZ { private char mcChar; public KeyEventCZ (){ } public KeyEventCZ (char pcChar){ setKeyChar(pcChar); } public char getKeyChar() { return mcChar; } public void setKeyChar(char pcChar){ mcChar=pcChar; } }
922f9e49d587b469ecde663825a16ce06ff28212
3,805
java
Java
backend/de.metas.ui.web.base/src/main/java-gen/de/metas/ui/web/base/model/X_WEBUI_Board.java
focadiz/metasfresh
212deed2ca14ebeab2c79fae88135cf25cb0c6ce
[ "RSA-MD" ]
1
2021-02-17T12:00:41.000Z
2021-02-17T12:00:41.000Z
backend/de.metas.ui.web.base/src/main/java-gen/de/metas/ui/web/base/model/X_WEBUI_Board.java
focadiz/metasfresh
212deed2ca14ebeab2c79fae88135cf25cb0c6ce
[ "RSA-MD" ]
null
null
null
backend/de.metas.ui.web.base/src/main/java-gen/de/metas/ui/web/base/model/X_WEBUI_Board.java
focadiz/metasfresh
212deed2ca14ebeab2c79fae88135cf25cb0c6ce
[ "RSA-MD" ]
null
null
null
23.78125
115
0.714586
995,184
/** Generated Model - DO NOT CHANGE */ package de.metas.ui.web.base.model; import java.sql.ResultSet; import java.util.Properties; /** Generated Model for WEBUI_Board * @author Adempiere (generated) */ @SuppressWarnings("javadoc") public class X_WEBUI_Board extends org.compiere.model.PO implements I_WEBUI_Board, org.compiere.model.I_Persistent { /** * */ private static final long serialVersionUID = 870288944L; /** Standard Constructor */ public X_WEBUI_Board (Properties ctx, int WEBUI_Board_ID, String trxName) { super (ctx, WEBUI_Board_ID, trxName); /** if (WEBUI_Board_ID == 0) { setAD_Table_ID (0); setName (null); setWEBUI_Board_ID (0); } */ } /** Load Constructor */ public X_WEBUI_Board (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO (Properties ctx) { org.compiere.model.POInfo poi = org.compiere.model.POInfo.getPOInfo (ctx, Table_Name, get_TrxName()); return poi; } @Override public org.compiere.model.I_AD_Table getAD_Table() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_AD_Table_ID, org.compiere.model.I_AD_Table.class); } @Override public void setAD_Table(org.compiere.model.I_AD_Table AD_Table) { set_ValueFromPO(COLUMNNAME_AD_Table_ID, org.compiere.model.I_AD_Table.class, AD_Table); } /** Set DB-Tabelle. @param AD_Table_ID Database Table information */ @Override public void setAD_Table_ID (int AD_Table_ID) { if (AD_Table_ID < 1) set_Value (COLUMNNAME_AD_Table_ID, null); else set_Value (COLUMNNAME_AD_Table_ID, Integer.valueOf(AD_Table_ID)); } /** Get DB-Tabelle. @return Database Table information */ @Override public int getAD_Table_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Table_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_AD_Val_Rule getAD_Val_Rule() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_AD_Val_Rule_ID, org.compiere.model.I_AD_Val_Rule.class); } @Override public void setAD_Val_Rule(org.compiere.model.I_AD_Val_Rule AD_Val_Rule) { set_ValueFromPO(COLUMNNAME_AD_Val_Rule_ID, org.compiere.model.I_AD_Val_Rule.class, AD_Val_Rule); } /** Set Dynamische Validierung. @param AD_Val_Rule_ID Regel für die dynamische Validierung */ @Override public void setAD_Val_Rule_ID (int AD_Val_Rule_ID) { if (AD_Val_Rule_ID < 1) set_Value (COLUMNNAME_AD_Val_Rule_ID, null); else set_Value (COLUMNNAME_AD_Val_Rule_ID, Integer.valueOf(AD_Val_Rule_ID)); } /** Get Dynamische Validierung. @return Regel für die dynamische Validierung */ @Override public int getAD_Val_Rule_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Val_Rule_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set Board. @param WEBUI_Board_ID Board */ @Override public void setWEBUI_Board_ID (int WEBUI_Board_ID) { if (WEBUI_Board_ID < 1) set_ValueNoCheck (COLUMNNAME_WEBUI_Board_ID, null); else set_ValueNoCheck (COLUMNNAME_WEBUI_Board_ID, Integer.valueOf(WEBUI_Board_ID)); } /** Get Board. @return Board */ @Override public int getWEBUI_Board_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_WEBUI_Board_ID); if (ii == null) return 0; return ii.intValue(); } }
922f9f631faa3b2ec1da877367996fd238dbe5e4
661
java
Java
Practice Java programs (10th grade)/pr102.java
ThatXuxe/ICSE-Java-Practice
d7fd831ea0ef89f46b690789b2b490af55054c1a
[ "Apache-2.0" ]
1
2020-08-04T05:13:08.000Z
2020-08-04T05:13:08.000Z
Practice Java programs (10th grade)/pr102.java
xuxey/ICSE-Java-Practice
d7fd831ea0ef89f46b690789b2b490af55054c1a
[ "Apache-2.0" ]
null
null
null
Practice Java programs (10th grade)/pr102.java
xuxey/ICSE-Java-Practice
d7fd831ea0ef89f46b690789b2b490af55054c1a
[ "Apache-2.0" ]
null
null
null
27.541667
74
0.472012
995,185
import java.util.*; public class pr102 { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.println("Enter 5 numbers: "); int[] arr = new int[5]; for(int i = 0; i<5;i++) arr[i] = sc.nextInt(); System.out.println("__________________________"); System.out.println("Enter search Item"); int s = sc.nextInt(), flag = 0, i; for(i = 0; i<5; i++) { if(s==arr[i]) { flag = 1; break; } } System.out.println((flag == 1)?"item found at "+(i+1):"not found"); } }
922f9fadcbefee4fd565a864bbc74d1123b71ffa
3,109
java
Java
app/src/main/java/com/innovalab/shock/vues/GraphView.java
Innovateamlab/Shock-Android
bc8ac7ddddbcc900fb2199a51faf76c4091c51d8
[ "BSD-3-Clause" ]
null
null
null
app/src/main/java/com/innovalab/shock/vues/GraphView.java
Innovateamlab/Shock-Android
bc8ac7ddddbcc900fb2199a51faf76c4091c51d8
[ "BSD-3-Clause" ]
null
null
null
app/src/main/java/com/innovalab/shock/vues/GraphView.java
Innovateamlab/Shock-Android
bc8ac7ddddbcc900fb2199a51faf76c4091c51d8
[ "BSD-3-Clause" ]
null
null
null
28.009009
133
0.715664
995,186
package com.innovalab.shock.vues; import android.app.Activity; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.util.AttributeSet; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.LinearLayout; import android.widget.ListView; import com.androidplot.Series; import com.androidplot.xy.BoundaryMode; import com.innovalab.shock.R; import com.innovalab.shock.modele.ObjetFrappe; import com.androidplot.xy.LineAndPointFormatter; import com.androidplot.xy.SimpleXYSeries; import com.androidplot.xy.XYPlot; import com.androidplot.xy.XYSeries; import com.androidplot.xy.XYSeriesFormatter; import com.jjoe64.graphview.series.DataPoint; import com.jjoe64.graphview.series.DataPointInterface; import com.jjoe64.graphview.series.LineGraphSeries; import com.jjoe64.graphview.series.OnDataPointTapListener; import java.util.ArrayList; import java.util.List; /** * Created by innovalab2 on 10/05/2017. */ public class GraphView extends LinearLayout { private ObjetFrappe objetFrappe; private com.jjoe64.graphview.GraphView graphView; public GraphView(Context context) { super(context); init(context); } public GraphView(Context context, AttributeSet attrs) { super(context, attrs); init(context); } public GraphView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(context); } private void init(Context context) { LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); inflater.inflate(R.layout.graph_view, this, true); graphView = (com.jjoe64.graphview.GraphView) findViewById(R.id.graph); setRange(); graphView.getViewport().setScalable(true); } private void setRange() { graphView.getViewport().setMinY(0); graphView.getViewport().setMaxY(255); graphView.getViewport().setYAxisBoundsManual(true); graphView.getViewport().setMinX(0); graphView.getViewport().setMaxX(2000); graphView.getViewport().setXAxisBoundsManual(true); } public void setObjetFrappe(ObjetFrappe obj){objetFrappe = obj;} public void display(OnDataPointTapListener listener) { graphView.removeAllSeries(); LineGraphSeries<DataPoint> series = new LineGraphSeries<DataPoint>(getPoints(objetFrappe.getTemps(), objetFrappe.lissage())); series.setOnDataPointTapListener(listener); graphView.addSeries(series); setRange(); } private DataPoint[] getPoints(List<Float> x, List<Float> y) { DataPoint[] points = new DataPoint[x.size()]; graphView.getViewport().setMaxX(x.size()); for(int i=0;i<x.size();i++) { points[i] = new DataPoint(x.get(i),y.get(i)); } return points; } }
922fa18028ce345464d02be8e1f2d239a6925655
5,314
java
Java
src/java.naming/share/classes/com/sun/jndi/ldap/sasl/TlsChannelBinding.java
1690296356/jdk
eaf668d1510c28d51e26c397b582b66ebdf7e263
[ "Apache-2.0" ]
1
2020-12-26T04:52:15.000Z
2020-12-26T04:52:15.000Z
src/java.naming/share/classes/com/sun/jndi/ldap/sasl/TlsChannelBinding.java
1690296356/jdk
eaf668d1510c28d51e26c397b582b66ebdf7e263
[ "Apache-2.0" ]
1
2020-12-26T04:57:19.000Z
2020-12-26T04:57:19.000Z
src/java.naming/share/classes/com/sun/jndi/ldap/sasl/TlsChannelBinding.java
1690296356/jdk
eaf668d1510c28d51e26c397b582b66ebdf7e263
[ "Apache-2.0" ]
1
2021-12-06T01:13:18.000Z
2021-12-06T01:13:18.000Z
36.14966
100
0.652428
995,187
/* * Copyright (c) 2020, Azul Systems, Inc. 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 com.sun.jndi.ldap.sasl; import javax.naming.NamingException; import javax.security.sasl.SaslException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateEncodingException; import java.security.cert.X509Certificate; import java.util.Arrays; import java.util.Hashtable; /** * This class implements the Channel Binding for TLS as defined in * <a href="https://www.ietf.org/rfc/rfc5929.txt"> * Channel Bindings for TLS</a> * * Format of the Channel Binding data is also defined in * <a href="https://www.ietf.org/rfc/rfc5056.txt"> * On the Use of Channel Bindings to Secure Channels</a> * section 2.1. * */ public class TlsChannelBinding { // TLS channel binding type property public static final String CHANNEL_BINDING_TYPE = "com.sun.jndi.ldap.tls.cbtype"; // internal TLS channel binding property public static final String CHANNEL_BINDING = "jdk.internal.sasl.tlschannelbinding"; public enum TlsChannelBindingType { /** * Channel binding on the basis of TLS Finished message. * TLS_UNIQUE is defined by RFC 5929 but is not supported * by the current LDAP stack. */ TLS_UNIQUE("tls-unique"), /** * Channel binding on the basis of TLS server certificate. */ TLS_SERVER_END_POINT("tls-server-end-point"); public String getName() { return name; } private final String name; TlsChannelBindingType(String name) { this.name = name; } } /** * Parse value of "com.sun.jndi.ldap.tls.cbtype" property * @param cbType * @return TLS Channel Binding type or null if * "com.sun.jndi.ldap.tls.cbtype" property has not been set. * @throws NamingException */ public static TlsChannelBindingType parseType(String cbType) throws NamingException { if (cbType != null) { if (cbType.equals(TlsChannelBindingType.TLS_SERVER_END_POINT.getName())) { return TlsChannelBindingType.TLS_SERVER_END_POINT; } else { throw new NamingException("Illegal value for " + CHANNEL_BINDING_TYPE + " property."); } } return null; } private final TlsChannelBindingType cbType; private final byte[] cbData; /** * Construct tls-server-end-point Channel Binding data * @param serverCertificate * @throws SaslException */ public static TlsChannelBinding create(X509Certificate serverCertificate) throws SaslException { try { final byte[] prefix = TlsChannelBindingType.TLS_SERVER_END_POINT.getName().concat(":").getBytes(); String hashAlg = serverCertificate.getSigAlgName(). replace("SHA", "SHA-").toUpperCase(); int ind = hashAlg.indexOf("WITH"); if (ind > 0) { hashAlg = hashAlg.substring(0, ind); if (hashAlg.equals("MD5") || hashAlg.equals("SHA-1")) { hashAlg = "SHA-256"; } } else { hashAlg = "SHA-256"; } MessageDigest md = MessageDigest.getInstance(hashAlg); byte[] hash = md.digest(serverCertificate.getEncoded()); byte[] cbData = Arrays.copyOf(prefix, prefix.length + hash.length ); System.arraycopy(hash, 0, cbData, prefix.length, hash.length); return new TlsChannelBinding(TlsChannelBindingType.TLS_SERVER_END_POINT, cbData); } catch (NoSuchAlgorithmException | CertificateEncodingException e) { throw new SaslException("Cannot create TLS channel binding data", e); } } private TlsChannelBinding(TlsChannelBindingType cbType, byte[] cbData) { this.cbType = cbType; this.cbData = cbData; } public TlsChannelBindingType getType() { return cbType; } public byte[] getData() { return cbData; } }
922fa2cd22400e4c6b1c5746b86a33f41e20cacf
7,179
java
Java
metaobj/metaobj-util/tool-lib/src/java/org/sakaiproject/metaobj/utils/mvc/impl/TemplateJstlView.java
sadupally/Dev
ead9de3993b7a805199ac254c6fa99d3dda48adf
[ "ECL-2.0" ]
null
null
null
metaobj/metaobj-util/tool-lib/src/java/org/sakaiproject/metaobj/utils/mvc/impl/TemplateJstlView.java
sadupally/Dev
ead9de3993b7a805199ac254c6fa99d3dda48adf
[ "ECL-2.0" ]
null
null
null
metaobj/metaobj-util/tool-lib/src/java/org/sakaiproject/metaobj/utils/mvc/impl/TemplateJstlView.java
sadupally/Dev
ead9de3993b7a805199ac254c6fa99d3dda48adf
[ "ECL-2.0" ]
null
null
null
35.04878
163
0.682672
995,188
/********************************************************************************** * $URL: https://source.sakaiproject.org/svn/metaobj/tags/sakai-10.4/metaobj-util/tool-lib/src/java/org/sakaiproject/metaobj/utils/mvc/impl/TemplateJstlView.java $ * $Id: TemplateJstlView.java 105079 2012-02-24 23:08:11Z hzdkv@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.mvc.impl; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.sakaiproject.component.cover.ComponentManager; import org.sakaiproject.metaobj.utils.mvc.intf.CommonModelController; import org.sakaiproject.portal.api.Editor; import org.sakaiproject.portal.api.PortalService; import org.sakaiproject.tool.api.Placement; import org.sakaiproject.tool.cover.ToolManager; import org.sakaiproject.util.EditorConfiguration; import org.sakaiproject.util.ResourceLoader; import org.springframework.web.servlet.view.JstlView; /** * Created by IntelliJ IDEA. * User: John Ellis * Date: Apr 30, 2004 * Time: 8:29:53 AM * To change this template use File | Settings | File Templates. */ public class TemplateJstlView extends JstlView { private String rightMenu = null; private String leftMenu = null; private String header = null; private String footer = null; private String body = null; private String template = null; private String title = null; private String defaultTemplateDefName = "defaultTemplateDef"; private String commonModelControllerName = "commonModelController"; /** * Prepares the view given the specified model, merging it with static * attributes and a RequestContext attribute, if necessary. * Delegates to renderMergedOutputModel for the actual rendering. * * @see #renderMergedOutputModel */ public void render(Map model, HttpServletRequest request, HttpServletResponse response) throws Exception { // Added to be able to conform to the locale in JSTL jsp's ResourceLoader rb = new ResourceLoader(); model.put("locale", rb.getLocale().toString()); SimpleBeanWrapper mapWrapper = (SimpleBeanWrapper) getWebApplicationContext().getBean(defaultTemplateDefName); Map defaultTemplateDef = (Map) mapWrapper.getWrappedBean(); addComponent("_rightMenu", rightMenu, request, defaultTemplateDef); addComponent("_leftMenu", leftMenu, request, defaultTemplateDef); addComponent("_header", header, request, defaultTemplateDef); addComponent("_footer", footer, request, defaultTemplateDef); addComponent("_body", body, request, defaultTemplateDef); addComponent("_title", title, request, defaultTemplateDef); template = addComponent("_template", template, request, defaultTemplateDef); PortalService portalService = (PortalService) ComponentManager.get(PortalService.class); Placement placement = ToolManager.getCurrentPlacement(); Editor editor = portalService.getActiveEditor(placement); String preloadScript = editor.getPreloadScript() == null ? "" : "<script type=\"text/javascript\" language=\"JavaScript\">" + editor.getPreloadScript() + "</script>\n"; String editorScript = editor.getEditorUrl() == null ? "" : "<script type=\"text/javascript\" language=\"JavaScript\" src=\"" + editor.getEditorUrl() + "\"></script>\n"; String launchScript = editor.getLaunchUrl() == null ? "" : "<script type=\"text/javascript\" language=\"JavaScript\" src=\"" + editor.getLaunchUrl() + "\"></script>\n"; StringBuilder headJs = new StringBuilder(); headJs.append("<script type=\"text/javascript\" language=\"JavaScript\" src=\"/library/js/headscripts.js\"></script>\n"); headJs.append("<script type=\"text/javascript\" language=\"JavaScript\">var sakai = sakai || {}; sakai.editor = sakai.editor || {}; \n"); headJs.append("sakai.editor.collectionId = '" + portalService.getBrowserCollectionId(placement) + "';\n"); headJs.append("sakai.editor.enableResourceSearch = " + EditorConfiguration.enableResourceSearch() + ";</script>\n"); headJs.append(preloadScript); headJs.append(editorScript); headJs.append(launchScript); request.setAttribute("editorHeadScript", headJs.toString()); CommonModelController controller = (CommonModelController) getWebApplicationContext().getBean(commonModelControllerName); controller.fillModel(model, request, response); this.setUrl(template); super.render(model, request, response); } protected String addComponent(String menuTag, String menuName, HttpServletRequest request, Map defaultTemplateDef) { if (menuName == null) { menuName = (String) defaultTemplateDef.get(menuTag); } if (menuName != null) { request.setAttribute(menuTag, menuName); } return menuName; } public String getRightMenu() { return rightMenu; } public void setRightMenu(String rightMenu) { this.rightMenu = rightMenu; } public String getLeftMenu() { return leftMenu; } public void setLeftMenu(String leftMenu) { this.leftMenu = leftMenu; } public String getHeader() { return header; } public void setHeader(String header) { this.header = header; } public String getFooter() { return footer; } public void setFooter(String footer) { this.footer = footer; } public String getBody() { return body; } public void setBody(String body) { this.body = body; } public String getDefaultTemplateDefName() { return defaultTemplateDefName; } public void setDefaultTemplateDefName(String defaultTemplateDefName) { this.defaultTemplateDefName = defaultTemplateDefName; } public String getTemplate() { return template; } public void setTemplate(String template) { this.template = template; } public String getCommonModelControllerName() { return commonModelControllerName; } public void setCommonModelControllerName(String commonModelControllerName) { this.commonModelControllerName = commonModelControllerName; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } }
922fa4039018f734546b4717ff10edd61af179a8
5,294
java
Java
src/edu/nyu/pqs/connectfour/ConnectFourModel.java
guangyuzh/connect-four
f4a58bbd0211fce3bcb2b5aabb59f9baf42ee4a3
[ "MIT" ]
1
2018-04-04T11:46:55.000Z
2018-04-04T11:46:55.000Z
src/edu/nyu/pqs/connectfour/ConnectFourModel.java
guangyuzh/connect-four
f4a58bbd0211fce3bcb2b5aabb59f9baf42ee4a3
[ "MIT" ]
null
null
null
src/edu/nyu/pqs/connectfour/ConnectFourModel.java
guangyuzh/connect-four
f4a58bbd0211fce3bcb2b5aabb59f9baf42ee4a3
[ "MIT" ]
null
null
null
30.425287
91
0.680582
995,189
package edu.nyu.pqs.connectfour; import edu.nyu.pqs.connectfour.grid.DropEffect; import edu.nyu.pqs.connectfour.player.ConnectFourPlayer; import edu.nyu.pqs.connectfour.player.ConnectFourPlayerFactory; import edu.nyu.pqs.connectfour.grid.ConnectFourGrid; import edu.nyu.pqs.connectfour.grid.ConnectFourGrid.Drop; import java.awt.Color; import java.util.LinkedList; import java.util.List; import static edu.nyu.pqs.connectfour.ConnectFourConfigs.*; /** * This is the model for the observer-listener design pattern. User can register/deregister * listeners to this model. * Evoked by the View, the model will call all listeners to perform actions like * start game, end game, etc. * The model mainly contains a list of listeners, list of players, game grid, * and game mode (single or double). The model can decide which player to play/drop * in a turn, update grid, and fire corresponding event according to the drop result. */ public class ConnectFourModel { private static ConnectFourModel model = new ConnectFourModel(); private List<ConnectFourListener> listeners = new LinkedList<ConnectFourListener>(); private boolean singleMode = false; private int turn = 0; private ConnectFourPlayer[] players = new ConnectFourPlayer[nPlayers]; private ConnectFourGrid grid; /** * singleton method * @return this.model */ public static ConnectFourModel getModel() { return model; } /** * Add the listener to the listeners list, if it hasn't been registered. * @param listener an implementation of Listener to be registered */ public void registerListener(ConnectFourListener listener) { if (listener == null) { throw new NullPointerException("Cannot register Null listener"); } if (!listeners.contains(listener)) { listeners.add(listener); } } /** * Remove the listener from the listeners list. * @param listener an implementation of Listener to be removed */ public void deregisterListener(ConnectFourListener listener) { if (listener == null) { throw new NullPointerException("Cannot register Null listener"); } listeners.remove(listener); } /** * Get all listeners of the model. * @return the list of listeners */ public List<ConnectFourListener> getListeners() { return listeners; } /** * @return the current Grid of the game */ public ConnectFourGrid getGrid() { return grid; } /** * Start the game, and notify all listeners to start the game */ public void startGame() { players[0] = ConnectFourPlayerFactory.getPlayer(false, 1); players[1] = ConnectFourPlayerFactory.getPlayer(singleMode, 2); grid = new ConnectFourGrid(); turn = 0; fireGameStartedEvent(); } /** * Set Model's mode to be single or double player * @param isSingle if the game is single mode or not */ public void setSingleMode(boolean isSingle) { singleMode = isSingle; } /** * Perform dropping at this column for manual player; * auto player may select other column later. * By selecting the drop button at this column: * For single mode: first apply drop for manual player1, if the drop doesn't * result in winning the game, or drops at a full column, then automatically * perform the opponent's drop; * For double mode: let this turn's player to drop. If this drop isn't at a full * column, change turn to its opponent. * @param column the column # of the drop JButton on the View */ public void drop(int column) { if (column >= nColumns || column < 0) { throw new IllegalArgumentException("column number should be [0, nColumns-1]"); } if (singleMode) { turn = 0; Drop drop1 = players[0].drop(column, grid); applyDropEffect(drop1); if (turn > 0 && drop1.getEffect() != DropEffect.WIN) { applyDropEffect(players[1].drop(column, grid)); } } else { Drop drop = players[turn].drop(column, grid); applyDropEffect(drop); } } private void applyDropEffect(Drop drop) { if (drop.getEffect() == DropEffect.COL_FULL) { fireColFullEvent(drop.getColumn()); return; } fireUpdateGridEvent(drop.getRow(), drop.getColumn(), drop.getColor()); turn = (turn + 1) % nPlayers; if (drop.getEffect() == DropEffect.DRAW) { fireDrawGameEvent(); } else if (drop.getEffect() == DropEffect.WIN) { fireWinGameEvent(drop.getColor()); } } private void fireGameStartedEvent() { for (ConnectFourListener listener : listeners) { listener.gameStarted(); } } private void fireColFullEvent(int column) { for (ConnectFourListener listener : listeners) { listener.colFull(column); } } private void fireDrawGameEvent() { for (ConnectFourListener listener : listeners) { listener.draw(); listener.gameover(); } } private void fireWinGameEvent(Color color) { for (ConnectFourListener listener : listeners) { listener.win(color); listener.gameover(); } } private void fireUpdateGridEvent(int row, int column, Color color) { for (ConnectFourListener listener : listeners) { listener.updateGrid(row, column, color); } } }
922fa51ee7cd8ef688ef44b344db6e97371bf396
1,524
java
Java
src/test/java/com/epam/ta/reportportal/core/item/impl/FinishTestItemHandlerAsyncImplTest.java
maartenjanvangool/service-api
444f182653655c5b80180dd3bfaaba3c0f27449b
[ "Apache-2.0" ]
null
null
null
src/test/java/com/epam/ta/reportportal/core/item/impl/FinishTestItemHandlerAsyncImplTest.java
maartenjanvangool/service-api
444f182653655c5b80180dd3bfaaba3c0f27449b
[ "Apache-2.0" ]
null
null
null
src/test/java/com/epam/ta/reportportal/core/item/impl/FinishTestItemHandlerAsyncImplTest.java
maartenjanvangool/service-api
444f182653655c5b80180dd3bfaaba3c0f27449b
[ "Apache-2.0" ]
null
null
null
33.866667
118
0.784777
995,190
package com.epam.ta.reportportal.core.item.impl; import com.epam.ta.reportportal.commons.ReportPortalUser; import com.epam.ta.reportportal.entity.project.ProjectRole; import com.epam.ta.reportportal.entity.user.UserRole; import com.epam.ta.reportportal.util.ReportingQueueService; import com.epam.ta.reportportal.ws.model.FinishTestItemRQ; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.amqp.core.AmqpTemplate; import static com.epam.ta.reportportal.ReportPortalUserUtil.getRpUser; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.verify; /** * @author Konstantin Antipin */ @ExtendWith(MockitoExtension.class) class FinishTestItemHandlerAsyncImplTest { @Mock AmqpTemplate amqpTemplate; @Mock ReportingQueueService reportingQueueService; @InjectMocks FinishTestItemHandlerAsyncImpl finishTestItemHandlerAsync; @Test void finishTestItem() { FinishTestItemRQ request = new FinishTestItemRQ(); ReportPortalUser user = getRpUser("test", UserRole.ADMINISTRATOR, ProjectRole.PROJECT_MANAGER, 1L); finishTestItemHandlerAsync.finishTestItem(user, user.getProjectDetails().get("test_project"), "123", request); verify(amqpTemplate).convertAndSend(any(), any(), any(), any()); verify(reportingQueueService).getReportingQueueKey(any()); } }
922fa571bd4079b4fc4fcf255824548770b1c872
787
java
Java
app/src/main/java/automotive/tum/de/routem/rest/RestInterface.java
Ivaylo-Dimitrov/RoutEm
0db7e48b48884766a8505292a0e25b3f962318e2
[ "Apache-2.0" ]
1
2018-03-04T09:39:07.000Z
2018-03-04T09:39:07.000Z
app/src/main/java/automotive/tum/de/routem/rest/RestInterface.java
Ivaylo-Dimitrov/RoutEm
0db7e48b48884766a8505292a0e25b3f962318e2
[ "Apache-2.0" ]
null
null
null
app/src/main/java/automotive/tum/de/routem/rest/RestInterface.java
Ivaylo-Dimitrov/RoutEm
0db7e48b48884766a8505292a0e25b3f962318e2
[ "Apache-2.0" ]
1
2018-03-04T09:39:52.000Z
2018-03-04T09:39:52.000Z
32.791667
168
0.720457
995,191
package automotive.tum.de.routem.rest; import java.util.ArrayList; import automotive.tum.de.routem.models.Route; import retrofit.Callback; import retrofit.http.GET; import retrofit.http.Path; import retrofit.http.Query; /** * Created by H1GHWAvE on 2/8/15. */ public interface RestInterface { @GET("/RouteManager/getRoutes?{param}") ArrayList getRouteFiltered(@Path("param") String param); @GET("/RouteManager/getRoutes") ArrayList<Route> getRoutes(@Query("lat") float lat, @Query("lon") float lon, @Query("radius") int radius, @Query("type") String type); @GET("/RouteManager/getRoutes") void getRoutesAsync(@Query("lat") float lat, @Query("lon") float lon, @Query("radius") int radius, @Query("type") String type, Callback<ArrayList<Route>> callback); }
922fa63b6f9b5ebf760f093b37e4a2d8ab6c6428
3,397
java
Java
segmentstore/server/src/main/java/io/pravega/segmentstore/server/reading/ReadIndexConfig.java
Prabhaker24/pravega
7645bb013a833ea6da74e7404d5e9f0813615aeb
[ "Apache-2.0" ]
1
2021-03-19T16:36:03.000Z
2021-03-19T16:36:03.000Z
segmentstore/server/src/main/java/io/pravega/segmentstore/server/reading/ReadIndexConfig.java
Prabhaker24/pravega
7645bb013a833ea6da74e7404d5e9f0813615aeb
[ "Apache-2.0" ]
4
2020-07-28T01:55:34.000Z
2020-07-29T06:22:15.000Z
segmentstore/server/src/main/java/io/pravega/segmentstore/server/reading/ReadIndexConfig.java
Prabhaker24/pravega
7645bb013a833ea6da74e7404d5e9f0813615aeb
[ "Apache-2.0" ]
1
2019-06-26T16:07:11.000Z
2019-06-26T16:07:11.000Z
39.5
172
0.726818
995,193
/** * Copyright (c) Dell Inc., or its subsidiaries. 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 */ package io.pravega.segmentstore.server.reading; import io.pravega.common.util.ConfigBuilder; import io.pravega.common.util.ConfigurationException; import io.pravega.common.util.Property; import io.pravega.common.util.TypedProperties; import java.time.Duration; import lombok.Getter; /** * Configuration for Read Index. */ public class ReadIndexConfig { //region Config Names public static final Property<Integer> STORAGE_READ_ALIGNMENT = Property.named("storageRead.alignment", 1024 * 1024, "storageReadAlignment"); public static final Property<Integer> MEMORY_READ_MIN_LENGTH = Property.named("memoryRead.length.min", 4 * 1024, "memoryReadMinLength"); public static final Property<Integer> STORAGE_READ_DEFAULT_TIMEOUT = Property.named("storageRead.timeout.default.millis", 30 * 1000, "storageReadDefaultTimeoutMillis"); private static final String COMPONENT_CODE = "readindex"; //endregion //region Members /** * A value to align all Storage Reads to. When a Storage Read is issued, the read length is adjusted (if possible) * to end on a multiple of this value. */ @Getter private final int storageReadAlignment; /** * The minimum number of bytes to serve from memory during reads. The ReadIndex will try to coalesce data from multiple * contiguous index entries, as long as they are all referring to cached data, when serving individual ReadResultEntries * from the ReadResult coming from a call to read(). There is no guarantee that all entries will be at least of this * size, nor that they will be exactly of this size (it is just an attempt at optimization). * <p> * This is most effective in cases when there is a large number of very small appends, which would otherwise be * returned as individual ReadResultEntries - this setting allows coalescing multiple such items into a single call. * <p> * Setting this to 0 will effectively disable this feature. */ @Getter private final int memoryReadMinLength; /** * The Default Timeout (should no other value be provided) for Storage reads. */ @Getter private final Duration storageReadDefaultTimeout; //endregion //region Constructor /** * Creates a new instance of the ReadIndexConfig class. * * @param properties The TypedProperties object to read Properties from. */ private ReadIndexConfig(TypedProperties properties) throws ConfigurationException { this.storageReadAlignment = properties.getInt(STORAGE_READ_ALIGNMENT); this.memoryReadMinLength = properties.getInt(MEMORY_READ_MIN_LENGTH); this.storageReadDefaultTimeout = Duration.ofMillis(properties.getInt(STORAGE_READ_DEFAULT_TIMEOUT)); } /** * Creates a new ConfigBuilder that can be used to create instances of this class. * * @return A new Builder for this class. */ public static ConfigBuilder<ReadIndexConfig> builder() { return new ConfigBuilder<>(COMPONENT_CODE, ReadIndexConfig::new); } //endregion }
922fa70809cbaf6eb7301680d15ce4aca0ae5c78
1,512
java
Java
qafe-mobile-gwt/src/main/java/com/qualogy/qafe/mgwt/server/event/assembler/ToggleEventRenderer.java
qafedev/qafe-platform
629528cc86408e865a02a9a066e9214b66ab518b
[ "Apache-2.0" ]
2
2016-05-19T02:27:37.000Z
2017-01-16T08:38:48.000Z
qafe-mobile-gwt/src/main/java/com/qualogy/qafe/mgwt/server/event/assembler/ToggleEventRenderer.java
qafedev/qafe-platform
629528cc86408e865a02a9a066e9214b66ab518b
[ "Apache-2.0" ]
1
2016-06-01T07:50:20.000Z
2016-06-01T07:50:20.000Z
qafe-mobile-gwt/src/main/java/com/qualogy/qafe/mgwt/server/event/assembler/ToggleEventRenderer.java
qafedev/qafe-platform
629528cc86408e865a02a9a066e9214b66ab518b
[ "Apache-2.0" ]
3
2016-03-09T00:08:02.000Z
2018-07-10T16:08:41.000Z
37.8
129
0.780423
995,194
/** * Copyright 2008-2017 Qualogy Solutions B.V. * * 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.qualogy.qafe.mgwt.server.event.assembler; import com.qualogy.qafe.bind.core.application.ApplicationContext; import com.qualogy.qafe.bind.presentation.event.EventItem; import com.qualogy.qafe.bind.presentation.event.function.Toggle; import com.qualogy.qafe.mgwt.client.vo.data.EventDataGVO; import com.qualogy.qafe.mgwt.client.vo.functions.BuiltInFunctionGVO; import com.qualogy.qafe.mgwt.client.vo.functions.ToggleGVO; import com.qualogy.qafe.web.util.SessionContainer; public class ToggleEventRenderer extends AbstractEventRenderer implements EventAssembler{ public BuiltInFunctionGVO convert(EventItem eventItem, EventDataGVO eventData,ApplicationContext context, SessionContainer sc) { BuiltInFunctionGVO bif = null; if (eventItem instanceof Toggle) { ToggleGVO toggle = new ToggleGVO(); bif = toggle; fillIn(eventItem, toggle, eventData); } return bif; } }
922fa7cc7584947560db8e0b6085a3168c8a0e8b
981
java
Java
adapter/persistence/src/main/java/com/report/adapter/persistence/repository/SwapiRepository.java
koksyn/hexagonal-java-report-generator
29f1a30274c5faf7f84c21559ea8ec40f77216b4
[ "MIT" ]
2
2020-03-29T19:11:54.000Z
2022-03-02T02:37:53.000Z
adapter/persistence/src/main/java/com/report/adapter/persistence/repository/SwapiRepository.java
koksyn/hexagonal-java-report-generator
29f1a30274c5faf7f84c21559ea8ec40f77216b4
[ "MIT" ]
null
null
null
adapter/persistence/src/main/java/com/report/adapter/persistence/repository/SwapiRepository.java
koksyn/hexagonal-java-report-generator
29f1a30274c5faf7f84c21559ea8ec40f77216b4
[ "MIT" ]
2
2020-02-07T19:19:03.000Z
2021-01-03T19:15:12.000Z
31.645161
92
0.759429
995,195
package com.report.adapter.persistence.repository; import com.report.application.domain.vo.CharacterPhrase; import com.report.application.domain.vo.PlanetName; import com.report.application.dto.FilmCharacterRecord; import lombok.NonNull; import lombok.RequiredArgsConstructor; import java.util.List; @RequiredArgsConstructor public class SwapiRepository implements com.report.application.port.driven.SwapiRepository { private final SwapiNativeRepository swapiNativeRepository; @Override public void deleteSwapiData() { swapiNativeRepository.cleanSwapiTables(); } @Override public List<FilmCharacterRecord> getFilmCharacterRecordsThatMeetTheCriteria( @NonNull PlanetName planetName, @NonNull CharacterPhrase characterPhrase ) { return swapiNativeRepository.findAllByPlanetNameAndCharacterNameThatContainsPhrase( planetName.getRaw(), characterPhrase.getRaw() ); } }
922fa834adb884fb91d45f8e13ee4c85f92509be
2,703
java
Java
app/src/main/java/com/akexorcist/cameraapi/MainActivity.java
oaunkun1/CountCoin
82b6d09da60719144c8f50445962f9662a7a82e8
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/akexorcist/cameraapi/MainActivity.java
oaunkun1/CountCoin
82b6d09da60719144c8f50445962f9662a7a82e8
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/akexorcist/cameraapi/MainActivity.java
oaunkun1/CountCoin
82b6d09da60719144c8f50445962f9662a7a82e8
[ "Apache-2.0" ]
null
null
null
30.370787
140
0.657418
995,196
package com.akexorcist.cameraapi; import android.Manifest; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.Button; import android.widget.Toast; import com.akexorcist.cameraapi.v1.CameraV1Activity; import com.akexorcist.cameraapi.v2.CoinActivity; import com.karumi.dexter.Dexter; import com.karumi.dexter.MultiplePermissionsReport; import com.karumi.dexter.PermissionToken; import com.karumi.dexter.listener.PermissionRequest; import com.karumi.dexter.listener.multi.MultiplePermissionsListener; import org.opencv.android.OpenCVLoader; import java.util.List; public class MainActivity extends AppCompatActivity { private Button button; private Button btnCameraApiV1; private Button btnActivity2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button =(Button) findViewById(R.id.btnActivity2); button.setOnClickListener(v -> openActivity2()); bindView(); setupView(); checkCameraPermission(); OpenCVLoader.initDebug(); } private void checkCameraPermission() { Dexter.withActivity(this) .withPermissions(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE) .withListener(new MultiplePermissionsListener() { @Override public void onPermissionsChecked(MultiplePermissionsReport report) { if (report.areAllPermissionsGranted()) { // Do something } else { Toast.makeText(MainActivity.this, R.string.camera_and_write_external_storage_denied, Toast.LENGTH_SHORT).show(); } } @Override public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) { token.continuePermissionRequest(); } }) .check(); } private void bindView() { btnCameraApiV1 = findViewById(R.id.btnCameraApiV1); btnActivity2 = findViewById(R.id.btnActivity2); } private void setupView() { btnCameraApiV1.setOnClickListener(view -> openActivity(CameraV1Activity.class)); } private void openActivity(Class<?> cls) { startActivity(new Intent(this, cls)); } public void openActivity2 (){ Intent intent = new Intent(this, CoinActivity.class); startActivity(intent); } }
922fa8ed1d5bbaf7ca2924566a43a3620a1f93fa
73
java
Java
sfm-map/src/main/java/org/simpleflatmapper/map/context/Key.java
zenios/SimpleFlatMapper
6e99418efcf72551eb9d2222fc3197cbc9168ec0
[ "MIT" ]
416
2015-01-05T21:21:35.000Z
2022-03-17T21:19:46.000Z
sfm-map/src/main/java/org/simpleflatmapper/map/context/Key.java
tanbinh123/SimpleFlatMapper
fbc08180307ae9ad1a5343bafc5575bd9ad66c38
[ "MIT" ]
651
2015-01-06T11:00:12.000Z
2022-01-21T23:18:17.000Z
sfm-map/src/main/java/org/simpleflatmapper/map/context/Key.java
tanbinh123/SimpleFlatMapper
fbc08180307ae9ad1a5343bafc5575bd9ad66c38
[ "MIT" ]
83
2015-02-15T00:41:52.000Z
2022-03-10T17:59:33.000Z
14.6
41
0.794521
995,197
package org.simpleflatmapper.map.context; public abstract class Key { }
922fa9dc8a6ed5eda39f703347d6999535f9dddc
9,650
java
Java
sources/qub/ChildProcessParameters.java
danschultequb/lib-java
16388bc5fab273209762484c396178c131141324
[ "MIT" ]
null
null
null
sources/qub/ChildProcessParameters.java
danschultequb/lib-java
16388bc5fab273209762484c396178c131141324
[ "MIT" ]
198
2018-01-30T20:45:34.000Z
2019-07-16T04:07:44.000Z
sources/qub/ChildProcessParameters.java
danschultequb/qub-java
e4d22f5cc6567ad76061a25edb40ba051c546974
[ "MIT" ]
null
null
null
36.97318
110
0.691917
995,198
package qub; /** * Parameters that can be specified to alter how an executable will be run. */ public interface ChildProcessParameters { /** * Create a new ExecutableParameters object. * @return The new ExecutableParameters object. */ static ChildProcessParameters create(String executablePath, String... arguments) { PreCondition.assertNotNullAndNotEmpty(executablePath, "executablePath"); PreCondition.assertNotNull(arguments, "arguments"); return ChildProcessParameters.create(Path.parse(executablePath), arguments); } /** * Create a new ExecutableParameters object. * @return The new ExecutableParameters object. */ static ChildProcessParameters create(String executablePath, Iterable<String> arguments) { PreCondition.assertNotNullAndNotEmpty(executablePath, "executablePath"); PreCondition.assertNotNull(arguments, "arguments"); return ChildProcessParameters.create(Path.parse(executablePath), arguments); } /** * Create a new ExecutableParameters object. * @return The new ExecutableParameters object. */ static ChildProcessParameters create(Path executablePath, String... arguments) { PreCondition.assertNotNull(executablePath, "executablePath"); PreCondition.assertNotNull(arguments, "arguments"); return ChildProcessParameters.create(executablePath, Iterable.create(arguments)); } /** * Create a new ExecutableParameters object. * @return The new ExecutableParameters object. */ static ChildProcessParameters create(Path executablePath, Iterable<String> arguments) { PreCondition.assertNotNull(executablePath, "executablePath"); PreCondition.assertNotNull(arguments, "arguments"); return BasicChildProcessParameters.create(executablePath, arguments); } /** * Create a new ExecutableParameters object. * @return The new ExecutableParameters object. */ static ChildProcessParameters create(File executableFile, String... arguments) { PreCondition.assertNotNull(executableFile, "executableFile"); PreCondition.assertNotNull(arguments, "arguments"); return ChildProcessParameters.create(executableFile.getPath(), arguments); } /** * Create a new ExecutableParameters object. * @return The new ExecutableParameters object. */ static ChildProcessParameters create(File executableFile, Iterable<String> arguments) { PreCondition.assertNotNull(executableFile, "executableFile"); PreCondition.assertNotNull(arguments, "arguments"); return ChildProcessParameters.create(executableFile.getPath(), arguments); } /** * Get the path to the executable to run. * @return The path to the executable to run. */ Path getExecutablePath(); /** * Get the command-line arguments that will be passed to the executable. * @return The command-line arguments that will be passed to the executable. */ Iterable<String> getArguments(); /** * Insert the provided argument into the list of command-line arguments at the provided index. * @param index The index at which to insert the provided argument. * @param argument The argument to insert. * @return This object for method chaining. */ ChildProcessParameters insertArgument(int index, String argument); /** * Add the provided argument to the list of command-line arguments that will be passed to the * executable. * @param argument The argument to add. * @return This object for method chaining. */ default ChildProcessParameters addArgument(String argument) { return this.insertArgument(this.getArguments().getCount(), argument); } /** * Add the provided arguments to the list of command-line arguments that will be passed to the executable. * @param arguments The arguments to add. * @return This object for method chaining. */ default ChildProcessParameters addArguments(String... arguments) { PreCondition.assertNotNull(arguments, "arguments"); for (final String argument : arguments) { this.addArgument(argument); } return this; } /** * Add the provided arguments to the list of command-line arguments that will be passed to the executable. * @param arguments The arguments to add. * @return This object for method chaining. */ default ChildProcessParameters addArguments(Iterable<String> arguments) { PreCondition.assertNotNull(arguments, "arguments"); for (final String argument : arguments) { this.addArgument(argument); } return this; } /** * Get the working folder path that the executable should be run in, or null if no working * folder path has been specified. * @return The working folder path that the executable should be run in, or null if no working * folder path has been specified. */ Path getWorkingFolderPath(); /** * Set the working folder path that the executable should be run in. * @param workingFolderPath The working folder path that the executable should be run in. * @return This object for method chaining. */ default ChildProcessParameters setWorkingFolderPath(String workingFolderPath) { PreCondition.assertNotNullAndNotEmpty(workingFolderPath, "workingFolderPath"); return this.setWorkingFolderPath(Path.parse(workingFolderPath)); } /** * Set the working folder path that the executable should be run in. * @param workingFolderPath The working folder path that the executable should be run in. * @return This object for method chaining. */ ChildProcessParameters setWorkingFolderPath(Path workingFolderPath); /** * Set the working folder that the executable should be run in. * @param workingFolder The working folder that the executable should be run in. * @return This object for method chaining. */ default ChildProcessParameters setWorkingFolder(Folder workingFolder) { PreCondition.assertNotNull(workingFolder, "workingFolder"); return this.setWorkingFolderPath(workingFolder.getPath()); } /** * Get the input stream that the executable should read from. * @return The input stream that the executable should read from. */ ByteReadStream getInputStream(); /** * Set the input stream that the executable should read from. * @param inputStream The input stream that the executable should read from. * @return This object for method chaining. */ ChildProcessParameters setInputStream(ByteReadStream inputStream); /** * Get the function that will be invoked to handle the output stream from the executable, or * null if no handler has been assigned. * @return The function that will be invoked to handle the output stream from the executable, * or null if no handler has been assigned. */ Action1<ByteReadStream> getOutputStreamHandler(); /** * Set the function that will be invoked to handle the output stream from the executable. * @param outputStreamHandler The function that will be invoked to handle the output stream * from the executable. * @return This object for method chaining. */ ChildProcessParameters setOutputStreamHandler(Action1<ByteReadStream> outputStreamHandler); /** * Redirect any bytes written to the child process's output stream to the provided outputStream. * @param outputStream The output stream that the child process's output stream will be written * to. * @return This object for method chaining. */ default ChildProcessParameters redirectOutputTo(ByteWriteStream outputStream) { PreCondition.assertNotNull(outputStream, "outputStream"); return this.setOutputStreamHandler((ByteReadStream childProcessOutputStream) -> { outputStream.writeAll(childProcessOutputStream).await(); }); } /** * Get the function that will be invoked to handle the error stream from the executable, or * null if no handler has been assigned. * @return The function that will be invoked to handle the error stream from the executable, or * null if no handler has been assigned. */ Action1<ByteReadStream> getErrorStreamHandler(); /** * Set the function that will be invoked to handle the error stream from the executable. * @param errorStreamHandler The function that will be invoked to handle the error stream from * the executable. * @return This object for method chaining. */ ChildProcessParameters setErrorStreamHandler(Action1<ByteReadStream> errorStreamHandler); /** * Redirect any bytes written to the child process's error stream to the provided errorStream. * @param errorStream The error stream that the child process's error stream will be written * to. * @return This object for method chaining. */ default ChildProcessParameters redirectErrorTo(ByteWriteStream errorStream) { PreCondition.assertNotNull(errorStream, "errorStream"); return this.setErrorStreamHandler((ByteReadStream childProcessErrorStream) -> { errorStream.writeAll(childProcessErrorStream).await(); }); } }
922faa2403960d0d498f953f7c020c9f859e6dea
1,027
java
Java
src/test/java/com/murilo/jumia/model/UgandaPhoneTests.java
MuriloCarraro/Jumia-Phone-Numbers
aa8662350a7f5894057538f3c168f938335ef781
[ "MIT" ]
null
null
null
src/test/java/com/murilo/jumia/model/UgandaPhoneTests.java
MuriloCarraro/Jumia-Phone-Numbers
aa8662350a7f5894057538f3c168f938335ef781
[ "MIT" ]
null
null
null
src/test/java/com/murilo/jumia/model/UgandaPhoneTests.java
MuriloCarraro/Jumia-Phone-Numbers
aa8662350a7f5894057538f3c168f938335ef781
[ "MIT" ]
null
null
null
34.233333
107
0.649464
995,199
package com.murilo.jumia.model; import com.murilo.jumia.model.constants.CountryCode; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; class UgandaPhoneTests { private final int min = 100000000; private final int max = 999999999; @Test void validPhoneTest() { for (int i = 0; i < 50; i++) { Integer randomPhoneInt = (int)(Math.random() * max + min); String randomPhone = randomPhoneInt.toString(); boolean isValid = randomPhone.length() == 9; BasicPhone phone = new UgandaPhone().setPhoneNumber("("+ CountryCode.UGANDA+")" + randomPhone); assertEquals(phone.isValid(), isValid); assertEquals(phone.getFormattedPhoneNumber(), randomPhone); phone = new UgandaPhone().setPhoneNumber("("+ CountryCode.UGANDA+")" + randomPhone); assertEquals(phone.isValid(), isValid); assertEquals(phone.getFormattedPhoneNumber(), randomPhone); } } }
922faadb478ee721698084822e41a115cd993e7c
1,784
java
Java
app/src/main/java/com/akseltorgard/steganography/async/EncodeTask.java
torgard/Steganography.xyz
3c4e2417c79ccd7f67611c5e45f7f942caab5681
[ "MIT" ]
4
2018-08-27T12:27:07.000Z
2021-01-04T19:56:50.000Z
app/src/main/java/com/akseltorgard/steganography/async/EncodeTask.java
torgard/Steganography.xyz
3c4e2417c79ccd7f67611c5e45f7f942caab5681
[ "MIT" ]
4
2019-02-03T18:48:18.000Z
2021-04-12T09:57:29.000Z
app/src/main/java/com/akseltorgard/steganography/async/EncodeTask.java
torgard/Steganography.xyz
3c4e2417c79ccd7f67611c5e45f7f942caab5681
[ "MIT" ]
6
2019-02-01T18:01:29.000Z
2021-09-18T14:23:03.000Z
33.660377
90
0.715807
995,200
package com.akseltorgard.steganography.async; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import com.akseltorgard.steganography.utils.BitmapUtils; import com.akseltorgard.steganography.utils.FileUtils; import com.akseltorgard.steganography.utils.SteganographyUtils; import static com.akseltorgard.steganography.utils.FileUtils.saveBitmap; public class EncodeTask extends SteganographyTask { public EncodeTask(AsyncResponse<SteganographyParams> delegate) { super(delegate); } /** * Encodes an image with the specified message, and saves it. * @param steganographyParams Contains filepath to image, and specified message * @return Contains filepath to encoded image. */ @Override protected SteganographyParams execute(SteganographyParams steganographyParams) { Bitmap bitmap = BitmapUtils.decodeFile(steganographyParams.getFilePath()); int w = bitmap.getWidth(); int h = bitmap.getHeight(); int numberOfPixels = w * h; byte[] data = steganographyParams.getMessage().getBytes(); int requiredLength = data.length * 8 + 32; if (requiredLength > numberOfPixels) { throw new IllegalArgumentException("Message is too long to fit into pixels."); } int[] encodedPixels = SteganographyUtils.encode( BitmapUtils.getPixels(bitmap, requiredLength), steganographyParams.getMessage() ); BitmapUtils.setPixels(bitmap, encodedPixels); Uri resultUri = FileUtils.saveBitmap(bitmap); steganographyParams.setResultUri(resultUri); steganographyParams.setType(AsyncResponse.Type.ENCODE_SUCCESS); return steganographyParams; } }
922fab53449ed909ce98eed3ebd8cc699297a761
65,829
java
Java
src/main/java/com/progenia/sigdep01_01/dialogs/EditerProprietaireDialog.java
jdissou/sigdep01_01
298070a36bd0bf8f00ad371efc716a02fedf25c0
[ "Unlicense" ]
null
null
null
src/main/java/com/progenia/sigdep01_01/dialogs/EditerProprietaireDialog.java
jdissou/sigdep01_01
298070a36bd0bf8f00ad371efc716a02fedf25c0
[ "Unlicense" ]
null
null
null
src/main/java/com/progenia/sigdep01_01/dialogs/EditerProprietaireDialog.java
jdissou/sigdep01_01
298070a36bd0bf8f00ad371efc716a02fedf25c0
[ "Unlicense" ]
null
null
null
54.002461
431
0.666682
995,201
/* * 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 com.progenia.sigdep01_01.dialogs; import com.progenia.sigdep01_01.data.business.*; import com.progenia.sigdep01_01.data.entity.*; import com.progenia.sigdep01_01.securities.services.SecurityService; import com.progenia.sigdep01_01.utilities.MessageDialogHelper; import com.progenia.sigdep01_01.utilities.ModeFormulaireEditerEnum; import com.vaadin.flow.component.*; import com.vaadin.flow.component.button.Button; import com.vaadin.flow.component.checkbox.Checkbox; import com.vaadin.flow.component.combobox.ComboBox; import com.vaadin.flow.component.dialog.Dialog; import com.vaadin.flow.component.formlayout.FormLayout; import com.vaadin.flow.component.html.Label; import com.vaadin.flow.component.tabs.Tab; import com.vaadin.flow.component.tabs.Tabs; import com.vaadin.flow.component.tabs.TabsVariant; import com.vaadin.flow.data.binder.BeanValidationBinder; import com.vaadin.flow.data.provider.DataProvider; import com.vaadin.flow.data.provider.ListDataProvider; import com.vaadin.flow.data.provider.SortDirection; import com.vaadin.flow.server.VaadinSession; import org.vaadin.miki.superfields.text.SuperTextField; import org.vaadin.spring.events.EventBus; import org.vaadin.spring.events.annotation.EventBusListenerMethod; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; /** * * @author Jamâl-Dine DISSOU */ public class EditerProprietaireDialog extends BaseEditerReferentielMaitreTabDialog<Proprietaire> { /*** * EditerProprietaireDialog is responsible for launch Dialog. * We make this a singleton class by creating a private constructor, * and returning a static instance in a getInstance() method. */ /* We make this view a reusable component that work in the same way as any Vaadin component : so, we can use it anywhere. We configure the component by setting properties, and the component notifies us of events through listeners. Creating a reusable component is as simple as making sure it can be configured through : setters, and that it fires events whenever something happens. Using the component should not have side effects, for instance it shouldn’t change anything in the database by itself. */ private static final String CACHED_SELECTED_TAB_INDEX = "EditerProprietaireDialogSelectedTab"; //CIF private CompteBusiness compteBusiness; private ArrayList<Compte> compteList = new ArrayList<Compte>(); private ListDataProvider<Compte> compteDataProvider; //CIF private JournalBusiness journalBusiness; private ArrayList<ZZZJournal> journalList = new ArrayList<ZZZJournal>(); private ListDataProvider<ZZZJournal> journalDataProvider; //Tabs private Tab tabInfoGenerale = new Tab(); private FormLayout tabInfoGeneraleFormLayout = new FormLayout(); private Tab tabQualification = new Tab(); private FormLayout tabQualificationFormLayout = new FormLayout(); /* Fields to edit properties in Proprietaire entity */ //Contrôles de tabInfoGenerale private SuperTextField txtCodeProprietaire = new SuperTextField(); private SuperTextField txtLibelleProprietaire = new SuperTextField(); private SuperTextField txtLibelleCourtProprietaire = new SuperTextField(); private SuperTextField txtAdresse = new SuperTextField(); private SuperTextField txtVille = new SuperTextField(); private SuperTextField txtNoTelephone = new SuperTextField(); private SuperTextField txtNoMobile = new SuperTextField(); private SuperTextField txtEmail = new SuperTextField(); private SuperTextField txtNoIFU = new SuperTextField(); private Checkbox chkInactif = new Checkbox(); //Contrôles de tabQualification private ComboBox<Compte> cboNoCompteTresorerie = new ComboBox<>(); //private ComboBox<Compte> cboNoCompteTresorerie = new ComboBox<>("N° Compte Trésorerie"); private ComboBox<Compte> cboNoCompteTVALoyer = new ComboBox<>(); //private ComboBox<Compte> cboNoCompteTVALoyer = new ComboBox<>("N° Compte TVA sur Loyer"); private ComboBox<Compte> cboNoCompteTVADepense = new ComboBox<>(); //private ComboBox<Compte> cboNoCompteTVADepense = new ComboBox<>("CompteTVADepense"); private ComboBox<ZZZJournal> cboCodeJournalLoyer = new ComboBox<>(); //private ComboBox<ZZZJournal> cboCodeJournalLoyer = new ComboBox<>("ZZZJournal des Loyers"); private ComboBox<ZZZJournal> cboCodeJournalDepense = new ComboBox<>(); //private ComboBox<ZZZJournal> cboCodeJournalDepense = new ComboBox<>("Code ZZZJournal Dépenses"); public EditerProprietaireDialog() { //Cette méthode contient les instructions pour créer les composants super(); this.binder = new BeanValidationBinder<>(Proprietaire.class); this.configureComponents(); } public static EditerProprietaireDialog getInstance() { try { if (VaadinSession.getCurrent().getAttribute(EditerProprietaireDialog.class) == null) { //Register an instance - We use this registre as a CACHE, i.e we store it only once VaadinSession.getCurrent().setAttribute(EditerProprietaireDialog.class, new EditerProprietaireDialog()); } return (EditerProprietaireDialog)(VaadinSession.getCurrent().getAttribute(EditerProprietaireDialog.class)); } catch (Exception e) { MessageDialogHelper.showAlertDialog("EditerProprietaireDialog.getInstance", e.toString()); e.printStackTrace(); return null; } } //public static EditerProprietaireDialog getInstance() { // Show Dialog public void showDialog(String dialogTitle, ModeFormulaireEditerEnum modeFormulaireEditerEnum, ArrayList<Proprietaire> targetBeanList, ArrayList<Proprietaire> referenceBeanList, String newComboValue, EventBus.UIEventBus uiEventBus, CompteBusiness compteBusiness, JournalBusiness journalBusiness) { //Cette méthode contient les instructions ad hoc try { //1- Initialisation des paramètres passés this.customSetDialogTitle(dialogTitle); this.customSetModeFormulaireEditer(modeFormulaireEditerEnum); this.customSetReferenceBeanList(referenceBeanList); if (this.modeFormulaireEditer == ModeFormulaireEditerEnum.AJOUTERCIF) { this.customSetNewComboValue(newComboValue); } this.uiEventBus = uiEventBus; this.compteBusiness = compteBusiness; this.journalBusiness = journalBusiness; this.uiEventBus.subscribe(this, false);//Use false as the second constructor parameter to indicate that the event does not come from the proprietaire //2- CIF this.compteList = (ArrayList)this.compteBusiness.findAll(); this.compteDataProvider = DataProvider.ofCollection(this.compteList); // Make the dataProvider sorted by NoCompte in ascending order this.compteDataProvider.setSortOrder(Compte::getNoCompte, SortDirection.ASCENDING); this.journalList = (ArrayList)this.journalBusiness.findAll(); this.journalDataProvider = DataProvider.ofCollection(this.journalList); // Make the dataProvider sorted by CodeJournal in ascending order this.journalDataProvider.setSortOrder(ZZZJournal::getCodeJournal, SortDirection.ASCENDING); //3- Setup ReadOnly Field Mode - Configure ReadOnly Field Set ComboBox DataProvider - Manage ToolBars this.customManageReadOnlyFieldMode(); this.configureReadOnlyField(); this.setComboBoxDataProvider(); this.customManageToolBars(); //4- Set up Target Bean - TargetBeanSet : cette instruction doit être exécutée avant l'exécution de Collections.sort(this.targetBeanList..... this.targetBeanList = targetBeanList; //5 - Make the this.targetBeanList sorted by CodeProprietaire in ascending order Collections.sort(this.targetBeanList, Comparator.comparing(Proprietaire::getCodeProprietaire)); //6- LoadFirstBean : cette instruction doit être exécutée après l'exécution de this.configureComponents() de façon à s'assurer de traiter les données une fois que les champs sont injectés this.customLoadFirstBean(); //7 - Open the dialog this.dialog.open(); } catch (Exception e) { MessageDialogHelper.showAlertDialog("EditerProprietaireDialog.showDialog", e.toString()); e.printStackTrace(); } } private void configureComponents() { //Associate the data with the formLayout columns and load the data. try { //1 - Set properties of the form this.tabs.addClassName("fichier-tab"); this.tabs.setOrientation(Tabs.Orientation.HORIZONTAL); this.tabs.setFlexGrowForEnclosedTabs(1); //Tabs covering the full width of the tab bar this.tabs.addThemeVariants(TabsVariant.LUMO_SMALL); this.tabs.setWidthFull(); this.tabInfoGenerale.setLabel("Informations Générales"); this.tabQualification.setLabel("Qualifications"); this.pages.setSizeFull(); //sets the form size to fill the screen. this.tabInfoGeneraleFormLayout.addClassName("fichier-form"); this.tabInfoGeneraleFormLayout.setSizeFull(); //sets the form size to fill the screen. this.tabInfoGeneraleFormLayout.setVisible(true); //At startup, set the first page visible, while the remaining are not this.tabQualificationFormLayout.addClassName("fichier-form"); this.tabQualificationFormLayout.setSizeFull(); //sets the form size to fill the screen. this.tabQualificationFormLayout.setVisible(false); //At startup, set the first page visible, while the remaining are not //2 - Define the Fields instances to use - We don't use .setLabel since we will use addFormItem instead of add to add items to the form - addFormItem allows us to set SuperTextField with on a FormaLayout when add doesn't //Contrôles de tabInfoGenerale this.txtCodeProprietaire.setWidth(150, Unit.PIXELS); //setWidth(100, Unit.PIXELS); this.txtCodeProprietaire.setRequired(true); this.txtCodeProprietaire.setRequiredIndicatorVisible(true); this.txtCodeProprietaire.addClassName(TEXTFIELD_LEFT_LABEL); this.txtLibelleProprietaire.setWidth(350, Unit.PIXELS); //setWidth(400, Unit.PIXELS); this.txtLibelleProprietaire.addClassName(TEXTFIELD_LEFT_LABEL); this.txtLibelleCourtProprietaire.setWidth(350, Unit.PIXELS); //setWidth(400, Unit.PIXELS); this.txtLibelleCourtProprietaire.addClassName(TEXTFIELD_LEFT_LABEL); this.txtAdresse.setWidth(350, Unit.PIXELS); this.txtAdresse.addClassName(TEXTFIELD_LEFT_LABEL); this.txtVille.setWidth(350, Unit.PIXELS); //setWidth(400, Unit.PIXELS); this.txtVille.addClassName(TEXTFIELD_LEFT_LABEL); this.txtNoTelephone.setWidth(150, Unit.PIXELS); //setWidth(400, Unit.PIXELS); this.txtNoTelephone.addClassName(TEXTFIELD_LEFT_LABEL); this.txtNoMobile.setWidth(150, Unit.PIXELS); this.txtNoMobile.addClassName(TEXTFIELD_LEFT_LABEL); this.txtEmail.setWidth(350, Unit.PIXELS); //setWidth(400, Unit.PIXELS); this.txtEmail.addClassName(TEXTFIELD_LEFT_LABEL); this.txtNoIFU.setWidth(350, Unit.PIXELS); //setWidth(400, Unit.PIXELS); this.txtNoIFU.addClassName(TEXTFIELD_LEFT_LABEL); this.chkInactif.setAutofocus(false); //Sepecific for isInactif //Contrôles de tabQualification this.cboNoCompteTresorerie.setWidth(150, Unit.PIXELS); //setWidth(400, Unit.PIXELS); this.cboNoCompteTresorerie.addClassName(COMBOBOX_LEFT_LABEL); // Choose which property from Compte is the presentation value this.cboNoCompteTresorerie.setItemLabelGenerator(Compte::getNoCompte); this.cboNoCompteTresorerie.setRequired(true); this.cboNoCompteTresorerie.setRequiredIndicatorVisible(true); //???this.cboNoCompteTresorerie.setLabel("Compte"); //???this.cboNoCompteTresorerie.setId("person"); this.cboNoCompteTresorerie.setClearButtonVisible(true); //Add Filtering this.cboNoCompteTresorerie.setAllowCustomValue(true); this.cboNoCompteTresorerie.setPreventInvalidInput(true); this.cboNoCompteTresorerie.addValueChangeListener(event -> { if (event.getValue() != null) { //BeforeUpdate NoCompteTresorerie (CIF): Contrôle de Inactif if (event.getValue().isInactif() == true) { MessageDialogHelper.showWarningDialog("Erreur de Saisie", "Le Compte de Trésorerie choisi est actuellement désactivé. Veuillez en saisir un autre."); //Cancel this.cboNoCompteTresorerie.setValue(event.getOldValue()); } //if (event.getValue() != null) { } }); /** * Allow users to enter a value which doesn't exist in the data set, and * set it as the value of the ComboBox. */ this.cboNoCompteTresorerie.addCustomValueSetListener(event -> { this.cboNoCompteTresorerie_NotInList(event.getDetail(), 11); }); this.cboNoCompteTVALoyer.setWidth(150, Unit.PIXELS); //setWidth(400, Unit.PIXELS); this.cboNoCompteTVALoyer.addClassName(COMBOBOX_LEFT_LABEL); // Choose which property from Compte is the presentation value this.cboNoCompteTVALoyer.setItemLabelGenerator(Compte::getNoCompte); this.cboNoCompteTVALoyer.setRequired(true); this.cboNoCompteTVALoyer.setRequiredIndicatorVisible(true); //???this.cboNoCompteTVALoyer.setLabel("CompteTVALoyer"); //???this.cboNoCompteTVALoyer.setId("person"); this.cboNoCompteTVALoyer.setClearButtonVisible(true); //Add Filtering this.cboNoCompteTVALoyer.setAllowCustomValue(true); this.cboNoCompteTVALoyer.setPreventInvalidInput(true); this.cboNoCompteTVALoyer.addValueChangeListener(event -> { if (event.getValue() != null) { //BeforeUpdate NoCompteTVALoyer (CIF): Contrôle de Inactif if (event.getValue().isInactif() == true) { MessageDialogHelper.showWarningDialog("Erreur de Saisie", "Le N° Compte TVA sur Loyer choisi est actuellement désactivé. Veuillez en saisir un autre."); //Cancel this.cboNoCompteTVALoyer.setValue(event.getOldValue()); } //if (event.getValue() != null) { } }); /** * Allow users to enter a value which doesn't exist in the data set, and * set it as the value of the ComboBox. */ this.cboNoCompteTVALoyer.addCustomValueSetListener(event -> { this.cboNoCompteTVALoyer_NotInList(event.getDetail(), 11); }); this.cboNoCompteTVADepense.setWidth(150, Unit.PIXELS); //setWidth(400, Unit.PIXELS); this.cboNoCompteTVADepense.addClassName(COMBOBOX_LEFT_LABEL); // Choose which property from Compte is the presentation value this.cboNoCompteTVADepense.setItemLabelGenerator(Compte::getNoCompte); this.cboNoCompteTVADepense.setRequired(true); this.cboNoCompteTVADepense.setRequiredIndicatorVisible(true); //???this.cboNoCompteTVADepense.setLabel("CompteTVADepense"); //???this.cboNoCompteTVADepense.setId("person"); this.cboNoCompteTVADepense.setClearButtonVisible(true); //Add Filtering this.cboNoCompteTVADepense.setAllowCustomValue(true); this.cboNoCompteTVADepense.setPreventInvalidInput(true); this.cboNoCompteTVADepense.addValueChangeListener(event -> { if (event.getValue() != null) { //BeforeUpdate NoCompteTVADepense (CIF): Contrôle de Inactif if (event.getValue().isInactif() == true) { MessageDialogHelper.showWarningDialog("Erreur de Saisie", "Le Compte de TVA sur Dépense choisi est actuellement désactivé. Veuillez en saisir une autre."); //Cancel this.cboNoCompteTVADepense.setValue(event.getOldValue()); } //if (event.getValue() != null) { } }); /** * Allow users to enter a value which doesn't exist in the data set, and * set it as the value of the ComboBox. */ this.cboNoCompteTVADepense.addCustomValueSetListener(event -> { this.cboNoCompteTVADepense_NotInList(event.getDetail(), 11); }); this.cboCodeJournalLoyer.setWidth(150, Unit.PIXELS); //setWidth(400, Unit.PIXELS); this.cboCodeJournalLoyer.addClassName(COMBOBOX_LEFT_LABEL); // Choose which property from ZZZJournal is the presentation value this.cboCodeJournalLoyer.setItemLabelGenerator(ZZZJournal::getCodeJournal); this.cboCodeJournalLoyer.setRequired(true); this.cboCodeJournalLoyer.setRequiredIndicatorVisible(true); //???this.cboCodeJournalLoyer.setLabel("JournalLoyer"); //???this.cboCodeJournalLoyer.setId("person"); this.cboCodeJournalLoyer.setClearButtonVisible(true); //Add Filtering this.cboCodeJournalLoyer.setAllowCustomValue(true); this.cboCodeJournalLoyer.setPreventInvalidInput(true); this.cboCodeJournalLoyer.addValueChangeListener(event -> { if (event.getValue() != null) { //BeforeUpdate CodeJournalLoyer (CIF): Contrôle de Inactif if (event.getValue().isInactif() == true) { MessageDialogHelper.showWarningDialog("Erreur de Saisie", "Le ZZZJournal de Loyer choisi est actuellement désactivé. Veuillez en saisir un autre."); //Cancel this.cboCodeJournalLoyer.setValue(event.getOldValue()); } //if (event.getValue() != null) { } }); /** * Allow users to enter a value which doesn't exist in the data set, and * set it as the value of the ComboBox. */ this.cboCodeJournalLoyer.addCustomValueSetListener(event -> { this.cboCodeJournalLoyer_NotInList(event.getDetail(), 6); }); this.cboCodeJournalDepense.setWidth(150, Unit.PIXELS); //setWidth(400, Unit.PIXELS); this.cboCodeJournalDepense.addClassName(COMBOBOX_LEFT_LABEL); // Choose which property from ZZZJournal is the presentation value this.cboCodeJournalDepense.setItemLabelGenerator(ZZZJournal::getCodeJournal); this.cboCodeJournalDepense.setRequired(true); this.cboCodeJournalDepense.setRequiredIndicatorVisible(true); //???this.cboCodeJournalDepense.setLabel("JournalDepense"); //???this.cboCodeJournalDepense.setId("person"); this.cboCodeJournalDepense.setClearButtonVisible(true); //Add Filtering this.cboCodeJournalDepense.setAllowCustomValue(true); this.cboCodeJournalDepense.setPreventInvalidInput(true); this.cboCodeJournalDepense.addValueChangeListener(event -> { if (event.getValue() != null) { //BeforeUpdate CodeJournalDepense (CIF): Contrôle de Inactif if (event.getValue().isInactif() == true) { MessageDialogHelper.showWarningDialog("Erreur de Saisie", "Le ZZZJournal de Dépense choisi est actuellement désactivé. Veuillez en saisir un autre."); //Cancel this.cboCodeJournalDepense.setValue(event.getOldValue()); } //if (event.getValue() != null) { } }); /** * Allow users to enter a value which doesn't exist in the data set, and * set it as the value of the ComboBox. */ this.cboCodeJournalDepense.addCustomValueSetListener(event -> { this.cboCodeJournalDepense_NotInList(event.getDetail(), 6); }); //3 - Bind Fields instances to use (Manual Data Binding) // Easily bind forms to beans and manage validation and buffering //To bind a component to read-only data, use a null value for the setter. Label lblCodeProprietaireValidationStatus = new Label(); this.binder.forField(this.txtCodeProprietaire) .asRequired("La Saisie du Code Propriétaire est Obligatoire. Veuillez saisir le Code Propriétaire.") .withValidator(text -> text != null && text.length() <= 2, "Code Propriétaire ne peut contenir au plus 2 caractères") .withValidationStatusHandler(status -> {lblCodeProprietaireValidationStatus.setText(status.getMessage().orElse("")); lblCodeProprietaireValidationStatus.setVisible(status.isError());}) .bind(Proprietaire::getCodeProprietaire, Proprietaire::setCodeProprietaire); Label lblLibelleProprietaireValidationStatus = new Label(); this.binder.forField(this.txtLibelleProprietaire) .withValidator(text -> text.length() <= 50, "Dénomination Propriétaire ne peut contenir au plus 50 caractères.") .withValidationStatusHandler(status -> {lblLibelleProprietaireValidationStatus.setText(status.getMessage().orElse("")); lblLibelleProprietaireValidationStatus.setVisible(status.isError());}) .bind(Proprietaire::getLibelleProprietaire, Proprietaire::setLibelleProprietaire); Label lblLibelleCourtProprietaireValidationStatus = new Label(); this.binder.forField(this.txtLibelleCourtProprietaire) .withValidator(text -> text.length() <= 20, "Dénomination Abrégée Propriétaire ne peut contenir au plus 20 caractères.") .withValidationStatusHandler(status -> {lblLibelleCourtProprietaireValidationStatus.setText(status.getMessage().orElse("")); lblLibelleCourtProprietaireValidationStatus.setVisible(status.isError());}) .bind(Proprietaire::getLibelleCourtProprietaire, Proprietaire::setLibelleCourtProprietaire); Label lblAdresseValidationStatus = new Label(); this.binder.forField(this.txtAdresse) .withValidator(text -> text.length() <= 200, "Adresse ne peut contenir au plus 200 caractères.") .withValidationStatusHandler(status -> {lblAdresseValidationStatus.setText(status.getMessage().orElse("")); lblAdresseValidationStatus.setVisible(status.isError());}) .bind(Proprietaire::getAdresse, Proprietaire::setAdresse); Label lblVilleValidationStatus = new Label(); this.binder.forField(this.txtVille) .withValidator(text -> text.length() <= 30, "Ville ne peut contenir au plus 30 caractères.") .withValidationStatusHandler(status -> {lblVilleValidationStatus.setText(status.getMessage().orElse("")); lblVilleValidationStatus.setVisible(status.isError());}) .bind(Proprietaire::getVille, Proprietaire::setVille); Label lblNoTelephoneValidationStatus = new Label(); this.binder.forField(this.txtNoTelephone) .withValidator(text -> text.length() <= 15, "N° Téléphone ne peut contenir au plus 15 caractères.") .withValidationStatusHandler(status -> {lblNoTelephoneValidationStatus.setText(status.getMessage().orElse("")); lblNoTelephoneValidationStatus.setVisible(status.isError());}) .bind(Proprietaire::getNoTelephone, Proprietaire::setNoTelephone); Label lblNoMobileValidationStatus = new Label(); this.binder.forField(this.txtNoMobile) .withValidator(text -> text.length() <= 15, "N° Mobile ne peut contenir au plus 15 caractères.") .withValidationStatusHandler(status -> {lblNoMobileValidationStatus.setText(status.getMessage().orElse("")); lblNoMobileValidationStatus.setVisible(status.isError());}) .bind(Proprietaire::getNoMobile, Proprietaire::setNoMobile); Label lblEmailValidationStatus = new Label(); this.binder.forField(this.txtEmail) .withValidator(text -> text.length() <= 100, "E-mail ne peut contenir au plus 100 caractères.") .withValidationStatusHandler(status -> {lblEmailValidationStatus.setText(status.getMessage().orElse("")); lblEmailValidationStatus.setVisible(status.isError());}) .bind(Proprietaire::getEmail, Proprietaire::setEmail); Label lblNoIFUValidationStatus = new Label(); this.binder.forField(this.txtNoIFU) .withValidator(text -> text.length() <= 20, "N° IFU ne peut contenir au plus 20 caractères.") .withValidationStatusHandler(status -> {lblNoIFUValidationStatus.setText(status.getMessage().orElse("")); lblNoIFUValidationStatus.setVisible(status.isError());}) .bind(Proprietaire::getNoIFU, Proprietaire::setNoIFU); this.binder.forField(this.chkInactif) .bind(Proprietaire::isInactif, Proprietaire::setInactif); Label lblCompteTresorerieValidationStatus = new Label(); this.binder.forField(this.cboNoCompteTresorerie) .asRequired("La Saisie du N° Compte Trésorerie est requise. Veuillez sélectionner un N° Compte Trésorerie") .bind(Proprietaire::getCompteTresorerie, Proprietaire::setCompteTresorerie); Label lblCompteTVALoyerValidationStatus = new Label(); this.binder.forField(this.cboNoCompteTVALoyer) .asRequired("La Saisie du N° Compte TVA sur Loyer est requise. Veuillez sélectionner un N° Compte TVA sur Loyer") .bind(Proprietaire::getCompteTVALoyer, Proprietaire::setCompteTVALoyer); Label lblCompteTVADepenseValidationStatus = new Label(); this.binder.forField(this.cboNoCompteTVADepense) .asRequired("La Saisie du N° Compte TVA sur Dépense est requise. Veuillez sélectionner un N° Compte TVA sur Dépense") .bind(Proprietaire::getCompteTVADepense, Proprietaire::setCompteTVADepense); Label lblJournalLoyerValidationStatus = new Label(); this.binder.forField(this.cboCodeJournalLoyer) .asRequired("La Saisie du ZZZJournal des Loyers est requise. Veuillez sélectionner un ZZZJournal des Loyers") .bind(Proprietaire::getJournalLoyer, Proprietaire::setJournalLoyer); Label lblJournalDepenseValidationStatus = new Label(); this.binder.forField(this.cboCodeJournalDepense) .asRequired("La Saisie du ZZZJournal des Dépenses est requise. Veuillez sélectionner un ZZZJournal des Dépenses") .bind(Proprietaire::getJournalDepense, Proprietaire::setJournalDepense); /* 3 - Alternative : Bind Fields instances that need validators manually and then bind all remaining fields using the bindInstanceFields method this.binder.bindInstanceFields(this.formLayout); //Automatic Data Binding //bindInstanceFields matches fields in Proprietaire and ProprietaireView based on their names. */ //4 - Add input fields to formLayout - We don't use .setLabel since we will use addFormItem instead of add to add items to the form - addFormItem allows us to set SuperTextField with on a FormaLayout when add doesn't //this.formLayout.add(this.txtCodeProprietaire, this.txtLibelleProprietaire, this.txtNomMandataire, this.txtNoTelephone, this.txtNoMobile, this.txtNoTelecopie, this.datDateNaissance, this.txtLieuNaissance, this.txtAdresse, this.txtVille, this.txtNombreHomme, this.txtNombreFemme, this.chkInactif, this.txtNoPieceIdentite, this.chkDeposant, this.chkEmprunteur, this.chkGarant, this.chkDirigeant, this.chkAdministrateur); //4 - Alternative this.tabInfoGeneraleFormLayout.addFormItem(this.txtCodeProprietaire, "Code Propriétaire :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabInfoGeneraleFormLayout.addFormItem(this.txtLibelleProprietaire, "Dénomination Proprietaire :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabInfoGeneraleFormLayout.addFormItem(this.txtLibelleCourtProprietaire, "Dénomination Abrégée :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabInfoGeneraleFormLayout.addFormItem(this.txtEmail, "E-mail :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabInfoGeneraleFormLayout.addFormItem(this.txtAdresse, "Adresse :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabInfoGeneraleFormLayout.addFormItem(this.txtVille, "Description Proprietaire :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabInfoGeneraleFormLayout.addFormItem(this.txtNoMobile, "N° Mobile :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabInfoGeneraleFormLayout.addFormItem(this.txtNoTelephone, "Responsable Proprietaire :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabInfoGeneraleFormLayout.addFormItem(this.txtNoIFU, "N° IFU :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabInfoGeneraleFormLayout.addFormItem(this.chkInactif, "Inactif :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabQualificationFormLayout.addFormItem(this.cboCodeJournalDepense, "Code ZZZJournal Dépenses :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabQualificationFormLayout.addFormItem(this.cboNoCompteTVADepense, "N° Compte TVA Dépense :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabQualificationFormLayout.addFormItem(this.cboCodeJournalLoyer, "ZZZJournal des Loyers :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabQualificationFormLayout.addFormItem(this.cboNoCompteTresorerie, "N° Compte Trésorerie :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabQualificationFormLayout.addFormItem(this.cboNoCompteTVALoyer, "N° Compte TVA sur Loyer :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); //5 - Making the Layout Responsive : Custom responsive layouting //breakpoint at 600px, with the label to the side. At resolutions lower than 600px, the label will be at the top and there is only 1 column. The form will show 2 columns if width is >= 600px tabInfoGeneraleFormLayout.setResponsiveSteps(new FormLayout.ResponsiveStep("0", 1, FormLayout.ResponsiveStep.LabelsPosition.TOP), new FormLayout.ResponsiveStep(PANEL_FLEX_BASIS, 2, FormLayout.ResponsiveStep.LabelsPosition.ASIDE)); /* //breakpoint at 600px, with the label to the side. At resolutions lower than 600px, the label will be at the top. In both cases there is only 1 column. tabInfoGeneraleFormLayout.setResponsiveSteps(new FormLayout.ResponsiveStep("0", 1, FormLayout.ResponsiveStep.LabelsPosition.TOP), new FormLayout.ResponsiveStep(PANEL_FLEX_BASIS, 1, FormLayout.ResponsiveStep.LabelsPosition.ASIDE)); */ this.tabQualificationFormLayout.setResponsiveSteps(new FormLayout.ResponsiveStep("0", 1, FormLayout.ResponsiveStep.LabelsPosition.TOP), new FormLayout.ResponsiveStep(PANEL_FLEX_BASIS, 2, FormLayout.ResponsiveStep.LabelsPosition.ASIDE)); /* //breakpoint at 600px, with the label to the side. At resolutions lower than 600px, the label will be at the top. In both cases there is only 1 column. this.tabQualificationFormLayout.setResponsiveSteps(new FormLayout.ResponsiveStep("0", 1, FormLayout.ResponsiveStep.LabelsPosition.TOP), new FormLayout.ResponsiveStep(PANEL_FLEX_BASIS, 1, FormLayout.ResponsiveStep.LabelsPosition.ASIDE)); */ //6 - Configure Tabs this.tabsToPages.put(this.tabInfoGenerale, this.tabInfoGeneraleFormLayout); this.tabsToPages.put(this.tabQualification, this.tabQualificationFormLayout); this.tabs.add(this.tabInfoGenerale, this.tabQualification); this.pages.add(this.tabInfoGeneraleFormLayout, this.tabQualificationFormLayout); //Configure OnSelectedTabChange this.tabs.addSelectedChangeListener(event -> { VaadinSession.getCurrent().setAttribute(CACHED_SELECTED_TAB_INDEX, this.tabs.getSelectedIndex()); this.showSelectedTab(); }); //Cache Selected Tab if (VaadinSession.getCurrent().getAttribute(CACHED_SELECTED_TAB_INDEX) == null) { VaadinSession.getCurrent().setAttribute(CACHED_SELECTED_TAB_INDEX, 0); } //First Page to show programmatically this.tabs.setSelectedIndex((int)VaadinSession.getCurrent().getAttribute(CACHED_SELECTED_TAB_INDEX)); //Pre-select tabs this.showSelectedTab(); } catch (Exception e) { MessageDialogHelper.showAlertDialog("EditerProprietaireDialog.configureComponents", e.toString()); e.printStackTrace(); } } private void showSelectedTab() { //Show Selected Tab try { Component selectedPage = this.tabsToPages.get(this.tabs.getSelectedTab()); this.tabsToPages.values().forEach(page -> page.setVisible(false)); selectedPage.setVisible(true); } catch (Exception e) { MessageDialogHelper.showAlertDialog("EditerProprietaireDialog.showSelectedTab", e.toString()); e.printStackTrace(); } } //private void showSelectedTab() { private void configureReadOnlyField() { try { this.txtCodeProprietaire.setReadOnly(this.isPrimaryKeyFieldReadOnly); this.txtLibelleProprietaire.setReadOnly(this.isContextualFieldReadOnly); this.txtLibelleCourtProprietaire.setReadOnly(this.isContextualFieldReadOnly); this.txtAdresse.setReadOnly(this.isContextualFieldReadOnly); this.txtVille.setReadOnly(this.isContextualFieldReadOnly); this.txtNoTelephone.setReadOnly(this.isContextualFieldReadOnly); this.txtNoMobile.setReadOnly(this.isContextualFieldReadOnly); this.txtEmail.setReadOnly(this.isContextualFieldReadOnly); this.txtNoIFU.setReadOnly(this.isContextualFieldReadOnly); this.chkInactif.setReadOnly(true); //Sepecific for isInactif this.cboNoCompteTresorerie.setReadOnly(this.isContextualFieldReadOnly); this.cboNoCompteTVALoyer.setReadOnly(this.isContextualFieldReadOnly); this.cboNoCompteTVADepense.setReadOnly(this.isContextualFieldReadOnly); this.cboCodeJournalLoyer.setReadOnly(this.isContextualFieldReadOnly); this.cboCodeJournalDepense.setReadOnly(this.isContextualFieldReadOnly); } catch (Exception e) { MessageDialogHelper.showAlertDialog("EditerProprietaireDialog.configureReadOnlyField", e.toString()); e.printStackTrace(); } } private void setComboBoxDataProvider() { //Set Combo Box DataProvider try { this.cboNoCompteTresorerie.setDataProvider(this.compteDataProvider); //this.cboNoCompteTresorerie.setItems(this.compteList); this.cboNoCompteTVALoyer.setDataProvider(this.compteDataProvider); //this.cboNoCompteTVALoyer.setItems(this.compteList); this.cboNoCompteTVADepense.setDataProvider(this.compteDataProvider); //this.cboNoCompteTVADepense.setItems(this.compteList); this.cboCodeJournalLoyer.setDataProvider(this.journalDataProvider); //this.cboCodeJournalLoyer.setItems(this.journalList); this.cboCodeJournalDepense.setDataProvider(this.journalDataProvider); //this.cboCodeJournalDepense.setItems(this.journalList); } catch (Exception e) { MessageDialogHelper.showAlertDialog("EditerProprietaireDialog.setComboBoxDataProvider", e.toString()); e.printStackTrace(); } } private void cboNoCompteTresorerie_NotInList(String strProposedVal, int intMaxFieldLength) { //Ajoute un nouveau Compte en entrant un libellé dans la zone de liste modifiable NoCompteTresorerie. String strNewVal = strProposedVal; try { if (SecurityService.getInstance().isAccessGranted("EditerCompteDialog") == true) { //Java Lambda Implementation of ComponentEventListener<ClickEvent<Button>> ComponentEventListener<ClickEvent<Button>> noClickListener = ev -> { //Ajout non accompli MessageDialogHelper.showWarningDialog("Erreur de Saisie", "La Saisie du N° Compte Trésorerie est requise. Veuillez en saisir un."); //Cancel - Il ne vaut pas la peine d'appeler clear ou setValue (null) sur le composant (ce qui revient au même). Le ComboBox a déjà une valeur nulle }; //Java Lambda Implementation of ComponentEventListener<ClickEvent<Button>> ComponentEventListener<ClickEvent<Button>> yesClickListener = ev -> { String finalNewVal; //Affiche une boîte de message et ajuste la longueur de la valeur introduite dans la zone de liste modifiable cboNoCompteTresorerie. if (strNewVal.length() > intMaxFieldLength) { MessageDialogHelper.showWarningDialog("Erreur de Saisie", "Le libellé est trop long. Les libellés de N° Compte Trésorerie ne peuvent dépasser " + intMaxFieldLength + " caractères. Le Libellé que vous avez introduit sera tronqué."); finalNewVal = strNewVal.substring(0, intMaxFieldLength - 1); } else { finalNewVal = strNewVal; } //Ouvre l'instance du Dialog EditerCompteDialog. EditerCompteDialog.getInstance().showDialog("Ajout de N° Compte", ModeFormulaireEditerEnum.AJOUTERCIF, new ArrayList<Compte>(), this.compteList, finalNewVal, this.uiEventBus); }; // Affiche une boîte de confirmation demandant si l'utilisateur désire ajouter un nouveau Compte. MessageDialogHelper.showYesNoDialog("Le N° Compte Trésorerie '" + strNewVal + "' n'est pas dans la liste.", "Désirez-vous ajouter un nouveau Compte Trésorerie?. Cliquez sur Oui pour confirmer l'ajout.", yesClickListener, noClickListener); } else { MessageDialogHelper.showWarningDialog("Erreur de Saisie", "La Saisie du N° Compte Trésorerie est requise. Veuillez en saisir un."); } //if (SecurityService.getInstance().isAccessGranted("EditerCompteDialog") == true) { } catch (Exception e) { MessageDialogHelper.showAlertDialog("EditerProprietaireDialog.cboNoCompteTresorerie_NotInList", e.toString()); e.printStackTrace(); } } //private void cboNoCompteTresorerie_NotInList(String strProposedVal, int intMaxFieldLength) private void cboNoCompteTVALoyer_NotInList(String strProposedVal, int intMaxFieldLength) { //Ajoute un nouveau Compte en entrant un libellé dans la zone de liste modifiable NoCompteTVALoyer. String strNewVal = strProposedVal; try { if (SecurityService.getInstance().isAccessGranted("EditerCompteDialog") == true) { //Java Lambda Implementation of ComponentEventListener<ClickEvent<Button>> ComponentEventListener<ClickEvent<Button>> noClickListener = ev -> { //Ajout non accompli MessageDialogHelper.showWarningDialog("Erreur de Saisie", "La Saisie du N° Compte TVA sur Loyer est requise. Veuillez en saisir un."); //Cancel - Il ne vaut pas la peine d'appeler clear ou setValue (null) sur le composant (ce qui revient au même). Le ComboBox a déjà une valeur nulle }; //Java Lambda Implementation of ComponentEventListener<ClickEvent<Button>> ComponentEventListener<ClickEvent<Button>> yesClickListener = ev -> { String finalNewVal; //Affiche une boîte de message et ajuste la longueur de la valeur introduite dans la zone de liste modifiable cboNoCompteTVALoyer. if (strNewVal.length() > intMaxFieldLength) { MessageDialogHelper.showWarningDialog("Erreur de Saisie", "Le libellé est trop long. Les libellés de N° Compte TVA sur Loyer ne peuvent dépasser " + intMaxFieldLength + " caractères. Le Libellé que vous avez introduit sera tronqué."); finalNewVal = strNewVal.substring(0, intMaxFieldLength - 1); } else { finalNewVal = strNewVal; } //Ouvre l'instance du Dialog EditerCompteDialog. EditerCompteDialog.getInstance().showDialog("Ajout de N° Compte", ModeFormulaireEditerEnum.AJOUTERCIF, new ArrayList<Compte>(), this.compteList, finalNewVal, this.uiEventBus); }; // Affiche une boîte de confirmation demandant si l'utilisateur désire ajouter un nouveau Compte TVA sur Loyer. MessageDialogHelper.showYesNoDialog("Le N° Compte TVA sur Loyer '" + strNewVal + "' n'est pas dans la liste.", "Désirez-vous ajouter un nouveau Compte TVA sur Loyer?. Cliquez sur Oui pour confirmer l'ajout.", yesClickListener, noClickListener); } else { MessageDialogHelper.showWarningDialog("Erreur de Saisie", "La Saisie du N° Compte TVA sur Loyer est requise. Veuillez en saisir un."); } //if (SecurityService.getInstance().isAccessGranted("EditerCompteDialog") == true) { } catch (Exception e) { MessageDialogHelper.showAlertDialog("EditerProprietaireDialog.cboNoCompteTVALoyer_NotInList", e.toString()); e.printStackTrace(); } } //private void cboNoCompteTVALoyer_NotInList(String strProposedVal, int intMaxFieldLength) private void cboNoCompteTVADepense_NotInList(String strProposedVal, int intMaxFieldLength) { //Ajoute un nouveau Compte en entrant un libellé dans la zone de liste modifiable NoCompteTVADepense. String strNewVal = strProposedVal; try { if (SecurityService.getInstance().isAccessGranted("EditerCompteDialog") == true) { //Java Lambda Implementation of ComponentEventListener<ClickEvent<Button>> ComponentEventListener<ClickEvent<Button>> noClickListener = ev -> { //Ajout non accompli MessageDialogHelper.showWarningDialog("Erreur de Saisie", "La Saisie du Compte est requise. Veuillez en saisir un."); //Cancel - Il ne vaut pas la peine d'appeler clear ou setValue (null) sur le composant (ce qui revient au même). Le ComboBox a déjà une valeur nulle }; //Java Lambda Implementation of ComponentEventListener<ClickEvent<Button>> ComponentEventListener<ClickEvent<Button>> yesClickListener = ev -> { String finalNewVal; //Affiche une boîte de message et ajuste la longueur de la valeur introduite dans la zone de liste modifiable cboNoCompteTVADepense. if (strNewVal.length() > intMaxFieldLength) { MessageDialogHelper.showWarningDialog("Erreur de Saisie", "Le libellé est trop long. Les libellés de Compte ne peuvent dépasser " + intMaxFieldLength + " caractères. Le Libellé que vous avez introduit sera tronqué."); finalNewVal = strNewVal.substring(0, intMaxFieldLength - 1); } else { finalNewVal = strNewVal; } //Ouvre l'instance du Dialog EditerCompteDialog. EditerCompteDialog.getInstance().showDialog("Ajout de Compte", ModeFormulaireEditerEnum.AJOUTERCIF, new ArrayList<Compte>(), this.compteList, finalNewVal, this.uiEventBus); }; // Affiche une boîte de confirmation demandant si l'utilisateur désire ajouter un nouveau Compte. MessageDialogHelper.showYesNoDialog("Le Compte '" + strNewVal + "' n'est pas dans la liste.", "Désirez-vous ajouter une nouveau Compte?. Cliquez sur Oui pour confirmer l'ajout.", yesClickListener, noClickListener); } else { MessageDialogHelper.showWarningDialog("Erreur de Saisie", "La Saisie du Compte est requise. Veuillez en saisir un."); } //if (SecurityService.getInstance().isAccessGranted("EditerCompteDialog") == true) { } catch (Exception e) { MessageDialogHelper.showAlertDialog("EditerProprietaireDialog.cboNoCompteTVADepense_NotInList", e.toString()); e.printStackTrace(); } } //private void cboNoCompteTVADepense_NotInList(String strProposedVal, int intMaxFieldLength) private void cboCodeJournalLoyer_NotInList(String strProposedVal, int intMaxFieldLength) { //Ajoute un nouveau ZZZJournal en entrant un libellé dans la zone de liste modifiable CodeJournalLoyer. String strNewVal = strProposedVal; try { if (SecurityService.getInstance().isAccessGranted("EditerJournalDialog") == true) { //Java Lambda Implementation of ComponentEventListener<ClickEvent<Button>> ComponentEventListener<ClickEvent<Button>> noClickListener = ev -> { //Ajout non accompli MessageDialogHelper.showWarningDialog("Erreur de Saisie", "La Saisie du ZZZJournal des Loyers est requise. Veuillez en saisir un."); //Cancel - Il ne vaut pas la peine d'appeler clear ou setValue (null) sur le composant (ce qui revient au même). Le ComboBox a déjà une valeur nulle }; //Java Lambda Implementation of ComponentEventListener<ClickEvent<Button>> ComponentEventListener<ClickEvent<Button>> yesClickListener = ev -> { String finalNewVal; //Affiche une boîte de message et ajuste la longueur de la valeur introduite dans la zone de liste modifiable cboCodeJournalLoyer. if (strNewVal.length() > intMaxFieldLength) { MessageDialogHelper.showWarningDialog("Erreur de Saisie", "Le libellé est trop long. Les libellés de ZZZJournal des Loyers ne peuvent dépasser " + intMaxFieldLength + " caractères. Le Libellé que vous avez introduit sera tronqué."); finalNewVal = strNewVal.substring(0, intMaxFieldLength - 1); } else { finalNewVal = strNewVal; } //Ouvre l'instance du Dialog EditerJournalDialog. EditerJournalDialog.getInstance().showDialog("Ajout de ZZZJournal", ModeFormulaireEditerEnum.AJOUTERCIF, new ArrayList<ZZZJournal>(), this.journalList, finalNewVal, this.uiEventBus, this.compteBusiness); }; // Affiche une boîte de confirmation demandant si l'utilisateur désire ajouter un nouveau ZZZJournal. MessageDialogHelper.showYesNoDialog("Le ZZZJournal des Loyers '" + strNewVal + "' n'est pas dans la liste.", "Désirez-vous ajouter un nouveau ZZZJournal des Loyers?. Cliquez sur Oui pour confirmer l'ajout.", yesClickListener, noClickListener); } else { MessageDialogHelper.showWarningDialog("Erreur de Saisie", "La Saisie du ZZZJournal des Loyers est requise. Veuillez en saisir un."); } //if (SecurityService.getInstance().isAccessGranted("EditerJournalDialog") == true) { } catch (Exception e) { MessageDialogHelper.showAlertDialog("EditerProprietaireDialog.cboCodeJournalLoyer_NotInList", e.toString()); e.printStackTrace(); } } //private void cboCodeJournalLoyer_NotInList(String strProposedVal, int intMaxFieldLength) private void cboCodeJournalDepense_NotInList(String strProposedVal, int intMaxFieldLength) { //Ajoute un nouveau ZZZJournal en entrant un libellé dans la zone de liste modifiable CodeJournalDepense. String strNewVal = strProposedVal; try { if (SecurityService.getInstance().isAccessGranted("EditerJournalDialog") == true) { //Java Lambda Implementation of ComponentEventListener<ClickEvent<Button>> ComponentEventListener<ClickEvent<Button>> noClickListener = ev -> { //Ajout non accompli MessageDialogHelper.showWarningDialog("Erreur de Saisie", "La Saisie du Code ZZZJournal Dépenses est requise. Veuillez en saisir un."); //Cancel - Il ne vaut pas la peine d'appeler clear ou setValue (null) sur le composant (ce qui revient au même). Le ComboBox a déjà une valeur nulle }; //Java Lambda Implementation of ComponentEventListener<ClickEvent<Button>> ComponentEventListener<ClickEvent<Button>> yesClickListener = ev -> { String finalNewVal; //Affiche une boîte de message et ajuste la longueur de la valeur introduite dans la zone de liste modifiable cboCodeJournalDepense. if (strNewVal.length() > intMaxFieldLength) { MessageDialogHelper.showWarningDialog("Erreur de Saisie", "Le libellé est trop long. Les libellés de Code ZZZJournal Dépenses ne peuvent dépasser " + intMaxFieldLength + " caractères. Le Libellé que vous avez introduit sera tronqué."); finalNewVal = strNewVal.substring(0, intMaxFieldLength - 1); } else { finalNewVal = strNewVal; } //Ouvre l'instance du Dialog EditerJournalDialog. EditerJournalDialog.getInstance().showDialog("Ajout de ZZZJournal", ModeFormulaireEditerEnum.AJOUTERCIF, new ArrayList<ZZZJournal>(), this.journalList, finalNewVal, this.uiEventBus, this.compteBusiness); }; // Affiche une boîte de confirmation demandant si l'utilisateur désire ajouter un nouveau ZZZJournal. MessageDialogHelper.showYesNoDialog("Le Code ZZZJournal des Dépenses '" + strNewVal + "' n'est pas dans la liste.", "Désirez-vous ajouter un nouveau ZZZJournal des Dépenses?. Cliquez sur Oui pour confirmer l'ajout.", yesClickListener, noClickListener); } else { MessageDialogHelper.showWarningDialog("Erreur de Saisie", "La Saisie du Code ZZZJournal Dépenses est requise. Veuillez en saisir un."); } //if (SecurityService.getInstance().isAccessGranted("EditerJournalDialog") == true) { } catch (Exception e) { MessageDialogHelper.showAlertDialog("EditerProprietaireDialog.cboCodeJournalDepense_NotInList", e.toString()); e.printStackTrace(); } } //private void cboCodeJournalDepense_NotInList(String strProposedVal, int intMaxFieldLength) @EventBusListenerMethod private void handleCompteTresorerieAddEventFromDialog(EditerCompteDialog.CompteAddEvent event) { //Handle Ajouter Compte Add Event received from Dialog //Ajouté à cause du CIF try { //1 - Sauvegarder la modification dans le backend Compte newInstance = this.compteBusiness.save(event.getCompte()); /* Notifying the List Data Provider About Item Changes The listing component does not automatically know about changes to the list of items or the individual items. For changes to reflect in the component, you need to notify the list data provider when items are changed, added or removed. */ //2 - Actualiser le Combo this.compteDataProvider.getItems().add(newInstance); this.compteDataProvider.refreshAll(); this.cboNoCompteTresorerie.setValue(newInstance); } catch (Exception e) { MessageDialogHelper.showAlertDialog("EditerProprietaireDialog.handleCompteTresorerieAddEventFromDialog", e.toString()); e.printStackTrace(); } } //private void handleCompteTresorerieAddEventFromDialog(CompteAddEvent event) { @EventBusListenerMethod private void handleCompteTVALoyerAddEventFromDialog(EditerCompteDialog.CompteAddEvent event) { //Handle Ajouter Compte Add Event received from Dialog //Ajouté à cause du CIF try { //1 - Sauvegarder la modification dans le backend Compte newInstance = this.compteBusiness.save(event.getCompte()); /* Notifying the List Data Provider About Item Changes The listing component does not automatically know about changes to the list of items or the individual items. For changes to reflect in the component, you need to notify the list data provider when items are changed, added or removed. */ //2 - Actualiser le Combo this.compteDataProvider.getItems().add(newInstance); this.compteDataProvider.refreshAll(); this.cboNoCompteTVALoyer.setValue(newInstance); } catch (Exception e) { MessageDialogHelper.showAlertDialog("EditerProprietaireDialog.handleCompteTVALoyerAddEventFromDialog", e.toString()); e.printStackTrace(); } } //private void handleCompteTVALoyerAddEventFromDialog(CompteAddEvent event) { @EventBusListenerMethod private void handleCompteTVADepenseAddEventFromDialog(EditerCompteDialog.CompteAddEvent event) { //Handle Ajouter Compte Add Event received from Dialog //Ajouté à cause du CIF try { //1 - Sauvegarder la modification dans le backend Compte newInstance = this.compteBusiness.save(event.getCompte()); /* Notifying the List Data Provider About Item Changes The listing component does not automatically know about changes to the list of items or the individual items. For changes to reflect in the component, you need to notify the list data provider when items are changed, added or removed. */ //2 - Actualiser le Combo this.compteDataProvider.getItems().add(newInstance); this.compteDataProvider.refreshAll(); this.cboNoCompteTVADepense.setValue(newInstance); } catch (Exception e) { MessageDialogHelper.showAlertDialog("EditerProprietaireDialog.handleCompteTVADepenseAddEventFromDialog", e.toString()); e.printStackTrace(); } } //private void handleCompteTVADepenseAddEventFromDialog(CompteAddEvent event) { @EventBusListenerMethod private void handleJournalLoyerAddEventFromDialog(EditerJournalDialog.JournalAddEvent event) { //Handle Ajouter ZZZJournal Add Event received from Dialog //Ajouté à cause du CIF try { //1 - Sauvegarder la modification dans le backend ZZZJournal newInstance = this.journalBusiness.save(event.getJournal()); /* Notifying the List Data Provider About Item Changes The listing component does not automatically know about changes to the list of items or the individual items. For changes to reflect in the component, you need to notify the list data provider when items are changed, added or removed. */ //2 - Actualiser le Combo this.journalDataProvider.getItems().add(newInstance); this.journalDataProvider.refreshAll(); this.cboCodeJournalLoyer.setValue(newInstance); } catch (Exception e) { MessageDialogHelper.showAlertDialog("EditerProprietaireDialog.handleJournalLoyerAddEventFromDialog", e.toString()); e.printStackTrace(); } } //private void handleJournalLoyerAddEventFromDialog(JournalAddEvent event) { @EventBusListenerMethod private void handleJournalDepenseAddEventFromDialog(EditerJournalDialog.JournalAddEvent event) { //Handle Ajouter ZZZJournal Add Event received from Dialog //Ajouté à cause du CIF try { //1 - Sauvegarder la modification dans le backend ZZZJournal newInstance = this.journalBusiness.save(event.getJournal()); /* Notifying the List Data Provider About Item Changes The listing component does not automatically know about changes to the list of items or the individual items. For changes to reflect in the component, you need to notify the list data provider when items are changed, added or removed. */ //2 - Actualiser le Combo this.journalDataProvider.getItems().add(newInstance); this.journalDataProvider.refreshAll(); this.cboCodeJournalDepense.setValue(newInstance); } catch (Exception e) { MessageDialogHelper.showAlertDialog("EditerProprietaireDialog.handleJournalDepenseAddEventFromDialog", e.toString()); e.printStackTrace(); } } //private void handleJournalDepenseAddEventFromDialog(JournalAddEvent event) { @Override protected void workingExecuteOnCurrent() { //execute Before Display current Bean try { } catch (Exception e) { MessageDialogHelper.showAlertDialog("EditerProprietaireDialog.workingExecuteOnCurrent", e.toString()); e.printStackTrace(); } } @Override protected void workingExecuteBeforeAddNew() { //execute Before Update current Bean try { } catch (Exception e) { MessageDialogHelper.showAlertDialog("EditerProprietaireDialog.workingExecuteBeforeUpdate", e.toString()); e.printStackTrace(); } } @Override protected void workingExecuteBeforeUpdate() { //execute Before Update current Bean try { } catch (Exception e) { MessageDialogHelper.showAlertDialog("EditerProprietaireDialog.workingExecuteBeforeUpdate", e.toString()); e.printStackTrace(); } } @Override protected void workingExecuteAfterUpdate() { //execute After Update current Bean try { } catch (Exception e) { MessageDialogHelper.showAlertDialog("EditerProprietaireDialog.workingExecuteAfterUpdate", e.toString()); e.printStackTrace(); } } @Override protected void workingExecuteAfterAddNew() { //execute After Add New Bean try { } catch (Exception e) { MessageDialogHelper.showAlertDialog("EditerProprietaireDialog.workingExecuteAfterUpdate", e.toString()); e.printStackTrace(); } } @Override public void publishAddEvent() { //Publish Add Event try { this.uiEventBus.publish(this, new ProprietaireAddEvent(this.dialog, this.currentBean)); } catch (Exception e) { MessageDialogHelper.showAlertDialog("EditerProprietaireDialog.publishAddEvent", e.toString()); e.printStackTrace(); } } @Override public void publishUpdateEvent() { //Publish Update Event try { this.uiEventBus.publish(this, new ProprietaireUpdateEvent(this.dialog, this.currentBean)); } catch (Exception e) { MessageDialogHelper.showAlertDialog("EditerProprietaireDialog.publishUpdateEvent", e.toString()); e.printStackTrace(); } } @Override public void publishRefreshEvent() { //Publish Refresh Event try { this.uiEventBus.publish(this, new ProprietaireRefreshEvent(this.dialog)); } catch (Exception e) { MessageDialogHelper.showAlertDialog("EditerProprietaireDialog.publishRefreshEvent", e.toString()); e.printStackTrace(); } } @Override protected boolean workingIsPrimaryKeyAndBeanExtraCheckValidated() { //TEST à effectuer avant la mise à jour ou l'ajout du nouvel enregistrement courant //Vérification de la validité de l'enregistrement courant Boolean blnCheckOk = false; try { if (this.referenceBeanList.stream() .anyMatch(p -> (p != this.currentBean) && (p.getCodeProprietaire() .equals(this.txtCodeProprietaire.getValue())))) { blnCheckOk = false; this.txtCodeProprietaire.focus(); MessageDialogHelper.showWarningDialog("Erreur de Saisie", "Risque de Doublons dans champ clé principale. Veuillez en saisir un autre Code Propriétaire."); } else blnCheckOk = true; } catch (Exception e) { MessageDialogHelper.showAlertDialog("EditerProprietaireDialog.workingIsPrimaryKeyAndBeanExtraCheckValidated", e.toString()); e.printStackTrace(); } return (blnCheckOk); }//protected boolean workingIsPrimaryKeyAndBeanExtraCheckValidated() @Override public Proprietaire workingCreateNewBeanInstance() { return (new Proprietaire()); } @Override protected void workingSetFieldsInitValues() { //Set default value - Code à exécuter après this.binder.readBean(this.currentBean) this.txtLibelleProprietaire.setValue(this.newComboValue); this.txtLibelleProprietaire.focus(); } //Setting Up Events /* Start of the API - EVENTS OUT */ public static abstract class EditerProprietaireDialogEvent extends ComponentEvent<Dialog> { private Proprietaire proprietaire; protected EditerProprietaireDialogEvent(Dialog source, Proprietaire argProprietaire) { /* The second constructor parameter determines whether the event is triggered by a DOM event in the browser or through the component’s server-side API. */ super(source, false); //Use false as the second constructor parameter to indicate that the event does not come from the client this.proprietaire = argProprietaire; } public Proprietaire getProprietaire() { return proprietaire; } } public static class ProprietaireAddEvent extends EditerProprietaireDialogEvent { public ProprietaireAddEvent(Dialog source, Proprietaire proprietaire) { super(source, proprietaire); } } public static class ProprietaireUpdateEvent extends EditerProprietaireDialogEvent { public ProprietaireUpdateEvent(Dialog source, Proprietaire proprietaire) { super(source, proprietaire); } } public static class ProprietaireRefreshEvent extends EditerProprietaireDialogEvent { public ProprietaireRefreshEvent(Dialog source) { super(source, null); } } /* End of the API - EVENTS OUT */ }
922fabe722e8c930d6da51d5dedba4fac7002346
1,053
java
Java
connect/runtime/src/main/java/org/apache/kafka/connect/runtime/distributed/RebalanceNeededException.java
tacticalrce/kafka
215cc9bf9f534c237d47cbef50ace301df8fa4d7
[ "Apache-2.0" ]
126
2018-08-31T21:47:30.000Z
2022-03-11T10:01:31.000Z
connect/runtime/src/main/java/org/apache/kafka/connect/runtime/distributed/RebalanceNeededException.java
tacticalrce/kafka
215cc9bf9f534c237d47cbef50ace301df8fa4d7
[ "Apache-2.0" ]
75
2019-03-07T20:24:18.000Z
2022-03-31T02:14:37.000Z
connect/runtime/src/main/java/org/apache/kafka/connect/runtime/distributed/RebalanceNeededException.java
tacticalrce/kafka
215cc9bf9f534c237d47cbef50ace301df8fa4d7
[ "Apache-2.0" ]
88
2016-11-27T02:16:11.000Z
2020-02-28T05:10:26.000Z
37.607143
75
0.762583
995,202
/* * 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.connect.runtime.distributed; import org.apache.kafka.connect.errors.ConnectException; public class RebalanceNeededException extends ConnectException { public RebalanceNeededException(String s) { super(s); } }
922facec2296744f0680ca646929b169436a70b8
5,088
java
Java
src/main/java/com/hbm/blocks/bomb/Balefire.java
Syncinus/Hbm-s-Nuclear-Tech-GIT
3ccc662ea0ca016d0d0a507864e2c0ec950c2807
[ "Unlicense" ]
null
null
null
src/main/java/com/hbm/blocks/bomb/Balefire.java
Syncinus/Hbm-s-Nuclear-Tech-GIT
3ccc662ea0ca016d0d0a507864e2c0ec950c2807
[ "Unlicense" ]
null
null
null
src/main/java/com/hbm/blocks/bomb/Balefire.java
Syncinus/Hbm-s-Nuclear-Tech-GIT
3ccc662ea0ca016d0d0a507864e2c0ec950c2807
[ "Unlicense" ]
null
null
null
29.241379
156
0.637186
995,203
package com.hbm.blocks.bomb; import java.util.Random; import com.hbm.blocks.ModBlocks; import com.hbm.potion.HbmPotion; import net.minecraft.block.Block; import net.minecraft.block.BlockFire; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.init.Blocks; import net.minecraft.potion.PotionEffect; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; public class Balefire extends BlockFire { public Balefire(String s) { super(); this.setUnlocalizedName(s); this.setRegistryName(s); this.setCreativeTab(null); ModBlocks.ALL_BLOCKS.add(this); } public void updateTick(World worldIn, BlockPos pos, IBlockState state, Random rand) { if (worldIn.getGameRules().getBoolean("doFireTick")) { if (!worldIn.isAreaLoaded(pos, 2)) return; // Forge: prevent loading unloaded chunks when spreading // fire if (!this.canPlaceBlockAt(worldIn, pos)) { worldIn.setBlockToAir(pos); } Block block = worldIn.getBlockState(pos.down()).getBlock(); boolean flag = block.isFireSource(worldIn, pos.down(), EnumFacing.UP); int i = ((Integer) state.getValue(AGE)).intValue(); /* if (!flag && worldIn.isRaining() && this.canDie(worldIn, pos) && rand.nextFloat() < 0.2F + (float)i * 0.03F) { worldIn.setBlockToAir(pos); } else*/ { /* if (i < 15) { state = state.withProperty(AGE, Integer.valueOf(i + rand.nextInt(3) / 2)); worldIn.setBlockState(pos, state, 4); }*/ worldIn.scheduleUpdate(pos, this, this.tickRate(worldIn) + rand.nextInt(10)); if (!flag) { if (!this.canNeighborCatchFire(worldIn, pos)) { if (!worldIn.getBlockState(pos.down()).isSideSolid(worldIn, pos.down(), EnumFacing.UP) || i > 3) { worldIn.setBlockToAir(pos); } return; } /* if (!this.canCatchFire(worldIn, pos.down(), EnumFacing.UP) && i == 15 && rand.nextInt(4) == 0) { worldIn.setBlockToAir(pos); return; }*/ } boolean flag1 = worldIn.isBlockinHighHumidity(pos); int j = 0; if (flag1) { j = -50; } this.tryCatchFire(worldIn, pos.east(), 300 + j, rand, i, EnumFacing.WEST); this.tryCatchFire(worldIn, pos.west(), 300 + j, rand, i, EnumFacing.EAST); this.tryCatchFire(worldIn, pos.down(), 250 + j, rand, i, EnumFacing.UP); this.tryCatchFire(worldIn, pos.up(), 250 + j, rand, i, EnumFacing.DOWN); this.tryCatchFire(worldIn, pos.north(), 300 + j, rand, i, EnumFacing.SOUTH); this.tryCatchFire(worldIn, pos.south(), 300 + j, rand, i, EnumFacing.NORTH); for (int k = -1; k <= 1; ++k) { for (int l = -1; l <= 1; ++l) { for (int i1 = -1; i1 <= 4; ++i1) { if (k != 0 || i1 != 0 || l != 0) { int j1 = 100; if (i1 > 1) { j1 += (i1 - 1) * 100; } BlockPos blockpos = pos.add(k, i1, l); int k1 = this.getNeighborEncouragement(worldIn, blockpos); if (k1 > 0) { int l1 = (k1 + 40 + worldIn.getDifficulty().getDifficultyId() * 7) / (i + 30); /* if (flag1) { l1 /= 2; }*/ if (l1 > 0 && rand.nextInt(j1) <= l1/* && (!worldIn.isRaining() || !this.canDie(worldIn, blockpos))*/) { int i2 = i + rand.nextInt(5) / 4; if (i2 > 15) { i2 = 15; } worldIn.setBlockState(blockpos, state.withProperty(AGE, Integer.valueOf(i2)), 3); } } } } } } } } } private boolean canNeighborCatchFire(World worldIn, BlockPos pos) { for (EnumFacing enumfacing : EnumFacing.values()) { if (this.canCatchFire(worldIn, pos.offset(enumfacing), enumfacing.getOpposite())) { return true; } } return false; } private int getNeighborEncouragement(World worldIn, BlockPos pos) { if (!worldIn.isAirBlock(pos)) { return 0; } else { int i = 0; for (EnumFacing enumfacing : EnumFacing.values()) { i = Math.max(worldIn.getBlockState(pos.offset(enumfacing)).getBlock().getFireSpreadSpeed(worldIn, pos.offset(enumfacing), enumfacing.getOpposite()), i); } return i; } } private void tryCatchFire(World p_149841_1_, BlockPos pos, int p_149841_5_, Random p_149841_6_, int p_149841_7_, EnumFacing face) { int j1 = p_149841_1_.getBlockState(pos).getBlock().getFlammability(p_149841_1_, pos, face); if (p_149841_6_.nextInt(p_149841_5_) < j1) { boolean flag = p_149841_1_.getBlockState(pos).getBlock() == Blocks.TNT; p_149841_1_.setBlockState(pos, this.getDefaultState().withProperty(AGE, 15), 3); if (flag) { Blocks.TNT.onBlockDestroyedByPlayer(p_149841_1_, pos, p_149841_1_.getBlockState(pos)); } } } @Override public void onEntityCollidedWithBlock(World worldIn, BlockPos pos, IBlockState state, Entity entityIn) { entityIn.setFire(10); if (entityIn instanceof EntityLivingBase) ((EntityLivingBase) entityIn).addPotionEffect(new PotionEffect(HbmPotion.radiation, 5 * 20, 9)); } }
922fae6ed6af4d94944485d63a8443f404da4a48
101,400
java
Java
components/esb-tools/plugins/org.wso2.integrationstudio.gmf.esb.edit/src-gen/org/wso2/integrationstudio/gmf/esb/parts/impl/APIResourceEndpointPropertiesEditionPartImpl.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.edit/src-gen/org/wso2/integrationstudio/gmf/esb/parts/impl/APIResourceEndpointPropertiesEditionPartImpl.java
sajithaliyanage/integration-studio
3329da9fa47e75028edf51f79264b6816bc4e333
[ "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.edit/src-gen/org/wso2/integrationstudio/gmf/esb/parts/impl/APIResourceEndpointPropertiesEditionPartImpl.java
sajithaliyanage/integration-studio
3329da9fa47e75028edf51f79264b6816bc4e333
[ "Apache-2.0" ]
25
2020-12-09T09:52:29.000Z
2022-03-16T06:18:08.000Z
41.625616
332
0.787495
995,204
/** * Generated with Acceleo */ package org.wso2.integrationstudio.gmf.esb.parts.impl; // Start of user code for imports import java.util.ArrayList; import java.util.List; import org.eclipse.emf.common.util.BasicEList; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.common.util.Enumerator; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.edit.ui.provider.AdapterFactoryLabelProvider; import org.eclipse.emf.eef.runtime.EEFRuntimePlugin; import org.eclipse.emf.eef.runtime.api.component.IPropertiesEditionComponent; import org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionEvent; import org.eclipse.emf.eef.runtime.api.parts.ISWTPropertiesEditionPart; import org.eclipse.emf.eef.runtime.impl.notify.PropertiesEditionEvent; import org.eclipse.emf.eef.runtime.impl.parts.CompositePropertiesEditionPart; import org.eclipse.emf.eef.runtime.ui.parts.PartComposer; import org.eclipse.emf.eef.runtime.ui.parts.sequence.BindingCompositionSequence; import org.eclipse.emf.eef.runtime.ui.parts.sequence.CompositionSequence; import org.eclipse.emf.eef.runtime.ui.parts.sequence.CompositionStep; import org.eclipse.emf.eef.runtime.ui.utils.EditingUtils; import org.eclipse.emf.eef.runtime.ui.widgets.EEFFeatureEditorDialog; import org.eclipse.emf.eef.runtime.ui.widgets.EMFComboViewer; import org.eclipse.emf.eef.runtime.ui.widgets.ReferencesTable; import org.eclipse.emf.eef.runtime.ui.widgets.ReferencesTable.ReferencesTableListener; import org.eclipse.emf.eef.runtime.ui.widgets.SWTUtils; import org.eclipse.emf.eef.runtime.ui.widgets.referencestable.ReferencesTableContentProvider; import org.eclipse.emf.eef.runtime.ui.widgets.referencestable.ReferencesTableSettings; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.jface.window.Window; import org.eclipse.swt.SWT; import org.eclipse.swt.events.FocusAdapter; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Text; import org.wso2.integrationstudio.gmf.esb.EsbPackage; import org.wso2.integrationstudio.gmf.esb.parts.APIResourceEndpointPropertiesEditionPart; import org.wso2.integrationstudio.gmf.esb.parts.EsbViewsRepository; import org.wso2.integrationstudio.gmf.esb.providers.EsbMessages; // End of user code /** * * */ public class APIResourceEndpointPropertiesEditionPartImpl extends CompositePropertiesEditionPart implements ISWTPropertiesEditionPart, APIResourceEndpointPropertiesEditionPart { protected Text description; protected Text commentsList; protected Button editCommentsList; protected EList commentsListList; protected Text endPointName; protected Button anonymous; protected Button inLine; protected Button duplicate; protected ReferencesTable properties; protected List<ViewerFilter> propertiesBusinessFilters = new ArrayList<ViewerFilter>(); protected List<ViewerFilter> propertiesFilters = new ArrayList<ViewerFilter>(); protected Button reversed; protected Button reliableMessagingEnabled; protected Button securityEnabled; protected Button addressingEnabled; protected EMFComboViewer addressingVersion; protected Button addressingSeparateListener; protected Text timeOutDuration; protected EMFComboViewer timeOutAction; protected Text retryErrorCodes; protected Text retryCount; protected Text retryDelay; protected Text suspendErrorCodes; protected Text suspendInitialDuration; protected Text suspendMaximumDuration; protected Text suspendProgressionFactor; protected EMFComboViewer format; protected EMFComboViewer optimize; protected ReferencesTable templateParameters; protected List<ViewerFilter> templateParametersBusinessFilters = new ArrayList<ViewerFilter>(); protected List<ViewerFilter> templateParametersFilters = new ArrayList<ViewerFilter>(); protected Button statisticsEnabled; protected Button traceEnabled; /** * Default constructor * @param editionComponent the {@link IPropertiesEditionComponent} that manage this part * */ public APIResourceEndpointPropertiesEditionPartImpl(IPropertiesEditionComponent editionComponent) { super(editionComponent); } /** * {@inheritDoc} * * @see org.eclipse.emf.eef.runtime.api.parts.ISWTPropertiesEditionPart# * createFigure(org.eclipse.swt.widgets.Composite) * */ public Composite createFigure(final Composite parent) { view = new Composite(parent, SWT.NONE); GridLayout layout = new GridLayout(); layout.numColumns = 3; view.setLayout(layout); createControls(view); return view; } /** * {@inheritDoc} * * @see org.eclipse.emf.eef.runtime.api.parts.ISWTPropertiesEditionPart# * createControls(org.eclipse.swt.widgets.Composite) * */ public void createControls(Composite view) { CompositionSequence aPIResourceEndpointStep = new BindingCompositionSequence(propertiesEditionComponent); CompositionStep propertiesStep = aPIResourceEndpointStep.addStep(EsbViewsRepository.APIResourceEndpoint.Properties.class); propertiesStep.addStep(EsbViewsRepository.APIResourceEndpoint.Properties.description); propertiesStep.addStep(EsbViewsRepository.APIResourceEndpoint.Properties.commentsList); propertiesStep.addStep(EsbViewsRepository.APIResourceEndpoint.Properties.endPointName); propertiesStep.addStep(EsbViewsRepository.APIResourceEndpoint.Properties.anonymous); propertiesStep.addStep(EsbViewsRepository.APIResourceEndpoint.Properties.inLine); propertiesStep.addStep(EsbViewsRepository.APIResourceEndpoint.Properties.duplicate); propertiesStep.addStep(EsbViewsRepository.APIResourceEndpoint.Properties.properties_); propertiesStep.addStep(EsbViewsRepository.APIResourceEndpoint.Properties.reversed); propertiesStep.addStep(EsbViewsRepository.APIResourceEndpoint.Properties.reliableMessagingEnabled); propertiesStep.addStep(EsbViewsRepository.APIResourceEndpoint.Properties.securityEnabled); propertiesStep.addStep(EsbViewsRepository.APIResourceEndpoint.Properties.addressingEnabled); propertiesStep.addStep(EsbViewsRepository.APIResourceEndpoint.Properties.addressingVersion); propertiesStep.addStep(EsbViewsRepository.APIResourceEndpoint.Properties.addressingSeparateListener); propertiesStep.addStep(EsbViewsRepository.APIResourceEndpoint.Properties.timeOutDuration); propertiesStep.addStep(EsbViewsRepository.APIResourceEndpoint.Properties.timeOutAction); propertiesStep.addStep(EsbViewsRepository.APIResourceEndpoint.Properties.retryErrorCodes); propertiesStep.addStep(EsbViewsRepository.APIResourceEndpoint.Properties.retryCount); propertiesStep.addStep(EsbViewsRepository.APIResourceEndpoint.Properties.retryDelay); propertiesStep.addStep(EsbViewsRepository.APIResourceEndpoint.Properties.suspendErrorCodes); propertiesStep.addStep(EsbViewsRepository.APIResourceEndpoint.Properties.suspendInitialDuration); propertiesStep.addStep(EsbViewsRepository.APIResourceEndpoint.Properties.suspendMaximumDuration); propertiesStep.addStep(EsbViewsRepository.APIResourceEndpoint.Properties.suspendProgressionFactor); propertiesStep.addStep(EsbViewsRepository.APIResourceEndpoint.Properties.format); propertiesStep.addStep(EsbViewsRepository.APIResourceEndpoint.Properties.optimize); propertiesStep.addStep(EsbViewsRepository.APIResourceEndpoint.Properties.templateParameters); propertiesStep.addStep(EsbViewsRepository.APIResourceEndpoint.Properties.statisticsEnabled); propertiesStep.addStep(EsbViewsRepository.APIResourceEndpoint.Properties.traceEnabled); composer = new PartComposer(aPIResourceEndpointStep) { @Override public Composite addToPart(Composite parent, Object key) { if (key == EsbViewsRepository.APIResourceEndpoint.Properties.class) { return createPropertiesGroup(parent); } if (key == EsbViewsRepository.APIResourceEndpoint.Properties.description) { return createDescriptionText(parent); } if (key == EsbViewsRepository.APIResourceEndpoint.Properties.commentsList) { return createCommentsListMultiValuedEditor(parent); } if (key == EsbViewsRepository.APIResourceEndpoint.Properties.endPointName) { return createEndPointNameText(parent); } if (key == EsbViewsRepository.APIResourceEndpoint.Properties.anonymous) { return createAnonymousCheckbox(parent); } if (key == EsbViewsRepository.APIResourceEndpoint.Properties.inLine) { return createInLineCheckbox(parent); } if (key == EsbViewsRepository.APIResourceEndpoint.Properties.duplicate) { return createDuplicateCheckbox(parent); } if (key == EsbViewsRepository.APIResourceEndpoint.Properties.properties_) { return createPropertiesAdvancedTableComposition(parent); } if (key == EsbViewsRepository.APIResourceEndpoint.Properties.reversed) { return createReversedCheckbox(parent); } if (key == EsbViewsRepository.APIResourceEndpoint.Properties.reliableMessagingEnabled) { return createReliableMessagingEnabledCheckbox(parent); } if (key == EsbViewsRepository.APIResourceEndpoint.Properties.securityEnabled) { return createSecurityEnabledCheckbox(parent); } if (key == EsbViewsRepository.APIResourceEndpoint.Properties.addressingEnabled) { return createAddressingEnabledCheckbox(parent); } if (key == EsbViewsRepository.APIResourceEndpoint.Properties.addressingVersion) { return createAddressingVersionEMFComboViewer(parent); } if (key == EsbViewsRepository.APIResourceEndpoint.Properties.addressingSeparateListener) { return createAddressingSeparateListenerCheckbox(parent); } if (key == EsbViewsRepository.APIResourceEndpoint.Properties.timeOutDuration) { return createTimeOutDurationText(parent); } if (key == EsbViewsRepository.APIResourceEndpoint.Properties.timeOutAction) { return createTimeOutActionEMFComboViewer(parent); } if (key == EsbViewsRepository.APIResourceEndpoint.Properties.retryErrorCodes) { return createRetryErrorCodesText(parent); } if (key == EsbViewsRepository.APIResourceEndpoint.Properties.retryCount) { return createRetryCountText(parent); } if (key == EsbViewsRepository.APIResourceEndpoint.Properties.retryDelay) { return createRetryDelayText(parent); } if (key == EsbViewsRepository.APIResourceEndpoint.Properties.suspendErrorCodes) { return createSuspendErrorCodesText(parent); } if (key == EsbViewsRepository.APIResourceEndpoint.Properties.suspendInitialDuration) { return createSuspendInitialDurationText(parent); } if (key == EsbViewsRepository.APIResourceEndpoint.Properties.suspendMaximumDuration) { return createSuspendMaximumDurationText(parent); } if (key == EsbViewsRepository.APIResourceEndpoint.Properties.suspendProgressionFactor) { return createSuspendProgressionFactorText(parent); } if (key == EsbViewsRepository.APIResourceEndpoint.Properties.format) { return createFormatEMFComboViewer(parent); } if (key == EsbViewsRepository.APIResourceEndpoint.Properties.optimize) { return createOptimizeEMFComboViewer(parent); } if (key == EsbViewsRepository.APIResourceEndpoint.Properties.templateParameters) { return createTemplateParametersAdvancedTableComposition(parent); } if (key == EsbViewsRepository.APIResourceEndpoint.Properties.statisticsEnabled) { return createStatisticsEnabledCheckbox(parent); } if (key == EsbViewsRepository.APIResourceEndpoint.Properties.traceEnabled) { return createTraceEnabledCheckbox(parent); } return parent; } }; composer.compose(view); } /** * */ protected Composite createPropertiesGroup(Composite parent) { Group propertiesGroup = new Group(parent, SWT.NONE); propertiesGroup.setText(EsbMessages.APIResourceEndpointPropertiesEditionPart_PropertiesGroupLabel); GridData propertiesGroupData = new GridData(GridData.FILL_HORIZONTAL); propertiesGroupData.horizontalSpan = 3; propertiesGroup.setLayoutData(propertiesGroupData); GridLayout propertiesGroupLayout = new GridLayout(); propertiesGroupLayout.numColumns = 3; propertiesGroup.setLayout(propertiesGroupLayout); return propertiesGroup; } protected Composite createDescriptionText(Composite parent) { createDescription(parent, EsbViewsRepository.APIResourceEndpoint.Properties.description, EsbMessages.APIResourceEndpointPropertiesEditionPart_DescriptionLabel); description = SWTUtils.createScrollableText(parent, SWT.BORDER); GridData descriptionData = new GridData(GridData.FILL_HORIZONTAL); description.setLayoutData(descriptionData); description.addFocusListener(new FocusAdapter() { /** * {@inheritDoc} * * @see org.eclipse.swt.events.FocusAdapter#focusLost(org.eclipse.swt.events.FocusEvent) * */ @Override @SuppressWarnings("synthetic-access") public void focusLost(FocusEvent e) { if (propertiesEditionComponent != null) propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(APIResourceEndpointPropertiesEditionPartImpl.this, EsbViewsRepository.APIResourceEndpoint.Properties.description, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, description.getText())); } }); description.addKeyListener(new KeyAdapter() { /** * {@inheritDoc} * * @see org.eclipse.swt.events.KeyAdapter#keyPressed(org.eclipse.swt.events.KeyEvent) * */ @Override @SuppressWarnings("synthetic-access") public void keyPressed(KeyEvent e) { if (e.character == SWT.CR) { if (propertiesEditionComponent != null) propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(APIResourceEndpointPropertiesEditionPartImpl.this, EsbViewsRepository.APIResourceEndpoint.Properties.description, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, description.getText())); } } }); EditingUtils.setID(description, EsbViewsRepository.APIResourceEndpoint.Properties.description); EditingUtils.setEEFtype(description, "eef::Text"); //$NON-NLS-1$ SWTUtils.createHelpButton(parent, propertiesEditionComponent.getHelpContent(EsbViewsRepository.APIResourceEndpoint.Properties.description, EsbViewsRepository.SWT_KIND), null); //$NON-NLS-1$ // Start of user code for createDescriptionText // End of user code return parent; } protected Composite createCommentsListMultiValuedEditor(Composite parent) { commentsList = SWTUtils.createScrollableText(parent, SWT.BORDER | SWT.READ_ONLY); GridData commentsListData = new GridData(GridData.FILL_HORIZONTAL); commentsListData.horizontalSpan = 2; commentsList.setLayoutData(commentsListData); EditingUtils.setID(commentsList, EsbViewsRepository.APIResourceEndpoint.Properties.commentsList); EditingUtils.setEEFtype(commentsList, "eef::MultiValuedEditor::field"); //$NON-NLS-1$ editCommentsList = new Button(parent, SWT.NONE); editCommentsList.setText(getDescription(EsbViewsRepository.APIResourceEndpoint.Properties.commentsList, EsbMessages.APIResourceEndpointPropertiesEditionPart_CommentsListLabel)); GridData editCommentsListData = new GridData(); editCommentsList.setLayoutData(editCommentsListData); editCommentsList.addSelectionListener(new SelectionAdapter() { /** * {@inheritDoc} * * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent) */ public void widgetSelected(SelectionEvent e) { EEFFeatureEditorDialog dialog = new EEFFeatureEditorDialog( commentsList.getShell(), "APIResourceEndpoint", new AdapterFactoryLabelProvider(adapterFactory), //$NON-NLS-1$ commentsListList, EsbPackage.eINSTANCE.getEsbElement_CommentsList().getEType(), null, false, true, null, null); if (dialog.open() == Window.OK) { commentsListList = dialog.getResult(); if (commentsListList == null) { commentsListList = new BasicEList(); } commentsList.setText(commentsListList.toString()); propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(APIResourceEndpointPropertiesEditionPartImpl.this, EsbViewsRepository.APIResourceEndpoint.Properties.commentsList, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, new BasicEList(commentsListList))); setHasChanged(true); } } }); EditingUtils.setID(editCommentsList, EsbViewsRepository.APIResourceEndpoint.Properties.commentsList); EditingUtils.setEEFtype(editCommentsList, "eef::MultiValuedEditor::browsebutton"); //$NON-NLS-1$ // Start of user code for createCommentsListMultiValuedEditor // End of user code return parent; } protected Composite createEndPointNameText(Composite parent) { createDescription(parent, EsbViewsRepository.APIResourceEndpoint.Properties.endPointName, EsbMessages.APIResourceEndpointPropertiesEditionPart_EndPointNameLabel); endPointName = SWTUtils.createScrollableText(parent, SWT.BORDER); GridData endPointNameData = new GridData(GridData.FILL_HORIZONTAL); endPointName.setLayoutData(endPointNameData); endPointName.addFocusListener(new FocusAdapter() { /** * {@inheritDoc} * * @see org.eclipse.swt.events.FocusAdapter#focusLost(org.eclipse.swt.events.FocusEvent) * */ @Override @SuppressWarnings("synthetic-access") public void focusLost(FocusEvent e) { if (propertiesEditionComponent != null) propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(APIResourceEndpointPropertiesEditionPartImpl.this, EsbViewsRepository.APIResourceEndpoint.Properties.endPointName, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, endPointName.getText())); } }); endPointName.addKeyListener(new KeyAdapter() { /** * {@inheritDoc} * * @see org.eclipse.swt.events.KeyAdapter#keyPressed(org.eclipse.swt.events.KeyEvent) * */ @Override @SuppressWarnings("synthetic-access") public void keyPressed(KeyEvent e) { if (e.character == SWT.CR) { if (propertiesEditionComponent != null) propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(APIResourceEndpointPropertiesEditionPartImpl.this, EsbViewsRepository.APIResourceEndpoint.Properties.endPointName, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, endPointName.getText())); } } }); EditingUtils.setID(endPointName, EsbViewsRepository.APIResourceEndpoint.Properties.endPointName); EditingUtils.setEEFtype(endPointName, "eef::Text"); //$NON-NLS-1$ SWTUtils.createHelpButton(parent, propertiesEditionComponent.getHelpContent(EsbViewsRepository.APIResourceEndpoint.Properties.endPointName, EsbViewsRepository.SWT_KIND), null); //$NON-NLS-1$ // Start of user code for createEndPointNameText // End of user code return parent; } protected Composite createAnonymousCheckbox(Composite parent) { anonymous = new Button(parent, SWT.CHECK); anonymous.setText(getDescription(EsbViewsRepository.APIResourceEndpoint.Properties.anonymous, EsbMessages.APIResourceEndpointPropertiesEditionPart_AnonymousLabel)); anonymous.addSelectionListener(new SelectionAdapter() { /** * {@inheritDoc} * * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent) * */ public void widgetSelected(SelectionEvent e) { if (propertiesEditionComponent != null) propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(APIResourceEndpointPropertiesEditionPartImpl.this, EsbViewsRepository.APIResourceEndpoint.Properties.anonymous, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, new Boolean(anonymous.getSelection()))); } }); GridData anonymousData = new GridData(GridData.FILL_HORIZONTAL); anonymousData.horizontalSpan = 2; anonymous.setLayoutData(anonymousData); EditingUtils.setID(anonymous, EsbViewsRepository.APIResourceEndpoint.Properties.anonymous); EditingUtils.setEEFtype(anonymous, "eef::Checkbox"); //$NON-NLS-1$ SWTUtils.createHelpButton(parent, propertiesEditionComponent.getHelpContent(EsbViewsRepository.APIResourceEndpoint.Properties.anonymous, EsbViewsRepository.SWT_KIND), null); //$NON-NLS-1$ // Start of user code for createAnonymousCheckbox // End of user code return parent; } protected Composite createInLineCheckbox(Composite parent) { inLine = new Button(parent, SWT.CHECK); inLine.setText(getDescription(EsbViewsRepository.APIResourceEndpoint.Properties.inLine, EsbMessages.APIResourceEndpointPropertiesEditionPart_InLineLabel)); inLine.addSelectionListener(new SelectionAdapter() { /** * {@inheritDoc} * * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent) * */ public void widgetSelected(SelectionEvent e) { if (propertiesEditionComponent != null) propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(APIResourceEndpointPropertiesEditionPartImpl.this, EsbViewsRepository.APIResourceEndpoint.Properties.inLine, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, new Boolean(inLine.getSelection()))); } }); GridData inLineData = new GridData(GridData.FILL_HORIZONTAL); inLineData.horizontalSpan = 2; inLine.setLayoutData(inLineData); EditingUtils.setID(inLine, EsbViewsRepository.APIResourceEndpoint.Properties.inLine); EditingUtils.setEEFtype(inLine, "eef::Checkbox"); //$NON-NLS-1$ SWTUtils.createHelpButton(parent, propertiesEditionComponent.getHelpContent(EsbViewsRepository.APIResourceEndpoint.Properties.inLine, EsbViewsRepository.SWT_KIND), null); //$NON-NLS-1$ // Start of user code for createInLineCheckbox // End of user code return parent; } protected Composite createDuplicateCheckbox(Composite parent) { duplicate = new Button(parent, SWT.CHECK); duplicate.setText(getDescription(EsbViewsRepository.APIResourceEndpoint.Properties.duplicate, EsbMessages.APIResourceEndpointPropertiesEditionPart_DuplicateLabel)); duplicate.addSelectionListener(new SelectionAdapter() { /** * {@inheritDoc} * * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent) * */ public void widgetSelected(SelectionEvent e) { if (propertiesEditionComponent != null) propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(APIResourceEndpointPropertiesEditionPartImpl.this, EsbViewsRepository.APIResourceEndpoint.Properties.duplicate, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, new Boolean(duplicate.getSelection()))); } }); GridData duplicateData = new GridData(GridData.FILL_HORIZONTAL); duplicateData.horizontalSpan = 2; duplicate.setLayoutData(duplicateData); EditingUtils.setID(duplicate, EsbViewsRepository.APIResourceEndpoint.Properties.duplicate); EditingUtils.setEEFtype(duplicate, "eef::Checkbox"); //$NON-NLS-1$ SWTUtils.createHelpButton(parent, propertiesEditionComponent.getHelpContent(EsbViewsRepository.APIResourceEndpoint.Properties.duplicate, EsbViewsRepository.SWT_KIND), null); //$NON-NLS-1$ // Start of user code for createDuplicateCheckbox // End of user code return parent; } /** * @param container * */ protected Composite createPropertiesAdvancedTableComposition(Composite parent) { this.properties = new ReferencesTable(getDescription(EsbViewsRepository.APIResourceEndpoint.Properties.properties_, EsbMessages.APIResourceEndpointPropertiesEditionPart_PropertiesLabel), new ReferencesTableListener() { public void handleAdd() { propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(APIResourceEndpointPropertiesEditionPartImpl.this, EsbViewsRepository.APIResourceEndpoint.Properties.properties_, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.ADD, null, null)); properties.refresh(); } public void handleEdit(EObject element) { propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(APIResourceEndpointPropertiesEditionPartImpl.this, EsbViewsRepository.APIResourceEndpoint.Properties.properties_, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.EDIT, null, element)); properties.refresh(); } public void handleMove(EObject element, int oldIndex, int newIndex) { propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(APIResourceEndpointPropertiesEditionPartImpl.this, EsbViewsRepository.APIResourceEndpoint.Properties.properties_, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.MOVE, element, newIndex)); properties.refresh(); } public void handleRemove(EObject element) { propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(APIResourceEndpointPropertiesEditionPartImpl.this, EsbViewsRepository.APIResourceEndpoint.Properties.properties_, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.REMOVE, null, element)); properties.refresh(); } public void navigateTo(EObject element) { } }); for (ViewerFilter filter : this.propertiesFilters) { this.properties.addFilter(filter); } this.properties.setHelpText(propertiesEditionComponent.getHelpContent(EsbViewsRepository.APIResourceEndpoint.Properties.properties_, EsbViewsRepository.SWT_KIND)); this.properties.createControls(parent); this.properties.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { if (e.item != null && e.item.getData() instanceof EObject) { propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(APIResourceEndpointPropertiesEditionPartImpl.this, EsbViewsRepository.APIResourceEndpoint.Properties.properties_, PropertiesEditionEvent.CHANGE, PropertiesEditionEvent.SELECTION_CHANGED, null, e.item.getData())); } } }); GridData propertiesData = new GridData(GridData.FILL_HORIZONTAL); propertiesData.horizontalSpan = 3; this.properties.setLayoutData(propertiesData); this.properties.setLowerBound(0); this.properties.setUpperBound(-1); properties.setID(EsbViewsRepository.APIResourceEndpoint.Properties.properties_); properties.setEEFType("eef::AdvancedTableComposition"); //$NON-NLS-1$ // Start of user code for createPropertiesAdvancedTableComposition // End of user code return parent; } protected Composite createReversedCheckbox(Composite parent) { reversed = new Button(parent, SWT.CHECK); reversed.setText(getDescription(EsbViewsRepository.APIResourceEndpoint.Properties.reversed, EsbMessages.APIResourceEndpointPropertiesEditionPart_ReversedLabel)); reversed.addSelectionListener(new SelectionAdapter() { /** * {@inheritDoc} * * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent) * */ public void widgetSelected(SelectionEvent e) { if (propertiesEditionComponent != null) propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(APIResourceEndpointPropertiesEditionPartImpl.this, EsbViewsRepository.APIResourceEndpoint.Properties.reversed, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, new Boolean(reversed.getSelection()))); } }); GridData reversedData = new GridData(GridData.FILL_HORIZONTAL); reversedData.horizontalSpan = 2; reversed.setLayoutData(reversedData); EditingUtils.setID(reversed, EsbViewsRepository.APIResourceEndpoint.Properties.reversed); EditingUtils.setEEFtype(reversed, "eef::Checkbox"); //$NON-NLS-1$ SWTUtils.createHelpButton(parent, propertiesEditionComponent.getHelpContent(EsbViewsRepository.APIResourceEndpoint.Properties.reversed, EsbViewsRepository.SWT_KIND), null); //$NON-NLS-1$ // Start of user code for createReversedCheckbox // End of user code return parent; } protected Composite createReliableMessagingEnabledCheckbox(Composite parent) { reliableMessagingEnabled = new Button(parent, SWT.CHECK); reliableMessagingEnabled.setText(getDescription(EsbViewsRepository.APIResourceEndpoint.Properties.reliableMessagingEnabled, EsbMessages.APIResourceEndpointPropertiesEditionPart_ReliableMessagingEnabledLabel)); reliableMessagingEnabled.addSelectionListener(new SelectionAdapter() { /** * {@inheritDoc} * * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent) * */ public void widgetSelected(SelectionEvent e) { if (propertiesEditionComponent != null) propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(APIResourceEndpointPropertiesEditionPartImpl.this, EsbViewsRepository.APIResourceEndpoint.Properties.reliableMessagingEnabled, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, new Boolean(reliableMessagingEnabled.getSelection()))); } }); GridData reliableMessagingEnabledData = new GridData(GridData.FILL_HORIZONTAL); reliableMessagingEnabledData.horizontalSpan = 2; reliableMessagingEnabled.setLayoutData(reliableMessagingEnabledData); EditingUtils.setID(reliableMessagingEnabled, EsbViewsRepository.APIResourceEndpoint.Properties.reliableMessagingEnabled); EditingUtils.setEEFtype(reliableMessagingEnabled, "eef::Checkbox"); //$NON-NLS-1$ SWTUtils.createHelpButton(parent, propertiesEditionComponent.getHelpContent(EsbViewsRepository.APIResourceEndpoint.Properties.reliableMessagingEnabled, EsbViewsRepository.SWT_KIND), null); //$NON-NLS-1$ // Start of user code for createReliableMessagingEnabledCheckbox // End of user code return parent; } protected Composite createSecurityEnabledCheckbox(Composite parent) { securityEnabled = new Button(parent, SWT.CHECK); securityEnabled.setText(getDescription(EsbViewsRepository.APIResourceEndpoint.Properties.securityEnabled, EsbMessages.APIResourceEndpointPropertiesEditionPart_SecurityEnabledLabel)); securityEnabled.addSelectionListener(new SelectionAdapter() { /** * {@inheritDoc} * * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent) * */ public void widgetSelected(SelectionEvent e) { if (propertiesEditionComponent != null) propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(APIResourceEndpointPropertiesEditionPartImpl.this, EsbViewsRepository.APIResourceEndpoint.Properties.securityEnabled, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, new Boolean(securityEnabled.getSelection()))); } }); GridData securityEnabledData = new GridData(GridData.FILL_HORIZONTAL); securityEnabledData.horizontalSpan = 2; securityEnabled.setLayoutData(securityEnabledData); EditingUtils.setID(securityEnabled, EsbViewsRepository.APIResourceEndpoint.Properties.securityEnabled); EditingUtils.setEEFtype(securityEnabled, "eef::Checkbox"); //$NON-NLS-1$ SWTUtils.createHelpButton(parent, propertiesEditionComponent.getHelpContent(EsbViewsRepository.APIResourceEndpoint.Properties.securityEnabled, EsbViewsRepository.SWT_KIND), null); //$NON-NLS-1$ // Start of user code for createSecurityEnabledCheckbox // End of user code return parent; } protected Composite createAddressingEnabledCheckbox(Composite parent) { addressingEnabled = new Button(parent, SWT.CHECK); addressingEnabled.setText(getDescription(EsbViewsRepository.APIResourceEndpoint.Properties.addressingEnabled, EsbMessages.APIResourceEndpointPropertiesEditionPart_AddressingEnabledLabel)); addressingEnabled.addSelectionListener(new SelectionAdapter() { /** * {@inheritDoc} * * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent) * */ public void widgetSelected(SelectionEvent e) { if (propertiesEditionComponent != null) propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(APIResourceEndpointPropertiesEditionPartImpl.this, EsbViewsRepository.APIResourceEndpoint.Properties.addressingEnabled, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, new Boolean(addressingEnabled.getSelection()))); } }); GridData addressingEnabledData = new GridData(GridData.FILL_HORIZONTAL); addressingEnabledData.horizontalSpan = 2; addressingEnabled.setLayoutData(addressingEnabledData); EditingUtils.setID(addressingEnabled, EsbViewsRepository.APIResourceEndpoint.Properties.addressingEnabled); EditingUtils.setEEFtype(addressingEnabled, "eef::Checkbox"); //$NON-NLS-1$ SWTUtils.createHelpButton(parent, propertiesEditionComponent.getHelpContent(EsbViewsRepository.APIResourceEndpoint.Properties.addressingEnabled, EsbViewsRepository.SWT_KIND), null); //$NON-NLS-1$ // Start of user code for createAddressingEnabledCheckbox // End of user code return parent; } /** * @generated NOT */ protected Composite createAddressingVersionEMFComboViewer(Composite parent) { createDescription(parent, EsbViewsRepository.APIResourceEndpoint.Properties.addressingVersion, EsbMessages.APIResourceEndpointPropertiesEditionPart_AddressingVersionLabel); addressingVersion = new EMFComboViewer(parent); addressingVersion.setContentProvider(new ArrayContentProvider()); addressingVersion.setLabelProvider(new AdapterFactoryLabelProvider(EEFRuntimePlugin.getDefault().getAdapterFactory())); GridData addressingVersionData = new GridData(GridData.FILL_HORIZONTAL); addressingVersion.getCombo().setLayoutData(addressingVersionData); addressingVersion.getCombo().addListener(SWT.MouseVerticalWheel, new Listener() { @Override public void handleEvent(Event arg0) { arg0.doit = false; } }); addressingVersion.addSelectionChangedListener(new ISelectionChangedListener() { /** * {@inheritDoc} * * @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent) * */ public void selectionChanged(SelectionChangedEvent event) { if (propertiesEditionComponent != null) propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(APIResourceEndpointPropertiesEditionPartImpl.this, EsbViewsRepository.APIResourceEndpoint.Properties.addressingVersion, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, getAddressingVersion())); } }); addressingVersion.setID(EsbViewsRepository.APIResourceEndpoint.Properties.addressingVersion); SWTUtils.createHelpButton(parent, propertiesEditionComponent.getHelpContent(EsbViewsRepository.APIResourceEndpoint.Properties.addressingVersion, EsbViewsRepository.SWT_KIND), null); //$NON-NLS-1$ // Start of user code for createAddressingVersionEMFComboViewer // End of user code return parent; } protected Composite createAddressingSeparateListenerCheckbox(Composite parent) { addressingSeparateListener = new Button(parent, SWT.CHECK); addressingSeparateListener.setText(getDescription(EsbViewsRepository.APIResourceEndpoint.Properties.addressingSeparateListener, EsbMessages.APIResourceEndpointPropertiesEditionPart_AddressingSeparateListenerLabel)); addressingSeparateListener.addSelectionListener(new SelectionAdapter() { /** * {@inheritDoc} * * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent) * */ public void widgetSelected(SelectionEvent e) { if (propertiesEditionComponent != null) propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(APIResourceEndpointPropertiesEditionPartImpl.this, EsbViewsRepository.APIResourceEndpoint.Properties.addressingSeparateListener, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, new Boolean(addressingSeparateListener.getSelection()))); } }); GridData addressingSeparateListenerData = new GridData(GridData.FILL_HORIZONTAL); addressingSeparateListenerData.horizontalSpan = 2; addressingSeparateListener.setLayoutData(addressingSeparateListenerData); EditingUtils.setID(addressingSeparateListener, EsbViewsRepository.APIResourceEndpoint.Properties.addressingSeparateListener); EditingUtils.setEEFtype(addressingSeparateListener, "eef::Checkbox"); //$NON-NLS-1$ SWTUtils.createHelpButton(parent, propertiesEditionComponent.getHelpContent(EsbViewsRepository.APIResourceEndpoint.Properties.addressingSeparateListener, EsbViewsRepository.SWT_KIND), null); //$NON-NLS-1$ // Start of user code for createAddressingSeparateListenerCheckbox // End of user code return parent; } protected Composite createTimeOutDurationText(Composite parent) { createDescription(parent, EsbViewsRepository.APIResourceEndpoint.Properties.timeOutDuration, EsbMessages.APIResourceEndpointPropertiesEditionPart_TimeOutDurationLabel); timeOutDuration = SWTUtils.createScrollableText(parent, SWT.BORDER); GridData timeOutDurationData = new GridData(GridData.FILL_HORIZONTAL); timeOutDuration.setLayoutData(timeOutDurationData); timeOutDuration.addFocusListener(new FocusAdapter() { /** * {@inheritDoc} * * @see org.eclipse.swt.events.FocusAdapter#focusLost(org.eclipse.swt.events.FocusEvent) * */ @Override @SuppressWarnings("synthetic-access") public void focusLost(FocusEvent e) { if (propertiesEditionComponent != null) propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(APIResourceEndpointPropertiesEditionPartImpl.this, EsbViewsRepository.APIResourceEndpoint.Properties.timeOutDuration, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, timeOutDuration.getText())); } }); timeOutDuration.addKeyListener(new KeyAdapter() { /** * {@inheritDoc} * * @see org.eclipse.swt.events.KeyAdapter#keyPressed(org.eclipse.swt.events.KeyEvent) * */ @Override @SuppressWarnings("synthetic-access") public void keyPressed(KeyEvent e) { if (e.character == SWT.CR) { if (propertiesEditionComponent != null) propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(APIResourceEndpointPropertiesEditionPartImpl.this, EsbViewsRepository.APIResourceEndpoint.Properties.timeOutDuration, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, timeOutDuration.getText())); } } }); EditingUtils.setID(timeOutDuration, EsbViewsRepository.APIResourceEndpoint.Properties.timeOutDuration); EditingUtils.setEEFtype(timeOutDuration, "eef::Text"); //$NON-NLS-1$ SWTUtils.createHelpButton(parent, propertiesEditionComponent.getHelpContent(EsbViewsRepository.APIResourceEndpoint.Properties.timeOutDuration, EsbViewsRepository.SWT_KIND), null); //$NON-NLS-1$ // Start of user code for createTimeOutDurationText // End of user code return parent; } /** * @generated NOT */ protected Composite createTimeOutActionEMFComboViewer(Composite parent) { createDescription(parent, EsbViewsRepository.APIResourceEndpoint.Properties.timeOutAction, EsbMessages.APIResourceEndpointPropertiesEditionPart_TimeOutActionLabel); timeOutAction = new EMFComboViewer(parent); timeOutAction.setContentProvider(new ArrayContentProvider()); timeOutAction.setLabelProvider(new AdapterFactoryLabelProvider(EEFRuntimePlugin.getDefault().getAdapterFactory())); GridData timeOutActionData = new GridData(GridData.FILL_HORIZONTAL); timeOutAction.getCombo().setLayoutData(timeOutActionData); timeOutAction.getCombo().addListener(SWT.MouseVerticalWheel, new Listener() { @Override public void handleEvent(Event arg0) { arg0.doit = false; } }); timeOutAction.addSelectionChangedListener(new ISelectionChangedListener() { /** * {@inheritDoc} * * @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent) * */ public void selectionChanged(SelectionChangedEvent event) { if (propertiesEditionComponent != null) propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(APIResourceEndpointPropertiesEditionPartImpl.this, EsbViewsRepository.APIResourceEndpoint.Properties.timeOutAction, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, getTimeOutAction())); } }); timeOutAction.setID(EsbViewsRepository.APIResourceEndpoint.Properties.timeOutAction); SWTUtils.createHelpButton(parent, propertiesEditionComponent.getHelpContent(EsbViewsRepository.APIResourceEndpoint.Properties.timeOutAction, EsbViewsRepository.SWT_KIND), null); //$NON-NLS-1$ // Start of user code for createTimeOutActionEMFComboViewer // End of user code return parent; } protected Composite createRetryErrorCodesText(Composite parent) { createDescription(parent, EsbViewsRepository.APIResourceEndpoint.Properties.retryErrorCodes, EsbMessages.APIResourceEndpointPropertiesEditionPart_RetryErrorCodesLabel); retryErrorCodes = SWTUtils.createScrollableText(parent, SWT.BORDER); GridData retryErrorCodesData = new GridData(GridData.FILL_HORIZONTAL); retryErrorCodes.setLayoutData(retryErrorCodesData); retryErrorCodes.addFocusListener(new FocusAdapter() { /** * {@inheritDoc} * * @see org.eclipse.swt.events.FocusAdapter#focusLost(org.eclipse.swt.events.FocusEvent) * */ @Override @SuppressWarnings("synthetic-access") public void focusLost(FocusEvent e) { if (propertiesEditionComponent != null) propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(APIResourceEndpointPropertiesEditionPartImpl.this, EsbViewsRepository.APIResourceEndpoint.Properties.retryErrorCodes, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, retryErrorCodes.getText())); } }); retryErrorCodes.addKeyListener(new KeyAdapter() { /** * {@inheritDoc} * * @see org.eclipse.swt.events.KeyAdapter#keyPressed(org.eclipse.swt.events.KeyEvent) * */ @Override @SuppressWarnings("synthetic-access") public void keyPressed(KeyEvent e) { if (e.character == SWT.CR) { if (propertiesEditionComponent != null) propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(APIResourceEndpointPropertiesEditionPartImpl.this, EsbViewsRepository.APIResourceEndpoint.Properties.retryErrorCodes, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, retryErrorCodes.getText())); } } }); EditingUtils.setID(retryErrorCodes, EsbViewsRepository.APIResourceEndpoint.Properties.retryErrorCodes); EditingUtils.setEEFtype(retryErrorCodes, "eef::Text"); //$NON-NLS-1$ SWTUtils.createHelpButton(parent, propertiesEditionComponent.getHelpContent(EsbViewsRepository.APIResourceEndpoint.Properties.retryErrorCodes, EsbViewsRepository.SWT_KIND), null); //$NON-NLS-1$ // Start of user code for createRetryErrorCodesText // End of user code return parent; } protected Composite createRetryCountText(Composite parent) { createDescription(parent, EsbViewsRepository.APIResourceEndpoint.Properties.retryCount, EsbMessages.APIResourceEndpointPropertiesEditionPart_RetryCountLabel); retryCount = SWTUtils.createScrollableText(parent, SWT.BORDER); GridData retryCountData = new GridData(GridData.FILL_HORIZONTAL); retryCount.setLayoutData(retryCountData); retryCount.addFocusListener(new FocusAdapter() { /** * {@inheritDoc} * * @see org.eclipse.swt.events.FocusAdapter#focusLost(org.eclipse.swt.events.FocusEvent) * */ @Override @SuppressWarnings("synthetic-access") public void focusLost(FocusEvent e) { if (propertiesEditionComponent != null) propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(APIResourceEndpointPropertiesEditionPartImpl.this, EsbViewsRepository.APIResourceEndpoint.Properties.retryCount, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, retryCount.getText())); } }); retryCount.addKeyListener(new KeyAdapter() { /** * {@inheritDoc} * * @see org.eclipse.swt.events.KeyAdapter#keyPressed(org.eclipse.swt.events.KeyEvent) * */ @Override @SuppressWarnings("synthetic-access") public void keyPressed(KeyEvent e) { if (e.character == SWT.CR) { if (propertiesEditionComponent != null) propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(APIResourceEndpointPropertiesEditionPartImpl.this, EsbViewsRepository.APIResourceEndpoint.Properties.retryCount, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, retryCount.getText())); } } }); EditingUtils.setID(retryCount, EsbViewsRepository.APIResourceEndpoint.Properties.retryCount); EditingUtils.setEEFtype(retryCount, "eef::Text"); //$NON-NLS-1$ SWTUtils.createHelpButton(parent, propertiesEditionComponent.getHelpContent(EsbViewsRepository.APIResourceEndpoint.Properties.retryCount, EsbViewsRepository.SWT_KIND), null); //$NON-NLS-1$ // Start of user code for createRetryCountText // End of user code return parent; } protected Composite createRetryDelayText(Composite parent) { createDescription(parent, EsbViewsRepository.APIResourceEndpoint.Properties.retryDelay, EsbMessages.APIResourceEndpointPropertiesEditionPart_RetryDelayLabel); retryDelay = SWTUtils.createScrollableText(parent, SWT.BORDER); GridData retryDelayData = new GridData(GridData.FILL_HORIZONTAL); retryDelay.setLayoutData(retryDelayData); retryDelay.addFocusListener(new FocusAdapter() { /** * {@inheritDoc} * * @see org.eclipse.swt.events.FocusAdapter#focusLost(org.eclipse.swt.events.FocusEvent) * */ @Override @SuppressWarnings("synthetic-access") public void focusLost(FocusEvent e) { if (propertiesEditionComponent != null) propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(APIResourceEndpointPropertiesEditionPartImpl.this, EsbViewsRepository.APIResourceEndpoint.Properties.retryDelay, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, retryDelay.getText())); } }); retryDelay.addKeyListener(new KeyAdapter() { /** * {@inheritDoc} * * @see org.eclipse.swt.events.KeyAdapter#keyPressed(org.eclipse.swt.events.KeyEvent) * */ @Override @SuppressWarnings("synthetic-access") public void keyPressed(KeyEvent e) { if (e.character == SWT.CR) { if (propertiesEditionComponent != null) propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(APIResourceEndpointPropertiesEditionPartImpl.this, EsbViewsRepository.APIResourceEndpoint.Properties.retryDelay, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, retryDelay.getText())); } } }); EditingUtils.setID(retryDelay, EsbViewsRepository.APIResourceEndpoint.Properties.retryDelay); EditingUtils.setEEFtype(retryDelay, "eef::Text"); //$NON-NLS-1$ SWTUtils.createHelpButton(parent, propertiesEditionComponent.getHelpContent(EsbViewsRepository.APIResourceEndpoint.Properties.retryDelay, EsbViewsRepository.SWT_KIND), null); //$NON-NLS-1$ // Start of user code for createRetryDelayText // End of user code return parent; } protected Composite createSuspendErrorCodesText(Composite parent) { createDescription(parent, EsbViewsRepository.APIResourceEndpoint.Properties.suspendErrorCodes, EsbMessages.APIResourceEndpointPropertiesEditionPart_SuspendErrorCodesLabel); suspendErrorCodes = SWTUtils.createScrollableText(parent, SWT.BORDER); GridData suspendErrorCodesData = new GridData(GridData.FILL_HORIZONTAL); suspendErrorCodes.setLayoutData(suspendErrorCodesData); suspendErrorCodes.addFocusListener(new FocusAdapter() { /** * {@inheritDoc} * * @see org.eclipse.swt.events.FocusAdapter#focusLost(org.eclipse.swt.events.FocusEvent) * */ @Override @SuppressWarnings("synthetic-access") public void focusLost(FocusEvent e) { if (propertiesEditionComponent != null) propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(APIResourceEndpointPropertiesEditionPartImpl.this, EsbViewsRepository.APIResourceEndpoint.Properties.suspendErrorCodes, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, suspendErrorCodes.getText())); } }); suspendErrorCodes.addKeyListener(new KeyAdapter() { /** * {@inheritDoc} * * @see org.eclipse.swt.events.KeyAdapter#keyPressed(org.eclipse.swt.events.KeyEvent) * */ @Override @SuppressWarnings("synthetic-access") public void keyPressed(KeyEvent e) { if (e.character == SWT.CR) { if (propertiesEditionComponent != null) propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(APIResourceEndpointPropertiesEditionPartImpl.this, EsbViewsRepository.APIResourceEndpoint.Properties.suspendErrorCodes, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, suspendErrorCodes.getText())); } } }); EditingUtils.setID(suspendErrorCodes, EsbViewsRepository.APIResourceEndpoint.Properties.suspendErrorCodes); EditingUtils.setEEFtype(suspendErrorCodes, "eef::Text"); //$NON-NLS-1$ SWTUtils.createHelpButton(parent, propertiesEditionComponent.getHelpContent(EsbViewsRepository.APIResourceEndpoint.Properties.suspendErrorCodes, EsbViewsRepository.SWT_KIND), null); //$NON-NLS-1$ // Start of user code for createSuspendErrorCodesText // End of user code return parent; } protected Composite createSuspendInitialDurationText(Composite parent) { createDescription(parent, EsbViewsRepository.APIResourceEndpoint.Properties.suspendInitialDuration, EsbMessages.APIResourceEndpointPropertiesEditionPart_SuspendInitialDurationLabel); suspendInitialDuration = SWTUtils.createScrollableText(parent, SWT.BORDER); GridData suspendInitialDurationData = new GridData(GridData.FILL_HORIZONTAL); suspendInitialDuration.setLayoutData(suspendInitialDurationData); suspendInitialDuration.addFocusListener(new FocusAdapter() { /** * {@inheritDoc} * * @see org.eclipse.swt.events.FocusAdapter#focusLost(org.eclipse.swt.events.FocusEvent) * */ @Override @SuppressWarnings("synthetic-access") public void focusLost(FocusEvent e) { if (propertiesEditionComponent != null) propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(APIResourceEndpointPropertiesEditionPartImpl.this, EsbViewsRepository.APIResourceEndpoint.Properties.suspendInitialDuration, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, suspendInitialDuration.getText())); } }); suspendInitialDuration.addKeyListener(new KeyAdapter() { /** * {@inheritDoc} * * @see org.eclipse.swt.events.KeyAdapter#keyPressed(org.eclipse.swt.events.KeyEvent) * */ @Override @SuppressWarnings("synthetic-access") public void keyPressed(KeyEvent e) { if (e.character == SWT.CR) { if (propertiesEditionComponent != null) propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(APIResourceEndpointPropertiesEditionPartImpl.this, EsbViewsRepository.APIResourceEndpoint.Properties.suspendInitialDuration, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, suspendInitialDuration.getText())); } } }); EditingUtils.setID(suspendInitialDuration, EsbViewsRepository.APIResourceEndpoint.Properties.suspendInitialDuration); EditingUtils.setEEFtype(suspendInitialDuration, "eef::Text"); //$NON-NLS-1$ SWTUtils.createHelpButton(parent, propertiesEditionComponent.getHelpContent(EsbViewsRepository.APIResourceEndpoint.Properties.suspendInitialDuration, EsbViewsRepository.SWT_KIND), null); //$NON-NLS-1$ // Start of user code for createSuspendInitialDurationText // End of user code return parent; } protected Composite createSuspendMaximumDurationText(Composite parent) { createDescription(parent, EsbViewsRepository.APIResourceEndpoint.Properties.suspendMaximumDuration, EsbMessages.APIResourceEndpointPropertiesEditionPart_SuspendMaximumDurationLabel); suspendMaximumDuration = SWTUtils.createScrollableText(parent, SWT.BORDER); GridData suspendMaximumDurationData = new GridData(GridData.FILL_HORIZONTAL); suspendMaximumDuration.setLayoutData(suspendMaximumDurationData); suspendMaximumDuration.addFocusListener(new FocusAdapter() { /** * {@inheritDoc} * * @see org.eclipse.swt.events.FocusAdapter#focusLost(org.eclipse.swt.events.FocusEvent) * */ @Override @SuppressWarnings("synthetic-access") public void focusLost(FocusEvent e) { if (propertiesEditionComponent != null) propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(APIResourceEndpointPropertiesEditionPartImpl.this, EsbViewsRepository.APIResourceEndpoint.Properties.suspendMaximumDuration, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, suspendMaximumDuration.getText())); } }); suspendMaximumDuration.addKeyListener(new KeyAdapter() { /** * {@inheritDoc} * * @see org.eclipse.swt.events.KeyAdapter#keyPressed(org.eclipse.swt.events.KeyEvent) * */ @Override @SuppressWarnings("synthetic-access") public void keyPressed(KeyEvent e) { if (e.character == SWT.CR) { if (propertiesEditionComponent != null) propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(APIResourceEndpointPropertiesEditionPartImpl.this, EsbViewsRepository.APIResourceEndpoint.Properties.suspendMaximumDuration, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, suspendMaximumDuration.getText())); } } }); EditingUtils.setID(suspendMaximumDuration, EsbViewsRepository.APIResourceEndpoint.Properties.suspendMaximumDuration); EditingUtils.setEEFtype(suspendMaximumDuration, "eef::Text"); //$NON-NLS-1$ SWTUtils.createHelpButton(parent, propertiesEditionComponent.getHelpContent(EsbViewsRepository.APIResourceEndpoint.Properties.suspendMaximumDuration, EsbViewsRepository.SWT_KIND), null); //$NON-NLS-1$ // Start of user code for createSuspendMaximumDurationText // End of user code return parent; } protected Composite createSuspendProgressionFactorText(Composite parent) { createDescription(parent, EsbViewsRepository.APIResourceEndpoint.Properties.suspendProgressionFactor, EsbMessages.APIResourceEndpointPropertiesEditionPart_SuspendProgressionFactorLabel); suspendProgressionFactor = SWTUtils.createScrollableText(parent, SWT.BORDER); GridData suspendProgressionFactorData = new GridData(GridData.FILL_HORIZONTAL); suspendProgressionFactor.setLayoutData(suspendProgressionFactorData); suspendProgressionFactor.addFocusListener(new FocusAdapter() { /** * {@inheritDoc} * * @see org.eclipse.swt.events.FocusAdapter#focusLost(org.eclipse.swt.events.FocusEvent) * */ @Override @SuppressWarnings("synthetic-access") public void focusLost(FocusEvent e) { if (propertiesEditionComponent != null) propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(APIResourceEndpointPropertiesEditionPartImpl.this, EsbViewsRepository.APIResourceEndpoint.Properties.suspendProgressionFactor, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, suspendProgressionFactor.getText())); } }); suspendProgressionFactor.addKeyListener(new KeyAdapter() { /** * {@inheritDoc} * * @see org.eclipse.swt.events.KeyAdapter#keyPressed(org.eclipse.swt.events.KeyEvent) * */ @Override @SuppressWarnings("synthetic-access") public void keyPressed(KeyEvent e) { if (e.character == SWT.CR) { if (propertiesEditionComponent != null) propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(APIResourceEndpointPropertiesEditionPartImpl.this, EsbViewsRepository.APIResourceEndpoint.Properties.suspendProgressionFactor, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, suspendProgressionFactor.getText())); } } }); EditingUtils.setID(suspendProgressionFactor, EsbViewsRepository.APIResourceEndpoint.Properties.suspendProgressionFactor); EditingUtils.setEEFtype(suspendProgressionFactor, "eef::Text"); //$NON-NLS-1$ SWTUtils.createHelpButton(parent, propertiesEditionComponent.getHelpContent(EsbViewsRepository.APIResourceEndpoint.Properties.suspendProgressionFactor, EsbViewsRepository.SWT_KIND), null); //$NON-NLS-1$ // Start of user code for createSuspendProgressionFactorText // End of user code return parent; } /** * @generated NOT */ protected Composite createFormatEMFComboViewer(Composite parent) { createDescription(parent, EsbViewsRepository.APIResourceEndpoint.Properties.format, EsbMessages.APIResourceEndpointPropertiesEditionPart_FormatLabel); format = new EMFComboViewer(parent); format.setContentProvider(new ArrayContentProvider()); format.setLabelProvider(new AdapterFactoryLabelProvider(EEFRuntimePlugin.getDefault().getAdapterFactory())); GridData formatData = new GridData(GridData.FILL_HORIZONTAL); format.getCombo().setLayoutData(formatData); format.getCombo().addListener(SWT.MouseVerticalWheel, new Listener() { @Override public void handleEvent(Event arg0) { arg0.doit = false; } }); format.addSelectionChangedListener(new ISelectionChangedListener() { /** * {@inheritDoc} * * @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent) * */ public void selectionChanged(SelectionChangedEvent event) { if (propertiesEditionComponent != null) propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(APIResourceEndpointPropertiesEditionPartImpl.this, EsbViewsRepository.APIResourceEndpoint.Properties.format, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, getFormat())); } }); format.setID(EsbViewsRepository.APIResourceEndpoint.Properties.format); SWTUtils.createHelpButton(parent, propertiesEditionComponent.getHelpContent(EsbViewsRepository.APIResourceEndpoint.Properties.format, EsbViewsRepository.SWT_KIND), null); //$NON-NLS-1$ // Start of user code for createFormatEMFComboViewer // End of user code return parent; } /** * @generated NOT */ protected Composite createOptimizeEMFComboViewer(Composite parent) { createDescription(parent, EsbViewsRepository.APIResourceEndpoint.Properties.optimize, EsbMessages.APIResourceEndpointPropertiesEditionPart_OptimizeLabel); optimize = new EMFComboViewer(parent); optimize.setContentProvider(new ArrayContentProvider()); optimize.setLabelProvider(new AdapterFactoryLabelProvider(EEFRuntimePlugin.getDefault().getAdapterFactory())); GridData optimizeData = new GridData(GridData.FILL_HORIZONTAL); optimize.getCombo().setLayoutData(optimizeData); optimize.getCombo().addListener(SWT.MouseVerticalWheel, new Listener() { @Override public void handleEvent(Event arg0) { arg0.doit = false; } }); optimize.addSelectionChangedListener(new ISelectionChangedListener() { /** * {@inheritDoc} * * @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent) * */ public void selectionChanged(SelectionChangedEvent event) { if (propertiesEditionComponent != null) propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(APIResourceEndpointPropertiesEditionPartImpl.this, EsbViewsRepository.APIResourceEndpoint.Properties.optimize, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, getOptimize())); } }); optimize.setID(EsbViewsRepository.APIResourceEndpoint.Properties.optimize); SWTUtils.createHelpButton(parent, propertiesEditionComponent.getHelpContent(EsbViewsRepository.APIResourceEndpoint.Properties.optimize, EsbViewsRepository.SWT_KIND), null); //$NON-NLS-1$ // Start of user code for createOptimizeEMFComboViewer // End of user code return parent; } /** * @param container * */ protected Composite createTemplateParametersAdvancedTableComposition(Composite parent) { this.templateParameters = new ReferencesTable(getDescription(EsbViewsRepository.APIResourceEndpoint.Properties.templateParameters, EsbMessages.APIResourceEndpointPropertiesEditionPart_TemplateParametersLabel), new ReferencesTableListener() { public void handleAdd() { propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(APIResourceEndpointPropertiesEditionPartImpl.this, EsbViewsRepository.APIResourceEndpoint.Properties.templateParameters, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.ADD, null, null)); templateParameters.refresh(); } public void handleEdit(EObject element) { propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(APIResourceEndpointPropertiesEditionPartImpl.this, EsbViewsRepository.APIResourceEndpoint.Properties.templateParameters, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.EDIT, null, element)); templateParameters.refresh(); } public void handleMove(EObject element, int oldIndex, int newIndex) { propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(APIResourceEndpointPropertiesEditionPartImpl.this, EsbViewsRepository.APIResourceEndpoint.Properties.templateParameters, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.MOVE, element, newIndex)); templateParameters.refresh(); } public void handleRemove(EObject element) { propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(APIResourceEndpointPropertiesEditionPartImpl.this, EsbViewsRepository.APIResourceEndpoint.Properties.templateParameters, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.REMOVE, null, element)); templateParameters.refresh(); } public void navigateTo(EObject element) { } }); for (ViewerFilter filter : this.templateParametersFilters) { this.templateParameters.addFilter(filter); } this.templateParameters.setHelpText(propertiesEditionComponent.getHelpContent(EsbViewsRepository.APIResourceEndpoint.Properties.templateParameters, EsbViewsRepository.SWT_KIND)); this.templateParameters.createControls(parent); this.templateParameters.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { if (e.item != null && e.item.getData() instanceof EObject) { propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(APIResourceEndpointPropertiesEditionPartImpl.this, EsbViewsRepository.APIResourceEndpoint.Properties.templateParameters, PropertiesEditionEvent.CHANGE, PropertiesEditionEvent.SELECTION_CHANGED, null, e.item.getData())); } } }); GridData templateParametersData = new GridData(GridData.FILL_HORIZONTAL); templateParametersData.horizontalSpan = 3; this.templateParameters.setLayoutData(templateParametersData); this.templateParameters.setLowerBound(0); this.templateParameters.setUpperBound(-1); templateParameters.setID(EsbViewsRepository.APIResourceEndpoint.Properties.templateParameters); templateParameters.setEEFType("eef::AdvancedTableComposition"); //$NON-NLS-1$ // Start of user code for createTemplateParametersAdvancedTableComposition // End of user code return parent; } protected Composite createStatisticsEnabledCheckbox(Composite parent) { statisticsEnabled = new Button(parent, SWT.CHECK); statisticsEnabled.setText(getDescription(EsbViewsRepository.APIResourceEndpoint.Properties.statisticsEnabled, EsbMessages.APIResourceEndpointPropertiesEditionPart_StatisticsEnabledLabel)); statisticsEnabled.addSelectionListener(new SelectionAdapter() { /** * {@inheritDoc} * * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent) * */ public void widgetSelected(SelectionEvent e) { if (propertiesEditionComponent != null) propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(APIResourceEndpointPropertiesEditionPartImpl.this, EsbViewsRepository.APIResourceEndpoint.Properties.statisticsEnabled, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, new Boolean(statisticsEnabled.getSelection()))); } }); GridData statisticsEnabledData = new GridData(GridData.FILL_HORIZONTAL); statisticsEnabledData.horizontalSpan = 2; statisticsEnabled.setLayoutData(statisticsEnabledData); EditingUtils.setID(statisticsEnabled, EsbViewsRepository.APIResourceEndpoint.Properties.statisticsEnabled); EditingUtils.setEEFtype(statisticsEnabled, "eef::Checkbox"); //$NON-NLS-1$ SWTUtils.createHelpButton(parent, propertiesEditionComponent.getHelpContent(EsbViewsRepository.APIResourceEndpoint.Properties.statisticsEnabled, EsbViewsRepository.SWT_KIND), null); //$NON-NLS-1$ // Start of user code for createStatisticsEnabledCheckbox // End of user code return parent; } protected Composite createTraceEnabledCheckbox(Composite parent) { traceEnabled = new Button(parent, SWT.CHECK); traceEnabled.setText(getDescription(EsbViewsRepository.APIResourceEndpoint.Properties.traceEnabled, EsbMessages.APIResourceEndpointPropertiesEditionPart_TraceEnabledLabel)); traceEnabled.addSelectionListener(new SelectionAdapter() { /** * {@inheritDoc} * * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent) * */ public void widgetSelected(SelectionEvent e) { if (propertiesEditionComponent != null) propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(APIResourceEndpointPropertiesEditionPartImpl.this, EsbViewsRepository.APIResourceEndpoint.Properties.traceEnabled, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, new Boolean(traceEnabled.getSelection()))); } }); GridData traceEnabledData = new GridData(GridData.FILL_HORIZONTAL); traceEnabledData.horizontalSpan = 2; traceEnabled.setLayoutData(traceEnabledData); EditingUtils.setID(traceEnabled, EsbViewsRepository.APIResourceEndpoint.Properties.traceEnabled); EditingUtils.setEEFtype(traceEnabled, "eef::Checkbox"); //$NON-NLS-1$ SWTUtils.createHelpButton(parent, propertiesEditionComponent.getHelpContent(EsbViewsRepository.APIResourceEndpoint.Properties.traceEnabled, EsbViewsRepository.SWT_KIND), null); //$NON-NLS-1$ // Start of user code for createTraceEnabledCheckbox // End of user code return parent; } /** * {@inheritDoc} * * @see org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionListener#firePropertiesChanged(org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionEvent) * */ public void firePropertiesChanged(IPropertiesEditionEvent event) { // Start of user code for tab synchronization // End of user code } /** * {@inheritDoc} * * @see org.wso2.integrationstudio.gmf.esb.parts.APIResourceEndpointPropertiesEditionPart#getDescription() * */ public String getDescription() { return description.getText(); } /** * {@inheritDoc} * * @see org.wso2.integrationstudio.gmf.esb.parts.APIResourceEndpointPropertiesEditionPart#setDescription(String newValue) * */ public void setDescription(String newValue) { if (newValue != null) { description.setText(newValue); } else { description.setText(""); //$NON-NLS-1$ } boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.APIResourceEndpoint.Properties.description); if (eefElementEditorReadOnlyState && description.isEnabled()) { description.setEnabled(false); description.setToolTipText(EsbMessages.APIResourceEndpoint_ReadOnly); } else if (!eefElementEditorReadOnlyState && !description.isEnabled()) { description.setEnabled(true); } } /** * {@inheritDoc} * * @see org.wso2.integrationstudio.gmf.esb.parts.APIResourceEndpointPropertiesEditionPart#getCommentsList() * */ public EList getCommentsList() { return commentsListList; } /** * {@inheritDoc} * * @see org.wso2.integrationstudio.gmf.esb.parts.APIResourceEndpointPropertiesEditionPart#setCommentsList(EList newValue) * */ public void setCommentsList(EList newValue) { commentsListList = newValue; if (newValue != null) { commentsList.setText(commentsListList.toString()); } else { commentsList.setText(""); //$NON-NLS-1$ } boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.APIResourceEndpoint.Properties.commentsList); if (eefElementEditorReadOnlyState && commentsList.isEnabled()) { commentsList.setEnabled(false); commentsList.setToolTipText(EsbMessages.APIResourceEndpoint_ReadOnly); } else if (!eefElementEditorReadOnlyState && !commentsList.isEnabled()) { commentsList.setEnabled(true); } } public void addToCommentsList(Object newValue) { commentsListList.add(newValue); if (newValue != null) { commentsList.setText(commentsListList.toString()); } else { commentsList.setText(""); //$NON-NLS-1$ } } public void removeToCommentsList(Object newValue) { commentsListList.remove(newValue); if (newValue != null) { commentsList.setText(commentsListList.toString()); } else { commentsList.setText(""); //$NON-NLS-1$ } } /** * {@inheritDoc} * * @see org.wso2.integrationstudio.gmf.esb.parts.APIResourceEndpointPropertiesEditionPart#getEndPointName() * */ public String getEndPointName() { return endPointName.getText(); } /** * {@inheritDoc} * * @see org.wso2.integrationstudio.gmf.esb.parts.APIResourceEndpointPropertiesEditionPart#setEndPointName(String newValue) * */ public void setEndPointName(String newValue) { if (newValue != null) { endPointName.setText(newValue); } else { endPointName.setText(""); //$NON-NLS-1$ } boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.APIResourceEndpoint.Properties.endPointName); if (eefElementEditorReadOnlyState && endPointName.isEnabled()) { endPointName.setEnabled(false); endPointName.setToolTipText(EsbMessages.APIResourceEndpoint_ReadOnly); } else if (!eefElementEditorReadOnlyState && !endPointName.isEnabled()) { endPointName.setEnabled(true); } } /** * {@inheritDoc} * * @see org.wso2.integrationstudio.gmf.esb.parts.APIResourceEndpointPropertiesEditionPart#getAnonymous() * */ public Boolean getAnonymous() { return Boolean.valueOf(anonymous.getSelection()); } /** * {@inheritDoc} * * @see org.wso2.integrationstudio.gmf.esb.parts.APIResourceEndpointPropertiesEditionPart#setAnonymous(Boolean newValue) * */ public void setAnonymous(Boolean newValue) { if (newValue != null) { anonymous.setSelection(newValue.booleanValue()); } else { anonymous.setSelection(false); } boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.APIResourceEndpoint.Properties.anonymous); if (eefElementEditorReadOnlyState && anonymous.isEnabled()) { anonymous.setEnabled(false); anonymous.setToolTipText(EsbMessages.APIResourceEndpoint_ReadOnly); } else if (!eefElementEditorReadOnlyState && !anonymous.isEnabled()) { anonymous.setEnabled(true); } } /** * {@inheritDoc} * * @see org.wso2.integrationstudio.gmf.esb.parts.APIResourceEndpointPropertiesEditionPart#getInLine() * */ public Boolean getInLine() { return Boolean.valueOf(inLine.getSelection()); } /** * {@inheritDoc} * * @see org.wso2.integrationstudio.gmf.esb.parts.APIResourceEndpointPropertiesEditionPart#setInLine(Boolean newValue) * */ public void setInLine(Boolean newValue) { if (newValue != null) { inLine.setSelection(newValue.booleanValue()); } else { inLine.setSelection(false); } boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.APIResourceEndpoint.Properties.inLine); if (eefElementEditorReadOnlyState && inLine.isEnabled()) { inLine.setEnabled(false); inLine.setToolTipText(EsbMessages.APIResourceEndpoint_ReadOnly); } else if (!eefElementEditorReadOnlyState && !inLine.isEnabled()) { inLine.setEnabled(true); } } /** * {@inheritDoc} * * @see org.wso2.integrationstudio.gmf.esb.parts.APIResourceEndpointPropertiesEditionPart#getDuplicate() * */ public Boolean getDuplicate() { return Boolean.valueOf(duplicate.getSelection()); } /** * {@inheritDoc} * * @see org.wso2.integrationstudio.gmf.esb.parts.APIResourceEndpointPropertiesEditionPart#setDuplicate(Boolean newValue) * */ public void setDuplicate(Boolean newValue) { if (newValue != null) { duplicate.setSelection(newValue.booleanValue()); } else { duplicate.setSelection(false); } boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.APIResourceEndpoint.Properties.duplicate); if (eefElementEditorReadOnlyState && duplicate.isEnabled()) { duplicate.setEnabled(false); duplicate.setToolTipText(EsbMessages.APIResourceEndpoint_ReadOnly); } else if (!eefElementEditorReadOnlyState && !duplicate.isEnabled()) { duplicate.setEnabled(true); } } /** * {@inheritDoc} * * @see org.wso2.integrationstudio.gmf.esb.parts.APIResourceEndpointPropertiesEditionPart#initProperties(EObject current, EReference containingFeature, EReference feature) */ public void initProperties(ReferencesTableSettings settings) { if (current.eResource() != null && current.eResource().getResourceSet() != null) this.resourceSet = current.eResource().getResourceSet(); ReferencesTableContentProvider contentProvider = new ReferencesTableContentProvider(); properties.setContentProvider(contentProvider); properties.setInput(settings); boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.APIResourceEndpoint.Properties.properties_); if (eefElementEditorReadOnlyState && properties.isEnabled()) { properties.setEnabled(false); properties.setToolTipText(EsbMessages.APIResourceEndpoint_ReadOnly); } else if (!eefElementEditorReadOnlyState && !properties.isEnabled()) { properties.setEnabled(true); } } /** * {@inheritDoc} * * @see org.wso2.integrationstudio.gmf.esb.parts.APIResourceEndpointPropertiesEditionPart#updateProperties() * */ public void updateProperties() { properties.refresh(); } /** * {@inheritDoc} * * @see org.wso2.integrationstudio.gmf.esb.parts.APIResourceEndpointPropertiesEditionPart#addFilterProperties(ViewerFilter filter) * */ public void addFilterToProperties(ViewerFilter filter) { propertiesFilters.add(filter); if (this.properties != null) { this.properties.addFilter(filter); } } /** * {@inheritDoc} * * @see org.wso2.integrationstudio.gmf.esb.parts.APIResourceEndpointPropertiesEditionPart#addBusinessFilterProperties(ViewerFilter filter) * */ public void addBusinessFilterToProperties(ViewerFilter filter) { propertiesBusinessFilters.add(filter); } /** * {@inheritDoc} * * @see org.wso2.integrationstudio.gmf.esb.parts.APIResourceEndpointPropertiesEditionPart#isContainedInPropertiesTable(EObject element) * */ public boolean isContainedInPropertiesTable(EObject element) { return ((ReferencesTableSettings)properties.getInput()).contains(element); } /** * {@inheritDoc} * * @see org.wso2.integrationstudio.gmf.esb.parts.APIResourceEndpointPropertiesEditionPart#getReversed() * */ public Boolean getReversed() { return Boolean.valueOf(reversed.getSelection()); } /** * {@inheritDoc} * * @see org.wso2.integrationstudio.gmf.esb.parts.APIResourceEndpointPropertiesEditionPart#setReversed(Boolean newValue) * */ public void setReversed(Boolean newValue) { if (newValue != null) { reversed.setSelection(newValue.booleanValue()); } else { reversed.setSelection(false); } boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.APIResourceEndpoint.Properties.reversed); if (eefElementEditorReadOnlyState && reversed.isEnabled()) { reversed.setEnabled(false); reversed.setToolTipText(EsbMessages.APIResourceEndpoint_ReadOnly); } else if (!eefElementEditorReadOnlyState && !reversed.isEnabled()) { reversed.setEnabled(true); } } /** * {@inheritDoc} * * @see org.wso2.integrationstudio.gmf.esb.parts.APIResourceEndpointPropertiesEditionPart#getReliableMessagingEnabled() * */ public Boolean getReliableMessagingEnabled() { return Boolean.valueOf(reliableMessagingEnabled.getSelection()); } /** * {@inheritDoc} * * @see org.wso2.integrationstudio.gmf.esb.parts.APIResourceEndpointPropertiesEditionPart#setReliableMessagingEnabled(Boolean newValue) * */ public void setReliableMessagingEnabled(Boolean newValue) { if (newValue != null) { reliableMessagingEnabled.setSelection(newValue.booleanValue()); } else { reliableMessagingEnabled.setSelection(false); } boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.APIResourceEndpoint.Properties.reliableMessagingEnabled); if (eefElementEditorReadOnlyState && reliableMessagingEnabled.isEnabled()) { reliableMessagingEnabled.setEnabled(false); reliableMessagingEnabled.setToolTipText(EsbMessages.APIResourceEndpoint_ReadOnly); } else if (!eefElementEditorReadOnlyState && !reliableMessagingEnabled.isEnabled()) { reliableMessagingEnabled.setEnabled(true); } } /** * {@inheritDoc} * * @see org.wso2.integrationstudio.gmf.esb.parts.APIResourceEndpointPropertiesEditionPart#getSecurityEnabled() * */ public Boolean getSecurityEnabled() { return Boolean.valueOf(securityEnabled.getSelection()); } /** * {@inheritDoc} * * @see org.wso2.integrationstudio.gmf.esb.parts.APIResourceEndpointPropertiesEditionPart#setSecurityEnabled(Boolean newValue) * */ public void setSecurityEnabled(Boolean newValue) { if (newValue != null) { securityEnabled.setSelection(newValue.booleanValue()); } else { securityEnabled.setSelection(false); } boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.APIResourceEndpoint.Properties.securityEnabled); if (eefElementEditorReadOnlyState && securityEnabled.isEnabled()) { securityEnabled.setEnabled(false); securityEnabled.setToolTipText(EsbMessages.APIResourceEndpoint_ReadOnly); } else if (!eefElementEditorReadOnlyState && !securityEnabled.isEnabled()) { securityEnabled.setEnabled(true); } } /** * {@inheritDoc} * * @see org.wso2.integrationstudio.gmf.esb.parts.APIResourceEndpointPropertiesEditionPart#getAddressingEnabled() * */ public Boolean getAddressingEnabled() { return Boolean.valueOf(addressingEnabled.getSelection()); } /** * {@inheritDoc} * * @see org.wso2.integrationstudio.gmf.esb.parts.APIResourceEndpointPropertiesEditionPart#setAddressingEnabled(Boolean newValue) * */ public void setAddressingEnabled(Boolean newValue) { if (newValue != null) { addressingEnabled.setSelection(newValue.booleanValue()); } else { addressingEnabled.setSelection(false); } boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.APIResourceEndpoint.Properties.addressingEnabled); if (eefElementEditorReadOnlyState && addressingEnabled.isEnabled()) { addressingEnabled.setEnabled(false); addressingEnabled.setToolTipText(EsbMessages.APIResourceEndpoint_ReadOnly); } else if (!eefElementEditorReadOnlyState && !addressingEnabled.isEnabled()) { addressingEnabled.setEnabled(true); } } /** * {@inheritDoc} * * @see org.wso2.integrationstudio.gmf.esb.parts.APIResourceEndpointPropertiesEditionPart#getAddressingVersion() * */ public Enumerator getAddressingVersion() { Enumerator selection = (Enumerator) ((StructuredSelection) addressingVersion.getSelection()).getFirstElement(); return selection; } /** * {@inheritDoc} * * @see org.wso2.integrationstudio.gmf.esb.parts.APIResourceEndpointPropertiesEditionPart#initAddressingVersion(Object input, Enumerator current) */ public void initAddressingVersion(Object input, Enumerator current) { addressingVersion.setInput(input); addressingVersion.modelUpdating(new StructuredSelection(current)); boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.APIResourceEndpoint.Properties.addressingVersion); if (eefElementEditorReadOnlyState && addressingVersion.isEnabled()) { addressingVersion.setEnabled(false); addressingVersion.setToolTipText(EsbMessages.APIResourceEndpoint_ReadOnly); } else if (!eefElementEditorReadOnlyState && !addressingVersion.isEnabled()) { addressingVersion.setEnabled(true); } } /** * {@inheritDoc} * * @see org.wso2.integrationstudio.gmf.esb.parts.APIResourceEndpointPropertiesEditionPart#setAddressingVersion(Enumerator newValue) * */ public void setAddressingVersion(Enumerator newValue) { addressingVersion.modelUpdating(new StructuredSelection(newValue)); boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.APIResourceEndpoint.Properties.addressingVersion); if (eefElementEditorReadOnlyState && addressingVersion.isEnabled()) { addressingVersion.setEnabled(false); addressingVersion.setToolTipText(EsbMessages.APIResourceEndpoint_ReadOnly); } else if (!eefElementEditorReadOnlyState && !addressingVersion.isEnabled()) { addressingVersion.setEnabled(true); } } /** * {@inheritDoc} * * @see org.wso2.integrationstudio.gmf.esb.parts.APIResourceEndpointPropertiesEditionPart#getAddressingSeparateListener() * */ public Boolean getAddressingSeparateListener() { return Boolean.valueOf(addressingSeparateListener.getSelection()); } /** * {@inheritDoc} * * @see org.wso2.integrationstudio.gmf.esb.parts.APIResourceEndpointPropertiesEditionPart#setAddressingSeparateListener(Boolean newValue) * */ public void setAddressingSeparateListener(Boolean newValue) { if (newValue != null) { addressingSeparateListener.setSelection(newValue.booleanValue()); } else { addressingSeparateListener.setSelection(false); } boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.APIResourceEndpoint.Properties.addressingSeparateListener); if (eefElementEditorReadOnlyState && addressingSeparateListener.isEnabled()) { addressingSeparateListener.setEnabled(false); addressingSeparateListener.setToolTipText(EsbMessages.APIResourceEndpoint_ReadOnly); } else if (!eefElementEditorReadOnlyState && !addressingSeparateListener.isEnabled()) { addressingSeparateListener.setEnabled(true); } } /** * {@inheritDoc} * * @see org.wso2.integrationstudio.gmf.esb.parts.APIResourceEndpointPropertiesEditionPart#getTimeOutDuration() * */ public String getTimeOutDuration() { return timeOutDuration.getText(); } /** * {@inheritDoc} * * @see org.wso2.integrationstudio.gmf.esb.parts.APIResourceEndpointPropertiesEditionPart#setTimeOutDuration(String newValue) * */ public void setTimeOutDuration(String newValue) { if (newValue != null) { timeOutDuration.setText(newValue); } else { timeOutDuration.setText(""); //$NON-NLS-1$ } boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.APIResourceEndpoint.Properties.timeOutDuration); if (eefElementEditorReadOnlyState && timeOutDuration.isEnabled()) { timeOutDuration.setEnabled(false); timeOutDuration.setToolTipText(EsbMessages.APIResourceEndpoint_ReadOnly); } else if (!eefElementEditorReadOnlyState && !timeOutDuration.isEnabled()) { timeOutDuration.setEnabled(true); } } /** * {@inheritDoc} * * @see org.wso2.integrationstudio.gmf.esb.parts.APIResourceEndpointPropertiesEditionPart#getTimeOutAction() * */ public Enumerator getTimeOutAction() { Enumerator selection = (Enumerator) ((StructuredSelection) timeOutAction.getSelection()).getFirstElement(); return selection; } /** * {@inheritDoc} * * @see org.wso2.integrationstudio.gmf.esb.parts.APIResourceEndpointPropertiesEditionPart#initTimeOutAction(Object input, Enumerator current) */ public void initTimeOutAction(Object input, Enumerator current) { timeOutAction.setInput(input); timeOutAction.modelUpdating(new StructuredSelection(current)); boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.APIResourceEndpoint.Properties.timeOutAction); if (eefElementEditorReadOnlyState && timeOutAction.isEnabled()) { timeOutAction.setEnabled(false); timeOutAction.setToolTipText(EsbMessages.APIResourceEndpoint_ReadOnly); } else if (!eefElementEditorReadOnlyState && !timeOutAction.isEnabled()) { timeOutAction.setEnabled(true); } } /** * {@inheritDoc} * * @see org.wso2.integrationstudio.gmf.esb.parts.APIResourceEndpointPropertiesEditionPart#setTimeOutAction(Enumerator newValue) * */ public void setTimeOutAction(Enumerator newValue) { timeOutAction.modelUpdating(new StructuredSelection(newValue)); boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.APIResourceEndpoint.Properties.timeOutAction); if (eefElementEditorReadOnlyState && timeOutAction.isEnabled()) { timeOutAction.setEnabled(false); timeOutAction.setToolTipText(EsbMessages.APIResourceEndpoint_ReadOnly); } else if (!eefElementEditorReadOnlyState && !timeOutAction.isEnabled()) { timeOutAction.setEnabled(true); } } /** * {@inheritDoc} * * @see org.wso2.integrationstudio.gmf.esb.parts.APIResourceEndpointPropertiesEditionPart#getRetryErrorCodes() * */ public String getRetryErrorCodes() { return retryErrorCodes.getText(); } /** * {@inheritDoc} * * @see org.wso2.integrationstudio.gmf.esb.parts.APIResourceEndpointPropertiesEditionPart#setRetryErrorCodes(String newValue) * */ public void setRetryErrorCodes(String newValue) { if (newValue != null) { retryErrorCodes.setText(newValue); } else { retryErrorCodes.setText(""); //$NON-NLS-1$ } boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.APIResourceEndpoint.Properties.retryErrorCodes); if (eefElementEditorReadOnlyState && retryErrorCodes.isEnabled()) { retryErrorCodes.setEnabled(false); retryErrorCodes.setToolTipText(EsbMessages.APIResourceEndpoint_ReadOnly); } else if (!eefElementEditorReadOnlyState && !retryErrorCodes.isEnabled()) { retryErrorCodes.setEnabled(true); } } /** * {@inheritDoc} * * @see org.wso2.integrationstudio.gmf.esb.parts.APIResourceEndpointPropertiesEditionPart#getRetryCount() * */ public String getRetryCount() { return retryCount.getText(); } /** * {@inheritDoc} * * @see org.wso2.integrationstudio.gmf.esb.parts.APIResourceEndpointPropertiesEditionPart#setRetryCount(String newValue) * */ public void setRetryCount(String newValue) { if (newValue != null) { retryCount.setText(newValue); } else { retryCount.setText(""); //$NON-NLS-1$ } boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.APIResourceEndpoint.Properties.retryCount); if (eefElementEditorReadOnlyState && retryCount.isEnabled()) { retryCount.setEnabled(false); retryCount.setToolTipText(EsbMessages.APIResourceEndpoint_ReadOnly); } else if (!eefElementEditorReadOnlyState && !retryCount.isEnabled()) { retryCount.setEnabled(true); } } /** * {@inheritDoc} * * @see org.wso2.integrationstudio.gmf.esb.parts.APIResourceEndpointPropertiesEditionPart#getRetryDelay() * */ public String getRetryDelay() { return retryDelay.getText(); } /** * {@inheritDoc} * * @see org.wso2.integrationstudio.gmf.esb.parts.APIResourceEndpointPropertiesEditionPart#setRetryDelay(String newValue) * */ public void setRetryDelay(String newValue) { if (newValue != null) { retryDelay.setText(newValue); } else { retryDelay.setText(""); //$NON-NLS-1$ } boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.APIResourceEndpoint.Properties.retryDelay); if (eefElementEditorReadOnlyState && retryDelay.isEnabled()) { retryDelay.setEnabled(false); retryDelay.setToolTipText(EsbMessages.APIResourceEndpoint_ReadOnly); } else if (!eefElementEditorReadOnlyState && !retryDelay.isEnabled()) { retryDelay.setEnabled(true); } } /** * {@inheritDoc} * * @see org.wso2.integrationstudio.gmf.esb.parts.APIResourceEndpointPropertiesEditionPart#getSuspendErrorCodes() * */ public String getSuspendErrorCodes() { return suspendErrorCodes.getText(); } /** * {@inheritDoc} * * @see org.wso2.integrationstudio.gmf.esb.parts.APIResourceEndpointPropertiesEditionPart#setSuspendErrorCodes(String newValue) * */ public void setSuspendErrorCodes(String newValue) { if (newValue != null) { suspendErrorCodes.setText(newValue); } else { suspendErrorCodes.setText(""); //$NON-NLS-1$ } boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.APIResourceEndpoint.Properties.suspendErrorCodes); if (eefElementEditorReadOnlyState && suspendErrorCodes.isEnabled()) { suspendErrorCodes.setEnabled(false); suspendErrorCodes.setToolTipText(EsbMessages.APIResourceEndpoint_ReadOnly); } else if (!eefElementEditorReadOnlyState && !suspendErrorCodes.isEnabled()) { suspendErrorCodes.setEnabled(true); } } /** * {@inheritDoc} * * @see org.wso2.integrationstudio.gmf.esb.parts.APIResourceEndpointPropertiesEditionPart#getSuspendInitialDuration() * */ public String getSuspendInitialDuration() { return suspendInitialDuration.getText(); } /** * {@inheritDoc} * * @see org.wso2.integrationstudio.gmf.esb.parts.APIResourceEndpointPropertiesEditionPart#setSuspendInitialDuration(String newValue) * */ public void setSuspendInitialDuration(String newValue) { if (newValue != null) { suspendInitialDuration.setText(newValue); } else { suspendInitialDuration.setText(""); //$NON-NLS-1$ } boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.APIResourceEndpoint.Properties.suspendInitialDuration); if (eefElementEditorReadOnlyState && suspendInitialDuration.isEnabled()) { suspendInitialDuration.setEnabled(false); suspendInitialDuration.setToolTipText(EsbMessages.APIResourceEndpoint_ReadOnly); } else if (!eefElementEditorReadOnlyState && !suspendInitialDuration.isEnabled()) { suspendInitialDuration.setEnabled(true); } } /** * {@inheritDoc} * * @see org.wso2.integrationstudio.gmf.esb.parts.APIResourceEndpointPropertiesEditionPart#getSuspendMaximumDuration() * */ public String getSuspendMaximumDuration() { return suspendMaximumDuration.getText(); } /** * {@inheritDoc} * * @see org.wso2.integrationstudio.gmf.esb.parts.APIResourceEndpointPropertiesEditionPart#setSuspendMaximumDuration(String newValue) * */ public void setSuspendMaximumDuration(String newValue) { if (newValue != null) { suspendMaximumDuration.setText(newValue); } else { suspendMaximumDuration.setText(""); //$NON-NLS-1$ } boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.APIResourceEndpoint.Properties.suspendMaximumDuration); if (eefElementEditorReadOnlyState && suspendMaximumDuration.isEnabled()) { suspendMaximumDuration.setEnabled(false); suspendMaximumDuration.setToolTipText(EsbMessages.APIResourceEndpoint_ReadOnly); } else if (!eefElementEditorReadOnlyState && !suspendMaximumDuration.isEnabled()) { suspendMaximumDuration.setEnabled(true); } } /** * {@inheritDoc} * * @see org.wso2.integrationstudio.gmf.esb.parts.APIResourceEndpointPropertiesEditionPart#getSuspendProgressionFactor() * */ public String getSuspendProgressionFactor() { return suspendProgressionFactor.getText(); } /** * {@inheritDoc} * * @see org.wso2.integrationstudio.gmf.esb.parts.APIResourceEndpointPropertiesEditionPart#setSuspendProgressionFactor(String newValue) * */ public void setSuspendProgressionFactor(String newValue) { if (newValue != null) { suspendProgressionFactor.setText(newValue); } else { suspendProgressionFactor.setText(""); //$NON-NLS-1$ } boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.APIResourceEndpoint.Properties.suspendProgressionFactor); if (eefElementEditorReadOnlyState && suspendProgressionFactor.isEnabled()) { suspendProgressionFactor.setEnabled(false); suspendProgressionFactor.setToolTipText(EsbMessages.APIResourceEndpoint_ReadOnly); } else if (!eefElementEditorReadOnlyState && !suspendProgressionFactor.isEnabled()) { suspendProgressionFactor.setEnabled(true); } } /** * {@inheritDoc} * * @see org.wso2.integrationstudio.gmf.esb.parts.APIResourceEndpointPropertiesEditionPart#getFormat() * */ public Enumerator getFormat() { Enumerator selection = (Enumerator) ((StructuredSelection) format.getSelection()).getFirstElement(); return selection; } /** * {@inheritDoc} * * @see org.wso2.integrationstudio.gmf.esb.parts.APIResourceEndpointPropertiesEditionPart#initFormat(Object input, Enumerator current) */ public void initFormat(Object input, Enumerator current) { format.setInput(input); format.modelUpdating(new StructuredSelection(current)); boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.APIResourceEndpoint.Properties.format); if (eefElementEditorReadOnlyState && format.isEnabled()) { format.setEnabled(false); format.setToolTipText(EsbMessages.APIResourceEndpoint_ReadOnly); } else if (!eefElementEditorReadOnlyState && !format.isEnabled()) { format.setEnabled(true); } } /** * {@inheritDoc} * * @see org.wso2.integrationstudio.gmf.esb.parts.APIResourceEndpointPropertiesEditionPart#setFormat(Enumerator newValue) * */ public void setFormat(Enumerator newValue) { format.modelUpdating(new StructuredSelection(newValue)); boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.APIResourceEndpoint.Properties.format); if (eefElementEditorReadOnlyState && format.isEnabled()) { format.setEnabled(false); format.setToolTipText(EsbMessages.APIResourceEndpoint_ReadOnly); } else if (!eefElementEditorReadOnlyState && !format.isEnabled()) { format.setEnabled(true); } } /** * {@inheritDoc} * * @see org.wso2.integrationstudio.gmf.esb.parts.APIResourceEndpointPropertiesEditionPart#getOptimize() * */ public Enumerator getOptimize() { Enumerator selection = (Enumerator) ((StructuredSelection) optimize.getSelection()).getFirstElement(); return selection; } /** * {@inheritDoc} * * @see org.wso2.integrationstudio.gmf.esb.parts.APIResourceEndpointPropertiesEditionPart#initOptimize(Object input, Enumerator current) */ public void initOptimize(Object input, Enumerator current) { optimize.setInput(input); optimize.modelUpdating(new StructuredSelection(current)); boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.APIResourceEndpoint.Properties.optimize); if (eefElementEditorReadOnlyState && optimize.isEnabled()) { optimize.setEnabled(false); optimize.setToolTipText(EsbMessages.APIResourceEndpoint_ReadOnly); } else if (!eefElementEditorReadOnlyState && !optimize.isEnabled()) { optimize.setEnabled(true); } } /** * {@inheritDoc} * * @see org.wso2.integrationstudio.gmf.esb.parts.APIResourceEndpointPropertiesEditionPart#setOptimize(Enumerator newValue) * */ public void setOptimize(Enumerator newValue) { optimize.modelUpdating(new StructuredSelection(newValue)); boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.APIResourceEndpoint.Properties.optimize); if (eefElementEditorReadOnlyState && optimize.isEnabled()) { optimize.setEnabled(false); optimize.setToolTipText(EsbMessages.APIResourceEndpoint_ReadOnly); } else if (!eefElementEditorReadOnlyState && !optimize.isEnabled()) { optimize.setEnabled(true); } } /** * {@inheritDoc} * * @see org.wso2.integrationstudio.gmf.esb.parts.APIResourceEndpointPropertiesEditionPart#initTemplateParameters(EObject current, EReference containingFeature, EReference feature) */ public void initTemplateParameters(ReferencesTableSettings settings) { if (current.eResource() != null && current.eResource().getResourceSet() != null) this.resourceSet = current.eResource().getResourceSet(); ReferencesTableContentProvider contentProvider = new ReferencesTableContentProvider(); templateParameters.setContentProvider(contentProvider); templateParameters.setInput(settings); boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.APIResourceEndpoint.Properties.templateParameters); if (eefElementEditorReadOnlyState && templateParameters.isEnabled()) { templateParameters.setEnabled(false); templateParameters.setToolTipText(EsbMessages.APIResourceEndpoint_ReadOnly); } else if (!eefElementEditorReadOnlyState && !templateParameters.isEnabled()) { templateParameters.setEnabled(true); } } /** * {@inheritDoc} * * @see org.wso2.integrationstudio.gmf.esb.parts.APIResourceEndpointPropertiesEditionPart#updateTemplateParameters() * */ public void updateTemplateParameters() { templateParameters.refresh(); } /** * {@inheritDoc} * * @see org.wso2.integrationstudio.gmf.esb.parts.APIResourceEndpointPropertiesEditionPart#addFilterTemplateParameters(ViewerFilter filter) * */ public void addFilterToTemplateParameters(ViewerFilter filter) { templateParametersFilters.add(filter); if (this.templateParameters != null) { this.templateParameters.addFilter(filter); } } /** * {@inheritDoc} * * @see org.wso2.integrationstudio.gmf.esb.parts.APIResourceEndpointPropertiesEditionPart#addBusinessFilterTemplateParameters(ViewerFilter filter) * */ public void addBusinessFilterToTemplateParameters(ViewerFilter filter) { templateParametersBusinessFilters.add(filter); } /** * {@inheritDoc} * * @see org.wso2.integrationstudio.gmf.esb.parts.APIResourceEndpointPropertiesEditionPart#isContainedInTemplateParametersTable(EObject element) * */ public boolean isContainedInTemplateParametersTable(EObject element) { return ((ReferencesTableSettings)templateParameters.getInput()).contains(element); } /** * {@inheritDoc} * * @see org.wso2.integrationstudio.gmf.esb.parts.APIResourceEndpointPropertiesEditionPart#getStatisticsEnabled() * */ public Boolean getStatisticsEnabled() { return Boolean.valueOf(statisticsEnabled.getSelection()); } /** * {@inheritDoc} * * @see org.wso2.integrationstudio.gmf.esb.parts.APIResourceEndpointPropertiesEditionPart#setStatisticsEnabled(Boolean newValue) * */ public void setStatisticsEnabled(Boolean newValue) { if (newValue != null) { statisticsEnabled.setSelection(newValue.booleanValue()); } else { statisticsEnabled.setSelection(false); } boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.APIResourceEndpoint.Properties.statisticsEnabled); if (eefElementEditorReadOnlyState && statisticsEnabled.isEnabled()) { statisticsEnabled.setEnabled(false); statisticsEnabled.setToolTipText(EsbMessages.APIResourceEndpoint_ReadOnly); } else if (!eefElementEditorReadOnlyState && !statisticsEnabled.isEnabled()) { statisticsEnabled.setEnabled(true); } } /** * {@inheritDoc} * * @see org.wso2.integrationstudio.gmf.esb.parts.APIResourceEndpointPropertiesEditionPart#getTraceEnabled() * */ public Boolean getTraceEnabled() { return Boolean.valueOf(traceEnabled.getSelection()); } /** * {@inheritDoc} * * @see org.wso2.integrationstudio.gmf.esb.parts.APIResourceEndpointPropertiesEditionPart#setTraceEnabled(Boolean newValue) * */ public void setTraceEnabled(Boolean newValue) { if (newValue != null) { traceEnabled.setSelection(newValue.booleanValue()); } else { traceEnabled.setSelection(false); } boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.APIResourceEndpoint.Properties.traceEnabled); if (eefElementEditorReadOnlyState && traceEnabled.isEnabled()) { traceEnabled.setEnabled(false); traceEnabled.setToolTipText(EsbMessages.APIResourceEndpoint_ReadOnly); } else if (!eefElementEditorReadOnlyState && !traceEnabled.isEnabled()) { traceEnabled.setEnabled(true); } } /** * {@inheritDoc} * * @see org.eclipse.emf.eef.runtime.api.parts.IPropertiesEditionPart#getTitle() * */ public String getTitle() { return EsbMessages.APIResourceEndpoint_Part_Title; } // Start of user code additional methods // End of user code }
922faebe2453373ddef458e86cc94848c80808d2
5,012
java
Java
app/src/main/java/me/ycdev/android/demo/lollipopdemo/usage/events/UsageEventsViewerActivity.java
ycdev-demo/LollipopExplorer
fb6457458c29711b776aa89930db09472595e38e
[ "Apache-2.0" ]
3
2015-11-24T07:27:46.000Z
2016-01-26T02:39:17.000Z
app/src/main/java/me/ycdev/android/demo/lollipopdemo/usage/events/UsageEventsViewerActivity.java
ycdev-demo/LollipopExplorer
fb6457458c29711b776aa89930db09472595e38e
[ "Apache-2.0" ]
null
null
null
app/src/main/java/me/ycdev/android/demo/lollipopdemo/usage/events/UsageEventsViewerActivity.java
ycdev-demo/LollipopExplorer
fb6457458c29711b776aa89930db09472595e38e
[ "Apache-2.0" ]
null
null
null
36.318841
99
0.649042
995,205
package me.ycdev.android.demo.lollipopdemo.usage.events; import android.app.Activity; import android.app.usage.UsageEvents; import android.app.usage.UsageStatsManager; import android.content.pm.PackageManager; import android.os.AsyncTask; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.ListView; import android.widget.TextView; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.List; import me.ycdev.android.demo.lollipopdemo.R; import me.ycdev.android.demo.lollipopdemo.usage.utils.UsageStatsUtils; import me.ycdev.android.lib.common.utils.DateTimeUtils; public class UsageEventsViewerActivity extends Activity { private static final String TAG = "AppsUsageViewerActivity"; private TextView mTimeSpanView; private ListView mListView; private UsageEventsViewerAdapter mAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.apps_usage_viewer); initViews(); if (!UsageStatsUtils.checkUsageStatsPermission(this)) { UsageStatsUtils.showPermissionDialog(this); } } private void initViews() { mTimeSpanView = (TextView) findViewById(R.id.stats_timespan); mListView = (ListView) findViewById(R.id.list); mAdapter = new UsageEventsViewerAdapter(getLayoutInflater()); mListView.setAdapter(mAdapter); } @Override protected void onResume() { super.onResume(); if (UsageStatsUtils.checkUsageStatsPermission(this)) { new LoadTask().execute(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.usage_events_viewer, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_sort_by_app_name) { mAdapter.sort(new UsageEventsItem.AppNameComparator()); item.setChecked(true); return true; } else if (id == R.id.action_sort_by_time) { mAdapter.sort(new UsageEventsItem.TimeStampComparator()); item.setChecked(true); return true; } else if (id == R.id.action_settings) { UsageStatsUtils.launchUsageStatsSettings(this); } return super.onOptionsItemSelected(item); } private class LoadTask extends AsyncTask<Void, Void, List<UsageEventsItem>> { private long mStartTime; private long mEndTime; @Override protected void onPreExecute() { // cur month usage Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.DAY_OF_MONTH, 1); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); mStartTime = calendar.getTimeInMillis(); calendar.add(Calendar.MONTH, 1); calendar.add(Calendar.MILLISECOND, -1); mEndTime = calendar.getTimeInMillis(); String startStr = DateTimeUtils.getReadableTimeStamp(mStartTime); String endStr = DateTimeUtils.getReadableTimeStamp(mEndTime); String timeInfo = getString(R.string.apps_usage_timespan, startStr, endStr); mTimeSpanView.setText(timeInfo); } @Override protected List<UsageEventsItem> doInBackground(Void... params) { //noinspection ResourceType UsageStatsManager usageStatsMgr = (UsageStatsManager) getSystemService("usagestats"); UsageEvents events = usageStatsMgr.queryEvents(mStartTime, mEndTime); List<UsageEventsItem> results = new ArrayList<>(); UsageEvents.Event event = new UsageEvents.Event(); PackageManager pm = getPackageManager(); while (events.getNextEvent(event)) { UsageEventsItem item = new UsageEventsItem(); item.pkgName = event.getPackageName(); item.className = event.getClassName(); item.type = event.getEventType(); item.timeStamp = event.getTimeStamp(); item.appName = item.pkgName; try { item.appName = pm.getApplicationInfo(item.pkgName, 0).loadLabel(pm).toString(); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } results.add(item); } Collections.sort(results, new UsageEventsItem.AppNameComparator()); return results; } @Override protected void onPostExecute(List<UsageEventsItem> resuls) { mAdapter.setData(resuls); } } }
922faefa103e546972d98dff33040e1ea71245cd
1,532
java
Java
dolphinscheduler-common/src/main/java/org/apache/dolphinscheduler/common/utils/ClusterConfUtils.java
czeming/dolphinscheduler
d516369e8076166ec85227f4adf3d1e9085285a6
[ "Apache-2.0" ]
1
2022-01-14T09:44:44.000Z
2022-01-14T09:44:44.000Z
dolphinscheduler-common/src/main/java/org/apache/dolphinscheduler/common/utils/ClusterConfUtils.java
czeming/dolphinscheduler
d516369e8076166ec85227f4adf3d1e9085285a6
[ "Apache-2.0" ]
null
null
null
dolphinscheduler-common/src/main/java/org/apache/dolphinscheduler/common/utils/ClusterConfUtils.java
czeming/dolphinscheduler
d516369e8076166ec85227f4adf3d1e9085285a6
[ "Apache-2.0" ]
2
2022-01-30T06:00:11.000Z
2022-01-30T06:08:25.000Z
31.265306
75
0.697781
995,206
/* * 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.dolphinscheduler.common.utils; import org.apache.dolphinscheduler.spi.utils.StringUtils; import com.fasterxml.jackson.databind.node.ObjectNode; /** * cluster conf will include all env type, but only k8s config now */ public class ClusterConfUtils { private static final String K8S_CONFIG = "k8s"; /** * get k8s * * @param config cluster config in db * @return */ public static String getK8sConfig(String config) { if (StringUtils.isEmpty(config)) { return null; } ObjectNode conf = JSONUtils.parseObject(config); if (conf == null) { return null; } return conf.get(K8S_CONFIG).asText(); } }
922faf4f24ebce84f6ff20339c4eeac595626f9b
641
java
Java
yoyo-rpc-loadbalance/src/main/java/com/tbkk/yoyo/rpc/loadbalance/route/YoyoRpcLoadBalanceRandomStrategy.java
tbkk/yoyo-rpc
f67a44206f446be03548aad83b86f4f5fbf9e7b7
[ "Apache-2.0" ]
17
2019-11-04T08:32:21.000Z
2021-01-07T08:10:16.000Z
yoyo-rpc-loadbalance/src/main/java/com/tbkk/yoyo/rpc/loadbalance/route/YoyoRpcLoadBalanceRandomStrategy.java
wanyine/yoyo-rpc
973ea7a919b568ac55fc8a0d778b5cfcc83c3eb5
[ "Apache-2.0" ]
4
2020-04-23T20:18:26.000Z
2021-12-09T21:54:50.000Z
yoyo-rpc-loadbalance/src/main/java/com/tbkk/yoyo/rpc/loadbalance/route/YoyoRpcLoadBalanceRandomStrategy.java
wanyine/yoyo-rpc
973ea7a919b568ac55fc8a0d778b5cfcc83c3eb5
[ "Apache-2.0" ]
7
2019-11-22T03:06:02.000Z
2019-12-26T07:12:20.000Z
22.103448
80
0.700468
995,207
package com.tbkk.yoyo.rpc.loadbalance.route; import com.tbkk.yoyo.rpc.loadbalance.YoyoRpcLoadBalance; import java.util.Random; import java.util.TreeSet; /** * random * * @author tbkk 2019-12-04 */ public class YoyoRpcLoadBalanceRandomStrategy extends YoyoRpcLoadBalance { private Random random = new Random(); @Override public String route(String serviceKey, TreeSet<String> addressSet) { // arr String[] addressArr = addressSet.toArray(new String[addressSet.size()]); // random String finalAddress = addressArr[random.nextInt(addressSet.size())]; return finalAddress; } }
922faffa30666ec4d5333a43dd08c8a84b6aa515
922
java
Java
Languages/Java/java_study_4/page14/Person.java
myarist/Progate
0132583c989b5ec1805d4de1a6f6861586cf152e
[ "MIT" ]
5
2021-09-08T03:07:22.000Z
2022-03-18T13:36:27.000Z
Languages/Java/java_study_4/page14/Person.java
myarist/Progate
0132583c989b5ec1805d4de1a6f6861586cf152e
[ "MIT" ]
null
null
null
Languages/Java/java_study_4/page14/Person.java
myarist/Progate
0132583c989b5ec1805d4de1a6f6861586cf152e
[ "MIT" ]
12
2021-05-11T07:54:20.000Z
2022-03-27T02:55:46.000Z
26.342857
84
0.642082
995,208
class Person { public static int count = 0; public String firstName, lastName; public int age; public double height, weight; Person(String firstName, String lastName, int age, double height, double weight) { Person.count++; this.firstName = firstName; this.lastName = lastName; this.age = age; this.height = height; this.weight = weight; } public String fullName() { return this.firstName + " " + this.lastName; } public void printData() { System.out.println("Nama saya " + this.fullName() + "."); System.out.println("Saya berusia " + this.age + " tahun."); System.out.println("Nilai BMI saya " + Math.round(this.bmi()) + "."); } public double bmi() { return this.weight / this.height / this.height; } // Definisikan method class `printCount` public static void printCount() { System.out.println("Total: " + Person.count + " orang."); } }
922fb00ab4d1e434942861dfa6983c5d61399196
572
java
Java
gomint-api/src/main/java/io/gomint/entity/projectile/EntityProjectile.java
joserobjr/gomint
7fbf262d1943adb4c9bd88ed5cee174ba6a4e8d8
[ "BSD-3-Clause" ]
1
2021-02-12T08:47:40.000Z
2021-02-12T08:47:40.000Z
gomint-api/src/main/java/io/gomint/entity/projectile/EntityProjectile.java
TobiasG-DE/GoMint
a797c8859120bcb4ffc00d95268026ee34e92551
[ "BSD-3-Clause" ]
null
null
null
gomint-api/src/main/java/io/gomint/entity/projectile/EntityProjectile.java
TobiasG-DE/GoMint
a797c8859120bcb4ffc00d95268026ee34e92551
[ "BSD-3-Clause" ]
null
null
null
20.428571
71
0.694056
995,209
/* * Copyright (c) 2020, GoMint, BlackyPaw and geNAZt * * This code is licensed under the BSD license found in the * LICENSE file in the root directory of this source tree. */ package io.gomint.entity.projectile; import io.gomint.entity.Entity; import io.gomint.entity.EntityLiving; /** * @author geNAZt * @version 1.0 * @stability 3 */ public interface EntityProjectile extends Entity { /** * Get the shooter of this projectile * * @return shooter of this projectile or null when shooter has died */ EntityLiving getShooter(); }
922fb0614e679a8e2e95950727d8b736bb1bd020
1,267
java
Java
dynamic/src/main/java/ch/raffael/sangria/dynamic/construct/package-info.java
Abnaxos/sangria
eb21a5913bff0dbbcc9d2936340767d59b6eb4da
[ "MIT" ]
null
null
null
dynamic/src/main/java/ch/raffael/sangria/dynamic/construct/package-info.java
Abnaxos/sangria
eb21a5913bff0dbbcc9d2936340767d59b6eb4da
[ "MIT" ]
null
null
null
dynamic/src/main/java/ch/raffael/sangria/dynamic/construct/package-info.java
Abnaxos/sangria
eb21a5913bff0dbbcc9d2936340767d59b6eb4da
[ "MIT" ]
null
null
null
43.689655
80
0.75296
995,210
/* * The MIT License (MIT) * * Copyright (c) 2015 Raffael Herzog * * 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. */ /** * @author <a href="mailto:anpch@example.com">Raffael Herzog</a> */ package ch.raffael.sangria.dynamic.construct;
922fb11417df900354bde1881a00d4a9dd3db0c2
1,465
java
Java
tests/com/reason/lang/reason/StringTemplateParsingTest.java
sweetliquid/reasonml-idea-plugin
56cb261ddbbe67208599860b319d8e748bf4a9a9
[ "MIT" ]
280
2017-07-08T06:20:06.000Z
2021-04-23T13:30:48.000Z
tests/com/reason/lang/reason/StringTemplateParsingTest.java
sweetliquid/reasonml-idea-plugin
56cb261ddbbe67208599860b319d8e748bf4a9a9
[ "MIT" ]
289
2017-07-04T07:35:21.000Z
2021-05-11T07:14:39.000Z
tests/com/reason/lang/reason/StringTemplateParsingTest.java
sweetliquid/reasonml-idea-plugin
56cb261ddbbe67208599860b319d8e748bf4a9a9
[ "MIT" ]
18
2017-08-09T11:53:48.000Z
2021-04-08T23:22:51.000Z
41.857143
123
0.713311
995,211
package com.reason.lang.reason; import com.intellij.psi.*; import com.reason.lang.core.*; import com.reason.lang.core.psi.*; import com.reason.lang.core.psi.impl.*; import java.util.*; @SuppressWarnings("ConstantConditions") public class StringTemplateParsingTest extends RmlParsingTestCase { public void test_basic() { PsiLet e = first(letExpressions(parseCode("let _ = {j|this is a $var Template string|j}"))); PsiLetBinding binding = e.getBinding(); PsiInterpolation inter = (PsiInterpolation) binding.getFirstChild(); Collection<PsiElement> parts = ORUtil.findImmediateChildrenOfType(inter, m_types.C_INTERPOLATION_PART); assertSize(2, parts); PsiInterpolationReference ref = ORUtil.findImmediateFirstChildOfClass(inter, PsiInterpolationReference.class); assertEquals("var", ref.getText()); } // https://github.com/reasonml-editor/reasonml-idea-plugin/issues/353 public void test_GH_353() { PsiLet e = first(letExpressions(parseCode("let _ = {j|$rowStart / $colStart|j}"))); PsiLetBinding binding = e.getBinding(); PsiInterpolation inter = (PsiInterpolation) binding.getFirstChild(); List<PsiInterpolationReference> refs = ORUtil.findImmediateChildrenOfClass(inter, PsiInterpolationReference.class); assertSize(2, refs); assertEquals("rowStart", refs.get(0).getText()); assertEquals("colStart", refs.get(1).getText()); } }
922fb1f9034814be882fca5bb228af6062c65f72
4,196
java
Java
src/test/java/guitests/guihandles/StatusBarFooterHandle.java
SandhyaGopakumar/main
d26c5eabcb9197518616a09662e343e7437de987
[ "MIT" ]
null
null
null
src/test/java/guitests/guihandles/StatusBarFooterHandle.java
SandhyaGopakumar/main
d26c5eabcb9197518616a09662e343e7437de987
[ "MIT" ]
257
2018-09-18T05:09:05.000Z
2018-11-12T14:56:52.000Z
src/test/java/guitests/guihandles/StatusBarFooterHandle.java
SandhyaGopakumar/main
d26c5eabcb9197518616a09662e343e7437de987
[ "MIT" ]
6
2018-09-17T15:33:13.000Z
2018-10-20T05:01:21.000Z
34.393443
119
0.704242
995,212
package guitests.guihandles; import org.controlsfx.control.StatusBar; import javafx.scene.Node; /** * A handle for the {@code StatusBarFooter} at the footer of the application. */ public class StatusBarFooterHandle extends NodeHandle<Node> { public static final String STATUS_BAR_PLACEHOLDER = "#statusbarPlaceholder"; private static final String SYNC_STATUS_ID = "#syncStatus"; private static final String TOTAL_PERSONS_STATUS_ID = "#totalPersonsStatus"; private static final String SAVE_LOCATION_STATUS_ID = "#saveLocationStatus"; private static final String DAYS_LEFT_STATUS_ID = "#daysLeft"; private final StatusBar syncStatusNode; private final StatusBar totalPersonsStatusNode; private final StatusBar saveLocationNode; private final StatusBar daysLeftNode; private String lastRememberedSyncStatus; private String getLastRememberedTotalPersonsStatus; private String lastRememberedSaveLocation; private String lastRemembereddaysLeft; public StatusBarFooterHandle(Node statusBarFooterNode) { super(statusBarFooterNode); syncStatusNode = getChildNode(SYNC_STATUS_ID); totalPersonsStatusNode = getChildNode(TOTAL_PERSONS_STATUS_ID); saveLocationNode = getChildNode(SAVE_LOCATION_STATUS_ID); daysLeftNode = getChildNode(DAYS_LEFT_STATUS_ID); } /** * Returns the text of the sync status portion of the status bar. */ public String getSyncStatus() { return syncStatusNode.getText(); } /** * Returns the text of the 'total persons' portion of the status bar. * Note: This code was adapted from the example implementation provide by @yamgent from SE-EDU */ public String getTotalPersonsStatus() { return totalPersonsStatusNode.getText(); } /** * Returns the text of the 'save location' portion of the status bar. */ public String getSaveLocation() { return saveLocationNode.getText(); } public String getdaysLeft() { return daysLeftNode.getText(); } /** * Remembers the content of the sync status portion of the status bar. */ public void rememberSyncStatus() { lastRememberedSyncStatus = getSyncStatus(); } /** * Returns true if the current content of the sync status is different from the value remembered by the most recent * {@code rememberSyncStatus()} call. */ public boolean isSyncStatusChanged() { return !lastRememberedSyncStatus.equals(getSyncStatus()); } /** * Remembers the content of the 'total' persons portion of the status bar * Note: This code was adapted from the example implementation provide by @yamgent from SE-EDU */ public void rememberTotalPersonsStatus() { getLastRememberedTotalPersonsStatus = getTotalPersonsStatus(); } /** * Returns true if the current content of the 'total persons' is different from the value remembered * by the most recent {@code rememberTotalPersonsStatus()} call. * * Note: This code was adapted from the example implementation provide by @yamgent from SE-EDU */ public boolean isTotalPersonsStatusChanged() { return !getLastRememberedTotalPersonsStatus.equals(getTotalPersonsStatus()); } /** * Remembers the content of the 'save location' portion of the status bar. */ public void rememberSaveLocation() { lastRememberedSaveLocation = getSaveLocation(); } /** * Returns true if the current content of the 'save location' is different from the value remembered by the most * recent {@code rememberSaveLocation()} call. */ public boolean isSaveLocationChanged() { return !lastRememberedSaveLocation.equals(getSaveLocation()); } public void rememberdaysLeft() { lastRemembereddaysLeft = getdaysLeft(); } /** * Returns true if the current content of the 'days left' is different from the value remembered by the most * recent {@code rememberdaysLeft()} call. */ public boolean isdaysLeftChanged() { return !lastRemembereddaysLeft.equals(getdaysLeft()); } }
922fb2b4a9cd93ba2767cc5e48026cc38c7cec49
1,516
java
Java
blanco/main/blanco/sample/GetTableSample4PostRequest.java
uedaueo/blancoRestAutotest
366174bb13048a40fdacbb73b0861de16d2194f8
[ "Apache-2.0" ]
null
null
null
blanco/main/blanco/sample/GetTableSample4PostRequest.java
uedaueo/blancoRestAutotest
366174bb13048a40fdacbb73b0861de16d2194f8
[ "Apache-2.0" ]
null
null
null
blanco/main/blanco/sample/GetTableSample4PostRequest.java
uedaueo/blancoRestAutotest
366174bb13048a40fdacbb73b0861de16d2194f8
[ "Apache-2.0" ]
null
null
null
21.657143
68
0.610818
995,213
/* * このソースコードは blanco Frameworkによって自動生成されています。 */ package blanco.sample; import java.util.ArrayList; import blanco.restgenerator.valueobject.ApiPostTelegram; /** * blancoRestのサンプルAPIの要求電文です。 */ public class GetTableSample4PostRequest extends ApiPostTelegram { /** * フィールド [codeNames] * * 項目の型 [java.util.ArrayList] */ private ArrayList<String> fCodeNames; /** * フィールド [codeNames]のセッターメソッド * * 項目の型 [java.util.ArrayList] * * @param argCodeNames フィールド[codeNames]に格納したい値 */ public void setCodeNames(final ArrayList<String> argCodeNames) { this.fCodeNames = argCodeNames; } /** * フィールド[codeNames]のゲッターメソッド * * 項目の型 [java.util.ArrayList] * * @return フィールド[codeNames]に格納されている値 */ public ArrayList<String> getCodeNames() { return this.fCodeNames; } /** * フィールド[codeNames]のゲッターメソッド * * 項目の型 [java.lang.String] * * @return フィールド[codeNames]の型名文字列 */ public static String typeCodeNames() { return "java.util.ArrayList<java.lang.String>"; } /** * このバリューオブジェクトの文字列表現を取得します。 * * オブジェクトのシャロー範囲でしかtoStringされない点に注意して利用してください。 * * @return バリューオブジェクトの文字列表現。 */ @Override public String toString() { java.lang.String buf = ""; buf = buf + "blanco.sample.GetTableSample4PostRequest["; buf = buf + "codeNames=" + this.fCodeNames; buf = buf + "]"; return buf; } }
922fb2dbcd359184b221d5f9dac491e01db8b681
2,914
java
Java
huomai-business/src/main/java/com/huomai/business/service/impl/HuomaiGiftConfigServiceImpl.java
shortVideoTeam/short-video-admin-services
0902c98374258ac6416097865b8155a723a259f7
[ "MIT" ]
null
null
null
huomai-business/src/main/java/com/huomai/business/service/impl/HuomaiGiftConfigServiceImpl.java
shortVideoTeam/short-video-admin-services
0902c98374258ac6416097865b8155a723a259f7
[ "MIT" ]
null
null
null
huomai-business/src/main/java/com/huomai/business/service/impl/HuomaiGiftConfigServiceImpl.java
shortVideoTeam/short-video-admin-services
0902c98374258ac6416097865b8155a723a259f7
[ "MIT" ]
null
null
null
32.377778
98
0.777282
995,214
package com.huomai.business.service.impl; import cn.hutool.core.bean.BeanUtil; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.huomai.business.bo.HuomaiGiftConfigAddBo; import com.huomai.business.bo.HuomaiGiftConfigEditBo; import com.huomai.business.bo.HuomaiGiftConfigQueryBo; import com.huomai.business.domain.HuomaiGiftConfig; import com.huomai.business.mapper.HuomaiGiftConfigMapper; import com.huomai.business.service.IHuomaiGiftConfigService; import com.huomai.business.vo.HuomaiGiftConfigVo; import com.huomai.common.core.page.PagePlus; import com.huomai.common.core.page.TableDataInfo; import com.huomai.common.utils.PageUtils; import org.springframework.stereotype.Service; import java.util.Collection; import java.util.List; import java.util.Map; /** * 红包金额配置Service业务层处理 * * @author huomai * @date 2021-06-30 */ @Service public class HuomaiGiftConfigServiceImpl extends ServiceImpl<HuomaiGiftConfigMapper, HuomaiGiftConfig> implements IHuomaiGiftConfigService { @Override public HuomaiGiftConfigVo queryById(Long id) { return getVoById(id, HuomaiGiftConfigVo.class); } @Override public TableDataInfo<HuomaiGiftConfigVo> queryPageList(HuomaiGiftConfigQueryBo bo) { PagePlus<HuomaiGiftConfig, HuomaiGiftConfigVo> result = pageVo(PageUtils.buildPagePlus(), buildQueryWrapper(bo), HuomaiGiftConfigVo.class); return PageUtils.buildDataInfo(result); } @Override public List<HuomaiGiftConfigVo> queryList(HuomaiGiftConfigQueryBo bo) { return listVo(buildQueryWrapper(bo), HuomaiGiftConfigVo.class); } private LambdaQueryWrapper<HuomaiGiftConfig> buildQueryWrapper(HuomaiGiftConfigQueryBo bo) { Map<String, Object> params = bo.getParams(); LambdaQueryWrapper<HuomaiGiftConfig> lqw = Wrappers.lambdaQuery(); lqw.eq(bo.getTotalAmount() != null, HuomaiGiftConfig::getTotalAmount, bo.getTotalAmount()); lqw.eq(bo.getSingleAmount() != null, HuomaiGiftConfig::getSingleAmount, bo.getSingleAmount()); return lqw; } @Override public Boolean insertByAddBo(HuomaiGiftConfigAddBo bo) { HuomaiGiftConfig add = BeanUtil.toBean(bo, HuomaiGiftConfig.class); validEntityBeforeSave(add); return save(add); } @Override public Boolean updateByEditBo(HuomaiGiftConfigEditBo bo) { HuomaiGiftConfig update = BeanUtil.toBean(bo, HuomaiGiftConfig.class); validEntityBeforeSave(update); return updateById(update); } /** * 保存前的数据校验 * * @param entity 实体类数据 */ private void validEntityBeforeSave(HuomaiGiftConfig entity) { // TODO 做一些数据校验,如唯一约束 } @Override public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) { if (isValid) { // TODO 做一些业务上的校验,判断是否需要校验 } return removeByIds(ids); } }
922fb2ffa9f1ea6b83080a902e1f2b10e22b1c03
4,306
java
Java
trunk/sqltoy-quickvo/src/main/java/org/sagacity/quickvo/engine/template/TemplateGenerator.java
tianqiqiu/chenrenfei-sagacity-sqltoy
41693072b01607b4a65e314d458f6ade4784891a
[ "Apache-2.0" ]
1
2019-02-26T04:50:26.000Z
2019-02-26T04:50:26.000Z
trunk/sagacity-quickvo/src/main/java/org/sagacity/quickvo/engine/template/TemplateGenerator.java
eidt/sagacity-sqltoy
9fb3e56046e6afebda5d1622430e2e11792a7fff
[ "Apache-2.0" ]
13
2021-08-09T20:44:55.000Z
2022-03-31T20:46:20.000Z
trunk/sagacity-quickvo/src/main/java/org/sagacity/quickvo/engine/template/TemplateGenerator.java
eidt/sagacity-sqltoy
9fb3e56046e6afebda5d1622430e2e11792a7fff
[ "Apache-2.0" ]
null
null
null
24.224719
96
0.678803
995,215
/** * */ package org.sagacity.quickvo.engine.template; import java.io.BufferedWriter; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.StringWriter; import java.io.Writer; import java.util.HashMap; import java.util.Map; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.sagacity.quickvo.utils.StringUtil; import freemarker.cache.StringTemplateLoader; import freemarker.template.Configuration; import freemarker.template.Template; /** * @project sagacity-quickvo * @description 基于freemarker的模版工具引擎,提供日常项目中模版和数据对象的结合处理 * @author zhongxuchen $<a href="mailto:efpyi@example.com">联系作者</a>$ * @version id:TemplateGenerator.java,Revision:v1.0,Date:2008-11-24 */ @SuppressWarnings({ "rawtypes", "unchecked" }) public class TemplateGenerator { /** * 定义全局日志 */ private final static Logger logger = LogManager.getLogger(TemplateGenerator.class); private static Configuration cfg = null; public static TemplateGenerator me; public static TemplateGenerator getInstance() { if (me == null) me = new TemplateGenerator(); return me; } /** * 编码格式,默认utf-8 */ private String encoding = "UTF-8"; /** * 设置编码格式 * * @param encoding */ public void setEncoding(String encoding) { this.encoding = encoding; } /** * * @todo 将字符串模版处理后以字符串输出 * @param keys * @param templateData * @param templateStr * @return */ public String create(String[] keys, Object[] templateData, String templateStr) { if (keys == null || templateData == null) return null; String result = null; StringWriter writer = null; try { init(); StringTemplateLoader templateLoader = new StringTemplateLoader(); templateLoader.putTemplate("string_template", templateStr); cfg.setTemplateLoader(templateLoader); Template template = null; if (StringUtil.isNotBlank(this.encoding)) template = cfg.getTemplate("string_template", this.encoding); else template = cfg.getTemplate("string_template"); Map root = new HashMap(); for (int i = 0; i < keys.length; i++) { root.put(keys[i], templateData[i]); } writer = new StringWriter(); template.process(root, writer); writer.flush(); result = writer.getBuffer().toString(); } catch (Exception e) { e.printStackTrace(); logger.error(e.getMessage(), e); } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { } } writer = null; } return result; } /** * @todo <b>将模板和数据结合产生到目的文件中</b> * @param keys * @param templateData * @param templateStr * @param distFile */ public void create(String[] keys, Object[] templateData, String templateStr, String distFile) { if (keys == null || templateData == null) return; Writer writer = null; FileOutputStream out = null; try { init(); StringTemplateLoader templateLoader = new StringTemplateLoader(); templateLoader.putTemplate("template", templateStr); cfg.setTemplateLoader(templateLoader); Template template = null; if (StringUtil.isNotBlank(this.encoding)) template = cfg.getTemplate("template", this.encoding); else template = cfg.getTemplate("template"); Map root = new HashMap(); for (int i = 0; i < keys.length; i++) { root.put(keys[i], templateData[i]); } out = new FileOutputStream(distFile); if (StringUtil.isNotBlank(this.encoding)) writer = new BufferedWriter(new OutputStreamWriter(out, this.encoding)); else writer = new BufferedWriter(new OutputStreamWriter(out)); logger.info("generate file " + distFile); template.process(root, writer); writer.flush(); } catch (Exception e) { e.printStackTrace(); logger.error(e.getMessage(), e); } finally { if (out != null) { try { out.close(); } catch (IOException e) { } } if (writer != null) { try { writer.close(); } catch (IOException e) { } } out = null; writer = null; } } /** * 销毁实例 */ public static void destory() { cfg = null; } public void init() { if (cfg == null) { cfg = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS); if (StringUtil.isNotBlank(this.encoding)) cfg.setDefaultEncoding(this.encoding); } } }
922fb37cbeb758939d2bb189c3f97e70680e530b
270
java
Java
app/src/main/java/com/origamistudios/boilerplate/ui/about/AboutFragmentProvider.java
OrigamiStudiosLLC/Android-Sample-Code
fa7a78017845f61b46a6604c0e2b159b2dc59f58
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/origamistudios/boilerplate/ui/about/AboutFragmentProvider.java
OrigamiStudiosLLC/Android-Sample-Code
fa7a78017845f61b46a6604c0e2b159b2dc59f58
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/origamistudios/boilerplate/ui/about/AboutFragmentProvider.java
OrigamiStudiosLLC/Android-Sample-Code
fa7a78017845f61b46a6604c0e2b159b2dc59f58
[ "Apache-2.0" ]
null
null
null
22.5
57
0.833333
995,216
package com.origamistudios.boilerplate.ui.about; import dagger.Module; import dagger.android.ContributesAndroidInjector; @Module public abstract class AboutFragmentProvider { @ContributesAndroidInjector abstract AboutFragment provideAboutFragmentFactory(); }
922fb3bacf864d69d20142a6fbde249c4fa11309
849
java
Java
src/test/java/seedu/address/logic/commands/main/ListBudgetCommandTest.java
sogggy/tp
a5fe214586f5a57322d097ed9df26b8987df50eb
[ "MIT" ]
1
2020-10-21T09:14:23.000Z
2020-10-21T09:14:23.000Z
src/test/java/seedu/address/logic/commands/main/ListBudgetCommandTest.java
sogggy/tp
a5fe214586f5a57322d097ed9df26b8987df50eb
[ "MIT" ]
235
2020-09-20T03:32:45.000Z
2020-11-10T05:00:58.000Z
src/test/java/seedu/address/logic/commands/main/ListBudgetCommandTest.java
sogggy/tp
a5fe214586f5a57322d097ed9df26b8987df50eb
[ "MIT" ]
5
2020-09-13T03:25:09.000Z
2020-09-13T03:40:32.000Z
29.275862
111
0.766784
995,217
package seedu.address.logic.commands.main; import static seedu.address.logic.commands.CommandTestUtil.assertCommandSuccess; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import seedu.address.model.Model; import seedu.address.model.ModelManager; import seedu.address.model.UserPrefs; import seedu.address.testutil.TypicalBudgets; class ListBudgetCommandTest { private Model model; private Model expectedModel; @BeforeEach void setUp() { model = new ModelManager(TypicalBudgets.getTypicalNusave(), new UserPrefs()); expectedModel = new ModelManager(model.getNusave(), new UserPrefs()); } @Test public void execute_listIsNotFiltered_showsSameList() { assertCommandSuccess(new ListBudgetCommand(), model, ListBudgetCommand.MESSAGE_SUCCESS, expectedModel); } }
922fb4d2f79408943f42d3c70b413ad2e65c24a3
3,058
java
Java
src/test/java/com/fangcloud/sdk/api/YfyTrashRequestTest.java
paynezhuang/fangcloud-java-sdk
10276395d85dd0e11a7119e554a4b3e2732fe5ed
[ "MIT" ]
6
2017-05-12T07:09:17.000Z
2019-06-25T00:31:06.000Z
src/test/java/com/fangcloud/sdk/api/YfyTrashRequestTest.java
paynezhuang/fangcloud-java-sdk
10276395d85dd0e11a7119e554a4b3e2732fe5ed
[ "MIT" ]
1
2020-03-24T09:50:06.000Z
2020-03-24T09:50:06.000Z
src/test/java/com/fangcloud/sdk/api/YfyTrashRequestTest.java
paynezhuang/fangcloud-java-sdk
10276395d85dd0e11a7119e554a4b3e2732fe5ed
[ "MIT" ]
3
2019-06-25T00:31:25.000Z
2020-10-22T11:41:14.000Z
40.773333
99
0.745585
995,218
package com.fangcloud.sdk.api; import com.fangcloud.sdk.YfyAppInfo; import com.fangcloud.sdk.YfyClient; import com.fangcloud.sdk.YfyRequestConfig; import com.fangcloud.sdk.api.file.YfyFile; import com.fangcloud.sdk.api.file.YfyFileRequest; import com.fangcloud.sdk.api.folder.YfyFolder; import com.fangcloud.sdk.api.folder.YfyFolderRequest; import com.fangcloud.sdk.api.trash.YfyTrashRequest; import com.fangcloud.sdk.exception.YfyException; import org.junit.After; import org.junit.Before; import org.junit.Test; import static com.fangcloud.sdk.SdkTestUtil.assertFileNotNull; import static com.fangcloud.sdk.SdkTestUtil.assertFolderNotNull; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class YfyTrashRequestTest { private static final String PARENT_NAME = "share-link-api-test"; private static final String FILE_NAME = "java-sdk-test.txt"; private static final String FOLDER_NAME = "java-sdk-test"; private YfyFileRequest fileRequest; private YfyFolderRequest folderRequest; private YfyTrashRequest trashRequest; private long testParentId; private long testFolderId; private long testFileId; @Before public void before() throws YfyException { YfyAppInfo.initAppInfo("test-client", "123456"); YfyClient client = new YfyClient(new YfyRequestConfig(), System.getenv().get("YFY_TOKEN")); fileRequest = client.files(); folderRequest = client.folders(); trashRequest = client.trashs(); testParentId = createAndAssertFolder(PARENT_NAME, 0L); testFolderId = createAndAssertFolder(FOLDER_NAME, testParentId); testFileId = uploadAndAssertFile(FILE_NAME, testParentId); } private long createAndAssertFolder(String name, long parentId) throws YfyException { YfyFolder folder = folderRequest.createFolder(name, parentId); assertFolderNotNull(folder); return folder.getId(); } private long uploadAndAssertFile(String fileName, long parentId) throws YfyException { YfyFile file = fileRequest.directUploadFile(parentId, fileName, YfyFileRequestTest.class.getResourceAsStream("/" + fileName)); assertFileNotNull(file); assertEquals(fileName, file.getName()); return file.getId(); } @After public void after() throws YfyException { assertTrue(folderRequest.deleteFolder(testParentId).getSuccess()); assertTrue(folderRequest.deleteFolderFromTrash(testParentId).getSuccess()); } @Test public void testRestoreAndClearTrash() throws YfyException { assertTrue(trashRequest.clearTrash(ItemTypeEnum.ITEM).getSuccess()); assertTrue(fileRequest.deleteFile(testFileId).getSuccess()); assertTrue(folderRequest.deleteFolder(testFolderId).getSuccess()); assertTrue(trashRequest.restoreTrash(ItemTypeEnum.ITEM).getSuccess()); assertFileNotNull(fileRequest.getFile(testFileId)); assertFolderNotNull(folderRequest.getFolder(testFolderId)); } }
922fb531a813073891f0783d36d8056268209394
1,874
java
Java
runelite-client/src/main/java/net/runelite/client/config/ConfigItemDescriptor.java
robmonte/runelite
e73ccc30691be9ffe9a85e7a89900194698447ed
[ "BSD-2-Clause" ]
189
2019-10-06T22:19:23.000Z
2022-03-26T17:56:49.000Z
runelite-client/src/main/java/net/runelite/client/config/ConfigItemDescriptor.java
robmonte/runelite
e73ccc30691be9ffe9a85e7a89900194698447ed
[ "BSD-2-Clause" ]
483
2019-10-06T06:55:02.000Z
2022-03-20T08:35:28.000Z
runelite-client/src/main/java/net/runelite/client/config/ConfigItemDescriptor.java
robmonte/runelite
e73ccc30691be9ffe9a85e7a89900194698447ed
[ "BSD-2-Clause" ]
789
2019-10-06T09:16:32.000Z
2022-03-31T17:58:53.000Z
32.877193
82
0.759872
995,219
/* * Copyright (c) 2017, Adam <dycjh@example.com> * 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, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 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 OWNER 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. */ package net.runelite.client.config; import java.lang.reflect.Type; import lombok.Value; @Value public class ConfigItemDescriptor implements ConfigObject { private final ConfigItem item; private final Type type; private final Range range; private final Alpha alpha; private final Units units; @Override public String key() { return item.keyName(); } @Override public String name() { return item.name(); } @Override public int position() { return item.position(); } }
922fb54820e802fc4bba854e9e932a181ba8f617
4,248
java
Java
Java/ElasticSearch/JdbcTemplate/ElasticSearch-00-JdbcTemplate/src/test/java/oiasso/systems/elastic/example/factory/ElasticSearchResponseDataFactoryTest.java
CarlosIribarren/Ejemplos-Examples
e8f7db3c7a1355b76d2a350bded72fa4bfc01817
[ "Apache-2.0" ]
null
null
null
Java/ElasticSearch/JdbcTemplate/ElasticSearch-00-JdbcTemplate/src/test/java/oiasso/systems/elastic/example/factory/ElasticSearchResponseDataFactoryTest.java
CarlosIribarren/Ejemplos-Examples
e8f7db3c7a1355b76d2a350bded72fa4bfc01817
[ "Apache-2.0" ]
null
null
null
Java/ElasticSearch/JdbcTemplate/ElasticSearch-00-JdbcTemplate/src/test/java/oiasso/systems/elastic/example/factory/ElasticSearchResponseDataFactoryTest.java
CarlosIribarren/Ejemplos-Examples
e8f7db3c7a1355b76d2a350bded72fa4bfc01817
[ "Apache-2.0" ]
null
null
null
37.59292
158
0.63936
995,220
package oiasso.systems.elastic.example.factory; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import java.io.IOException; import org.codehaus.jackson.JsonNode; import org.codehaus.jackson.JsonProcessingException; import org.codehaus.jackson.map.ObjectMapper; import org.junit.Before; import org.junit.Test; public class ElasticSearchResponseDataFactoryTest { private static final String AGGREGATIONS_GENRES = "{" + " \"genres\" : {" + " \"doc_count_error_upper_bound\": 0, " + " \"sum_other_doc_count\": 0, " + " \"buckets\" : [ " + " {" + " \"key\" : \"electronic\"," + " \"doc_count\" : 6" + " }," + " {" + " \"key\" : \"rock\"," + " \"doc_count\" : 3" + " }," + " {" + " \"key\" : \"jazz\"," + " \"doc_count\" : 2" + " }" + " ]" + " }" + "}"; private ElasticSearchResponseDataFactory elasticSearchResponseDataFactory; @Before public void setUp() { elasticSearchResponseDataFactory = new ElasticSearchResponseDataFactory(); } @Test public void getTotalHits_when_json_have_total_hits_should_return_the_value_of_total_hits() throws JsonProcessingException, IOException { final JsonNode root = this.createJsonNode("{\"hits\":{\"total\":{\"value\":27}}}"); assertEquals("27", elasticSearchResponseDataFactory.getTotalHits(root)); } @Test public void getAggregations_when_json_have_aggregations_should_return_aggregations() throws JsonProcessingException, IOException { final JsonNode expected = this.createJsonNode("{\"max_price\": {\"value\": 200.0}}"); final JsonNode root = this.createJsonNode("{\"aggregations\": {\"max_price\": {\"value\": 200.0}}}"); final JsonNode actual = elasticSearchResponseDataFactory.getAggregations(root); assertEquals(expected, actual); } @Test public void getBuckets_when_json_have_buckets_with_name_should_return_buckets() throws JsonProcessingException, IOException { final JsonNode expected = this.createJsonNode("[" + "{\"key\" : \"electronic\",\"doc_count\" : 6}," + "{\"key\" : \"rock\",\"doc_count\" : 3}," + "{\"key\" : \"jazz\", \"doc_count\" : 2}"+ "]"); final JsonNode aggregations = this.createJsonNode(AGGREGATIONS_GENRES); final JsonNode actual = elasticSearchResponseDataFactory.getBuckets(aggregations, "genres"); assertEquals(expected, actual); } @Test public void getDateAggregation_when_json_not_have_buckets_with_same_name_should_return_null() throws JsonProcessingException, IOException { final JsonNode aggregations = this.createJsonNode("{" + " \"min\" : {" + " \"value\" : 1.5541107E12," + " \"value_as_string\" : \"2019/04/01 09:25:00\"" + " }" + " }"); assertNull(elasticSearchResponseDataFactory.getDateAggregation(aggregations, "maxDate")); } @Test public void getDateAggregation_when_json_not_have_aggregations_with_value_as_string_should_return_null() throws JsonProcessingException, IOException { final JsonNode aggregations = this.createJsonNode("{" + " \"min\" : {" + " \"value\" : 1.5541107E12" + " }" + " }"); assertNull(elasticSearchResponseDataFactory.getDateAggregation(aggregations, "min")); } @Test public void getDateAggregation_when_json_have_aggregations_with_value_as_string_should_return_value_as_string() throws JsonProcessingException, IOException { final JsonNode aggregations = this.createJsonNode("{" + " \"max\" : {" + " \"value\" : 1.588680323E12," + " \"value_as_string\" : \"2020/05/05 12:05:23\"" + " }" + " }"); final String actual = elasticSearchResponseDataFactory.getDateAggregation(aggregations, "max"); assertEquals("2020/05/05 12:05:23", actual); } private JsonNode createJsonNode(final String json) throws JsonProcessingException, IOException { final ObjectMapper mapper = new ObjectMapper(); return mapper.readTree(json); } }
922fb61c3b18c6a0b413f66fbadf26aa10471ca0
6,783
java
Java
processing/src/main/java/io/druid/query/groupby/epinephelinae/Grouper.java
potto007/druid
a73f1c9c70bb11ec0b1297f9354f6450eefdfc0f
[ "Apache-2.0" ]
1
2019-11-06T08:01:15.000Z
2019-11-06T08:01:15.000Z
processing/src/main/java/io/druid/query/groupby/epinephelinae/Grouper.java
potto007/druid
a73f1c9c70bb11ec0b1297f9354f6450eefdfc0f
[ "Apache-2.0" ]
null
null
null
processing/src/main/java/io/druid/query/groupby/epinephelinae/Grouper.java
potto007/druid
a73f1c9c70bb11ec0b1297f9354f6450eefdfc0f
[ "Apache-2.0" ]
1
2019-11-06T08:01:44.000Z
2019-11-06T08:01:44.000Z
29.237069
117
0.659148
995,221
/* * Licensed to Metamarkets Group Inc. (Metamarkets) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. Metamarkets 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 io.druid.query.groupby.epinephelinae; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import java.io.Closeable; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.Comparator; import java.util.Iterator; /** * Groupers aggregate metrics from rows that they typically get from a ColumnSelectorFactory, under * grouping keys that some outside driver is passing in. They can also iterate over the grouped * rows after the aggregation is done. * * They work sort of like a map of KeyType to aggregated values, except they don't support * random lookups. * * @param <KeyType> type of the key that will be passed in */ public interface Grouper<KeyType> extends Closeable { /** * Aggregate the current row with the provided key. Some implementations are thread-safe and * some are not. * * @param key key object * @param keyHash result of {@link Groupers#hash(Object)} on the key * * @return true if the row was aggregated, false if not due to hitting resource limits */ boolean aggregate(KeyType key, int keyHash); /** * Aggregate the current row with the provided key. Some implementations are thread-safe and * some are not. * * @param key key * * @return true if the row was aggregated, false if not due to hitting resource limits */ boolean aggregate(KeyType key); /** * Reset the grouper to its initial state. */ void reset(); /** * Close the grouper and release associated resources. */ @Override void close(); /** * Iterate through entries. If a comparator is provided, do a sorted iteration. * * Once this method is called, writes are no longer safe. After you are done with the iterator returned by this * method, you should either call {@link #close()} (if you are done with the Grouper), {@link #reset()} (if you * want to reuse it), or {@link #iterator(boolean)} again if you want another iterator. * * If "sorted" is true then the iterator will return sorted results. It will use KeyType's natural ordering on * deserialized objects, and will use the {@link KeySerde#comparator()} on serialized objects. Woe be unto you * if these comparators are not equivalent. * * @param sorted return sorted results * * @return entry iterator */ Iterator<Entry<KeyType>> iterator(final boolean sorted); class Entry<T> { final T key; final Object[] values; @JsonCreator public Entry( @JsonProperty("k") T key, @JsonProperty("v") Object[] values ) { this.key = key; this.values = values; } @JsonProperty("k") public T getKey() { return key; } @JsonProperty("v") public Object[] getValues() { return values; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Entry<?> entry = (Entry<?>) o; if (!key.equals(entry.key)) { return false; } // Probably incorrect - comparing Object[] arrays with Arrays.equals return Arrays.equals(values, entry.values); } @Override public int hashCode() { int result = key.hashCode(); result = 31 * result + Arrays.hashCode(values); return result; } @Override public String toString() { return "Entry{" + "key=" + key + ", values=" + Arrays.toString(values) + '}'; } } interface KeySerdeFactory<T> { /** * Create a new KeySerde, which may be stateful. */ KeySerde<T> factorize(); /** * Return an object that knows how to compare two serialized key instances. Will be called by the * {@link #iterator(boolean)} method if sorting is enabled. * * @return comparator for key objects. */ Comparator<T> objectComparator(); } /** * Possibly-stateful object responsible for serde and comparison of keys. Does not need to be thread-safe. */ interface KeySerde<T> { /** * Size of the keys returned by {@link #toByteBuffer(Object)} (which must be a fixed size) */ int keySize(); /** * Class of the keys. */ Class<T> keyClazz(); /** * Serialize a key. This will be called by the {@link #aggregate(Comparable)} method. The buffer will not * be retained after the aggregate method returns, so reusing buffers is OK. * * This method may return null, which indicates that some internal resource limit has been reached and * no more keys can be generated. In this situation you can call {@link #reset()} and try again, although * beware the caveats on that method. * * @param key key object * * @return serialized key, or null if we are unable to serialize more keys due to resource limits */ ByteBuffer toByteBuffer(T key); /** * Deserialize a key from a buffer. Will be called by the {@link #iterator(boolean)} method. * * @param buffer buffer containing the key * @param position key start position in the buffer * * @return key object */ T fromByteBuffer(ByteBuffer buffer, int position); /** * Return an object that knows how to compare two serialized keys. Will be called by the * {@link #iterator(boolean)} method if sorting is enabled. * * @return comparator for keys */ KeyComparator bufferComparator(); /** * Reset the keySerde to its initial state. After this method is called, {@link #fromByteBuffer(ByteBuffer, int)} * and {@link #bufferComparator()} may no longer work properly on previously-serialized keys. */ void reset(); } interface KeyComparator { int compare(ByteBuffer lhsBuffer, ByteBuffer rhsBuffer, int lhsPosition, int rhsPosition); } }
922fb6ab5b9277389ccbee60adf3d78df6c04b1f
552
java
Java
src/java/org/apache/cassandra/config/MutantsLoadgenOptions.java
hobinyoon/mutants-cassandra
a26821726dcedbb5a96a02e649d552e06815ea5f
[ "Apache-2.0" ]
null
null
null
src/java/org/apache/cassandra/config/MutantsLoadgenOptions.java
hobinyoon/mutants-cassandra
a26821726dcedbb5a96a02e649d552e06815ea5f
[ "Apache-2.0" ]
2
2016-07-06T14:38:40.000Z
2016-07-07T16:41:20.000Z
src/java/org/apache/cassandra/config/MutantsLoadgenOptions.java
hobinyoon/mutants-cassandra
a26821726dcedbb5a96a02e649d552e06815ea5f
[ "Apache-2.0" ]
1
2015-11-07T03:07:04.000Z
2015-11-07T03:07:04.000Z
20.444444
52
0.730072
995,222
package org.apache.cassandra.config; public class MutantsLoadgenOptions { public Global global = new Global(); public PerObj per_obj = new PerObj(); public DB db = new DB(); } class Global { public long num_writes_per_simulation_time_mins; public int progress_report_interval_ms; public String write_time_dist; } class PerObj { public double avg_reads; public String num_reads_dist; public String read_time_dist; public long obj_size; } class DB { public boolean requests; public long num_threads; }
922fb6f6f929ea9b151a166e8890311a824cff0b
6,023
java
Java
mall-gateway/src/main/java/com/tang/mall/gateway/authorization/AuthorizationManager.java
tangxiaonian/mall-cli
9351d515858b87fa785932594daf2d32c0229805
[ "Apache-2.0" ]
null
null
null
mall-gateway/src/main/java/com/tang/mall/gateway/authorization/AuthorizationManager.java
tangxiaonian/mall-cli
9351d515858b87fa785932594daf2d32c0229805
[ "Apache-2.0" ]
null
null
null
mall-gateway/src/main/java/com/tang/mall/gateway/authorization/AuthorizationManager.java
tangxiaonian/mall-cli
9351d515858b87fa785932594daf2d32c0229805
[ "Apache-2.0" ]
null
null
null
41.826389
115
0.634567
995,223
package com.tang.mall.gateway.authorization; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.nimbusds.jose.JWSObject; import com.tang.mall.common.constant.AuthConstant; import com.tang.mall.common.domain.UserDto; import com.tang.mall.gateway.config.IgnoreUrlsConfig; import lombok.extern.slf4j.Slf4j; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.http.HttpMethod; import org.springframework.http.server.reactive.ServerHttpRequest; import org.springframework.security.authorization.AuthorizationDecision; import org.springframework.security.authorization.ReactiveAuthorizationManager; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.web.server.authorization.AuthorizationContext; import org.springframework.stereotype.Component; import org.springframework.util.AntPathMatcher; import org.springframework.util.PathMatcher; import org.springframework.util.StringUtils; import org.springframework.web.server.ServerWebExchange; import reactor.core.publisher.Mono; import javax.annotation.Resource; import java.text.ParseException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * @Classname AuthorizationManager * @Description [ 自定义认证接口管理,访问后端路径需要验证权限 ] * @Author Tang * @Date 2020/9/4 22:16 * @Created by ASUS */ @Slf4j @Component public class AuthorizationManager implements ReactiveAuthorizationManager<AuthorizationContext> { @Resource public IgnoreUrlsConfig ignoreUrlsConfig; @Resource public RedisTemplate<String, Object> redisTemplate; /** * 自定义鉴权方法 * @param authentication 登录成功的用户信息 * @param authorizationContext * @return */ @Override public Mono<AuthorizationDecision> check(Mono<Authentication> authentication, AuthorizationContext authorizationContext) { ServerWebExchange serverWebExchange = authorizationContext.getExchange(); ServerHttpRequest request = serverWebExchange.getRequest(); log.info( "AuthorizationManager.....调用开始...." ); String uriPath = request.getURI().getPath(); PathMatcher pathMatcher = new AntPathMatcher(); // 1.匹配白名单 if ( ignoreUrlsConfig.getUrls() .stream() .anyMatch(ignoreUrl -> pathMatcher.match(ignoreUrl, uriPath)) ) { // 同意授权 return Mono.just(new AuthorizationDecision(true)); } // 2.跨越的预检请求 if (request.getMethod() == HttpMethod.OPTIONS) { // 同意授权 return Mono.just(new AuthorizationDecision(true)); } // 3.夸端处理 String token = request.getHeaders().getFirst(AuthConstant.JWT_TOKEN_HEADER); if (StringUtils.isEmpty(token)) { return Mono.just(new AuthorizationDecision(false)); } String realToken = token.replace(AuthConstant.JWT_TOKEN_PREFIX, ""); try { // 解析jwt生成的token JWSObject jwsObject = JWSObject.parse(realToken); String userStr = jwsObject.getPayload().toString(); UserDto userDto = JSON.parseObject(userStr, UserDto.class); // 后台登录,匹配路径请求是后台 if (AuthConstant.ADMIN_CLIENT_ID.equals(userDto.getClientId()) && !pathMatcher.match(AuthConstant.ADMIN_URL_PATTERN, uriPath)) { return Mono.just(new AuthorizationDecision(false)); } // 前台登录,匹配路径是是后台 if (AuthConstant.PORTAL_CLIENT_ID.equals(userDto.getClientId()) && pathMatcher.match(AuthConstant.ADMIN_URL_PATTERN, uriPath)) { return Mono.just(new AuthorizationDecision(false)); } // 非管理端路径直接放行 if (!pathMatcher.match(AuthConstant.ADMIN_URL_PATTERN, uriPath)) { return Mono.just(new AuthorizationDecision(true)); } log.info("当前请求得路径为:--->" + uriPath); // 管理端路径需要验证权限 // 权限格式:role_map /mall-admin/brand/** 3_订单管理员,2_订单管理员 // /mall-admin/product/** 3_订单管理员,2_订单管理员 Map<Object, Object> entries = redisTemplate.opsForHash() .entries(AuthConstant.RESOURCE_ROLES_MAP_KEY); // 获取资源url对应的角色集合 List<String> roleNames = entries.keySet().stream() .filter(item -> pathMatcher.match(item.toString(), uriPath)) // 获取url对应的role_name 列表 .map(item_1 -> (JSONArray.parseArray(entries.get(item_1.toString()).toString(), String.class))) .findFirst().orElse(new ArrayList<String>()); if (roleNames.size() == 0) { return Mono.just(new AuthorizationDecision(false)); } // 也可以通过 userDto.getAuthorities(); 拿到角色列表 // List<String> roles = userDto.getAuthorities(); // System.out.println( "roles--->" ); // roles.forEach(System.out::println); // 获取最新的 角色列表 List<String> roles = roleNames .stream() .map( // ROLE_5_超级管理员 roleName -> AuthConstant.AUTHORITY_PREFIX + roleName ).collect(Collectors.toList()); // 验证角色 return authentication .filter(Authentication::isAuthenticated) .flatMapIterable(Authentication::getAuthorities) .map(GrantedAuthority::getAuthority) .any(roles::contains) .map(AuthorizationDecision::new) .defaultIfEmpty(new AuthorizationDecision(false)); } catch (ParseException e) { e.printStackTrace(); } return Mono.just(new AuthorizationDecision(false)); } }
922fb71684bc4c9a57c3b4edf2639d108d9a2f12
4,796
java
Java
EcMainModule/src/msf/ecmm/emctrl/pojo/parts/DeviceNodeOsUpgrade.java
multi-service-fabric/element-controller
e1491c4e6df88606e908a1563a70a16e3ec53758
[ "Apache-2.0" ]
1
2018-03-19T03:45:59.000Z
2018-03-19T03:45:59.000Z
EcMainModule/src/msf/ecmm/emctrl/pojo/parts/DeviceNodeOsUpgrade.java
multi-service-fabric/element-controller
e1491c4e6df88606e908a1563a70a16e3ec53758
[ "Apache-2.0" ]
null
null
null
EcMainModule/src/msf/ecmm/emctrl/pojo/parts/DeviceNodeOsUpgrade.java
multi-service-fabric/element-controller
e1491c4e6df88606e908a1563a70a16e3ec53758
[ "Apache-2.0" ]
1
2020-04-02T01:18:04.000Z
2020-04-02T01:18:04.000Z
24.345178
120
0.661176
995,224
/* * Copyright(c) 2019 Nippon Telegraph and Telephone Corporation */ package msf.ecmm.emctrl.pojo.parts; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; /** * Class for the device infomation (to upgrade OS in the node). */ @XmlAccessorType(XmlAccessType.FIELD) @XmlRootElement(name = "device") public class DeviceNodeOsUpgrade { /** The name of the node to be added. */ private String name = null; /** The name of the node type to be added. */ @XmlElement(name = "node-type") private String nodeType = null; /** The equipment information to be added. */ private Equipment equipment = null; /** The coversion tatble of the physical IF information. */ @XmlElement(name = "physical-ifs") private List<InterfaceNames> physiIfNames = null; /** The coversion tatble of the LAG information IF. */ @XmlElement(name = "lag-ifs") private List<InterfaceNames> lagIfNames = null; /** The list of the internal link IF information. */ @XmlElement(name = "internal-interface") private List<InternalInterface> internalInterfaceList = null; /** The DB-updating flag */ @XmlElement(name = "db_update") private String dbUpdate = null; /** * A new instance is generated. */ public DeviceNodeOsUpgrade() { super(); } /** * The name of the added node is acquired. * * @return The name of the added node */ public String getName() { return name; } /** * The name of the added node is set. * * @param name * The name of the added node */ public void setName(String name) { this.name = name; } /** * The type name of the node is acquired. * * @return The type name of the node */ public String getNodeType() { return nodeType; } /** * The type name of the node is set. * * @param nodeType * The type name of the node. */ public void setNodeType(String nodeType) { this.nodeType = nodeType; } /** * The information on the added equipment is acquired. * * @return The information on the added equipment. */ public Equipment getEquipment() { return equipment; } /** * The information on the added device set. * * @param equipment * The information on the added device */ public void setEquipment(Equipment equipment) { this.equipment = equipment; } /** * The table for converting the physical IF to the information IF is acquired. * * @return The table for converting the physical IF to the information IF */ public List<InterfaceNames> getPhysiIfNames() { return physiIfNames; } /** * The table for converting the physical IF to the information IF is set * * @param physiIfNames * The table for converting the physical IF to the information IF */ public void setPhysiIfNames(List<InterfaceNames> physiIfNames) { this.physiIfNames = physiIfNames; } /** * The table for converting the LAG information IF is acquired. * * @return The table for converting the LAG information IF */ public List<InterfaceNames> getLagIfNames() { return lagIfNames; } /** * The table for converting the LAG information IF is acquired. * * @param lagIfNames * The table for converting the LAG information IF */ public void setLagIfNames(List<InterfaceNames> lagIfNames) { this.lagIfNames = lagIfNames; } /** * The informaton list for setting the internal link is acquired. * * @return The informaton list for setting the internal link */ public List<InternalInterface> getInternalIntefaceList() { return internalInterfaceList; } /** * The informaton list for setting the internal link is set. * * @param internalLagList * The informaton list for setting the internal link. */ public void setInternalInterfaceList(List<InternalInterface> internalLagList) { this.internalInterfaceList = internalLagList; } /** * The DB-updating flag is added. * * @return The DB-updating flag */ public String addDbUpdate() { return dbUpdate = new String(""); } /** * The DB-updating flag is deleted. * */ public void delDbUpdate() { this.dbUpdate = null; } /* (non JavaDoc) * @see java.lang.Object#toString() */ @Override public String toString() { return "DeviceNodeOsUpgrade [name=" + name + ", nodeType=" + nodeType + ", equipment=" + equipment + ", physiIfNames=" + physiIfNames + ", lagIfNames=" + lagIfNames + ", internalLagList=" + internalInterfaceList + ", dbUpdate=" + dbUpdate + "]"; } }
922fb739bf53a8bdfe71a108258a5e4b167da931
758
java
Java
gulimall-ware/src/main/java/com/atguigu/gulimall/ware/service/PurchaseService.java
ShotoZheng/gulimall
8bf0bd8d3436f07d34122f79035d97feede476d7
[ "Apache-2.0" ]
null
null
null
gulimall-ware/src/main/java/com/atguigu/gulimall/ware/service/PurchaseService.java
ShotoZheng/gulimall
8bf0bd8d3436f07d34122f79035d97feede476d7
[ "Apache-2.0" ]
null
null
null
gulimall-ware/src/main/java/com/atguigu/gulimall/ware/service/PurchaseService.java
ShotoZheng/gulimall
8bf0bd8d3436f07d34122f79035d97feede476d7
[ "Apache-2.0" ]
null
null
null
23.78125
69
0.768725
995,225
package com.atguigu.gulimall.ware.service; import com.atguigu.gulimall.ware.vo.MergeVo; import com.atguigu.gulimall.ware.vo.PurchaseDoneVo; import com.baomidou.mybatisplus.extension.service.IService; import com.atguigu.common.utils.PageUtils; import com.atguigu.gulimall.ware.entity.PurchaseEntity; import java.util.List; import java.util.Map; /** * 采购信息 * * @author shotozheng * @email hzdkv@example.com * @date 2021-05-16 21:45:42 */ public interface PurchaseService extends IService<PurchaseEntity> { PageUtils queryPage(Map<String, Object> params); PageUtils queryPageUnreceivePurchase(Map<String, Object> params); void mergePurchase(MergeVo mergeVo); void received(List<Long> ids); void done(PurchaseDoneVo doneVo); }
922fb78111edf989032ad0d7eb3bf3329d32443d
10,724
java
Java
app/src/main/java/com/chen/data/LeaveApplication.java
HelloWroldDeveloper/classmanager
de855321ded7b2af0b9fbd5ebc13a59d7afd6159
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/chen/data/LeaveApplication.java
HelloWroldDeveloper/classmanager
de855321ded7b2af0b9fbd5ebc13a59d7afd6159
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/chen/data/LeaveApplication.java
HelloWroldDeveloper/classmanager
de855321ded7b2af0b9fbd5ebc13a59d7afd6159
[ "Apache-2.0" ]
null
null
null
37.760563
130
0.562197
995,226
package com.chen.data; import android.util.Log; import android.widget.Toast; import com.chen.activity.BaseActivity; import com.chen.adapter.LeaveApplyContentAdapter; import com.chen.fragment.Leave_apply_add_s3_fragment; import com.chen.handle.DataInput; import com.chen.handle.DataOutput; import com.chen.handle.HttpUtil; import com.chen.handle.Util; import org.json.JSONObject; import org.litepal.crud.DataSupport; import java.io.IOException; import java.net.URLDecoder; import java.text.ParseException; import java.util.ArrayList; import java.util.List; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response; //请假申请 实体类 public class LeaveApplication extends DataSupport { public static final int REVIEWING=1;//状态:审核中 public static final int PASSED=2;//状态:已通过 public static final int NO_PASS=3;//状态:未通过 public static final int IGNORED=4;//状态:已忽略 public static final int OVER_DUE=5;//状态:已过期 public static final String TAG="LeaveApplication";//用于生成日志的tag //用于保存和读取数据的关键字 public static final String KEY_TITLE="title"; public static final String KEY_CONTENT="content"; public static final String KEY_START_DATE="start_date"; public static final String KEY_END_DATE="end_date"; public static final String KEY_START_TIME="start_time"; public static final String KEY_END_TIME="end_time"; //用于保存和读取数据的关键字 private static List<LeaveApplication> applications;//请假申请 列表 private String title; private String content; private String start_date; private String end_date; private String create_date; private int status; private int application_id; public LeaveApplication(String title,String content,MyDate start_date,MyDate end_date,int id){ this.title=title; this.content=content; this.start_date=start_date.toString(); this.end_date=end_date.toString(); this.status=LeaveApplication.REVIEWING; this.create_date=MyDate.getCurrentDate().toString(); this.application_id =id; } public String getTitle(){ return title; } public String getContent() { return content; } public MyDate getStart_date() { return MyDate.parseMyDate(start_date); } public MyDate getEnd_date() { return MyDate.parseMyDate(end_date); } public MyDate getCreate_date() { return MyDate.parseMyDate(create_date); } public int getStatus() { return status; } public int getApplication_id() { return application_id; } public String getStatusStatement(){ switch (status){ case LeaveApplication.REVIEWING: return "审核中"; case LeaveApplication.PASSED: return "已通过"; case LeaveApplication.NO_PASS: return "未通过"; case LeaveApplication.IGNORED: return "已忽略"; case LeaveApplication.OVER_DUE: return "已过期"; default: return null; } } public void setStatus(int status) { this.status = status; } //更新某个请假申请的状态 public void updateStatus(final LeaveApplyContentAdapter adapter, final BaseActivity activity){ //根据id向服务器发起查询请假申请状态的请求,并保存到result中 List<HttpUtil.Arg> args=new ArrayList<>(); args.add(new HttpUtil.Arg("type","check_application_status")); args.add(new HttpUtil.Arg("id",getApplication_id()+"")); HttpUtil.sendGetHttpRequest(args, new Callback() { @Override public void onFailure(Call call, IOException e) { Util.displayError(activity,e,"查询请假申请状态失败",TAG,true); } @Override public void onResponse(Call call, Response response) { try{ String result=new JSONObject(URLDecoder.decode(response.body().string(),"utf-8")).getString("status"); switch (result){ case "no": activity.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(activity,"在服务器找不到对应的请假申请",Toast.LENGTH_SHORT).show(); } }); return; case "1": int status=getStatus(); if((status!=LeaveApplication.OVER_DUE)&&MyDate.before_now(getEnd_date())){ setStatus(LeaveApplication.OVER_DUE); }else if((status==LeaveApplication.REVIEWING)&&MyDate.before_now(getStart_date())){ setStatus(LeaveApplication.IGNORED); } break; case "2": setStatus(LeaveApplication.NO_PASS); break; case "3": setStatus(LeaveApplication.PASSED); break; } adapter.setApplication(LeaveApplication.this); adapter.notifyDataSetChanged(); }catch (Exception e){ Util.displayError(activity,e,"查询请假申请状态失败",TAG,true); } } }); } //初始化请假申请列表 public static void initApplications(){ applications= DataInput.getApplications(); /* //测试 MyDate date1=new MyDate(2020,1,1,1,1); MyDate date2=new MyDate(2020,1,2,2,2); for (int i=1;i<=50;i++){ String content=""; for (int k=1;k<=600;k++){ content+=(""+i); } LeaveApplication leave=new LeaveApplication(i+""+i,content,date1,date2,i); applications.add(leave); } //测试 */ } public static List<LeaveApplication> getApplications(){ return applications; } //通过id查找 请假申请 public static LeaveApplication findApplicationByID(int id){ for(LeaveApplication application:applications){ if(application.getApplication_id()==id){ return application; } } return null; } //添加新的请假申请 public static void addNewApplication(final String title, final String content, final MyDate start_date, final MyDate end_date, final Leave_apply_add_s3_fragment fragment, final BaseActivity activity){ //根据title,content,start_date,end_date和create_date向服务器发出创建请假申请的请求 User now_user=User.getNowUser(); List<HttpUtil.Arg> args=new ArrayList<>(); args.add(new HttpUtil.Arg("type","add_application")); args.add(new HttpUtil.Arg("number",now_user.getNumber())); args.add(new HttpUtil.Arg("name",now_user.getName())); args.add(new HttpUtil.Arg("class",DataInput.getClassNumber())); args.add(new HttpUtil.Arg("title",title)); args.add(new HttpUtil.Arg("content",content)); args.add(new HttpUtil.Arg("start_date",start_date.toString())); args.add(new HttpUtil.Arg("end_date",end_date.toString())); args.add(new HttpUtil.Arg("create_date",MyDate.getCurrentDate().toString())); HttpUtil.sendPostHttpRequest(args, new Callback() { @Override public void onFailure(Call call, IOException e) { Util.displayError(activity,e,"创建请假申请失败",TAG,true); } @Override public void onResponse(Call call, Response response) { try { int id=Integer.parseInt(new JSONObject(URLDecoder.decode(response.body().string(),"utf-8")).getString("id")); applications.add(new LeaveApplication(title,content,start_date,end_date,id)); activity.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(activity,"成功创建申请",Toast.LENGTH_SHORT).show(); fragment.setCreating(true); DataOutput.deleteApplication(activity); activity.finish(); } }); }catch (Exception e){ Util.displayError(activity,e,"创建请假申请失败",TAG,true); } } }); } public static void deleteApplication(int id,final BaseActivity activity){ for(int i=0;i<applications.size();i++){ if(applications.get(i).getApplication_id()==id){ applications.remove(i); break; } } //根据id向服务器发出删除请假申请的请求(在此书写逻辑) List<HttpUtil.Arg> args=new ArrayList<>(); args.add(new HttpUtil.Arg("type","delete_application")); args.add(new HttpUtil.Arg("id",id+"")); HttpUtil.sendGetHttpRequest(args, new Callback() { @Override public void onFailure(Call call, IOException e) { Util.displayError(activity,e,"删除请假申请失败",TAG,true); } @Override public void onResponse(Call call, Response response) { try{ String status=new JSONObject(URLDecoder.decode(response.body().string(),"utf-8")).getString("status"); if(status.equals("ok")){ Toast.makeText(activity,"删除成功",Toast.LENGTH_SHORT).show(); activity.finish(); }else { activity.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(activity,"在服务器找不到相应的请假申请",Toast.LENGTH_SHORT).show(); } }); } }catch (Exception e){ Util.displayError(activity,e,"删除请假申请失败",TAG,true); } } }); } //更新请假申请列表 public static void updateApplications(){ //根据开始时间和结束日期更新请假申请 try{ for(LeaveApplication application:applications){ if((application.getStatus()!=LeaveApplication.OVER_DUE)&&MyDate.before_now(application.getEnd_date())){ application.setStatus(LeaveApplication.OVER_DUE); } } }catch (ParseException e){ e.printStackTrace(); Log.e(TAG,"无法解析日期"); } //根据开始时间和结束日期更新请假申请 } }
922fb79fab3fc2437c172af1cb84df3aefacac97
867
java
Java
easyload_library/src/main/java/com/zhangxb/easyload_library/layout/AbstractLayout.java
izhangxb/EasyLoad
76a864f27505b29303c6f103d4d8f4231aa390c5
[ "Apache-2.0" ]
null
null
null
easyload_library/src/main/java/com/zhangxb/easyload_library/layout/AbstractLayout.java
izhangxb/EasyLoad
76a864f27505b29303c6f103d4d8f4231aa390c5
[ "Apache-2.0" ]
null
null
null
easyload_library/src/main/java/com/zhangxb/easyload_library/layout/AbstractLayout.java
izhangxb/EasyLoad
76a864f27505b29303c6f103d4d8f4231aa390c5
[ "Apache-2.0" ]
null
null
null
25.5
110
0.750865
995,227
package com.zhangxb.easyload_library.layout; import android.content.Context; import android.support.annotation.AttrRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.View; import android.widget.FrameLayout; import java.util.HashMap; import java.util.Map; /** * Created by zhangxb on 2017/9/27. */ public abstract class AbstractLayout extends FrameLayout { public AbstractLayout(@NonNull Context context) { super(context); } public AbstractLayout(@NonNull Context context, @Nullable AttributeSet attrs) { super(context, attrs); } public AbstractLayout(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr) { super(context, attrs, defStyleAttr); } public abstract int setLayout(); }
922fb907a55a4c28e64e6cf01a21310c6545fced
8,033
java
Java
laravel-converted/src/main/java/com/project/convertedCode/globalNamespace/namespaces/Hamcrest/classes/Util.java
RuntimeConverter/RuntimeConverterLarvelJava
7ae848744fbcd993122347ffac853925ea4ea3b9
[ "MIT" ]
null
null
null
laravel-converted/src/main/java/com/project/convertedCode/globalNamespace/namespaces/Hamcrest/classes/Util.java
RuntimeConverter/RuntimeConverterLarvelJava
7ae848744fbcd993122347ffac853925ea4ea3b9
[ "MIT" ]
null
null
null
laravel-converted/src/main/java/com/project/convertedCode/globalNamespace/namespaces/Hamcrest/classes/Util.java
RuntimeConverter/RuntimeConverterLarvelJava
7ae848744fbcd993122347ffac853925ea4ea3b9
[ "MIT" ]
null
null
null
42.278947
101
0.624175
995,228
package com.project.convertedCode.globalNamespace.namespaces.Hamcrest.classes; import com.runtimeconverter.runtime.references.ReferenceContainer; import com.runtimeconverter.runtime.passByReference.PassByReferenceArgs; import com.runtimeconverter.runtime.classes.StaticBaseClass; import com.runtimeconverter.runtime.references.BasicReferenceContainer; import com.runtimeconverter.runtime.nativeFunctions.typeIsA.function_is_array; import com.project.convertedCode.globalNamespace.namespaces.Hamcrest.classes.Matcher; import com.runtimeconverter.runtime.includes.IncludeEventException; import com.runtimeconverter.runtime.classes.RuntimeClassBase; import com.runtimeconverter.runtime.RuntimeEnv; import com.runtimeconverter.runtime.interfaces.UpdateRuntimeScopeInterface; import com.runtimeconverter.runtime.ZVal; import com.runtimeconverter.runtime.reflection.ReflectionClassData; import com.runtimeconverter.runtime.annotations.ConvertedParameter; import com.runtimeconverter.runtime.arrays.ZPair; import com.project.convertedCode.globalNamespace.namespaces.Hamcrest.namespaces.Core.classes.IsEqual; import java.lang.invoke.MethodHandles; import com.runtimeconverter.runtime.RuntimeStack; import com.runtimeconverter.runtime.interfaces.ContextConstants; import com.runtimeconverter.runtime.nativeClasses.spl.exceptions.InvalidArgumentException; import com.runtimeconverter.runtime.classes.NoConstructor; import com.runtimeconverter.runtime.nativeFunctions.array.function_count; import com.runtimeconverter.runtime.annotations.ConvertedMethod; import static com.runtimeconverter.runtime.ZVal.toStringR; import static com.runtimeconverter.runtime.ZVal.assignParameter; /* Converted with The Runtime Converter (runtimeconverter.com) vendor/hamcrest/hamcrest-php/hamcrest/Hamcrest/Util.php */ public class Util extends RuntimeClassBase { public Util(RuntimeEnv env, Object... args) { super(env); } public Util(NoConstructor n) { super(n); } public static final Object CONST_class = "Hamcrest\\Util"; // Runtime Converter Internals // RuntimeStaticCompanion contains static methods // RequestStaticProperties contains static (per-request) properties // ReflectionClassData contains php reflection data used by the runtime library public static class RuntimeStaticCompanion extends StaticBaseClass { private static final MethodHandles.Lookup staticCompanionLookup = MethodHandles.lookup(); @ConvertedMethod public Object registerGlobalFunctions(RuntimeEnv env, Object... args) { RuntimeStack stack = new RuntimeStack(); stack.setupGlobals(env); Scope14 scope = new Scope14(); stack.pushScope(scope); scope._thisVarAlias = this; try { ContextConstants runtimeConverterFunctionClassConstants = new ContextConstants() .setDir("/vendor/hamcrest/hamcrest-php/hamcrest/Hamcrest") .setFile( "/vendor/hamcrest/hamcrest-php/hamcrest/Hamcrest/Util.php"); env.include( toStringR( env.addRootFilesystemPrefix( "/vendor/hamcrest/hamcrest-php/hamcrest/Hamcrest"), env) + "/../Hamcrest.php", stack, runtimeConverterFunctionClassConstants, true, true); throw new IncludeEventException(null); } catch (IncludeEventException runtimeConverterIncludeException) { return runtimeConverterIncludeException.returnValue; } } @ConvertedMethod @ConvertedParameter(index = 0, name = "item") public Object wrapValueWithIsEqual(RuntimeEnv env, Object... args) { Object item = assignParameter(args, 0, false); return ZVal.assign( ZVal.isTrue(ZVal.checkInstanceType(item, Matcher.class, "Hamcrest\\Matcher")) ? item : IsEqual.runtimeStaticObject.equalTo(env, item)); } @ConvertedMethod @ConvertedParameter(index = 0, name = "matchers", typeHint = "array") public Object checkAllAreMatchers(RuntimeEnv env, Object... args) { Object matchers = assignParameter(args, 0, false); Object m = null; for (ZPair zpairResult174 : ZVal.getIterable(matchers, env, true)) { m = ZVal.assign(zpairResult174.getValue()); if (!ZVal.isTrue(ZVal.checkInstanceType(m, Matcher.class, "Hamcrest\\Matcher"))) { throw ZVal.getException( env, new InvalidArgumentException( env, "Each argument or element must be a Hamcrest matcher")); } } return null; } @ConvertedMethod @ConvertedParameter(index = 0, name = "items", typeHint = "array") public Object createMatcherArray(RuntimeEnv env, Object... args) { ReferenceContainer items = new BasicReferenceContainer(assignParameter(args, 0, false)); ReferenceContainer item = new BasicReferenceContainer(null); if (ZVal.toBool( ZVal.equalityCheck( function_count.f.env(env).call(items.getObject()).value(), 1)) && ZVal.toBool( function_is_array.f.env(env).call(items.arrayGet(env, 0)).value())) { items.setObject(ZVal.assign(items.arrayGet(env, 0))); } for (ZPair zpairResult175 : ZVal.getIterable(items.getObject(), env, true)) { item = zpairResult175; if (!ZVal.isTrue( ZVal.checkInstanceType( item.getObject(), Matcher.class, "Hamcrest\\Matcher"))) { item.setObject(IsEqual.runtimeStaticObject.equalTo(env, item.getObject())); } } return ZVal.assign(items.getObject()); } } public static final RuntimeStaticCompanion runtimeStaticObject = new RuntimeStaticCompanion(); private static final ReflectionClassData runtimeConverterReflectionData = ReflectionClassData.builder() .setName("Hamcrest\\Util") .setLookup( Util.class, MethodHandles.lookup(), RuntimeStaticCompanion.staticCompanionLookup) .setLocalProperties() .setFilename("vendor/hamcrest/hamcrest-php/hamcrest/Hamcrest/Util.php") .get(); @Override public ReflectionClassData getRuntimeConverterReflectionData() { return runtimeConverterReflectionData; } @Override public Object converterRuntimeCallExtended( RuntimeEnv env, String method, Class<?> caller, PassByReferenceArgs passByReferenceArgs, Object... args) { return RuntimeClassBase.converterRuntimeCallExtendedWithDataStatic( this, runtimeConverterReflectionData, env, method, caller, passByReferenceArgs, args); } private static class Scope14 implements UpdateRuntimeScopeInterface { Object _thisVarAlias; public void updateStack(RuntimeStack stack) { stack.setVariable("this", this._thisVarAlias); } public void updateScope(RuntimeStack stack) { this._thisVarAlias = stack.getVariable("this"); } } }
922fb94350dc1504fdffd55ecd8a64b81dd7186d
5,520
java
Java
examples/demo/domain/src/main/java/demoapp/dom/domain/actions/Action/executionPublishing/jdo/ActionExecutionPublishingJdo.java
ecpnv-devops/isis
aeda00974e293e2792783090360b155a9d1a6624
[ "Apache-2.0" ]
665
2015-01-01T06:06:28.000Z
2022-03-27T01:11:56.000Z
examples/demo/domain/src/main/java/demoapp/dom/domain/actions/Action/executionPublishing/jdo/ActionExecutionPublishingJdo.java
jalexmelendez/isis
ddf3bd186cad585b959b7f20d8c9ac5e3f33263d
[ "Apache-2.0" ]
176
2015-02-07T11:29:36.000Z
2022-03-25T04:43:12.000Z
examples/demo/domain/src/main/java/demoapp/dom/domain/actions/Action/executionPublishing/jdo/ActionExecutionPublishingJdo.java
jalexmelendez/isis
ddf3bd186cad585b959b7f20d8c9ac5e3f33263d
[ "Apache-2.0" ]
337
2015-01-02T03:01:34.000Z
2022-03-21T15:56:28.000Z
35.612903
109
0.729167
995,229
/* * 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 demoapp.dom.domain.actions.Action.executionPublishing.jdo; import javax.jdo.annotations.DatastoreIdentity; import javax.jdo.annotations.IdGeneratorStrategy; import javax.jdo.annotations.IdentityType; import javax.jdo.annotations.PersistenceCapable; import org.springframework.context.annotation.Profile; import org.apache.isis.applib.annotation.Action; import org.apache.isis.applib.annotation.ActionLayout; import org.apache.isis.applib.annotation.DomainObject; import org.apache.isis.applib.annotation.Editing; import org.apache.isis.applib.annotation.MemberSupport; import org.apache.isis.applib.annotation.Nature; import org.apache.isis.applib.annotation.ObjectSupport; import org.apache.isis.applib.annotation.Property; import org.apache.isis.applib.annotation.PropertyLayout; import org.apache.isis.applib.annotation.Publishing; import org.apache.isis.applib.annotation.SemanticsOf; import lombok.Getter; import lombok.Setter; import demoapp.dom.domain.actions.Action.executionPublishing.ActionExecutionPublishingDisabledMetaAnnotation; import demoapp.dom.domain.actions.Action.executionPublishing.ActionExecutionPublishingEnabledMetaAnnotation; import demoapp.dom.domain.actions.Action.executionPublishing.ActionExecutionPublishingEntity; @Profile("demo-jdo") //tag::class[] @PersistenceCapable(identityType = IdentityType.DATASTORE, schema = "demo") @DatastoreIdentity(strategy = IdGeneratorStrategy.IDENTITY, column = "id") @DomainObject( nature=Nature.ENTITY , logicalTypeName = "demo.ActionExecutionPublishingEntity" , editing = Editing.DISABLED ) public class ActionExecutionPublishingJdo extends ActionExecutionPublishingEntity { // ... //end::class[] public ActionExecutionPublishingJdo(final String initialValue) { this.property = initialValue; this.propertyMetaAnnotated = initialValue; this.propertyMetaAnnotatedOverridden = initialValue; } @ObjectSupport public String title() { return "Action#executionPublishing (JDO)"; } //tag::property[] @Property() @PropertyLayout(fieldSetId = "annotation", sequence = "1") @Getter @Setter private String property; @Property() @PropertyLayout(fieldSetId = "meta-annotated", sequence = "1") @Getter @Setter private String propertyMetaAnnotated; @Property() @PropertyLayout(fieldSetId = "meta-annotated-overridden", sequence = "1") @Getter @Setter private String propertyMetaAnnotatedOverridden; //end::property[] //tag::annotation[] @Action( executionPublishing = Publishing.ENABLED // <.> , semantics = SemanticsOf.IDEMPOTENT ) @ActionLayout( named = "Update Property" , describedAs = "@Action(publishing = ENABLED)" , associateWith = "property" , sequence = "1" ) public ActionExecutionPublishingJdo updatePropertyUsingAnnotation(final String value) { setProperty(value); return this; } @MemberSupport public String default0UpdatePropertyUsingAnnotation() { return getProperty(); } //end::annotation[] //tag::meta-annotation[] @ActionExecutionPublishingEnabledMetaAnnotation // <.> @Action( semantics = SemanticsOf.IDEMPOTENT ) @ActionLayout( named = "Update Property" , describedAs = "@ActionPublishingEnabledMetaAnnotation" , associateWith = "propertyMetaAnnotated" , sequence = "1" ) public ActionExecutionPublishingJdo updatePropertyUsingMetaAnnotation(final String value) { setPropertyMetaAnnotated(value); return this; } @MemberSupport public String default0UpdatePropertyUsingMetaAnnotation() { return getPropertyMetaAnnotated(); } //end::meta-annotation[] //tag::meta-annotation-overridden[] @ActionExecutionPublishingDisabledMetaAnnotation // <.> @Action( executionPublishing = Publishing.ENABLED // <.> , semantics = SemanticsOf.IDEMPOTENT ) @ActionLayout( named = "Update Property" , describedAs = "@ActionPublishingDisabledMetaAnnotation " + "@Action(publishing = ENABLED)" , associateWith = "propertyMetaAnnotatedOverridden" , sequence = "1" ) public ActionExecutionPublishingJdo updatePropertyUsingMetaAnnotationButOverridden(final String value) { setPropertyMetaAnnotatedOverridden(value); return this; } @MemberSupport public String default0UpdatePropertyUsingMetaAnnotationButOverridden() { return getPropertyMetaAnnotatedOverridden(); } //end::meta-annotation-overridden[] //tag::class[] } //end::class[]
922fb9bc0a0773ee8663968a6b94161f79341250
23,367
java
Java
src/com/thomasdiewald/pixelflow/java/dwgl/DwGLTexture3D.java
stevestorey/PixelFlow
3db49397164bc76373ff7e15c0a31dadb0037801
[ "MIT" ]
1,133
2016-09-15T00:49:36.000Z
2022-03-30T08:31:52.000Z
src/com/thomasdiewald/pixelflow/java/dwgl/DwGLTexture3D.java
stevestorey/PixelFlow
3db49397164bc76373ff7e15c0a31dadb0037801
[ "MIT" ]
39
2016-10-02T03:07:47.000Z
2021-12-20T23:43:44.000Z
src/com/thomasdiewald/pixelflow/java/dwgl/DwGLTexture3D.java
stevestorey/PixelFlow
3db49397164bc76373ff7e15c0a31dadb0037801
[ "MIT" ]
134
2016-10-19T15:23:08.000Z
2022-03-07T05:47:00.000Z
28.496341
172
0.609064
995,230
/** * * PixelFlow | Copyright (C) 2016 Thomas Diewald - http://thomasdiewald.com * * A Processing/Java library for high performance GPU-Computing (GLSL). * MIT License: https://opensource.org/licenses/MIT * */ package com.thomasdiewald.pixelflow.java.dwgl; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; import com.jogamp.opengl.GL; import com.jogamp.opengl.GL2; import com.jogamp.opengl.GL2ES2; import com.jogamp.opengl.GL2ES3; import com.jogamp.opengl.GL2GL3; import com.jogamp.opengl.GLES3; import com.thomasdiewald.pixelflow.java.DwPixelFlow; public class DwGLTexture3D{ static private int TEX_COUNT = 0; public DwPixelFlow context; private GL2ES2 gl; public final int[] HANDLE = {0}; // some default values. TODO public final int target = GL2ES2.GL_TEXTURE_3D; public int internalFormat = GL2ES2.GL_RGBA8; public int format = GL2ES2.GL_RGBA; public int type = GL2ES2.GL_UNSIGNED_BYTE; public int filter = GL2ES2.GL_NEAREST; public int wrap = GL2ES2.GL_CLAMP_TO_BORDER; public int num_channel = 4; public int byte_per_channel = 1; // dimension public int w = 0; public int h = 0; public int d = 0; // PixelBufferObject public final int[] HANDLE_pbo = {0}; // Texture, for Subregion copies and data transfer public DwGLTexture3D texsub = null; // recursion! public DwGLTexture3D(){ } public DwGLTexture3D createEmtpyCopy(){ DwGLTexture3D tex = new DwGLTexture3D(); tex.resize(context, this); return tex; } public void release(){ // release texture if(isTexture()){ gl.glDeleteTextures(1, HANDLE, 0); HANDLE[0] = 0; w = 0; h = 0; if(--TEX_COUNT < 0){ TEX_COUNT = 0; System.out.println("ERROR: released to many textures"); } } // release pbo if(hasPBO()){ gl.glDeleteBuffers(1, HANDLE_pbo, 0); HANDLE_pbo[0] = 0; } // release subtexture if(texsub != null){ texsub.release(); texsub = null; } } public int w(){ return w; } public int h(){ return h; } public int d(){ return d; } public boolean isTexture(){ return (gl != null) && (HANDLE[0] != 0); } public boolean isTexture2(){ return (gl != null) && gl.glIsTexture(HANDLE[0]); } public boolean hasPBO(){ return (gl != null) && (HANDLE_pbo[0] != 0); } public int getMem_Byte(){ return w * h * d * byte_per_channel * num_channel; } public int getMem_KiloByte(){ return getMem_Byte() >> 10; } public int getMem_MegaByte(){ return getMem_Byte() >> 20; } public boolean resize(DwPixelFlow context, DwGLTexture3D othr){ return resize(context, othr, othr.w, othr.h, othr.d); } public boolean resize(DwPixelFlow context, DwGLTexture3D othr, int w, int h, int d){ return resize(context, othr.internalFormat, w, h, d, othr.format, othr.type, othr.filter, othr.wrap, othr.num_channel, othr.byte_per_channel); } public boolean resize(DwPixelFlow context, int w, int h, int d) { return resize(context, internalFormat, w, h, d, format, type, filter, wrap, num_channel, byte_per_channel, null); } public boolean resize(DwPixelFlow context, int internalFormat, int w, int h, int d, int format, int type, int filter, int num_channel, int byte_per_channel) { return resize(context, internalFormat, w, h, d, format, type, filter, wrap, num_channel, byte_per_channel, null); } public boolean resize(DwPixelFlow context, int internalFormat, int w, int h, int d, int format, int type, int filter, int wrap, int num_channel, int byte_per_channel) { return resize(context, internalFormat, w, h, d, format, type, filter, wrap, num_channel, byte_per_channel, null); } public boolean resize(DwPixelFlow context, int internalFormat, int w, int h, int d, int format, int type, int filter, int num_channel, int byte_per_channel, Buffer data) { return resize(context, internalFormat, w, h, d, format, type, filter, wrap, num_channel, byte_per_channel, data); } public boolean resize(DwPixelFlow context, int internalFormat, int w, int h, int d, int format, int type, int filter, int wrap, int num_channel, int byte_per_channel, Buffer data) { this.context = context; this.gl = context.gl; if(w <= 0 || h <= 0 || d <= 0) return false; // figure out what needs to be done for this texture boolean B_ALLOC=false, B_RESIZE=false, B_FILTER=false, B_WRAP=false, B_BIND=false; B_ALLOC |= !isTexture(); B_RESIZE |= B_ALLOC; B_RESIZE |= this.w != w; // width B_RESIZE |= this.h != h; // height B_RESIZE |= this.d != d; // depth B_RESIZE |= this.internalFormat != internalFormat; // internalFormat B_RESIZE |= this.format != format; // format B_RESIZE |= this.type != type; // type B_FILTER |= B_ALLOC || B_RESIZE; B_FILTER |= this.filter != filter; B_WRAP |= B_ALLOC || B_RESIZE; B_WRAP |= this.wrap != wrap; B_BIND = B_ALLOC | B_RESIZE | B_FILTER | B_WRAP; // assign fields this.w = w; this.h = h; this.d = d; this.internalFormat = internalFormat; this.format = format; this.type = type; this.filter = filter; this.wrap = wrap; this.num_channel = num_channel; this.byte_per_channel = byte_per_channel; if(B_ALLOC){ gl.glGenTextures(1, HANDLE, 0); TEX_COUNT++; } if(B_RESIZE) { gl.glBindTexture(target, HANDLE[0]); gl.glBindTexture(target, HANDLE[0]); // gl.glTexParameteri(target, GL2ES2.GL_TEXTURE_BASE_LEVEL, 0); // gl.glTexParameteri(target, GL2ES2.GL_TEXTURE_MAX_LEVEL, 0); gl.glPixelStorei(GL2ES2.GL_UNPACK_ALIGNMENT, 1); gl.glPixelStorei(GL2ES2.GL_PACK_ALIGNMENT , 1); // int[] val = new int[1]; // gl.glGetIntegerv(GL2ES2.GL_UNPACK_ALIGNMENT, val, 0); // System.out.println("GL_UNPACK_ALIGNMENT "+val[0]); // gl.glGetIntegerv(GL2ES2.GL_PACK_ALIGNMENT, val, 0); // System.out.println("GL_PACK_ALIGNMENT "+val[0]); gl.glTexImage3D (target, 0, internalFormat, w, h, d, 0, format, type, data); // gl.glTexSubImage2D(target, 0, 0, 0, w, h, format, type, data); } if(B_FILTER) { gl.glBindTexture(target, HANDLE[0]); gl.glTexParameteri(target, GL2ES2.GL_TEXTURE_MIN_FILTER, filter); // GL_NEAREST, GL_LINEAR gl.glTexParameteri(target, GL2ES2.GL_TEXTURE_MAG_FILTER, filter); } if(B_WRAP) { gl.glBindTexture(target, HANDLE[0]); gl.glTexParameteri(target, GL2ES2.GL_TEXTURE_WRAP_R, wrap); gl.glTexParameteri(target, GL2ES2.GL_TEXTURE_WRAP_S, wrap); gl.glTexParameteri(target, GL2ES2.GL_TEXTURE_WRAP_T, wrap); gl.glTexParameterfv(target, GL2ES2.GL_TEXTURE_BORDER_COLOR, new float[]{0,0,0,0}, 0); } if(B_BIND) { gl.glBindTexture(target, 0); context.errorCheck("DwGLTexture.resize tex"); } return B_RESIZE; } /** * <pre> * GL_CLAMP_TO_EDGE * GL_CLAMP_TO_BORDER * GL_MIRRORED_REPEAT * GL_REPEAT (default) * GL_MIRROR_CLAMP_TO_EDGE * </pre> * @param wrap */ public void setParamWrap(int wrap){ this.wrap = wrap; gl.glBindTexture (target, HANDLE[0]); gl.glTexParameteri(target, GL2.GL_TEXTURE_WRAP_R, wrap); gl.glTexParameteri(target, GL2.GL_TEXTURE_WRAP_S, wrap); gl.glTexParameteri(target, GL2.GL_TEXTURE_WRAP_T, wrap); gl.glBindTexture (target, 0); } /** * <pre> * GL_CLAMP_TO_EDGE * GL_CLAMP_TO_BORDER * GL_MIRRORED_REPEAT * GL_REPEAT (default) * GL_MIRROR_CLAMP_TO_EDGE * </pre> * @param wrap */ public void setParamWrap(int wrap, float[] border_color){ this.wrap = wrap; gl.glBindTexture (target, HANDLE[0]); gl.glTexParameteri (target, GL2.GL_TEXTURE_WRAP_R, wrap); gl.glTexParameteri (target, GL2.GL_TEXTURE_WRAP_S, wrap); gl.glTexParameteri (target, GL2.GL_TEXTURE_WRAP_T, wrap); gl.glTexParameterfv(target, GL2.GL_TEXTURE_BORDER_COLOR, border_color, 0); gl.glBindTexture (target, 0); } /** * <pre> * GL_TEXTURE_MAG_FILTER * - GL_NEAREST * - GL_LINEAR (default) * * GL_TEXTURE_MIN_FILTER * - GL_NEAREST ................... nearest texel * - GL_LINEAR .................... linear texel * - GL_NEAREST_MIPMAP_NEAREST .... nearest texel, nearest mipmap (default) * - GL_LINEAR_MIPMAP_NEAREST ..... linear texel, nearest mipmap * - GL_NEAREST_MIPMAP_LINEAR ..... nearest texel, linear mipmap * - GL_LINEAR_MIPMAP_LINEAR ...... linear texel, linear mipmap * </pre> * * @param minfilter * @param magfilter */ public void setParamFilter(int filter){ this.filter = filter; gl.glBindTexture (target, HANDLE[0]); gl.glTexParameteri(target, GL2.GL_TEXTURE_MIN_FILTER, filter); gl.glTexParameteri(target, GL2.GL_TEXTURE_MAG_FILTER, filter); gl.glBindTexture (target, 0); } /** * <pre> * GL_TEXTURE_MAG_FILTER * - GL_NEAREST * - GL_LINEAR (default) * * GL_TEXTURE_MIN_FILTER * - GL_NEAREST ................... nearest texel * - GL_LINEAR .................... linear texel * - GL_NEAREST_MIPMAP_NEAREST .... nearest texel, nearest mipmap (default) * - GL_LINEAR_MIPMAP_NEAREST ..... linear texel, nearest mipmap * - GL_NEAREST_MIPMAP_LINEAR ..... nearest texel, linear mipmap * - GL_LINEAR_MIPMAP_LINEAR ...... linear texel, linear mipmap * </pre> * * @param minfilter * @param magfilter */ public void setParamFilter(int minfilter, int magfilter){ gl.glBindTexture (target, HANDLE[0]); gl.glTexParameteri(target, GL2.GL_TEXTURE_MIN_FILTER, minfilter); gl.glTexParameteri(target, GL2.GL_TEXTURE_MAG_FILTER, magfilter); gl.glBindTexture (target, 0); } public void generateMipMap(){ gl.glBindTexture (target, HANDLE[0]); gl.glTexParameteri (target, GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR_MIPMAP_LINEAR); gl.glGenerateMipmap(target); gl.glBindTexture (target, 0); } public void setParam_Border(float[] border){ gl.glBindTexture (target, HANDLE[0]); gl.glTexParameterfv(target, GLES3.GL_TEXTURE_BORDER_COLOR, border, 0); gl.glBindTexture (target, 0); } public void setParam_Border(int[] border){ gl.glBindTexture (target, HANDLE[0]); gl.glTexParameterIiv(target, GLES3.GL_TEXTURE_BORDER_COLOR, border, 0); gl.glBindTexture (target, 0); } public void glTexParameteri(int param, int value, boolean bind){ if(bind) bind(); glTexParameteri(param, value); if(bind) unbind(); } public void glTexParameteriv(int param, int[] value, boolean bind){ if(bind) bind(); glTexParameteriv(param, value); if(bind) unbind(); } public void glTexParameterf(int param, float value, boolean bind){ if(bind) bind(); glTexParameterf(param, value); if(bind) unbind(); } public void glTexParameterfv(int param, float[] value, boolean bind){ if(bind) bind(); glTexParameterfv(param, value); if(bind) unbind(); } public void glTexParameteri(int param, int value){ gl.glTexParameteri (target, param, value); } public void glTexParameteriv(int param, int[] value){ gl.glTexParameteriv (target, param, value, 0); } public void glTexParameterf(int param, float value){ gl.glTexParameterf (target, param, value); } public void glTexParameterfv(int param, float[] value){ gl.glTexParameterfv(target, param, value, 0); } public void bind(){ gl.glBindTexture(target, HANDLE[0]); } public void unbind(){ gl.glBindTexture(target, 0); } public void swizzle(int[] i4_GL_TEXTURE_SWIZZLE_RGBA){ glTexParameteriv(GL2.GL_TEXTURE_SWIZZLE_RGBA, i4_GL_TEXTURE_SWIZZLE_RGBA, true); } private DwGLTexture3D createTexSubImage(int x, int y, int w, int h){ // create/resize texture from the size of the subregion if(texsub == null){ texsub = new DwGLTexture3D(); } if(x + w > this.w) { System.out.println("Error DwGLTexture.createTexSubImage: region-x is not within texture bounds"); } if(y + h > this.h) { System.out.println("Error DwGLTexture.createTexSubImage: region-y is not within texture bounds "); } texsub.resize(context, internalFormat, w, h, d, format, type, filter, num_channel, byte_per_channel); // copy the subregion to the texture context.beginDraw(this, 0); gl.glBindTexture(target, texsub.HANDLE[0]); gl.glCopyTexSubImage3D(target, 0, 0, 0, 0, x, y, w, h); gl.glBindTexture(target, 0); context.endDraw("DwGLTexture.createTexSubImage"); return texsub; } /** * GPU_DATA_READ == 0 ... a lot faster for the full texture.<br> * only slightly slower for single texels.<br> * <br> * GPU_DATA_READ == 1 ... very slow for the full texture.<br> * takes twice as long as "getData_GL2GL3()".<br> * <br> */ public static int GPU_DATA_READ = 0; // TODO: get data /** * * @param cx * @param cy * @param canvas_w * @param h * @param data array, for the returned opengl-texture-data * @return */ public ByteBuffer getData_GL2ES3(){ return getData_GL2ES3(0,0,w,h); } public ByteBuffer getData_GL2ES3(int x, int y, int w, int h){ int data_len = w * h * num_channel; int buffer_size = data_len * byte_per_channel; context.beginDraw(this, 0); if(HANDLE_pbo[0] == 0){ gl.glGenBuffers(1, HANDLE_pbo, 0); } gl.glBindBuffer(GL2ES3.GL_PIXEL_PACK_BUFFER, HANDLE_pbo[0]); gl.glBufferData(GL2ES3.GL_PIXEL_PACK_BUFFER, buffer_size, null, GL2ES3.GL_DYNAMIC_READ); gl.glReadPixels(x, y, w, h, format, type, 0); ByteBuffer bbuffer = gl.glMapBufferRange(GL2ES3.GL_PIXEL_PACK_BUFFER, 0, buffer_size, GL2ES3.GL_MAP_READ_BIT); // ByteBuffer bbuffer = gl.glMapBuffer(GL2ES3.GL_PIXEL_PACK_BUFFER, GL2ES3.GL_READ_ONLY); gl.glUnmapBuffer(GL2ES3.GL_PIXEL_PACK_BUFFER); gl.glBindBuffer(GL2ES3.GL_PIXEL_PACK_BUFFER, 0); context.endDraw(); DwGLError.debug(gl, "DwGLTexture.getData_GL2ES3"); return bbuffer; } public void getData_GL2GL3(int x, int y, int w, int h, Buffer buffer){ DwGLTexture3D tex = this; // create a new texture, the size of the given region, and copy the pixels to it if(!(x == 0 && y == 0 && w == this.w && h == this.h)){ tex = createTexSubImage(x,y,w,h); } // transfer pixels from the sub-region texture to the host application tex.getData_GL2GL3(buffer); } // copy texture-data to given float array public void getData_GL2GL3(Buffer buffer){ int data_len = w * h * num_channel; if(buffer.remaining() < data_len){ System.out.println("ERROR DwGLTexture.getData_GL2GL3: buffer to small: "+buffer.capacity() +" < "+data_len); return; } GL2GL3 gl23 = gl.getGL2GL3(); gl23.glBindTexture(target, HANDLE[0]); gl23.glGetTexImage(target, 0, format, type, buffer); gl23.glBindTexture(target, 0); DwGLError.debug(gl, "DwGLTexture.getData_GL2GL3"); } ////////////////////Texture Data Transfer - Integer ////////////////////////// public int[] getIntegerTextureData(int[] data){ return getIntegerTextureData(data, 0, 0, w, h, 0); } public int[] getIntegerTextureData(int[] data, int x, int y, int w, int h){ return getIntegerTextureData(data, x, y, w, h, 0); } public int[] getIntegerTextureData(int[] data, int x, int y, int w, int h, int data_off){ int data_len = w * h * num_channel; data = realloc(data, data_off + data_len); if(GPU_DATA_READ == 0){ getData_GL2GL3(x, y, w, h, IntBuffer.wrap(data).position(data_off)); } else if(GPU_DATA_READ == 1){ getData_GL2ES3(x, y, w, h).asIntBuffer().get(data, data_off, data_len); } return data; } //////////////////// Texture Data Transfer - Float /////////////////////////// public float[] getFloatTextureData(float[] data){ return getFloatTextureData(data, 0, 0, w, h, 0); } public float[] getFloatTextureData(float[] data, int x, int y, int w, int h){ return getFloatTextureData(data, x, y, w, h, 0); } public float[] getFloatTextureData(float[] data, int x, int y, int w, int h, int data_off){ int data_len = w * h * num_channel; data = realloc(data, data_off + data_len); if(GPU_DATA_READ == 0){ getData_GL2GL3(x, y, w, h, FloatBuffer.wrap(data).position(data_off)); } else if(GPU_DATA_READ == 1){ getData_GL2ES3(x, y, w, h).asFloatBuffer().get(data, data_off, data_len); } return data; } //////////////////// Texture Data Transfer - Byte /////////////////////////// /** * * byte[] px_byte = Fluid.getByteTextureData(Fluid.tex_obstacleC.src, null); * PGraphics2D pg_tmp = (PGraphics2D) createGraphics(Fluid.fluid_w, Fluid.fluid_h, P2D); * pg_tmp.loadPixels(); * for(int i = 0; i < pg_tmp.pixels.length; i++){ * int O = (int)(px_byte[i]); * pg_tmp.pixels[i] = O << 24 | O << 16 | O << 8 | O; * } * pg_tmp.updatePixels(); * * * @param tex_min * @param data * @return */ public byte[] getByteTextureData(byte[] data){ return getByteTextureData(data, 0, 0, w, h, 0); } public byte[] getByteTextureData(byte[] data, int x, int y, int w, int h){ return getByteTextureData(data, x, y, w, h, 0); } public byte[] getByteTextureData(byte[] data, int x, int y, int w, int h, int data_off){ int data_len = w * h * num_channel; data = realloc(data, data_off + data_len); if(GPU_DATA_READ == 0){ getData_GL2GL3(x, y, w, h, ByteBuffer.wrap(data).position(data_off)); } else if(GPU_DATA_READ == 1){ getData_GL2ES3(x, y, w, h).get(data, data_off, data_len); } return data; } static private final float[] realloc(float[] data, int size){ if(data == null || data.length < size){ float[] data_new = new float[size]; if(data != null){ System.arraycopy(data, 0, data_new, 0, data.length); } data = data_new; } return data; } static private final int[] realloc(int[] data, int size){ if(data == null || data.length < size){ int[] data_new = new int[size]; if(data != null){ System.arraycopy(data, 0, data_new, 0, data.length); } data = data_new; } return data; } static private final byte[] realloc(byte[] data, int size){ if(data == null || data.length < size){ byte[] data_new = new byte[size]; if(data != null){ System.arraycopy(data, 0, data_new, 0, data.length); } data = data_new; } return data; } // not tested // public boolean setData(Buffer data, int offset_x, int offset_y, int size_x, int size_y){ // if( offset_x + size_x > this.w ) return false; // if( offset_y + size_y > this.h ) return false; // // gl.glBindTexture (target, HANDLE[0]); // gl.glTexSubImage2D(target, 0, offset_x, offset_y, size_x, size_y, format, type, data); // gl.glBindTexture (target, 0); // // return true; // } // // public boolean setData(Buffer data){ // return setData(data, 0, 0, w, h); // } public void clear(float v){ clear(v,v,v,v); } DwGLTexture3D[] layers_tex = new DwGLTexture3D[1]; int[] layers_idx = new int[1]; public void clear(float r, float g, float b, float a){ layers_tex[0] = this; for(int i = 0; i < d; i++){ layers_idx[0] = i; context.framebuffer.clearTexture(r,g,b,a, layers_tex, layers_idx); } } // public void beginDraw(){ // framebuffer.bind(this); // gl.glViewport(0, 0, w, h); // // // default settings // gl.glColorMask(true, true, true, true); // gl.glDepthMask(false); // gl.glDisable(GL.GL_DEPTH_TEST); // gl.glDisable(GL.GL_STENCIL_TEST); // gl.glDisable(GL.GL_BLEND); // // gl.glClearColor(0, 0, 0, 0); // // gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_STENCIL_BUFFER_BIT); // } // public void endDraw(){ // framebuffer.unbind(); // } static public class TexturePingPong{ public DwGLTexture3D src = new DwGLTexture3D(); public DwGLTexture3D dst = new DwGLTexture3D(); public TexturePingPong(){ } public boolean resize(DwPixelFlow context, int internalFormat, int w, int h, int d, int format, int type, int filter, int wrap, int num_channel, int byte_per_channel){ boolean resized = false; resized |= src.resize(context, internalFormat, w, h, d, format, type, filter, wrap, num_channel, byte_per_channel); resized |= dst.resize(context, internalFormat, w, h, d, format, type, filter, wrap, num_channel, byte_per_channel); return resized; } public boolean resize(DwPixelFlow context, int internalFormat, int w, int h, int d, int format, int type, int filter, int num_channel, int byte_per_channel){ boolean resized = false; resized |= src.resize(context, internalFormat, w, h, d, format, type, filter, num_channel, byte_per_channel); resized |= dst.resize(context, internalFormat, w, h, d, format, type, filter, num_channel, byte_per_channel); return resized; } // public void resize(DwPixelFlow context, int internalFormat, int w, int h, int d, int format, int type, int filter, int num_channel, int byte_per_channel){ // src.resize(context, internalFormat, w, h, d, format, type, filter, num_channel, byte_per_channel); // dst.resize(context, internalFormat, w, h, d, format, type, filter, num_channel, byte_per_channel); // } public void release(){ if(src != null){ src.release(); } if(dst != null){ dst.release(); } } public void swap(){ DwGLTexture3D tmp; tmp = src; src = dst; dst = tmp; } public void clear(float v){ src.clear(v); dst.clear(v); } public void clear(float r, float g, float b, float a){ src.clear(r,g,b,a); dst.clear(r,g,b,a); } } }
922fb9dca8d59ca65316aa3a071ec4e075ac07cb
1,418
java
Java
05_Java_EE_Servlet_Api4..0/exercises/src/main/java/softuni/domain/repositories/ProductRepository.java
IvoIvanov77/JavaWebDevelopmentBasics
0a7aa468bedd72d4d8ebd640f47de9f65bbe3318
[ "MIT" ]
null
null
null
05_Java_EE_Servlet_Api4..0/exercises/src/main/java/softuni/domain/repositories/ProductRepository.java
IvoIvanov77/JavaWebDevelopmentBasics
0a7aa468bedd72d4d8ebd640f47de9f65bbe3318
[ "MIT" ]
null
null
null
05_Java_EE_Servlet_Api4..0/exercises/src/main/java/softuni/domain/repositories/ProductRepository.java
IvoIvanov77/JavaWebDevelopmentBasics
0a7aa468bedd72d4d8ebd640f47de9f65bbe3318
[ "MIT" ]
null
null
null
27.269231
88
0.589563
995,231
package softuni.domain.repositories; import softuni.domain.model.Product; import javax.persistence.NoResultException; import java.util.List; public class ProductRepository extends BaseRepository { public ProductRepository() { } public Product findByName(String name) { Product result = (Product) executeAction(repositoryActionResult -> { Product productFromDb = null; try{ productFromDb = (Product) this.entityManager.createQuery( "select p from Product p where p.name = :name ") .setParameter("name", name) .getSingleResult(); }catch (NoResultException e){ ; } repositoryActionResult.setResult(productFromDb); }).getResult(); return result; } @SuppressWarnings("unchecked") public List<Product> findAll() { List<Product> result = (List<Product>) executeAction(repositoryActionResult -> { repositoryActionResult.setResult( this.entityManager.createQuery( "select p from Product p") .getResultList()); }).getResult(); return result; } public void saveProduct(Product product) { executeAction(repositoryActionResult -> this.entityManager.persist(product)); } }
922fbb6c3321437dc1a3ebf5aba010b66359958b
6,218
java
Java
src/main/java/me/st28/flexseries/flexcore/list/ListManager.java
FlexSeries/FlexCore
9ea3b8ecce44ce03c7d6e2b9085b0ec66dbfada3
[ "MIT" ]
null
null
null
src/main/java/me/st28/flexseries/flexcore/list/ListManager.java
FlexSeries/FlexCore
9ea3b8ecce44ce03c7d6e2b9085b0ec66dbfada3
[ "MIT" ]
1
2015-07-10T02:00:34.000Z
2015-07-10T02:00:34.000Z
src/main/java/me/st28/flexseries/flexcore/list/ListManager.java
FlexSeries/FlexCore
9ea3b8ecce44ce03c7d6e2b9085b0ec66dbfada3
[ "MIT" ]
null
null
null
39.858974
128
0.660663
995,232
/** * FlexCore - Licensed under the MIT License (MIT) * * Copyright (c) Stealth2800 <http://stealthyone.com/> * Copyright (c) contributors <https://github.com/FlexSeries> * * 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 me.st28.flexseries.flexcore.list; import me.st28.flexseries.flexcore.FlexCore; import me.st28.flexseries.flexcore.logging.LogHelper; import me.st28.flexseries.flexcore.plugin.module.FlexModule; import me.st28.flexseries.flexcore.plugin.FlexPlugin; import org.apache.commons.lang.Validate; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.file.FileConfiguration; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; /** * Helper for commands that have list-based output with a header.<br /> * Allows multiple plugins to have consistently styled lists. * <br /> * <b>Example:</b><br /> * ===== Topic (pg.1/5) =====<br /> * 1) Element 1<br /> * 2) Element 2 */ public final class ListManager extends FlexModule<FlexCore> { static ListManager getInstance() { return FlexPlugin.getRegisteredModule(ListManager.class); } int pageItems; int lineLength = 54; String msgNextPage; String msgNoElements; private final String UNKNOWN_ELEMENT_FORMAT = "&cUnknown element format: &6{NAME}&c."; private Map<String, String> formatsElement = new HashMap<>(); private Map<String, ListHeader> formatsHeader = new HashMap<>(); public ListManager(FlexCore plugin) { super(plugin, "lists", "Handles the creation and formatting of lists that are displayed as output for commands", false); } @Override protected void handleReload() { FileConfiguration config = getConfig(); pageItems = config.getInt("general config.page items", 8); lineLength = config.getInt("general config.line length", 54); msgNextPage = config.getString("messages.next page", "&c&oType &6&o/{COMMAND} {NEXTPAGE} &c&oto view the next page."); msgNoElements = config.getString("messages.no elements", "&c&oNothing here."); formatsElement.clear(); ConfigurationSection elementSec = config.getConfigurationSection("formats.elements"); if (elementSec != null) { for (String key : elementSec.getKeys(false)) { if (formatsElement.containsKey(key.toLowerCase())) { LogHelper.warning(this, "A element format named '" + key.toLowerCase() + "' is already loaded."); continue; } formatsElement.put(key.toLowerCase(), elementSec.getString(key)); } } formatsHeader.clear(); ConfigurationSection headerSec = config.getConfigurationSection("formats.headers"); if (headerSec != null) { for (String key : headerSec.getKeys(false)) { if (formatsHeader.containsKey(key.toLowerCase())) { LogHelper.warning(this, "A header format named '" + key.toLowerCase() + "' is already loaded."); continue; } ListHeader header; try { header = new ListHeader(headerSec.getConfigurationSection(key)); } catch (Exception ex) { LogHelper.warning(this, "An exception occurred while loading header '" + key.toLowerCase() + "'"); ex.printStackTrace(); continue; } formatsHeader.put(key.toLowerCase(), header); } } } @Override protected void handleSave(boolean async) { ConfigurationSection config = getConfig().getConfigurationSection("formats.elements"); for (Entry<String, String> entry : formatsElement.entrySet()) { config.set(entry.getKey(), entry.getValue()); } } /** * @return a header format matching a given name. */ public ListHeader getHeaderFormat(String name) { Validate.notNull(name, "Name cannot be null."); name = name.toLowerCase(); return !formatsHeader.containsKey(name) ? new ListHeader(name) : formatsHeader.get(name); } /** * @return an element format matching a given name. */ public String getElementFormat(String name) { Validate.notNull(name, "Name cannot be null."); name = name.toLowerCase(); return !formatsElement.containsKey(name) ? UNKNOWN_ELEMENT_FORMAT.replace("{NAME}", name) : formatsElement.get(name); } /** * Creates an element format if it doesn't already exist in the configuration file. * * @param name The name of the format. * @param defaultFormat The default format. This will be saved to the configuration file if nothing is already set. */ public void createElementFormat(String name, String defaultFormat) { Validate.notNull(name, "Name cannot be null."); Validate.notNull(defaultFormat, "Default format cannot be null."); name = name.toLowerCase(); if (!formatsElement.containsKey(name)) { formatsElement.put(name, defaultFormat); } } }
922fbd3db39464e70d486f1abd56bb82eea0bc66
15,664
java
Java
src/main/java/org/openjax/cdm/lexer/Lexer.java
openjax/classic-cdm
e0d03914d4ea62b9236d82f94d42757a5f470462
[ "MIT" ]
1
2019-06-19T04:55:11.000Z
2019-06-19T04:55:11.000Z
src/main/java/org/openjax/cdm/lexer/Lexer.java
openjax/classic-cdm
e0d03914d4ea62b9236d82f94d42757a5f470462
[ "MIT" ]
1
2020-12-19T03:55:58.000Z
2021-06-29T04:55:55.000Z
src/main/java/org/openjax/cdm/lexer/Lexer.java
openjax/cdm
e0d03914d4ea62b9236d82f94d42757a5f470462
[ "MIT" ]
null
null
null
30.65362
536
0.485572
995,233
/* Copyright (c) 2014 OpenJAX * * 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. * * You should have received a copy of The MIT License (MIT) along with this * program. If not, see <http://opensource.org/licenses/MIT/>. */ package org.openjax.cdm.lexer; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import org.libj.util.StreamSearcher; import org.openjax.cdm.Audit; public final class Lexer { private static final StreamSearcher.Char eol = new StreamSearcher.Char(new char[] {'\r'}, new char[] {'\n'}); private static final StreamSearcher.Char closeComment = new StreamSearcher.Char(new char[] {'*', '/'}); private static final StreamSearcher.Char singleQuote = new StreamSearcher.Char(new char[] {'\''}); private static final StreamSearcher.Char doubleQuote = new StreamSearcher.Char(new char[] {'"'}); private Lexer() { } public interface Token { interface Listener { void onStartDocument(); boolean onToken(Token token, int start, int end); void onEndDocument(); } String name(); int ordinal(); } public enum Delimiter implements Token { // NOTE: The declaration list of Delimiter(s) must be in sorted alphabetical order! EXCLAMATION("!"), PERCENT("%"), AMPERSAND("&"), AND("&&"), PAREN_OPEN("("), PAREN_CLOSE(")"), ASTERISK("*"), PLUS("+"), PLUS_PLUS("++"), PLUS_EQ("+="), COMMA(","), MINUS("-"), MINUS_MINUS("--"), MINUS_EQ("-="), DOT("."), SLASH("/"), COLON(":"), SEMI_COLON(";"), LT("<"), LTLT("<<"), LTLTLT("<<<"), LTE("<="), EQ("="), EQEQ("=="), GT(">"), GTE(">="), GTGT(">>"), GTGTGT(">>>"), QUESTION("?"), AT("@"), BRACKET_OPEN("["), ARRAY("[]"), BRACKET_CLOSE("]"), CARAT("^"), BRACE_OPEN("{"), PIPE("|"), OR("||"), BRACE_CLOSE("}"), TILDE("~"); public final String ch; public final int[][] children; Delimiter(final String ch) { this.ch = ch; this.children = new int[ch.length() + 1][]; } @Override public String toString() { return ch; } } public enum Span implements Token { WHITESPACE("\t", "\n", "\r", " "), LINE_COMMENT("//"), BLOCK_COMMENT("/*"), NUMBER, CHARACTER, STRING, WORD; public final String[] ch; Span(final String ... ch) { this.ch = ch; } } /* * So far, best performance is with FileInputStream, reading chars. */ public static Audit tokenize(final File file, final Token.Listener listener) throws IOException { try (final InputStreamReader in = new FileReader(file)) { // FIXME: What if the length of the file is greater than Integer.MAX_VALUE?! return tokenize(in, (int)file.length(), listener); } } public static Audit tokenize(final Reader in, final int length, final Token.Listener listener) throws IOException { final char[] chars = new char[length]; final Audit audit = new Audit(chars); int i = 0; char ch; Token token = null; int len = 0; if (listener != null) listener.onStartDocument(); for (int b; i < chars.length;) { if ((b = in.read()) == -1) throw new IOException("Unexpected end of stream"); ch = chars[i++] = (char)b; if ('0' <= ch && ch <= '9' && token != Span.WORD) { if (token != Span.NUMBER) { audit.push(token, i - len - 1, len); if (listener != null && !listener.onToken(token, i - len - 1, len)) return audit; len = 1; token = Span.NUMBER; } else { ++len; } } else if (('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') || (len != 0 && '0' <= ch && ch <= '9') || ch == '$' || ch == '_') { // TODO: Handle 0x0000, 0b0000, 1.234e2, and 999_99__9999L if (token == Span.NUMBER && (ch == 'd' || ch == 'D' || ch == 'f' || ch == 'F' || ch == 'l' || ch == 'L')) { ++len; } else if (token == Span.WORD) { ++len; } else { if (token == Span.WHITESPACE || !(token instanceof Keyword)) { audit.push(token, i - len - 1, len); if (listener != null && !listener.onToken(token, i - len - 1, len)) return audit; len = 1; token = Keyword.findNext(null, 0, ch); if (token == null) token = Span.WORD; } else { token = Keyword.findNext(((Keyword)token), len, ch); if (token == null) token = Span.WORD; ++len; } } } else if (ch == '\n' || ch == '\r' || ch == ' ' || ch == '\t') { if (token == Span.WHITESPACE) { ++len; } else { audit.push(token, i - len - 1, len); if (listener != null && !listener.onToken(token, i - len - 1, len)) return audit; len = 1; token = Span.WHITESPACE; } } else if (ch == '.') { if (token == null || token == Delimiter.BRACKET_OPEN || token == Delimiter.BRACE_OPEN) { len = 1; token = Span.NUMBER; } else if (token == Span.NUMBER) { ++len; } else { audit.push(token, i - len - 1, len); if (listener != null && !listener.onToken(token, i - len - 1, len)) return audit; len = 1; token = Delimiter.DOT; } } else if (ch == '&') { if (token == Delimiter.AMPERSAND) { // && len = 2; token = Delimiter.AND; } else { audit.push(token, i - len - 1, len); if (listener != null && !listener.onToken(token, i - len - 1, len)) return audit; len = 1; token = Delimiter.AMPERSAND; } } else if (ch == '|') { if (token == Delimiter.PIPE) { // || len = 2; token = Delimiter.OR; } else { audit.push(token, i - len - 1, len); if (listener != null && !listener.onToken(token, i - len - 1, len)) return audit; len = 1; token = Delimiter.PIPE; } } else if (ch == '=') { if (token == Delimiter.LT) { // <= len = 2; token = Delimiter.LTE; } else if (token == Delimiter.GT) { // >= len = 2; token = Delimiter.GTE; } else if (token == Delimiter.EQ) { // == len = 2; token = Delimiter.EQEQ; } else if (token == Delimiter.MINUS) { // -= len = 2; token = Delimiter.MINUS_EQ; } else if (token == Delimiter.PLUS) { // += len = 2; token = Delimiter.PLUS_EQ; } else { audit.push(token, i - len - 1, len); if (listener != null && !listener.onToken(token, i - len - 1, len)) return audit; len = 1; token = Delimiter.EQ; } } else if (ch == '<') { if (token == Delimiter.LT) { // << len = 2; token = Delimiter.LTLT; } else if (token == Delimiter.LTLT) { // <<< len = 3; token = Delimiter.LTLTLT; } else { audit.push(token, i - len - 1, len); if (listener != null && !listener.onToken(token, i - len - 1, len)) return audit; len = 1; token = Delimiter.LT; } } else if (ch == '>') { if (token == Delimiter.GT) { // >> len = 2; token = Delimiter.GTGT; } else if (token == Delimiter.GTGT) { // >>> len = 3; token = Delimiter.GTGTGT; } else { audit.push(token, i - len - 1, len); if (listener != null && !listener.onToken(token, i - len - 1, len)) return audit; len = 1; token = Delimiter.GT; } } else if (ch == '-') { if (token == Delimiter.MINUS) { // -- len = 2; token = Delimiter.MINUS_MINUS; } else { audit.push(token, i - len - 1, len); if (listener != null && !listener.onToken(token, i - len - 1, len)) return audit; len = 1; token = Delimiter.MINUS; } } else if (ch == '+') { if (token == Delimiter.PLUS) { // ++ len = 2; token = Delimiter.PLUS_PLUS; } else { audit.push(token, i - len - 1, len); if (listener != null && !listener.onToken(token, i - len - 1, len)) return audit; len = 1; token = Delimiter.PLUS; } } else if (ch == '~') { audit.push(token, i - len - 1, len); if (listener != null && !listener.onToken(token, i - len - 1, len)) return audit; len = 1; token = Delimiter.TILDE; } else if (ch == '!') { audit.push(token, i - len - 1, len); if (listener != null && !listener.onToken(token, i - len - 1, len)) return audit; len = 1; token = Delimiter.EXCLAMATION; } else if (ch == '@') { audit.push(token, i - len - 1, len); if (listener != null && !listener.onToken(token, i - len - 1, len)) return audit; len = 1; token = Delimiter.AT; } else if (ch == '^') { audit.push(token, i - len - 1, len); if (listener != null && !listener.onToken(token, i - len - 1, len)) return audit; len = 1; token = Delimiter.CARAT; } else if (ch == '%') { audit.push(token, i - len - 1, len); if (listener != null && !listener.onToken(token, i - len - 1, len)) return audit; len = 1; token = Delimiter.PERCENT; } else if (ch == ',') { audit.push(token, i - len - 1, len); if (listener != null && !listener.onToken(token, i - len - 1, len)) return audit; len = 1; token = Delimiter.COMMA; } else if (ch == ';') { audit.push(token, i - len - 1, len); if (listener != null && !listener.onToken(token, i - len - 1, len)) return audit; len = 1; token = Delimiter.SEMI_COLON; } else if (ch == ':') { audit.push(token, i - len - 1, len); if (listener != null && !listener.onToken(token, i - len - 1, len)) return audit; len = 1; token = Delimiter.COLON; } else if (ch == '?') { audit.push(token, i - len - 1, len); if (listener != null && !listener.onToken(token, i - len - 1, len)) return audit; len = 1; token = Delimiter.QUESTION; } else if (ch == '(') { audit.push(token, i - len - 1, len); if (listener != null && !listener.onToken(token, i - len - 1, len)) return audit; len = 1; token = Delimiter.PAREN_OPEN; } else if (ch == ')') { audit.push(token, i - len - 1, len); if (listener != null && !listener.onToken(token, i - len - 1, len)) return audit; len = 1; token = Delimiter.PAREN_CLOSE; } else if (ch == '{') { audit.push(token, i - len - 1, len); if (listener != null && !listener.onToken(token, i - len - 1, len)) return audit; len = 1; token = Delimiter.BRACE_OPEN; } else if (ch == '}') { audit.push(token, i - len - 1, len); if (listener != null && !listener.onToken(token, i - len - 1, len)) return audit; len = 1; token = Delimiter.BRACE_CLOSE; } else if (ch == '[') { audit.push(token, i - len - 1, len); if (listener != null && !listener.onToken(token, i - len - 1, len)) return audit; len = 1; token = Delimiter.BRACKET_OPEN; } else if (ch == ']') { if (token == Delimiter.BRACKET_OPEN) { // [] len = 2; token = Delimiter.ARRAY; } else { audit.push(token, i - len - 1, len); if (listener != null && !listener.onToken(token, i - len - 1, len)) return audit; len = 1; token = Delimiter.BRACKET_CLOSE; } } else if (ch == '/') { if (token == Delimiter.SLASH) { // Start of line comment // find end of line // index from // to end of comment, not including newline // this is the only situation where the token is added at time of detection of end of block, cause the eol char is not supposed to be a part of the // token len = eol.search(in, chars, i); audit.push(Span.LINE_COMMENT, i - 2, len + 2); if (listener != null && !listener.onToken(token, i - len - 1, len)) return audit; i += len; len = 0; token = null; } else { audit.push(token, i - len - 1, len); if (listener != null && !listener.onToken(token, i - len - 1, len)) return audit; len = 1; token = Delimiter.SLASH; } } else if (ch == '*') { if (token == Delimiter.SLASH) { // Start of block comment // find end of block comment // index from /* to */ including any & all characters between i += len = closeComment.search(in, chars, i); len += 2; token = Span.BLOCK_COMMENT; } else { audit.push(token, i - len - 1, len); if (listener != null && !listener.onToken(token, i - len - 1, len)) return audit; len = 1; token = Delimiter.ASTERISK; } } else if (ch == '\'') { audit.push(token, i - len - 1, len); if (listener != null && !listener.onToken(token, i - len - 1, len)) return audit; len = 1; int t; i += t = singleQuote.search(in, chars, i); len += t; // take care of '\'' situation // TODO: Handle '\u0000' and '\0' if (chars[i - 2] == '\\' && len == 3) { i += t = singleQuote.search(in, chars, i); len += t; } token = Span.CHARACTER; } else if (ch == '"') { audit.push(token, i - len - 1, len); if (listener != null && !listener.onToken(token, i - len - 1, len)) return audit; len = 1; int l; i += l = doubleQuote.search(in, chars, i); len += l; // take care of \" situation if (chars[i - 2] == '\\') { i += l = doubleQuote.search(in, chars, i); len += l; } token = Span.STRING; } else { System.err.print(ch); } } // add the last token, because its final delimiter can be the EOF audit.push(token, i - len, len); if (listener != null) listener.onEndDocument(); return audit; } }
922fbe4c4a4ab541ed1358c74ddd4750543cb398
7,487
java
Java
core/camel-core-model/src/main/java/org/apache/camel/model/FaultToleranceConfigurationCommon.java
narsinallamilli/camel-1
599a3a0e2ab610e71dafe326965d697b8061db06
[ "Apache-2.0" ]
4,262
2015-01-01T15:28:37.000Z
2022-03-31T04:46:41.000Z
core/camel-core-model/src/main/java/org/apache/camel/model/FaultToleranceConfigurationCommon.java
narsinallamilli/camel-1
599a3a0e2ab610e71dafe326965d697b8061db06
[ "Apache-2.0" ]
3,408
2015-01-03T02:11:17.000Z
2022-03-31T20:07:56.000Z
core/camel-core-model/src/main/java/org/apache/camel/model/FaultToleranceConfigurationCommon.java
dhlparcel/camel
3aea09efaf1db4d424b52a813312bee86c1225e9
[ "Apache-2.0" ]
5,505
2015-01-02T14:58:12.000Z
2022-03-30T19:23:41.000Z
34.344037
118
0.702418
995,234
/* * 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.camel.model; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import org.apache.camel.spi.Metadata; @XmlAccessorType(XmlAccessType.FIELD) public class FaultToleranceConfigurationCommon extends IdentifiedType { @XmlAttribute @Metadata(label = "circuitbreaker") private String circuitBreakerRef; @XmlAttribute @Metadata(label = "circuitbreaker", defaultValue = "5000", javaType = "java.time.Duration") private String delay; @XmlAttribute @Metadata(label = "circuitbreaker", defaultValue = "1", javaType = "java.lang.Integer") private String successThreshold; @XmlAttribute @Metadata(label = "circuitbreaker", defaultValue = "20", javaType = "java.lang.Integer") private String requestVolumeThreshold; @XmlAttribute @Metadata(label = "circuitbreaker", defaultValue = "50", javaType = "java.lang.Integer") private String failureRatio; @XmlAttribute @Metadata(label = "timeout", defaultValue = "false", javaType = "java.lang.Boolean") private String timeoutEnabled; @XmlAttribute @Metadata(label = "timeout", defaultValue = "1000", javaType = "java.time.Duration") private String timeoutDuration; @XmlAttribute @Metadata(label = "timeout", defaultValue = "10", javaType = "java.lang.Integer") private String timeoutPoolSize; @XmlAttribute @Metadata(label = "timeout") private String timeoutScheduledExecutorServiceRef; @XmlAttribute @Metadata(label = "bulkhead", defaultValue = "false", javaType = "java.lang.Boolean") private String bulkheadEnabled; @XmlAttribute @Metadata(label = "bulkhead", defaultValue = "10", javaType = "java.lang.Integer") private String bulkheadMaxConcurrentCalls; @XmlAttribute @Metadata(label = "bulkhead", defaultValue = "10", javaType = "java.lang.Integer") private String bulkheadWaitingTaskQueue; @XmlAttribute @Metadata(label = "bulkhead") private String bulkheadExecutorServiceRef; // Getter/Setter // ------------------------------------------------------------------------- public String getCircuitBreakerRef() { return circuitBreakerRef; } /** * Refers to an existing io.smallrye.faulttolerance.core.circuit.breaker.CircuitBreaker instance to lookup and use * from the registry. When using this, then any other circuit breaker options are not in use. */ public void setCircuitBreakerRef(String circuitBreakerRef) { this.circuitBreakerRef = circuitBreakerRef; } public String getDelay() { return delay; } /** * Control how long the circuit breaker stays open. The default is 5 seconds. */ public void setDelay(String delay) { this.delay = delay; } public String getSuccessThreshold() { return successThreshold; } /** * Controls the number of trial calls which are allowed when the circuit breaker is half-open */ public void setSuccessThreshold(String successThreshold) { this.successThreshold = successThreshold; } public String getRequestVolumeThreshold() { return requestVolumeThreshold; } /** * Controls the size of the rolling window used when the circuit breaker is closed */ public void setRequestVolumeThreshold(String requestVolumeThreshold) { this.requestVolumeThreshold = requestVolumeThreshold; } public String getFailureRatio() { return failureRatio; } /** * Configures the failure rate threshold in percentage. If the failure rate is equal or greater than the threshold * the CircuitBreaker transitions to open and starts short-circuiting calls. * <p> * The threshold must be greater than 0 and not greater than 100. Default value is 50 percentage. */ public void setFailureRatio(String failureRatio) { this.failureRatio = failureRatio; } public String getTimeoutEnabled() { return timeoutEnabled; } /** * Whether timeout is enabled or not on the circuit breaker. Default is false. */ public void setTimeoutEnabled(String timeoutEnabled) { this.timeoutEnabled = timeoutEnabled; } public String getTimeoutDuration() { return timeoutDuration; } /** * Configures the thread execution timeout. Default value is 1 second. */ public void setTimeoutDuration(String timeoutDuration) { this.timeoutDuration = timeoutDuration; } public String getTimeoutPoolSize() { return timeoutPoolSize; } /** * Configures the pool size of the thread pool when timeout is enabled. Default value is 10. */ public void setTimeoutPoolSize(String timeoutPoolSize) { this.timeoutPoolSize = timeoutPoolSize; } public String getTimeoutScheduledExecutorServiceRef() { return timeoutScheduledExecutorServiceRef; } /** * References to a custom thread pool to use when timeout is enabled */ public void setTimeoutScheduledExecutorServiceRef(String timeoutScheduledExecutorServiceRef) { this.timeoutScheduledExecutorServiceRef = timeoutScheduledExecutorServiceRef; } public String getBulkheadEnabled() { return bulkheadEnabled; } /** * Whether bulkhead is enabled or not on the circuit breaker. Default is false. */ public void setBulkheadEnabled(String bulkheadEnabled) { this.bulkheadEnabled = bulkheadEnabled; } public String getBulkheadMaxConcurrentCalls() { return bulkheadMaxConcurrentCalls; } /** * Configures the max amount of concurrent calls the bulkhead will support. */ public void setBulkheadMaxConcurrentCalls(String bulkheadMaxConcurrentCalls) { this.bulkheadMaxConcurrentCalls = bulkheadMaxConcurrentCalls; } public String getBulkheadWaitingTaskQueue() { return bulkheadWaitingTaskQueue; } /** * Configures the task queue size for holding waiting tasks to be processed by the bulkhead. */ public void setBulkheadWaitingTaskQueue(String bulkheadWaitingTaskQueue) { this.bulkheadWaitingTaskQueue = bulkheadWaitingTaskQueue; } public String getBulkheadExecutorServiceRef() { return bulkheadExecutorServiceRef; } /** * References to a custom thread pool to use when bulkhead is enabled. */ public void setBulkheadExecutorServiceRef(String bulkheadExecutorServiceRef) { this.bulkheadExecutorServiceRef = bulkheadExecutorServiceRef; } }
922fbe827f617788f5a2e09a2aba64cb8e1c9866
2,271
java
Java
gulimall-order/src/main/java/com/atguigu/gulimall/order/controller/RefundInfoController.java
IceS2388/gulimall
b8587580e2f64415b686ebf96223b4171d0e4136
[ "Apache-2.0" ]
null
null
null
gulimall-order/src/main/java/com/atguigu/gulimall/order/controller/RefundInfoController.java
IceS2388/gulimall
b8587580e2f64415b686ebf96223b4171d0e4136
[ "Apache-2.0" ]
2
2021-04-22T17:11:41.000Z
2021-09-20T21:01:08.000Z
gulimall-order/src/main/java/com/atguigu/gulimall/order/controller/RefundInfoController.java
IceS2388/gulimall
b8587580e2f64415b686ebf96223b4171d0e4136
[ "Apache-2.0" ]
null
null
null
24.978022
63
0.699956
995,235
package com.atguigu.gulimall.order.controller; import java.util.Arrays; import java.util.Map; //import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.atguigu.gulimall.order.entity.RefundInfoEntity; import com.atguigu.gulimall.order.service.RefundInfoService; import com.atguigu.common.utils.PageUtils; import com.atguigu.common.utils.R; /** * 退款信息 * * @author ices * @email efpyi@example.com * @date 2020-07-27 23:22:52 */ @RestController @RequestMapping("order/refundinfo") public class RefundInfoController { @Autowired private RefundInfoService refundInfoService; /** * 列表 */ @RequestMapping("/list") //@RequiresPermissions("order:refundinfo:list") public R list(@RequestParam Map<String, Object> params){ PageUtils page = refundInfoService.queryPage(params); return R.ok().put("page", page); } /** * 信息 */ @RequestMapping("/info/{id}") //@RequiresPermissions("order:refundinfo:info") public R info(@PathVariable("id") Long id){ RefundInfoEntity refundInfo = refundInfoService.getById(id); return R.ok().put("refundInfo", refundInfo); } /** * 保存 */ @RequestMapping("/save") //@RequiresPermissions("order:refundinfo:save") public R save(@RequestBody RefundInfoEntity refundInfo){ refundInfoService.save(refundInfo); return R.ok(); } /** * 修改 */ @RequestMapping("/update") //@RequiresPermissions("order:refundinfo:update") public R update(@RequestBody RefundInfoEntity refundInfo){ refundInfoService.updateById(refundInfo); return R.ok(); } /** * 删除 */ @RequestMapping("/delete") //@RequiresPermissions("order:refundinfo:delete") public R delete(@RequestBody Long[] ids){ refundInfoService.removeByIds(Arrays.asList(ids)); return R.ok(); } }
922fbeaaf642842c2e25cdeaa3a1114bb7de4ccd
613
java
Java
poj/src/main/java/org/poj/Main1316.java
mccxj/online-judge-code-example
e61c85b1af0613312e149986fb8bd64154d70d95
[ "Apache-2.0" ]
2
2018-04-26T09:36:21.000Z
2018-04-26T09:36:23.000Z
poj/src/main/java/org/poj/Main1316.java
mccxj/leetcode
e61c85b1af0613312e149986fb8bd64154d70d95
[ "Apache-2.0" ]
4
2017-01-09T02:12:29.000Z
2017-01-15T01:34:41.000Z
poj/src/main/java/org/poj/Main1316.java
mccxj/online-judge-code-example
e61c85b1af0613312e149986fb8bd64154d70d95
[ "Apache-2.0" ]
null
null
null
19.15625
47
0.417618
995,236
package org.poj; /** * Self Numbers(http://poj.org/problem?id=1316) * <p/> * <p/> * 数学题,简单题,使用计数数组进行两遍查询即可 */ public class Main1316 { public static void main(String args[]) { // 9999计算出来的是10035 int[] gen = new int[10036]; for (int i = 1; i < 10001; i++) { gen[d(i)]++; } for (int i = 1; i < 10001; i++) { if (gen[i] == 0) System.out.println(i); } } private static int d(int n) { int t = n; while (t != 0) { n += t % 10; t /= 10; } return n; } }
922fbeb7be339124bc976b09ece828e8468ac8f0
15,856
java
Java
app/src/main/java/ohi/andre/consolelauncher/commands/CommandTuils.java
ferranastals/console
dabd0347e0fe7c20f6d2abdd485865e77a09627e
[ "Apache-2.0" ]
null
null
null
app/src/main/java/ohi/andre/consolelauncher/commands/CommandTuils.java
ferranastals/console
dabd0347e0fe7c20f6d2abdd485865e77a09627e
[ "Apache-2.0" ]
null
null
null
app/src/main/java/ohi/andre/consolelauncher/commands/CommandTuils.java
ferranastals/console
dabd0347e0fe7c20f6d2abdd485865e77a09627e
[ "Apache-2.0" ]
null
null
null
34.848352
127
0.587033
995,237
package ohi.andre.consolelauncher.commands; import android.annotation.SuppressLint; import android.graphics.Color; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import ohi.andre.consolelauncher.commands.main.MainPack; import ohi.andre.consolelauncher.commands.main.Param; import ohi.andre.consolelauncher.commands.specific.ParamCommand; import ohi.andre.consolelauncher.managers.AppsManager; import ohi.andre.consolelauncher.managers.ContactManager; import ohi.andre.consolelauncher.managers.FileManager; import ohi.andre.consolelauncher.managers.FileManager.DirInfo; import ohi.andre.consolelauncher.managers.XMLPrefsManager; import ohi.andre.consolelauncher.managers.music.MusicManager2; import ohi.andre.consolelauncher.managers.notifications.NotificationManager; import ohi.andre.consolelauncher.tuils.SimpleMutableEntry; import ohi.andre.consolelauncher.tuils.Tuils; @SuppressLint("DefaultLocale") public class CommandTuils { private static FileManager.SpecificExtensionFileFilter extensionFileFilter = new FileManager.SpecificExtensionFileFilter(); private static FileManager.SpecificNameFileFilter nameFileFilter = new FileManager.SpecificNameFileFilter(); public static List<XMLPrefsManager.XMLPrefsSave> xmlPrefsEntrys; public static List<String> xmlPrefsFiles; // parse a command public static Command parse(String input, ExecutePack info, boolean suggestion) throws Exception { Command command = new Command(); String name = CommandTuils.findName(input); if (!Tuils.isAlpha(name)) return null; CommandAbstraction cmd = info.commandGroup.getCommandByName(name); if (cmd == null) { return null; } command.cmd = cmd; input = input.substring(name.length()); input = input.trim(); ArrayList<Object> args = new ArrayList<>(); int nArgs = 0; int[] types; try { if(cmd instanceof ParamCommand) { ArgInfo arg = param((MainPack) info, (ParamCommand) cmd, input); if(arg == null || !arg.found) { return command; } input = arg.residualString; Param p = (Param) arg.arg; types = p.args(); nArgs++; args.add(p); } else { types = cmd.argType(); } if (types != null) { for (int count = 0; count < types.length; count++) { if (input == null) break; input = input.trim(); if(input.length() == 0) { break; } ArgInfo arg = CommandTuils.getArg(info, input, types[count], suggestion); if(arg == null) { return null; } if (!arg.found) { command.indexNotFound = cmd instanceof ParamCommand ? count + 1 : count; args.add(input); command.mArgs = args.toArray(new Object[args.size()]); command.nArgs = nArgs; return command; } nArgs += arg.n; args.add(arg.arg); input = arg.residualString; } } } catch (Exception e) {} command.mArgs = args.toArray(new Object[args.size()]); command.nArgs = nArgs; return command; } // find command name private static String findName(String input) { int space = input.indexOf(Tuils.SPACE); if (space == -1) { return input; } else { return input.substring(0, space); } } // find args public static ArgInfo getArg(ExecutePack info, String input, int type, boolean suggestion) { if (type == CommandAbstraction.FILE && info instanceof MainPack) { MainPack pack = (MainPack) info; return file(input, pack.currentDirectory); } else if (type == CommandAbstraction.CONTACTNUMBER && info instanceof MainPack) { MainPack pack = (MainPack) info; return contactNumber(input, pack.contacts); } else if (type == CommandAbstraction.PLAIN_TEXT) { return plainText(input); } else if (type == CommandAbstraction.VISIBLE_PACKAGE && info instanceof MainPack) { MainPack pack = (MainPack) info; return activityName(input, pack.appsManager); } else if (type == CommandAbstraction.HIDDEN_PACKAGE && info instanceof MainPack) { MainPack pack = (MainPack) info; return hiddenPackage(input, pack.appsManager); } else if (type == CommandAbstraction.TEXTLIST) { return textList(input); } else if (type == CommandAbstraction.SONG && info instanceof MainPack) { MainPack pack = (MainPack) info; return song(input, pack.player); } else if (type == CommandAbstraction.FILE_LIST && info instanceof MainPack) { MainPack pack = (MainPack) info; if (suggestion) return file(input, pack.currentDirectory); else return fileList(input, pack.currentDirectory); } else if (type == CommandAbstraction.COMMAND) { return command(input, info.commandGroup); } else if(type == CommandAbstraction.BOOLEAN) { return bln(input); } else if(type == CommandAbstraction.COLOR) { return color(input); } else if(type == CommandAbstraction.CONFIG_ENTRY) { return configEntry(input); } else if(type == CommandAbstraction.CONFIG_FILE) { return configFile(input); } else if(type == CommandAbstraction.INT) { return integer(input); } else if(type == CommandAbstraction.DEFAULT_APP) { return defaultApp(input, ((MainPack) info).appsManager); } else if(type == CommandAbstraction.ALL_PACKAGES) { return allPackages(input, ((MainPack) info).appsManager); } return null; } // args extractors { private static ArgInfo color(String input) { input = input.trim(); int space = input.indexOf(Tuils.SPACE); String cl = input.substring(0, space == -1 ? input.length() : space); input = space == -1 ? Tuils.EMPTYSTRING : input.substring(space + 1); try { Color.parseColor(cl); return new ArgInfo(cl, input, true, 1); } catch (Exception e) { return new ArgInfo(null, input, false, 0); } } private static ArgInfo bln(String input) { String used, notUsed; if(input.contains(Tuils.SPACE)) { int space = input.indexOf(Tuils.SPACE); used = input.substring(0, space); notUsed = input.substring(space + 1); } else { used = input; notUsed = null; } Object result = used.toLowerCase().equals("true"); return new ArgInfo(result, notUsed, used.length() > 0, used.length() > 0 ? 1 : 0); } private static ArgInfo plainText(String input) { return new ArgInfo(input, "", true, 1); } private static ArgInfo textList(String input) { if (input == null) { return null; } String[] strings = input.split(Tuils.SPACE + "+"); List<String> arg = new ArrayList<>(Arrays.asList(strings)); return new ArgInfo(arg, null, true, arg.size()); } private static ArgInfo command(String string, CommandGroup active) { CommandAbstraction abstraction = null; try { abstraction = active.getCommandByName(string); } catch (Exception e) {} return new ArgInfo(abstraction, null, abstraction != null, 1); } @SuppressWarnings("unchecked") private static ArgInfo file(String input, File cd) { List<String> strings = (List<String>) CommandTuils.textList(input).arg; String toVerify = ""; for (int count = 0; count < strings.size(); count++) { toVerify = toVerify.concat(strings.get(count)); DirInfo info = CommandTuils.getFile(toVerify, cd); if (info.file != null && info.notFound == null) { while (count-- >= 0) strings.remove(0); String residual = Tuils.toPlanString(strings, Tuils.SPACE); return new ArgInfo(info.file, residual, true, 1); } toVerify = toVerify.concat(" "); } return new ArgInfo(null, input, false, 0); } @SuppressWarnings("unchecked") private static ArgInfo fileList(String input, File cd) { List<File> files = new ArrayList<>(); List<String> strings = (List<String>) CommandTuils.textList(input).arg; String toVerify = ""; for (int count = 0; count < strings.size(); count++) { String s = strings.get(count); toVerify = toVerify.concat(s); DirInfo dir = CommandTuils.getFile(toVerify, cd); if (dir.notFound == null) { files.add(dir.file); toVerify = ""; continue; } List<File> tempFiles = CommandTuils.attemptWildcard(dir); if (tempFiles != null) { files.addAll(tempFiles); toVerify = Tuils.EMPTYSTRING; continue; } toVerify = toVerify.concat(Tuils.SPACE); } if (toVerify.length() > 0) return new ArgInfo(null, null, false, 0); return new ArgInfo(files, null, files.size() > 0, files.size()); } private static DirInfo getFile(String path, File cd) { return FileManager.cd(cd, path); } private static List<File> attemptWildcard(DirInfo dir) { List<File> files; FileManager.WildcardInfo info = FileManager.wildcard(dir.notFound); if(info == null) { return null; } File cd = dir.file; if (!cd.isDirectory()) { return null; } if (info.allExtensions && info.allNames) { files = Arrays.asList(cd.listFiles()); } else if(info.allNames) { extensionFileFilter.setExtension(info.extension); files = Arrays.asList(cd.listFiles(extensionFileFilter)); } else if(info.allExtensions) { nameFileFilter.setName(info.name); files = Arrays.asList(cd.listFiles(nameFileFilter)); } else { return null; } if (files.size() > 0) { return files; } else { return null; } } private static ArgInfo param(MainPack pack, ParamCommand cmd, String input) { if(input == null || input.trim().length() == 0) return null; int indexOfFirstSpace = input.indexOf(Tuils.SPACE); if (indexOfFirstSpace == -1) { indexOfFirstSpace = input.length(); } String param = input.substring(0, indexOfFirstSpace).trim(); if(param.length() > 0 && !param.startsWith("-")) param = "-".concat(param); SimpleMutableEntry<Boolean, Param> sm = cmd.getParam(pack, param); Param p = sm.getValue(); boolean df = sm.getKey(); return new ArgInfo(p, df ? input : input.substring(indexOfFirstSpace), p != null, p != null ? 1 : 0); } private static ArgInfo activityName(String input, AppsManager apps) { AppsManager.LaunchInfo info = apps.findLaunchInfoWithLabel(input, AppsManager.SHOWN_APPS); return new ArgInfo(info, null, info != null, info != null ? 1 : 0); } private static ArgInfo hiddenPackage(String input, AppsManager apps) { AppsManager.LaunchInfo info = apps.findLaunchInfoWithLabel(input, AppsManager.HIDDEN_APPS); return new ArgInfo(info, null, info != null, info != null ? 1 : 0); } private static ArgInfo allPackages(String input, AppsManager apps) { AppsManager.LaunchInfo info = apps.findLaunchInfoWithLabel(input, AppsManager.SHOWN_APPS); if(info == null) { info = apps.findLaunchInfoWithLabel(input, AppsManager.HIDDEN_APPS); } return new ArgInfo(info, null, info != null, info != null ? 1 : 0); } private static ArgInfo defaultApp(String input, AppsManager apps) { AppsManager.LaunchInfo info = apps.findLaunchInfoWithLabel(input, AppsManager.SHOWN_APPS); if(info == null) { return new ArgInfo(input, null, true, 1); } else { return new ArgInfo(info, null, true, 1); } } private static ArgInfo contactNumber(String input, ContactManager contacts) { String number; if (Tuils.isNumber(input)) number = input; else number = contacts.findNumber(input); return new ArgInfo(number, null, number != null, 1); } private static ArgInfo song(String input, MusicManager2 music) { return new ArgInfo(input, null, true, 1); } private static ArgInfo configEntry(String input) { int index = input.indexOf(Tuils.SPACE); if(xmlPrefsEntrys == null) { xmlPrefsEntrys = new ArrayList<>(); for(XMLPrefsManager.XMLPrefsRoot element : XMLPrefsManager.XMLPrefsRoot.values()) Collections.addAll(element.copy); Collections.addAll(xmlPrefsEntrys, AppsManager.Options.values()); Collections.addAll(xmlPrefsEntrys, NotificationManager.Options.values()); } String candidate = index == -1 ? input : input.substring(0,index); for(XMLPrefsManager.XMLPrefsSave xs : xmlPrefsEntrys) { if(xs.is(candidate)) { return new ArgInfo(xs, index == -1 ? null : input.substring(index + 1,input.length()), true, 1); } } return new ArgInfo(null, input, false, 0); } private static ArgInfo configFile(String input) { if(xmlPrefsFiles == null) { xmlPrefsFiles = new ArrayList<>(); for(XMLPrefsManager.XMLPrefsRoot element : XMLPrefsManager.XMLPrefsRoot.values()) xmlPrefsFiles.add(element.path); xmlPrefsFiles.add(AppsManager.PATH); xmlPrefsFiles.add(NotificationManager.PATH); } for(String xs : xmlPrefsFiles) { if(xs.equalsIgnoreCase(input)) return new ArgInfo(xs, null, true, 1); } return new ArgInfo(null, input, false, 0); } private static ArgInfo integer(String input) { int n; String s; int index = input.indexOf(Tuils.SPACE); if(index == -1) s = input; else s = input.substring(0, index); try { n = Integer.parseInt(s); } catch (NumberFormatException e) { return new ArgInfo(null, input, false, 0); } return new ArgInfo(n, index == -1 ? null : input.substring(index + 1), true, 1); } public static boolean isSuRequest(String input) { return input.equals("su"); } public static boolean isSuCommand(String input) { return input.startsWith("su "); } public static class ArgInfo { public Object arg; public String residualString; public int n; public boolean found; public ArgInfo(Object arg, String residualString, boolean found, int nFound) { this.arg = arg; this.residualString = residualString; this.found = found; this.n = nFound; } } }
922fbf52b9b90c40126d62ff7aaa5472f48b796d
707
java
Java
src/main/java/com/github/microwww/bitcoin/wallet/Env.java
microwww/java-bitcoin
3e4de30ecf56ffca8eb68c346fd3e8f165c454f5
[ "Apache-2.0" ]
null
null
null
src/main/java/com/github/microwww/bitcoin/wallet/Env.java
microwww/java-bitcoin
3e4de30ecf56ffca8eb68c346fd3e8f165c454f5
[ "Apache-2.0" ]
null
null
null
src/main/java/com/github/microwww/bitcoin/wallet/Env.java
microwww/java-bitcoin
3e4de30ecf56ffca8eb68c346fd3e8f165c454f5
[ "Apache-2.0" ]
null
null
null
30.73913
99
0.66761
995,238
package com.github.microwww.bitcoin.wallet; public enum Env { MAIN(0, 128, "bitcoincash", "bc", 5), TEST(111, 239, "bchtest", "tb", 196), REG_TEST(111, 239, "bchreg", "bcrt", 196), ; public final byte address; public final byte dumpedPrivateKey; public final String bitcash; public final String addressBECH32; public final byte addressP2SH; Env(int address, int dumpedPrivateKey, String bitcash, String addressBECH32, int addressP2SH) { this.address = (byte) address; this.dumpedPrivateKey = (byte) dumpedPrivateKey; this.bitcash = bitcash; this.addressBECH32 = addressBECH32; this.addressP2SH = (byte) addressP2SH; } }
922fbf5ff533b6396267e7db8496e524d3100f9b
390
java
Java
gulimall-member/src/main/java/com/wgl/gulimall/member/dao/MemberLoginLogDao.java
JayMeWangGL/gulimall
8ae829f6685e0b3d9766507ec67d035a6a508c4a
[ "Apache-2.0" ]
null
null
null
gulimall-member/src/main/java/com/wgl/gulimall/member/dao/MemberLoginLogDao.java
JayMeWangGL/gulimall
8ae829f6685e0b3d9766507ec67d035a6a508c4a
[ "Apache-2.0" ]
null
null
null
gulimall-member/src/main/java/com/wgl/gulimall/member/dao/MemberLoginLogDao.java
JayMeWangGL/gulimall
8ae829f6685e0b3d9766507ec67d035a6a508c4a
[ "Apache-2.0" ]
null
null
null
21.777778
77
0.77551
995,239
package com.wgl.gulimall.member.dao; import com.wgl.gulimall.member.entity.MemberLoginLogEntity; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; /** * 会员登录记录 * * @author wangguoli * @email hzdkv@example.com * @date 2020-11-23 14:20:18 */ @Mapper public interface MemberLoginLogDao extends BaseMapper<MemberLoginLogEntity> { }
922fc1363e24bbf1c6810e8b44a8e79c68455186
344
java
Java
tiankafei-code-product/tiankafei-service/tiankafei-user-service/tiankafei-user-server/src/main/java/org/tiankafei/user/feign/LoginCustomFeign.java
tiankafei/java
9ff39cb47b8f2144851856b4412b1b0b7781cb09
[ "Apache-2.0" ]
1
2021-08-23T03:10:33.000Z
2021-08-23T03:10:33.000Z
tiankafei-code-product/tiankafei-service/tiankafei-user-service/tiankafei-user-server/src/main/java/org/tiankafei/user/feign/LoginCustomFeign.java
tiankafei/java
9ff39cb47b8f2144851856b4412b1b0b7781cb09
[ "Apache-2.0" ]
8
2020-09-02T15:14:03.000Z
2021-01-08T00:34:26.000Z
tiankafei-code-product/tiankafei-service/tiankafei-user-service/tiankafei-user-server/src/main/java/org/tiankafei/user/feign/LoginCustomFeign.java
tiankafei/java
9ff39cb47b8f2144851856b4412b1b0b7781cb09
[ "Apache-2.0" ]
2
2020-11-25T07:58:22.000Z
2021-01-28T00:15:11.000Z
26.461538
111
0.77907
995,240
package org.tiankafei.user.feign; import org.springframework.cloud.openfeign.FeignClient; import org.tiankafei.login.feign.LoginFeign; /** * @author 魏双双 * @since 1.0 **/ @FeignClient(value = "login-service", contextId = "loginCustomFeign", fallbackFactory = LoginCustomError.class) public interface LoginCustomFeign extends LoginFeign { }
922fc23228786eafb170638d2b2d972af6e10568
360
java
Java
app/src/main/java/com/multithread/cocoon/di/scope/PerActivity.java
amircoder/MVVM_Flow
6da12d05dc1fd776978fc6434b7683ae2b1c2f81
[ "MIT" ]
1
2020-12-07T21:30:29.000Z
2020-12-07T21:30:29.000Z
app/src/main/java/com/multithread/cocoon/di/scope/PerActivity.java
amircoder/MVVM_Flow
6da12d05dc1fd776978fc6434b7683ae2b1c2f81
[ "MIT" ]
2
2020-12-21T19:08:51.000Z
2020-12-21T19:56:08.000Z
app/src/main/java/com/multithread/cocoon/di/scope/PerActivity.java
amircoder/MVVM_Flow
6da12d05dc1fd776978fc6434b7683ae2b1c2f81
[ "MIT" ]
null
null
null
21.176471
100
0.780556
995,241
package com.multithread.cocoon.di.scope; import java.lang.annotation.Retention; import javax.inject.Scope; import static java.lang.annotation.RetentionPolicy.RUNTIME; /** * Dagger activity scope. Used in activity modules to indicate that the scope of the injected object * is an activity. */ @Scope @Retention(RUNTIME) public @interface PerActivity { }
922fc38c81231177bdd33a3cbe72feac7192d074
1,600
java
Java
src/main/RunApplicationManager.java
njhofmann/ApplicationManager
1da9a77ac899bb6945f6e4f4e4290e7a2ec64ce9
[ "MIT" ]
null
null
null
src/main/RunApplicationManager.java
njhofmann/ApplicationManager
1da9a77ac899bb6945f6e4f4e4290e7a2ec64ce9
[ "MIT" ]
null
null
null
src/main/RunApplicationManager.java
njhofmann/ApplicationManager
1da9a77ac899bb6945f6e4f4e4290e7a2ec64ce9
[ "MIT" ]
null
null
null
25.396825
98
0.711875
995,242
package main; import controller.Controller; import java.io.File; import javafx.application.Application; import javafx.scene.Scene; import javafx.stage.Stage; import model.ModelImpl; import model.ModelInterface; import view.ViewImpl; import view.ViewInterface; /** * Starts up this ApplicationManager. */ public class RunApplicationManager extends Application { ModelInterface model; ViewInterface view; /** * Starts up this ApplicationManager with the proper configurations (if any). * @param args configurations to start this program up with */ public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) { String filePath = new File(".").getAbsolutePath() + "/src/model/XMLData.xml"; model = new ModelImpl(filePath); // Open associated model for editing model.openModelData(); view = new ViewImpl(); ControllerInterface controller = new Controller(view, model); Scene scene = new Scene(view.asParent(), view.getWidth(), view.getHeight()); primaryStage.setTitle("Application Manager"); primaryStage.setResizable(false); primaryStage.setScene(scene); primaryStage.show(); } /** * After use has closed the View window, save changes made in the model, so long as the model is * assigned. * @throws IllegalArgumentException if the model has not yet been properly assigned */ @Override public void stop() { if (model == null) { throw new IllegalArgumentException("Model must be non null to save info!"); } model.closeModelData(); } }
922fc39dd8fb72f927760ad970a42696aed43d30
1,894
java
Java
src/org/adaptlab/chpir/android/survey/Models/GridLabel.java
mnipper/AndroidSurvey
f5f2ad214e755465eaae242b879548603ca3f287
[ "MIT" ]
6
2015-02-25T04:57:04.000Z
2019-03-29T12:18:50.000Z
src/org/adaptlab/chpir/android/survey/Models/GridLabel.java
mnipper/AndroidSurvey
f5f2ad214e755465eaae242b879548603ca3f287
[ "MIT" ]
null
null
null
src/org/adaptlab/chpir/android/survey/Models/GridLabel.java
mnipper/AndroidSurvey
f5f2ad214e755465eaae242b879548603ca3f287
[ "MIT" ]
13
2015-01-15T09:07:45.000Z
2020-01-30T08:59:39.000Z
26.676056
92
0.729145
995,243
package org.adaptlab.chpir.android.survey.Models; import org.adaptlab.chpir.android.activerecordcloudsync.ReceiveModel; import org.adaptlab.chpir.android.survey.AppUtil; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; import com.activeandroid.annotation.Column; import com.activeandroid.annotation.Table; import com.activeandroid.query.Select; @Table(name = "GridLabels") public class GridLabel extends ReceiveModel { private static final String TAG = "GridLabel"; @Column(name = "RemoteId", unique = true, onUniqueConflict = Column.ConflictAction.REPLACE) private Long mRemoteId; @Column(name = "Option") private Option mOption; @Column(name = "Grid") private Grid mGrid; @Column(name = "Label") private String mLabel; @Override public void createObjectFromJSON(JSONObject jsonObject) { try { Long remoteId = jsonObject.getLong("id"); GridLabel gridLabel = GridLabel.findByRemoteId(remoteId); if (gridLabel == null) { gridLabel = this; } gridLabel.setRemoteId(remoteId); gridLabel.setLabel(jsonObject.getString("label")); if (!jsonObject.isNull("option_id")) { gridLabel.setOption(Option.findByRemoteId(jsonObject.getLong("option_id"))); } gridLabel.setGrid(Grid.findByRemoteId(jsonObject.getLong("grid_id"))); gridLabel.save(); } catch (JSONException je) { Log.e(TAG, "Error parsing object json", je); } } public static GridLabel findByRemoteId(Long remoteId) { return new Select().from(GridLabel.class).where("RemoteId = ?", remoteId).executeSingle(); } public String getLabelText() { return mLabel; } private void setLabel(String label) { mLabel = label; } private void setOption(Option option) { mOption = option; } private void setGrid(Grid grid) { mGrid = grid; } private void setRemoteId(Long remoteId) { mRemoteId = remoteId; } }
922fc3d33d8aec5d9110276927b783334fe9c502
903
java
Java
integration-tests/it-common/src/main/java/org/apache/servicecomb/it/schema/generic/PersonBean.java
MC-JY/servicecomb-java-chassis
6c769733220a2ea7b4f2161ee4e0451d9f289cc8
[ "Apache-2.0" ]
1,336
2018-11-10T14:52:16.000Z
2022-03-25T16:17:27.000Z
integration-tests/it-common/src/main/java/org/apache/servicecomb/it/schema/generic/PersonBean.java
MC-JY/servicecomb-java-chassis
6c769733220a2ea7b4f2161ee4e0451d9f289cc8
[ "Apache-2.0" ]
1,582
2018-11-09T09:44:51.000Z
2022-03-31T08:07:21.000Z
integration-tests/it-common/src/main/java/org/apache/servicecomb/it/schema/generic/PersonBean.java
MC-JY/servicecomb-java-chassis
6c769733220a2ea7b4f2161ee4e0451d9f289cc8
[ "Apache-2.0" ]
485
2018-11-12T01:58:35.000Z
2022-03-24T02:10:00.000Z
41.045455
75
0.763012
995,244
/* * 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.servicecomb.it.schema.generic; public class PersonBean extends AbstractBean { }
922fc4536391d7b46e019342b10b263819afb235
501
java
Java
src/main/java/com/haohan/platform/service/sys/common/supcan/annotation/common/properties/SupBackground.java
haohanscm/pds
94bebd021f409a3bd6d6c25e6ceb5439f0063df5
[ "Apache-2.0" ]
null
null
null
src/main/java/com/haohan/platform/service/sys/common/supcan/annotation/common/properties/SupBackground.java
haohanscm/pds
94bebd021f409a3bd6d6c25e6ceb5439f0063df5
[ "Apache-2.0" ]
null
null
null
src/main/java/com/haohan/platform/service/sys/common/supcan/annotation/common/properties/SupBackground.java
haohanscm/pds
94bebd021f409a3bd6d6c25e6ceb5439f0063df5
[ "Apache-2.0" ]
null
null
null
18.555556
96
0.676647
995,245
/** * Copyright &copy; 2012-2017 <a href="http://www.haohanwork.com">haohan</a> All rights reserved */ package com.haohan.platform.service.sys.common.supcan.annotation.common.properties; import java.lang.annotation.*; /** * 硕正Background注解 * * @author WangZhen * @version 2013-11-12 */ @Target({ElementType.ANNOTATION_TYPE}) @Retention(RetentionPolicy.RUNTIME) @Inherited public @interface SupBackground { /** * 背景颜色 * * @return */ String bgColor() default ""; }
922fc5352a7329926724aea7814c0603020cdaaf
2,002
java
Java
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/api/ops/impl/meta/PostulateMetaOp.java
eric-erki/deeplearning4j
b9d462f66879e9315767b70190bd2ab31b9a3275
[ "Apache-2.0" ]
null
null
null
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/api/ops/impl/meta/PostulateMetaOp.java
eric-erki/deeplearning4j
b9d462f66879e9315767b70190bd2ab31b9a3275
[ "Apache-2.0" ]
null
null
null
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/api/ops/impl/meta/PostulateMetaOp.java
eric-erki/deeplearning4j
b9d462f66879e9315767b70190bd2ab31b9a3275
[ "Apache-2.0" ]
null
null
null
27.819444
107
0.628058
995,246
/* * ****************************************************************************** * * Copyright (c) 2021 Deeplearning4j Contributors * * * * This program and the accompanying materials are made available under the * * terms of the Apache License, Version 2.0 which is available 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. * * * * SPDX-License-Identifier: Apache-2.0 * ***************************************************************************** */ package org.nd4j.linalg.api.ops.impl.meta; import org.nd4j.autodiff.samediff.SDVariable; import org.nd4j.linalg.api.ndarray.INDArray; import org.nd4j.linalg.api.ops.ReduceOp; import org.nd4j.linalg.api.ops.ScalarOp; import org.nd4j.linalg.api.ops.TransformOp; import org.nd4j.linalg.api.ops.grid.OpDescriptor; import java.util.List; /** * You're NOT supposed to directly call this op. Do it on your own risk, only if you're absolutely have to. * * @author dycjh@example.com */ public class PostulateMetaOp extends BaseMetaOp { public PostulateMetaOp() { } public PostulateMetaOp(INDArray x, INDArray y) { super(x, y); } public PostulateMetaOp(ScalarOp opA, ReduceOp opB) { super(opA, opB); } public PostulateMetaOp(TransformOp opA, ReduceOp opB) { super(opA, opB); } public PostulateMetaOp(OpDescriptor opA, OpDescriptor opB) { super(opA, opB); } @Override public int opNum() { return 1; } @Override public String opName() { return "meta_postulate"; } @Override public List<SDVariable> doDiff(List<SDVariable> f1) { return null; } }
922fc602eec15f131048e5ee375bbcd1a72699e1
201
java
Java
samples/BasicApp/androidstudio/BasicApp/app/src/main/java/org/libcinder/sample/basicapp/BasicAppActivity.java
s3global/Cinder
e83f5bb9c01a63eec20168d02953a0879e5100f7
[ "BSD-2-Clause" ]
3,494
2015-01-02T08:42:09.000Z
2022-03-31T14:16:23.000Z
samples/BasicApp/androidstudio/BasicApp/app/src/main/java/org/libcinder/sample/basicapp/BasicAppActivity.java
edselmalasig/Cinder
2284df43f77b6b99f8f05384c516e962d9336bc3
[ "BSD-2-Clause" ]
1,284
2015-01-02T07:31:47.000Z
2022-03-30T02:06:43.000Z
samples/BasicApp/androidstudio/BasicApp/app/src/main/java/org/libcinder/sample/basicapp/BasicAppActivity.java
edselmalasig/Cinder
2284df43f77b6b99f8f05384c516e962d9336bc3
[ "BSD-2-Clause" ]
780
2015-01-02T22:14:29.000Z
2022-03-30T00:16:56.000Z
25.125
60
0.81592
995,247
package org.libcinder.sample.basicapp; import org.libcinder.app.CinderNativeActivity; public class BasicAppActivity extends CinderNativeActivity { static final String TAG = "BasicAppActivity"; }
922fc605a8e676228306b1e6a9389b512a3c9e99
612
java
Java
commons/src/main/java/schulscheduler/i18n/DefaultValues.java
Philipp91/SchulScheduler
c599a0bd4d3bbcde0923dabf1fbc693ee3ec1bdc
[ "Apache-2.0" ]
null
null
null
commons/src/main/java/schulscheduler/i18n/DefaultValues.java
Philipp91/SchulScheduler
c599a0bd4d3bbcde0923dabf1fbc693ee3ec1bdc
[ "Apache-2.0" ]
null
null
null
commons/src/main/java/schulscheduler/i18n/DefaultValues.java
Philipp91/SchulScheduler
c599a0bd4d3bbcde0923dabf1fbc693ee3ec1bdc
[ "Apache-2.0" ]
null
null
null
21.857143
75
0.650327
995,248
package schulscheduler.i18n; /** * Wrapper um default.properties, damit die Werte mit UTF-8 geladen werden. */ public class DefaultValues extends UTF8ResourceBundle { /** * Singleton-Pattern, enthält eine Instanz. */ private static final DefaultValues INSTANCE = new DefaultValues(); /** * @return Ein Resource-Bundle für die aktive Locale. */ public static DefaultValues getInstance() { return INSTANCE; } /** * Default-Konstruktor, über den das UTF8_CONTROL angebunden wird. */ public DefaultValues() { super("default"); } }