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
92376f9cc93288504998d17d9f5938b220ceade2
441
java
Java
domain-model/src/main/java/uk/gov/hmcts/cmc/domain/constraints/FutureDateConstraintValidator.java
ManishParyani/cmc-claim-store
4b96a674dd27c54f8491d587576ad26b38159bb9
[ "MIT" ]
13
2017-11-04T16:52:53.000Z
2021-12-10T16:19:13.000Z
domain-model/src/main/java/uk/gov/hmcts/cmc/domain/constraints/FutureDateConstraintValidator.java
ManishParyani/cmc-claim-store
4b96a674dd27c54f8491d587576ad26b38159bb9
[ "MIT" ]
1,952
2017-09-13T10:36:57.000Z
2022-03-07T10:32:44.000Z
domain-model/src/main/java/uk/gov/hmcts/cmc/domain/constraints/FutureDateConstraintValidator.java
ManishParyani/cmc-claim-store
4b96a674dd27c54f8491d587576ad26b38159bb9
[ "MIT" ]
18
2018-01-24T14:26:43.000Z
2021-08-13T14:51:56.000Z
29.4
98
0.791383
998,058
package uk.gov.hmcts.cmc.domain.constraints; import java.time.LocalDate; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; public class FutureDateConstraintValidator implements ConstraintValidator<FutureDate, LocalDate> { @Override public boolean isValid(LocalDate value, ConstraintValidatorContext context) { return value == null || value.isAfter(LocalDate.now()); } }
92376ff9006bc389ad608c342494a603557c2194
1,607
java
Java
src/main/java/daomephsta/unpick/constantmappers/IConstantMapper.java
therealfarfetchd/unpick
a369ed36f8e543294798412c760bff7485bb58fd
[ "MIT" ]
null
null
null
src/main/java/daomephsta/unpick/constantmappers/IConstantMapper.java
therealfarfetchd/unpick
a369ed36f8e543294798412c760bff7485bb58fd
[ "MIT" ]
null
null
null
src/main/java/daomephsta/unpick/constantmappers/IConstantMapper.java
therealfarfetchd/unpick
a369ed36f8e543294798412c760bff7485bb58fd
[ "MIT" ]
null
null
null
41.205128
124
0.759801
998,059
package daomephsta.unpick.constantmappers; import org.objectweb.asm.tree.FieldInsnNode; /** * Defines a mapping of inlined values to replacement instructions. * @author Daomephsta */ public interface IConstantMapper { /** * Maps an inlined value to a replacement instruction, for a given target method. * @param methodOwner the internal name of the class that owns the target method. * @param methodName the name of the target method. * @param methodDescriptor the descriptor of the target method. * @param parameterIndex the index of the parameter of the target method that {@code value} is passed as. * @param value the inlined value. * @return An instruction to replace the inlined value with. */ public FieldInsnNode map(String methodOwner, String methodName, String methodDescriptor, int parameterIndex, Object value); /** * @param methodOwner the internal name of the class that owns the method. * @param methodName the name of the method. * @param methodDescriptor the descriptor of the method. * @return true if this mapper targets the method. */ public boolean targets(String methodOwner, String methodName, String methodDescriptor); /** * @param methodOwner the internal name of the class that owns the method. * @param methodName the name of the method. * @param methodDescriptor the descriptor of the method. * @return true if this mapper targets the parameter of the method with a * parameter index of {@code parameterIndex}. */ public boolean targets(String methodOwner, String methodName, String methodDescriptor, int parameterIndex); }
9237705df7c564f7b9c97a40ce9803799ae62c96
989
java
Java
hibernate-validator/src/main/java/com/liyulin/hibernate/validator/entity/ProductVO.java
weispring/demo
087ae2d4ec97e67979136c3de295be80abfc6e40
[ "Apache-2.0" ]
11
2017-08-22T03:20:01.000Z
2021-03-11T10:31:08.000Z
hibernate-validator/src/main/java/com/liyulin/hibernate/validator/entity/ProductVO.java
luckyQing/demo
4d949df653d6f4968cb73aa7ef21725943b4450d
[ "Apache-2.0" ]
33
2020-12-31T06:12:05.000Z
2022-03-13T06:45:24.000Z
hibernate-validator/src/main/java/com/liyulin/hibernate/validator/entity/ProductVO.java
weispring/demo
087ae2d4ec97e67979136c3de295be80abfc6e40
[ "Apache-2.0" ]
3
2020-02-15T13:15:31.000Z
2021-07-21T05:32:24.000Z
24.121951
69
0.721941
998,060
package com.liyulin.hibernate.validator.entity; import java.math.BigDecimal; import java.math.BigInteger; import javax.validation.constraints.DecimalMax; import javax.validation.constraints.DecimalMin; import javax.validation.constraints.Min; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import org.hibernate.validator.constraints.Length; import com.liyulin.hibernate.validator.entity.ValidatorGroup.Insert; import lombok.Data; /** * group校验测试 * * @author liyulin * @date 上午11:38:10 */ @Data public class ProductVO { @NotNull(message = "id不允许为空", groups = { Insert.class }) @Min(value = 1, message = "最小值为1") private BigInteger id; @NotBlank(message = "名称不能为空") @Length(max = 10, message = "名称最大长度为10") private String name; @NotNull(message = "价格不能为空") @DecimalMin(value = "1", message = "价格最小值为1") @DecimalMax(value = "100", message = "价格最大值为100") private BigDecimal price; }
92377087ad0f4c9152686d3db91c059f6ba980f6
3,120
java
Java
src/main/java/net/glamenvseptzen/studyj8jcajsse/Main.java
msakamoto-sf/study-java8-jca-jsse
b86125abb2172186f0d898fbe3f6d6109d6881d6
[ "MIT" ]
null
null
null
src/main/java/net/glamenvseptzen/studyj8jcajsse/Main.java
msakamoto-sf/study-java8-jca-jsse
b86125abb2172186f0d898fbe3f6d6109d6881d6
[ "MIT" ]
null
null
null
src/main/java/net/glamenvseptzen/studyj8jcajsse/Main.java
msakamoto-sf/study-java8-jca-jsse
b86125abb2172186f0d898fbe3f6d6109d6881d6
[ "MIT" ]
null
null
null
38.518519
104
0.599038
998,061
package net.glamenvseptzen.studyj8jcajsse; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import net.glamenvseptzen.studyj8jcajsse.subcommand.DumpMajorJcaJssePolicy; import net.glamenvseptzen.studyj8jcajsse.subcommand.DumpMessageDigestProviders; import net.glamenvseptzen.studyj8jcajsse.subcommand.DumpSecureRandomProviders; import net.glamenvseptzen.studyj8jcajsse.subcommand.DumpSecurityProviders; public class Main { static final byte[] BYTES_00_FF; static final Map<String, ISubCommand> COMMANDS; static { BYTES_00_FF = new byte[256]; for (int i = 0; i <= 0xFF; i++) { BYTES_00_FF[i] = (byte) i; } COMMANDS = new LinkedHashMap<>(); COMMANDS.put("dump-providers", new DumpSecurityProviders()); COMMANDS.put("dump-secure-random-providers", new DumpSecureRandomProviders()); COMMANDS.put("dump-message-digest-providers", new DumpMessageDigestProviders()); COMMANDS.put("dump-major-policy", new DumpMajorJcaJssePolicy()); } public static String stripCRLF(final Object o) { return stripCRLF(o.toString()); } public static String stripCRLF(final String s) { return s.replace("\r", "").replace("\n", ""); } public static String dumpHex(final byte[] src) { final HexDumper hd = new HexDumper(); hd.setPrefix("0x"); hd.setSeparator(","); hd.setToUpperCase(false); return hd.dump(src); } public static byte[] toba(int... src) { if (src.length == 0) { return new byte[] {}; } final byte[] r = new byte[src.length]; for (int i = 0; i < src.length; i++) { r[i] = (byte) src[i]; } return r; } public static void main(String[] args) throws Exception { String[] subargs = new String[0]; ISubCommand subcommand = null; if (args.length > 0 && COMMANDS.containsKey(args[0])) { subargs = (args.length > 1) ? Arrays.copyOfRange(args, 1, args.length - 1) : new String[0]; subcommand = COMMANDS.get(args[0]); subcommand.run(subargs); } else { System.out.println("Command Line Arguments : <command-name> (args...)"); System.out.println("\n<command-name> are:"); for (Entry<String, ISubCommand> e : COMMANDS.entrySet()) { System.out.println(e.getKey() + " - " + e.getValue().getDescription()); } System.out.print("\nEnter <command-name>:"); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); final String commandname = br.readLine().trim(); if (COMMANDS.containsKey(commandname)) { COMMANDS.get(commandname).run(new String[0]); } else { System.err.println(commandname + " is not available."); } } } }
92377169e633661b88df87a98511e9ec18ebfc0d
2,623
java
Java
app/src/main/java/com/merryapps/tictacpro/ui/MainActivity.java
PravSonawane/tictacpro-android-game
25a13ad291d9c14d5b382521c5959cfdb5626fd6
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/merryapps/tictacpro/ui/MainActivity.java
PravSonawane/tictacpro-android-game
25a13ad291d9c14d5b382521c5959cfdb5626fd6
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/merryapps/tictacpro/ui/MainActivity.java
PravSonawane/tictacpro-android-game
25a13ad291d9c14d5b382521c5959cfdb5626fd6
[ "Apache-2.0" ]
null
null
null
31.987805
120
0.701487
998,062
package com.merryapps.tictacpro.ui; import android.os.Bundle; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.Window; import android.view.WindowManager; import android.widget.FrameLayout; import com.merryapps.TicTacProApp; import com.merryapps.TicTacProManagerFactory; import com.merryapps.tictacpro.R; public class MainActivity extends AppCompatActivity { private static final String TAG = "MainActivity"; private FrameLayout placeHolder; private GameController gameController; private MenuFragment menuFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //remove the status bar requestWindowFeature(Window.FEATURE_NO_TITLE); this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_main); initViews(); //load seed data managerFactory().globalStatsManager().loadSeedData(); //init gameController gameController = new GameController(this); //replacing placeholder with menu fragment if (savedInstanceState == null) { menuFragment = new MenuFragment(); getSupportFragmentManager().beginTransaction() .replace(R.id.activity_main_frmLyt_placeHolder_id, menuFragment, MenuFragment.FRAGMENT_NAME_TAG) .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE) .commit(); } else { menuFragment = (MenuFragment) getSupportFragmentManager().findFragmentByTag(MenuFragment.FRAGMENT_NAME_TAG); } } @Override public void onBackPressed() { Log.d(TAG, "onBackPressed() called"); Log.d(TAG, "onBackPressed: getSupportFragmentManager().getBackStackEntryCount():" + getSupportFragmentManager().getBackStackEntryCount()); if(getSupportFragmentManager().getBackStackEntryCount() > 0) { getSupportFragmentManager().popBackStackImmediate(); } else { super.onBackPressed(); } } private void initViews() { placeHolder = (FrameLayout) findViewById(R.id.activity_main_frmLyt_placeHolder_id); } public TicTacProManagerFactory managerFactory() { return (TicTacProManagerFactory) ((TicTacProApp) getApplication()).getManagerFactory(); } GameController getGameController() { return this.gameController; } }
923772a737045a511db59dde3372067af601388b
7,363
java
Java
src/lk/ijse/gdse41/ias/dao/custom/impl/QueryDAOImpl.java
MissakaI/Institute-Administration-System
ed633b3eea56a2763456445b7b624dc473241d97
[ "Apache-2.0" ]
null
null
null
src/lk/ijse/gdse41/ias/dao/custom/impl/QueryDAOImpl.java
MissakaI/Institute-Administration-System
ed633b3eea56a2763456445b7b624dc473241d97
[ "Apache-2.0" ]
null
null
null
src/lk/ijse/gdse41/ias/dao/custom/impl/QueryDAOImpl.java
MissakaI/Institute-Administration-System
ed633b3eea56a2763456445b7b624dc473241d97
[ "Apache-2.0" ]
null
null
null
44.355422
214
0.647155
998,063
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package lk.ijse.gdse41.ias.dao.custom.impl; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; import lk.ijse.gdse41.ias.dao.custom.QueryDAO; import lk.ijse.gdse41.ias.dao.db.ConnectionFactory; import lk.ijse.gdse41.ias.dto.AttendanceDTO; import lk.ijse.gdse41.ias.dto.ClassScheduleDTO; import lk.ijse.gdse41.ias.dto.PaymentDTO; import lk.ijse.gdse41.ias.dto.StudentDTO; import lk.ijse.gdse41.ias.dto.SubjectDTO; import lk.ijse.gdse41.ias.dto.TutorDTO; import lk.ijse.gdse41.ias.dto.TutorSubjectDTO; /** * * @author midda */ public class QueryDAOImpl implements QueryDAO{ Connection conn; public QueryDAOImpl() { conn=ConnectionFactory.getInstance().getConnection(); } @Override public ArrayList<StudentDTO> getStudentsInClass(String cid) throws Exception { String SQL="SELECT * FROM student WHERE sid IN (" + "SELECT sid FROM registration WHERE cid=?)"; PreparedStatement stm=conn.prepareStatement(SQL); stm.setObject(1, cid); ResultSet rst=stm.executeQuery(); ArrayList<StudentDTO> studentList=new ArrayList<>(); while (rst.next()){ StudentDTO s=new StudentDTO(rst.getString(1),rst.getString(2),rst.getString(3),rst.getString(4),rst.getString(5),rst.getBoolean(6) ,rst.getString(7),rst.getString(8),rst.getString(9),rst.getString(10),rst.getString(11),rst.getString(12)); studentList.add(s); } return studentList; } @Override public ArrayList<AttendanceDTO> getAttendanceToClass(String cid, String date) throws Exception { String SQL="SELECT * FROM attendance WHERE a_date=? && rid IN (SELECT rid FROM registration WHERE cid=?)"; PreparedStatement stm=conn.prepareStatement(SQL); stm.setObject(1, date); stm.setObject(2, cid); ArrayList<AttendanceDTO> attendanceList=new ArrayList<>(); ResultSet rst=stm.executeQuery(); while (rst.next()){ AttendanceDTO a=new AttendanceDTO(rst.getString(1), rst.getString(2), rst.getString(3)); attendanceList.add(a); } return attendanceList; } @Override public ArrayList<ClassScheduleDTO> getCSandStudentCount(ClassScheduleDTO dto) throws Exception { String SQL="SELECT CS.*, COUNT(R.rid), B.b_year FROM class_schedule CS, registration R, batch B WHERE CS.cid=R.cid && CS.bid=B.bid && CS.tsid=? HAVING COUNT(R.rid)>0"; PreparedStatement stm=conn.prepareStatement(SQL); stm.setObject(1,dto.getTsid()); ArrayList<ClassScheduleDTO> csdtoList=new ArrayList<>(); ResultSet rst = stm.executeQuery(); while (rst.next()){ if(rst.getString(1)!=null){ ClassScheduleDTO cs=new ClassScheduleDTO(rst.getString(1), rst.getString(2), rst.getString(3), rst.getString(4), rst.getString(5), rst.getInt(6), rst.getString(7), rst.getInt(8), rst.getDouble(9), rst.getDouble(10), rst.getInt(11)); cs.setYear(rst.getInt(12)); csdtoList.add(cs); } } return csdtoList; } @Override public ArrayList<ClassScheduleDTO> getHallSchedule(ClassScheduleDTO dto) throws Exception { String SQL="SELECT CS.*,B.b_year FROM class_schedule CS, batch B WHERE CS.bid=B.bid && (hid_1=? || hid_2=?)"; PreparedStatement stm=conn.prepareStatement(SQL); stm.setObject(1,dto.getHid_1()); stm.setObject(2,dto.getHid_2()); ArrayList<ClassScheduleDTO> csdtoList=new ArrayList<>(); ResultSet rst = stm.executeQuery(); while (rst.next()){ if(rst.getString(1)!=null){ ClassScheduleDTO cs=new ClassScheduleDTO(rst.getString(1), rst.getString(2), rst.getString(3), rst.getString(4), rst.getString(5), rst.getInt(6), rst.getString(7), rst.getInt(8), rst.getDouble(9), rst.getDouble(10), 0); cs.setYear(rst.getInt(11)); csdtoList.add(cs); } } return csdtoList; } @Override public PaymentDTO getTutorsMonthlyPayment(String cid, int month) throws Exception { String SQL="SELECT COUNT(R.rid), COUNT(P.pid), SUM(if(free_card=TRUE, 1, 0)) FROM registration R LEFT JOIN payment P USING (rid) WHERE R.cid=? && P.p_month=? && YEAR(P.p_date)=YEAR(CURDATE()) GROUP BY cid"; PreparedStatement stm=conn.prepareStatement(SQL); stm.setObject(1, cid); stm.setObject(2, month); ResultSet rst=stm.executeQuery(); if(rst.next()){ PaymentDTO dto=new PaymentDTO(rst.getInt(1), rst.getInt(2), rst.getInt(3)); return dto; } return null; } @Override public ArrayList<SubjectDTO> getSubjectsOfBatch(String bid) throws Exception { String SQL=String.format("SELECT DISTINCT S.* FROM tutor_subject T, subject S, class_schedule C, batch B " + "WHERE T.subID=S.subID && B.bid=c.BID && C.tsid=T.tsid && B.bid='%s'",bid); Statement stm=conn.createStatement(); ResultSet rst=stm.executeQuery(SQL); ArrayList<SubjectDTO> subjectList=new ArrayList<>(); while(rst.next()){ SubjectDTO subject=new SubjectDTO(rst.getString(1),rst.getString(2),rst.getString(3)); subjectList.add(subject); } return subjectList; } @Override public ArrayList<TutorDTO> getTutorsTeachingSubjectForBatch(TutorDTO dto) throws Exception { String SQL=String.format("SELECT T.* FROM tutor_subject TS, subject S, class_schedule C, batch B, Tutor T " + "WHERE TS.subID=S.subID && B.bid=c.BID && C.tsid=TS.tsid && TS.tid=T.tid && B.bid='%s' && S.subID='%s'",dto.getBid(),dto.getSubId()); Statement stm=conn.createStatement(); ResultSet rst=stm.executeQuery(SQL); ArrayList<TutorDTO> tutorList=new ArrayList<>(); while(rst.next()){ TutorDTO tutor = new TutorDTO(rst.getString(1),rst.getString(2),rst.getString(3),rst.getString(4),rst.getString(5),rst.getString(6),rst.getString(7),rst.getString(8),rst.getString(9),rst.getString(10)); tutorList.add(tutor); } return tutorList; } @Override public ArrayList<TutorSubjectDTO> getSubjectWithTutor(String tid) throws Exception { String SQL="SELECT S.*,TS.tsid,TS.tid FROM subject S, tutor_subject TS WHERE S.subId=TS.subId && S.subId IN " + "(SELECT subId FROM tutor_subject WHERE tid=?);"; PreparedStatement stm=conn.prepareStatement(SQL); stm.setObject(1, tid); ResultSet rst=stm.executeQuery(); ArrayList<TutorSubjectDTO> tsdtoList=new ArrayList<>(); while (rst.next()){ TutorSubjectDTO sdto=new TutorSubjectDTO(rst.getString(4), rst.getString(5), rst.getString(1)); sdto.setSubID(rst.getString(1)); sdto.setSubName(rst.getString(2)); sdto.setGrade(rst.getString(3)); tsdtoList.add(sdto); } return tsdtoList; } }
9237730fb9825237af5936b895f091cd1df4301e
359
java
Java
src/main/java/edu/jxust/SpatialQuery/SingleLevelGrid.java
ZSanting/BigSpatialData
3349d18caff95c436d478fbb33a78f2faa68817a
[ "Apache-2.0" ]
null
null
null
src/main/java/edu/jxust/SpatialQuery/SingleLevelGrid.java
ZSanting/BigSpatialData
3349d18caff95c436d478fbb33a78f2faa68817a
[ "Apache-2.0" ]
null
null
null
src/main/java/edu/jxust/SpatialQuery/SingleLevelGrid.java
ZSanting/BigSpatialData
3349d18caff95c436d478fbb33a78f2faa68817a
[ "Apache-2.0" ]
1
2018-11-12T08:10:33.000Z
2018-11-12T08:10:33.000Z
17.095238
35
0.635097
998,064
/** * @Title: SingleLevelGrid.java * @Package edu.jxust.SpatialQuery * @Description: TODO * @author 张炫铤 * @date 2017年3月6日 下午10:08:06 * @version V1.0 */ package edu.jxust.SpatialQuery; /** * @ClassName: SingleLevelGrid * @Description: TODO * @author 张炫铤 * @date 2017年3月6日 下午10:08:06 * */ public class SingleLevelGrid { }
9237751231a0b3ea381197a09ea2fd6bb690d8fa
5,034
java
Java
core/src/test/java/com/fujitsu/dc/test/jersey/cell/ctl/ExtRoleListTest.java
personium/io
c6347872165d8abf3d1c820ae05c2c030282d5b0
[ "Apache-2.0" ]
30
2015-01-01T05:59:20.000Z
2017-02-06T21:51:45.000Z
core/src/test/java/com/fujitsu/dc/test/jersey/cell/ctl/ExtRoleListTest.java
nguyenhoangvietk56/io
c6347872165d8abf3d1c820ae05c2c030282d5b0
[ "Apache-2.0" ]
16
2016-01-29T08:49:46.000Z
2017-02-02T08:30:04.000Z
core/src/test/java/com/fujitsu/dc/test/jersey/cell/ctl/ExtRoleListTest.java
nguyenhoangvietk56/io
c6347872165d8abf3d1c820ae05c2c030282d5b0
[ "Apache-2.0" ]
18
2015-01-27T06:06:36.000Z
2016-01-29T10:00:58.000Z
43.025641
112
0.684744
998,065
/** * personium.io * Copyright 2014 FUJITSU LIMITED * * 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.fujitsu.dc.test.jersey.cell.ctl; import java.util.HashMap; import java.util.Map; import org.apache.http.HttpStatus; import org.json.simple.JSONObject; import org.junit.Test; import org.junit.experimental.categories.Category; import com.fujitsu.dc.test.categories.Integration; import com.fujitsu.dc.test.categories.Regression; import com.fujitsu.dc.test.categories.Unit; import com.fujitsu.dc.test.jersey.AbstractCase; import com.fujitsu.dc.test.jersey.ODataCommon; import com.fujitsu.dc.test.unit.core.UrlUtils; import com.fujitsu.dc.test.utils.BoxUtils; import com.fujitsu.dc.test.utils.CellUtils; import com.fujitsu.dc.test.utils.ExtRoleUtils; import com.fujitsu.dc.test.utils.TResponse; /** * ExtCell一覧取得のテスト. */ @Category({Unit.class, Integration.class, Regression.class }) public class ExtRoleListTest extends ODataCommon { private final String token = AbstractCase.MASTER_TOKEN_NAME; private static String extRoleTestCell = "testextrolecell1"; private static String testExtRoleName = UrlUtils.roleResource(extRoleTestCell, "__", "testextrole"); private static final String EXT_ROLE_TYPE = "CellCtl.ExtRole"; /** * コンストラクタ. テスト対象のパッケージをsuperに渡す必要がある */ public ExtRoleListTest() { super("com.fujitsu.dc.core.rs"); } /** * ExtRole一覧取得の正常系のテスト. */ @SuppressWarnings("unchecked") @Test public final void ExtRole一覧取得の正常系のテスト() { String relationName = "testrelation02"; String relationBoxName = "box1"; try { // Cell作成 CellUtils.create(extRoleTestCell, token, HttpStatus.SC_CREATED); // Box作成 BoxUtils.create(extRoleTestCell, relationBoxName, token); // Relation作成 CellCtlUtils.createRelation(extRoleTestCell, relationName, relationBoxName); JSONObject body = new JSONObject(); body.put("ExtRole", testExtRoleName); body.put("_Relation.Name", relationName); body.put("_Relation._Box.Name", relationBoxName); JSONObject body2 = new JSONObject(); body2.put("ExtRole", testExtRoleName + "1"); body2.put("_Relation.Name", relationName); body2.put("_Relation._Box.Name", relationBoxName); // ExtRole作成 ExtRoleUtils.create(token, extRoleTestCell, body, HttpStatus.SC_CREATED); ExtRoleUtils.create(token, extRoleTestCell, body2, HttpStatus.SC_CREATED); // ExtRole一覧取得 TResponse response = ExtRoleUtils.list(token, extRoleTestCell, HttpStatus.SC_OK); // レスポンスボディーのチェック(URI) Map<String, String> uri = new HashMap<String, String>(); uri.put(testExtRoleName, UrlUtils.extRoleUrl(extRoleTestCell, relationBoxName, relationName, testExtRoleName)); uri.put(testExtRoleName + "1", UrlUtils.extRoleUrl(extRoleTestCell, relationBoxName, relationName, testExtRoleName + "1")); // レスポンスボディーのチェック Map<String, Map<String, Object>> additional = new HashMap<String, Map<String, Object>>(); Map<String, Object> additionalprop = new HashMap<String, Object>(); Map<String, Object> additionalprop2 = new HashMap<String, Object>(); additionalprop.put("ExtRole", testExtRoleName); additionalprop.put("_Relation.Name", relationName); additionalprop.put("_Relation._Box.Name", relationBoxName); additionalprop2.put("ExtRole", testExtRoleName + "1"); additionalprop2.put("_Relation.Name", relationName); additionalprop2.put("_Relation._Box.Name", relationBoxName); additional.put(testExtRoleName, additionalprop); additional.put(testExtRoleName + "1", additionalprop2); ODataCommon.checkResponseBodyList(response.bodyAsJson(), uri, EXT_ROLE_TYPE, additional, "ExtRole"); } finally { CellCtlUtils.deleteExtRole(extRoleTestCell, testExtRoleName, relationName, relationBoxName); CellCtlUtils.deleteExtRole(extRoleTestCell, testExtRoleName + "1", relationName, relationBoxName); CellCtlUtils.deleteRelation(extRoleTestCell, relationName, relationBoxName); BoxUtils.delete(extRoleTestCell, token, relationBoxName); CellUtils.delete(token, extRoleTestCell); } } }
92377612010fdec98ca48feaaa87d8da55cee889
460
java
Java
lib/test/on2019_04/on2019_04_24_Codeforces_Round__554__Div__2_/B___Neko_Performs_Cat_Furrier_Transform/Main.java
osmanys/cpjava2
707c57ff9bca694ff159e95cd9af45675b1ac7e2
[ "Apache-2.0" ]
1
2019-04-17T04:05:03.000Z
2019-04-17T04:05:03.000Z
lib/test/on2019_04/on2019_04_24_Codeforces_Round__554__Div__2_/B___Neko_Performs_Cat_Furrier_Transform/Main.java
osmanys/cpjava2
707c57ff9bca694ff159e95cd9af45675b1ac7e2
[ "Apache-2.0" ]
null
null
null
lib/test/on2019_04/on2019_04_24_Codeforces_Round__554__Div__2_/B___Neko_Performs_Cat_Furrier_Transform/Main.java
osmanys/cpjava2
707c57ff9bca694ff159e95cd9af45675b1ac7e2
[ "Apache-2.0" ]
null
null
null
30.666667
173
0.823913
998,066
package on2019_04.on2019_04_24_Codeforces_Round__554__Div__2_.B___Neko_Performs_Cat_Furrier_Transform; import net.egork.chelper.tester.NewTester; import org.junit.Assert; import org.junit.Test; public class Main { @Test public void test() throws Exception { if (!NewTester.test("lib/test/on2019_04/on2019_04_24_Codeforces_Round__554__Div__2_/B___Neko_Performs_Cat_Furrier_Transform/B - Neko Performs Cat Furrier Transform.json")) Assert.fail(); } }
923777c292702aee2c3bb406af0e773404d4c4dd
2,120
java
Java
Mobile App/Code/sources/com/google/android/gms/games/leaderboard/LeaderboardVariantRef.java
shivi98g/EpilNet-EpilepsyPredictor
15a98fb9ac7ee535005fb2aebb36548f28c7f6d1
[ "MIT" ]
null
null
null
Mobile App/Code/sources/com/google/android/gms/games/leaderboard/LeaderboardVariantRef.java
shivi98g/EpilNet-EpilepsyPredictor
15a98fb9ac7ee535005fb2aebb36548f28c7f6d1
[ "MIT" ]
null
null
null
Mobile App/Code/sources/com/google/android/gms/games/leaderboard/LeaderboardVariantRef.java
shivi98g/EpilNet-EpilepsyPredictor
15a98fb9ac7ee535005fb2aebb36548f28c7f6d1
[ "MIT" ]
null
null
null
24.090909
87
0.62783
998,067
package com.google.android.gms.games.leaderboard; import com.google.android.gms.common.data.C0705d; import com.google.android.gms.common.data.DataHolder; public final class LeaderboardVariantRef extends C0705d implements LeaderboardVariant { LeaderboardVariantRef(DataHolder dataHolder, int i) { super(dataHolder, i); } public boolean equals(Object obj) { return LeaderboardVariantEntity.m3688a(this, obj); } public int getCollection() { return getInteger("collection"); } public String getDisplayPlayerRank() { return getString("player_display_rank"); } public String getDisplayPlayerScore() { return getString("player_display_score"); } public long getNumScores() { if (mo11082aS("total_scores")) { return -1; } return getLong("total_scores"); } public long getPlayerRank() { if (mo11082aS("player_rank")) { return -1; } return getLong("player_rank"); } public String getPlayerScoreTag() { return getString("player_score_tag"); } public long getRawPlayerScore() { if (mo11082aS("player_raw_score")) { return -1; } return getLong("player_raw_score"); } public int getTimeSpan() { return getInteger("timespan"); } public boolean hasPlayerInfo() { return !mo11082aS("player_raw_score"); } public int hashCode() { return LeaderboardVariantEntity.m3687a(this); } /* renamed from: mK */ public String mo14307mK() { return getString("top_page_token_next"); } /* renamed from: mL */ public String mo14308mL() { return getString("window_page_token_prev"); } /* renamed from: mM */ public String mo14309mM() { return getString("window_page_token_next"); } /* renamed from: mN */ public LeaderboardVariant freeze() { return new LeaderboardVariantEntity(this); } public String toString() { return LeaderboardVariantEntity.m3689b(this); } }
923778af45a8922921ecb7acf8b63e1c3f0540bf
60,883
java
Java
src/main/java/com/google/firebase/auth/FirebaseAuth.java
MathBunny/firebase-admin-java
a6b81e8b597d390cc9d4728ddaf54a2d6f3e0357
[ "Apache-2.0" ]
null
null
null
src/main/java/com/google/firebase/auth/FirebaseAuth.java
MathBunny/firebase-admin-java
a6b81e8b597d390cc9d4728ddaf54a2d6f3e0357
[ "Apache-2.0" ]
1
2021-12-09T19:27:57.000Z
2021-12-09T19:27:57.000Z
src/main/java/com/google/firebase/auth/FirebaseAuth.java
ohbus/firebase-admin-java
3485c98f42d483b2336aa4357546f6d56d2a9346
[ "Apache-2.0" ]
null
null
null
44.932103
121
0.731797
998,068
/* * Copyright 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.firebase.auth; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import com.google.api.client.json.JsonFactory; import com.google.api.client.util.Clock; import com.google.api.core.ApiFuture; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Strings; import com.google.common.base.Supplier; import com.google.common.base.Suppliers; import com.google.firebase.FirebaseApp; import com.google.firebase.ImplFirebaseTrampolines; import com.google.firebase.auth.FirebaseUserManager.EmailLinkType; import com.google.firebase.auth.FirebaseUserManager.UserImportRequest; import com.google.firebase.auth.ListUsersPage.DefaultUserSource; import com.google.firebase.auth.ListUsersPage.PageFactory; import com.google.firebase.auth.UserRecord.CreateRequest; import com.google.firebase.auth.UserRecord.UpdateRequest; import com.google.firebase.auth.internal.FirebaseTokenFactory; import com.google.firebase.internal.CallableOperation; import com.google.firebase.internal.FirebaseService; import com.google.firebase.internal.NonNull; import com.google.firebase.internal.Nullable; import java.io.IOException; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; /** * This class is the entry point for all server-side Firebase Authentication actions. * * <p>You can get an instance of FirebaseAuth via {@link FirebaseAuth#getInstance(FirebaseApp)} and * then use it to perform a variety of authentication-related operations, including generating * custom tokens for use by client-side code, verifying Firebase ID Tokens received from clients, or * creating new FirebaseApp instances that are scoped to a particular authentication UID. */ public class FirebaseAuth { private static final String SERVICE_ID = FirebaseAuth.class.getName(); private static final String ERROR_CUSTOM_TOKEN = "ERROR_CUSTOM_TOKEN"; private final Object lock = new Object(); private final AtomicBoolean destroyed = new AtomicBoolean(false); private final FirebaseApp firebaseApp; private final Supplier<FirebaseTokenFactory> tokenFactory; private final Supplier<? extends FirebaseTokenVerifier> idTokenVerifier; private final Supplier<? extends FirebaseTokenVerifier> cookieVerifier; private final Supplier<? extends FirebaseUserManager> userManager; private final JsonFactory jsonFactory; private FirebaseAuth(Builder builder) { this.firebaseApp = checkNotNull(builder.firebaseApp); this.tokenFactory = threadSafeMemoize(builder.tokenFactory); this.idTokenVerifier = threadSafeMemoize(builder.idTokenVerifier); this.cookieVerifier = threadSafeMemoize(builder.cookieVerifier); this.userManager = threadSafeMemoize(builder.userManager); this.jsonFactory = firebaseApp.getOptions().getJsonFactory(); } /** * Gets the FirebaseAuth instance for the default {@link FirebaseApp}. * * @return The FirebaseAuth instance for the default {@link FirebaseApp}. */ public static FirebaseAuth getInstance() { return FirebaseAuth.getInstance(FirebaseApp.getInstance()); } /** * Gets an instance of FirebaseAuth for a specific {@link FirebaseApp}. * * @param app The {@link FirebaseApp} to get a FirebaseAuth instance for. * @return A FirebaseAuth instance. */ public static synchronized FirebaseAuth getInstance(FirebaseApp app) { FirebaseAuthService service = ImplFirebaseTrampolines.getService(app, SERVICE_ID, FirebaseAuthService.class); if (service == null) { service = ImplFirebaseTrampolines.addService(app, new FirebaseAuthService(app)); } return service.getInstance(); } /** * Creates a new Firebase session cookie from the given ID token and options. The returned JWT * can be set as a server-side session cookie with a custom cookie policy. * * @param idToken The Firebase ID token to exchange for a session cookie. * @param options Additional options required to create the cookie. * @return A Firebase session cookie string. * @throws IllegalArgumentException If the ID token is null or empty, or if options is null. * @throws FirebaseAuthException If an error occurs while generating the session cookie. */ public String createSessionCookie( @NonNull String idToken, @NonNull SessionCookieOptions options) throws FirebaseAuthException { return createSessionCookieOp(idToken, options).call(); } /** * Similar to {@link #createSessionCookie(String, SessionCookieOptions)} but performs the * operation asynchronously. * * @param idToken The Firebase ID token to exchange for a session cookie. * @param options Additional options required to create the cookie. * @return An {@code ApiFuture} which will complete successfully with a session cookie string. * If an error occurs while generating the cookie or if the specified ID token is invalid, * the future throws a {@link FirebaseAuthException}. * @throws IllegalArgumentException If the ID token is null or empty, or if options is null. */ public ApiFuture<String> createSessionCookieAsync( @NonNull String idToken, @NonNull SessionCookieOptions options) { return createSessionCookieOp(idToken, options).callAsync(firebaseApp); } private CallableOperation<String, FirebaseAuthException> createSessionCookieOp( final String idToken, final SessionCookieOptions options) { checkNotDestroyed(); checkArgument(!Strings.isNullOrEmpty(idToken), "idToken must not be null or empty"); checkNotNull(options, "options must not be null"); final FirebaseUserManager userManager = getUserManager(); return new CallableOperation<String, FirebaseAuthException>() { @Override protected String execute() throws FirebaseAuthException { return userManager.createSessionCookie(idToken, options); } }; } /** * Parses and verifies a Firebase session cookie. * * <p>If verified successfully, returns a parsed version of the cookie from which the UID and the * other claims can be read. If the cookie is invalid, throws a {@link FirebaseAuthException}. * * <p>This method does not check whether the cookie has been revoked. See * {@link #verifySessionCookie(String, boolean)}. * * @param cookie A Firebase session cookie string to verify and parse. * @return A {@link FirebaseToken} representing the verified and decoded cookie. */ public FirebaseToken verifySessionCookie(String cookie) throws FirebaseAuthException { return verifySessionCookie(cookie, false); } /** * Parses and verifies a Firebase session cookie. * * <p>If {@code checkRevoked} is true, additionally verifies that the cookie has not been * revoked. * * <p>If verified successfully, returns a parsed version of the cookie from which the UID and the * other claims can be read. If the cookie is invalid or has been revoked while * {@code checkRevoked} is true, throws a {@link FirebaseAuthException}. * * @param cookie A Firebase session cookie string to verify and parse. * @param checkRevoked A boolean indicating whether to check if the cookie was explicitly * revoked. * @return A {@link FirebaseToken} representing the verified and decoded cookie. */ public FirebaseToken verifySessionCookie( String cookie, boolean checkRevoked) throws FirebaseAuthException { return verifySessionCookieOp(cookie, checkRevoked).call(); } /** * Similar to {@link #verifySessionCookie(String)} but performs the operation asynchronously. * * @param cookie A Firebase session cookie string to verify and parse. * @return An {@code ApiFuture} which will complete successfully with the parsed cookie, or * unsuccessfully with the failure Exception. */ public ApiFuture<FirebaseToken> verifySessionCookieAsync(String cookie) { return verifySessionCookieAsync(cookie, false); } /** * Similar to {@link #verifySessionCookie(String, boolean)} but performs the operation * asynchronously. * * @param cookie A Firebase session cookie string to verify and parse. * @param checkRevoked A boolean indicating whether to check if the cookie was explicitly * revoked. * @return An {@code ApiFuture} which will complete successfully with the parsed cookie, or * unsuccessfully with the failure Exception. */ public ApiFuture<FirebaseToken> verifySessionCookieAsync(String cookie, boolean checkRevoked) { return verifySessionCookieOp(cookie, checkRevoked).callAsync(firebaseApp); } private CallableOperation<FirebaseToken, FirebaseAuthException> verifySessionCookieOp( final String cookie, final boolean checkRevoked) { checkNotDestroyed(); checkArgument(!Strings.isNullOrEmpty(cookie), "Session cookie must not be null or empty"); final FirebaseTokenVerifier sessionCookieVerifier = getSessionCookieVerifier(checkRevoked); return new CallableOperation<FirebaseToken, FirebaseAuthException>() { @Override public FirebaseToken execute() throws FirebaseAuthException { return sessionCookieVerifier.verifyToken(cookie); } }; } @VisibleForTesting FirebaseTokenVerifier getSessionCookieVerifier(boolean checkRevoked) { FirebaseTokenVerifier verifier = cookieVerifier.get(); if (checkRevoked) { FirebaseUserManager userManager = getUserManager(); verifier = RevocationCheckDecorator.decorateSessionCookieVerifier(verifier, userManager); } return verifier; } /** * Creates a Firebase custom token for the given UID. This token can then be sent back to a client * application to be used with the * <a href="/docs/auth/admin/create-custom-tokens#sign_in_using_custom_tokens_on_clients">signInWithCustomToken</a> * authentication API. * * <p>{@link FirebaseApp} must have been initialized with service account credentials to use * call this method. * * @param uid The UID to store in the token. This identifies the user to other Firebase services * (Realtime Database, Firebase Auth, etc.). Should be less than 128 characters. * @return A Firebase custom token string. * @throws IllegalArgumentException If the specified uid is null or empty, or if the app has not * been initialized with service account credentials. * @throws FirebaseAuthException If an error occurs while generating the custom token. */ public String createCustomToken(@NonNull String uid) throws FirebaseAuthException { return createCustomToken(uid, null); } /** * Creates a Firebase custom token for the given UID, containing the specified additional * claims. This token can then be sent back to a client application to be used with the * <a href="/docs/auth/admin/create-custom-tokens#sign_in_using_custom_tokens_on_clients">signInWithCustomToken</a> * authentication API. * * <p>This method attempts to generate a token using: * <ol> * <li>the private key of {@link FirebaseApp}'s service account credentials, if provided at * initialization. * <li>the <a href="https://cloud.google.com/iam/reference/rest/v1/projects.serviceAccounts/signBlob">IAM service</a> * if a service account email was specified via * {@link com.google.firebase.FirebaseOptions.Builder#setServiceAccountId(String)}. * <li>the <a href="https://cloud.google.com/appengine/docs/standard/java/appidentity/">App Identity * service</a> if the code is deployed in the Google App Engine standard environment. * <li>the <a href="https://cloud.google.com/compute/docs/storing-retrieving-metadata"> * local Metadata server</a> if the code is deployed in a different GCP-managed environment * like Google Compute Engine. * </ol> * * <p>This method throws an exception when all the above fail. * * @param uid The UID to store in the token. This identifies the user to other Firebase services * (Realtime Database, Firebase Auth, etc.). Should be less than 128 characters. * @param developerClaims Additional claims to be stored in the token (and made available to * security rules in Database, Storage, etc.). These must be able to be serialized to JSON * (e.g. contain only Maps, Arrays, Strings, Booleans, Numbers, etc.) * @return A Firebase custom token string. * @throws IllegalArgumentException If the specified uid is null or empty. * @throws IllegalStateException If the SDK fails to discover a viable approach for signing * tokens. * @throws FirebaseAuthException If an error occurs while generating the custom token. */ public String createCustomToken(@NonNull String uid, @Nullable Map<String, Object> developerClaims) throws FirebaseAuthException { return createCustomTokenOp(uid, developerClaims).call(); } /** * Similar to {@link #createCustomToken(String)} but performs the operation asynchronously. * * @param uid The UID to store in the token. This identifies the user to other Firebase services * (Realtime Database, Firebase Auth, etc.). Should be less than 128 characters. * @return An {@code ApiFuture} which will complete successfully with the created Firebase custom * token, or unsuccessfully with the failure Exception. * @throws IllegalArgumentException If the specified uid is null or empty, or if the app has not * been initialized with service account credentials. */ public ApiFuture<String> createCustomTokenAsync(@NonNull String uid) { return createCustomTokenAsync(uid, null); } /** * Similar to {@link #createCustomToken(String, Map)} but performs the operation * asynchronously. * * @param uid The UID to store in the token. This identifies the user to other Firebase services * (Realtime Database, Storage, etc.). Should be less than 128 characters. * @param developerClaims Additional claims to be stored in the token (and made available to * security rules in Database, Storage, etc.). These must be able to be serialized to JSON * (e.g. contain only Maps, Arrays, Strings, Booleans, Numbers, etc.) * @return An {@code ApiFuture} which will complete successfully with the created Firebase custom * token, or unsuccessfully with the failure Exception. * @throws IllegalArgumentException If the specified uid is null or empty, or if the app has not * been initialized with service account credentials. */ public ApiFuture<String> createCustomTokenAsync( @NonNull String uid, @Nullable Map<String, Object> developerClaims) { return createCustomTokenOp(uid, developerClaims).callAsync(firebaseApp); } private CallableOperation<String, FirebaseAuthException> createCustomTokenOp( final String uid, final Map<String, Object> developerClaims) { checkNotDestroyed(); checkArgument(!Strings.isNullOrEmpty(uid), "uid must not be null or empty"); final FirebaseTokenFactory tokenFactory = this.tokenFactory.get(); return new CallableOperation<String, FirebaseAuthException>() { @Override public String execute() throws FirebaseAuthException { try { return tokenFactory.createSignedCustomAuthTokenForUser(uid, developerClaims); } catch (IOException e) { throw new FirebaseAuthException(ERROR_CUSTOM_TOKEN, "Failed to generate a custom token", e); } } }; } /** * Parses and verifies a Firebase ID Token. * * <p>A Firebase application can identify itself to a trusted backend server by sending its * Firebase ID Token (accessible via the {@code getToken} API in the Firebase Authentication * client) with its requests. The backend server can then use the {@code verifyIdToken()} method * to verify that the token is valid. This method ensures that the token is correctly signed, * has not expired, and it was issued to the Firebase project associated with this * {@link FirebaseAuth} instance. * * <p>This method does not check whether a token has been revoked. Use * {@link #verifyIdToken(String, boolean)} to perform an additional revocation check. * * @param token A Firebase ID token string to parse and verify. * @return A {@link FirebaseToken} representing the verified and decoded token. * @throws IllegalArgumentException If the token is null, empty, or if the {@link FirebaseApp} * instance does not have a project ID associated with it. * @throws FirebaseAuthException If an error occurs while parsing or validating the token. */ public FirebaseToken verifyIdToken(@NonNull String token) throws FirebaseAuthException { return verifyIdToken(token, false); } /** * Parses and verifies a Firebase ID Token. * * <p>A Firebase application can identify itself to a trusted backend server by sending its * Firebase ID Token (accessible via the {@code getToken} API in the Firebase Authentication * client) with its requests. The backend server can then use the {@code verifyIdToken()} method * to verify that the token is valid. This method ensures that the token is correctly signed, * has not expired, and it was issued to the Firebase project associated with this * {@link FirebaseAuth} instance. * * <p>If {@code checkRevoked} is set to true, this method performs an additional check to see * if the ID token has been revoked since it was issues. This requires making an additional * remote API call. * * @param token A Firebase ID token string to parse and verify. * @param checkRevoked A boolean denoting whether to check if the tokens were revoked. * @return A {@link FirebaseToken} representing the verified and decoded token. * @throws IllegalArgumentException If the token is null, empty, or if the {@link FirebaseApp} * instance does not have a project ID associated with it. * @throws FirebaseAuthException If an error occurs while parsing or validating the token. */ public FirebaseToken verifyIdToken( @NonNull String token, boolean checkRevoked) throws FirebaseAuthException { return verifyIdTokenOp(token, checkRevoked).call(); } /** * Similar to {@link #verifyIdToken(String)} but performs the operation asynchronously. * * @param token A Firebase ID Token to verify and parse. * @return An {@code ApiFuture} which will complete successfully with the parsed token, or * unsuccessfully with a {@link FirebaseAuthException}. * @throws IllegalArgumentException If the token is null, empty, or if the {@link FirebaseApp} * instance does not have a project ID associated with it. */ public ApiFuture<FirebaseToken> verifyIdTokenAsync(@NonNull String token) { return verifyIdTokenAsync(token, false); } /** * Similar to {@link #verifyIdToken(String, boolean)} but performs the operation asynchronously. * * @param token A Firebase ID Token to verify and parse. * @param checkRevoked A boolean denoting whether to check if the tokens were revoked. * @return An {@code ApiFuture} which will complete successfully with the parsed token, or * unsuccessfully with a {@link FirebaseAuthException}. * @throws IllegalArgumentException If the token is null, empty, or if the {@link FirebaseApp} * instance does not have a project ID associated with it. */ public ApiFuture<FirebaseToken> verifyIdTokenAsync(@NonNull String token, boolean checkRevoked) { return verifyIdTokenOp(token, checkRevoked).callAsync(firebaseApp); } private CallableOperation<FirebaseToken, FirebaseAuthException> verifyIdTokenOp( final String token, final boolean checkRevoked) { checkNotDestroyed(); checkArgument(!Strings.isNullOrEmpty(token), "ID token must not be null or empty"); final FirebaseTokenVerifier verifier = getIdTokenVerifier(checkRevoked); return new CallableOperation<FirebaseToken, FirebaseAuthException>() { @Override protected FirebaseToken execute() throws FirebaseAuthException { return verifier.verifyToken(token); } }; } @VisibleForTesting FirebaseTokenVerifier getIdTokenVerifier(boolean checkRevoked) { FirebaseTokenVerifier verifier = idTokenVerifier.get(); if (checkRevoked) { FirebaseUserManager userManager = getUserManager(); verifier = RevocationCheckDecorator.decorateIdTokenVerifier(verifier, userManager); } return verifier; } /** * Revokes all refresh tokens for the specified user. * * <p>Updates the user's tokensValidAfterTimestamp to the current UTC time expressed in * milliseconds since the epoch and truncated to 1 second accuracy. It is important that the * server on which this is called has its clock set correctly and synchronized. * * <p>While this will revoke all sessions for a specified user and disable any new ID tokens for * existing sessions from getting minted, existing ID tokens may remain active until their * natural expiration (one hour). * To verify that ID tokens are revoked, use {@link #verifyIdTokenAsync(String, boolean)}. * * @param uid The user id for which tokens are revoked. * @throws IllegalArgumentException If the user ID is null or empty. * @throws FirebaseAuthException If an error occurs while revoking tokens. */ public void revokeRefreshTokens(@NonNull String uid) throws FirebaseAuthException { revokeRefreshTokensOp(uid).call(); } /** * Similar to {@link #revokeRefreshTokens(String)} but performs the operation asynchronously. * * @param uid The user id for which tokens are revoked. * @return An {@code ApiFuture} which will complete successfully or fail with a * {@link FirebaseAuthException} in the event of an error. * @throws IllegalArgumentException If the user ID is null or empty. */ public ApiFuture<Void> revokeRefreshTokensAsync(@NonNull String uid) { return revokeRefreshTokensOp(uid).callAsync(firebaseApp); } private CallableOperation<Void, FirebaseAuthException> revokeRefreshTokensOp(final String uid) { checkNotDestroyed(); checkArgument(!Strings.isNullOrEmpty(uid), "uid must not be null or empty"); final FirebaseUserManager userManager = getUserManager(); return new CallableOperation<Void, FirebaseAuthException>() { @Override protected Void execute() throws FirebaseAuthException { int currentTimeSeconds = (int) (System.currentTimeMillis() / 1000); UpdateRequest request = new UpdateRequest(uid).setValidSince(currentTimeSeconds); userManager.updateUser(request, jsonFactory); return null; } }; } /** * Gets the user data corresponding to the specified user ID. * * @param uid A user ID string. * @return A {@link UserRecord} instance. * @throws IllegalArgumentException If the user ID string is null or empty. * @throws FirebaseAuthException If an error occurs while retrieving user data. */ public UserRecord getUser(@NonNull String uid) throws FirebaseAuthException { return getUserOp(uid).call(); } /** * Similar to {@link #getUser(String)} but performs the operation asynchronously. * * @param uid A user ID string. * @return An {@code ApiFuture} which will complete successfully with a {@link UserRecord} * instance. If an error occurs while retrieving user data or if the specified user ID does * not exist, the future throws a {@link FirebaseAuthException}. * @throws IllegalArgumentException If the user ID string is null or empty. */ public ApiFuture<UserRecord> getUserAsync(@NonNull String uid) { return getUserOp(uid).callAsync(firebaseApp); } private CallableOperation<UserRecord, FirebaseAuthException> getUserOp(final String uid) { checkNotDestroyed(); checkArgument(!Strings.isNullOrEmpty(uid), "uid must not be null or empty"); final FirebaseUserManager userManager = getUserManager(); return new CallableOperation<UserRecord, FirebaseAuthException>() { @Override protected UserRecord execute() throws FirebaseAuthException { return userManager.getUserById(uid); } }; } /** * Gets the user data corresponding to the specified user email. * * @param email A user email address string. * @return A {@link UserRecord} instance. * @throws IllegalArgumentException If the email is null or empty. * @throws FirebaseAuthException If an error occurs while retrieving user data. */ public UserRecord getUserByEmail(@NonNull String email) throws FirebaseAuthException { return getUserByEmailOp(email).call(); } /** * Similar to {@link #getUserByEmail(String)} but performs the operation asynchronously. * * @param email A user email address string. * @return An {@code ApiFuture} which will complete successfully with a {@link UserRecord} * instance. If an error occurs while retrieving user data or if the email address does not * correspond to a user, the future throws a {@link FirebaseAuthException}. * @throws IllegalArgumentException If the email is null or empty. */ public ApiFuture<UserRecord> getUserByEmailAsync(@NonNull String email) { return getUserByEmailOp(email).callAsync(firebaseApp); } private CallableOperation<UserRecord, FirebaseAuthException> getUserByEmailOp( final String email) { checkNotDestroyed(); checkArgument(!Strings.isNullOrEmpty(email), "email must not be null or empty"); final FirebaseUserManager userManager = getUserManager(); return new CallableOperation<UserRecord, FirebaseAuthException>() { @Override protected UserRecord execute() throws FirebaseAuthException { return userManager.getUserByEmail(email); } }; } /** * Gets the user data corresponding to the specified user phone number. * * @param phoneNumber A user phone number string. * @return A a {@link UserRecord} instance. * @throws IllegalArgumentException If the phone number is null or empty. * @throws FirebaseAuthException If an error occurs while retrieving user data. */ public UserRecord getUserByPhoneNumber(@NonNull String phoneNumber) throws FirebaseAuthException { return getUserByPhoneNumberOp(phoneNumber).call(); } /** * Gets the user data corresponding to the specified user phone number. * * @param phoneNumber A user phone number string. * @return An {@code ApiFuture} which will complete successfully with a {@link UserRecord} * instance. If an error occurs while retrieving user data or if the phone number does not * correspond to a user, the future throws a {@link FirebaseAuthException}. * @throws IllegalArgumentException If the phone number is null or empty. */ public ApiFuture<UserRecord> getUserByPhoneNumberAsync(@NonNull String phoneNumber) { return getUserByPhoneNumberOp(phoneNumber).callAsync(firebaseApp); } private CallableOperation<UserRecord, FirebaseAuthException> getUserByPhoneNumberOp( final String phoneNumber) { checkNotDestroyed(); checkArgument(!Strings.isNullOrEmpty(phoneNumber), "phone number must not be null or empty"); final FirebaseUserManager userManager = getUserManager(); return new CallableOperation<UserRecord, FirebaseAuthException>() { @Override protected UserRecord execute() throws FirebaseAuthException { return userManager.getUserByPhoneNumber(phoneNumber); } }; } /** * Gets the user data corresponding to the specified identifiers. * * <p>There are no ordering guarantees; in particular, the nth entry in the users result list is * not guaranteed to correspond to the nth entry in the input parameters list. * * <p>A maximum of 100 identifiers may be specified. If more than 100 identifiers are * supplied, this method throws an {@link IllegalArgumentException}. * * @param identifiers The identifiers used to indicate which user records should be returned. Must * have 100 or fewer entries. * @return The corresponding user records. * @throws IllegalArgumentException If any of the identifiers are invalid or if more than 100 * identifiers are specified. * @throws NullPointerException If the identifiers parameter is null. * @throws FirebaseAuthException If an error occurs while retrieving user data. */ public GetUsersResult getUsers(@NonNull Collection<UserIdentifier> identifiers) throws FirebaseAuthException { return getUsersOp(identifiers).call(); } /** * Gets the user data corresponding to the specified identifiers. * * <p>There are no ordering guarantees; in particular, the nth entry in the users result list is * not guaranteed to correspond to the nth entry in the input parameters list. * * <p>A maximum of 100 identifiers may be specified. If more than 100 identifiers are * supplied, this method throws an {@link IllegalArgumentException}. * * @param identifiers The identifiers used to indicate which user records should be returned. * Must have 100 or fewer entries. * @return An {@code ApiFuture} that resolves to the corresponding user records. * @throws IllegalArgumentException If any of the identifiers are invalid or if more than 100 * identifiers are specified. * @throws NullPointerException If the identifiers parameter is null. */ public ApiFuture<GetUsersResult> getUsersAsync(@NonNull Collection<UserIdentifier> identifiers) { return getUsersOp(identifiers).callAsync(firebaseApp); } private CallableOperation<GetUsersResult, FirebaseAuthException> getUsersOp( @NonNull final Collection<UserIdentifier> identifiers) { checkNotDestroyed(); checkNotNull(identifiers, "identifiers must not be null"); checkArgument(identifiers.size() <= FirebaseUserManager.MAX_GET_ACCOUNTS_BATCH_SIZE, "identifiers parameter must have <= " + FirebaseUserManager.MAX_GET_ACCOUNTS_BATCH_SIZE + " entries."); final FirebaseUserManager userManager = getUserManager(); return new CallableOperation<GetUsersResult, FirebaseAuthException>() { @Override protected GetUsersResult execute() throws FirebaseAuthException { Set<UserRecord> users = userManager.getAccountInfo(identifiers); Set<UserIdentifier> notFound = new HashSet<>(); for (UserIdentifier id : identifiers) { if (!isUserFound(id, users)) { notFound.add(id); } } return new GetUsersResult(users, notFound); } }; } private boolean isUserFound(UserIdentifier id, Collection<UserRecord> userRecords) { for (UserRecord userRecord : userRecords) { if (id.matches(userRecord)) { return true; } } return false; } /** * Gets a page of users starting from the specified {@code pageToken}. Page size is * limited to 1000 users. * * @param pageToken A non-empty page token string, or null to retrieve the first page of users. * @return A {@link ListUsersPage} instance. * @throws IllegalArgumentException If the specified page token is empty. * @throws FirebaseAuthException If an error occurs while retrieving user data. */ public ListUsersPage listUsers(@Nullable String pageToken) throws FirebaseAuthException { return listUsers(pageToken, FirebaseUserManager.MAX_LIST_USERS_RESULTS); } /** * Gets a page of users starting from the specified {@code pageToken}. * * @param pageToken A non-empty page token string, or null to retrieve the first page of users. * @param maxResults Maximum number of users to include in the returned page. This may not * exceed 1000. * @return A {@link ListUsersPage} instance. * @throws IllegalArgumentException If the specified page token is empty, or max results value * is invalid. * @throws FirebaseAuthException If an error occurs while retrieving user data. */ public ListUsersPage listUsers( @Nullable String pageToken, int maxResults) throws FirebaseAuthException { return listUsersOp(pageToken, maxResults).call(); } /** * Similar to {@link #listUsers(String)} but performs the operation asynchronously. * * @param pageToken A non-empty page token string, or null to retrieve the first page of users. * @return An {@code ApiFuture} which will complete successfully with a {@link ListUsersPage} * instance. If an error occurs while retrieving user data, the future throws an exception. * @throws IllegalArgumentException If the specified page token is empty. */ public ApiFuture<ListUsersPage> listUsersAsync(@Nullable String pageToken) { return listUsersAsync(pageToken, FirebaseUserManager.MAX_LIST_USERS_RESULTS); } /** * Similar to {@link #listUsers(String, int)} but performs the operation asynchronously. * * @param pageToken A non-empty page token string, or null to retrieve the first page of users. * @param maxResults Maximum number of users to include in the returned page. This may not * exceed 1000. * @return An {@code ApiFuture} which will complete successfully with a {@link ListUsersPage} * instance. If an error occurs while retrieving user data, the future throws an exception. * @throws IllegalArgumentException If the specified page token is empty, or max results value * is invalid. */ public ApiFuture<ListUsersPage> listUsersAsync(@Nullable String pageToken, int maxResults) { return listUsersOp(pageToken, maxResults).callAsync(firebaseApp); } private CallableOperation<ListUsersPage, FirebaseAuthException> listUsersOp( @Nullable final String pageToken, final int maxResults) { checkNotDestroyed(); final FirebaseUserManager userManager = getUserManager(); final PageFactory factory = new PageFactory( new DefaultUserSource(userManager, jsonFactory), maxResults, pageToken); return new CallableOperation<ListUsersPage, FirebaseAuthException>() { @Override protected ListUsersPage execute() throws FirebaseAuthException { return factory.create(); } }; } /** * Creates a new user account with the attributes contained in the specified * {@link CreateRequest}. * * @param request A non-null {@link CreateRequest} instance. * @return A {@link UserRecord} instance corresponding to the newly created account. * @throws NullPointerException if the provided request is null. * @throws FirebaseAuthException if an error occurs while creating the user account. */ public UserRecord createUser(@NonNull CreateRequest request) throws FirebaseAuthException { return createUserOp(request).call(); } /** * Similar to {@link #createUser(CreateRequest)} but performs the operation asynchronously. * * @param request A non-null {@link CreateRequest} instance. * @return An {@code ApiFuture} which will complete successfully with a {@link UserRecord} * instance corresponding to the newly created account. If an error occurs while creating the * user account, the future throws a {@link FirebaseAuthException}. * @throws NullPointerException if the provided request is null. */ public ApiFuture<UserRecord> createUserAsync(@NonNull CreateRequest request) { return createUserOp(request).callAsync(firebaseApp); } private CallableOperation<UserRecord, FirebaseAuthException> createUserOp( final CreateRequest request) { checkNotDestroyed(); checkNotNull(request, "create request must not be null"); final FirebaseUserManager userManager = getUserManager(); return new CallableOperation<UserRecord, FirebaseAuthException>() { @Override protected UserRecord execute() throws FirebaseAuthException { String uid = userManager.createUser(request); return userManager.getUserById(uid); } }; } /** * Updates an existing user account with the attributes contained in the specified * {@link UpdateRequest}. * * @param request A non-null {@link UpdateRequest} instance. * @return A {@link UserRecord} instance corresponding to the updated user account. * account, the task fails with a {@link FirebaseAuthException}. * @throws NullPointerException if the provided update request is null. * @throws FirebaseAuthException if an error occurs while updating the user account. */ public UserRecord updateUser(@NonNull UpdateRequest request) throws FirebaseAuthException { return updateUserOp(request).call(); } /** * Similar to {@link #updateUser(UpdateRequest)} but performs the operation asynchronously. * * @param request A non-null {@link UpdateRequest} instance. * @return An {@code ApiFuture} which will complete successfully with a {@link UserRecord} * instance corresponding to the updated user account. If an error occurs while updating the * user account, the future throws a {@link FirebaseAuthException}. */ public ApiFuture<UserRecord> updateUserAsync(@NonNull UpdateRequest request) { return updateUserOp(request).callAsync(firebaseApp); } private CallableOperation<UserRecord, FirebaseAuthException> updateUserOp( final UpdateRequest request) { checkNotDestroyed(); checkNotNull(request, "update request must not be null"); final FirebaseUserManager userManager = getUserManager(); return new CallableOperation<UserRecord, FirebaseAuthException>() { @Override protected UserRecord execute() throws FirebaseAuthException { userManager.updateUser(request, jsonFactory); return userManager.getUserById(request.getUid()); } }; } /** * Sets the specified custom claims on an existing user account. A null claims value removes * any claims currently set on the user account. The claims should serialize into a valid JSON * string. The serialized claims must not be larger than 1000 characters. * * @param uid A user ID string. * @param claims A map of custom claims or null. * @throws FirebaseAuthException If an error occurs while updating custom claims. * @throws IllegalArgumentException If the user ID string is null or empty, or the claims * payload is invalid or too large. */ public void setCustomUserClaims(@NonNull String uid, @Nullable Map<String, Object> claims) throws FirebaseAuthException { setCustomUserClaimsOp(uid, claims).call(); } /** * @deprecated Use {@link #setCustomUserClaims(String, Map)} instead. */ public void setCustomClaims(@NonNull String uid, @Nullable Map<String, Object> claims) throws FirebaseAuthException { setCustomUserClaims(uid, claims); } /** * Similar to {@link #setCustomUserClaims(String, Map)} but performs the operation asynchronously. * * @param uid A user ID string. * @param claims A map of custom claims or null. * @return An {@code ApiFuture} which will complete successfully when the user account has been * updated. If an error occurs while deleting the user account, the future throws a * {@link FirebaseAuthException}. * @throws IllegalArgumentException If the user ID string is null or empty. */ public ApiFuture<Void> setCustomUserClaimsAsync( @NonNull String uid, @Nullable Map<String, Object> claims) { return setCustomUserClaimsOp(uid, claims).callAsync(firebaseApp); } private CallableOperation<Void, FirebaseAuthException> setCustomUserClaimsOp( final String uid, final Map<String, Object> claims) { checkNotDestroyed(); checkArgument(!Strings.isNullOrEmpty(uid), "uid must not be null or empty"); final FirebaseUserManager userManager = getUserManager(); return new CallableOperation<Void, FirebaseAuthException>() { @Override protected Void execute() throws FirebaseAuthException { final UpdateRequest request = new UpdateRequest(uid).setCustomClaims(claims); userManager.updateUser(request, jsonFactory); return null; } }; } /** * Deletes the user identified by the specified user ID. * * @param uid A user ID string. * @throws IllegalArgumentException If the user ID string is null or empty. * @throws FirebaseAuthException If an error occurs while deleting the user. */ public void deleteUser(@NonNull String uid) throws FirebaseAuthException { deleteUserOp(uid).call(); } /** * Similar to {@link #deleteUser(String)} but performs the operation asynchronously. * * @param uid A user ID string. * @return An {@code ApiFuture} which will complete successfully when the specified user account * has been deleted. If an error occurs while deleting the user account, the future throws a * {@link FirebaseAuthException}. * @throws IllegalArgumentException If the user ID string is null or empty. */ public ApiFuture<Void> deleteUserAsync(String uid) { return deleteUserOp(uid).callAsync(firebaseApp); } private CallableOperation<Void, FirebaseAuthException> deleteUserOp(final String uid) { checkNotDestroyed(); checkArgument(!Strings.isNullOrEmpty(uid), "uid must not be null or empty"); final FirebaseUserManager userManager = getUserManager(); return new CallableOperation<Void, FirebaseAuthException>() { @Override protected Void execute() throws FirebaseAuthException { userManager.deleteUser(uid); return null; } }; } /** * Deletes the users specified by the given identifiers. * * <p>Deleting a non-existing user does not generate an error (the method is idempotent). * Non-existing users are considered to be successfully deleted and are therefore included in the * DeleteUsersResult.getSuccessCount() value. * * <p>A maximum of 1000 identifiers may be supplied. If more than 1000 identifiers are * supplied, this method throws an {@link IllegalArgumentException}. * * <p>This API has a rate limit of 1 QPS. Exceeding the limit may result in a quota exceeded * error. If you want to delete more than 1000 users, we suggest adding a delay to ensure you * don't exceed this limit. * * @param uids The uids of the users to be deleted. Must have <= 1000 entries. * @return The total number of successful/failed deletions, as well as the array of errors that * correspond to the failed deletions. * @throw IllegalArgumentException If any of the identifiers are invalid or if more than 1000 * identifiers are specified. * @throws FirebaseAuthException If an error occurs while deleting users. */ public DeleteUsersResult deleteUsers(List<String> uids) throws FirebaseAuthException { return deleteUsersOp(uids).call(); } /** * Similar to {@link #deleteUsers(List)} but performs the operation asynchronously. * * @param uids The uids of the users to be deleted. Must have <= 1000 entries. * @return An {@code ApiFuture} that resolves to the total number of successful/failed * deletions, as well as the array of errors that correspond to the failed deletions. If an * error occurs while deleting the user account, the future throws a * {@link FirebaseAuthException}. * @throw IllegalArgumentException If any of the identifiers are invalid or if more than 1000 * identifiers are specified. */ public ApiFuture<DeleteUsersResult> deleteUsersAsync(List<String> uids) { return deleteUsersOp(uids).callAsync(firebaseApp); } private CallableOperation<DeleteUsersResult, FirebaseAuthException> deleteUsersOp( final List<String> uids) { checkNotDestroyed(); checkNotNull(uids, "uids must not be null"); for (String uid : uids) { UserRecord.checkUid(uid); } checkArgument(uids.size() <= FirebaseUserManager.MAX_DELETE_ACCOUNTS_BATCH_SIZE, "uids parameter must have <= " + FirebaseUserManager.MAX_DELETE_ACCOUNTS_BATCH_SIZE + " entries."); final FirebaseUserManager userManager = getUserManager(); return new CallableOperation<DeleteUsersResult, FirebaseAuthException>() { @Override protected DeleteUsersResult execute() throws FirebaseAuthException { return userManager.deleteUsers(uids); } }; } /** * Imports the provided list of users into Firebase Auth. You can import a maximum of 1000 users * at a time. This operation is optimized for bulk imports and does not check identifier * uniqueness which could result in duplications. * * <p>{@link UserImportOptions} is required to import users with passwords. See * {@link #importUsers(List, UserImportOptions)}. * * @param users A non-empty list of users to be imported. Length must not exceed 1000. * @return A {@link UserImportResult} instance. * @throws IllegalArgumentException If the users list is null, empty or has more than 1000 * elements. Or if at least one user specifies a password. * @throws FirebaseAuthException If an error occurs while importing users. */ public UserImportResult importUsers(List<ImportUserRecord> users) throws FirebaseAuthException { return importUsers(users, null); } /** * Imports the provided list of users into Firebase Auth. At most 1000 users can be imported at a * time. This operation is optimized for bulk imports and will ignore checks on identifier * uniqueness which could result in duplications. * * @param users A non-empty list of users to be imported. Length must not exceed 1000. * @param options a {@link UserImportOptions} instance or null. Required when importing users * with passwords. * @return A {@link UserImportResult} instance. * @throws IllegalArgumentException If the users list is null, empty or has more than 1000 * elements. Or if at least one user specifies a password, and options is null. * @throws FirebaseAuthException If an error occurs while importing users. */ public UserImportResult importUsers(List<ImportUserRecord> users, @Nullable UserImportOptions options) throws FirebaseAuthException { return importUsersOp(users, options).call(); } /** * Similar to {@link #importUsers(List)} but performs the operation asynchronously. * * @param users A non-empty list of users to be imported. Length must not exceed 1000. * @return An {@code ApiFuture} which will complete successfully when the user accounts are * imported. If an error occurs while importing the users, the future throws a * {@link FirebaseAuthException}. * @throws IllegalArgumentException If the users list is null, empty or has more than 1000 * elements. Or if at least one user specifies a password. */ public ApiFuture<UserImportResult> importUsersAsync(List<ImportUserRecord> users) { return importUsersAsync(users, null); } /** * Similar to {@link #importUsers(List, UserImportOptions)} but performs the operation * asynchronously. * * @param users A non-empty list of users to be imported. Length must not exceed 1000. * @param options a {@link UserImportOptions} instance or null. Required when importing users * with passwords. * @return An {@code ApiFuture} which will complete successfully when the user accounts are * imported. If an error occurs while importing the users, the future throws a * {@link FirebaseAuthException}. * @throws IllegalArgumentException If the users list is null, empty or has more than 1000 * elements. Or if at least one user specifies a password, and options is null. */ public ApiFuture<UserImportResult> importUsersAsync(List<ImportUserRecord> users, @Nullable UserImportOptions options) { return importUsersOp(users, options).callAsync(firebaseApp); } private CallableOperation<UserImportResult, FirebaseAuthException> importUsersOp( final List<ImportUserRecord> users, final UserImportOptions options) { checkNotDestroyed(); final UserImportRequest request = new UserImportRequest(users, options, jsonFactory); final FirebaseUserManager userManager = getUserManager(); return new CallableOperation<UserImportResult, FirebaseAuthException>() { @Override protected UserImportResult execute() throws FirebaseAuthException { return userManager.importUsers(request); } }; } /** * Generates the out-of-band email action link for password reset flows for the specified email * address. * * @param email The email of the user whose password is to be reset. * @return A password reset link. * @throws IllegalArgumentException If the email address is null or empty. * @throws FirebaseAuthException If an error occurs while generating the link. */ public String generatePasswordResetLink(@NonNull String email) throws FirebaseAuthException { return generatePasswordResetLink(email, null); } /** * Generates the out-of-band email action link for password reset flows for the specified email * address. * * @param email The email of the user whose password is to be reset. * @param settings The action code settings object which defines whether * the link is to be handled by a mobile app and the additional state information to be * passed in the deep link. * @return A password reset link. * @throws IllegalArgumentException If the email address is null or empty. * @throws FirebaseAuthException If an error occurs while generating the link. */ public String generatePasswordResetLink( @NonNull String email, @Nullable ActionCodeSettings settings) throws FirebaseAuthException { return generateEmailActionLinkOp(EmailLinkType.PASSWORD_RESET, email, settings).call(); } /** * Similar to {@link #generatePasswordResetLink(String)} but performs the operation * asynchronously. * * @param email The email of the user whose password is to be reset. * @return An {@code ApiFuture} which will complete successfully with the generated email action * link. If an error occurs while generating the link, the future throws a * {@link FirebaseAuthException}. * @throws IllegalArgumentException If the email address is null or empty. */ public ApiFuture<String> generatePasswordResetLinkAsync(@NonNull String email) { return generatePasswordResetLinkAsync(email, null); } /** * Similar to {@link #generatePasswordResetLink(String, ActionCodeSettings)} but performs the * operation asynchronously. * * @param email The email of the user whose password is to be reset. * @param settings The action code settings object which defines whether * the link is to be handled by a mobile app and the additional state information to be * passed in the deep link. * @return An {@code ApiFuture} which will complete successfully with the generated email action * link. If an error occurs while generating the link, the future throws a * {@link FirebaseAuthException}. * @throws IllegalArgumentException If the email address is null or empty. */ public ApiFuture<String> generatePasswordResetLinkAsync( @NonNull String email, @Nullable ActionCodeSettings settings) { return generateEmailActionLinkOp(EmailLinkType.PASSWORD_RESET, email, settings) .callAsync(firebaseApp); } /** * Generates the out-of-band email action link for email verification flows for the specified * email address. * * @param email The email of the user to be verified. * @return An email verification link. * @throws IllegalArgumentException If the email address is null or empty. * @throws FirebaseAuthException If an error occurs while generating the link. */ public String generateEmailVerificationLink(@NonNull String email) throws FirebaseAuthException { return generateEmailVerificationLink(email, null); } /** * Generates the out-of-band email action link for email verification flows for the specified * email address, using the action code settings provided. * * @param email The email of the user to be verified. * @return An email verification link. * @throws IllegalArgumentException If the email address is null or empty. * @throws FirebaseAuthException If an error occurs while generating the link. */ public String generateEmailVerificationLink( @NonNull String email, @Nullable ActionCodeSettings settings) throws FirebaseAuthException { return generateEmailActionLinkOp(EmailLinkType.VERIFY_EMAIL, email, settings).call(); } /** * Similar to {@link #generateEmailVerificationLink(String)} but performs the * operation asynchronously. * * @param email The email of the user to be verified. * @return An {@code ApiFuture} which will complete successfully with the generated email action * link. If an error occurs while generating the link, the future throws a * {@link FirebaseAuthException}. * @throws IllegalArgumentException If the email address is null or empty. */ public ApiFuture<String> generateEmailVerificationLinkAsync(@NonNull String email) { return generateEmailVerificationLinkAsync(email, null); } /** * Similar to {@link #generateEmailVerificationLink(String, ActionCodeSettings)} but performs the * operation asynchronously. * * @param email The email of the user to be verified. * @param settings The action code settings object which defines whether * the link is to be handled by a mobile app and the additional state information to be * passed in the deep link. * @return An {@code ApiFuture} which will complete successfully with the generated email action * link. If an error occurs while generating the link, the future throws a * {@link FirebaseAuthException}. * @throws IllegalArgumentException If the email address is null or empty. */ public ApiFuture<String> generateEmailVerificationLinkAsync( @NonNull String email, @Nullable ActionCodeSettings settings) { return generateEmailActionLinkOp(EmailLinkType.VERIFY_EMAIL, email, settings) .callAsync(firebaseApp); } /** * Generates the out-of-band email action link for email link sign-in flows, using the action * code settings provided. * * @param email The email of the user signing in. * @param settings The action code settings object which defines whether * the link is to be handled by a mobile app and the additional state information to be * passed in the deep link. * @return An email verification link. * @throws IllegalArgumentException If the email address is null or empty. * @throws FirebaseAuthException If an error occurs while generating the link. */ public String generateSignInWithEmailLink( @NonNull String email, @NonNull ActionCodeSettings settings) throws FirebaseAuthException { return generateEmailActionLinkOp(EmailLinkType.EMAIL_SIGNIN, email, settings).call(); } /** * Similar to {@link #generateSignInWithEmailLink(String, ActionCodeSettings)} but performs the * operation asynchronously. * * @param email The email of the user signing in. * @param settings The action code settings object which defines whether * the link is to be handled by a mobile app and the additional state information to be * passed in the deep link. * @return An {@code ApiFuture} which will complete successfully with the generated email action * link. If an error occurs while generating the link, the future throws a * {@link FirebaseAuthException}. * @throws IllegalArgumentException If the email address is null or empty. * @throws NullPointerException If the settings is null. */ public ApiFuture<String> generateSignInWithEmailLinkAsync( String email, @NonNull ActionCodeSettings settings) { return generateEmailActionLinkOp(EmailLinkType.EMAIL_SIGNIN, email, settings) .callAsync(firebaseApp); } @VisibleForTesting FirebaseUserManager getUserManager() { return this.userManager.get(); } private CallableOperation<String, FirebaseAuthException> generateEmailActionLinkOp( final EmailLinkType type, final String email, final ActionCodeSettings settings) { checkNotDestroyed(); checkArgument(!Strings.isNullOrEmpty(email), "email must not be null or empty"); if (type == EmailLinkType.EMAIL_SIGNIN) { checkNotNull(settings, "ActionCodeSettings must not be null when generating sign-in links"); } final FirebaseUserManager userManager = getUserManager(); return new CallableOperation<String, FirebaseAuthException>() { @Override protected String execute() throws FirebaseAuthException { return userManager.getEmailActionLink(type, email, settings); } }; } private <T> Supplier<T> threadSafeMemoize(final Supplier<T> supplier) { return Suppliers.memoize(new Supplier<T>() { @Override public T get() { checkNotNull(supplier); synchronized (lock) { checkNotDestroyed(); return supplier.get(); } } }); } private void checkNotDestroyed() { synchronized (lock) { checkState(!destroyed.get(), "FirebaseAuth instance is no longer alive. This happens when " + "the parent FirebaseApp instance has been deleted."); } } private void destroy() { synchronized (lock) { destroyed.set(true); } } private static FirebaseAuth fromApp(final FirebaseApp app) { return FirebaseAuth.builder() .setFirebaseApp(app) .setTokenFactory(new Supplier<FirebaseTokenFactory>() { @Override public FirebaseTokenFactory get() { return FirebaseTokenUtils.createTokenFactory(app, Clock.SYSTEM); } }) .setIdTokenVerifier(new Supplier<FirebaseTokenVerifier>() { @Override public FirebaseTokenVerifier get() { return FirebaseTokenUtils.createIdTokenVerifier(app, Clock.SYSTEM); } }) .setCookieVerifier(new Supplier<FirebaseTokenVerifier>() { @Override public FirebaseTokenVerifier get() { return FirebaseTokenUtils.createSessionCookieVerifier(app, Clock.SYSTEM); } }) .setUserManager(new Supplier<FirebaseUserManager>() { @Override public FirebaseUserManager get() { return new FirebaseUserManager(app); } }) .build(); } @VisibleForTesting static Builder builder() { return new Builder(); } static class Builder { private FirebaseApp firebaseApp; private Supplier<FirebaseTokenFactory> tokenFactory; private Supplier<? extends FirebaseTokenVerifier> idTokenVerifier; private Supplier<? extends FirebaseTokenVerifier> cookieVerifier; private Supplier<FirebaseUserManager> userManager; private Builder() { } Builder setFirebaseApp(FirebaseApp firebaseApp) { this.firebaseApp = firebaseApp; return this; } Builder setTokenFactory(Supplier<FirebaseTokenFactory> tokenFactory) { this.tokenFactory = tokenFactory; return this; } Builder setIdTokenVerifier(Supplier<? extends FirebaseTokenVerifier> idTokenVerifier) { this.idTokenVerifier = idTokenVerifier; return this; } Builder setCookieVerifier(Supplier<? extends FirebaseTokenVerifier> cookieVerifier) { this.cookieVerifier = cookieVerifier; return this; } Builder setUserManager(Supplier<FirebaseUserManager> userManager) { this.userManager = userManager; return this; } FirebaseAuth build() { return new FirebaseAuth(this); } } private static class FirebaseAuthService extends FirebaseService<FirebaseAuth> { FirebaseAuthService(FirebaseApp app) { super(SERVICE_ID, FirebaseAuth.fromApp(app)); } @Override public void destroy() { instance.destroy(); } } }
92377904845f8fac91ec0803327cc1eeff1b6b90
1,338
java
Java
src/main/java/com/egouletlang/logmein/http/ErrorResponse.java
egouletlang/logmein-assignment
3c83d5c8462d5c88552b66ab531cee9ee8f9e4a2
[ "MIT" ]
null
null
null
src/main/java/com/egouletlang/logmein/http/ErrorResponse.java
egouletlang/logmein-assignment
3c83d5c8462d5c88552b66ab531cee9ee8f9e4a2
[ "MIT" ]
null
null
null
src/main/java/com/egouletlang/logmein/http/ErrorResponse.java
egouletlang/logmein-assignment
3c83d5c8462d5c88552b66ab531cee9ee8f9e4a2
[ "MIT" ]
null
null
null
31.116279
70
0.727952
998,069
package com.egouletlang.logmein.http; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import springfox.documentation.schema.ModelReference; @JsonSerialize public class ErrorResponse{ @JsonProperty private String status; @JsonProperty private String msg; public ErrorResponse(String status, String msg) { this.status = status; this.msg = msg; } public static ResponseEntity<?> badRequest(String msg) { HttpStatus status = HttpStatus.BAD_REQUEST; ErrorResponse err = new ErrorResponse(status.toString(), msg); return new ResponseEntity(err, status); } public static ResponseEntity<?> conflict(String msg) { HttpStatus status = HttpStatus.CONFLICT; ErrorResponse err = new ErrorResponse(status.toString(), msg); return new ResponseEntity(err, status); } public static ResponseEntity<?> internalServerError(String msg) { HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR; ErrorResponse err = new ErrorResponse(status.toString(), msg); return new ResponseEntity(err, status); } }
9237791f7a8590b89799f2976aa8647eacd4b1ee
4,205
java
Java
fluentTest/arm/code/groupable_resource_inheritance/src/main/java/com/fluent/gencode/groupable_resource_inheritance/implementation/CatImpl.java
sakintoye/autorest.java
f92fa485c84c54dc397af5841dcfda66045d5dca
[ "MIT" ]
null
null
null
fluentTest/arm/code/groupable_resource_inheritance/src/main/java/com/fluent/gencode/groupable_resource_inheritance/implementation/CatImpl.java
sakintoye/autorest.java
f92fa485c84c54dc397af5841dcfda66045d5dca
[ "MIT" ]
null
null
null
fluentTest/arm/code/groupable_resource_inheritance/src/main/java/com/fluent/gencode/groupable_resource_inheritance/implementation/CatImpl.java
sakintoye/autorest.java
f92fa485c84c54dc397af5841dcfda66045d5dca
[ "MIT" ]
null
null
null
29.405594
129
0.639239
998,070
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.fluent.gencode.groupable_resource_inheritance.implementation; import com.microsoft.azure.arm.resources.models.implementation.GroupableResourceCoreImpl; import com.fluent.gencode.groupable_resource_inheritance.Cat; import rx.Observable; import com.fluent.gencode.groupable_resource_inheritance.CatUpdate; import com.fluent.gencode.groupable_resource_inheritance.CatSku; import org.joda.time.DateTime; import com.fluent.gencode.groupable_resource_inheritance.ColorTypes; import com.fluent.gencode.groupable_resource_inheritance.CreationData; import rx.functions.Func1; class CatImpl extends GroupableResourceCoreImpl<Cat, CatInner, CatImpl, PetsManager> implements Cat, Cat.Definition, Cat.Update { private CatUpdate updateParameter; CatImpl(String name, CatInner inner, PetsManager manager) { super(name, inner, manager); this.updateParameter = new CatUpdate(); } @Override public Observable<Cat> createResourceAsync() { CatsInner client = this.manager().inner().cats(); return client.createOrUpdateAsync(this.resourceGroupName(), this.name(), this.inner()) .map(new Func1<CatInner, CatInner>() { @Override public CatInner call(CatInner resource) { resetCreateUpdateParameters(); return resource; } }) .map(innerToFluentMap(this)); } @Override public Observable<Cat> updateResourceAsync() { CatsInner client = this.manager().inner().cats(); return client.updateAsync(this.resourceGroupName(), this.name(), this.updateParameter) .map(new Func1<CatInner, CatInner>() { @Override public CatInner call(CatInner resource) { resetCreateUpdateParameters(); return resource; } }) .map(innerToFluentMap(this)); } @Override protected Observable<CatInner> getInnerAsync() { CatsInner client = this.manager().inner().cats(); return client.getByResourceGroupAsync(this.resourceGroupName(), this.name()); } @Override public boolean isInCreateMode() { return this.inner().id() == null; } private void resetCreateUpdateParameters() { this.updateParameter = new CatUpdate(); } @Override public Integer animalSizeGB() { return this.inner().animalSizeGB(); } @Override public CreationData creationData() { return this.inner().creationData(); } @Override public String managedBy() { return this.inner().managedBy(); } @Override public ColorTypes osType() { return this.inner().osType(); } @Override public String provisioningState() { return this.inner().provisioningState(); } @Override public CatSku sku() { return this.inner().sku(); } @Override public DateTime timeCreated() { return this.inner().timeCreated(); } @Override public CatImpl withCreationData(CreationData creationData) { this.inner().withCreationData(creationData); return this; } @Override public CatImpl withAnimalSizeGB(Integer animalSizeGB) { if (isInCreateMode()) { this.inner().withAnimalSizeGB(animalSizeGB); } else { this.updateParameter.withAnimalSizeGB(animalSizeGB); } return this; } @Override public CatImpl withOsType(ColorTypes osType) { if (isInCreateMode()) { this.inner().withOsType(osType); } else { this.updateParameter.withOsType(osType); } return this; } @Override public CatImpl withSku(CatSku sku) { if (isInCreateMode()) { this.inner().withSku(sku); } else { this.updateParameter.withSku(sku); } return this; } }
92377979051740f342fdc7c8bf3a11989f69e9cb
1,905
java
Java
src/main/java/com/feicent/zhang/base/innerclass/OutClass.java
yzuzhang/zhang
85b5b6fae6a22ee026c7a34c61242a564824a442
[ "Apache-2.0" ]
null
null
null
src/main/java/com/feicent/zhang/base/innerclass/OutClass.java
yzuzhang/zhang
85b5b6fae6a22ee026c7a34c61242a564824a442
[ "Apache-2.0" ]
7
2019-11-13T05:28:53.000Z
2022-01-21T23:16:26.000Z
src/main/java/com/feicent/zhang/base/innerclass/OutClass.java
yzuzhang/zhang
85b5b6fae6a22ee026c7a34c61242a564824a442
[ "Apache-2.0" ]
null
null
null
35.943396
77
0.47664
998,071
package com.feicent.zhang.base.innerclass; public class OutClass { static class InnerClass1 { public void method1(InnerClass2 class2){ String threadName = Thread.currentThread().getName(); synchronized (class2) { System.out.println(threadName + "进入InnerClass1类中的method1方法"); for(int i = 0; i < 10; i++){ System.out.println("i=" + i); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(threadName + "离开InnerClass1类中的method1方法"); } } public synchronized void method2(){ String threadName = Thread.currentThread().getName(); System.out.println(threadName +"进入InnerClass1类中的method2方法"); for(int i = 0; i < 10; i++){ System.out.println("i=" + i); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(threadName + "离开InnerClass1类中的method2方法"); } } static class InnerClass2{ public synchronized void method1(){ String threadName = Thread.currentThread().getName(); System.out.println(threadName + "进入InnerClass2类中的method1方法"); for(int k = 0; k < 10; k++){ System.out.println("k=" + k); try{ Thread.sleep(100); }catch(InterruptedException e){ e.printStackTrace(); } } System.out.println(threadName + "离开InnerClass2类中的method1方法"); } } }
9237798f49dd9c12b5b8def0f6864ab8595b90cf
2,180
java
Java
gulimall-order/src/main/java/com/liuz/gulimall/order/controller/UndoLogController.java
present43/gulimall
a454d3f4ebaed23988c3ed7bef74d4dd39235297
[ "Apache-2.0" ]
null
null
null
gulimall-order/src/main/java/com/liuz/gulimall/order/controller/UndoLogController.java
present43/gulimall
a454d3f4ebaed23988c3ed7bef74d4dd39235297
[ "Apache-2.0" ]
null
null
null
gulimall-order/src/main/java/com/liuz/gulimall/order/controller/UndoLogController.java
present43/gulimall
a454d3f4ebaed23988c3ed7bef74d4dd39235297
[ "Apache-2.0" ]
null
null
null
23.956044
64
0.684404
998,072
package com.liuz.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.liuz.gulimall.order.entity.UndoLogEntity; import com.liuz.gulimall.order.service.UndoLogService; import com.liuz.common.utils.PageUtils; import com.liuz.common.utils.R; /** * * * @author liuz * @email hzdkv@example.com * @date 2020-10-10 10:01:18 */ @RestController @RequestMapping("order/undolog") public class UndoLogController { @Autowired private UndoLogService undoLogService; /** * 列表 */ @RequestMapping("/list") // @RequiresPermissions("order:undolog:list") public R list(@RequestParam Map<String, Object> params){ PageUtils page = undoLogService.queryPage(params); return R.ok().put("page", page); } /** * 信息 */ @RequestMapping("/info/{id}") // @RequiresPermissions("order:undolog:info") public R info(@PathVariable("id") Long id){ UndoLogEntity undoLog = undoLogService.getById(id); return R.ok().put("undoLog", undoLog); } /** * 保存 */ @RequestMapping("/save") // @RequiresPermissions("order:undolog:save") public R save(@RequestBody UndoLogEntity undoLog){ undoLogService.save(undoLog); return R.ok(); } /** * 修改 */ @RequestMapping("/update") // @RequiresPermissions("order:undolog:update") public R update(@RequestBody UndoLogEntity undoLog){ undoLogService.updateById(undoLog); return R.ok(); } /** * 删除 */ @RequestMapping("/delete") // @RequiresPermissions("order:undolog:delete") public R delete(@RequestBody Long[] ids){ undoLogService.removeByIds(Arrays.asList(ids)); return R.ok(); } }
923779b37d28c1dbc69ad8804a613373e595a8ac
469
java
Java
sda-commons-server-key-mgmt/src/main/java/org/sdase/commons/keymgmt/manager/NoKeyKeyManager.java
thrstnh/sda-dropwizard-commons
c31f99c312e2e164ae50cf714e90b8c4b34c7454
[ "MIT" ]
34
2020-01-09T10:15:03.000Z
2022-03-30T21:14:24.000Z
sda-commons-server-key-mgmt/src/main/java/org/sdase/commons/keymgmt/manager/NoKeyKeyManager.java
SDA-SE/sda-dropwizard-commons
c98b07f2421d5370abc1bd2b147bbfe1c245f231
[ "MIT" ]
1,487
2020-01-08T13:51:49.000Z
2022-03-31T11:24:35.000Z
sda-commons-server-key-mgmt/src/main/java/org/sdase/commons/keymgmt/manager/NoKeyKeyManager.java
thrstnh/sda-dropwizard-commons
c31f99c312e2e164ae50cf714e90b8c4b34c7454
[ "MIT" ]
6
2020-03-26T06:57:06.000Z
2021-11-25T16:11:13.000Z
21.318182
98
0.733475
998,073
package org.sdase.commons.keymgmt.manager; import java.util.Collections; import java.util.Set; /** * simulates a non existing key. For a non exiting key, there are no valid values and therefore no * testable can be seen as valid. */ public class NoKeyKeyManager implements KeyManager { @Override public Set<String> getValidValues() { return Collections.emptySet(); } @Override public boolean isValidValue(String testable) { return false; } }
92377a2a9f44ea6c3c44ff05d988d63b21d05333
4,965
java
Java
src/Game.java
Ursinus-CS174-F2020/Week1_2048
93b204eaef3e6aeb4e8683437ff4682c513bdc4d
[ "Apache-2.0" ]
null
null
null
src/Game.java
Ursinus-CS174-F2020/Week1_2048
93b204eaef3e6aeb4e8683437ff4682c513bdc4d
[ "Apache-2.0" ]
null
null
null
src/Game.java
Ursinus-CS174-F2020/Week1_2048
93b204eaef3e6aeb4e8683437ff4682c513bdc4d
[ "Apache-2.0" ]
null
null
null
29.035088
81
0.536354
998,074
import java.util.Random; import java.util.Scanner; public class Game { private int[][] board; public Game() { board = new int[4][4]; } /** * Print out the board in text, making enough space to * accommodate 4 digit numbers like 2048 */ public void printBoard() { for (int i = 0; i < 4; i++) { System.out.println("========================="); for (int j = 0; j < 4; j++) { if (board[i][j] > 0) { System.out.printf("|%4d ", board[i][j]); } else { System.out.printf("| "); } } System.out.println("|"); } System.out.println("=========================\n"); } /** * Clear the board by putting all zeroes into it */ public void clearBoard() { for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { board[i][j] = 0; } } } /** * Add a single random number that's either a 2 or a 4 */ public void addRandom() { // TODO: Group 1 fills this in } /** * Initialize a grid with some amount of random numbers that * are either 2s or 4s * @param numInitial How many numbers to place */ public void makeRandomGrid(int numInitial) { // TODO: Group 1 fills this in } /** * Move all of the nonzero entries over to the right so there * are no gaps and everything is touching the right */ public void moveRight() { // TODO: Group 2 fills this in } /** * Move all of the nonzero entries down so there * are no gaps and everything is touching the bottom */ public void moveDown() { // TODO: Group 3 fills this in } /** * Combine all adjacent numbers that are the same in a particular row * There are three cases * 1) There are two in a row. In this case, put a zero in the place * of the first one, and replace the second one with twice its value * 2) There are three in a row. In this case, put a zero in the first place, * keep the original value in the second place, and put twice the original * value in the third place * 3) There are 4 in a row. Put zeros in the first two, and put twice * the value in the second two */ public void combineRight() { // TODO: Group 4 fills this in } /** * Combine all adjacent numbers that are the same in a particular column * There are three cases * 1) There are two in a row. In this case, put a zero in the place * of the first one, and replace the second one with twice its value * 2) There are three in a row. In this case, put a zero in the first place, * keep the original value in the second place, and put twice the original * value in the third place * 3) There are 4 in a row. Put zeros in the first two, and put twice * the value in the second two */ public void combineDown() { // TODO: Group 5 fills this in } /** * Reflect the board vertically */ public void flipVertically() { // TODO: Group 6 fills this in } /** * Reflect the board horizontally */ public void flipHorizontally() { // TODO: Group 6 fills this in } /** * Return whether the board is full * @return true if the board is full, false otherwise */ public boolean isFull() { // TODO: Group 7 fills this in return false; // TODO: This is a dummy value } /** * Check that the board is full *and* it is not possible * to combine any adjacent elements * @return true if the game is over, false otherwise */ public boolean isOver() { // TODO: Group 7 fills this in return false; // TODO: This is a dummy value } /** * Repeat the following until the board is full * 1) Print the board * 2) Have the user choose a direction: * a Left, d right, w up, s down * 3) Move the board in that direction and combine things as necessary * 4) Print the resulting board * 5) If the board is not full, put a new random 2 or 4 on the board */ public void playGame() { } /** * You can use this for debugging; put any numbers you like in * the board */ public void makeMyOwnGrid() { clearBoard(); // TODO: Fill this in with your own custom board board[0][0] = 4; board[1][3] = 2; board[2][1] = 2; } public static void main(String[] args) { Game game = new Game(); // TODO: Debugging/test code here game.makeMyOwnGrid(); game.printBoard(); } }
92377a87bb88d36929da7e6981e64bb2ffb91326
1,187
java
Java
runescape-client/src/main/java/Ignored.java
Magnusrn/runelite
c77297f6d6e0e78a37fcdefe88a8e61bf060d4d4
[ "BSD-2-Clause" ]
null
null
null
runescape-client/src/main/java/Ignored.java
Magnusrn/runelite
c77297f6d6e0e78a37fcdefe88a8e61bf060d4d4
[ "BSD-2-Clause" ]
null
null
null
runescape-client/src/main/java/Ignored.java
Magnusrn/runelite
c77297f6d6e0e78a37fcdefe88a8e61bf060d4d4
[ "BSD-2-Clause" ]
null
null
null
21.581818
56
0.697557
998,075
import net.runelite.mapping.Export; import net.runelite.mapping.Implements; import net.runelite.mapping.ObfuscatedGetter; import net.runelite.mapping.ObfuscatedName; import net.runelite.mapping.ObfuscatedSignature; @ObfuscatedName("ng") @Implements("Ignored") public class Ignored extends User { @ObfuscatedName("v") @ObfuscatedGetter( intValue = -60193045 ) @Export("id") int id; Ignored() { } // L: 6 @ObfuscatedName("v") @ObfuscatedSignature( descriptor = "(Lng;B)I", garbageValue = "-48" ) @Export("compareTo_ignored") int compareTo_ignored(Ignored var1) { return this.id - var1.id; // L: 9 } @ObfuscatedName("c") @ObfuscatedSignature( descriptor = "(Lnn;I)I", garbageValue = "842367957" ) @Export("compareTo_user") public int compareTo_user(User var1) { return this.compareTo_ignored((Ignored)var1); // L: 13 } public int compareTo(Object var1) { return this.compareTo_ignored((Ignored)var1); // L: 17 } @ObfuscatedName("u") @ObfuscatedSignature( descriptor = "(IB)V", garbageValue = "127" ) static void method6828(int var0) { if (var0 != Login.loginIndex) { // L: 1852 Login.loginIndex = var0; // L: 1853 } } // L: 1854 }
92377aa4d74e7a00c8f0bc46d1716506ea9793e3
2,689
java
Java
src/main/java/com/inferni/giftcard/APIHook/Manager.java
MatiasMunk/CraftingStore-GiftCard-Extension
66a7782eb417633a7b1885517f624724b75241a1
[ "Apache-2.0" ]
null
null
null
src/main/java/com/inferni/giftcard/APIHook/Manager.java
MatiasMunk/CraftingStore-GiftCard-Extension
66a7782eb417633a7b1885517f624724b75241a1
[ "Apache-2.0" ]
null
null
null
src/main/java/com/inferni/giftcard/APIHook/Manager.java
MatiasMunk/CraftingStore-GiftCard-Extension
66a7782eb417633a7b1885517f624724b75241a1
[ "Apache-2.0" ]
null
null
null
37.347222
133
0.593529
998,076
package com.inferni.giftcard.APIHook; import com.inferni.giftcard.Email.Emailer; import com.inferni.giftcard.GiftCard; import com.inferni.giftcard.Util.DataInterface; import freemarker.template.TemplateException; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.file.FileConfiguration; import javax.mail.MessagingException; import java.io.IOException; import java.util.List; import java.util.Set; public class Manager { private static Manager instance; public Manager() { instance = this; } public static Manager getInstance() { if (instance == null) { instance = new Manager(); } return instance; } public void makeGiftCard(String player, int amount, CommandSender sender){ int cardID = Hook.makeNewCard(amount); DataInterface.getInstance().addToPendingEmailList(player, cardID); sender.sendMessage(ChatColor.translateAlternateColorCodes ('&', GiftCard.config.getString("createCard") .replaceAll("%id%", cardID + ""))); } public void email(String player, String email, CommandSender sender) throws TemplateException, IOException, MessagingException { FileConfiguration d = GiftCard.data; if (!d.contains("Pending")) { d.createSection("Pending"); } ConfigurationSection data = d.getConfigurationSection("Pending"); if (data.contains(player)){ List<Integer> cards = data.getIntegerList(player); for (int c : cards){ Emailer.getInstance().sendEmail(c+"", player, email); sender.sendMessage(ChatColor.translateAlternateColorCodes ('&', GiftCard.config.getString("emailSent") .replaceAll("%email%", email))); if (Bukkit.getOfflinePlayer(player).isOnline()){ for (String s : GiftCard.config.getStringList("recieveCard")){ Bukkit.getPlayer(player).sendMessage(ChatColor .translateAlternateColorCodes('&', s .replaceAll("%code%", Hook.getCardCode(c+"")))); } } } data.set(player, null); Set<String> keys = data.getKeys(false); keys.remove(player); GiftCard.getInstance().dataFile.saveData(); } else { //No player } } }
92377b3cb83828c8df56cecd1c09a2b8a09717e5
1,071
java
Java
a206_Date/DateDemo.java
Harlotte1998/JavaReview
20d0488052123dfe228b523745d7da21be55a4fa
[ "Apache-2.0" ]
null
null
null
a206_Date/DateDemo.java
Harlotte1998/JavaReview
20d0488052123dfe228b523745d7da21be55a4fa
[ "Apache-2.0" ]
null
null
null
a206_Date/DateDemo.java
Harlotte1998/JavaReview
20d0488052123dfe228b523745d7da21be55a4fa
[ "Apache-2.0" ]
null
null
null
24.340909
69
0.542484
998,077
package HeiMa.a206_Date; import java.util.Date; /** * @Author Miracle Liuce * @Date 2021/11/13 16:49 * @Version 1.0 6.1 Date类概述和构造方法 Date代表了-一个特定的时间,精确到毫秒 方法名 说明 public Date() 分配一个Date对象,并初始化,以便它代表它被分配的时间,精确到毫秒 public Date(long date) 分配个Date对象,并将其初始化为表示从标准基准时间起指定的毫秒数 CST 指的是 中国标准时间 */ public class DateDemo { public static void main(String[] args) { //public Date() 分配一个Date对象,并初始化,以便它代表它被分配的时间,精确到毫秒 Date d1=new Date(); System.out.println(d1); /* * 按照常理 System.out.println(d1);应该是一个 路径名@地址值 * 但是 输出的是 Sat Nov 13 17:03:53 CST 2021 * 说明 他重写了 这个 toString方法 * */ //public Date(long date) 分配个Date对象,并将其初始化为表示从标准基准时间起指定的毫秒数 long data =1000*60*60; Date d2=new Date(data); System.out.println(d2); /* *应该输出 格林威治 时间 * 1970年 01日 01:00:00 * 但是我国位于 东八区 时间要 +8 * Thu Jan 01 09:00:00 CST 1970 * * */ } }
92377bb840b19d27240037530d523d615fa43daa
12,046
java
Java
src/main/java/com/varobank/common/gremlin/queries/BatchWriteQueries.java
VaroBank/kafka-neptune-sink
a946f66db2670a16ae7ca420561f903a1c4bf2e4
[ "BSD-2-Clause" ]
1
2022-03-21T21:44:19.000Z
2022-03-21T21:44:19.000Z
src/main/java/com/varobank/common/gremlin/queries/BatchWriteQueries.java
VaroBank/kafka-neptune-sink
a946f66db2670a16ae7ca420561f903a1c4bf2e4
[ "BSD-2-Clause" ]
null
null
null
src/main/java/com/varobank/common/gremlin/queries/BatchWriteQueries.java
VaroBank/kafka-neptune-sink
a946f66db2670a16ae7ca420561f903a1c4bf2e4
[ "BSD-2-Clause" ]
null
null
null
47.801587
140
0.623277
998,078
/* Copyright (c) 2022 Varo Bank, N.A. 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 HOLDER 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 com.varobank.common.gremlin.queries; import com.varobank.common.gremlin.utils.ConnectionConfig; import com.varobank.common.gremlin.utils.Schema; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.apache.tinkerpop.gremlin.structure.T; import org.apache.tinkerpop.gremlin.structure.VertexProperty.Cardinality; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashSet; import java.util.Map; import java.util.Set; import static org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__.*; public class BatchWriteQueries extends BaseQueries { private GremlinTraversal traversal; private String emptyJSON = "{}"; private Set<String> createdVerticesInBatch = new HashSet<>(); private static final Logger logger = LoggerFactory.getLogger(BatchWriteQueries.class); protected BatchWriteQueries(ConnectionConfig connectionConfig, Schema schema) { this.traversal = new GremlinTraversal(connectionConfig.traversalSource()); setSchema(schema); } /** * Soft delete of the vertex record in Neptune DB. Neptune schema must be defined. * @param json * @param topic * @param op * @param ts_ms * @param insertDateTime */ public void deleteVertex(JSONObject json, String topic, String op, long ts_ms, long insertDateTime) { Map<String, String> settings = getSchema().get(topic); String id = settings.get("id"); String prefix = settings.get("prefix"); String idValue = prefix + json.get(id); GraphTraversal g = traversal.V().hasLabel(topic).has(T.id, idValue). fold(). coalesce(unfold(), addV(topic).property(T.id, idValue)); traversal = new GremlinTraversal(g. property(Cardinality.single, "op", op). property(Cardinality.single, "ts_ms", ts_ms). property(Cardinality.single, "insertDateTime", insertDateTime)); } /** * Creates or updates a vertex record in the Neptune DB from provided json. Neptune schema must be defined. * @param json * @param topic * @param op * @param ts_ms * @param insertDateTime */ public void upsertVertex(JSONObject json, String topic, String op, long ts_ms, long insertDateTime) { Map<String, String> settings = getSchema().get(topic); if (settings == null) { logger.error("No schema defined for " + topic); } String id = settings.get("id"); String prefix = settings.get("prefix"); String idValue = prefix + json.get(id); GraphTraversal query = traversal.V(idValue).hasLabel(topic); GraphTraversal temp = query.asAdmin().clone().values("ts_ms"); long prevTimestamp = temp.hasNext() ? ((Number)temp.next()).longValue() : 0L; if (ts_ms >= prevTimestamp) { GraphTraversal g = query.asAdmin().clone(). fold(). coalesce(unfold(), addV(topic).property(T.id, idValue)); json.keys().forEachRemaining(key -> { Object value = json.get(key); if (!key.equals("id") && !key.equals(id)) { if (JSONObject.NULL == value) { value = emptyJSON; } g.property(Cardinality.single, key, value); } }); traversal = new GremlinTraversal(g. property(Cardinality.single, "op", op). property(Cardinality.single, "ts_ms", ts_ms). property(Cardinality.single, "insertDateTime", insertDateTime)); } } /** * Creates or updates an Edge record in the Neptune DB from provided json. Neptune schema must be defined. * In order to create an edge between two vertices those two vertices must exist. Prior to creating of an edge * the following conditions are checked: * - when creating an edge from parent vertex to child vertex (one-to-one or many-to-one relationship) child vertex * must be pre-created if it doesn't exist (child vertex is pre-created as an empty vertex with just child vertex id) * - when creating an edge from child vertex to parent vertex (one-to-one or one-to-many relationship) parent vertex * must be pre-created if it doesn't exist (as an empty vertex with the parent vertex id) * * All pre-created empty vertices are updated with the real data as soon as this data is pulled from the Kafka. * * Many-to-many relationship can only be created via an intermediate vertex using many-to-one and one-to-many * relationships which has to defined in the Neptune schema. * @param json * @param topic * @param op * @param ts_ms * @param insertDateTime */ public void upsertEdge(JSONObject json, String topic, String op, long ts_ms, long insertDateTime) { Map<String, String> settings = getSchema().get(topic); if (settings.containsKey("child")) { String id = settings.get("id"); String prefix = settings.get("prefix"); String fromVertexId = prefix + json.get(id); String childTopicsStr = settings.get("child"); String[] childTopics = childTopicsStr.split(","); for (String childTopic: childTopics) { Map<String, String> childSettings = getSchema().get(childTopic); if (childSettings.containsKey("kafka_topic")) { String connectingPropKey = childSettings.get("parent_prop_key"); String edgeLabel = childSettings.get("edge_label"); if (childSettings.get("id").equals(childSettings.get("ref_key"))) { String childPrefix = childSettings.get("prefix"); String connectingPropKeyValue = json.get(connectingPropKey) != null ? json.get(connectingPropKey).toString() : null; if (connectingPropKeyValue != null && !connectingPropKeyValue.isEmpty()) { String toVertexId = childPrefix + connectingPropKeyValue; // 1. Pre-create child vertx if enough info in current JSON message about the child // This allows to create many to one and one to one relationship createVertexIfNotExist(toVertexId, childTopic, insertDateTime); addEdge(fromVertexId, toVertexId, edgeLabel, insertDateTime); } else { logger.warn("connectingPropKey " + connectingPropKey + " is empty. Topic: " + topic + " json: " + json); } } } } } if (isCreatableParentRelationship(topic)) { String parentPropKey = settings.get("parent_prop_key"); String connectingRefKey = settings.get("ref_key"); String parentTopic = settings.get("parent"); Map<String, String> parentSettings = getSchema().get(parentTopic); String parentId = parentSettings.get("id"); String prefix = settings.get("prefix"); String id = settings.get("id"); String toVertexId = prefix + json.get(id); String edgeLabel = settings.get("edge_label"); if (parentId.equals(parentPropKey)) { // 2. Pre-create parent vertx if enough info in current JSON message about the parent // This allows to create one to many and one to one relationship String parentPrefix = parentSettings.get("prefix"); String connectingRefKeyValue = json.get(connectingRefKey) != null ? json.get(connectingRefKey).toString() : null; if (connectingRefKeyValue != null && !connectingRefKeyValue.isEmpty()) { String fromVertexId = parentPrefix + connectingRefKeyValue; //case the parent vertex can be pre-created if not exists createVertexIfNotExist(fromVertexId, parentTopic, insertDateTime); addEdge(fromVertexId, toVertexId, edgeLabel, insertDateTime); } else { logger.warn("connectingRefKey " + connectingRefKey + " is empty. Topic: " + topic + " json: " + json); } } } } void addEdge(String fromVertexId, String toVertexId, String edgeLabel, long insertDateTime) { String edgeId = String.format("%s-%s", fromVertexId, toVertexId); logger.info("Adding edge: " + edgeId); traversal = new GremlinTraversal(traversal. V(fromVertexId).outE(edgeLabel).hasId(edgeId).fold().coalesce( unfold(), V(fromVertexId).addE(edgeLabel).to(V(toVertexId)). property(T.id, edgeId). property(Cardinality.single,"insertDateTime", insertDateTime))); } public boolean isCreatableParentRelationship(String topic) { Map<String, String> settings = getSchema().get(topic); if (settings.containsKey("parent") && settings.containsKey("kafka_topic")) { String parentPropKey = settings.get("parent_prop_key"); String parentTopic = settings.get("parent"); Map<String, String> parentSettings = getSchema().get(parentTopic); String parentId = parentSettings.get("id"); if (parentId.equals(parentPropKey)) { return true; } } return false; } void createVertexIfNotExist(String vertexId, String topic, long insertDateTime) { if (!createdVerticesInBatch.contains(vertexId)) { GraphTraversal query = traversal.V(vertexId).hasLabel(topic); GraphTraversal temp = query.asAdmin().clone().id(); if (!temp.hasNext()) { GraphTraversal g = query.asAdmin().clone(). fold(). coalesce(unfold(), addV(topic).property(T.id, vertexId)). property(Cardinality.single, "ts_ms", 0L). property(Cardinality.single, "insertDateTime", insertDateTime); traversal = new GremlinTraversal(g); } createdVerticesInBatch.add(vertexId); } } public long execute(long batchId) { if (traversal != null) { return traversal.execute(batchId); } else { return 0; } } }
92377ca93fd70108efedc4f821a3debb34ef5839
468
java
Java
src/main/java/io/quarkus/samples/petclinic/dto/order/OrderResponseDto.java
iei-dasa/dasa-tropicana-backend
23ea27b532c9d99c8d915231f2a785b8ca067f63
[ "MIT" ]
null
null
null
src/main/java/io/quarkus/samples/petclinic/dto/order/OrderResponseDto.java
iei-dasa/dasa-tropicana-backend
23ea27b532c9d99c8d915231f2a785b8ca067f63
[ "MIT" ]
null
null
null
src/main/java/io/quarkus/samples/petclinic/dto/order/OrderResponseDto.java
iei-dasa/dasa-tropicana-backend
23ea27b532c9d99c8d915231f2a785b8ca067f63
[ "MIT" ]
null
null
null
23.4
50
0.747863
998,079
package io.quarkus.samples.petclinic.dto.order; import java.time.LocalDate; import java.util.List; public class OrderResponseDto { private Long id; private Double totalPrice; private LocalDate date; private String firstName; private String lastName; private String city; private String address; private String email; private String phoneNumber; private Integer postIndex; private List<OrderItemResponseDto> orderItems; }
92377cb49ebefdb60d6124e3e6e4ddec79740096
621
java
Java
RNAstructure_Source/java_interface/src/ur_rna/GUITester/ScriptParser/ASTNamedArgument.java
mayc2/PseudoKnot_research
33e94b84435d87aff3d89dbad970c438ac173331
[ "MIT" ]
null
null
null
RNAstructure_Source/java_interface/src/ur_rna/GUITester/ScriptParser/ASTNamedArgument.java
mayc2/PseudoKnot_research
33e94b84435d87aff3d89dbad970c438ac173331
[ "MIT" ]
null
null
null
RNAstructure_Source/java_interface/src/ur_rna/GUITester/ScriptParser/ASTNamedArgument.java
mayc2/PseudoKnot_research
33e94b84435d87aff3d89dbad970c438ac173331
[ "MIT" ]
null
null
null
31.05
167
0.774557
998,080
/* Generated By:JJTree: Do not edit this line. ASTNamedArgument.java Version 6.0 */ /* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=false,TRACK_TOKENS=false,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ package ur_rna.GUITester.ScriptParser; public class ASTNamedArgument extends ScriptNode { public String name; public ScriptNode val; public ASTNamedArgument(int id) { super(id); } public ASTNamedArgument(GuiTestScriptParser p, int id) { super(p, id); } } /* JavaCC - OriginalChecksum=6a9c286571d18d21be5219f300103fd2 (do not edit this line) */
92377d5ae5ea0c2dde3095a985513650ad243fd7
537
java
Java
chapter_001/src/test/java/ru/job4j/array/SquareTest.java
andreworlov91/aorlov
9e9700a53f33342ab8160a71f72d52d63a0208fb
[ "Apache-2.0" ]
null
null
null
chapter_001/src/test/java/ru/job4j/array/SquareTest.java
andreworlov91/aorlov
9e9700a53f33342ab8160a71f72d52d63a0208fb
[ "Apache-2.0" ]
null
null
null
chapter_001/src/test/java/ru/job4j/array/SquareTest.java
andreworlov91/aorlov
9e9700a53f33342ab8160a71f72d52d63a0208fb
[ "Apache-2.0" ]
null
null
null
18.689655
62
0.623616
998,081
package ru.job4j.array; import org.junit.Test; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; /** * Test. * * @author AndrewOrlov (anpch@example.com) * @version $Id$ * @since 0.1 */ public class SquareTest { /** * Test calculate. */ @Test public void whenCalculateFourNumsWhenHaveEqualsMassive() { Square square = new Square(); int[] mas = square.calculate(4); int[] expectedMas = {0, 1, 4, 9}; assertThat(mas, is(expectedMas)); } }
92377ef4b1420eb56a6406282deac3f15acda856
755
java
Java
src/main/java/com/ganghuan/myRPCVersion4/server/TestServer.java
c1028131070/MyRPCFromZero
b994d6ad1808bd9cb3b93c8e7762d700f84cab61
[ "Apache-2.0" ]
224
2020-08-06T03:52:04.000Z
2022-03-30T03:37:27.000Z
src/main/java/com/ganghuan/myRPCVersion4/server/TestServer.java
warren-chen/MyRPCFromZero
61b878e5cf6a6c6dcb66a27dbeaa47b746364f97
[ "Apache-2.0" ]
2
2021-06-30T13:37:55.000Z
2021-07-22T13:10:04.000Z
src/main/java/com/ganghuan/myRPCVersion4/server/TestServer.java
warren-chen/MyRPCFromZero
61b878e5cf6a6c6dcb66a27dbeaa47b746364f97
[ "Apache-2.0" ]
50
2020-08-10T16:14:16.000Z
2022-03-26T12:45:40.000Z
35.952381
66
0.770861
998,082
package com.ganghuan.myRPCVersion4.server; import com.ganghuan.myRPCVersion4.service.BlogService; import com.ganghuan.myRPCVersion4.service.BlogServiceImpl; import com.ganghuan.myRPCVersion4.service.UserService; import com.ganghuan.myRPCVersion4.service.UserServiceImpl; public class TestServer { public static void main(String[] args) { UserService userService = new UserServiceImpl(); BlogService blogService = new BlogServiceImpl(); ServiceProvider serviceProvider = new ServiceProvider(); serviceProvider.provideServiceInterface(userService); serviceProvider.provideServiceInterface(blogService); RPCServer RPCServer = new NettyRPCServer(serviceProvider); RPCServer.start(8899); } }
9237803fb7fa07e97c9d4a9a858d23299a576a39
5,668
java
Java
src/main/java/setadokalo/customfog/config/gui/widgets/WarningWidget.java
helpimnotdrowning/custom-fog
a5a0afe873872d7956add8b42d7af4a4e558758d
[ "MIT" ]
11
2020-09-11T08:04:30.000Z
2022-01-22T09:16:41.000Z
src/main/java/setadokalo/customfog/config/gui/widgets/WarningWidget.java
helpimnotdrowning/custom-fog
a5a0afe873872d7956add8b42d7af4a4e558758d
[ "MIT" ]
32
2020-10-20T15:15:36.000Z
2022-03-31T02:25:28.000Z
src/main/java/setadokalo/customfog/config/gui/widgets/WarningWidget.java
helpimnotdrowning/custom-fog
a5a0afe873872d7956add8b42d7af4a4e558758d
[ "MIT" ]
8
2020-09-11T08:05:05.000Z
2022-03-11T17:04:48.000Z
31.314917
126
0.62844
998,083
package setadokalo.customfog.config.gui.widgets; import com.mojang.blaze3d.systems.RenderSystem; import net.minecraft.client.MinecraftClient; import net.minecraft.client.font.TextRenderer; import net.minecraft.client.gui.Drawable; import net.minecraft.client.gui.DrawableHelper; import net.minecraft.client.gui.Element; import net.minecraft.client.util.math.MatrixStack; import net.minecraft.text.OrderedText; import net.minecraft.text.Text; import net.minecraft.util.Identifier; import org.jetbrains.annotations.NotNull; import java.util.Arrays; import java.util.List; public class WarningWidget implements Drawable, Element { public enum Type { WARNING(0), ERROR(40); int texturePos; Type(int pos) { texturePos = pos; } int getTexturePos() { return texturePos; } } @NotNull protected final List<Text> warningText; protected int x, y; protected int width, height; @NotNull protected Type type; public int getX() { return x; } public int getY() { return y; } public void setX(int x) { this.x = x; } public void setY(int y) { this.y = y; } public int getWidth() { return width; } public void setWidth(int width) { this.width = width; } public int getHeight() { return height; } public WarningWidget(@NotNull Type type, int x, int y, int width, Text... lines) { this(type, width, lines); this.x = x; this.y = y; } public WarningWidget(int width, Text... lines) { this(Type.WARNING, width, lines); } public WarningWidget(@NotNull Type type, int width, Text... lines) { this.type = type; this.warningText = Arrays.asList(lines); this.width = width; TextRenderer renderer = MinecraftClient.getInstance().textRenderer; for (Text line : lines) { int sWidth = renderer.getWidth(line.asString()) + 28; if (sWidth > width) { width = sWidth; } } this.height = lines.length * (renderer.fontHeight + 1) + 16; } public static void drawNinepatchRect( MatrixStack matrices, int x, int y, int width, int height, int u, int v, int edgeSize, int centerSize) { // left to right, then top to bottom /* Top row */ DrawableHelper.drawTexture(matrices, x, y, /* x, y */ u, v, /* u, v */ edgeSize, edgeSize, /* width, height */ 256, 256); /* textureWidth, textureHeight */ DrawableHelper.drawTexture(matrices, x + edgeSize, y, /* x, y */ width - edgeSize * 2, edgeSize, /* width, height */ u + edgeSize, v, /* u, v */ centerSize, edgeSize, /* regionWidth, regionHeight */ 256, 256); /* textureWidth, textureHeight */ DrawableHelper.drawTexture(matrices, x + width - edgeSize, y, u + edgeSize + centerSize, v, edgeSize, edgeSize, 256, 256); /* Middle row */ DrawableHelper.drawTexture(matrices, x, y + edgeSize, /* x, y */ edgeSize, height - edgeSize * 2, /* width, height */ u, v + edgeSize, /* u, v */ edgeSize, centerSize, /* regionWidth, regionHeight */ 256, 256); /* textureWidth, textureHeight */ DrawableHelper.drawTexture(matrices, x + edgeSize, y + edgeSize, /* x, y */ width - edgeSize * 2, height - edgeSize * 2, /* width, height */ u + edgeSize, v + edgeSize, /* u, v */ centerSize, centerSize, /* regionWidth, regionHeight */ 256, 256); /* textureWidth, textureHeight */ DrawableHelper.drawTexture(matrices, x + width - edgeSize, y + edgeSize, /* x, y */ edgeSize, height - edgeSize * 2, /* width, height */ u + edgeSize + centerSize, v + edgeSize, /* u, v */ edgeSize, centerSize, /* regionWidth, regionHeight */ 256, 256); /* textureWidth, textureHeight */ /* Bottom row */ DrawableHelper.drawTexture(matrices, x, y + height - edgeSize, /* x, y */ u, v + edgeSize + centerSize, /* u, v */ edgeSize, edgeSize, /* width, height */ 256, 256); /* textureWidth, textureHeight */ DrawableHelper.drawTexture(matrices, x + edgeSize, y + height - edgeSize, /* x, y */ width - edgeSize * 2, edgeSize, /* width, height */ u + edgeSize, v + edgeSize + centerSize, /* u, v */ centerSize, edgeSize, /* regionWidth, regionHeight */ 256, 256); /* textureWidth, textureHeight */ DrawableHelper.drawTexture(matrices, x + width - edgeSize, y + height - edgeSize, u + edgeSize + centerSize, v + edgeSize + centerSize, edgeSize, edgeSize, 256, 256); } @Override public void render(MatrixStack matrices, int mouseX, int mouseY, float delta) { // CustomFog.log(Level.INFO, "hhhh");' RenderSystem.setShaderTexture(0, new Identifier("custom-fog", "textures/gui/cfog-gui.png")); drawNinepatchRect(matrices, this.x, this.y, width, height, 0, 0, 5, 10); DrawableHelper.drawTexture(matrices, this.x + 5, this.y + (this.height - 20)/2, 20, type.getTexturePos(), 20, 20, 256, 256); TextRenderer textRenderer = MinecraftClient.getInstance().textRenderer; int y = 7; for (Text line : this.warningText) { OrderedText orderedText = line.asOrderedText(); int color = 0xFFFFFFFF; if (line.getStyle() != null && line.getStyle().getColor() != null) color = line.getStyle().getColor().getRgb(); // textRenderer.drawWithShadow(matrices, orderedText, this.x + 20, this.y + y, color); DrawableHelper.drawCenteredTextWithShadow(matrices, textRenderer, orderedText, this.x + 10 + width / 2, this.y + y, color); y += textRenderer.fontHeight + 2; } } }
9237807a6fe452e97bb4fe09205704274bcce4b5
970
java
Java
dbconsoledrawer/src/test/java/com/db/consoledrawing/command/CreateCanvasCommandTest.java
syedimra953/sample-projects
e66105b10e754f1a05bd1a7324c2a0a55020faa5
[ "Apache-2.0" ]
null
null
null
dbconsoledrawer/src/test/java/com/db/consoledrawing/command/CreateCanvasCommandTest.java
syedimra953/sample-projects
e66105b10e754f1a05bd1a7324c2a0a55020faa5
[ "Apache-2.0" ]
null
null
null
dbconsoledrawer/src/test/java/com/db/consoledrawing/command/CreateCanvasCommandTest.java
syedimra953/sample-projects
e66105b10e754f1a05bd1a7324c2a0a55020faa5
[ "Apache-2.0" ]
null
null
null
30.3125
69
0.724742
998,084
package com.db.consoledrawing.command; import com.db.consoledrawing.exception.InvalidCommandParamsException; import org.junit.Test; public class CreateCanvasCommandTest { @Test public void testCreate() throws InvalidCommandParamsException { new CreateCommand("1", "1"); } @Test(expected = InvalidCommandParamsException.class) public void testCreate2() throws InvalidCommandParamsException { new CreateCommand("-11", "1"); } @Test(expected = InvalidCommandParamsException.class) public void testCreate3() throws InvalidCommandParamsException { new CreateCommand("1", "-1"); } @Test(expected = InvalidCommandParamsException.class) public void testCreate4() throws InvalidCommandParamsException { new CreateCommand("1"); } @Test(expected = InvalidCommandParamsException.class) public void testCreate6() throws InvalidCommandParamsException { new CreateCommand(); } }
923781167ae1b18b92497e59104a4fffdfb52ec2
940
java
Java
src/main/java/ga/rugal/demo/core/entity/Student.java
Rugal/spring-boot-template
b46142731afa3e88e0aea56f1f02ca42308e8129
[ "Apache-2.0" ]
null
null
null
src/main/java/ga/rugal/demo/core/entity/Student.java
Rugal/spring-boot-template
b46142731afa3e88e0aea56f1f02ca42308e8129
[ "Apache-2.0" ]
null
null
null
src/main/java/ga/rugal/demo/core/entity/Student.java
Rugal/spring-boot-template
b46142731afa3e88e0aea56f1f02ca42308e8129
[ "Apache-2.0" ]
null
null
null
26.111111
80
0.759574
998,085
package ga.rugal.demo.core.entity; import static config.SystemDefaultProperty.SCHEMA; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import javax.validation.constraints.Size; import lombok.Data; @Data @Entity @Table(name = "student", schema = SCHEMA) public class Student { private static final String SEQUENCE_NAME = "student_sid_seq"; @Basic(optional = false) @Column(name = "sid") @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = SEQUENCE_NAME) @Id @SequenceGenerator(name = SEQUENCE_NAME, allocationSize = 1, sequenceName = SCHEMA + "." + SEQUENCE_NAME) private Integer sid; @Size(max = 20) @Column(length = 20) private String name; }
92378158aba5fd04b69463cce2c0295ddc847228
4,841
java
Java
openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/ServiceDeclarationNodesTests.java
kapilraajP/openapi-tools
4fb7a186ab217df127ed8c1abd2a2b94fef482fc
[ "Apache-2.0" ]
7
2021-11-18T12:52:31.000Z
2022-03-23T21:28:27.000Z
openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/ServiceDeclarationNodesTests.java
kapilraajP/openapi-tools
4fb7a186ab217df127ed8c1abd2a2b94fef482fc
[ "Apache-2.0" ]
231
2021-11-17T08:57:53.000Z
2022-03-30T11:06:06.000Z
openapi-cli/src/test/java/io/ballerina/openapi/generators/openapi/ServiceDeclarationNodesTests.java
kapilraajP/openapi-tools
4fb7a186ab217df127ed8c1abd2a2b94fef482fc
[ "Apache-2.0" ]
13
2021-12-05T15:49:03.000Z
2022-03-23T21:29:13.000Z
44.412844
117
0.699029
998,086
/* * Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.ballerina.openapi.generators.openapi; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.io.FilenameFilter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Objects; import java.util.stream.Collectors; import java.util.stream.Stream; import static io.ballerina.openapi.generators.openapi.TestUtils.deleteDirectory; /** * This test class contains the service nodes related special scenarios. */ public class ServiceDeclarationNodesTests { private static final Path RES_DIR = Paths.get("src/test/resources/ballerina-to-openapi/advance").toAbsolutePath(); private Path tempDir; @BeforeMethod public void setup() throws IOException { this.tempDir = Files.createTempDirectory("bal-to-openapi-test-out-" + System.nanoTime()); } @Test(description = "Multiple services with same absolute path") public void multipleServiceWithSameAbsolute() throws IOException { Path ballerinaFilePath = RES_DIR.resolve("multiple_services.bal"); executeMethod(ballerinaFilePath, "multiple_service_01.yaml", "hello_openapi.yaml", "hello_"); } @Test(description = "Multiple services with absolute path as '/'. ") public void multipleServiceWithOutAbsolute() throws IOException { Path ballerinaFilePath = RES_DIR.resolve("multiple_services_without_base_path.bal"); executeMethod(ballerinaFilePath, "multiple_service_02.yaml", "multiple_services_without_base_path_openapi.yaml", "multiple_services_without_base_path_"); } @Test(description = "Multiple services with no absolute path") public void multipleServiceNoBasePath() throws IOException { Path ballerinaFilePath = RES_DIR.resolve("multiple_services_no_base_path.bal"); executeMethod(ballerinaFilePath, "multiple_service_03.yaml", "multiple_services_no_base_path_openapi.yaml", "multiple_services_no_base_path_"); } private static String getStringFromGivenBalFile(Path expectedServiceFile, String s) throws IOException { Stream<String> expectedServiceLines = Files.lines(expectedServiceFile.resolve(s)); String expectedServiceContent = expectedServiceLines.collect(Collectors.joining("\n")); expectedServiceLines.close(); return expectedServiceContent; } public static String findFile(Path dir, String dirName) { FilenameFilter fileNameFilter = (dir1, name) -> name.startsWith(dirName); String[] fileNames = Objects.requireNonNull(dir.toFile().list(fileNameFilter)); return fileNames.length > 0 ? fileNames[0] : null; } private void executeMethod(Path ballerinaFilePath, String yamlFile, String generatedYamlFile, String secondGeneratedFile) throws IOException { Path tempDir = Files.createTempDirectory("bal-to-openapi-test-out-" + System.nanoTime()); try { String expectedYamlContent = getStringFromGivenBalFile(RES_DIR.resolve("openapi"), yamlFile); OpenApiConverter openApiConverter = new OpenApiConverter(); openApiConverter.generateOAS3DefinitionsAllService(ballerinaFilePath, tempDir, null, false); if (Files.exists(tempDir.resolve(generatedYamlFile)) && findFile(tempDir, secondGeneratedFile) != null) { String generatedYaml = getStringFromGivenBalFile(tempDir, generatedYamlFile); generatedYaml = (generatedYaml.trim()).replaceAll("\\s+", ""); expectedYamlContent = (expectedYamlContent.trim()).replaceAll("\\s+", ""); Assert.assertTrue(generatedYaml.contains(expectedYamlContent)); } else { Assert.fail("Yaml was not generated"); } } catch (IOException e) { Assert.fail("Error while generating the service. " + e.getMessage()); } finally { deleteDirectory(tempDir); System.gc(); } } }
923781d1c26b3b8dee6ff1f8f29557d69a7c7d45
3,358
java
Java
src/test/java/com/jenkov/db/test/util/MappingUtilTest.java
jjenkov/butterfly-persistence
c9123830eb311ec84ea7055b08664e96dff58e48
[ "Apache-2.0" ]
23
2016-04-26T14:21:57.000Z
2022-03-06T23:35:32.000Z
src/test/java/com/jenkov/db/test/util/MappingUtilTest.java
jjenkov/butterfly-persistence
c9123830eb311ec84ea7055b08664e96dff58e48
[ "Apache-2.0" ]
6
2019-12-14T10:30:55.000Z
2022-02-04T23:30:53.000Z
src/test/java/com/jenkov/db/test/util/MappingUtilTest.java
jjenkov/butterfly-persistence
c9123830eb311ec84ea7055b08664e96dff58e48
[ "Apache-2.0" ]
16
2016-05-05T16:56:12.000Z
2020-07-03T09:45:39.000Z
34.979167
107
0.712924
998,087
package com.jenkov.db.test.util; import com.jenkov.db.impl.mapping.Key; import com.jenkov.db.impl.mapping.KeyValue; import com.jenkov.db.impl.mapping.ObjectMappingFactory; import com.jenkov.db.itf.mapping.*; import com.jenkov.db.test.objects.PersistentObject; import com.jenkov.db.util.MappingUtil; import com.jenkov.testing.mock.impl.MethodInvocation; import com.jenkov.testing.mock.impl.MockFactory; import com.jenkov.testing.mock.itf.IMock; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.sql.PreparedStatement; import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Jakob Jenkov - Copyright 2005 Jenkov Development */ public class MappingUtilTest{ private IObjectMappingFactory mappingFactory = new ObjectMappingFactory(); private IObjectMapping mapping = null; @BeforeEach protected void setUp() throws Exception { mapping = mappingFactory.createObjectMapping(); IKey primaryKey = new Key(); primaryKey.setTable("persistent_object"); primaryKey.addColumn("id"); primaryKey.addColumn("name"); mapping.setPrimaryKey(primaryKey); IGetterMapping getterMapping = this.mappingFactory.createGetterMapping(long.class); getterMapping.setColumnName("id"); getterMapping.setObjectMethod(PersistentObject.class.getMethod("getId", null)); getterMapping.setTableMapped(true); mapping.addGetterMapping(getterMapping); getterMapping = this.mappingFactory.createGetterMapping(String.class); getterMapping.setColumnName("name"); getterMapping.setObjectMethod(PersistentObject.class.getMethod("getName", null)); getterMapping.setTableMapped(true); mapping.addGetterMapping(getterMapping); } @Test public void testInsertPrimaryKey() throws Exception{ PreparedStatement statement = (PreparedStatement) MockFactory.createProxy(PreparedStatement.class); IMock invocationHandler = MockFactory.getMock(statement); IKeyValue keyValue = new KeyValue(); keyValue.addColumnValue("id" , new Long(99)); keyValue.addColumnValue("name", "aName"); MappingUtil.insertPrimaryKey(this.mapping, keyValue, statement, 1); MethodInvocation invocation = new MethodInvocation("setLong", new Class[]{int.class, long.class}, new Object[]{new Integer(1), new Long(99)}); invocationHandler.assertInvoked(invocation); invocation = new MethodInvocation("setString", new Class[]{int.class, String.class}, new Object[]{new Integer(2), "aName"}); invocationHandler.assertInvoked(invocation); this.mapping.getPrimaryKey().removeColumn("name"); invocationHandler.clear(); MappingUtil.insertPrimaryKey(this.mapping, keyValue, statement, 1); invocation = new MethodInvocation("setLong", new Class[]{int.class, long.class}, new Object[]{new Integer(1), new Long(99)}); invocationHandler.assertInvoked(invocation); this.mapping.getPrimaryKey().removeColumn("id"); invocationHandler.clear(); MappingUtil.insertPrimaryKey(this.mapping, keyValue, statement, 1); assertEquals(0, invocationHandler.getInvocations().size(), "should be no invcations"); } }
923781f04b4fac98e7a982abc92e3eb2ec3c5972
8,615
java
Java
core/servicemix-core/src/main/java/org/apache/servicemix/components/util/PojoSupport.java
cquoss/servicemix3
a4ce3148916c940fa204b713795bb21e8d0cd42e
[ "Apache-2.0" ]
2
2015-07-29T22:58:57.000Z
2021-11-10T19:04:24.000Z
core/servicemix-core/src/main/java/org/apache/servicemix/components/util/PojoSupport.java
cquoss/servicemix3
a4ce3148916c940fa204b713795bb21e8d0cd42e
[ "Apache-2.0" ]
null
null
null
core/servicemix-core/src/main/java/org/apache/servicemix/components/util/PojoSupport.java
cquoss/servicemix3
a4ce3148916c940fa204b713795bb21e8d0cd42e
[ "Apache-2.0" ]
12
2015-10-05T13:32:39.000Z
2021-11-10T19:04:18.000Z
32.756654
106
0.675334
998,088
/* * 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.servicemix.components.util; import javax.jbi.JBIException; import javax.jbi.component.ComponentContext; import javax.jbi.component.ComponentLifeCycle; import javax.jbi.messaging.DeliveryChannel; import javax.jbi.messaging.ExchangeStatus; import javax.jbi.messaging.Fault; import javax.jbi.messaging.InOnly; import javax.jbi.messaging.InOptionalOut; import javax.jbi.messaging.InOut; import javax.jbi.messaging.MessageExchange; import javax.jbi.messaging.MessageExchangeFactory; import javax.jbi.messaging.MessagingException; import javax.jbi.messaging.NormalizedMessage; import javax.jbi.servicedesc.ServiceEndpoint; import javax.management.ObjectName; import javax.xml.namespace.QName; import org.apache.servicemix.jbi.FaultException; import org.apache.servicemix.jbi.NotInitialisedYetException; import org.apache.servicemix.jbi.management.BaseLifeCycle; /** * A useful base class for a POJO based JBI component which contains most of the basic plumbing * * @version $Revision$ */ public abstract class PojoSupport extends BaseLifeCycle implements ComponentLifeCycle { private ComponentContext context; private ObjectName extensionMBeanName; private QName service; private String endpoint; private MessageExchangeFactory exchangeFactory; private String description = "POJO Component"; private ServiceEndpoint serviceEndpoint; private DeliveryChannel channel; protected PojoSupport() { } protected PojoSupport(QName service, String endpoint) { this.service = service; this.endpoint = endpoint; } /** * Get the description * @return the description */ public String getDescription() { return description; } /** * Called when the Component is initialized * * @param cc * @throws JBIException */ public void init(ComponentContext cc) throws JBIException { this.context = cc; this.channel = this.context.getDeliveryChannel(); init(); if (service != null && endpoint != null) { serviceEndpoint = context.activateEndpoint(service, endpoint); } } /** * Shut down the item. The releases resources, preparing to uninstall * * @exception javax.jbi.JBIException if the item fails to shut down. */ public void shutDown() throws javax.jbi.JBIException { if (serviceEndpoint != null) { context.deactivateEndpoint(serviceEndpoint); } exchangeFactory = null; super.shutDown(); } // Helper methods //------------------------------------------------------------------------- /** * A helper method to return the body of the message as a POJO which could be a * bean or some DOMish model of the body. * * @param message the message on which to extract the body * @return the body of the message as a POJO or DOM object * @throws MessagingException */ public Object getBody(NormalizedMessage message) throws MessagingException { return MessageHelper.getBody(message); } /** * Sets the body of the message as a POJO * * @param message the message on which to set the body * @param body the POJO or DOMish model to set * @throws MessagingException */ public void setBody(NormalizedMessage message, Object body) throws MessagingException { MessageHelper.setBody(message, body); } // Properties //------------------------------------------------------------------------- public ObjectName getExtensionMBeanName() { return extensionMBeanName; } public void setExtensionMBeanName(ObjectName extensionMBeanName) { this.extensionMBeanName = extensionMBeanName; } public ComponentContext getContext() { return context; } public QName getService() { return service; } public void setService(QName service) { this.service = service; } public String getEndpoint() { return endpoint; } public void setEndpoint(String endpoint) { this.endpoint = endpoint; } /** * Provide access to the default message exchange exchangeFactory, lazily creating one. */ public MessageExchangeFactory getExchangeFactory() throws MessagingException { if (exchangeFactory == null && context != null) { exchangeFactory = getDeliveryChannel().createExchangeFactory(); } return exchangeFactory; } public DeliveryChannel getDeliveryChannel() throws MessagingException { if (channel == null) { throw new NotInitialisedYetException(); } return channel; } /** * A helper method to allow a component to initialise prior to the endpoint being activated * but after the component context has been configured. * * @throws JBIException */ protected void init() throws JBIException { super.init(); } /** * A helper method to indicate that the message exchange is complete * which will set the status to {@link ExchangeStatus#DONE} and send the message * on the delivery channel. * * @param exchange * @throws MessagingException */ public void done(MessageExchange exchange) throws MessagingException { exchange.setStatus(ExchangeStatus.DONE); getDeliveryChannel().send(exchange); } public void send(MessageExchange exchange) throws MessagingException { getDeliveryChannel().send(exchange); } public boolean sendSync(MessageExchange exchange) throws MessagingException { return getDeliveryChannel().sendSync(exchange); } public boolean sendSync(MessageExchange exchange, long timeMillis) throws MessagingException { return getDeliveryChannel().sendSync(exchange, timeMillis); } /** * A helper method to indicate that the message exchange should be * continued with the given response and send the message * on the delivery channel. * * @param exchange * @throws MessagingException */ public void answer(MessageExchange exchange, NormalizedMessage answer) throws MessagingException { exchange.setMessage(answer, "out"); getDeliveryChannel().send(exchange); } /** * A helper method which fails and completes the given exchange with the specified fault */ public void fail(MessageExchange exchange, Fault fault) throws MessagingException { if (exchange instanceof InOnly || fault == null) { exchange.setError(new FaultException("Fault occured for in-only exchange", exchange, fault)); } else { exchange.setFault(fault); } getDeliveryChannel().send(exchange); } /** * A helper method which fails and completes the given exchange with the specified error * @throws MessagingException */ public void fail(MessageExchange exchange, Exception error) throws MessagingException { if (exchange instanceof InOnly || !(error instanceof FaultException)) { exchange.setError(error); } else { FaultException faultException = (FaultException) error; exchange.setFault(faultException.getFault()); } getDeliveryChannel().send(exchange); } /** * A helper method which will return true if the exchange is capable of both In and Out such as InOut, * InOptionalOut etc. * * @param exchange * @return true if the exchange can handle both input and output */ protected boolean isInAndOut(MessageExchange exchange) { return exchange instanceof InOut || exchange instanceof InOptionalOut; } }
9237823ba14a424e5a79bf5acdf21070c2802e8a
1,373
java
Java
tapestry5-annotations/src/main/java/org/apache/tapestry5/beaneditor/RelativePosition.java
shisheng-1/tapestry-5
28ac1aebdf09d27611d111c702266b12e10b074c
[ "Apache-2.0" ]
72
2015-02-23T16:30:56.000Z
2022-03-30T03:42:27.000Z
tapestry5-annotations/src/main/java/org/apache/tapestry5/beaneditor/RelativePosition.java
shisheng-1/tapestry-5
28ac1aebdf09d27611d111c702266b12e10b074c
[ "Apache-2.0" ]
7
2016-03-03T10:21:45.000Z
2021-12-02T20:03:17.000Z
tapestry5-annotations/src/main/java/org/apache/tapestry5/beaneditor/RelativePosition.java
shisheng-1/tapestry-5
28ac1aebdf09d27611d111c702266b12e10b074c
[ "Apache-2.0" ]
87
2015-02-20T09:17:50.000Z
2022-01-31T12:11:24.000Z
41.606061
171
0.740714
998,089
// Copyright 2007 The Apache Software Foundation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.apache.tapestry5.beaneditor; /** * Controls the position of newly added <a href="https://tapestry.apache.org/current/apidocs/org/apache/tapestry5/beanmodel/PropertyModel.html">PropertyModel</a> inside a * <a href="https://tapestry.apache.org/current/apidocs/org/apache/tapestry5/beanmodel/BeanModel.html">BeanModel</a>. */ public enum RelativePosition { /** * The new <a href="https://tapestry.apache.org/current/apidocs/org/apache/tapestry5/beanmodel/PropertyModel.html">PropertyModel</a> goes before the existing model. */ BEFORE, /** * The new <a href="https://tapestry.apache.org/current/apidocs/org/apache/tapestry5/beanmodel/PropertyModel.html">PropertyModel</a> goes after the existing model. */ AFTER }
923782f56f48ea85b7414ae772401af8a670722e
7,802
java
Java
distro/wildfly/subsystem/src/main/java/org/camunda/bpm/container/impl/jboss/deployment/processor/ModuleDependencyProcessor.java
npwork/camunda-bpm-platform
41be33a14c712e357aeb669c2f8914af927ea678
[ "Apache-2.0" ]
2,577
2015-01-02T07:43:55.000Z
2022-03-31T22:31:45.000Z
distro/wildfly/subsystem/src/main/java/org/camunda/bpm/container/impl/jboss/deployment/processor/ModuleDependencyProcessor.java
npwork/camunda-bpm-platform
41be33a14c712e357aeb669c2f8914af927ea678
[ "Apache-2.0" ]
839
2015-01-12T22:06:28.000Z
2022-03-24T13:26:29.000Z
distro/wildfly/subsystem/src/main/java/org/camunda/bpm/container/impl/jboss/deployment/processor/ModuleDependencyProcessor.java
npwork/camunda-bpm-platform
41be33a14c712e357aeb669c2f8914af927ea678
[ "Apache-2.0" ]
1,270
2015-01-02T03:39:25.000Z
2022-03-31T06:04:37.000Z
54.943662
163
0.79595
998,090
/* * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH * under one or more contributor license agreements. See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. Camunda licenses this file to you under the Apache License, * Version 2.0; 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.camunda.bpm.container.impl.jboss.deployment.processor; import org.camunda.bpm.container.impl.jboss.deployment.marker.ProcessApplicationAttachments; import org.camunda.bpm.container.impl.jboss.service.ProcessApplicationModuleService; import org.camunda.bpm.container.impl.jboss.service.ServiceNames; import org.jboss.as.server.deployment.AttachmentList; import org.jboss.as.server.deployment.Attachments; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.as.server.deployment.DeploymentUnitProcessor; import org.jboss.as.server.deployment.module.ModuleDependency; import org.jboss.as.server.deployment.module.ModuleSpecification; import org.jboss.modules.Module; import org.jboss.modules.ModuleIdentifier; import org.jboss.modules.ModuleLoader; import org.jboss.msc.service.ServiceController.Mode; import org.jboss.msc.service.ServiceName; /** * <p>This Processor creates implicit module dependencies for process applications</p> * * <p>Concretely speaking, this processor adds a module dependency from the process * application module (deployment unit) to the process engine module (and other camunda libraries * which are useful for process apps).</p> * * @author Daniel Meyer * */ public class ModuleDependencyProcessor implements DeploymentUnitProcessor { public static final int PRIORITY = 0x2300; public static ModuleIdentifier MODULE_IDENTIFYER_PROCESS_ENGINE = ModuleIdentifier.create("org.camunda.bpm.camunda-engine"); public static ModuleIdentifier MODULE_IDENTIFYER_XML_MODEL = ModuleIdentifier.create("org.camunda.bpm.model.camunda-xml-model"); public static ModuleIdentifier MODULE_IDENTIFYER_BPMN_MODEL = ModuleIdentifier.create("org.camunda.bpm.model.camunda-bpmn-model"); public static ModuleIdentifier MODULE_IDENTIFYER_CMMN_MODEL = ModuleIdentifier.create("org.camunda.bpm.model.camunda-cmmn-model"); public static ModuleIdentifier MODULE_IDENTIFYER_DMN_MODEL = ModuleIdentifier.create("org.camunda.bpm.model.camunda-dmn-model"); public static ModuleIdentifier MODULE_IDENTIFYER_SPIN = ModuleIdentifier.create("org.camunda.spin.camunda-spin-core"); public static ModuleIdentifier MODULE_IDENTIFYER_CONNECT = ModuleIdentifier.create("org.camunda.connect.camunda-connect-core"); public static ModuleIdentifier MODULE_IDENTIFYER_ENGINE_DMN = ModuleIdentifier.create("org.camunda.bpm.dmn.camunda-engine-dmn"); public static ModuleIdentifier MODULE_IDENTIFYER_GRAAL_JS = ModuleIdentifier.create("org.graalvm.js.js-scriptengine"); public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); if (deploymentUnit.getParent() == null) { //The deployment unit has no parent so it is a simple war or an ear. ModuleLoader moduleLoader = Module.getBootModuleLoader(); //If it is a simpleWar and marked with process application we have to add the dependency boolean isProcessApplicationWarOrEar = ProcessApplicationAttachments.isProcessApplication(deploymentUnit); AttachmentList<DeploymentUnit> subdeployments = deploymentUnit.getAttachment(Attachments.SUB_DEPLOYMENTS); //Is the list of sub deployments empty the deployment unit is a war file. //In cases of war files we have nothing todo. if (subdeployments != null) { //The deployment unit contains sub deployments which means the deployment unit is an ear. //We have to check whether sub deployments are process applications or not. boolean subDeploymentIsProcessApplication = false; for (DeploymentUnit subDeploymentUnit : subdeployments) { if (ProcessApplicationAttachments.isProcessApplication(subDeploymentUnit)) { subDeploymentIsProcessApplication = true; break; } } //If one sub deployment is a process application then we add to all the dependency //Also we have to add the dependency to the current deployment unit which is an ear if (subDeploymentIsProcessApplication) { for (DeploymentUnit subDeploymentUnit : subdeployments) { final ModuleSpecification moduleSpecification = subDeploymentUnit.getAttachment(Attachments.MODULE_SPECIFICATION); addSystemDependencies(moduleLoader, moduleSpecification); } //An ear is not marked as process application but also needs the dependency isProcessApplicationWarOrEar = true; } } if (isProcessApplicationWarOrEar) { final ModuleSpecification moduleSpecification = deploymentUnit.getAttachment(Attachments.MODULE_SPECIFICATION); addSystemDependencies(moduleLoader, moduleSpecification); } } // install the pa-module service ModuleIdentifier identifyer = deploymentUnit.getAttachment(Attachments.MODULE_IDENTIFIER); String moduleName = identifyer.toString(); ProcessApplicationModuleService processApplicationModuleService = new ProcessApplicationModuleService(); ServiceName serviceName = ServiceNames.forProcessApplicationModuleService(moduleName); phaseContext.getServiceTarget() .addService(serviceName, processApplicationModuleService) .addDependency(phaseContext.getPhaseServiceName()) .setInitialMode(Mode.ACTIVE) .install(); } private void addSystemDependencies(ModuleLoader moduleLoader, final ModuleSpecification moduleSpecification) { addSystemDependency(moduleLoader, moduleSpecification, MODULE_IDENTIFYER_PROCESS_ENGINE); addSystemDependency(moduleLoader, moduleSpecification, MODULE_IDENTIFYER_XML_MODEL); addSystemDependency(moduleLoader, moduleSpecification, MODULE_IDENTIFYER_BPMN_MODEL); addSystemDependency(moduleLoader, moduleSpecification, MODULE_IDENTIFYER_CMMN_MODEL); addSystemDependency(moduleLoader, moduleSpecification, MODULE_IDENTIFYER_DMN_MODEL); addSystemDependency(moduleLoader, moduleSpecification, MODULE_IDENTIFYER_SPIN); addSystemDependency(moduleLoader, moduleSpecification, MODULE_IDENTIFYER_CONNECT); addSystemDependency(moduleLoader, moduleSpecification, MODULE_IDENTIFYER_ENGINE_DMN); addSystemDependency(moduleLoader, moduleSpecification, MODULE_IDENTIFYER_GRAAL_JS, true); } private void addSystemDependency(ModuleLoader moduleLoader, final ModuleSpecification moduleSpecification, ModuleIdentifier dependency) { addSystemDependency(moduleLoader, moduleSpecification, dependency, false); } private void addSystemDependency(ModuleLoader moduleLoader, final ModuleSpecification moduleSpecification, ModuleIdentifier dependency, boolean importServices) { moduleSpecification.addSystemDependency(new ModuleDependency(moduleLoader, dependency, false, false, importServices, false)); } public void undeploy(DeploymentUnit context) { } }
92378396f57ab8d85f1f8590e6701eda76c8100e
464
java
Java
wms-produce-manage/src/main/java/com/deer/wms/produce/manage/service/ProcessQualityInfoService.java
yuanfayang/wms-parent
17d7796daf9f75d05c8505f69f2bc2baf3192cc6
[ "0BSD" ]
null
null
null
wms-produce-manage/src/main/java/com/deer/wms/produce/manage/service/ProcessQualityInfoService.java
yuanfayang/wms-parent
17d7796daf9f75d05c8505f69f2bc2baf3192cc6
[ "0BSD" ]
null
null
null
wms-produce-manage/src/main/java/com/deer/wms/produce/manage/service/ProcessQualityInfoService.java
yuanfayang/wms-parent
17d7796daf9f75d05c8505f69f2bc2baf3192cc6
[ "0BSD" ]
null
null
null
25.777778
89
0.797414
998,091
package com.deer.wms.produce.manage.service; import com.deer.wms.produce.manage.model.ProcessQualityInfo; import com.deer.wms.produce.manage.model.ProcessQualityInfoParams; import com.deer.wms.project.seed.core.service.Service; import java.util.List; /** * Created by hy on 2019/07/19. */ public interface ProcessQualityInfoService extends Service<ProcessQualityInfo, Integer> { //List<ProcessQualityInfo> findList(ProcessQualityInfoParams params) ; }
923783e4c97fb9f76237a78ccaca5ed14274823c
1,622
java
Java
clients/src/test/java/org/apache/kafka/common/utils/ShellTest.java
JoeHughes-IBM/Kafka
6185bc0276c03075022c30d3c36f7f5c09ef19c6
[ "Apache-2.0" ]
20
2015-06-05T03:44:18.000Z
2019-06-05T19:37:54.000Z
clients/src/test/java/org/apache/kafka/common/utils/ShellTest.java
JoeHughes-IBM/Kafka
6185bc0276c03075022c30d3c36f7f5c09ef19c6
[ "Apache-2.0" ]
4
2016-08-11T19:50:18.000Z
2017-06-27T16:59:11.000Z
clients/src/test/java/org/apache/kafka/common/utils/ShellTest.java
JoeHughes-IBM/Kafka
6185bc0276c03075022c30d3c36f7f5c09ef19c6
[ "Apache-2.0" ]
14
2015-07-09T11:21:53.000Z
2019-05-15T02:07:57.000Z
36.044444
95
0.724414
998,092
/* * 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.common.utils; import org.junit.Rule; import org.junit.Test; import org.junit.rules.Timeout; import static org.junit.Assert.assertEquals; import static org.junit.Assume.assumeTrue; public class ShellTest { @Rule public final Timeout globalTimeout = Timeout.seconds(180); @Test public void testEchoHello() throws Exception { assumeTrue(!OperatingSystem.IS_WINDOWS); String output = Shell.execCommand("echo", "hello"); assertEquals("hello\n", output); } @Test public void testHeadDevZero() throws Exception { assumeTrue(!OperatingSystem.IS_WINDOWS); final int length = 100000; String output = Shell.execCommand("head", "-c", Integer.toString(length), "/dev/zero"); assertEquals(length, output.length()); } }
9237842301eadffff86218c5a3b029dc296f570d
3,984
java
Java
src/main/java/com/irontigers/robot/Constants.java
npmanos/infiniterecharge2021
26b35115363ff1fde1d02275e0496bb2066a1c46
[ "BSD-3-Clause" ]
1
2021-03-15T04:26:03.000Z
2021-03-15T04:26:03.000Z
src/main/java/com/irontigers/robot/Constants.java
npmanos/infiniterecharge2021
26b35115363ff1fde1d02275e0496bb2066a1c46
[ "BSD-3-Clause" ]
null
null
null
src/main/java/com/irontigers/robot/Constants.java
npmanos/infiniterecharge2021
26b35115363ff1fde1d02275e0496bb2066a1c46
[ "BSD-3-Clause" ]
1
2021-06-03T23:45:27.000Z
2021-06-03T23:45:27.000Z
39.445545
100
0.640562
998,093
/*----------------------------------------------------------------------------*/ /* Copyright (c) 2018-2019 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ package com.irontigers.robot; import edu.wpi.first.wpilibj.util.Units; /** * The Constants class provides a convenient place for teams to hold robot-wide * numerical or boolean constants. This class should not be used for any other * purpose. All constants should be declared globally (i.e. public static). Do * not put anything functional in this class. * * <p> * It is advised to statically import this class (or one of its inner classes) * wherever the constants are needed, to reduce verbosity. */ public final class Constants { public static final class Drive { public static final int FRNT_LFT = 2; public static final int BCK_LFT = 1; public static final int FRNT_RT = 4; public static final int BCK_RT = 3; public static final double ENC_CNV_FCTR = 1 / 8.45 * (Units.inchesToMeters(6) * Math.PI); } public static final class Shooter { public static final int FLYWHEEL_ADDR = 1; public static final int TURRET_ADDR = 2; public static final double DEFUALT_SHOOTER_SPD = 1; public static final double DEFAULT_TURRET_SPD = 0.05; public static final double AUTO_TURRET_SPD_FAST = 0.1; public static final double AUTO_TURRET_SPD_SLOW = 0.07; public static final double MAX_TURRET_SPD = 0.1; public static final double TURRET_ANGLE_CNV_FACTOR = 204800.0 / 1803.0; public static final int MAX_TURRET_ANGLE = 30; // Final value is 85 (we hope) public static final int MOTOR_TOOTH_CNT = 16; public static final int FLYWHEEL_TOOTH_CNT = 24; public static final double FLYWHEEL_CIRCUM_FT = 0.5 * Math.PI; public static final double FLYWHEEL_RPS_CNV_FACTOR = (16.0 * 10.0) / (24.0 * 2048.0); public static final double TARGET_FLYWHEEL_RPM = 67000; public static final double ANGLE = Units.degreesToRadians(30); public static final double HEIGHT_OFFSET = 0; //3.75; public static final double TARGET_HEIGHT = GameField.TOP_PORT_CENTER_HEIGHT - HEIGHT_OFFSET; public static final double POWER_INCREMENT = 1.0 / 100.0; public static final long TURRET_ENC_OFFSET = -527; public static final double TURRET_KP = 0.00413; public static final double TURRET_KI = 0.00; public static final double TURRET_KD = 0.0121; public static final double TURRET_MAX_V = 100; public static final double TURRET_MAX_A = 100; public static final double TURRET_KS = 0.37; public static final double TURRET_KV = 0.00863; } public static final class Magazine { public static final int MAG_ADDR = 6; public static final int INTAKE_ADDR = 7; public static final int BOT_SENSOR_PORT = 0; public static final int TOP_SENSOR_PORT = 1; public static final int GATE_PORT = 0; public static final double MAG_SPD = .2; public static final double INTAKE_SPD = .3; } public static final class VISION { public static final double HEIGHT = 37.5; private static final double yOffset = 0.830619; } public static final class Controllers { public static final int PORT = 0; public static final int TEST_PORT = 1; } public static final class GameField { public static final double TOP_PORT_CENTER_HEIGHT = 8.1875 * 12.0; } public static final class Falcon500 { public static final int ENCODER_PPR = 2048; } }
9237843f61c94d2bd89470bb284bbb874a689902
9,185
java
Java
src/main/java/org/onebusaway/gtfs_realtime/trip_updates_producer_demo/GtfsRealtimeProviderImpl.java
JLLeitschuh/onebusaway-gtfs-realtime-trip-updates-producer-demo
f1391145abcf509862bb51ad8c405580cffba67c
[ "Apache-2.0" ]
8
2016-03-22T10:48:09.000Z
2021-02-03T03:17:05.000Z
src/main/java/org/onebusaway/gtfs_realtime/trip_updates_producer_demo/GtfsRealtimeProviderImpl.java
JLLeitschuh/onebusaway-gtfs-realtime-trip-updates-producer-demo
f1391145abcf509862bb51ad8c405580cffba67c
[ "Apache-2.0" ]
2
2020-02-11T15:11:53.000Z
2021-02-03T03:27:59.000Z
src/main/java/org/onebusaway/gtfs_realtime/trip_updates_producer_demo/GtfsRealtimeProviderImpl.java
JLLeitschuh/onebusaway-gtfs-realtime-trip-updates-producer-demo
f1391145abcf509862bb51ad8c405580cffba67c
[ "Apache-2.0" ]
10
2015-04-08T02:08:41.000Z
2022-02-04T08:41:00.000Z
34.923954
93
0.728035
998,094
/** * Copyright (C) 2012 Google, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onebusaway.gtfs_realtime.trip_updates_producer_demo; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.inject.Inject; import javax.inject.Singleton; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONTokener; import org.onebusway.gtfs_realtime.exporter.GtfsRealtimeExporterModule; import org.onebusway.gtfs_realtime.exporter.GtfsRealtimeLibrary; import org.onebusway.gtfs_realtime.exporter.GtfsRealtimeMutableProvider; import org.onebusway.gtfs_realtime.exporter.GtfsRealtimeProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.transit.realtime.GtfsRealtime.FeedEntity; import com.google.transit.realtime.GtfsRealtime.FeedMessage; import com.google.transit.realtime.GtfsRealtime.Position; import com.google.transit.realtime.GtfsRealtime.TripDescriptor; import com.google.transit.realtime.GtfsRealtime.TripUpdate; import com.google.transit.realtime.GtfsRealtime.TripUpdate.StopTimeEvent; import com.google.transit.realtime.GtfsRealtime.TripUpdate.StopTimeUpdate; import com.google.transit.realtime.GtfsRealtime.VehicleDescriptor; import com.google.transit.realtime.GtfsRealtime.VehiclePosition; /** * This class produces GTFS-realtime trip updates and vehicle positions by * periodically polling the custom SEPTA vehicle data API and converting the * resulting vehicle data into the GTFS-realtime format. * * Since this class implements {@link GtfsRealtimeProvider}, it will * automatically be queried by the {@link GtfsRealtimeExporterModule} to export * the GTFS-realtime feeds to file or to host them using a simple web-server, as * configured by the client. * * @author bdferris * */ @Singleton public class GtfsRealtimeProviderImpl { private static final Logger _log = LoggerFactory.getLogger(GtfsRealtimeProviderImpl.class); private ScheduledExecutorService _executor; private GtfsRealtimeMutableProvider _gtfsRealtimeProvider; private URL _url; /** * How often vehicle data will be downloaded, in seconds. */ private int _refreshInterval = 30; @Inject public void setGtfsRealtimeProvider(GtfsRealtimeMutableProvider gtfsRealtimeProvider) { _gtfsRealtimeProvider = gtfsRealtimeProvider; } /** * @param url the URL for the SEPTA vehicle data API. */ public void setUrl(URL url) { _url = url; } /** * @param refreshInterval how often vehicle data will be downloaded, in * seconds. */ public void setRefreshInterval(int refreshInterval) { _refreshInterval = refreshInterval; } /** * The start method automatically starts up a recurring task that periodically * downloads the latest vehicle data from the SEPTA vehicle stream and * processes them. */ @PostConstruct public void start() { _log.info("starting GTFS-realtime service"); _executor = Executors.newSingleThreadScheduledExecutor(); _executor.scheduleAtFixedRate(new VehiclesRefreshTask(), 0, _refreshInterval, TimeUnit.SECONDS); } /** * The stop method cancels the recurring vehicle data downloader task. */ @PreDestroy public void stop() { _log.info("stopping GTFS-realtime service"); _executor.shutdownNow(); } /**** * Private Methods - Here is where the real work happens ****/ /** * This method downloads the latest vehicle data, processes each vehicle in * turn, and create a GTFS-realtime feed of trip updates and vehicle positions * as a result. */ private void refreshVehicles() throws IOException, JSONException { /** * We download the vehicle details as an array of JSON objects. */ JSONArray vehicleArray = downloadVehicleDetails(); /** * The FeedMessage.Builder is what we will use to build up our GTFS-realtime * feeds. We create a feed for both trip updates and vehicle positions. */ FeedMessage.Builder tripUpdates = GtfsRealtimeLibrary.createFeedMessageBuilder(); FeedMessage.Builder vehiclePositions = GtfsRealtimeLibrary.createFeedMessageBuilder(); /** * We iterate over every JSON vehicle object. */ for (int i = 0; i < vehicleArray.length(); ++i) { JSONObject obj = vehicleArray.getJSONObject(i); String trainNumber = obj.getString("trainno"); String route = obj.getString("dest"); String stopId = obj.getString("nextstop"); double lat = obj.getDouble("lat"); double lon = obj.getDouble("lon"); int delay = obj.getInt("late"); /** * We construct a TripDescriptor and VehicleDescriptor, which will be used * in both trip updates and vehicle positions to identify the trip and * vehicle. Ideally, we would have a trip id to use for the trip * descriptor, but the SEPTA api doesn't include it, so we settle for a * route id instead. */ TripDescriptor.Builder tripDescriptor = TripDescriptor.newBuilder(); tripDescriptor.setRouteId(route); VehicleDescriptor.Builder vehicleDescriptor = VehicleDescriptor.newBuilder(); vehicleDescriptor.setId(trainNumber); /** * To construct our TripUpdate, we create a stop-time arrival event for * the next stop for the vehicle, with the specified arrival delay. We add * the stop-time update to a TripUpdate builder, along with the trip and * vehicle descriptors. */ StopTimeEvent.Builder arrival = StopTimeEvent.newBuilder(); arrival.setDelay(delay * 60); StopTimeUpdate.Builder stopTimeUpdate = StopTimeUpdate.newBuilder(); stopTimeUpdate.setArrival(arrival); stopTimeUpdate.setStopId(stopId); TripUpdate.Builder tripUpdate = TripUpdate.newBuilder(); tripUpdate.addStopTimeUpdate(stopTimeUpdate); tripUpdate.setTrip(tripDescriptor); tripUpdate.setVehicle(vehicleDescriptor); /** * Create a new feed entity to wrap the trip update and add it to the * GTFS-realtime trip updates feed. */ FeedEntity.Builder tripUpdateEntity = FeedEntity.newBuilder(); tripUpdateEntity.setId(trainNumber); tripUpdateEntity.setTripUpdate(tripUpdate); tripUpdates.addEntity(tripUpdateEntity); /** * To construct our VehiclePosition, we create a position for the vehicle. * We add the position to a VehiclePosition builder, along with the trip * and vehicle descriptors. */ Position.Builder position = Position.newBuilder(); position.setLatitude((float) lat); position.setLongitude((float) lon); VehiclePosition.Builder vehiclePosition = VehiclePosition.newBuilder(); vehiclePosition.setPosition(position); vehiclePosition.setTrip(tripDescriptor); vehiclePosition.setVehicle(vehicleDescriptor); /** * Create a new feed entity to wrap the vehicle position and add it to the * GTFS-realtime vehicle positions feed. */ FeedEntity.Builder vehiclePositionEntity = FeedEntity.newBuilder(); vehiclePositionEntity.setId(trainNumber); vehiclePositionEntity.setVehicle(vehiclePosition); vehiclePositions.addEntity(vehiclePositionEntity); } /** * Build out the final GTFS-realtime feed messagse and save them. */ _gtfsRealtimeProvider.setTripUpdates(tripUpdates.build()); _gtfsRealtimeProvider.setVehiclePositions(vehiclePositions.build()); _log.info("vehicles extracted: " + tripUpdates.getEntityCount()); } /** * @return a JSON array parsed from the data pulled from the SEPTA vehicle * data API. */ private JSONArray downloadVehicleDetails() throws IOException, JSONException { BufferedReader reader = new BufferedReader(new InputStreamReader( _url.openStream())); JSONTokener tokener = new JSONTokener(reader); JSONArray vehiclesArray = new JSONArray(tokener); return vehiclesArray; } /** * Task that will download new vehicle data from the remote data source when * executed. */ private class VehiclesRefreshTask implements Runnable { @Override public void run() { try { _log.info("refreshing vehicles"); refreshVehicles(); } catch (Exception ex) { _log.warn("Error in vehicle refresh task", ex); } } } }
9237844bbfe325e203e82035fceb48b69d360994
1,263
java
Java
ByteByByte/3Sum/ThreeSumSolution.java
Gadigeppa-J/ds-algo-java
0f1c12d48e5045baacdf2768daae1fdf42c21893
[ "Apache-2.0" ]
null
null
null
ByteByByte/3Sum/ThreeSumSolution.java
Gadigeppa-J/ds-algo-java
0f1c12d48e5045baacdf2768daae1fdf42c21893
[ "Apache-2.0" ]
null
null
null
ByteByByte/3Sum/ThreeSumSolution.java
Gadigeppa-J/ds-algo-java
0f1c12d48e5045baacdf2768daae1fdf42c21893
[ "Apache-2.0" ]
null
null
null
14.686047
138
0.522565
998,095
/** * @author: Gadigeppa Muthu * @date: 18-Apr-2020 * * Question: Given a list of integers, write a function that returns all sets of 3 numbers in the list, a, b, and c, so that a + b + c == 0 * * threeSum({-1, 0, 1, 2, -1, -4}) * [-1, -1, 2] * [-1, 0, 1] * **/ import java.util.List; import java.util.ArrayList; import java.util.Arrays; public class ThreeSumSolution{ public static List<List<Integer>> threeSum(int[] nums) { Arrays.sort(nums); List<List<Integer>> result = new ArrayList<>(); for (int i = 0 ; i < nums.length-2; i++){ if (i>0 && nums[i]==nums[i-1]){continue;} int j=i+1; int k=nums.length-1; while(j<k){ //System.out.println(nums[i]); if (j>i+1 && nums[j]==nums[j-1]){ j++; continue; } if (k<nums.length-1 && nums[k]==nums[k+1]){ k--; continue; } int sm = nums[i] + nums[j] + nums[k]; if (sm==0){ result.add(Arrays.asList(nums[i], nums[j], nums[k])); j++; k--; }else if (sm>0){ k--; }else{ j++; } } } return result; } public static void main(String[] args){ List<List<Integer>> result = threeSum(new int[]{-1, 0, 1, 2, -1, -4}); System.out.println(result); } }
923784c461ab2e707eee20668e25995e884621f0
7,136
java
Java
java/compiler/impl/src/com/intellij/compiler/backwardRefs/JavaCompilerRefAdapter.java
nvartolomei/intellij-community
1aac326dadacf65d45decc25cef21f94f7b80d69
[ "Apache-2.0" ]
2
2019-04-28T07:48:50.000Z
2020-12-11T14:18:08.000Z
java/compiler/impl/src/com/intellij/compiler/backwardRefs/JavaCompilerRefAdapter.java
nvartolomei/intellij-community
1aac326dadacf65d45decc25cef21f94f7b80d69
[ "Apache-2.0" ]
1
2020-07-30T19:04:47.000Z
2020-07-30T19:04:47.000Z
java/compiler/impl/src/com/intellij/compiler/backwardRefs/JavaCompilerRefAdapter.java
nvartolomei/intellij-community
1aac326dadacf65d45decc25cef21f94f7b80d69
[ "Apache-2.0" ]
1
2020-10-15T05:56:42.000Z
2020-10-15T05:56:42.000Z
41.488372
155
0.703896
998,096
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.compiler.backwardRefs; import com.intellij.ide.highlighter.JavaClassFileType; import com.intellij.ide.highlighter.JavaFileType; import com.intellij.openapi.application.ReadAction; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.roots.impl.LibraryScopeCache; import com.intellij.psi.*; import com.intellij.psi.impl.source.PsiFileWithStubSupport; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.searches.ClassInheritorsSearch; import com.intellij.psi.util.ClassUtil; import com.intellij.util.Processor; import com.intellij.util.containers.ContainerUtil; import gnu.trove.TIntHashSet; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.jps.backwardRefs.CompilerRef; import org.jetbrains.jps.backwardRefs.NameEnumerator; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.stream.Stream; public class JavaCompilerRefAdapter implements LanguageCompilerRefAdapter { @NotNull @Override public Set<FileType> getFileTypes() { return ContainerUtil.set(JavaFileType.INSTANCE, JavaClassFileType.INSTANCE); } @Override public CompilerRef asCompilerRef(@NotNull PsiElement element, @NotNull NameEnumerator names) throws IOException { if (mayBeVisibleOutsideOwnerFile(element)) { if (element instanceof PsiField) { final PsiField field = (PsiField)element; final PsiClass aClass = field.getContainingClass(); if (aClass == null || aClass instanceof PsiAnonymousClass) return null; final String jvmOwnerName = ClassUtil.getJVMClassName(aClass); final String name = field.getName(); if (jvmOwnerName == null) return null; final int ownerId = names.tryEnumerate(jvmOwnerName); if (ownerId == 0) return null; final int nameId = names.tryEnumerate(name); if (nameId == 0) return null; return new CompilerRef.JavaCompilerFieldRef(ownerId, nameId); } else if (element instanceof PsiMethod) { final PsiClass aClass = ((PsiMethod)element).getContainingClass(); if (aClass == null || aClass instanceof PsiAnonymousClass) return null; final String jvmOwnerName = ClassUtil.getJVMClassName(aClass); if (jvmOwnerName == null) return null; final PsiMethod method = (PsiMethod)element; final String name = method.isConstructor() ? "<init>" : method.getName(); final int parametersCount = method.getParameterList().getParametersCount(); final int ownerId = names.tryEnumerate(jvmOwnerName); if (ownerId == 0) return null; final int nameId = names.tryEnumerate(name); if (nameId == 0) return null; return new CompilerRef.JavaCompilerMethodRef(ownerId, nameId, parametersCount); } else if (element instanceof PsiClass) { final String jvmClassName = ClassUtil.getJVMClassName((PsiClass)element); if (jvmClassName != null) { final int nameId = names.tryEnumerate(jvmClassName); if (nameId != 0) { return new CompilerRef.JavaCompilerClassRef(nameId); } } } } return null; } @NotNull @Override public List<CompilerRef> getHierarchyRestrictedToLibraryScope(@NotNull CompilerRef baseRef, @NotNull PsiElement basePsi, @NotNull NameEnumerator names, @NotNull GlobalSearchScope libraryScope) throws IOException { @Nullable PsiClass value = basePsi instanceof PsiClass ? (PsiClass)basePsi : ReadAction.compute(() -> (PsiMember)basePsi).getContainingClass(); final PsiClass baseClass = Objects.requireNonNull(value); final List<CompilerRef> overridden = new ArrayList<>(); final IOException[] exception = new IOException[]{null}; Processor<PsiClass> processor = c -> { if (c.hasModifierProperty(PsiModifier.PRIVATE)) return true; String qName = ReadAction.compute(() -> c.getQualifiedName()); if (qName == null) return true; try { final int nameId = names.tryEnumerate(qName); if (nameId != 0) { overridden.add(baseRef.override(nameId)); } } catch (IOException e) { exception[0] = e; return false; } return true; }; ClassInheritorsSearch.search(baseClass, LibraryScopeCache.getInstance(baseClass.getProject()).getLibrariesOnlyScope(), true).forEach(processor); if (exception[0] != null) { throw exception[0]; } return overridden; } @NotNull @Override public Class<? extends CompilerRef.CompilerClassHierarchyElementDef> getHierarchyObjectClass() { return CompilerRef.CompilerClassHierarchyElementDef.class; } @NotNull @Override public Class<? extends CompilerRef> getFunExprClass() { return CompilerRef.JavaCompilerFunExprDef.class; } @Override public PsiClass @NotNull [] findDirectInheritorCandidatesInFile(SearchId @NotNull [] internalNames, @NotNull PsiFileWithStubSupport file) { return JavaCompilerElementRetriever.retrieveClassesByInternalIds(internalNames, file); } @Override public PsiFunctionalExpression @NotNull [] findFunExpressionsInFile(SearchId @NotNull [] funExpressions, @NotNull PsiFileWithStubSupport file) { TIntHashSet requiredIndices = new TIntHashSet(funExpressions.length); for (SearchId funExpr : funExpressions) { requiredIndices.add(funExpr.getId()); } return JavaCompilerElementRetriever.retrieveFunExpressionsByIndices(requiredIndices, file); } @Override public boolean isClass(@NotNull PsiElement element) { return element instanceof PsiClass; } @Override public PsiElement @NotNull [] getInstantiableConstructors(@NotNull PsiElement aClass) { if (!(aClass instanceof PsiClass)) { throw new IllegalArgumentException("parameter should be an instance of PsiClass: " + aClass); } PsiClass theClass = (PsiClass)aClass; if (theClass.hasModifierProperty(PsiModifier.ABSTRACT)) { return PsiElement.EMPTY_ARRAY; } return Stream.of(theClass.getConstructors()).filter(c -> !c.hasModifierProperty(PsiModifier.PRIVATE)).toArray(s -> PsiElement.ARRAY_FACTORY.create(s)); } @Override public boolean isDirectInheritor(PsiElement candidate, PsiNamedElement baseClass) { return ((PsiClass) candidate).isInheritor((PsiClass) baseClass, false); } private static boolean mayBeVisibleOutsideOwnerFile(@NotNull PsiElement element) { if (!(element instanceof PsiModifierListOwner)) return true; if (((PsiModifierListOwner)element).hasModifierProperty(PsiModifier.PRIVATE)) return false; return true; } }
9237850998a589beeb040487f485354161711b00
1,075
java
Java
x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/session/EmptyRowSet.java
YMhao/elasticsearch
3bb826aa5cf477d3f0cc2397bda517d501c08b9a
[ "Apache-2.0" ]
3
2017-05-31T14:46:18.000Z
2022-02-15T08:04:05.000Z
x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/session/EmptyRowSet.java
YMhao/elasticsearch
3bb826aa5cf477d3f0cc2397bda517d501c08b9a
[ "Apache-2.0" ]
61
2015-01-09T10:44:57.000Z
2018-04-17T14:56:08.000Z
x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/session/EmptyRowSet.java
YMhao/elasticsearch
3bb826aa5cf477d3f0cc2397bda517d501c08b9a
[ "Apache-2.0" ]
4
2015-09-18T20:09:38.000Z
2019-08-07T12:46:41.000Z
20.673077
79
0.650233
998,097
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ package org.elasticsearch.xpack.sql.session; import org.elasticsearch.xpack.sql.type.Schema; class EmptyRowSet extends AbstractRowSet implements SchemaRowSet { private final Schema schema; EmptyRowSet(Schema schema) { this.schema = schema; } @Override protected boolean doHasCurrent() { return false; } @Override protected boolean doNext() { return false; } @Override protected Object getColumn(int index) { throw new UnsupportedOperationException(); } @Override protected void doReset() { // no-op } @Override public int size() { return 0; } @Override public Cursor nextPageCursor() { return Cursor.EMPTY; } @Override public Schema schema() { return schema; } }
9237853cea69683672813bb94b9e2550db2d3e8e
893
java
Java
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/GroovyHashBangFileTypeDetector.java
dunno99/intellij-community
aa656a5d874b947271b896b2105e4370827b9149
[ "Apache-2.0" ]
1
2020-01-28T17:32:44.000Z
2020-01-28T17:32:44.000Z
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/GroovyHashBangFileTypeDetector.java
dunno99/intellij-community
aa656a5d874b947271b896b2105e4370827b9149
[ "Apache-2.0" ]
2
2022-02-19T09:45:05.000Z
2022-02-27T20:32:55.000Z
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/GroovyHashBangFileTypeDetector.java
dunno99/intellij-community
aa656a5d874b947271b896b2105e4370827b9149
[ "Apache-2.0" ]
2
2020-03-15T08:57:37.000Z
2020-04-07T04:48:14.000Z
35.72
78
0.769317
998,098
/* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.plugins.groovy; import com.intellij.openapi.fileTypes.impl.HashBangFileTypeDetector; public class GroovyHashBangFileTypeDetector extends HashBangFileTypeDetector { public GroovyHashBangFileTypeDetector() { super(GroovyFileType.GROOVY_FILE_TYPE, "groovy"); } }
923785bb62596f8a460f854dda4ac48aa4a014c2
8,404
java
Java
libpageradatper/src/main/java/com/bilibili/lib/pageradapter/IDFragmentStatePagerAdapter.java
Bilibili/adaptation
9d7ee7f1f6729e7d8d3fe19b4c8649cd77e15dc5
[ "Apache-2.0" ]
27
2016-04-06T10:36:20.000Z
2018-10-29T05:35:21.000Z
libpageradatper/src/main/java/com/bilibili/lib/pageradapter/IDFragmentStatePagerAdapter.java
Bilibili/adaptation
9d7ee7f1f6729e7d8d3fe19b4c8649cd77e15dc5
[ "Apache-2.0" ]
null
null
null
libpageradatper/src/main/java/com/bilibili/lib/pageradapter/IDFragmentStatePagerAdapter.java
Bilibili/adaptation
9d7ee7f1f6729e7d8d3fe19b4c8649cd77e15dc5
[ "Apache-2.0" ]
7
2016-05-04T00:54:57.000Z
2018-10-23T05:16:33.000Z
36.380952
101
0.606497
998,099
/* * Copyright (C) 2011 The Android Open Source Project * Copyright (C) 2016 Bilibili, Inc. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.bilibili.lib.pageradapter; import android.os.Bundle; import android.os.Parcelable; import android.support.annotation.CallSuper; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.view.PagerAdapter; import android.util.Log; import android.util.SparseArray; import android.view.View; import android.view.ViewGroup; /** * The {@code position} of fragment sometimes is unreliable. * So this PagerAdapter implementation use item id instead of position to saving fragments. */ public abstract class IDFragmentStatePagerAdapter extends PagerAdapter { private static final String TAG = "ID-PagerAdapter"; private static final boolean DEBUG = false; private static final String KEY_PREFIX = "i"; private static final String KEY_SAVED_STATES = "states"; /** Fragment instances cache map, the key is id */ private SparseArray<Fragment> mFragments = new SparseArray<>(); /** The key is id */ private SparseArray<Fragment.SavedState> mSavedState = new SparseArray<>(); private final FragmentManager mFragmentManager; private FragmentTransaction mCurrentTransaction = null; private Fragment mCurrentPrimaryItem = null; public IDFragmentStatePagerAdapter(FragmentManager fm) { mFragmentManager = fm; } @Override public Object instantiateItem(ViewGroup container, int position) { final int id = getItemId(position); // find in restored fragments cache Fragment f = mFragments.get(id); if (f != null) { return f; } if (mCurrentTransaction == null) { // will commit() when finishUpdate() call mCurrentTransaction = mFragmentManager.beginTransaction(); } Fragment fragment = getItem(id); if(DEBUG) { Log.v(TAG, "Adding item #" + position + ": id =" + id + ", f=" + fragment); } Fragment.SavedState fss = mSavedState.get(id); if (fss != null) { Bundle state; try { state = Reflection.on(Fragment.SavedState.class).fieldValue(fss, "mState"); } catch (NoSuchFieldException e) { if(DEBUG) Log.w(TAG, "No field name 'mState'!"); state = null; } if (state != null) { state.setClassLoader(fragment.getClass().getClassLoader()); } fragment.setInitialSavedState(fss); } fragment.setMenuVisibility(false); fragment.setUserVisibleHint(false); mFragments.put(id, fragment); mCurrentTransaction.add(container.getId(), fragment); return fragment; } @Override public void destroyItem(ViewGroup container, int position, Object object) { Fragment fragment = (Fragment) object; if (mCurrentTransaction == null) { mCurrentTransaction = mFragmentManager.beginTransaction(); } int id = getItemId(position); if(DEBUG) Log.v(TAG, "Removing item #" + position + ": id=" + id + ", f=" + object + " v=" + ((Fragment) object).getView()); // The Fragment instance will be destroyed when finishUpdate() called. // Don't worry. Save it's state here! mSavedState.put(id, mFragmentManager.saveFragmentInstanceState(fragment)); // Remove it from cache and the FragmentManager. mFragments.remove(id); mCurrentTransaction.remove(fragment); } @Override @CallSuper public void setPrimaryItem(ViewGroup container, int position, Object object) { Fragment fragment = (Fragment) object; if (fragment != mCurrentPrimaryItem) { if (mCurrentPrimaryItem != null) { mCurrentPrimaryItem.setMenuVisibility(false); mCurrentPrimaryItem.setUserVisibleHint(false); } if (fragment != null) { fragment.setMenuVisibility(true); fragment.setUserVisibleHint(true); } mCurrentPrimaryItem = fragment; } } /** * @param position Position within this adapter * @return Unique identifier for the item at position */ protected abstract int getItemId(int position); /** * @param id The item's id * @return Fragment associated with a specified id * @see #getItemId(int) */ protected abstract Fragment getItem(int id); /** * Useful for {@link #getItemPosition(Object)} to determine if * Fragment item's position has changed. * @param id Fragment item id * @return index in [0, {@link #getCount()}), * or {@link #POSITION_UNCHANGED} if the item's position has not changed, * or {@link #POSITION_NONE} if the item is no longer present. * @see #getItemPosition(Object) */ protected abstract int getPositionOf(int id); @Override public final int getItemPosition(Object object) { int position = mFragments.indexOfValue((Fragment) object); if (position < 0) return POSITION_NONE; int id = mFragments.keyAt(position); return getPositionOf(id); } @Override public boolean isViewFromObject(View view, Object object) { return ((Fragment) object).getView() == view; } @Override public void startUpdate(ViewGroup container) { } @Override public void finishUpdate(ViewGroup container) { if (mCurrentTransaction != null) { mCurrentTransaction.commitAllowingStateLoss(); mCurrentTransaction = null; mFragmentManager.executePendingTransactions(); } } @Override @CallSuper public Parcelable saveState() { Bundle state = new Bundle(); if (mSavedState.size() > 0) { state.putSparseParcelableArray(KEY_SAVED_STATES, mSavedState); } for (int i = 0; i < mFragments.size(); i++) { Fragment f = mFragments.valueAt(i); String key = KEY_PREFIX + mFragments.keyAt(i); // save Fragment sate in FragmentManager by our key! mFragmentManager.putFragment(state, key, f); } return state; } @Override @CallSuper public void restoreState(Parcelable state, ClassLoader loader) { if (state != null) { Bundle bundle = (Bundle) state; bundle.setClassLoader(loader); mSavedState.clear(); mFragments.clear(); SparseArray<Fragment.SavedState> fss = bundle.getSparseParcelableArray(KEY_SAVED_STATES); if (fss != null) { for (int i = 0; i < fss.size(); i++) { mSavedState.put(fss.keyAt(i), fss.valueAt(i)); } } Iterable<String> keys = bundle.keySet(); for (String key : keys) { if (key.startsWith(KEY_PREFIX)) { Fragment f = mFragmentManager.getFragment(bundle, key); int id; try { id = Integer.parseInt(key.substring(KEY_PREFIX.length())); } catch (NumberFormatException e) { // should not happen! throw new IllegalStateException("Can't find id at key " + key); } if (f != null) { f.setMenuVisibility(false); mFragments.put(id, f); } else { Log.w(TAG, "Bad fragment at key " + key); } } } } } }
923786718af5fe7f1beb57b1d2640b8b773181b5
8,343
java
Java
src/main/java/org/grouplens/grapht/InjectionContainer.java
AutoscanForJava/org.grouplens.grapht-grapht
f6a5d21014ed05413ec811621fdd815feb053d7a
[ "MIT" ]
21
2015-03-17T21:01:57.000Z
2022-03-13T06:02:29.000Z
src/main/java/org/grouplens/grapht/InjectionContainer.java
AutoscanForJava/org.grouplens.grapht-grapht
f6a5d21014ed05413ec811621fdd815feb053d7a
[ "MIT" ]
39
2015-02-04T16:12:16.000Z
2021-06-07T23:02:47.000Z
src/main/java/org/grouplens/grapht/InjectionContainer.java
AutoscanForJava/org.grouplens.grapht-grapht
f6a5d21014ed05413ec811621fdd815feb053d7a
[ "MIT" ]
13
2015-02-05T06:27:06.000Z
2022-02-11T18:04:54.000Z
40.5
181
0.664869
998,100
/* * Grapht, an open source dependency injector. * Copyright 2014-2017 various contributors (see CONTRIBUTORS.txt) * Copyright 2010-2014 Regents of the University of Minnesota * * 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 org.grouplens.grapht; import com.google.common.base.Function; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSetMultimap; import com.google.common.collect.Maps; import com.google.common.collect.SetMultimap; import org.grouplens.grapht.graph.DAGEdge; import org.grouplens.grapht.graph.DAGNode; import org.grouplens.grapht.reflect.Desire; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map; import java.util.Set; import java.util.WeakHashMap; /** * Container for dependency-injected components. A container is the scope of memoization, so * components with a cache policy of {@link CachePolicy#MEMOIZE} will share an instance so long * as they are instantiated by the same instantiator. * * @since 0.9 * @author <a href="http://www.grouplens.org">GroupLens Research</a> */ public class InjectionContainer { private static final Logger logger = LoggerFactory.getLogger(InjectionContainer.class); private final CachePolicy defaultCachePolicy; private final Map<DAGNode<Component, Dependency>, Instantiator> providerCache; private final LifecycleManager manager; /** * Create a new instantiator with a default policy of {@code MEMOIZE}. * @return The instantiator. */ public static InjectionContainer create() { return create(CachePolicy.MEMOIZE); } /** * Create a new instantiator without a lifecycle manager. * @param dft The default cache policy. * @return The instantiator. */ public static InjectionContainer create(CachePolicy dft) { return new InjectionContainer(dft, null); } /** * Create a new instantiator. * @param dft The default cache policy. * @param mgr The lifecycle manager. * @return The instantiator. */ public static InjectionContainer create(CachePolicy dft, LifecycleManager mgr) { return new InjectionContainer(dft, mgr); } private InjectionContainer(CachePolicy dft, LifecycleManager mgr) { defaultCachePolicy = dft; providerCache = new WeakHashMap<DAGNode<Component, Dependency>, Instantiator>(); manager = mgr; } /** * Get a provider that, when invoked, will return an instance of the component represented * by a graph. * * * @param node The graph. * @return A provider to instantiate {@code graph}. * @see #makeInstantiator(DAGNode, SetMultimap) */ public Instantiator makeInstantiator(DAGNode<Component, Dependency> node) { return makeInstantiator(node, ImmutableSetMultimap.<DAGNode<Component, Dependency>, DAGEdge<Component, Dependency>>of()); } /** * Get a provider that, when invoked, will return an instance of the component represented * by a graph with back edges. The provider will implement the cache policy, so cached nodes * will return a memoized provider. * * @param node The graph. * @param backEdges A multimap of back edges for cyclic dependencies. * @return A provider to instantiate {@code graph}. */ public Instantiator makeInstantiator(DAGNode<Component, Dependency> node, SetMultimap<DAGNode<Component, Dependency>, DAGEdge<Component, Dependency>> backEdges) { Instantiator cached; synchronized (providerCache) { cached = providerCache.get(node); } if (cached == null) { logger.debug("Node has not been memoized, instantiating: {}", node.getLabel()); Map<Desire, Instantiator> depMap = makeDependencyMap(node, backEdges); Instantiator raw = node.getLabel().getSatisfaction().makeInstantiator(depMap, manager); CachePolicy policy = node.getLabel().getCachePolicy(); if (policy.equals(CachePolicy.NO_PREFERENCE)) { policy = defaultCachePolicy; } if (policy.equals(CachePolicy.MEMOIZE)) { // enforce memoization on providers for MEMOIZE policy cached = Instantiators.memoize(raw); } else { // Satisfaction.makeInstantiator() returns providers that are expected // to create new instances with each invocation assert policy.equals(CachePolicy.NEW_INSTANCE); cached = raw; } synchronized (providerCache) { if (!providerCache.containsKey(node)) { providerCache.put(node, cached); } else { logger.debug("two threads built instantiator for {}, discarding 2nd build", node); cached = providerCache.get(node); } } } return cached; } private Map<Desire, Instantiator> makeDependencyMap(DAGNode<Component, Dependency> node, SetMultimap<DAGNode<Component, Dependency>, DAGEdge<Component, Dependency>> backEdges) { Set<DAGEdge<Component,Dependency>> edges = node.getOutgoingEdges(); if (backEdges.containsKey(node)) { ImmutableSet.Builder<DAGEdge<Component,Dependency>> bld = ImmutableSet.builder(); edges = bld.addAll(edges) .addAll(backEdges.get(node)) .build(); } ImmutableSet.Builder<Desire> desires = ImmutableSet.builder(); for (DAGEdge<Component,Dependency> edge: edges) { desires.add(edge.getLabel().getInitialDesire()); } return Maps.asMap(desires.build(), new DepLookup(edges, backEdges)); } /** * Get the lifecycle manager for this container. * @return The lifecycle manager for the container. */ @Nullable public LifecycleManager getLifecycleManager() { return manager; } /** * Function to look up a desire in a set of dependency edges. */ private class DepLookup implements Function<Desire,Instantiator> { private final Set<DAGEdge<Component, Dependency>> edges; private final SetMultimap<DAGNode<Component, Dependency>, DAGEdge<Component, Dependency>> backEdges; /** * Construct a depenency lookup funciton. * @param edges The set of edges to consult. * @param backEdges The back edge map (to pass to {@link #makeInstantiator(DAGNode,SetMultimap)}). */ public DepLookup(Set<DAGEdge<Component,Dependency>> edges, SetMultimap<DAGNode<Component, Dependency>, DAGEdge<Component, Dependency>> backEdges) { this.edges = edges; this.backEdges = backEdges; } @Nullable @Override public Instantiator apply(@Nullable Desire input) { for (DAGEdge<Component,Dependency> edge: edges) { if (edge.getLabel().getInitialDesire().equals(input)) { return makeInstantiator(edge.getTail(), backEdges); } } return null; } } }
923786fceebea0990de29cb71467e10c72c6554f
580
java
Java
src/main/java/com/mazentop/modules/emp/commond/ProProductTypeCoommond.java
chanwaikit/fulin-test
e31ef03596b724ba48d72ca8021492e6f251ec20
[ "0BSD" ]
null
null
null
src/main/java/com/mazentop/modules/emp/commond/ProProductTypeCoommond.java
chanwaikit/fulin-test
e31ef03596b724ba48d72ca8021492e6f251ec20
[ "0BSD" ]
null
null
null
src/main/java/com/mazentop/modules/emp/commond/ProProductTypeCoommond.java
chanwaikit/fulin-test
e31ef03596b724ba48d72ca8021492e6f251ec20
[ "0BSD" ]
null
null
null
25.217391
125
0.781034
998,101
package com.mazentop.modules.emp.commond; import com.mazentop.entity.ProProductType; import com.mztframework.commond.PageCommond; import com.mztframework.dao.annotation.Criteria; import com.mztframework.dao.annotation.Expression; import lombok.Data; /** * @author: wangzy * @date: 2020/3/13 * @description: */ @Data public class ProProductTypeCoommond extends PageCommond{ @Criteria(expression = Expression.LIKE, property = ProProductType.F_PRODUCT_TYPE_NAME, alias = ProProductType.TABLE_NAME) private String productTypeName; private String root = "root"; }
9237892925929c693801a22d60aaa5dfbf229219
1,746
java
Java
app/src/main/java/com/raisound/asrdemo_en/tings/Mactivity.java
Tinawood/notepad
247d6d225a47c963c3986b6a9da3c20ab5cef406
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/raisound/asrdemo_en/tings/Mactivity.java
Tinawood/notepad
247d6d225a47c963c3986b6a9da3c20ab5cef406
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/raisound/asrdemo_en/tings/Mactivity.java
Tinawood/notepad
247d6d225a47c963c3986b6a9da3c20ab5cef406
[ "Apache-2.0" ]
null
null
null
31.178571
80
0.65063
998,102
package com.raisound.asrdemo_en.tings; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.ListView; import com.raisound.asrdemo_en.R; import com.raisound.asrdemo_en.camera.MainCamera; import com.raisound.asrdemo_en.dictation.Dictation; import com.raisound.asrdemo_en.speekui.MaActivity; import com.raisound.asrdemo_en.time.MainActivity; /** * Created by Wz on 2016/8/10. */ public class Mactivity extends Activity { protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.mactivity); Button Bq = (Button) findViewById(R.id.btn_Bq); Bq.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Mactivity.this, TMainActivity.class); startActivity(intent); } }); Button Bw = (Button) findViewById(R.id.btn_Bw); Bw.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Mactivity.this, MainActivity.class); startActivity(intent); } }); Button Tx = (Button) findViewById(R.id.btn_Tx); Tx.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Mactivity.this, MainCamera.class); startActivity(intent); } }); } }
923789c01cbc36a2538bf972899e92e4e3f10fc3
2,214
java
Java
jhaws/net/src/main/java/org/jhaws/common/net/client/FirefoxCookieStoreBase.java
jurgendl/jhaws
9f8c0f0ee64315644bd112426fcec2a135a2cdf2
[ "MIT" ]
2
2015-03-18T15:04:51.000Z
2018-10-08T15:43:08.000Z
jhaws/net/src/main/java/org/jhaws/common/net/client/FirefoxCookieStoreBase.java
jurgendl/jhaws
9f8c0f0ee64315644bd112426fcec2a135a2cdf2
[ "MIT" ]
11
2020-07-01T08:44:17.000Z
2022-03-30T17:53:42.000Z
jhaws/net/src/main/java/org/jhaws/common/net/client/FirefoxCookieStoreBase.java
jurgendl/jhaws
9f8c0f0ee64315644bd112426fcec2a135a2cdf2
[ "MIT" ]
null
null
null
33.545455
114
0.730804
998,103
package org.jhaws.common.net.client; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.jhaws.common.io.FilePath; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.sqlite.SQLiteDataSource; public class FirefoxCookieStoreBase { protected NamedParameterJdbcTemplate jdbc; public FirefoxCookieStoreBase(FilePath cookieStore) { SQLiteDataSource dataSource = new SQLiteDataSource(); cookieStore = cookieStore.copyTo(cookieStore.appendExtension("backup")); String url = "jdbc:sqlite:" + cookieStore.getAbsolutePath(); System.out.println(url); dataSource.setUrl(url); jdbc = new NamedParameterJdbcTemplate(dataSource); } public FirefoxCookieStoreBase() { this(FilePath.getUserHomeDirectory().child("AppData\\Roaming\\Mozilla\\Firefox\\Profiles").getChildren().get(0) .child("cookies.sqlite")); } public List<CookieBase> getSerializableCookies() { Map<String, Object> params = new HashMap<>(); RowMapper<CookieBase> cookieRowMapper = new RowMapper<CookieBase>() { @Override public CookieBase mapRow(ResultSet rs, int rowNum) throws SQLException { try { int i = 1; String host_key = rs.getString(i++); String name = rs.getString(i++); String path = rs.getString(i++); byte[] decrypted_value = rs.getBytes(i++); Date expires = new Date(1000l * rs.getInt(i++)); boolean secure = rs.getBoolean(i++); CookieBase cookie = new CookieBase(); cookie.setName(name); cookie.setValue(new String(decrypted_value)); cookie.setDomain(host_key); cookie.setPath(path); cookie.setExpiryDate(expires); cookie.setSecure(secure); return cookie; } catch (Exception ex) { throw new RuntimeException(ex); } } }; System.out.println("loading firefox cookies"); return jdbc.query("select host, name, path, value, expiry, isSecure from moz_cookies", params, cookieRowMapper); } public static void main(String[] args) { new FirefoxCookieStoreBase().getSerializableCookies().forEach(System.out::println); } }
92378a119dde7087204f24c0e7c126a5f9728d73
9,573
java
Java
test/com/joshcheek/server/WebFrameworkTest.java
JoshCheek/java-web-server
404b483a0f9152a98b74702e2c3ee0af5fbff64a
[ "Unlicense" ]
2
2015-09-14T16:55:26.000Z
2017-08-10T06:57:52.000Z
test/com/joshcheek/server/WebFrameworkTest.java
JoshCheek/java-web-server
404b483a0f9152a98b74702e2c3ee0af5fbff64a
[ "Unlicense" ]
null
null
null
test/com/joshcheek/server/WebFrameworkTest.java
JoshCheek/java-web-server
404b483a0f9152a98b74702e2c3ee0af5fbff64a
[ "Unlicense" ]
null
null
null
34.311828
128
0.567116
998,104
package com.joshcheek.server; import com.joshcheek.server.webFramework.WebFramework; import java.io.*; import java.net.Socket; import java.util.regex.Pattern; /** * Created by IntelliJ IDEA. * User: joshuajcheek * Date: 9/1/11 * Time: 1:15 PM * To change this template use File | Settings | File Templates. */ public class WebFrameworkTest extends junit.framework.TestCase { private ByteArrayOutputStream output; public void testICanUseTheWebFrameworkLikeThis() throws Exception { WebFramework greetingApp = new WebFramework(8082) { public void defineRoutes() { new GetRequest("/index") { public String controller() { setStatus(418); setHeader("Content-Type", "text/plain"); return "Hello, world!"; } }; } }; // ensure everything is set up properly assertEquals(8082, greetingApp.port()); assertTrue(greetingApp.doesItRespondTo("GET", "/index")); assertFalse(greetingApp.doesItRespondTo("GET", "/foobar")); // can we run it? assertFalse(greetingApp.isRunning()); greetingApp.startRunning(); assertTrue(greetingApp.isRunning()); greetingApp.stopRunning(); assertFalse(greetingApp.isRunning()); // do the requests work right? greetingApp.startRunning(); assertResponds(greetingApp, "/index", 418, "Hello, world!", "Content-Type", "text/plain"); assertResponds(greetingApp, "/foobar", 404); greetingApp.stopRunning(); } public void testAWebFrameworkTakesItsPort() { WebFramework app = new WebFramework(1234) { public void defineRoutes() {} }; assertEquals(1234, app.port()); } public void testRespondsToNoRoutesByDefault() { WebFramework app = new WebFramework(1234) { public void defineRoutes() {} }; assertFalse(app.doesItRespondTo("GET", "/")); } public void testCanDefineRoutesForGetRequests() { WebFramework app = new WebFramework(1234) { public void defineRoutes() { new GetRequest("/index") { public String controller() { return ""; } }; } }; assertTrue( app.doesItRespondTo("GET" , "/index")); assertFalse( app.doesItRespondTo("POST" , "/index")); assertFalse( app.doesItRespondTo("GET" , "/foobar")); } public void testCanDefineRoutesForPostRequests() { WebFramework app = new WebFramework(1234) { public void defineRoutes() { new PostRequest("/index") { public String controller() { return ""; } }; } }; assertTrue( app.doesItRespondTo("POST" , "/index")); assertFalse( app.doesItRespondTo("GET" , "/index")); assertFalse( app.doesItRespondTo("POST" , "/foobar")); } public void testControllerCanSetTheStatusCode() { WebFramework app = new WebFramework(1234) { public void defineRoutes() { new PostRequest("/index") { public String controller() { setStatus(100); return "Hello, world!"; } }; } }; assertTrue(100 == interactionFor(app, "POST", "/index").getStatus()); } public void testStatusDefaultsTo200IfFoundAnd404IfNotFound() { WebFramework app = new WebFramework(1234) { public void defineRoutes() { new GetRequest("/index") { public String controller() { return ""; } }; } }; assertTrue(200 == interactionFor(app, "GET", "/index").getStatus()); assertTrue(404 == interactionFor(app, "GET", "/foobar").getStatus()); } public void testControllerCanSetTheHeaders() { WebFramework app = new WebFramework(1234) { public void defineRoutes() { new PostRequest("/index") { public String controller() { setHeader("Content-Type", "text/plain"); setHeader("Accept-Charset", "utf-8"); return "Hello, world!"; } }; } }; HTTPInteraction interaction = interactionFor(app, "POST", "/index"); assertEquals("text/plain", interaction.headerFor("Content-Type")); assertEquals("utf-8", interaction.headerFor("Accept-Charset")); } public void testControllerReturnValueIsTheContent() { WebFramework app = new WebFramework(1234) { public void defineRoutes() { new PostRequest("/index") { public String controller() { return "Hello, world!"; } }; } }; HTTPInteraction interaction = interactionFor(app, "POST", "/index"); assertEquals("Hello, world!", interaction.getContent()); } public void testNoContentIfControllerReturnsNull() { WebFramework app = new WebFramework(1234) { public void defineRoutes() { new PostRequest("/index") { public String controller() { return null; } }; } }; HTTPInteraction interaction = interactionFor(app, "POST", "/index"); assertEquals("", interaction.getContent()); assertEquals("0", interaction.headerFor("Content-Length")); } public void testCanMatchUrl() { WebFramework app = new WebFramework(1234) { public void defineRoutes() { new PostRequest("/:route") { public String controller() { return getParam("route"); } }; } }; HTTPInteraction interaction = interactionFor(app, "POST", "/abcdefg"); assertEquals("abcdefg", interaction.getContent()); } public String output() { return output.toString(); } private HTTPInteraction interactionFor(WebFramework app, String method, String uri) { HTTPInteraction interaction = mockHTTPInteraction(uri); app.respondTo(method, uri, interaction); return interaction; } private HTTPInteraction mockHTTPInteraction() { return mockHTTPInteraction("/"); } private HTTPInteraction mockHTTPInteraction(String uri) { try { return new HTTPInteraction(mockReader(uri), mockWriter()); } catch (IOException e) { e.printStackTrace(); return null; } } private BufferedReader mockReader(String uri) { return new BufferedReader(new StringReader("GET " + uri + " HTTP/1.1")); } private PrintStream mockWriter() { output = new ByteArrayOutputStream(); return new PrintStream(output); } private void assertResponds(WebFramework app, String uri, int status, String content, String ... headers) throws Exception { Socket socket = getSocket(app); sendRequest(socket, uri); Thread.sleep(300); String response = getResponse(socket); assertHasStatus(response, status); assertHasContent(response, content); assertHasHeaders(response, headers); socket.close(); } private void assertResponds(WebFramework app, String uri, int status) throws Exception { Socket socket = getSocket(app); sendRequest(socket, uri); Thread.sleep(300); String response = getResponse(socket); assertHasStatus(response, status); socket.close(); } private void assertHasStatus(String response, int status) { String firstLine = response.substring(0, response.indexOf('\n')); assertMatches(Integer.toString(status), firstLine); } private void sendRequest(Socket socket, String uri) throws IOException { PrintStream writer = SocketService.getPrintStream(socket); writer.print("GET " + uri + " HTTP/1.1\r\n\r\n"); } private Socket getSocket(WebFramework app) throws IOException { return new Socket("localhost", app.port()); } private String getResponse(Socket socket) throws IOException { BufferedReader reader = SocketService.getBufferedReader(socket); String answer = ""; for(int c; (c=reader.read()) != -1; ) answer += Character.toString((char) c); return answer; } private void assertHasHeaders(String response, String[] headers) { for(int i=0; i<headers.length; i += 2) assertMatches(regexFor(headers[i], headers[i+1]), response); } private String regexFor(String key, String value) { return key + ":\\s+" + value + "\r\n"; } private void assertHasContent(String response, String content) { assertTrue(response.endsWith(content)); } private void assertMatches(String regex, String toMatch) { boolean doesMatch = Pattern.compile(".*" + regex + ".*", Pattern.DOTALL).matcher(toMatch).matches(); assertTrue("Expected \"" + output + "\" to match /" + regex+"/", doesMatch); } }
92378a65b905475b3029d09cab47bfb4ff267d08
148
java
Java
src/main/java/com/softeq/app/domain/UserRepositoryCustom.java
Softeq/spring-querydsl-project-template
03f524ed6a95402756309157b2ed2b30b3d3bb5f
[ "MIT" ]
7
2019-10-28T10:05:51.000Z
2021-12-29T13:09:50.000Z
src/main/java/com/softeq/app/domain/UserRepositoryCustom.java
Softeq/spring-querydsl-project-template
03f524ed6a95402756309157b2ed2b30b3d3bb5f
[ "MIT" ]
4
2019-10-21T13:07:31.000Z
2019-10-29T10:31:54.000Z
src/main/java/com/softeq/app/domain/UserRepositoryCustom.java
Softeq/spring-querydsl-project-template
03f524ed6a95402756309157b2ed2b30b3d3bb5f
[ "MIT" ]
2
2021-03-19T07:45:09.000Z
2021-04-11T14:31:14.000Z
14.8
47
0.77027
998,105
package com.softeq.app.domain; import java.util.List; public interface UserRepositoryCustom { List<User> findByLastName(String lastName); }
92378b593e98381636b98cf93befa9346ecc2634
3,599
java
Java
app/src/main/java/com/ljmu/andre/snaptools/MediaSaving/MediaSaver.java
tardeaux/SnapTools
899f8f2d4ce1d840ae537bd16b8da98b8180aeeb
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/ljmu/andre/snaptools/MediaSaving/MediaSaver.java
tardeaux/SnapTools
899f8f2d4ce1d840ae537bd16b8da98b8180aeeb
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/ljmu/andre/snaptools/MediaSaving/MediaSaver.java
tardeaux/SnapTools
899f8f2d4ce1d840ae537bd16b8da98b8180aeeb
[ "Apache-2.0" ]
null
null
null
29.991667
116
0.61656
998,106
package com.ljmu.andre.snaptools.MediaSaving; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.google.common.base.MoreObjects; import com.ljmu.andre.snaptools.Exceptions.MediaNotSavedException; import com.ljmu.andre.snaptools.MediaSaving.AdapterHandler.MediaAdapter; import com.ljmu.andre.snaptools.Utils.Assert; import com.ljmu.andre.snaptools.Utils.FileUtils; import com.ljmu.andre.snaptools.Utils.ThreadUtils; import java.io.File; /** * This class was created by Andre R M (SID: 701439) * It and its contents are free to use by all */ public class MediaSaver { @Nullable private Object boundData; private boolean threaded; private boolean overwrite; private File outputFile; private Saveable saveable; public MediaSaver setBoundData(@Nullable Object boundData) { this.boundData = boundData; return this; } public MediaSaver setThreaded(boolean threaded) { this.threaded = threaded; return this; } public MediaSaver shouldOverwrite(boolean overwrite) { this.overwrite = overwrite; return this; } public MediaSaver setOutputFile(String directory, String filename) { setOutputFile(new File(directory, filename)); return this; } public MediaSaver setOutputFile(@NonNull File outputFile) { this.outputFile = outputFile; return this; } public MediaSaver setSaveable(@NonNull Saveable saveable) { this.saveable = saveable; return this; } public <T> void save() { Assert.notNull("Missing MediaSaver parameters: " + toString(), saveable, outputFile); if (!overwrite && outputFile.exists()) { saveable.mediaSaveFinished(MediaSaveState.EXISTED, null, boundData); return; } if (!outputFile.exists()) { outputFile = FileUtils.createFile(outputFile); if (outputFile == null) { if (saveable != null) { MediaNotSavedException mnsException = new MediaNotSavedException("Couldn't create output file"); saveable.mediaSaveFinished( MediaSaveState.FAILED, mnsException, boundData ); } return; } } T content = saveable.getSaveableContent(); MediaAdapter<T> mediaAdapter = AdapterHandler.getMediaAdapter(content.getClass()); Assert.notNull("MediaAdapter not found for: " + content.getClass().getSimpleName(), mediaAdapter); if (!threaded) { mediaAdapter.save(content, outputFile, saveable, boundData); return; } ThreadUtils.getThreadPool().execute(() -> mediaAdapter.save(content, outputFile, saveable, boundData)); } @Override public String toString() { return MoreObjects.toStringHelper(this) .omitNullValues() .add("boundData", boundData) .add("threaded", threaded) .add("overwrite", overwrite) .add("outputFile", outputFile) .add("saveable", saveable) .toString(); } public enum MediaSaveState { SUCCESS, FAILED, EXISTED } public interface Saveable { <T> T getSaveableContent(); void mediaSaveFinished( @NonNull MediaSaveState state, @Nullable Throwable error, @Nullable Object boundData); } }
92378b7f33f8b26aad7897911b261561798d0b2a
155
java
Java
waskj-base/base-chart-core/src/main/java/com/waskj/base/chart/core/model/code/EffectType.java
wangfei0904306/waskj-parent
2babea43baca4f32dacfd3534ff7b1309a78da40
[ "MIT" ]
null
null
null
waskj-base/base-chart-core/src/main/java/com/waskj/base/chart/core/model/code/EffectType.java
wangfei0904306/waskj-parent
2babea43baca4f32dacfd3534ff7b1309a78da40
[ "MIT" ]
null
null
null
waskj-base/base-chart-core/src/main/java/com/waskj/base/chart/core/model/code/EffectType.java
wangfei0904306/waskj-parent
2babea43baca4f32dacfd3534ff7b1309a78da40
[ "MIT" ]
null
null
null
12.916667
45
0.63871
998,107
package com.waskj.base.chart.core.model.code; /** * 特效类型 * * @author liuzh * @since 2016-02-28 10:33 */ public enum EffectType { ripple //涟漪特效 }
92378ca229de3d49e5e06ff8d9173091566f2ee1
4,730
java
Java
core/src/main/java/com/huawei/openstack4j/model/map/reduce/Cluster.java
wuchen-huawei/huaweicloud-sdk-java
1e4b76c737d23c5d5df59405015ea136651b6fc1
[ "Apache-2.0" ]
46
2018-09-30T08:55:22.000Z
2021-11-07T20:02:57.000Z
core/src/main/java/com/huawei/openstack4j/model/map/reduce/Cluster.java
wuchen-huawei/huaweicloud-sdk-java
1e4b76c737d23c5d5df59405015ea136651b6fc1
[ "Apache-2.0" ]
18
2019-04-11T02:37:30.000Z
2021-04-30T09:03:38.000Z
core/src/main/java/com/huawei/openstack4j/model/map/reduce/Cluster.java
wuchen-huawei/huaweicloud-sdk-java
1e4b76c737d23c5d5df59405015ea136651b6fc1
[ "Apache-2.0" ]
42
2019-01-22T07:54:00.000Z
2021-12-13T01:14:14.000Z
29.104294
161
0.53204
998,108
/******************************************************************************* * Copyright 2016 ContainX and OpenStack4j * * 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.huawei.openstack4j.model.map.reduce; import java.util.Date; import java.util.List; import java.util.Map; import com.fasterxml.jackson.annotation.JsonCreator; import com.huawei.openstack4j.common.Buildable; import com.huawei.openstack4j.model.ModelEntity; import com.huawei.openstack4j.model.map.reduce.builder.ClusterBuilder; /** * An OpenStack Cluster * * @author upchh@example.com */ public interface Cluster extends ModelEntity, Buildable<ClusterBuilder> { enum Status { /* * Since it is being developed, this list is not stable yet. Note * also that MapReduce cluster status may appear in 2 words, e.g. * "Adding Instances", but we match only the first word for simplicity * until the list is stable. * See http://docs.openstack.org/developer/sahara/userdoc/statuses.html for more info. */ UNRECOGNIZED, VALIDATING, INFRAUPDATING, SPAWNING, WAITING, PREPARING, CONFIGURING, STARTING, ACTIVE, SCALING, ADDING, DECOMMISSIONING, DELETING, ERROR; @JsonCreator public static Status forValue(String value) { if (value != null) { for (Status s : Status.values()) { if (value.toUpperCase().startsWith(s.name())) return s; } } return Status.UNRECOGNIZED; } } /** * @return the status of the cluster */ Status getStatus(); /** * @return the information of the cluster */ Map<String, ? extends ServiceInfo> getInfos(); /** * @return the template id of the cluster */ String getClusterTemplateId(); /** * @return the if the cluster is transient */ Boolean isTransient(); /** * @return the description of the cluster */ String getDescription(); /** * @return the configurations of the cluster */ Map<String,? extends ServiceConfig> getClusterConfigs(); /** * @return the created date of the cluster */ Date getCreatedAt(); /** * @return the default image id of the cluster */ String getDefaultImageId(); /** * @return the user keypair id of the cluster */ String getUserKeypairId(); /** * @return the updated date of the cluster */ Date getUpdatedAt(); /** * @return the plugin name of the cluster */ String getPluginName(); /** * @return the management network of the cluster */ String getManagementNetworkId(); /** * @return the anti-affinity of the cluster */ List<String> getAntiAffinity(); /** * @return the tenant id of the cluster */ String getTenantId(); /** * @return the node groups of the cluster */ List<? extends NodeGroup> getNodeGroups(); /** * @return the management public key of the cluster */ String getManagementPublicKey(); /** * @return the status description of the cluster */ String getStatusDescription(); /** * @return the hadoop version of the cluster */ String getHadoopVersion(); /** * @return the identifier of the cluster */ String getId(); /** * @return the trust id of the cluster */ String getTrustId(); /** * @return the name of the cluster */ String getName(); }
92378d70913e5d51f1f31983bce826344cb74d51
2,700
java
Java
re/src/main/java/cn/rootelement/enumeration/CommonFileTypeEnum.java
ljtnono/re
fd9814c80378369fc0e4ad8b478eb2e73bb75601
[ "MIT" ]
4
2020-01-31T04:01:13.000Z
2020-04-11T05:06:28.000Z
re/src/main/java/cn/rootelement/enumeration/CommonFileTypeEnum.java
ljtnono/re
fd9814c80378369fc0e4ad8b478eb2e73bb75601
[ "MIT" ]
16
2020-01-10T06:10:46.000Z
2022-02-18T22:59:31.000Z
re/src/main/java/cn/rootelement/enumeration/CommonFileTypeEnum.java
ljtnono/root_element
60aaf0be9e8949033a8584347e5af9b79826c070
[ "MIT" ]
1
2019-12-26T02:16:08.000Z
2019-12-26T02:16:08.000Z
17.419355
80
0.34037
998,109
package cn.rootelement.enumeration; /** * 常见文件类型枚举,文件分为以下几种类型 * 1. 图片 2. 音乐 3. 文档 4. 视频 5. pdf书籍 6. markdown 7. 代码 8. 其他 * 其中3表示excel word ppt office文件 * @author ljt * @date 2020/1/30 * @version 1.0.2 */ public enum CommonFileTypeEnum { //################################ 1.图片 ################################// /** jpg图片文件 */ JPG("jpg", 1), /** jpeg图片文件 */ JPEG("jpeg", 1), /** png图片文件 */ PNG("png", 1), /** bmp图片文件 */ BMP("bmp", 1), /** gif图片文件 */ GIF("gif", 1), //################################ 2.音乐 ################################// /** mp3文件 */ MP3("mp3", 2), /** wma文件 */ WMA("wma", 2), /** wav文件 */ WAV("wav", 2), //################################ 3.文档 ################################// /** word文档 */ DOC("doc", 3), /** word文档 */ DOCX("docx", 3), /** 普通文本文件 */ TXT("txt", 3), /** excel表格 */ XLSX("xlsx", 3), /** excel表格 */ XLS("xls", 3), /** ppt文件 */ PPT("ppt", 3), /** pptx文件 */ PPTX("pptx", 3), //################################ 4.视频 ################################// /** avi文件 */ AVI("avi", 4), /** mpeg文件 */ MPEG("mpeg", 4), /** mov文件 */ MOV("mov", 4), /** wmv文件 */ WMV("wmv", 4), /** rmvb文件 */ RMVB("rmvb", 4), //################################ 5.pdf ################################// /** pdf文件 */ PDF("pdf", 5), //################################ 6.md ################################// /** md文件 */ MD("md", 6), //################################ 7.code ################################// /** sql文件 */ SQL("sql", 7), /** java源文件 */ JAVA("java", 7), /** xml文件 */ XML("xml", 7), /** json文件 */ JSON("json", 7), /** conf配置文件 */ CONF("conf", 7), /** jsp文件 */ JSP("jsp", 7), /** ini文件 */ INI("ini", 7), /** html文件 */ HTML("html", 7), /** css文件 */ CSS("css", 7), /** javascript文件 */ JS("javascript", 7), //################################ 8.其他 ################################// /** bin文件 */ BIN("bin", 8), /** zip压缩文件 */ ZIP("zip", 8), /** rar压缩文件 */ RAR("rar", 8), /** gz压缩文件 */ GZ("gz", 8); private String value; private int type; CommonFileTypeEnum(String value, Integer type) { this.value = value; this.type = type; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public int getType() { return type; } public void setType(int type) { this.type = type; } }
92378da9585139336fc95e69fc3a4374013ae4c7
2,896
java
Java
library/medialibrary/src/main/java/deviceinfo/mayur/medialibrary/data/BytesBufferPool.java
mayurkaul/medialibrary
dcec5f6320cb9d222541a11c7c83de485a557118
[ "Apache-2.0" ]
30
2017-12-01T21:48:12.000Z
2021-12-15T08:22:33.000Z
library/medialibrary/src/main/java/deviceinfo/mayur/medialibrary/data/BytesBufferPool.java
naseemakhtar994/medialibrary
1b6b9a47ea2cb04ed0f98641f9465abeb76299c2
[ "Apache-2.0" ]
1
2018-05-30T06:15:28.000Z
2019-11-06T14:42:42.000Z
library/medialibrary/src/main/java/deviceinfo/mayur/medialibrary/data/BytesBufferPool.java
naseemakhtar994/medialibrary
1b6b9a47ea2cb04ed0f98641f9465abeb76299c2
[ "Apache-2.0" ]
11
2017-12-04T03:27:01.000Z
2019-11-23T05:23:29.000Z
31.478261
94
0.593923
998,110
/* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package deviceinfo.mayur.medialibrary.data; import java.io.FileDescriptor; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import deviceinfo.mayur.medialibrary.util.ThreadPool; public class BytesBufferPool { private static final int READ_STEP = 4096; public static class BytesBuffer { public byte[] data; public int offset; public int length; private BytesBuffer(int capacity) { this.data = new byte[capacity]; } // an helper function to read content from FileDescriptor public void readFrom(ThreadPool.JobContext jc, FileDescriptor fd) throws IOException { FileInputStream fis = new FileInputStream(fd); length = 0; try { int capacity = data.length; while (true) { int step = Math.min(READ_STEP, capacity - length); int rc = fis.read(data, length, step); if (rc < 0 || jc.isCancelled()) return; length += rc; if (length == capacity) { byte[] newData = new byte[data.length * 2]; System.arraycopy(data, 0, newData, 0, data.length); data = newData; capacity = data.length; } } } finally { fis.close(); } } } private final int mPoolSize; private final int mBufferSize; private final ArrayList<BytesBuffer> mList; public BytesBufferPool(int poolSize, int bufferSize) { mList = new ArrayList<BytesBuffer>(poolSize); mPoolSize = poolSize; mBufferSize = bufferSize; } public synchronized BytesBuffer get() { int n = mList.size(); return n > 0 ? mList.remove(n - 1) : new BytesBuffer(mBufferSize); } public synchronized void recycle(BytesBuffer buffer) { if (buffer.data.length != mBufferSize) return; if (mList.size() < mPoolSize) { buffer.offset = 0; buffer.length = 0; mList.add(buffer); } } public synchronized void clear() { mList.clear(); } }
92378dcdf97ff50e6e6cc8b61bb77b4364dcacba
813
java
Java
app/src/main/java/olog/dev/leeto/ui/_activity_detail/di/DetailActivitySubComponent.java
ologe/leeto
d071d7af88b2b050c65c6ff53c58ffbedae5066d
[ "MIT" ]
3
2019-03-08T19:06:08.000Z
2020-04-01T16:20:42.000Z
app/src/main/java/olog/dev/leeto/ui/_activity_detail/di/DetailActivitySubComponent.java
ologe/leeto
d071d7af88b2b050c65c6ff53c58ffbedae5066d
[ "MIT" ]
null
null
null
app/src/main/java/olog/dev/leeto/ui/_activity_detail/di/DetailActivitySubComponent.java
ologe/leeto
d071d7af88b2b050c65c6ff53c58ffbedae5066d
[ "MIT" ]
null
null
null
28.034483
85
0.768758
998,111
package olog.dev.leeto.ui._activity_detail.di; import dagger.Subcomponent; import dagger.android.AndroidInjector; import olog.dev.leeto.dagger.PerActivity; import olog.dev.leeto.ui._activity_detail.DetailActivity; import olog.dev.leeto.ui._activity_detail.DetailFragmentsModule; @Subcomponent(modules = { DetailModule.class, DetailFragmentsModule.class }) @PerActivity public interface DetailActivitySubComponent extends AndroidInjector<DetailActivity> { @Subcomponent.Builder abstract class Builder extends AndroidInjector.Builder<DetailActivity>{ public abstract Builder detailActivityModule(DetailModule module); @Override public void seedInstance(DetailActivity instance) { detailActivityModule(new DetailModule(instance)); } } }
92378e08b69f8a06f9ba43cff6c1df2f1f0efc2c
2,884
java
Java
src/main/java/org/ldk/structs/CustomMessageReader.java
lightningdevkit/ldk-garbagecollected
52476c310c3ec9e37a37929c19bad0b8e5dc0f35
[ "Apache-2.0", "MIT" ]
27
2021-02-05T16:34:19.000Z
2022-03-30T18:41:56.000Z
src/main/java/org/ldk/structs/CustomMessageReader.java
TheBlueMatt/ldk-garbagecollected
99a3d528524ef1de3ad0dd3d0f81e5c2df0de226
[ "Apache-2.0", "MIT" ]
57
2021-02-05T16:38:28.000Z
2022-03-29T22:27:00.000Z
src/main/java/org/ldk/structs/CustomMessageReader.java
TheBlueMatt/ldk-garbagecollected
99a3d528524ef1de3ad0dd3d0f81e5c2df0de226
[ "Apache-2.0", "MIT" ]
8
2021-02-12T02:22:14.000Z
2021-12-11T09:40:21.000Z
43.69697
103
0.76595
998,112
package org.ldk.structs; import org.ldk.impl.bindings; import org.ldk.enums.*; import org.ldk.util.*; import java.util.Arrays; import java.lang.ref.Reference; import javax.annotation.Nullable; /** * Trait to be implemented by custom message (unrelated to the channel/gossip LN layers) * decoders. */ @SuppressWarnings("unchecked") // We correctly assign various generic arrays public class CustomMessageReader extends CommonBase { final bindings.LDKCustomMessageReader bindings_instance; CustomMessageReader(Object _dummy, long ptr) { super(ptr); bindings_instance = null; } private CustomMessageReader(bindings.LDKCustomMessageReader arg) { super(bindings.LDKCustomMessageReader_new(arg)); this.ptrs_to.add(arg); this.bindings_instance = arg; } @Override @SuppressWarnings("deprecation") protected void finalize() throws Throwable { if (ptr != 0) { bindings.CustomMessageReader_free(ptr); } super.finalize(); } public static interface CustomMessageReaderInterface { /** * Decodes a custom message to `CustomMessageType`. If the given message type is known to the * implementation and the message could be decoded, must return `Ok(Some(message))`. If the * message type is unknown to the implementation, must return `Ok(None)`. If a decoding error * occur, must return `Err(DecodeError::X)` where `X` details the encountered error. */ Result_COption_TypeZDecodeErrorZ read(short message_type, byte[] buffer); } private static class LDKCustomMessageReaderHolder { CustomMessageReader held; } public static CustomMessageReader new_impl(CustomMessageReaderInterface arg) { final LDKCustomMessageReaderHolder impl_holder = new LDKCustomMessageReaderHolder(); impl_holder.held = new CustomMessageReader(new bindings.LDKCustomMessageReader() { @Override public long read(short message_type, byte[] buffer) { Result_COption_TypeZDecodeErrorZ ret = arg.read(message_type, buffer); long result = ret == null ? 0 : ret.clone_ptr(); return result; } }); return impl_holder.held; } /** * Decodes a custom message to `CustomMessageType`. If the given message type is known to the * implementation and the message could be decoded, must return `Ok(Some(message))`. If the * message type is unknown to the implementation, must return `Ok(None)`. If a decoding error * occur, must return `Err(DecodeError::X)` where `X` details the encountered error. */ public Result_COption_TypeZDecodeErrorZ read(short message_type, byte[] buffer) { long ret = bindings.CustomMessageReader_read(this.ptr, message_type, buffer); Reference.reachabilityFence(this); Reference.reachabilityFence(message_type); Reference.reachabilityFence(buffer); if (ret >= 0 && ret <= 4096) { return null; } Result_COption_TypeZDecodeErrorZ ret_hu_conv = Result_COption_TypeZDecodeErrorZ.constr_from_ptr(ret); return ret_hu_conv; } }
92378f24565f66777942986b6373c72dc93a60d4
6,141
java
Java
android/src/main/java/com/freelogic/flutter_sunyard_printer/utils/Util.java
esmauro/flutter_sunyard_printer
51be29b7a2114ac1432875ac84a2b44e09a58235
[ "BSD-3-Clause" ]
null
null
null
android/src/main/java/com/freelogic/flutter_sunyard_printer/utils/Util.java
esmauro/flutter_sunyard_printer
51be29b7a2114ac1432875ac84a2b44e09a58235
[ "BSD-3-Clause" ]
null
null
null
android/src/main/java/com/freelogic/flutter_sunyard_printer/utils/Util.java
esmauro/flutter_sunyard_printer
51be29b7a2114ac1432875ac84a2b44e09a58235
[ "BSD-3-Clause" ]
null
null
null
23.894942
70
0.545677
998,113
package com.freelogic.flutter_sunyard_printer.utils; import android.annotation.SuppressLint; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; @SuppressLint("DefaultLocale") public class Util { /** * 字节数组转换为字符串 * * @param bArray * 0x00, 0xAF * @return "00AF" */ public static String BytesToString(byte[] bArray) { if (bArray == null) { return null; } if (bArray.length == 0) { return ""; } StringBuffer sb = new StringBuffer(bArray.length); String sTemp; for (int i = 0; i < bArray.length; i++) { sTemp = Integer.toHexString(0xFF & bArray[i]); if (sTemp.length() < 2) sb.append(0); sb.append(sTemp.toUpperCase()); } return sb.toString(); } /** * 一个字节转换为字符串 * * @param b * 0xAF * @return "AF" */ public static String OneByteToString(byte b) { byte[] bTemp = new byte[1]; bTemp[0] = b; return BytesToString(bTemp); } /** * 字符串转换为字节数组 * * @param data * "00AF" * @return 0x00, 0xAF */ public static byte[] StringToBytes(String data) { String hexString = data.toUpperCase().trim(); if (hexString.length() % 2 != 0) { return null; } byte[] retData = new byte[hexString.length() / 2]; for (int i = 0; i < hexString.length(); i++) { int int_ch; // 两位16进制数转化后的10进制数 char hex_char1 = hexString.charAt(i); // //两位16进制数中的第一位(高位*16) int int_ch1; if (hex_char1 >= '0' && hex_char1 <= '9') int_ch1 = (hex_char1 - 48) * 16; // // 0 的Ascll - 48 else if (hex_char1 >= 'A' && hex_char1 <= 'F') int_ch1 = (hex_char1 - 55) * 16; // // A 的Ascll - 65 else return null; i++; char hex_char2 = hexString.charAt(i); // /两位16进制数中的第二位(低位) int int_ch2; if (hex_char2 >= '0' && hex_char2 <= '9') int_ch2 = (hex_char2 - 48); // // 0 的Ascll - 48 else if (hex_char2 >= 'A' && hex_char2 <= 'F') int_ch2 = hex_char2 - 55; // // A 的Ascll - 65 else return null; int_ch = int_ch1 + int_ch2; retData[i / 2] = (byte) int_ch;// 将转化后的数放入Byte里 } return retData; } @SuppressLint("SimpleDateFormat") public static String DateToString(Date date, String format) { SimpleDateFormat sdf = new SimpleDateFormat(format); String str = sdf.format(date); return str; } @SuppressLint("SimpleDateFormat") public static Date StringToDate(String dateString, String format) { SimpleDateFormat sdf = new SimpleDateFormat(format); sdf.setLenient(false); Date date; try { date = sdf.parse(dateString); return date; } catch (ParseException e) { e.printStackTrace(); } return null; } public static byte[] concat(byte[] b1, byte[] b2) { if(b1==null) { return b2; } else if (b2==null) { return b1; } byte[] result = new byte[b1.length + b2.length]; System.arraycopy(b1, 0, result, 0, b1.length); System.arraycopy(b2, 0, result, b1.length, b2.length); return result; } public static byte[] subbytes(byte[] src, int start, int length) { if (src == null || start < 0 || length <= 0) { return null; } if (src.length < start + length) { return null; } byte[] result = new byte[length]; System.arraycopy(src, start, result, 0, result.length); return result; } /** * @param num * @return 该数字的15-8位 */ public static byte getNumHigh(int num) { return (byte) ((num & 0xFF00) >> 8); } /** * @param num * @return 该数字的7-0位 */ public static byte getNumLow(int num) { return (byte) (num & 0xFF); } /** * @param high * 高地址字节 * @param low * 低地址字节 * @return 两个字节代表的int */ public static int getInteger(byte high, byte low) { return (0xFF & high) * 0x100 + (0xFF & low); } /** * @功能: BCD码转为10进制串(阿拉伯数据) * @参数: BCD码 * @结果: 10进制串 */ public static String bcd2Str(byte[] bytes) { StringBuffer temp = new StringBuffer(bytes.length * 2); for (int i = 0; i < bytes.length; i++) { temp.append((byte) ((bytes[i] & 0xf0) >>> 4)); temp.append((byte) (bytes[i] & 0x0f)); } return temp.toString().substring(0, 1).equalsIgnoreCase("0") ? temp .toString().substring(1) : temp.toString(); } /** * @功能: 10进制串转为BCD码 * @参数: 10进制串 * @结果: BCD码 */ public static byte[] str2Bcd(String asc) { int len = asc.length(); int mod = len % 2; if (mod != 0) { asc = "0" + asc; len = asc.length(); } byte abt[] = new byte[len]; if (len >= 2) { len = len / 2; } byte bbt[] = new byte[len]; abt = asc.getBytes(); int j, k; for (int p = 0; p < asc.length() / 2; p++) { if ((abt[2 * p] >= '0') && (abt[2 * p] <= '9')) { j = abt[2 * p] - '0'; } else if ((abt[2 * p] >= 'a') && (abt[2 * p] <= 'z')) { j = abt[2 * p] - 'a' + 0x0a; } else { j = abt[2 * p] - 'A' + 0x0a; } if ((abt[2 * p + 1] >= '0') && (abt[2 * p + 1] <= '9')) { k = abt[2 * p + 1] - '0'; } else if ((abt[2 * p + 1] >= 'a') && (abt[2 * p + 1] <= 'z')) { k = abt[2 * p + 1] - 'a' + 0x0a; } else { k = abt[2 * p + 1] - 'A' + 0x0a; } int a = (j << 4) + k; byte b = (byte) a; bbt[p] = b; } return bbt; } /** * 查找byte * @param src 带查找的byte数组 * @param offset byte数组偏移 * @param b * @return */ public static int byteFind(byte[] src, int offset, byte b) { if (offset > src.length - 1) { return -1; } for (int i = offset; i < src.length; i++) { if (src[i] == b) { return i; } } return -1; } /** * 将index偏移的可见字符的两字节的byte数组转换为int * @param data "FF"--0x45 0x45 * @param index 偏移 * @return 0xFF */ public static int hexByteStrigToInt(byte[] data, int index) { if (data == null) { return 0; } if (data.length - index < 2) { return 0; } byte[] lLength = new byte[2]; byte[] tempLength; System.arraycopy(data, index, lLength, 0, 2); tempLength = StringToBytes(new String(lLength)); if (tempLength == null) { return 0; } return tempLength[0]; } }
92378f8d670f730a0fbf840a2e8e6c70d6934765
27,558
java
Java
src/main/java/com/gooddata/warehouse/WarehouseService.java
MilanKovacik/gooddata-java
b48ee995eb750f871cc1fe556c462e71a1180523
[ "BSD-3-Clause" ]
null
null
null
src/main/java/com/gooddata/warehouse/WarehouseService.java
MilanKovacik/gooddata-java
b48ee995eb750f871cc1fe556c462e71a1180523
[ "BSD-3-Clause" ]
null
null
null
src/main/java/com/gooddata/warehouse/WarehouseService.java
MilanKovacik/gooddata-java
b48ee995eb750f871cc1fe556c462e71a1180523
[ "BSD-3-Clause" ]
null
null
null
42.331797
145
0.640576
998,114
/* * Copyright (C) 2004-2017, GoodData(R) Corporation. All rights reserved. * This source code is licensed under the BSD-style license found in the * LICENSE.txt file in the root directory of this source tree. */ package com.gooddata.warehouse; import com.gooddata.AbstractPollHandler; import com.gooddata.AbstractService; import com.gooddata.FutureResult; import com.gooddata.GoodDataException; import com.gooddata.GoodDataRestException; import com.gooddata.GoodDataSettings; import com.gooddata.PollResult; import com.gooddata.collections.MultiPageList; import com.gooddata.collections.Page; import com.gooddata.collections.PageRequest; import com.gooddata.collections.PageableList; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.client.ClientHttpResponse; import org.springframework.http.converter.json.MappingJacksonValue; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; import org.springframework.web.util.UriComponentsBuilder; import org.springframework.web.util.UriTemplate; import java.io.IOException; import java.net.URI; import static com.gooddata.util.Validate.notEmpty; import static com.gooddata.util.Validate.notNull; import static java.lang.String.format; /** * Provide access to warehouse API - create, update, list and delete warehouses. */ public class WarehouseService extends AbstractService { private static final String DEFAULT_SCHEMA_NAME = "default"; /** * Sets RESTful HTTP Spring template. Should be called from constructor of concrete service extending * this abstract one. * * @param restTemplate RESTful HTTP Spring template * @param settings settings */ public WarehouseService(final RestTemplate restTemplate, final GoodDataSettings settings) { super(restTemplate, settings); } /** * Sets RESTful HTTP Spring template. Should be called from constructor of concrete service extending * this abstract one. * * @param restTemplate RESTful HTTP Spring template * @deprecated use WarehouseService(RestTemplate, GoodDataSettings) constructor instead */ @Deprecated public WarehouseService(final RestTemplate restTemplate) { super(restTemplate); } /** * Create new warehouse. * * @param warehouse warehouse to create * * @return created warehouse */ public FutureResult<Warehouse> createWarehouse(final Warehouse warehouse) { notNull(warehouse, "warehouse"); final WarehouseTask task; try { task = restTemplate.postForObject(Warehouses.URI, warehouse, WarehouseTask.class); } catch (GoodDataException | RestClientException e) { throw new GoodDataException("Unable to create Warehouse", e); } if (task == null) { throw new GoodDataException("Empty response when Warehouse POSTed to API"); } return new PollResult<>(this, new AbstractPollHandler<WarehouseTask,Warehouse>(task.getPollUri(), WarehouseTask.class, Warehouse.class) { @Override public boolean isFinished(ClientHttpResponse response) throws IOException { return HttpStatus.CREATED.equals(response.getStatusCode()); } @Override protected void onFinish() { if (!getResult().isEnabled()) { throw new GoodDataException("Created warehouse, uri: " + getResult().getUri() + " is not enabled!"); } } @Override public void handlePollResult(WarehouseTask pollResult) { try { final Warehouse warehouse = restTemplate.getForObject(pollResult.getWarehouseUri(), Warehouse.class); setResult(warehouse); } catch (GoodDataException | RestClientException e) { throw new GoodDataException("Warehouse creation finished, but can't get created warehouse, uri: " + pollResult.getWarehouseUri(), e); } } @Override public void handlePollException(final GoodDataRestException e) { throw new GoodDataException("Unable to create warehouse", e); } }); } /** * Delete Warehouse. * @param warehouse to delete */ public void removeWarehouse(final Warehouse warehouse) { notNull(warehouse, "warehouse"); notNull(warehouse.getUri(), "warehouse.uri"); try { restTemplate.delete(warehouse.getUri()); } catch (GoodDataException | RestClientException e) { throw new GoodDataException("Unable to delete Warehouse, uri: " + warehouse.getUri(), e); } } /** * Get Warehouse identified by given uri. * @param uri warehouse uri * @return Warehouse * @throws com.gooddata.GoodDataException when Warehouse can't be accessed */ public Warehouse getWarehouseByUri(final String uri) { notEmpty(uri, "uri"); try { return restTemplate.getForObject(uri, Warehouse.class); } catch (GoodDataRestException e) { if (HttpStatus.NOT_FOUND.value() == e.getStatusCode()) { throw new WarehouseNotFoundException(uri, e); } else { throw e; } } catch (RestClientException e) { throw new GoodDataException("Unable to get Warehouse instance " + uri, e); } } /** * Get Warehouse identified by given id. * @param id warehouse id * @return Warehouse * @throws com.gooddata.GoodDataException when Warehouse can't be accessed */ public Warehouse getWarehouseById(String id) { notEmpty(id, "id"); return getWarehouseByUri(uriFromId(id)); } private static String uriFromId(String id) { return Warehouse.TEMPLATE.expand(id).toString(); } /** * Lists Warehouses. Returns empty list in case there are no warehouses. * Returns only first page if there's more instances than page limit. Use {@link PageableList#stream()} to iterate * over all pages, or {@link MultiPageList#collectAll()} to load the entire list. * * @return MultiPageList first page of list of warehouse instances or empty list */ public PageableList<Warehouse> listWarehouses() { return listWarehouses(new PageRequest()); } /** * Lists Warehouses. Returns empty list in case there are no warehouses. * Returns requested page (by page limit and offset). Use {@link #listWarehouses()} to get first page with default setting. * * @param startPage page to be listed * @return MultiPageList requested page of list of instances or empty list */ public PageableList<Warehouse> listWarehouses(final Page startPage) { notNull(startPage, "startPage"); return new MultiPageList<>(startPage, page -> listWarehouses(getWarehousesUri(page))); } private URI getWarehousesUri() { return URI.create(Warehouses.URI); } private URI getWarehousesUri(final Page page) { return page.getPageUri(UriComponentsBuilder.fromUri(getWarehousesUri())); } private PageableList<Warehouse> listWarehouses(final URI uri) { try { final Warehouses result = restTemplate.getForObject(uri, Warehouses.class); if (result == null) { return new PageableList<>(); } return result; } catch (GoodDataException | RestClientException e) { throw new GoodDataException("Unable to list Warehouses", e); } } /** * Lists warehouse users. Returns empty list in case there are no users. * Use {@link PageableList#stream()} to iterate over all pages, * or {@link MultiPageList#collectAll()} to load the entire list. * * @param warehouse warehouse * @return MultiPageList requested page of list of instances or empty list */ public PageableList<WarehouseUser> listWarehouseUsers(final Warehouse warehouse) { return listWarehouseUsers(warehouse, new PageRequest()); } /** * Lists warehouse users, starting with specified page. Returns empty list in case there are no users. * Use {@link PageableList#stream()} to iterate over all pages, * or {@link MultiPageList#collectAll()} to load the entire list. * * @param warehouse warehouse * @param startPage page to start with * @return MultiPageList requested page of list of instances starting with startPage or empty list */ public PageableList<WarehouseUser> listWarehouseUsers(final Warehouse warehouse, final Page startPage) { notNull(warehouse, "warehouse"); notNull(warehouse.getId(), "warehouse.id"); notNull(startPage, "startPage"); return new MultiPageList<>(startPage, page -> listWarehouseUsers(warehouse, getWarehouseUsersUri(warehouse, page))); } private URI getWarehouseUsersUri(final Warehouse warehouse) { return WarehouseUsers.TEMPLATE.expand(warehouse.getId()); } private URI getWarehouseUsersUri(final Warehouse warehouse, final Page page) { return page.getPageUri(UriComponentsBuilder.fromUri(getWarehouseUsersUri(warehouse))); } private PageableList<WarehouseUser> listWarehouseUsers(final Warehouse warehouse, final URI uri) { try { final WarehouseUsers result = restTemplate.getForObject(uri, WarehouseUsers.class); return result == null ? new PageableList<>() : result; } catch (GoodDataException | RestClientException e) { throw new GoodDataException("Unable to list users of warehouse " + warehouse.getId(), e); } } /** * Add given user to given warehouse. * * @param warehouse warehouse the user should be added to * @param user user to be added * @return added user in warehouse */ public FutureResult<WarehouseUser> addUserToWarehouse(final Warehouse warehouse, final WarehouseUser user) { notNull(user, "user"); notNull(warehouse, "warehouse"); notNull(warehouse.getId(), "warehouse.id"); final WarehouseTask task; try { task = restTemplate.postForObject(WarehouseUsers.URI, user, WarehouseTask.class, warehouse.getId()); } catch (GoodDataException | RestClientException e) { throw new GoodDataException("Unable add user to warehouse " + warehouse.getId(), e); } if (task == null) { throw new GoodDataException("Empty response when user POSTed to API"); } return new PollResult<>(this, new AbstractPollHandler<WarehouseTask, WarehouseUser> (task.getPollUri(), WarehouseTask.class, WarehouseUser.class) { @Override public boolean isFinished(ClientHttpResponse response) throws IOException { return HttpStatus.CREATED.equals(response.getStatusCode()); } @Override public void handlePollResult(WarehouseTask pollResult) { try { final WarehouseUser newUser = restTemplate.getForObject(pollResult.getWarehouseUserUri(), WarehouseUser.class); setResult(newUser); } catch (GoodDataException | RestClientException e) { throw new GoodDataException("User added to warehouse, but can't get it back, uri: " + pollResult.getWarehouseUserUri(), e); } } @Override public void handlePollException(final GoodDataRestException e) { throw new GoodDataException("Unable to add user to warehouse", e); } }); } /** * Remove given user from warehouse instance * @param user to remove from warehouse * @return empty future result * @throws WarehouseUserNotFoundException when user for removal can't be found * @throws GoodDataException any other reason */ public FutureResult<Void> removeUserFromWarehouse(final WarehouseUser user) { notNull(user, "user"); notNull(user.getUri(), "user.uri"); final WarehouseTask task; try { task = restTemplate.exchange(user.getUri(), HttpMethod.DELETE, null, WarehouseTask.class).getBody(); } catch (GoodDataRestException e) { if (HttpStatus.NOT_FOUND.value() == e.getStatusCode()) { throw new WarehouseUserNotFoundException(user.getUri(), e); } else { throw e; } } catch (RestClientException e) { throw new GoodDataException("Unable to remove Warehouse user from instance " + user.getUri(), e); } if (task == null) { throw new GoodDataException("Empty response when user removed"); } return new PollResult<>(this, new AbstractPollHandler<WarehouseTask, Void> (task.getPollUri(), WarehouseTask.class, Void.class) { @Override public boolean isFinished(ClientHttpResponse response) throws IOException { return HttpStatus.CREATED.equals(response.getStatusCode()); } @Override public void handlePollResult(WarehouseTask pollResult) { setResult(null); } @Override public void handlePollException(final GoodDataRestException e) { throw new GoodDataException("Unable to remove user from warehouse", e); } }); } /** * Updates given Warehouse. * * @param toUpdate warehouse to be updated * @return updated warehouse * @throws com.gooddata.GoodDataException when update fails */ public Warehouse updateWarehouse(final Warehouse toUpdate) { notNull(toUpdate, "warehouse"); notNull(toUpdate.getUri(), "warehouse.uri"); try { restTemplate.put(toUpdate.getUri(), toUpdate); } catch (GoodDataRestException | RestClientException e) { throw new GoodDataException("Unable to update Warehouse, uri: " + toUpdate.getUri()); } return getWarehouseByUri(toUpdate.getUri()); } /** * list schemas for Warehouse * * @param warehouse to list schemas for * @return MultiPageList pageable list of warehouse schemas */ public PageableList<WarehouseSchema> listWarehouseSchemas(final Warehouse warehouse) { return listWarehouseSchemas(warehouse, new PageRequest()); } /** * list schemas for Warehouse * * @param warehouse to list schemas for * @param startPage page to be listed * @return MultiPageList pageable list of warehouse schemas */ public PageableList<WarehouseSchema> listWarehouseSchemas(final Warehouse warehouse, final Page startPage) { return new MultiPageList<>(startPage, page -> listWarehouseSchemas(getWarehouseSchemasUri(warehouse, page)) ); } private URI getWarehouseSchemasUri(final Warehouse warehouse) { notNull(warehouse, "warehouse"); notNull(warehouse.getId(), "warehouse.id"); return WarehouseSchemas.TEMPLATE.expand(warehouse.getId()); } private URI getWarehouseSchemasUri(final Warehouse warehouse, final Page page) { notNull(page, "page"); return page.getPageUri(UriComponentsBuilder.fromUri(getWarehouseSchemasUri(warehouse))); } private PageableList<WarehouseSchema> listWarehouseSchemas(final URI uri) { try { final WarehouseSchemas result = restTemplate.getForObject(uri, WarehouseSchemas.class); if (result == null) { return new PageableList<>(); } return result; } catch (GoodDataException | RestClientException e) { throw new GoodDataException("Unable to list Warehouse schemas", e); } } /** * get warehouse schema by name * * @param warehouse to get schema for * @param name of schema * @return warehouse schema */ public WarehouseSchema getWarehouseSchemaByName(final Warehouse warehouse, final String name) { notNull(warehouse, "warehouse"); notNull(warehouse.getId(), "warehouse.id"); notEmpty(name, "name"); final String uri = WarehouseSchema.TEMPLATE.expand(warehouse.getId(), name).toString(); return getWarehouseSchemaByUri(uri); } /** * get warehouse schema by uri * * @param uri of schema * @return warehouse schema */ public WarehouseSchema getWarehouseSchemaByUri(final String uri) { notEmpty(uri, "uri"); try { return restTemplate.getForObject(uri, WarehouseSchema.class); } catch (GoodDataRestException e) { if (HttpStatus.NOT_FOUND.value() == e.getStatusCode()) { throw new WarehouseSchemaNotFoundException(uri, e); } else { throw e; } } catch (RestClientException e) { throw new GoodDataException("Unable to get Warehouse instance " + uri, e); } } /** * get default warehouse schema * * @param warehouse to get default schema for * @return default warehouse schema */ public WarehouseSchema getDefaultWarehouseSchema(final Warehouse warehouse) { return getWarehouseSchemaByName(warehouse, DEFAULT_SCHEMA_NAME); } /** * List S3 credentials for the Warehouse. Returns empty list if no credentials are found. * * @param warehouse warehouse to get S3 credentials for * @return PageableList with all S3 credentials belonging to the Warehouse (not null) * @throws WarehouseS3CredentialsException in case of failure during the REST operation */ public PageableList<WarehouseS3Credentials> listWarehouseS3Credentials(final Warehouse warehouse) { notNull(warehouse, "warehouse"); final String uri = getWarehouseS3CredentialsListUri(warehouse).toString(); try { final WarehouseS3CredentialsList result = restTemplate.getForObject(uri, WarehouseS3CredentialsList.class); if (result == null) { return new PageableList<>(); } return result; } catch (GoodDataException | RestClientException e) { throw new WarehouseS3CredentialsException(uri, "Unable to list Warehouse S3 credentials at " + uri, e); } } /** * Get S3 credentials for the Warehouse based on {@code region} and {@code accessKey}. * * @param warehouse warehouse to get S3 credentials for * @return single S3 credentials record (not null) * @throws WarehouseS3CredentialsNotFoundException if no S3 credentials for the given parameters were found * @throws WarehouseS3CredentialsException in case of failure during the REST operation */ public WarehouseS3Credentials getWarehouseS3Credentials(final Warehouse warehouse, final String region, final String accessKey) { notNull(warehouse, "warehouse"); notEmpty(region, "region"); notEmpty(accessKey, "accessKey"); final String uri = getWarehouseS3CredentialsUri(warehouse, region, accessKey).toString(); try { return restTemplate.getForObject(uri, WarehouseS3Credentials.class); } catch (GoodDataRestException e) { if (HttpStatus.NOT_FOUND.value() == e.getStatusCode()) { throw new WarehouseS3CredentialsNotFoundException(uri, e); } else { throw e; } } catch (RestClientException e) { throw new WarehouseS3CredentialsException(uri, "Unable to get Warehouse S3 credentials " + uri, e); } } /** * add new S3 credentials to the Warehouse * * @param warehouse warehouse the S3 credentials should be added to * @param s3Credentials the credentials to store * @return added credentials (not null) * @throws WarehouseS3CredentialsException in case of failure during the REST operation */ public FutureResult<WarehouseS3Credentials> addS3Credentials(final Warehouse warehouse, final WarehouseS3Credentials s3Credentials) { notNull(warehouse, "warehouse"); notEmpty(warehouse.getId(), "warehouse.id"); notNull(s3Credentials, "s3Credentials"); final WarehouseTask task = createWarehouseTask(WarehouseS3CredentialsList.URI, HttpMethod.POST, s3Credentials, createUpdateHttpEntity(s3Credentials), warehouse.getId()); final String newCredentialsUri = WarehouseS3Credentials.TEMPLATE.expand(warehouse.getId(), s3Credentials.getRegion(), s3Credentials.getAccessKey()).toString(); return new PollResult<>(this, createS3PollHandler(newCredentialsUri, task, "add")); } /** * update S3 credentials in the Warehouse * * @param s3Credentials the credentials to update * @return updated credentials (not null) * @throws WarehouseS3CredentialsException in case of failure during the REST operation */ public FutureResult<WarehouseS3Credentials> updateS3Credentials(final WarehouseS3Credentials s3Credentials) { notNull(s3Credentials, "s3Credentials"); notNull(s3Credentials.getUri(), "s3Credentials.links.self"); final WarehouseTask task = createWarehouseTask(s3Credentials.getUri(), HttpMethod.PUT, s3Credentials, createUpdateHttpEntity(s3Credentials)); return new PollResult<>(this, createS3PollHandler(s3Credentials.getUri(), task, "update")); } /** * delete S3 credentials in the Warehouse * * @param s3Credentials the credentials to delete * @return nothing (Void) * @throws WarehouseS3CredentialsException in case of failure during the REST operation */ public FutureResult<Void> removeS3Credentials(final WarehouseS3Credentials s3Credentials) { notNull(s3Credentials, "s3Credentials"); notNull(s3Credentials.getUri(), "s3Credentials.links.self"); final HttpEntity<MappingJacksonValue> emptyRequestEntity = new HttpEntity<>(new HttpHeaders()); final WarehouseTask task = createWarehouseTask(s3Credentials.getUri(), HttpMethod.DELETE, s3Credentials, emptyRequestEntity); return new PollResult<>(this, createS3PollHandler(s3Credentials.getUri(), task, Void.class, "delete")); } private WarehouseTask createWarehouseTask(final String targetUri, final HttpMethod httpMethod, final WarehouseS3Credentials s3Credentials, final HttpEntity<MappingJacksonValue> requestEntity, final Object... args) { try { final HttpEntity<WarehouseTask> taskHttpEntity = restTemplate.exchange(targetUri, httpMethod, requestEntity, WarehouseTask.class, args); if (taskHttpEntity == null || taskHttpEntity.getBody() == null) { throw new WarehouseS3CredentialsException(targetUri, format("Empty response when trying to %s S3 credentials via API", httpMethod.name())); } return taskHttpEntity.getBody(); } catch (GoodDataException | RestClientException e) { final String expandedTargetUri = new UriTemplate(targetUri).expand(args).toString(); throw new WarehouseS3CredentialsException(targetUri, format("Unable to %s S3 credentials %s with region: %s, access key: %s", httpMethod.name(), expandedTargetUri, s3Credentials.getRegion(), s3Credentials.getAccessKey()), e); } } private HttpEntity<MappingJacksonValue> createUpdateHttpEntity(final WarehouseS3Credentials s3Credentials) { final MappingJacksonValue jacksonValue = new MappingJacksonValue(s3Credentials); jacksonValue.setSerializationView(WarehouseS3Credentials.UpdateView.class); return new HttpEntity<>(jacksonValue); } private AbstractPollHandler<WarehouseTask, WarehouseS3Credentials> createS3PollHandler(final String credentialsUri, final WarehouseTask task, final String action) { return createS3PollHandler(credentialsUri, task, WarehouseS3Credentials.class, action); } private <R> AbstractPollHandler<WarehouseTask, R> createS3PollHandler(final String credentialsUri, final WarehouseTask task, final Class<R> resultClass, final String action) { return new AbstractPollHandler<WarehouseTask, R>(task.getPollUri(), WarehouseTask.class, resultClass) { @Override public boolean isFinished(ClientHttpResponse response) throws IOException { final HttpStatus expectedStatus = "add".equals(action) ? HttpStatus.CREATED : HttpStatus.OK; return response.getStatusCode() == expectedStatus; } @Override public void handlePollResult(WarehouseTask pollResult) { final String uri = pollResult.getWarehouseS3CredentialsUri(); try { final R result = restTemplate.getForObject(uri, resultClass); setResult(result); } catch (GoodDataException | RestClientException e) { throw new WarehouseS3CredentialsException(uri, format("Attempt to %s S3 credentials in warehouse failed, can't get the result, uri: %s", action, uri), e); } } @Override public void handlePollException(final GoodDataRestException e) { throw new WarehouseS3CredentialsException(credentialsUri, format("Unable to %s S3 credentials in warehouse, uri: %s", action, credentialsUri), e); } }; } private URI getWarehouseS3CredentialsListUri(final Warehouse warehouse) { notEmpty(warehouse.getId(), "warehouse.id"); return WarehouseS3CredentialsList.TEMPLATE.expand(warehouse.getId()); } private URI getWarehouseS3CredentialsUri(final Warehouse warehouse, final String region, final String accessKey) { notEmpty(warehouse.getId(), "warehouse.id"); return WarehouseS3Credentials.TEMPLATE.expand(warehouse.getId(), region, accessKey); } }
92379007d4682a0d5d74442a9f7f4ac86688266f
2,902
java
Java
rtmppublisher/src/main/java/com/takusemba/rtmppublisher/VideoHandler.java
hitgou/RtmpPublisher
8bd1e473040bd09ced6cf4195d10a442738f3c41
[ "Apache-2.0" ]
604
2018-02-03T10:29:00.000Z
2022-03-31T16:00:08.000Z
rtmppublisher/src/main/java/com/takusemba/rtmppublisher/VideoHandler.java
hitgou/RtmpPublisher
8bd1e473040bd09ced6cf4195d10a442738f3c41
[ "Apache-2.0" ]
40
2018-02-04T21:16:32.000Z
2022-01-31T14:45:29.000Z
rtmppublisher/src/main/java/com/takusemba/rtmppublisher/VideoHandler.java
hitgou/RtmpPublisher
8bd1e473040bd09ced6cf4195d10a442738f3c41
[ "Apache-2.0" ]
151
2018-02-04T14:33:31.000Z
2022-03-01T02:56:05.000Z
31.89011
101
0.598897
998,115
package com.takusemba.rtmppublisher; import android.graphics.SurfaceTexture; import android.opengl.EGLContext; import android.os.Handler; import android.os.HandlerThread; import java.io.IOException; class VideoHandler implements CameraSurfaceRenderer.OnRendererStateChangedListener { private static final int FRAME_RATE = 30; /** * note that to use {@link VideoEncoder} and {@link VideoRenderer} from handler. */ private Handler handler; private VideoEncoder videoEncoder; private VideoRenderer videoRenderer; interface OnVideoEncoderStateListener { void onVideoDataEncoded(byte[] data, int size, int timestamp); } void setOnVideoEncoderStateListener(OnVideoEncoderStateListener listener) { videoEncoder.setOnVideoEncoderStateListener(listener); } VideoHandler() { this.videoRenderer = new VideoRenderer(); this.videoEncoder = new VideoEncoder(); HandlerThread handlerThread = new HandlerThread("VideoHandler"); handlerThread.start(); handler = new Handler(handlerThread.getLooper()); } void start(final int width, final int height, final int bitRate, final EGLContext sharedEglContext, final long startStreamingAt) { handler.post(new Runnable() { @Override public void run() { try { videoEncoder.prepare(width, height, bitRate, FRAME_RATE, startStreamingAt); videoEncoder.start(); videoRenderer.initialize(sharedEglContext, videoEncoder.getInputSurface()); } catch (IOException ioe) { throw new RuntimeException(ioe); } } }); } void stop() { handler.post(new Runnable() { @Override public void run() { if (videoEncoder.isEncoding()) { videoEncoder.stop(); } if (videoRenderer.isInitialized()) { videoRenderer.release(); } } }); } @Override public void onSurfaceCreated(SurfaceTexture surfaceTexture) { // no-op } @Override public void onFrameDrawn(final int textureId, final float[] transform, final long timestamp) { handler.post(new Runnable() { @Override public void run() { long elapsedTime = System.currentTimeMillis() - videoEncoder.getLastFrameEncodedAt(); if (!videoEncoder.isEncoding() || !videoRenderer.isInitialized() || elapsedTime < getFrameInterval()) { return; } videoRenderer.draw(textureId, transform, timestamp); } }); } private long getFrameInterval() { return 1000 / FRAME_RATE; } }
9237911a662213fb8e32009bcc891bed724a14ac
473
java
Java
src/fooddelivery/dataStructures/Pair.java
Dawlau/Food-Delivery-Platform
cade3108f3a667d5da82e99ee52fa16837332dee
[ "MIT" ]
null
null
null
src/fooddelivery/dataStructures/Pair.java
Dawlau/Food-Delivery-Platform
cade3108f3a667d5da82e99ee52fa16837332dee
[ "MIT" ]
null
null
null
src/fooddelivery/dataStructures/Pair.java
Dawlau/Food-Delivery-Platform
cade3108f3a667d5da82e99ee52fa16837332dee
[ "MIT" ]
null
null
null
16.310345
37
0.570825
998,116
package fooddelivery.dataStructures; public class Pair <T, Q>{ private T first; private Q second; public Pair(T first, Q second){ this.setFirst(first); this.setSecond(second); } public T getFirst() { return first; } public void setFirst(T first) { this.first = first; } public Q getSecond() { return second; } public void setSecond(Q second) { this.second = second; } }
9237919650810b1fe7de7d0aaabdd73c04842f84
870
java
Java
basic-server/src/test/java/com/zimug/courses/security/basic/PasswordEncoderTest.java
Aric-Sun/boot-security-starter
ab0c3ee9b0fcb62354a3d993d88cf033568a1623
[ "MIT" ]
null
null
null
basic-server/src/test/java/com/zimug/courses/security/basic/PasswordEncoderTest.java
Aric-Sun/boot-security-starter
ab0c3ee9b0fcb62354a3d993d88cf033568a1623
[ "MIT" ]
null
null
null
basic-server/src/test/java/com/zimug/courses/security/basic/PasswordEncoderTest.java
Aric-Sun/boot-security-starter
ab0c3ee9b0fcb62354a3d993d88cf033568a1623
[ "MIT" ]
null
null
null
29
76
0.67931
998,117
package com.zimug.courses.security.basic; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.Test; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; /** * @author AricSun * @date 2021.12.28 16:28 */ @Slf4j public class PasswordEncoderTest { @Test void bCryptPasswordTest(){ BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); String rawPassword = "123456"; String encodedPassword = passwordEncoder.encode(rawPassword); log.info("原始密码:" + rawPassword); log.info("加密后密码:" + encodedPassword); log.info(rawPassword + "是否匹配" + encodedPassword + ": " + passwordEncoder.matches(rawPassword, encodedPassword)); log.info("654321是否匹配" + encodedPassword + ": " + passwordEncoder.matches("654321", encodedPassword)); } }
923791b1cc755af97ec9c543a01f54a34644a660
704
java
Java
src/test/java/com/ansar/jeticketprinter/model/gsontraining/TestObject.java
Sepehr79/JeticketPrinter
3ae16386f90b2b2cbe45251804d6f8ac82a86ae3
[ "Apache-2.0" ]
1
2021-07-12T09:48:04.000Z
2021-07-12T09:48:04.000Z
src/test/java/com/ansar/jeticketprinter/model/gsontraining/TestObject.java
Sepehr79/JeticketPrinter
3ae16386f90b2b2cbe45251804d6f8ac82a86ae3
[ "Apache-2.0" ]
null
null
null
src/test/java/com/ansar/jeticketprinter/model/gsontraining/TestObject.java
Sepehr79/JeticketPrinter
3ae16386f90b2b2cbe45251804d6f8ac82a86ae3
[ "Apache-2.0" ]
null
null
null
29.333333
84
0.767045
998,118
package com.ansar.jeticketprinter.model.gsontraining; import com.ansar.jeticketprinter.model.pojo.ConnectionProperties; public class TestObject { private ConnectionProperties connectionProperties; public TestObject(ConnectionProperties connectionProperties) { this.connectionProperties = connectionProperties; } public TestObject() { this.connectionProperties = new ConnectionProperties.Builder().build(); } public ConnectionProperties getConnectionProperties() { return connectionProperties; } public void setConnectionProperties(ConnectionProperties connectionProperties) { this.connectionProperties = connectionProperties; } }
923791bdd58c03f564b8e4a50923148a8c4c8d74
502
java
Java
bingandroid/src/main/java/com/snail/bingandroid/serialization/entry/InfoboxActions.java
LeonidVeremchuk/BingMapAndroid
7e7bf5844fc739ddf55d7643ff34c256107b83ba
[ "Apache-2.0" ]
16
2016-11-26T12:23:19.000Z
2021-03-19T15:32:42.000Z
bingandroid/src/main/java/com/snail/bingandroid/serialization/entry/InfoboxActions.java
LeonidVeremchuk/BingMapAndroid
7e7bf5844fc739ddf55d7643ff34c256107b83ba
[ "Apache-2.0" ]
1
2017-05-17T13:34:30.000Z
2017-05-17T13:34:30.000Z
bingandroid/src/main/java/com/snail/bingandroid/serialization/entry/InfoboxActions.java
LeonidVeremchuk/BingMapAndroid
7e7bf5844fc739ddf55d7643ff34c256107b83ba
[ "Apache-2.0" ]
1
2018-02-14T12:43:18.000Z
2018-02-14T12:43:18.000Z
23.904762
76
0.685259
998,119
package com.snail.bingandroid.serialization.entry; import com.snail.bingandroid.serialization.ISerializable; /** * Created by Leonid Veremchuk on 11/9/16. */ public class InfoboxActions extends BaseBingEntry implements ISerializable { public InfoboxActions(String label, String id) { mValues.put("id", id); mValues.put("label", label); mValues.put("eventHandler", ""); } @Override public String toJsObject() { return toBaseString(mValues); } }
9237930fbd036a52985799cebed113e16f0b7d6f
1,984
java
Java
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/operations/command/SetOperation.java
raymondk/flink
2738c02db7100ff172b4ca7bd4c294419fe7ba7c
[ "Apache-2.0" ]
9
2016-09-22T22:53:13.000Z
2019-11-30T03:07:29.000Z
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/operations/command/SetOperation.java
raymondk/flink
2738c02db7100ff172b4ca7bd4c294419fe7ba7c
[ "Apache-2.0" ]
7
2021-12-18T18:39:23.000Z
2022-03-11T12:56:01.000Z
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/operations/command/SetOperation.java
raymondk/flink
2738c02db7100ff172b4ca7bd4c294419fe7ba7c
[ "Apache-2.0" ]
2
2022-02-15T07:05:13.000Z
2022-03-18T07:08:20.000Z
30.523077
97
0.691028
998,120
/* * 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.flink.table.operations.command; import org.apache.flink.table.operations.Operation; import javax.annotation.Nullable; import java.util.Optional; import static org.apache.flink.util.Preconditions.checkNotNull; /** * Operation to represent SET command. If {@link #getKey()} and {@link #getValue()} are empty, it * means show all the configurations. Otherwise, set value to the configuration key. */ public class SetOperation implements Operation { @Nullable private final String key; @Nullable private final String value; public SetOperation() { this.key = null; this.value = null; } public SetOperation(String key, String value) { this.key = checkNotNull(key); this.value = checkNotNull(value); } public Optional<String> getKey() { return Optional.ofNullable(key); } public Optional<String> getValue() { return Optional.ofNullable(value); } @Override public String asSummaryString() { if (key == null && value == null) { return "SET"; } else { return String.format("SET %s=%s", key, value); } } }
9237933e23a14adf11200c6ab66930a23f85c2ec
229
java
Java
org/apache/poi/util/Beta.java
AlhonGelios/AO
3e78fefe875ab102016e1259874886970e3c5c2a
[ "Apache-2.0" ]
1
2021-04-09T06:03:36.000Z
2021-04-09T06:03:36.000Z
org/apache/poi/util/Beta.java
kelu124/pyS3
86eb139d971921418d6a62af79f2868f9c7704d5
[ "MIT" ]
null
null
null
org/apache/poi/util/Beta.java
kelu124/pyS3
86eb139d971921418d6a62af79f2868f9c7704d5
[ "MIT" ]
null
null
null
20.818182
44
0.820961
998,121
package org.apache.poi.util; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Documented @Retention(RetentionPolicy.SOURCE) public @interface Beta { }
923793e74921227a869894afa783fdd6343ab57c
875
java
Java
src/main/java/com/google/security/zynamics/zylib/gui/JStackView/IStackModelListener.java
nkrios/binnavi
8e0aef41402db6c6ecb2a26bb943bbbc5fd989b2
[ "Apache-2.0" ]
12
2018-03-23T13:05:58.000Z
2021-03-13T04:04:50.000Z
src/main/java/com/google/security/zynamics/zylib/gui/JStackView/IStackModelListener.java
Jason-Cooke/binnavi
b98b191d8132cbde7186b486d23a217fcab4ec44
[ "Apache-2.0" ]
null
null
null
src/main/java/com/google/security/zynamics/zylib/gui/JStackView/IStackModelListener.java
Jason-Cooke/binnavi
b98b191d8132cbde7186b486d23a217fcab4ec44
[ "Apache-2.0" ]
4
2019-12-10T09:14:06.000Z
2021-03-12T12:20:58.000Z
32.407407
91
0.768
998,122
/* Copyright 2011-2016 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.google.security.zynamics.zylib.gui.JStackView; /** * Interface for listener objects that want to be notified about changes in the stack data. */ public interface IStackModelListener { /** * Invoked after the data of the stack model changed. */ void dataChanged(); }
92379416d789a40ffcbdcb1c57866aefbcf88f1f
693
java
Java
Agents/FloodAgent/FloodAgent/src/main/java/uk/ac/cam/cares/jps/agent/flood/sparqlbuilder/ValuesPattern.java
cambridge-cares/TheWorldAvatar
baf08ddc090414c6d01e48c74b408f2192461e9e
[ "MIT" ]
21
2021-03-08T01:58:25.000Z
2022-03-09T15:46:16.000Z
Agents/FloodAgent/FloodAgent/src/main/java/uk/ac/cam/cares/jps/agent/flood/sparqlbuilder/ValuesPattern.java
cambridge-cares/TheWorldAvatar
baf08ddc090414c6d01e48c74b408f2192461e9e
[ "MIT" ]
63
2021-05-04T15:05:30.000Z
2022-03-23T14:32:29.000Z
Agents/FloodAgent/FloodAgent/src/main/java/uk/ac/cam/cares/jps/agent/flood/sparqlbuilder/ValuesPattern.java
cambridge-cares/TheWorldAvatar
baf08ddc090414c6d01e48c74b408f2192461e9e
[ "MIT" ]
15
2021-03-08T07:52:03.000Z
2022-03-29T04:46:20.000Z
23.896552
65
0.714286
998,123
package uk.ac.cam.cares.jps.agent.flood.sparqlbuilder; import java.util.List; import org.eclipse.rdf4j.sparqlbuilder.core.Variable; import org.eclipse.rdf4j.sparqlbuilder.graphpattern.GraphPattern; import org.eclipse.rdf4j.sparqlbuilder.rdf.Iri; public class ValuesPattern implements GraphPattern { List<Iri> values; Variable var; public ValuesPattern(Variable var, List<Iri> values) { this.values = values; this.var = var; } @Override public String getQueryString() { String queryString = "VALUES " + var.getQueryString() + " {"; for (Iri value : values) { queryString += value.getQueryString() + " "; } queryString += "}"; return queryString; } }
923794c9f3d3aff8a5fccc64ffcb46ae7d69efdc
3,851
java
Java
src/br/com/infox/telas/TelaSobre.java
lessacaires/java_oc
55a9244eb55616ba4cf935bc2e35b03fde2e3d8e
[ "MIT" ]
null
null
null
src/br/com/infox/telas/TelaSobre.java
lessacaires/java_oc
55a9244eb55616ba4cf935bc2e35b03fde2e3d8e
[ "MIT" ]
null
null
null
src/br/com/infox/telas/TelaSobre.java
lessacaires/java_oc
55a9244eb55616ba4cf935bc2e35b03fde2e3d8e
[ "MIT" ]
null
null
null
40.968085
156
0.608933
998,124
/* * 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 br.com.infox.telas; /** * * @author User */ public class TelaSobre extends javax.swing.JInternalFrame { /** * Creates new form TelaSobre2 */ public TelaSobre() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); setClosable(true); setIconifiable(true); setMaximizable(true); setResizable(true); jLabel1.setText("Sistema para controle de ordem de seviço"); jLabel2.setText("Desenvolvido por Wyliston Lessa Caires"); jLabel3.setText("Sob a licença GPL"); jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/infox/icones/GNU.png"))); // NOI18N javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel1) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel4)) .addComponent(jLabel2)) .addGap(53, 53, 53)))) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(33, 33, 33) .addComponent(jLabel1) .addGap(18, 18, 18) .addComponent(jLabel2) .addGap(30, 30, 30) .addComponent(jLabel3) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel4) .addContainerGap()) ); setBounds(0, 0, 640, 480); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; // End of variables declaration//GEN-END:variables }
9237965382a577f8b2fa11308d26d8d14ff0ce04
8,415
java
Java
branches/toobs-0.1/Platform/BusinessLogic/src/org/toobs/framework/biz/scriptmanager/ScriptServiceImpl.java
toobs/Toobs
9c2467add64c66ef2f8368e8a432cf2f4306508a
[ "Apache-2.0" ]
3
2016-02-05T10:00:31.000Z
2018-04-17T09:47:21.000Z
branches/toobs-0.1/Platform/BusinessLogic/src/org/toobs/framework/biz/scriptmanager/ScriptServiceImpl.java
toobs/Toobs
9c2467add64c66ef2f8368e8a432cf2f4306508a
[ "Apache-2.0" ]
1
2022-01-27T16:18:54.000Z
2022-01-27T16:18:54.000Z
legacy/toobs-0.1/Platform/BusinessLogic/src/org/toobs/framework/biz/scriptmanager/ScriptServiceImpl.java
parabuzzle/toobs
8b9ff1be99f55b9e97ddd86518e104bd45f2ccdd
[ "Apache-2.0" ]
3
2016-03-09T22:59:30.000Z
2019-05-08T05:41:06.000Z
36.11588
109
0.664052
998,125
package org.toobs.framework.biz.scriptmanager; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; //import org.hibernate.Session; //import org.hibernate.SessionFactory; import org.mozilla.javascript.Context; import org.mozilla.javascript.ImporterTopLevel; import org.mozilla.javascript.JavaScriptException; import org.mozilla.javascript.NativeJavaObject; import org.mozilla.javascript.Script; import org.mozilla.javascript.Scriptable; import org.mozilla.javascript.ScriptableObject; import org.mozilla.javascript.WrappedException; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.orm.hibernate3.SessionFactoryUtils; import org.toobs.framework.exception.PermissionException; import org.toobs.framework.exception.ValidationException; @SuppressWarnings("unchecked") public final class ScriptServiceImpl implements IScriptManager, BeanFactoryAware { private Log log = LogFactory.getLog(ScriptServiceImpl.class); private Map registry = new HashMap(); private boolean doReload = true; private BeanFactory beanFactory; public ScriptServiceImpl() { super(); } public Object runScript(String scriptName, Map params, Map outParams) throws ScriptException { Object result = null; // Setup script context and scope. Context ctx = Context.enter(); Scriptable scope = new ImporterTopLevel(ctx); // Add Spring beanFactory for use in scripts. Object wrappedBeanFactory = Context.javaToJS(this.beanFactory, scope); ScriptableObject.putProperty(scope, "beanFactory", wrappedBeanFactory); Object wrappedLog = Context.javaToJS(this.log, scope); ScriptableObject.putProperty(scope, "log", wrappedLog); Object wrappedOutParams = Context.javaToJS(outParams, scope); ScriptableObject.putProperty(scope, "outParams", wrappedOutParams); // Add other parameters as passed in. if (null != params) { Iterator it = params.entrySet().iterator(); while (it.hasNext()) { Entry thisEntry = (Entry) it.next(); Object wrappedParam = Context.javaToJS(thisEntry.getValue(), scope); ScriptableObject.putProperty(scope, (String) thisEntry.getKey(), wrappedParam); } } // Get the script Script script = this.loadScript(scriptName, ctx); // Run script, return result. if (null != script) { result = script.exec(ctx, scope); } else { throw new ScriptException("Can't find script:" + scriptName); } return result; } public Object runScript(String action, String objectDao, String objectType, Map params, Map outParams) throws ScriptException, ValidationException, PermissionException { NativeJavaObject result = null; // Setup script context and scope. try { Context ctx = Context.enter(); Scriptable scope = new ImporterTopLevel(ctx); // Add Spring beanFactory for use in scripts. Object wrappedBeanFactory = Context.javaToJS(this.beanFactory, scope); ScriptableObject.putProperty(scope, "beanFactory", wrappedBeanFactory); // Add log object to be used in scripts. Object wrappedLog = Context.javaToJS(this.log, scope); ScriptableObject.putProperty(scope, "log", wrappedLog); // Add action and objectType as parameters. Object wrappedAction = Context.javaToJS(action, scope); ScriptableObject.putProperty(scope, "action", wrappedAction); Object wrappedObjectDao = Context.javaToJS(objectDao, scope); ScriptableObject.putProperty(scope, "objectDao", wrappedObjectDao); if (beanFactory.containsBean(objectDao)) { Object wrappedObjectDaoImpl = Context.javaToJS(beanFactory.getBean(objectDao), scope); ScriptableObject.putProperty(scope, "objectDaoImpl", wrappedObjectDaoImpl); } if (objectType != null) { Object wrappedObjectType = Context.javaToJS(objectType, scope); ScriptableObject.putProperty(scope, "objectType", wrappedObjectType); } Object wrappedParams = Context.javaToJS(params, scope); ScriptableObject.putProperty(scope, "params", wrappedParams); Object wrappedOutParams = Context.javaToJS(outParams, scope); ScriptableObject.putProperty(scope, "outParams", wrappedOutParams); /* TODO Check there are no uses of SessionFactory in scripts SessionFactory sessionFactory = (SessionFactory)beanFactory.getBean("sessionFactory"); Session session = SessionFactoryUtils.getSession(sessionFactory, false); Object wrappedSession = Context.javaToJS(session, scope); ScriptableObject.putProperty(scope, "session", wrappedSession); */ // Fetch the script with action_objecttype_bizScript.js as the pattern. // This includes using the more generic action_bizScript.js if an object // specific // override does not exist. String scriptName = action + "_" + objectType; Script script = this.loadScript(scriptName, ctx); if (null == script) { scriptName = action; script = this.loadScript(scriptName, ctx); } // Run script, return result. if (null != script) { try { result = (NativeJavaObject) script.exec(ctx, scope); } catch (JavaScriptException e) { Object eValue = ((JavaScriptException)e).getValue(); if (eValue instanceof NativeJavaObject) { NativeJavaObject njo = (NativeJavaObject)((JavaScriptException)e).getValue(); Throwable t = (Throwable)njo.unwrap(); if (t instanceof ValidationException) { throw (ValidationException)t; } else { log.error("Wrapped Exception: " + t.getMessage(), t); throw e; } } else { throw e; } } catch (WrappedException e) { Throwable t = (Throwable)e.getWrappedException(); if (t instanceof ValidationException) { throw (ValidationException)t; } else if (t instanceof PermissionException) { throw (PermissionException)t; } else { log.error("Wrapped Exception: " + t.getMessage(), t); throw e; } } } else { throw new ScriptException("Can't find script:" + action + "_" + objectType); } } finally { Context.exit(); } if(result != null) { return result.unwrap(); } return null; } private Script loadScript(String scriptName, Context ctx) throws ScriptException { Date initStart = new Date();; if (registry.containsKey(scriptName) && !doReload) { return (Script) registry.get(scriptName); } Script script = null; ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); URL configFileURL = classLoader.getResource("script/" + scriptName + ".js"); // If the file exists, read it. if (null != configFileURL) { try { InputStreamReader reader = new InputStreamReader(configFileURL.openStream()); script = ctx.compileReader(reader, scriptName, 1, null); } catch (IOException e) { throw new ScriptException("Can't load script:" + scriptName); } } this.registry.put(scriptName, script); if (log.isDebugEnabled()) { Date initEnd = new Date(); log.debug("Script [" + scriptName + "] - Compile Time: " + (initEnd.getTime() - initStart.getTime())); } return script; } public BeanFactory getBeanFactory() { return beanFactory; } public void setBeanFactory(BeanFactory beanFactory) throws BeansException { this.beanFactory = beanFactory; } public boolean isDoReload() { return doReload; } public void setDoReload(boolean doReload) { this.doReload = doReload; } }
923796bf04c6d6991f2d5e8cf41390fba74e55d0
794
java
Java
core/client/formatfs/src/main/java/alluxio/client/file/cache/remote/grpc/service/UpdateInfoOrBuilder.java
PasaLab/FSClientCache
6b730f2bc5aae5dd9e0dc13f16555a9ecd8f04d8
[ "Apache-2.0" ]
1
2020-10-21T14:33:52.000Z
2020-10-21T14:33:52.000Z
core/client/formatfs/src/main/java/alluxio/client/file/cache/remote/grpc/service/UpdateInfoOrBuilder.java
PasaLab/FSClientCache
6b730f2bc5aae5dd9e0dc13f16555a9ecd8f04d8
[ "Apache-2.0" ]
null
null
null
core/client/formatfs/src/main/java/alluxio/client/file/cache/remote/grpc/service/UpdateInfoOrBuilder.java
PasaLab/FSClientCache
6b730f2bc5aae5dd9e0dc13f16555a9ecd8f04d8
[ "Apache-2.0" ]
1
2021-12-06T11:50:21.000Z
2021-12-06T11:50:21.000Z
20.894737
67
0.633501
998,126
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: metedataService.proto package alluxio.client.file.cache.remote.grpc.service; public interface UpdateInfoOrBuilder extends // @@protoc_insertion_point(interface_extends:proto.UpdateInfo) com.google.protobuf.MessageOrBuilder { /** * <code>string host = 1;</code> */ String getHost(); /** * <code>string host = 1;</code> */ com.google.protobuf.ByteString getHostBytes(); /** * <code>int32 port = 2;</code> */ int getPort(); /** * <code>.proto.fileInfo info = 3;</code> */ boolean hasInfo(); /** * <code>.proto.fileInfo info = 3;</code> */ fileInfo getInfo(); /** * <code>.proto.fileInfo info = 3;</code> */ fileInfoOrBuilder getInfoOrBuilder(); }
9237974b98566dee6ea390777c7a394724561d06
4,837
java
Java
java/org/l2jserver/gameserver/model/zone/type/FortZone.java
Williams-BR/L2JStudio-V2
f3d3b329657c0f031dab107e6d4ceb5ddad0bea6
[ "MIT" ]
6
2020-05-14T22:52:59.000Z
2022-02-24T01:37:23.000Z
java/org/l2jserver/gameserver/model/zone/type/FortZone.java
huttysa/L2JServer_C6_Interlude
f3d3b329657c0f031dab107e6d4ceb5ddad0bea6
[ "MIT" ]
2
2020-12-10T15:08:48.000Z
2021-12-01T01:01:46.000Z
java/org/l2jserver/gameserver/model/zone/type/FortZone.java
huttysa/L2JServer_C6_Interlude
f3d3b329657c0f031dab107e6d4ceb5ddad0bea6
[ "MIT" ]
15
2020-05-08T20:41:06.000Z
2022-02-24T01:36:58.000Z
23.254808
93
0.699607
998,127
/* * This file is part of the L2JServer project. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.l2jserver.gameserver.model.zone.type; import java.util.ArrayList; import java.util.List; import org.l2jserver.gameserver.enums.TeleportWhereType; import org.l2jserver.gameserver.instancemanager.FortManager; import org.l2jserver.gameserver.model.actor.Creature; import org.l2jserver.gameserver.model.actor.instance.PlayerInstance; import org.l2jserver.gameserver.model.actor.instance.SiegeSummonInstance; import org.l2jserver.gameserver.model.entity.siege.Fort; import org.l2jserver.gameserver.model.zone.ZoneId; import org.l2jserver.gameserver.model.zone.ZoneRespawn; import org.l2jserver.gameserver.network.SystemMessageId; /** * A castle zone * @author programmos */ public class FortZone extends ZoneRespawn { private Fort _fort; public FortZone(int id) { super(id); } @Override public void setParameter(String name, String value) { switch (name) { case "fortId": { final int fortId = Integer.parseInt(value); // Register self to the correct fort _fort = FortManager.getInstance().getFortById(fortId); _fort.setZone(this); break; } default: { super.setParameter(name, value); break; } } } @Override protected void onEnter(Creature creature) { if (_fort.getSiege().isInProgress()) { creature.setInsideZone(ZoneId.PVP, true); creature.setInsideZone(ZoneId.SIEGE, true); if (creature instanceof PlayerInstance) { ((PlayerInstance) creature).sendPacket(SystemMessageId.YOU_HAVE_ENTERED_A_COMBAT_ZONE); } } } @Override protected void onExit(Creature creature) { if (_fort.getSiege().isInProgress()) { creature.setInsideZone(ZoneId.PVP, false); creature.setInsideZone(ZoneId.SIEGE, false); if (creature instanceof PlayerInstance) { ((PlayerInstance) creature).sendPacket(SystemMessageId.YOU_HAVE_LEFT_A_COMBAT_ZONE); // Set pvp flag if (((PlayerInstance) creature).getPvpFlag() == 0) { ((PlayerInstance) creature).startPvPFlag(); } } } if (creature instanceof SiegeSummonInstance) { ((SiegeSummonInstance) creature).unSummon(((SiegeSummonInstance) creature).getOwner()); } } @Override protected void onDieInside(Creature creature) { } @Override protected void onReviveInside(Creature creature) { } public void updateZoneStatusForCharactersInside() { if (_fort.getSiege().isInProgress()) { for (Creature creature : getCharactersInside()) { try { onEnter(creature); } catch (NullPointerException e) { } } } else { for (Creature creature : getCharactersInside()) { try { creature.setInsideZone(ZoneId.PVP, false); creature.setInsideZone(ZoneId.SIEGE, false); if (creature instanceof PlayerInstance) { ((PlayerInstance) creature).sendPacket(SystemMessageId.YOU_HAVE_LEFT_A_COMBAT_ZONE); } if (creature instanceof SiegeSummonInstance) { ((SiegeSummonInstance) creature).unSummon(((SiegeSummonInstance) creature).getOwner()); } } catch (NullPointerException e) { } } } } /** * Removes all foreigners from the fort * @param owningClanId */ public void banishForeigners(int owningClanId) { for (Creature temp : getCharactersInside()) { if (!(temp instanceof PlayerInstance)) { continue; } if (((PlayerInstance) temp).getClanId() == owningClanId) { continue; } ((PlayerInstance) temp).teleToLocation(TeleportWhereType.TOWN); } } /** * Sends a message to all players in this zone * @param message */ public void announceToPlayers(String message) { for (Creature temp : getCharactersInside()) { if (temp instanceof PlayerInstance) { ((PlayerInstance) temp).sendMessage(message); } } } /** * Returns all players within this zone * @return */ public List<PlayerInstance> getAllPlayers() { final List<PlayerInstance> players = new ArrayList<>(); for (Creature temp : getCharactersInside()) { if (temp instanceof PlayerInstance) { players.add((PlayerInstance) temp); } } return players; } }
923797c256f81c9ce6aae8469ac04fc556bf5464
1,347
java
Java
sabot/kernel/src/main/java/com/dremio/sabot/op/sort/external/Sv4HyperContainer.java
geetek/dremio-oss
812c7f32f9437df52b1d7bd8d5c45f9a79b6e9d2
[ "Apache-2.0" ]
1,085
2017-07-19T15:08:38.000Z
2022-03-29T13:35:07.000Z
sabot/kernel/src/main/java/com/dremio/sabot/op/sort/external/Sv4HyperContainer.java
geetek/dremio-oss
812c7f32f9437df52b1d7bd8d5c45f9a79b6e9d2
[ "Apache-2.0" ]
20
2017-07-19T20:16:27.000Z
2021-12-02T10:56:25.000Z
sabot/kernel/src/main/java/com/dremio/sabot/op/sort/external/Sv4HyperContainer.java
geetek/dremio-oss
812c7f32f9437df52b1d7bd8d5c45f9a79b6e9d2
[ "Apache-2.0" ]
398
2017-07-19T18:12:58.000Z
2022-03-30T09:37:40.000Z
27.489796
75
0.740163
998,128
/* * Copyright (C) 2017-2019 Dremio Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.dremio.sabot.op.sort.external; import org.apache.arrow.memory.BufferAllocator; import org.apache.arrow.vector.types.pojo.Schema; import com.dremio.exec.record.ExpandableHyperContainer; import com.dremio.exec.record.selection.SelectionVector4; public class Sv4HyperContainer extends ExpandableHyperContainer { private SelectionVector4 sv4; public Sv4HyperContainer(BufferAllocator allocator, Schema schema) { super(allocator, schema); } @Override public SelectionVector4 getSelectionVector4() { return sv4; } public void setSelectionVector4(SelectionVector4 sv4){ this.sv4 = sv4; } @Override public void close() { if(sv4 != null){ sv4.clear(); } super.close(); } }
923797db0906cd220ea6ce21be66970f31adb0f3
1,504
java
Java
knights-tour/src/test/java/Test.java
Dophin2009/csa-projects
25d12706b50b85380eaa6b3459bc69a0db625a00
[ "MIT" ]
null
null
null
knights-tour/src/test/java/Test.java
Dophin2009/csa-projects
25d12706b50b85380eaa6b3459bc69a0db625a00
[ "MIT" ]
null
null
null
knights-tour/src/test/java/Test.java
Dophin2009/csa-projects
25d12706b50b85380eaa6b3459bc69a0db625a00
[ "MIT" ]
null
null
null
28.923077
113
0.637633
998,129
import tour.Knight; import tour.Square; import java.util.ArrayList; import java.util.List; import java.util.Random; //This class should be used to test the methods in square and main. The code in here can be modified and changed //as you see fit. I have given you the code to test the entirety of your program but you may find it useful to //write your own test cases (or use JUnit). public class Test { public static void main(String[] args) { Random randy = new Random(); int startR = randy.nextInt(8); int startC = randy.nextInt(8); //Creates a tour.Knight at a random starting location Knight lancelot = new Knight(new Square(startR,startC,0),8,8); //call solve() method List<Square> answer = lancelot.solve(); //prints out the squares in the answer for (Square sq: answer) { System.out.println(sq); } //This section prints out an 8 x 8 display of the position number 1 through 64 //in the order that the knight visits them int[][] result = new int[8][8]; int pos = 0; //this loop puts the position number into the 2d array for (int k = 0; k < answer.size(); k++) { int r = answer.get(k).getRow(); int c = answer.get(k).getColumn(); result[r][c] = pos+1; pos++; } //this loop displays the 2d array result for (int r = 0; r < result.length; r++) { for (int c = 0; c < result[r].length; c++) { System.out.print(result[r][c] + "\t"); } System.out.println(); } } }
923797ff2a344e37ec1e57546f81c5f0044aa4f2
4,474
java
Java
spring-integration-rmi/src/main/java/org/springframework/integration/rmi/RmiInboundGateway.java
KyeongMoon/spring-integration
fa060900b0434627c4a520a2ae84a7a20dae735f
[ "Apache-2.0" ]
1,093
2015-01-01T15:28:50.000Z
2022-03-29T18:30:56.000Z
spring-integration-rmi/src/main/java/org/springframework/integration/rmi/RmiInboundGateway.java
KyeongMoon/spring-integration
fa060900b0434627c4a520a2ae84a7a20dae735f
[ "Apache-2.0" ]
1,920
2015-01-05T12:16:48.000Z
2022-03-31T16:58:41.000Z
spring-integration-rmi/src/main/java/org/springframework/integration/rmi/RmiInboundGateway.java
KyeongMoon/spring-integration
fa060900b0434627c4a520a2ae84a7a20dae735f
[ "Apache-2.0" ]
922
2015-01-05T05:10:05.000Z
2022-03-30T21:06:32.000Z
29.051948
96
0.771122
998,130
/* * Copyright 2002-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.integration.rmi; import java.rmi.RemoteException; import java.rmi.registry.Registry; import org.springframework.integration.gateway.MessagingGatewaySupport; import org.springframework.integration.gateway.RequestReplyExchanger; import org.springframework.integration.support.context.NamedComponent; import org.springframework.lang.Nullable; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; import org.springframework.remoting.support.RemoteInvocationExecutor; import org.springframework.util.Assert; import org.springframework.util.StringUtils; /** * An inbound Messaging Gateway for RMI-based remoting. * * @author Mark Fisher * @author Artem Bilan * @author Gary Russell * * @deprecated since 5.4 with no replacement. */ @Deprecated public class RmiInboundGateway extends MessagingGatewaySupport implements RequestReplyExchanger { public static final String SERVICE_NAME_PREFIX = "org.springframework.integration.rmiGateway."; private final org.springframework.remoting.rmi.RmiServiceExporter exporter = new org.springframework.remoting.rmi.RmiServiceExporter(); private String requestChannelName; private String registryHost; private int registryPort = Registry.REGISTRY_PORT; private boolean expectReply = true; private RemoteInvocationExecutor remoteInvocationExecutor; /** * Specify the request channel where messages will be sent. * It must not be <code>null</code>, and it must have a name. */ @Override public void setRequestChannel(MessageChannel requestChannel) { Assert.notNull(requestChannel, "requestChannel must not be null"); Assert.isTrue(requestChannel instanceof NamedComponent && StringUtils.hasText(((NamedComponent) requestChannel).getComponentName()), "RmiGateway's request channel must have a name."); this.requestChannelName = ((NamedComponent) requestChannel).getComponentName(); super.setRequestChannel(requestChannel); } @Override public void setRequestChannelName(String requestChannelName) { this.requestChannelName = requestChannelName; super.setRequestChannelName(requestChannelName); } /** * Specify whether the gateway should be expected to return a reply. * The default is '<code>true</code>'. * @param expectReply true when a reply is expected. */ public void setExpectReply(boolean expectReply) { this.expectReply = expectReply; } public void setRegistryHost(String registryHost) { this.registryHost = registryHost; } public void setRegistryPort(int registryPort) { this.registryPort = registryPort; } public void setRemoteInvocationExecutor(RemoteInvocationExecutor remoteInvocationExecutor) { this.remoteInvocationExecutor = remoteInvocationExecutor; } @Override public String getComponentType() { return "rmi:inbound-gateway"; } @Override protected void onInit() { super.onInit(); if (this.registryHost != null) { this.exporter.setRegistryHost(this.registryHost); } this.exporter.setRegistryPort(this.registryPort); if (this.remoteInvocationExecutor != null) { this.exporter.setRemoteInvocationExecutor(this.remoteInvocationExecutor); } this.exporter.setService(this); this.exporter.setServiceInterface(RequestReplyExchanger.class); this.exporter.setServiceName(SERVICE_NAME_PREFIX + this.requestChannelName); try { this.exporter.afterPropertiesSet(); } catch (RemoteException e) { throw new IllegalStateException(e); } } @Override @Nullable public Message<?> exchange(Message<?> message) { if (this.expectReply) { return sendAndReceiveMessage(message); } else { send(message); return null; } } @Override public void destroy() { try { super.destroy(); this.exporter.destroy(); } catch (Exception e) { throw new IllegalStateException(e); } } }
92379822deb36a65220afdc888f38eee1d369b35
2,189
java
Java
src/main/java/com/avseredyuk/configuration/WebSecurityConfig.java
avseredyuk/lhc
087b1901adf79c08ed6fbbd4b2b1873d27c6f36c
[ "MIT" ]
null
null
null
src/main/java/com/avseredyuk/configuration/WebSecurityConfig.java
avseredyuk/lhc
087b1901adf79c08ed6fbbd4b2b1873d27c6f36c
[ "MIT" ]
160
2017-09-16T08:07:43.000Z
2022-03-02T05:34:49.000Z
src/main/java/com/avseredyuk/configuration/WebSecurityConfig.java
avseredyuk/lhc
087b1901adf79c08ed6fbbd4b2b1873d27c6f36c
[ "MIT" ]
null
null
null
40.537037
106
0.731384
998,131
package com.avseredyuk.configuration; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private JwtAuthenticationEntryPoint unauthorizedHandler; @Override @Bean public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @Bean public JwtAuthenticationFilter authenticationTokenFilterBean() throws Exception { return new JwtAuthenticationFilter(); } @Override protected void configure(HttpSecurity http) throws Exception { http.cors().and().csrf().disable(). authorizeRequests() .antMatchers( "/admin/generate-token", "/gauge/*", "/status", "/report/add", "/pump/add", "/bootup/add", "/cfg", "/", "/index.html", "/assets/*", "/*.js", "/*.css" ).permitAll() .anyRequest().authenticated() .and() .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); http .addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class); } @Bean public BCryptPasswordEncoder encoder() { return new BCryptPasswordEncoder(); } }
92379aaa7acacdee7f0ce01aae3579c08c62f6e0
6,621
java
Java
src/main/java/dam/gestionhotelera/Util/Registro.java
jesusDrago/hotel
2a0cd86dff53b77f53eed7914eb391fd456784d7
[ "Apache-2.0" ]
1
2017-12-04T06:04:05.000Z
2017-12-04T06:04:05.000Z
src/main/java/dam/gestionhotelera/Util/Registro.java
CanaryCode/hotel
2a0cd86dff53b77f53eed7914eb391fd456784d7
[ "Apache-2.0" ]
null
null
null
src/main/java/dam/gestionhotelera/Util/Registro.java
CanaryCode/hotel
2a0cd86dff53b77f53eed7914eb391fd456784d7
[ "Apache-2.0" ]
null
null
null
43.27451
125
0.609425
998,132
package dam.gestionhotelera.Util; import java.util.Arrays; import java.util.List; /* * 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. */ /** * * @author Antonio Jesús Pérez Delgado */ public class Registro{ private final String[] arrayPaises = {"desconocido","España","Alemania","Inglaterra","Francia","Italia", "Austria","Bèlgica","Holanda","Portugal","Suiza","Luxemburgo","Rusia","Suecia","Noruega", "Finlandia","Irlanda","Escocia","Gales","Dinarmaca","Polonia", "Afganistán","Albania","Alemania","Andorra","Angola","Antigua y Barbuda","Arabia Saudita", "Argelia","Argentina","Armenia","Australia","Austria","Azerbaiyán","Bahamas","Bangladés", "Barbados","Baréin","Bélgica","Belice","Benín","Bielorrusia","Birmania","Bolivia", "Bosnia y Herzegovina","Botsuana","Brasil","Brunéi","Bulgaria","Burkina Faso","Burundi","Bután" ,"Cabo Verde","Camboya","Camerún","Canadá","Catar","Chad","Chile","China","Chipre", "Ciudad del Vaticano","Colombia","Comoras","Corea del Norte","Corea del Sur","Costa de Marfil", "Costa Rica","Croacia","Cuba","Dinamarca","Dominica","Ecuador","Egipto","El Salvador", "Emiratos Árabes Unidos","Eritrea","Eslovaquia","Eslovenia","España","Estados Unidos","Estonia" ,"Etiopía","Filipinas","Finlandia","Fiyi","Francia","Gabón","Gambia","Georgia","Ghana","Granada" ,"Grecia","Guatemala","Guyana","Guinea","Guinea ecuatorial","Guinea-Bisáu","Haití","Honduras", "Hungría","India","Indonesia","Irak","Irán","Irlanda","Islandia","Islas Marshall","Islas Salomón", "Israel","Italia","Jamaica","Japón","Jordania","Kazajistán","Kenia","Kirguistán","Kiribati","Kuwait", "Laos","Lesoto","Letonia","Líbano","Liberia","Libia","Liechtenstein","Lituania","Luxemburgo", "Madagascar","Malasia","Malaui","Maldivas","Malí","Malta","Marruecos","Mauricio","Mauritania","México", "Micronesia","Moldavia","Mónaco","Mongolia","Montenegro","Mozambique","Namibia","Nauru","Nepal", "Nicaragua","Níger","Nigeria","Noruega","Nueva Zelanda","Omán","Países Bajos","Pakistán","Palaos", "Panamá","Papúa Nueva Guinea","Paraguay","Perú","Polonia","Portugal","Reino Unido","República Centroafricana", "República Checa","República de Macedonia","República del Congo","Rep Democrática del Congo", "República Dominicana","República Sudafricana","Ruanda","Rumanía","Rusia","Samoa","San Cristóbal y Nieves", "San Marino","San Vicente y las Granadinas","Santa Lucía","Santo Tomé y Príncipe","Senegal","Serbia", "Seychelles","Sierra Leona","Singapur","Siria","Somalia","Sri Lanka","Suazilandia","Sudán","Sudán del Sur", "Suecia","Suiza","Surinam","Tailandia","Tanzania","Tayikistán","Timor Oriental","Togo","Tonga","Trinidad y Tobago", "Túnez","Turkmenistán","Turquía","Tuvalu","Ucrania","Uganda","Uruguay","Uzbekistán","Vanuatu","Venezuela","Vietnam", "Yemen","Yibuti","Zambia","Zimbabue"}; private final String[] arrayTurnos = { "primero", "segundo" }; List<String> listaTurno = Arrays.asList(arrayTurnos); private final String[] arrayMesas= { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99" }; List<String> listaMesa = Arrays.asList(arrayMesas); private final String[] arrayCategoria = { "Normal", "V.I.P", "Especial", "Repetidor" }; List<String> listaCategoria = Arrays.asList(arrayCategoria); private final String[] arrayPension = { "M.P.", "Completa","Alo Y Des" }; List<String> ListaPension = Arrays.asList(arrayPension); private final String[] arrayCategoriaRiu = { "Class", "Diamante","Gold" }; List<String> ListaCategoriaRiu = Arrays.asList(arrayCategoriaRiu); private final String[] arrayHabitacion = { "11", "13","412" }; List<String> ListaHabitacion= Arrays.asList(arrayHabitacion); private final String[] arrayTratamiento = { "Sr/Sra", "Dr/Dra", "Ingeniero/a","Don/Doña", "Ilustrisimo/a","Excelentisimo/a", "ninguno" }; List<String> ListaTratamiento = Arrays.asList(arrayTratamiento); public List<String> getListaTurno() { return listaTurno; } public void setListaTurno(List<String> listaTurno) { this.listaTurno = listaTurno; } public List<String> getListaMesa() { return listaMesa; } public void setListaMesa(List<String> listaMesa) { this.listaMesa = listaMesa; } public List<String> getListaCategoria() { return listaCategoria; } public void setListaCategoria(List<String> listaCategoria) { this.listaCategoria = listaCategoria; } public List<String> getListaPension() { return ListaPension; } public void setListaPension(List<String> ListaPension) { this.ListaPension = ListaPension; } public List<String> getListaCategoriaRiu() { return ListaCategoriaRiu; } public void setListaCategoriaRiu(List<String> ListaCategoriaRiu) { this.ListaCategoriaRiu = ListaCategoriaRiu; } public List<String> getListaHabitacion() { return ListaHabitacion; } public void setListaHabitacion(List<String> ListaHabitacion) { this.ListaHabitacion = ListaHabitacion; } public List<String> getListaTratamiento() { return ListaTratamiento; } public void setListaTratamiento(List<String> ListaTratamiento) { this.ListaTratamiento = ListaTratamiento; } List listaPaises = Arrays.asList(arrayPaises); public List getListaPaises() { return listaPaises; } public void setListaPaises(List listaPaises) { this.listaPaises = listaPaises; } }
92379be347cda23377c5dec0d80df24a788bb99a
2,867
java
Java
quarkus-test-core/src/main/java/io/quarkus/test/tracing/QuarkusScenarioTracer.java
DavideD/quarkus-test-framework
7806a376d9d51e3a76ef55a1588316eb28744422
[ "Apache-2.0" ]
10
2021-05-27T09:56:00.000Z
2022-03-11T18:16:41.000Z
quarkus-test-core/src/main/java/io/quarkus/test/tracing/QuarkusScenarioTracer.java
DavideD/quarkus-test-framework
7806a376d9d51e3a76ef55a1588316eb28744422
[ "Apache-2.0" ]
193
2021-05-04T09:04:39.000Z
2022-03-18T13:19:55.000Z
quarkus-test-core/src/main/java/io/quarkus/test/tracing/QuarkusScenarioTracer.java
DavideD/quarkus-test-framework
7806a376d9d51e3a76ef55a1588316eb28744422
[ "Apache-2.0" ]
16
2021-05-04T05:43:41.000Z
2021-11-26T10:06:41.000Z
35.8375
123
0.737705
998,133
package io.quarkus.test.tracing; import static io.quarkus.test.tracing.QuarkusScenarioTags.ERROR; import static io.quarkus.test.tracing.QuarkusScenarioTags.SUCCESS; import java.util.Collections; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.stream.Stream; import org.apache.thrift.transport.TTransportException; import io.jaegertracing.internal.JaegerTracer; import io.jaegertracing.internal.reporters.RemoteReporter; import io.jaegertracing.internal.samplers.ConstSampler; import io.jaegertracing.thrift.internal.senders.HttpSender; import io.opentracing.Span; import io.opentracing.Tracer; import io.opentracing.log.Fields; import io.quarkus.test.bootstrap.ScenarioContext; import io.quarkus.test.utils.TestExecutionProperties; public class QuarkusScenarioTracer { private final Tracer tracer; private final QuarkusScenarioSpan quarkusScenarioSpan; private final QuarkusScenarioTags quarkusScenarioTags; public QuarkusScenarioTracer(String jaegerHttpEndpoint) throws TTransportException { tracer = new JaegerTracer.Builder(TestExecutionProperties.getServiceName()) .withReporter(new RemoteReporter.Builder() .withSender(new HttpSender.Builder(jaegerHttpEndpoint).build()).build()) .withSampler(new ConstSampler(true)) .build(); this.quarkusScenarioTags = new QuarkusScenarioTags(); this.quarkusScenarioSpan = new QuarkusScenarioSpan(tracer, quarkusScenarioTags); } public void updateWithTag(ScenarioContext context, String tag) { quarkusScenarioSpan.save(Collections.emptyMap(), newHashSet(tag), context); } public void finishWithSuccess(ScenarioContext context) { finishWithSuccess(context, SUCCESS); } public void finishWithSuccess(ScenarioContext context, String tag) { quarkusScenarioSpan.save(Collections.emptyMap(), newHashSet(tag), context).finish(); } public void finishWithError(ScenarioContext context, Throwable cause) { finishWithError(context, cause, ERROR); } public void finishWithError(ScenarioContext context, Throwable cause, String tag) { Map<String, ?> err = Map.of(Fields.EVENT, "error", Fields.ERROR_OBJECT, cause, Fields.MESSAGE, cause.getMessage()); quarkusScenarioSpan.save(err, newHashSet(tag), context).finish(); } public Span createSpanContext(ScenarioContext context) { return quarkusScenarioSpan.getOrCreate(context); } public Tracer getTracer() { return tracer; } public QuarkusScenarioTags getTestFrameworkTags() { return quarkusScenarioTags; } private static Set<String> newHashSet(String... values) { Set<String> set = new HashSet<>(); Stream.of(values).forEach(set::add); return set; } }
92379d4b06b6ad34e10839d3bfd7ab09aa4a23ff
865
java
Java
src/main/java/com/dtsirlin/trip_tracker/Utils/CSVParser.java
dtsirlin/trip-tracker
e019db306ce5a159e0fd4cf4ecb1b5f516035782
[ "MIT" ]
null
null
null
src/main/java/com/dtsirlin/trip_tracker/Utils/CSVParser.java
dtsirlin/trip-tracker
e019db306ce5a159e0fd4cf4ecb1b5f516035782
[ "MIT" ]
null
null
null
src/main/java/com/dtsirlin/trip_tracker/Utils/CSVParser.java
dtsirlin/trip-tracker
e019db306ce5a159e0fd4cf4ecb1b5f516035782
[ "MIT" ]
null
null
null
24.027778
69
0.610405
998,134
package com.dtsirlin.trip_tracker.Utils; import java.io.BufferedReader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Author: Daniel Tsirlin * Date created: 05/02/2019 * Date last modified: 05/02/2019 * <p> * CSVParser * <p> * Util class for helping with parsing an input csv file * and split it up based on the comma delimiter */ public class CSVParser { public static List<List<String>> parseFile(BufferedReader file) { List<List<String>> records = new ArrayList<>(); String thisLine = null; try { while ((thisLine = file.readLine()) != null) { String[] values = thisLine.split(","); records.add(Arrays.asList(values)); } } catch (Exception e) { e.printStackTrace(); } return records; } }
92379d71bde41559e61ace22a96a95099de2c1c0
226
java
Java
src/Model/SegregationCell.java
calebsanfo/cellular-automata
b771b408371bfeaaa91d67681e1887121b931ea1
[ "MIT" ]
null
null
null
src/Model/SegregationCell.java
calebsanfo/cellular-automata
b771b408371bfeaaa91d67681e1887121b931ea1
[ "MIT" ]
null
null
null
src/Model/SegregationCell.java
calebsanfo/cellular-automata
b771b408371bfeaaa91d67681e1887121b931ea1
[ "MIT" ]
null
null
null
18.833333
72
0.685841
998,135
package Model; /** * Represents the possible states of cells in the segregation simulation * X = person of type X. O = person of type O. * * @author Achilles Dabrowski */ public enum SegregationCell { X, O, EMPTY; }
92379ddc1779f89b49a2700474a1af039affdd11
783
java
Java
src/main/java/com/letv/plugin/pluginloader/apk/compat/CompatibilityInfoCompat.java
tiwer/letv
1eeb7079be8bad4ffb61fdb06ff8d49760f9e120
[ "Apache-2.0" ]
39
2017-08-07T09:03:54.000Z
2021-09-29T09:31:39.000Z
src/main/java/com/letv/plugin/pluginloader/apk/compat/CompatibilityInfoCompat.java
JackChan1999/letv
1eeb7079be8bad4ffb61fdb06ff8d49760f9e120
[ "Apache-2.0" ]
null
null
null
src/main/java/com/letv/plugin/pluginloader/apk/compat/CompatibilityInfoCompat.java
JackChan1999/letv
1eeb7079be8bad4ffb61fdb06ff8d49760f9e120
[ "Apache-2.0" ]
39
2017-05-08T13:11:39.000Z
2021-12-26T12:42:14.000Z
34.043478
111
0.722861
998,136
package com.letv.plugin.pluginloader.apk.compat; import com.letv.plugin.pluginloader.apk.utils.FieldUtils; public class CompatibilityInfoCompat { private static Class sClass; private static Object sDefaultCompatibilityInfo; private static Class getMyClass() throws ClassNotFoundException { if (sClass == null) { sClass = Class.forName("android.content.res.CompatibilityInfo"); } return sClass; } public static Object DEFAULT_COMPATIBILITY_INFO() throws IllegalAccessException, ClassNotFoundException { if (sDefaultCompatibilityInfo == null) { sDefaultCompatibilityInfo = FieldUtils.readStaticField(getMyClass(), "DEFAULT_COMPATIBILITY_INFO"); } return sDefaultCompatibilityInfo; } }
92379e51a27c04676a5de2847c66060a4389abf7
5,612
java
Java
app/repository/UserRepository.java
adamconway/university-software-project
a28bf6a5e33bdadaf8d3d9b73b261fa617e8f829
[ "CC0-1.0" ]
1
2020-10-01T08:17:38.000Z
2020-10-01T08:17:38.000Z
app/repository/UserRepository.java
adamconway/university-software-project
a28bf6a5e33bdadaf8d3d9b73b261fa617e8f829
[ "CC0-1.0" ]
null
null
null
app/repository/UserRepository.java
adamconway/university-software-project
a28bf6a5e33bdadaf8d3d9b73b261fa617e8f829
[ "CC0-1.0" ]
1
2020-10-01T07:09:14.000Z
2020-10-01T07:09:14.000Z
32.818713
206
0.640592
998,137
package repository; import controllers.dto.User.CreateUserReq; import controllers.dto.User.NationalityReq; import controllers.dto.User.UpdateUserReq; import finders.UserFinder; import models.Nationality; import models.TravellerType; import models.User; import models.UserNationality; import play.db.ebean.Transactional; import javax.inject.Inject; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import static java.util.concurrent.CompletableFuture.supplyAsync; public class UserRepository { private DatabaseExecutionContext context; private UserFinder userFinder = new UserFinder(); @Inject public UserRepository(DatabaseExecutionContext context) { this.context = context; } /** * Gets user by their email * @param email the user email * @return completable future of user */ public CompletableFuture<User> getUserByEmail(String email) { return supplyAsync(() -> userFinder.findByEmail(email), context); } /** * Gets all users * @return completable future of list of users */ public CompletableFuture<List<User>> getAllUsers() { return supplyAsync(() -> userFinder.findAll(), context); } /** * Displays all travellers meeting the (optional) request query parameters * * @return CompletionStage<List<Traveller>> */ @Transactional public CompletionStage<List<User>> getFilteredUsers(String fname, String lname, String gender, Integer minAge, Integer maxAge, List<String> nationalities, List<String> traveller_types, String orderBy) { return supplyAsync(() -> userFinder.findUsersByParams(fname, lname, gender, minAge, maxAge, nationalities, traveller_types, orderBy), context); } /** * Creates a new user * @param request the request DTO * @return completable future of new user id */ public CompletableFuture<Long> createNewUser(CreateUserReq request) { return supplyAsync(() -> { // Insert user User user = new User(request); // int in Java defaults to 0 System.out.println("Account Type of inserterted user " + request.accountType); user.setAccountType(request.accountType); user.insert(); // Insert nationalities for(NationalityReq nationality: request.nationalities) { Nationality nationalityNew = Nationality.find.byId(nationality.id); UserNationality userNationality = new UserNationality(user, nationalityNew, nationality.hasPassport); userNationality.insert(); } // Insert traveller types user.travellerTypes = new ArrayList<TravellerType>(); for(long i: request.travellerTypes) { user.travellerTypes.add(TravellerType.find.byId(i)); } user.save(); return user.id; }, context); } /** * Gets one user by id * @param id the user id * @return completable future of user */ public CompletableFuture<User> getUser(Long id) { return supplyAsync(() -> userFinder.findById(id), context); } /** * Gets one user by id * @param id the user id * @return completable future of user */ public CompletableFuture<User> getUserIncludeDeleted(Long id) { return supplyAsync(() -> userFinder.findByIdIncludeDeleted(id), context); } /** * Updates the details of a user that matches their header and the id * @param request the request DTO * @param id the user id * @return completable future of user id */ public CompletableFuture<Long> updateUser(UpdateUserReq request, Long id) { return supplyAsync(() -> { User user = User.find.byId(id); user.setFirstName(request.firstName); user.setMiddleName(request.middleName); user.setLastName(request.lastName); user.setDateOfBirth(request.dateOfBirth); user.setGender(request.gender); user.nationalities.clear(); user.travellerTypes.clear(); List<UserNationality> userNationalities = UserNationality.find.query().where().eq("user.id", id).findList(); for (UserNationality un : userNationalities) { un.delete(); } for(NationalityReq nationality: request.nationalities) { Nationality nationalityNew = Nationality.find.byId(nationality.id); UserNationality userNationality = new UserNationality(user, nationalityNew, nationality.hasPassport); userNationality.insert(); user.nationalities.add(userNationality); } user.travellerTypes = new ArrayList<TravellerType>(); for(long i: request.travellerTypes) { user.travellerTypes.add(TravellerType.find.byId(i)); } user.save(); return user.id; }, context); } /** * Changes the user's destination field to the oppositive of its current value * @param id the users id * @return the users new deleted value */ public CompletableFuture<Boolean> toggleUserDeleted(Long id) { return supplyAsync(() -> { User user = User.find.findByIdIncludeDeleted(id); user.setDeleted(!user.isDeleted()); user.save(); return user.deleted; }, context); } }
92379fae086713170015de0cc8139ec67d61aa3a
126
java
Java
src/main/java/pl/amarcinkowski/bookee/Main.java
amarcinkowski/bookee
efd71d582dda13477f7e740f62f95d0cda2c11a2
[ "Apache-2.0" ]
null
null
null
src/main/java/pl/amarcinkowski/bookee/Main.java
amarcinkowski/bookee
efd71d582dda13477f7e740f62f95d0cda2c11a2
[ "Apache-2.0" ]
null
null
null
src/main/java/pl/amarcinkowski/bookee/Main.java
amarcinkowski/bookee
efd71d582dda13477f7e740f62f95d0cda2c11a2
[ "Apache-2.0" ]
null
null
null
12.6
41
0.706349
998,138
package pl.amarcinkowski.bookee; public class Main { public static void main(String[] args) { new BookeeService(); } }
92379fdbf0f5635b369936cbc672f70c50d024b3
1,505
java
Java
rxbinding/src/main/java/com/jakewharton/rxbinding2/widget/RatingBarRatingChangeObservable.java
kujyp/RxBinding
566ecd64cf44505acad19a75cfe820693c8c7318
[ "Apache-2.0" ]
1
2017-10-26T07:49:26.000Z
2017-10-26T07:49:26.000Z
rxbinding/src/main/java/com/jakewharton/rxbinding2/widget/RatingBarRatingChangeObservable.java
kujyp/RxBinding
566ecd64cf44505acad19a75cfe820693c8c7318
[ "Apache-2.0" ]
null
null
null
rxbinding/src/main/java/com/jakewharton/rxbinding2/widget/RatingBarRatingChangeObservable.java
kujyp/RxBinding
566ecd64cf44505acad19a75cfe820693c8c7318
[ "Apache-2.0" ]
null
null
null
29.509804
97
0.748837
998,139
package com.jakewharton.rxbinding2.widget; import android.widget.RatingBar; import android.widget.RatingBar.OnRatingBarChangeListener; import com.jakewharton.rxbinding2.InitialValueObservable; import io.reactivex.Observer; import io.reactivex.android.MainThreadDisposable; import static com.jakewharton.rxbinding2.internal.Preconditions.checkMainThread; final class RatingBarRatingChangeObservable extends InitialValueObservable<Float> { private final RatingBar view; RatingBarRatingChangeObservable(RatingBar view) { this.view = view; } @Override protected void subscribeListener(Observer<? super Float> observer) { if (!checkMainThread(observer)) { return; } Listener listener = new Listener(view, observer); view.setOnRatingBarChangeListener(listener); observer.onSubscribe(listener); } @Override protected Float getInitialValue() { return view.getRating(); } static final class Listener extends MainThreadDisposable implements OnRatingBarChangeListener { private final RatingBar view; private final Observer<? super Float> observer; Listener(RatingBar view, Observer<? super Float> observer) { this.view = view; this.observer = observer; } @Override public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) { if (!isDisposed()) { observer.onNext(rating); } } @Override protected void onDispose() { view.setOnRatingBarChangeListener(null); } } }
9237a0322d382535c39fed9ede5aa6db73b66acd
25,466
java
Java
server/src/gensrc/java/com/xinqihd/sns/gameserver/proto/XinqiBceVoiceChat.java
zyb2013/gameserver
a06cbd577684767dc50f61ff2a7a65be6001aec1
[ "Apache-2.0" ]
21
2015-04-13T18:29:56.000Z
2020-02-03T20:35:32.000Z
server/src/gensrc/java/com/xinqihd/sns/gameserver/proto/XinqiBceVoiceChat.java
zyb2013/gameserver
a06cbd577684767dc50f61ff2a7a65be6001aec1
[ "Apache-2.0" ]
2
2016-01-07T01:57:39.000Z
2016-05-07T15:40:18.000Z
server/src/gensrc/java/com/xinqihd/sns/gameserver/proto/XinqiBceVoiceChat.java
wangqi/gameserver
a06cbd577684767dc50f61ff2a7a65be6001aec1
[ "Apache-2.0" ]
18
2015-07-26T04:12:41.000Z
2021-08-16T10:03:02.000Z
35.028886
155
0.630252
998,140
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: BceVoiceChat.proto package com.xinqihd.sns.gameserver.proto; public final class XinqiBceVoiceChat { private XinqiBceVoiceChat() {} public static void registerAllExtensions( com.google.protobuf.ExtensionRegistry registry) { } public interface BceVoiceChatOrBuilder extends com.google.protobuf.MessageOrBuilder { // required int32 msgType = 1; boolean hasMsgType(); int getMsgType(); // optional bytes msgContent = 2; boolean hasMsgContent(); com.google.protobuf.ByteString getMsgContent(); // optional string usrId = 3; boolean hasUsrId(); String getUsrId(); // optional int32 second = 4; boolean hasSecond(); int getSecond(); // optional int32 filter = 10 [default = 0]; boolean hasFilter(); int getFilter(); // optional bool autoplay = 11 [default = false]; boolean hasAutoplay(); boolean getAutoplay(); } public static final class BceVoiceChat extends com.google.protobuf.GeneratedMessage implements BceVoiceChatOrBuilder { // Use BceVoiceChat.newBuilder() to construct. private BceVoiceChat(Builder builder) { super(builder); } private BceVoiceChat(boolean noInit) {} private static final BceVoiceChat defaultInstance; public static BceVoiceChat getDefaultInstance() { return defaultInstance; } public BceVoiceChat getDefaultInstanceForType() { return defaultInstance; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.xinqihd.sns.gameserver.proto.XinqiBceVoiceChat.internal_static_com_xinqihd_sns_gameserver_proto_BceVoiceChat_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return com.xinqihd.sns.gameserver.proto.XinqiBceVoiceChat.internal_static_com_xinqihd_sns_gameserver_proto_BceVoiceChat_fieldAccessorTable; } private int bitField0_; // required int32 msgType = 1; public static final int MSGTYPE_FIELD_NUMBER = 1; private int msgType_; public boolean hasMsgType() { return ((bitField0_ & 0x00000001) == 0x00000001); } public int getMsgType() { return msgType_; } // optional bytes msgContent = 2; public static final int MSGCONTENT_FIELD_NUMBER = 2; private com.google.protobuf.ByteString msgContent_; public boolean hasMsgContent() { return ((bitField0_ & 0x00000002) == 0x00000002); } public com.google.protobuf.ByteString getMsgContent() { return msgContent_; } // optional string usrId = 3; public static final int USRID_FIELD_NUMBER = 3; private java.lang.Object usrId_; public boolean hasUsrId() { return ((bitField0_ & 0x00000004) == 0x00000004); } public String getUsrId() { java.lang.Object ref = usrId_; if (ref instanceof String) { return (String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; String s = bs.toStringUtf8(); if (com.google.protobuf.Internal.isValidUtf8(bs)) { usrId_ = s; } return s; } } private com.google.protobuf.ByteString getUsrIdBytes() { java.lang.Object ref = usrId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((String) ref); usrId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } // optional int32 second = 4; public static final int SECOND_FIELD_NUMBER = 4; private int second_; public boolean hasSecond() { return ((bitField0_ & 0x00000008) == 0x00000008); } public int getSecond() { return second_; } // optional int32 filter = 10 [default = 0]; public static final int FILTER_FIELD_NUMBER = 10; private int filter_; public boolean hasFilter() { return ((bitField0_ & 0x00000010) == 0x00000010); } public int getFilter() { return filter_; } // optional bool autoplay = 11 [default = false]; public static final int AUTOPLAY_FIELD_NUMBER = 11; private boolean autoplay_; public boolean hasAutoplay() { return ((bitField0_ & 0x00000020) == 0x00000020); } public boolean getAutoplay() { return autoplay_; } private void initFields() { msgType_ = 0; msgContent_ = com.google.protobuf.ByteString.EMPTY; usrId_ = ""; second_ = 0; filter_ = 0; autoplay_ = false; } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized != -1) return isInitialized == 1; if (!hasMsgType()) { memoizedIsInitialized = 0; return false; } memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (((bitField0_ & 0x00000001) == 0x00000001)) { output.writeInt32(1, msgType_); } if (((bitField0_ & 0x00000002) == 0x00000002)) { output.writeBytes(2, msgContent_); } if (((bitField0_ & 0x00000004) == 0x00000004)) { output.writeBytes(3, getUsrIdBytes()); } if (((bitField0_ & 0x00000008) == 0x00000008)) { output.writeInt32(4, second_); } if (((bitField0_ & 0x00000010) == 0x00000010)) { output.writeInt32(10, filter_); } if (((bitField0_ & 0x00000020) == 0x00000020)) { output.writeBool(11, autoplay_); } getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream .computeInt32Size(1, msgType_); } if (((bitField0_ & 0x00000002) == 0x00000002)) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(2, msgContent_); } if (((bitField0_ & 0x00000004) == 0x00000004)) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(3, getUsrIdBytes()); } if (((bitField0_ & 0x00000008) == 0x00000008)) { size += com.google.protobuf.CodedOutputStream .computeInt32Size(4, second_); } if (((bitField0_ & 0x00000010) == 0x00000010)) { size += com.google.protobuf.CodedOutputStream .computeInt32Size(10, filter_); } if (((bitField0_ & 0x00000020) == 0x00000020)) { size += com.google.protobuf.CodedOutputStream .computeBoolSize(11, autoplay_); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { return super.writeReplace(); } public static com.xinqihd.sns.gameserver.proto.XinqiBceVoiceChat.BceVoiceChat parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static com.xinqihd.sns.gameserver.proto.XinqiBceVoiceChat.BceVoiceChat parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static com.xinqihd.sns.gameserver.proto.XinqiBceVoiceChat.BceVoiceChat parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static com.xinqihd.sns.gameserver.proto.XinqiBceVoiceChat.BceVoiceChat parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static com.xinqihd.sns.gameserver.proto.XinqiBceVoiceChat.BceVoiceChat parseFrom(java.io.InputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static com.xinqihd.sns.gameserver.proto.XinqiBceVoiceChat.BceVoiceChat parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static com.xinqihd.sns.gameserver.proto.XinqiBceVoiceChat.BceVoiceChat parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { Builder builder = newBuilder(); if (builder.mergeDelimitedFrom(input)) { return builder.buildParsed(); } else { return null; } } public static com.xinqihd.sns.gameserver.proto.XinqiBceVoiceChat.BceVoiceChat parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { Builder builder = newBuilder(); if (builder.mergeDelimitedFrom(input, extensionRegistry)) { return builder.buildParsed(); } else { return null; } } public static com.xinqihd.sns.gameserver.proto.XinqiBceVoiceChat.BceVoiceChat parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static com.xinqihd.sns.gameserver.proto.XinqiBceVoiceChat.BceVoiceChat parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(com.xinqihd.sns.gameserver.proto.XinqiBceVoiceChat.BceVoiceChat prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder<Builder> implements com.xinqihd.sns.gameserver.proto.XinqiBceVoiceChat.BceVoiceChatOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.xinqihd.sns.gameserver.proto.XinqiBceVoiceChat.internal_static_com_xinqihd_sns_gameserver_proto_BceVoiceChat_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return com.xinqihd.sns.gameserver.proto.XinqiBceVoiceChat.internal_static_com_xinqihd_sns_gameserver_proto_BceVoiceChat_fieldAccessorTable; } // Construct using com.xinqihd.sns.gameserver.proto.XinqiBceVoiceChat.BceVoiceChat.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); msgType_ = 0; bitField0_ = (bitField0_ & ~0x00000001); msgContent_ = com.google.protobuf.ByteString.EMPTY; bitField0_ = (bitField0_ & ~0x00000002); usrId_ = ""; bitField0_ = (bitField0_ & ~0x00000004); second_ = 0; bitField0_ = (bitField0_ & ~0x00000008); filter_ = 0; bitField0_ = (bitField0_ & ~0x00000010); autoplay_ = false; bitField0_ = (bitField0_ & ~0x00000020); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.xinqihd.sns.gameserver.proto.XinqiBceVoiceChat.BceVoiceChat.getDescriptor(); } public com.xinqihd.sns.gameserver.proto.XinqiBceVoiceChat.BceVoiceChat getDefaultInstanceForType() { return com.xinqihd.sns.gameserver.proto.XinqiBceVoiceChat.BceVoiceChat.getDefaultInstance(); } public com.xinqihd.sns.gameserver.proto.XinqiBceVoiceChat.BceVoiceChat build() { com.xinqihd.sns.gameserver.proto.XinqiBceVoiceChat.BceVoiceChat result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } private com.xinqihd.sns.gameserver.proto.XinqiBceVoiceChat.BceVoiceChat buildParsed() throws com.google.protobuf.InvalidProtocolBufferException { com.xinqihd.sns.gameserver.proto.XinqiBceVoiceChat.BceVoiceChat result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException( result).asInvalidProtocolBufferException(); } return result; } public com.xinqihd.sns.gameserver.proto.XinqiBceVoiceChat.BceVoiceChat buildPartial() { com.xinqihd.sns.gameserver.proto.XinqiBceVoiceChat.BceVoiceChat result = new com.xinqihd.sns.gameserver.proto.XinqiBceVoiceChat.BceVoiceChat(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.msgType_ = msgType_; if (((from_bitField0_ & 0x00000002) == 0x00000002)) { to_bitField0_ |= 0x00000002; } result.msgContent_ = msgContent_; if (((from_bitField0_ & 0x00000004) == 0x00000004)) { to_bitField0_ |= 0x00000004; } result.usrId_ = usrId_; if (((from_bitField0_ & 0x00000008) == 0x00000008)) { to_bitField0_ |= 0x00000008; } result.second_ = second_; if (((from_bitField0_ & 0x00000010) == 0x00000010)) { to_bitField0_ |= 0x00000010; } result.filter_ = filter_; if (((from_bitField0_ & 0x00000020) == 0x00000020)) { to_bitField0_ |= 0x00000020; } result.autoplay_ = autoplay_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.xinqihd.sns.gameserver.proto.XinqiBceVoiceChat.BceVoiceChat) { return mergeFrom((com.xinqihd.sns.gameserver.proto.XinqiBceVoiceChat.BceVoiceChat)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.xinqihd.sns.gameserver.proto.XinqiBceVoiceChat.BceVoiceChat other) { if (other == com.xinqihd.sns.gameserver.proto.XinqiBceVoiceChat.BceVoiceChat.getDefaultInstance()) return this; if (other.hasMsgType()) { setMsgType(other.getMsgType()); } if (other.hasMsgContent()) { setMsgContent(other.getMsgContent()); } if (other.hasUsrId()) { setUsrId(other.getUsrId()); } if (other.hasSecond()) { setSecond(other.getSecond()); } if (other.hasFilter()) { setFilter(other.getFilter()); } if (other.hasAutoplay()) { setAutoplay(other.getAutoplay()); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { if (!hasMsgType()) { return false; } return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder( this.getUnknownFields()); while (true) { int tag = input.readTag(); switch (tag) { case 0: this.setUnknownFields(unknownFields.build()); onChanged(); return this; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); onChanged(); return this; } break; } case 8: { bitField0_ |= 0x00000001; msgType_ = input.readInt32(); break; } case 18: { bitField0_ |= 0x00000002; msgContent_ = input.readBytes(); break; } case 26: { bitField0_ |= 0x00000004; usrId_ = input.readBytes(); break; } case 32: { bitField0_ |= 0x00000008; second_ = input.readInt32(); break; } case 80: { bitField0_ |= 0x00000010; filter_ = input.readInt32(); break; } case 88: { bitField0_ |= 0x00000020; autoplay_ = input.readBool(); break; } } } } private int bitField0_; // required int32 msgType = 1; private int msgType_ ; public boolean hasMsgType() { return ((bitField0_ & 0x00000001) == 0x00000001); } public int getMsgType() { return msgType_; } public Builder setMsgType(int value) { bitField0_ |= 0x00000001; msgType_ = value; onChanged(); return this; } public Builder clearMsgType() { bitField0_ = (bitField0_ & ~0x00000001); msgType_ = 0; onChanged(); return this; } // optional bytes msgContent = 2; private com.google.protobuf.ByteString msgContent_ = com.google.protobuf.ByteString.EMPTY; public boolean hasMsgContent() { return ((bitField0_ & 0x00000002) == 0x00000002); } public com.google.protobuf.ByteString getMsgContent() { return msgContent_; } public Builder setMsgContent(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000002; msgContent_ = value; onChanged(); return this; } public Builder clearMsgContent() { bitField0_ = (bitField0_ & ~0x00000002); msgContent_ = getDefaultInstance().getMsgContent(); onChanged(); return this; } // optional string usrId = 3; private java.lang.Object usrId_ = ""; public boolean hasUsrId() { return ((bitField0_ & 0x00000004) == 0x00000004); } public String getUsrId() { java.lang.Object ref = usrId_; if (!(ref instanceof String)) { String s = ((com.google.protobuf.ByteString) ref).toStringUtf8(); usrId_ = s; return s; } else { return (String) ref; } } public Builder setUsrId(String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000004; usrId_ = value; onChanged(); return this; } public Builder clearUsrId() { bitField0_ = (bitField0_ & ~0x00000004); usrId_ = getDefaultInstance().getUsrId(); onChanged(); return this; } void setUsrId(com.google.protobuf.ByteString value) { bitField0_ |= 0x00000004; usrId_ = value; onChanged(); } // optional int32 second = 4; private int second_ ; public boolean hasSecond() { return ((bitField0_ & 0x00000008) == 0x00000008); } public int getSecond() { return second_; } public Builder setSecond(int value) { bitField0_ |= 0x00000008; second_ = value; onChanged(); return this; } public Builder clearSecond() { bitField0_ = (bitField0_ & ~0x00000008); second_ = 0; onChanged(); return this; } // optional int32 filter = 10 [default = 0]; private int filter_ ; public boolean hasFilter() { return ((bitField0_ & 0x00000010) == 0x00000010); } public int getFilter() { return filter_; } public Builder setFilter(int value) { bitField0_ |= 0x00000010; filter_ = value; onChanged(); return this; } public Builder clearFilter() { bitField0_ = (bitField0_ & ~0x00000010); filter_ = 0; onChanged(); return this; } // optional bool autoplay = 11 [default = false]; private boolean autoplay_ ; public boolean hasAutoplay() { return ((bitField0_ & 0x00000020) == 0x00000020); } public boolean getAutoplay() { return autoplay_; } public Builder setAutoplay(boolean value) { bitField0_ |= 0x00000020; autoplay_ = value; onChanged(); return this; } public Builder clearAutoplay() { bitField0_ = (bitField0_ & ~0x00000020); autoplay_ = false; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:com.xinqihd.sns.gameserver.proto.BceVoiceChat) } static { defaultInstance = new BceVoiceChat(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:com.xinqihd.sns.gameserver.proto.BceVoiceChat) } private static com.google.protobuf.Descriptors.Descriptor internal_static_com_xinqihd_sns_gameserver_proto_BceVoiceChat_descriptor; private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_com_xinqihd_sns_gameserver_proto_BceVoiceChat_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n\022BceVoiceChat.proto\022 com.xinqihd.sns.ga" + "meserver.proto\"~\n\014BceVoiceChat\022\017\n\007msgTyp" + "e\030\001 \002(\005\022\022\n\nmsgContent\030\002 \001(\014\022\r\n\005usrId\030\003 \001" + "(\t\022\016\n\006second\030\004 \001(\005\022\021\n\006filter\030\n \001(\005:\0010\022\027\n" + "\010autoplay\030\013 \001(\010:\005falseB\023B\021XinqiBceVoiceC" + "hat" }; com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() { public com.google.protobuf.ExtensionRegistry assignDescriptors( com.google.protobuf.Descriptors.FileDescriptor root) { descriptor = root; internal_static_com_xinqihd_sns_gameserver_proto_BceVoiceChat_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_com_xinqihd_sns_gameserver_proto_BceVoiceChat_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_com_xinqihd_sns_gameserver_proto_BceVoiceChat_descriptor, new java.lang.String[] { "MsgType", "MsgContent", "UsrId", "Second", "Filter", "Autoplay", }, com.xinqihd.sns.gameserver.proto.XinqiBceVoiceChat.BceVoiceChat.class, com.xinqihd.sns.gameserver.proto.XinqiBceVoiceChat.BceVoiceChat.Builder.class); return null; } }; com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { }, assigner); } // @@protoc_insertion_point(outer_class_scope) }
9237a148b8ac734a03f379ebdad8cd116792ec61
5,456
java
Java
test/transform/resource/after-delombok/SuperBuilderWithCustomBuilderMethod.java
mankeyl/lombok
d3b763f9dab4a46e88ff10bc2132fb6f12fda639
[ "MIT" ]
9,959
2015-01-02T21:02:36.000Z
2021-04-22T20:07:49.000Z
test/transform/resource/after-delombok/SuperBuilderWithCustomBuilderMethod.java
mankeyl/lombok
d3b763f9dab4a46e88ff10bc2132fb6f12fda639
[ "MIT" ]
2,007
2015-01-29T19:56:09.000Z
2021-04-21T14:46:05.000Z
test/transform/resource/after-delombok/SuperBuilderWithCustomBuilderMethod.java
mankeyl/lombok
d3b763f9dab4a46e88ff10bc2132fb6f12fda639
[ "MIT" ]
2,147
2015-01-04T01:49:48.000Z
2021-04-22T13:32:19.000Z
38.153846
231
0.713893
998,141
//version 8: Javac 6 will error out due to `ChildBuilder` not existing before properly running lombok. Giving j6 support status, not worth fixing. import java.util.List; public class SuperBuilderWithCustomBuilderMethod { public static class Parent<A> { A field1; List<String> items; @java.lang.SuppressWarnings("all") public static abstract class ParentBuilder<A, C extends SuperBuilderWithCustomBuilderMethod.Parent<A>, B extends SuperBuilderWithCustomBuilderMethod.Parent.ParentBuilder<A, C, B>> { @java.lang.SuppressWarnings("all") private A field1; @java.lang.SuppressWarnings("all") private java.util.ArrayList<String> items; @java.lang.SuppressWarnings("all") protected abstract B self(); @java.lang.SuppressWarnings("all") public abstract C build(); /** * @return {@code this}. */ @java.lang.SuppressWarnings("all") public B field1(final A field1) { this.field1 = field1; return self(); } @java.lang.SuppressWarnings("all") public B item(final String item) { if (this.items == null) this.items = new java.util.ArrayList<String>(); this.items.add(item); return self(); } @java.lang.SuppressWarnings("all") public B items(final java.util.Collection<? extends String> items) { if (items == null) { throw new java.lang.NullPointerException("items cannot be null"); } if (this.items == null) this.items = new java.util.ArrayList<String>(); this.items.addAll(items); return self(); } @java.lang.SuppressWarnings("all") public B clearItems() { if (this.items != null) this.items.clear(); return self(); } @java.lang.Override @java.lang.SuppressWarnings("all") public java.lang.String toString() { return "SuperBuilderWithCustomBuilderMethod.Parent.ParentBuilder(field1=" + this.field1 + ", items=" + this.items + ")"; } } @java.lang.SuppressWarnings("all") private static final class ParentBuilderImpl<A> extends SuperBuilderWithCustomBuilderMethod.Parent.ParentBuilder<A, SuperBuilderWithCustomBuilderMethod.Parent<A>, SuperBuilderWithCustomBuilderMethod.Parent.ParentBuilderImpl<A>> { @java.lang.SuppressWarnings("all") private ParentBuilderImpl() { } @java.lang.Override @java.lang.SuppressWarnings("all") protected SuperBuilderWithCustomBuilderMethod.Parent.ParentBuilderImpl<A> self() { return this; } @java.lang.Override @java.lang.SuppressWarnings("all") public SuperBuilderWithCustomBuilderMethod.Parent<A> build() { return new SuperBuilderWithCustomBuilderMethod.Parent<A>(this); } } @java.lang.SuppressWarnings("all") protected Parent(final SuperBuilderWithCustomBuilderMethod.Parent.ParentBuilder<A, ?, ?> b) { this.field1 = b.field1; java.util.List<String> items; switch (b.items == null ? 0 : b.items.size()) { case 0: items = java.util.Collections.emptyList(); break; case 1: items = java.util.Collections.singletonList(b.items.get(0)); break; default: items = java.util.Collections.unmodifiableList(new java.util.ArrayList<String>(b.items)); } this.items = items; } @java.lang.SuppressWarnings("all") public static <A> SuperBuilderWithCustomBuilderMethod.Parent.ParentBuilder<A, ?, ?> builder() { return new SuperBuilderWithCustomBuilderMethod.Parent.ParentBuilderImpl<A>(); } } public static class Child<A> extends Parent<A> { double field3; public static <A> ChildBuilder<A, ?, ?> builder() { return new ChildBuilderImpl<A>().item("default item"); } @java.lang.SuppressWarnings("all") public static abstract class ChildBuilder<A, C extends SuperBuilderWithCustomBuilderMethod.Child<A>, B extends SuperBuilderWithCustomBuilderMethod.Child.ChildBuilder<A, C, B>> extends Parent.ParentBuilder<A, C, B> { @java.lang.SuppressWarnings("all") private double field3; @java.lang.Override @java.lang.SuppressWarnings("all") protected abstract B self(); @java.lang.Override @java.lang.SuppressWarnings("all") public abstract C build(); /** * @return {@code this}. */ @java.lang.SuppressWarnings("all") public B field3(final double field3) { this.field3 = field3; return self(); } @java.lang.Override @java.lang.SuppressWarnings("all") public java.lang.String toString() { return "SuperBuilderWithCustomBuilderMethod.Child.ChildBuilder(super=" + super.toString() + ", field3=" + this.field3 + ")"; } } @java.lang.SuppressWarnings("all") private static final class ChildBuilderImpl<A> extends SuperBuilderWithCustomBuilderMethod.Child.ChildBuilder<A, SuperBuilderWithCustomBuilderMethod.Child<A>, SuperBuilderWithCustomBuilderMethod.Child.ChildBuilderImpl<A>> { @java.lang.SuppressWarnings("all") private ChildBuilderImpl() { } @java.lang.Override @java.lang.SuppressWarnings("all") protected SuperBuilderWithCustomBuilderMethod.Child.ChildBuilderImpl<A> self() { return this; } @java.lang.Override @java.lang.SuppressWarnings("all") public SuperBuilderWithCustomBuilderMethod.Child<A> build() { return new SuperBuilderWithCustomBuilderMethod.Child<A>(this); } } @java.lang.SuppressWarnings("all") protected Child(final SuperBuilderWithCustomBuilderMethod.Child.ChildBuilder<A, ?, ?> b) { super(b); this.field3 = b.field3; } } public static void test() { Child<Integer> x = Child.<Integer>builder().field3(0.0).field1(5).item("").build(); } }
9237a305e8264c43206c747cd16078416b009b6c
1,898
java
Java
ruoyi-quartz/src/main/java/com/ruoyi/quartz/service/IJobService.java
kaifazhehcf/ics-park
98b5ce350d3299e81433c79593fb12e811fc7509
[ "MIT" ]
9
2021-10-09T14:58:27.000Z
2022-01-26T07:21:29.000Z
ruoyi-quartz/src/main/java/com/ruoyi/quartz/service/IJobService.java
923325596/ics-park
98b5ce350d3299e81433c79593fb12e811fc7509
[ "MIT" ]
1
2021-05-14T01:37:22.000Z
2021-05-15T08:26:36.000Z
ruoyi-quartz/src/main/java/com/ruoyi/quartz/service/IJobService.java
923325596/ics-park
98b5ce350d3299e81433c79593fb12e811fc7509
[ "MIT" ]
6
2021-06-26T13:34:29.000Z
2022-01-16T12:13:57.000Z
18.25
69
0.576923
998,142
package com.ruoyi.quartz.service; import com.ruoyi.common.core.service.IBaseService; import com.ruoyi.common.exception.job.TaskException; import com.ruoyi.quartz.domain.Job; import org.quartz.SchedulerException; import java.util.List; /** * 定时任务调度信息信息 服务层 * * @author ruoyi */ public interface IJobService extends IBaseService<Job> { /** * 获取quartz调度器的计划任务 * * @param job 调度信息 * @return 调度任务集合 */ List<Job> selectJobList(Job job); /** * 通过调度任务ID查询调度信息 * * @param jobId 调度任务ID * @return 调度任务对象信息 */ Job selectJobById(Long jobId); /** * 暂停任务 * * @param job 调度信息 * @return 结果 */ int pauseJob(Job job) throws SchedulerException; /** * 恢复任务 * * @param job 调度信息 * @return 结果 */ int resumeJob(Job job) throws SchedulerException; /** * 删除任务后,所对应的trigger也将被删除 * * @param job 调度信息 * @return 结果 */ int deleteJob(Job job) throws SchedulerException; /** * 批量删除调度信息 * * @param jobIds 需要删除的任务ID * @return 结果 */ void deleteJobByIds(Long[] jobIds) throws SchedulerException; /** * 任务调度状态修改 * * @param job 调度信息 * @return 结果 */ int changeStatus(Job job) throws SchedulerException; /** * 立即运行任务 * * @param job 调度信息 * @return 结果 */ void run(Job job) throws SchedulerException; /** * 新增任务 * * @param job 调度信息 * @return 结果 */ int insertJob(Job job) throws SchedulerException, TaskException; /** * 更新任务 * * @param job 调度信息 * @return 结果 */ int updateJob(Job job) throws SchedulerException, TaskException; /** * 校验cron表达式是否有效 * * @param cronExpression 表达式 * @return 结果 */ boolean checkCronExpressionIsValid(String cronExpression); }
9237a3a91a947f528709539e67f9d3a183cf5f90
5,931
java
Java
src/main/java/nablarch/fw/dicontainer/container/ContainerBuilder.java
backpaper0/nablarch-fw-scoped-dicontainer
540f2c5279d18460150bfa8575fe40510132e259
[ "Apache-2.0" ]
null
null
null
src/main/java/nablarch/fw/dicontainer/container/ContainerBuilder.java
backpaper0/nablarch-fw-scoped-dicontainer
540f2c5279d18460150bfa8575fe40510132e259
[ "Apache-2.0" ]
7
2019-10-24T02:05:54.000Z
2020-11-04T05:23:00.000Z
src/main/java/nablarch/fw/dicontainer/container/ContainerBuilder.java
backpaper0/nablarch-fw-scoped-dicontainer
540f2c5279d18460150bfa8575fe40510132e259
[ "Apache-2.0" ]
1
2019-11-08T05:16:34.000Z
2019-11-08T05:16:34.000Z
29.361386
103
0.651829
998,143
package nablarch.fw.dicontainer.container; import java.util.Collections; import java.util.Objects; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import javax.inject.Provider; import nablarch.core.log.Logger; import nablarch.core.log.LoggerManager; import nablarch.fw.dicontainer.Container; import nablarch.fw.dicontainer.component.AliasMapping; import nablarch.fw.dicontainer.component.ComponentDefinition; import nablarch.fw.dicontainer.component.ComponentDefinitionRepository; import nablarch.fw.dicontainer.component.ComponentId; import nablarch.fw.dicontainer.component.ComponentKey; import nablarch.fw.dicontainer.component.ComponentKey.AliasKey; import nablarch.fw.dicontainer.component.ErrorCollector; import nablarch.fw.dicontainer.component.impl.ContainerInjectableConstructor; import nablarch.fw.dicontainer.event.ContainerCreated; import nablarch.fw.dicontainer.exception.ContainerException; import nablarch.fw.dicontainer.scope.Scope; /** * DIコンテナのビルダー。 * * @param <BUILDER> このビルダーのサブクラス */ public class ContainerBuilder<BUILDER extends ContainerBuilder<BUILDER>> { /** * ロガー */ private static final Logger logger = LoggerManager.get(ContainerBuilder.class); /** * コンポーネント定義のリポジトリ */ private final ComponentDefinitionRepository definitions = new ComponentDefinitionRepository(); /** * エイリアスキーと検索キーのマッピング */ private final AliasMapping aliasesMap = new AliasMapping(); /** * バリデーションエラーを収集するクラス */ protected final ErrorCollector errorCollector = ErrorCollector.newInstance(); /** * DIコンテナの構築を開始した時点の{@link System#nanoTime()}値 */ private final long startedAt; /** * インスタンスを生成する。 * */ public ContainerBuilder() { this.startedAt = System.nanoTime(); logger.logInfo("Start building a Container."); } /** * {@link ErrorCollector#throwExceptionIfExistsError()}で無視をする例外クラスを設定する。 * * @param ignoreMe 無視される例外クラス * @return このビルダー自身 */ public BUILDER ignoreError(final Class<? extends ContainerException> ignoreMe) { logger.logDebug("Ignore error during building Container. ignored class=" + ignoreMe.getName()); errorCollector.ignore(ignoreMe); return self(); } /** * コンポーネント定義を登録する。 * * @param <T> コンポーネントの型 * @param key 検索キー * @param definition コンポーネント定義 * @return このビルダー自身 */ public <T> BUILDER register(final ComponentKey<T> key, final ComponentDefinition<T> definition) { logger.logDebug("Start registering component definition. key=" + key); for (final AliasKey aliasKey : key.aliasKeys()) { logger.logDebug("Register alias key [" + aliasKey + "] for [" + key + "]"); aliasesMap.register(aliasKey, key); } definitions.register(key, definition); logger.logDebug("Component definition registered. key=" + key); return self(); } /** * コンポーネント定義を検索する。 * * @param key 検索キー * @return コンポーネント定義の集合 */ public Set<ComponentDefinition<?>> findComponentDefinitions(final ComponentKey<?> key) { final ComponentDefinition<?> definition = definitions.find(key); if (definition != null) { return Collections.singleton(definition); } final Set<ComponentKey<?>> alterKeys = aliasesMap.find(key.asAliasKey()); return alterKeys.stream().map(definitions::find).filter(Objects::nonNull) .collect(Collectors.toSet()); } /** * 依存関係の循環を検出するためのバリデーションを行う。 * * @param key 検索キー * @param target 対象となるコンポーネント定義 */ public void validateCycleDependency(final ComponentKey<?> key, final ComponentDefinition<?> target) { final CycleDependencyValidationContext context = CycleDependencyValidationContext .newContext(this, target); context.validateCycleDependency(key); } /** * バリデーションエラーを追加する。 * * @param exception バリデーションエラー */ public void addError(final ContainerException exception) { errorCollector.add(exception); } /** * DIコンテナを構築する。 * * @return 構築されたDIコンテナ */ public Container build() { registerContainer(); definitions.validate(this); errorCollector.throwExceptionIfExistsError(); final DefaultContainer container = new DefaultContainer(definitions, aliasesMap); final long time = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startedAt); logger.logInfo("Built Container. " + time + "(msec)"); container.fire(new ContainerCreated()); return container; } /** * DIコンテナのコンポーネント定義を登録する。 * */ private void registerContainer() { final ComponentKey<DefaultContainer> key = new ComponentKey<>( DefaultContainer.class); final ComponentDefinition<DefaultContainer> definition = ComponentDefinition .builder(DefaultContainer.class) .injectableConstructor(new ContainerInjectableConstructor()) .scope(new ContainerScope()) .build() .get(); register(key, definition); } /** * 自分自身を{@code BUILDER}型へキャストする。 * * @return 自分自身 */ private BUILDER self() { return (BUILDER) this; } /** * DIコンテナ専用のスコープ。 * */ private final class ContainerScope implements Scope { @Override public <T> T getComponent(final ComponentId id, final Provider<T> provider) { return provider.get(); } @Override public int dimensions() { return Integer.MAX_VALUE; } @Override public <T> void register(final ComponentDefinition<T> definition) { } } }
9237a5189c99f2d7523572ebdd1e74182260be1f
7,532
java
Java
project/src/main/java/com/google/sps/servlets/BrowseServlet.java
SirLegolot/ProjectCloudBerry
aff7717a0c7ea6e7f3fe4a4f50c7f67ae400b754
[ "Apache-2.0" ]
2
2020-08-07T20:59:55.000Z
2020-09-02T21:49:57.000Z
project/src/main/java/com/google/sps/servlets/BrowseServlet.java
SirLegolot/ProjectCloudBerry
aff7717a0c7ea6e7f3fe4a4f50c7f67ae400b754
[ "Apache-2.0" ]
3
2020-06-29T14:43:55.000Z
2020-07-24T18:47:15.000Z
project/src/main/java/com/google/sps/servlets/BrowseServlet.java
SirLegolot/ProjectCloudBerry
aff7717a0c7ea6e7f3fe4a4f50c7f67ae400b754
[ "Apache-2.0" ]
1
2020-08-07T21:03:26.000Z
2020-08-07T21:03:26.000Z
40.934783
127
0.714286
998,144
package com.google.sps.servlets; import com.google.gson.Gson; import java.util.ArrayList; import java.util.List; import java.util.Arrays; import java.util.Map; import java.util.Set; import java.util.HashSet; import com.google.sps.data.*; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.Text; import com.google.appengine.api.datastore.PreparedQuery; import com.google.appengine.api.datastore.Query; import com.google.appengine.api.datastore.Query.SortDirection; import com.google.appengine.api.datastore.FetchOptions; import com.google.appengine.api.blobstore.BlobInfo; import com.google.appengine.api.blobstore.BlobInfoFactory; import com.google.appengine.api.blobstore.BlobKey; import com.google.appengine.api.blobstore.BlobstoreService; import com.google.appengine.api.blobstore.BlobstoreServiceFactory; import com.google.appengine.api.blobstore.FileInfo; import java.io.IOException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.appengine.api.users.UserService; import com.google.appengine.api.users.UserServiceFactory; @WebServlet("/browse") public class BrowseServlet extends HttpServlet { protected Gson gson; protected DatastoreService datastore; protected BlobstoreService blobstore; protected UserService userService; public BrowseServlet() { super(); gson = new Gson(); datastore = DatastoreServiceFactory.getDatastoreService(); blobstore = BlobstoreServiceFactory.getBlobstoreService(); userService = UserServiceFactory.getUserService(); } @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { // Retrieve parameters from the request String productSetDisplayName = request.getParameter("productSetDisplayName"); String productCategory = request.getParameter("productCategory"); String businessId = request.getParameter("businessId"); String sortOrder = request.getParameter("sortOrder"); String searchId = request.getParameter("searchId"); // Set parameters to apprpriate defaults, if necessary. if (businessId.equals("none")) { businessId = null; } if (productCategory.equals("none")) { productCategory = null; } String productSetId = null; ProductSetEntity productSet = null; if (!productSetDisplayName.equals("none")) { // true indicates we are searching with the displayname instead of the id. productSet = ServletLibrary.retrieveProductSetInfo(datastore, productSetDisplayName, true); } if (productSet != null) { productSetId = productSet.getProductSetId(); } // Search database based on the filters. List<ProductEntity> products = ServletLibrary.findProducts(datastore, businessId, productSetId, productCategory, sortOrder); if (searchId != null) { SearchInfo searchInfo = ServletLibrary.retrieveSearchInfo(datastore, searchId); if (searchInfo.getGcsUrl() != null) { String generalProductSetId = "cloudberryAllProducts"; List <String> productSearchIds = ProductSearchLibrary.getSimilarProductsGcs(generalProductSetId, searchInfo.getProductCategory(), changeGcsFormat(searchInfo.getGcsUrl())); List<ProductEntity> imageSearchProducts = new ArrayList<>(); productSearchIds.forEach(productId->imageSearchProducts.add(ServletLibrary.retrieveProductInfo(datastore, productId))); Set<ProductEntity> uniqueProducts = new HashSet<>(products); List<ProductEntity> productsDisplayed = new ArrayList<>(); for (ProductEntity product : imageSearchProducts) { if (uniqueProducts.contains(product)) productsDisplayed.add(product); } products = productsDisplayed; } // Text query if it is specified, will take in this list and output a new // list that satisfies the query. if (searchInfo.getTextSearch() != null) { products = TextSearchLibrary.textSearch(datastore, products, searchInfo.getTextSearch()); } } // TODO: call sorting mechanism here for location. boolean sortLocation = Boolean.parseBoolean(request.getParameter("location")); if (sortLocation && userService.isUserLoggedIn()) { List<ProductWithAddress> productsWithAddress = ServletLibrary.convertToProductWithAddress(datastore, products); Account account = ServletLibrary.retrieveAccountInfo(datastore, userService, userService.getCurrentUser().getUserId()); products = MapsLibrary.sortByLocation(productsWithAddress, account); } // Send the response. String json = gson.toJson(products); response.setContentType("application/json;"); response.getWriter().println(json); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { String textSearch = request.getParameter("textSearch"); boolean userUploadedImage = Boolean.parseBoolean(request.getParameter("userUploadedImage")); // Creates a new SearchInfo object, which will be stored in datastore. String searchId = ServletLibrary.generateUUID(); Entity searchInfo = new Entity("SearchInfo", searchId); searchInfo.setProperty("searchId", searchId); searchInfo.setProperty("timestamp", System.currentTimeMillis()); if (userService.isUserLoggedIn()) { searchInfo.setProperty("userId", userService.getCurrentUser().getUserId()); ServletLibrary.addSearchInfoToSearchHistory(datastore, userService.getCurrentUser().getUserId(), searchId); } else { searchInfo.setProperty("userId", null); } // Checks if the user sent a text search or a image search or both. Adds // query properties appropriately. searchInfo.setProperty("gcsUrl", null); searchInfo.setProperty("imageUrl", null); searchInfo.setProperty("textSearch", null); searchInfo.setProperty("productCategory", null); if (userUploadedImage) { String gcsUrl = CloudStorageLibrary.getGcsFilePath(request, blobstore); BlobKey blobKey = blobstore.createGsBlobKey(gcsUrl); String imageUrl = "/serveBlobstoreImage?blobKey=" + blobKey.getKeyString(); searchInfo.setProperty("gcsUrl", gcsUrl); searchInfo.setProperty("imageUrl", imageUrl); searchInfo.setProperty("productCategory", request.getParameter("productCategorySearch")); } if (!textSearch.isEmpty()) { searchInfo.setProperty("textSearch", textSearch); } datastore.put(searchInfo); response.sendRedirect("/browse.html?searchId="+searchId); } private String changeGcsFormat(String gcsUri){ String newGcsFormat = "gs://"; String[] gcsArray = gcsUri.split("/"); newGcsFormat += gcsArray[2] + "/" + gcsArray[3]; // The last and the penultimate indexes of the split gcsUri give the strings required to reformat the // gcsuri to a valid parameter for the createReferenceImage method. return newGcsFormat; } }
9237a56fcba4fa19d3cb314a6a6eccea1b7fb374
1,101
java
Java
src/main/java/befaster/solutions/FIZ/FizzBuzzSolution.java
DPNT-Sourcecode/FIZ-tsix01
6b902256e0b5d1497f9e18c8c7010bc8f08f49e9
[ "Apache-2.0" ]
null
null
null
src/main/java/befaster/solutions/FIZ/FizzBuzzSolution.java
DPNT-Sourcecode/FIZ-tsix01
6b902256e0b5d1497f9e18c8c7010bc8f08f49e9
[ "Apache-2.0" ]
null
null
null
src/main/java/befaster/solutions/FIZ/FizzBuzzSolution.java
DPNT-Sourcecode/FIZ-tsix01
6b902256e0b5d1497f9e18c8c7010bc8f08f49e9
[ "Apache-2.0" ]
null
null
null
25.604651
76
0.527702
998,145
package befaster.solutions.FIZ; public class FizzBuzzSolution { public String fizzBuzz(Integer number) { StringBuilder result = new StringBuilder(); if (isFizz(number)) { result.append("fizz").append(" "); } if (isBuzz(number)) { result.append("buzz").append(" "); } if (isDeluxe(number)) { if(number % 2 != 0) { result.append("fake "); } result.append("deluxe"); } if(result.length() == 0) { return String.valueOf(number); } return result.toString().trim(); } private boolean isFizz(Integer number) { return (number % 3 == 0 || String.valueOf(number).contains("3")); } private boolean isBuzz(Integer number) { return (number % 5 == 0 || String.valueOf(number).contains("5")); } private boolean isDeluxe(Integer number) { return ((number % 3 == 0 && String.valueOf(number).contains("3")) || (number % 5 == 0 && String.valueOf(number).contains("5"))); } }
9237a5e7606401c521c961fe1842254160fe3a59
746
java
Java
AppDevFrameworkProject/src/main/java/com/cit/eugene/service/business/MovieManager.java
eugenebell/Application_Development_Frameworks_Project
0da8450bafe843877b34b9f4e7835359489513bf
[ "MIT" ]
null
null
null
AppDevFrameworkProject/src/main/java/com/cit/eugene/service/business/MovieManager.java
eugenebell/Application_Development_Frameworks_Project
0da8450bafe843877b34b9f4e7835359489513bf
[ "MIT" ]
null
null
null
AppDevFrameworkProject/src/main/java/com/cit/eugene/service/business/MovieManager.java
eugenebell/Application_Development_Frameworks_Project
0da8450bafe843877b34b9f4e7835359489513bf
[ "MIT" ]
null
null
null
19.128205
62
0.642091
998,146
package com.cit.eugene.service.business; import java.util.List; import com.cit.eugene.model.Movie; /** * Class is for the Management of Movies. * * @author Eugene */ public interface MovieManager { /** * Returns the list of Movies. * * @return List<Movie> */ public List<Movie> getMovieListing(); /** * Returns the list of Movies that match the selected genre. * * @param genreID Long * @return List<Movie> */ public List<Movie> getMovieListingByGenreID(Long genreID); /** * Returns the movie based on movieID and user name. * * @param username String * @param movieID Long * @return Movie */ public Movie getMovieByID(String username, Long movieID); }
9237a744ae58b70e7470b5c4cb1816a86dd91db9
8,153
java
Java
nels-portal/src/main/java/no/nels/portal/pages/idp/NeLSIdpUserBean.java
elixir-no-nels/nels-core
b7988f3b85456c7c55064a20ca7d832083a3c51d
[ "Apache-2.0" ]
3
2018-05-16T10:44:38.000Z
2020-12-24T10:53:41.000Z
nels-portal/src/main/java/no/nels/portal/pages/idp/NeLSIdpUserBean.java
elixir-no-nels/nels-core
b7988f3b85456c7c55064a20ca7d832083a3c51d
[ "Apache-2.0" ]
13
2021-12-10T00:51:17.000Z
2022-02-16T00:55:20.000Z
nels-portal/src/main/java/no/nels/portal/pages/idp/NeLSIdpUserBean.java
elixir-no-nels/nels-core
b7988f3b85456c7c55064a20ca7d832083a3c51d
[ "Apache-2.0" ]
null
null
null
37.228311
231
0.598798
998,147
package no.nels.portal.pages.idp; import no.nels.commons.abstracts.ASystemUser; import no.nels.commons.model.IDPUser; import no.nels.commons.model.idps.NeLSIdp; import no.nels.commons.model.systemusers.AdministratorUser; import no.nels.commons.model.systemusers.HelpDeskUser; import no.nels.commons.utilities.StringUtilities; import no.nels.idp.core.facades.IdpFacade; import no.nels.idp.core.model.db.NeLSIdpUser; import no.nels.portal.Config; import no.nels.portal.abstracts.ASecureBean; import no.nels.portal.facades.*; import no.nels.portal.model.enumerations.ManagedBeanNames; import no.nels.portal.model.enumerations.PageModes; import no.nels.portal.model.enumerations.URLParameterNames; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; import java.util.ArrayList; @ManagedBean(name = ManagedBeanNames.pages_idp_nels_idpuser_edit) @ViewScoped public class NeLSIdpUserBean extends ASecureBean { /*Caution: The bean assumes e-mail is used as username*/ private NeLSIdpUser idpUser; private String firstName, lastName, email, affiliation, initialPassword = StringUtilities.getRandomString(6); private boolean immediateNeLSProfileCreation = true; public boolean isImmediateNeLSProfileCreation() { return immediateNeLSProfileCreation; } public void setImmediateNeLSProfileCreation(boolean immediateNeLSProfileCreation) { this.immediateNeLSProfileCreation = immediateNeLSProfileCreation; } @Override public String getPageTitle() { if (!isPostback()) { secure(); this.registerRequestUrl(); if (this.getPageMode().equalsIgnoreCase(PageModes.Edit)) { this.idpUser = IdpFacade.getById(Long .valueOf((String) this .getUrlParameter(URLParameterNames.ID))); this.firstName = this.idpUser.getFirstName(); this.lastName = this.idpUser.getLastName(); this.email = this.idpUser.getEmail(); this.affiliation = this.idpUser.getAffiliation(); } } return "NeLS Idp User"; } @Override public void secure() { ArrayList<ASystemUser> userTypes = new ArrayList<ASystemUser>() { { add(new AdministratorUser()); add(new HelpDeskUser()); } }; SecurityFacade.requireSystemUserType(userTypes); } public boolean validateInput() { boolean ret = true; if (email.equalsIgnoreCase("") || !StringUtilities.isValidEmailAddress(email)) { MessageFacade.AddError("invalid e-mail", "You have to provide a valid e-mail"); ret = false; } else { NeLSIdpUser usr = IdpFacade.getByEmail(email); if (usr != null) { if (this.getPageMode().equalsIgnoreCase(PageModes.New)) { MessageFacade.AddError("already used e-mail", "The email has already been used on another account."); ret = false; } else if (this.getPageMode().equalsIgnoreCase(PageModes.Edit) && usr.getId() != getIdpUser().getId()) { MessageFacade.AddError("already used e-mail", "The updated email has already been used on another account."); ret = false; } } else { usr = IdpFacade.getByUserName(email); if (usr != null) { if (this.getPageMode().equalsIgnoreCase(PageModes.New)) { MessageFacade.AddError("already used username", "The username has already been used on another account."); ret = false; } else if (this.getPageMode().equalsIgnoreCase(PageModes.Edit) && usr.getId() != getIdpUser().getId()) { MessageFacade.AddError("already used username", "The updated username has already been used on another account."); ret = false; } } } } if (firstName.equalsIgnoreCase("")) { MessageFacade.AddError("First name not provided", "You have to submit the First name"); ret = false; } if (lastName.equalsIgnoreCase("")) { MessageFacade.AddError("Last name not provided", "You have to submit the Last name"); ret = false; } if (affiliation.equalsIgnoreCase("")) { MessageFacade.AddError("affiliation not provided", "You have to provide the institution name or affiliation"); ret = false; } if (this.getPageMode().equalsIgnoreCase(PageModes.New) && initialPassword.equalsIgnoreCase("")) { MessageFacade.AddError("blank password", "You have to provide an initial password"); ret = false; } return ret; } public void cmdCancel_Click() { NavigationFacade.closePopup(); } public void cmdAdd_Click() { if (validateInput()) { NeLSIdpUser newIdpUser = IdpFacade.RegisterUser(email, initialPassword, firstName, lastName, email, affiliation); if (newIdpUser != null) { MessageFacade.addInfo("New User created "); if(isImmediateNeLSProfileCreation()) { SecurityFacade.createNeLSProfile(new IDPUser(new NeLSIdp(), newIdpUser.getUsername(), newIdpUser.getFirstName() + " " + newIdpUser.getLastName(), newIdpUser.getEmail(), newIdpUser.getAffiliation())); } //send e-mail String newUserEmailMessage = Config.getMailNewNeLSIdpUser(); newUserEmailMessage = newUserEmailMessage.replace("?fullName", firstName + " " + lastName).replace("?userName", email).replace("?tempPassword", initialPassword).replace("?webappUrl", Config.getApplicationRootURL()); try { MailFacade.sendMail(Config.getSenderEmail(), new String[]{email}, null, null, "Your NeLS Account Credentails", newUserEmailMessage, false); LoggingFacade.logDebugInfo("new user credentials sent"); } catch (Exception e) { MessageFacade.addInfo("Sending e-mail", e.getMessage()); e.printStackTrace(); } NavigationFacade.closePopup(); } else { MessageFacade.addInfo("Adding user failed", "Something went wrong. Contact the system administrator"); } } } public void cmdUpdate_Click() { if (validateInput()) { if(IdpFacade.UpdateUser(idpUser.getId(),email,firstName,lastName,email,affiliation)!= null) { MessageFacade.addInfo("Success ", "User details updated"); } else { MessageFacade.addFatal("Error saving user details"); } } } public NeLSIdpUser getIdpUser() { return idpUser; } public void setIdpUser(NeLSIdpUser idpUser) { this.idpUser = idpUser; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getAffiliation() { return affiliation; } public void setAffiliation(String affiliation) { this.affiliation = affiliation; } public String getInitialPassword() { return initialPassword; } public void setInitialPassword(String initialPassword) { this.initialPassword = initialPassword; } }
9237a82fb85a2d238da782c514536b03d01a255a
3,165
java
Java
sofa-boot-project/sofa-boot-core/rpc-sofa-boot/src/test/java/com/alipay/sofa/rpc/boot/test/misc/XsdTimeoutTest.java
HTGP02/sofa-boot
798460a5732660abfb4101dfdfe92dc439742fb5
[ "Apache-2.0" ]
1
2020-10-14T08:37:02.000Z
2020-10-14T08:37:02.000Z
sofa-boot-project/sofa-boot-core/rpc-sofa-boot/src/test/java/com/alipay/sofa/rpc/boot/test/misc/XsdTimeoutTest.java
HTGP02/sofa-boot
798460a5732660abfb4101dfdfe92dc439742fb5
[ "Apache-2.0" ]
4
2020-12-02T18:44:50.000Z
2021-12-14T21:52:59.000Z
sofa-boot-project/sofa-boot-core/rpc-sofa-boot/src/test/java/com/alipay/sofa/rpc/boot/test/misc/XsdTimeoutTest.java
HTGP02/sofa-boot
798460a5732660abfb4101dfdfe92dc439742fb5
[ "Apache-2.0" ]
null
null
null
42.824324
101
0.754497
998,148
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alipay.sofa.rpc.boot.test.misc; import com.alipay.sofa.rpc.boot.runtime.binding.RpcBinding; import com.alipay.sofa.rpc.boot.runtime.binding.RpcBindingType; import com.alipay.sofa.runtime.api.component.ComponentName; import com.alipay.sofa.runtime.service.component.ReferenceComponent; import com.alipay.sofa.runtime.service.component.ServiceComponent; import com.alipay.sofa.runtime.spi.component.SofaRuntimeContext; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.ImportResource; import org.springframework.test.context.junit4.SpringRunner; /** * @author <a href="mailto:anpch@example.com">guaner.zzx</a> * Created on 2019/12/18 */ @SpringBootApplication @RunWith(SpringRunner.class) @SpringBootTest(classes = XsdTimeoutTest.class, properties = { "timeout=10000" }) @ImportResource("/spring/service_reference.xml") public class XsdTimeoutTest { @Autowired WhateverInterface whatever; @Autowired SofaRuntimeContext sofaRuntimeContext; @Test public void testService() { Assert.assertEquals(whatever.say(), "whatever"); } @Test public void testServiceTimeout() { ServiceComponent component = (ServiceComponent) sofaRuntimeContext.getComponentManager() .getComponentInfo( new ComponentName(ServiceComponent.SERVICE_COMPONENT_TYPE, WhateverInterface.class .getName())); RpcBinding binding = (RpcBinding) component.getService().getBinding( RpcBindingType.BOLT_BINDING_TYPE); Assert.assertEquals((long) binding.getRpcBindingParam().getTimeout(), 10000); } @Test public void testReferenceTimeout() { ReferenceComponent component = (ReferenceComponent) (sofaRuntimeContext .getComponentManager() .getComponentInfosByType(ReferenceComponent.REFERENCE_COMPONENT_TYPE).iterator().next()); RpcBinding binding = (RpcBinding) component.getReference().getBinding( RpcBindingType.BOLT_BINDING_TYPE); Assert.assertEquals((long) binding.getRpcBindingParam().getTimeout(), 10000); } }
9237a8d226a8a8419c76cfd7a3d92b08f5a137c3
1,867
java
Java
subprojects/org.compiere.model/src/java/org/compiere/model/Server.java
iDempiere-micro/idempiere-micro
a5c09f37d68950b458cf23ce4a2c50e98c50ea2c
[ "MIT" ]
null
null
null
subprojects/org.compiere.model/src/java/org/compiere/model/Server.java
iDempiere-micro/idempiere-micro
a5c09f37d68950b458cf23ce4a2c50e98c50ea2c
[ "MIT" ]
1
2018-07-09T12:41:14.000Z
2018-07-09T13:13:06.000Z
subprojects/org.compiere.model/src/java/org/compiere/model/Server.java
iDempiere-micro/idempiere-micro
a5c09f37d68950b458cf23ce4a2c50e98c50ea2c
[ "MIT" ]
null
null
null
27.865672
99
0.667916
998,149
package org.compiere.model; import java.util.Properties; /** * Interface for adempiere/Server. */ public interface Server { /** * Post Immediate * @param ctx Client Context * @param AD_Client_ID Client ID of Document * @param AD_Table_ID Table ID of Document * @param Record_ID Record ID of this document * @param force force posting * @return null, if success or error message */ public String postImmediate( Properties ctx, int AD_Client_ID, int AD_Table_ID, int Record_ID, boolean force); /** * Process Remote * @param ctx Context * @param pi Process Info * @return resulting Process Info */ public IProcessInfo process( Properties ctx, IProcessInfo pi ); /** * Run Workflow (and wait) on Server * @param ctx Context * @param pi Process Info * @param AD_Workflow_ID id * @return process info */ public IProcessInfo workflow( Properties ctx, IProcessInfo pi, int AD_Workflow_ID ); /** * Send EMail from Server * @param ctx Context * @param email * @return message return from email server */ public String sendEMail( Properties ctx, IEMail email); /** * Execute task on server * @param ctx Context * @param AD_Task_ID task * @return execution trace */ public String executeTask( Properties ctx, int AD_Task_ID ); /** * Cash Reset * @param ctx Context * @param tableName table name * @param Record_ID record or 0 for all * @return number of records reset */ public int cacheReset( Properties ctx, String tableName,int Record_ID ); /** * Execute db proces on server * @param ctx Context * @param processInfo * @param procedureName * @return ProcessInfo */ public IProcessInfo dbProcess( Properties ctx, IProcessInfo processInfo, String procedureName ); }
9237a92c34cc85de66b93845b6961ddfb3588088
1,038
java
Java
duc.uscript.parent/duc.uscript.execution.interpreter/k3-gen/duc/uscript/execution/interpreter/statement/AStatementAspectStatementAspectContext.java
lmouline/aintea
687eae73d25a99c5de2b0be02c90ebd0ad4a1262
[ "Apache-2.0" ]
1
2019-02-27T15:15:20.000Z
2019-02-27T15:15:20.000Z
duc.uscript.parent/duc.uscript.execution.interpreter/k3-gen/duc/uscript/execution/interpreter/statement/AStatementAspectStatementAspectContext.java
lmouline/uscript
687eae73d25a99c5de2b0be02c90ebd0ad4a1262
[ "Apache-2.0" ]
5
2019-02-08T13:30:30.000Z
2019-02-22T14:46:31.000Z
duc.uscript.parent/duc.uscript.execution.interpreter/k3-gen/duc/uscript/execution/interpreter/statement/AStatementAspectStatementAspectContext.java
lmouline/uscript
687eae73d25a99c5de2b0be02c90ebd0ad4a1262
[ "Apache-2.0" ]
null
null
null
45.130435
220
0.821773
998,150
package duc.uscript.execution.interpreter.statement; import duc.uscript.execution.interpreter.statement.AStatementAspectStatementAspectProperties; import duc.uscript.uScript.Statement; import java.util.Map; @SuppressWarnings("all") public class AStatementAspectStatementAspectContext { public static final AStatementAspectStatementAspectContext INSTANCE = new AStatementAspectStatementAspectContext(); public static AStatementAspectStatementAspectProperties getSelf(final Statement _self) { if (!INSTANCE.map.containsKey(_self)) INSTANCE.map.put(_self, new duc.uscript.execution.interpreter.statement.AStatementAspectStatementAspectProperties()); return INSTANCE.map.get(_self); } private Map<Statement, AStatementAspectStatementAspectProperties> map = new java.util.WeakHashMap<duc.uscript.uScript.Statement, duc.uscript.execution.interpreter.statement.AStatementAspectStatementAspectProperties>(); public Map<Statement, AStatementAspectStatementAspectProperties> getMap() { return map; } }
9237a96e9a1204311d49f9b37129859321bc869f
10,591
java
Java
geoportal/src/com/esri/gpt/framework/context/ApplicationConfiguration.java
tomkralidis/geoportal-server
9844d7caa1f0b9fdf2b76b336ca7aa213fbd59ee
[ "Apache-2.0" ]
176
2015-01-08T19:00:40.000Z
2022-03-23T10:17:30.000Z
geoportal/src/com/esri/gpt/framework/context/ApplicationConfiguration.java
tomkralidis/geoportal-server
9844d7caa1f0b9fdf2b76b336ca7aa213fbd59ee
[ "Apache-2.0" ]
224
2015-01-05T16:17:21.000Z
2021-08-30T22:39:28.000Z
geoportal/src/com/esri/gpt/framework/context/ApplicationConfiguration.java
tomkralidis/geoportal-server
9844d7caa1f0b9fdf2b76b336ca7aa213fbd59ee
[ "Apache-2.0" ]
88
2015-01-15T11:47:05.000Z
2022-03-10T02:06:46.000Z
33.837061
120
0.753187
998,151
/* See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * Esri Inc. licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.esri.gpt.framework.context; import com.esri.gpt.catalog.context.CatalogConfiguration; import com.esri.gpt.control.download.DownloadConfiguration; import com.esri.gpt.control.webharvest.engine.HarvesterConfiguration; import com.esri.gpt.control.webharvest.protocol.ProtocolFactories; import com.esri.gpt.framework.ArcGIS.InteractiveMap; import com.esri.gpt.framework.mail.MailConfiguration; import com.esri.gpt.framework.scheduler.ThreadSchedulerConfiguration; import com.esri.gpt.framework.security.identity.IdentityAdapter; import com.esri.gpt.framework.security.identity.IdentityConfiguration; import com.esri.gpt.framework.security.identity.UnconfiguredIdentityAdapter; import com.esri.gpt.framework.sql.DatabaseReferences; import com.esri.gpt.framework.util.LogUtil; import com.esri.gpt.framework.util.Val; import com.esri.gpt.framework.security.metadata.MetadataAccessPolicy; import java.util.logging.Level; /** * Represents the primary configuration for an application. * <p> * This configuration is scoped at the application level. Writes * should occur during initial loading only. Writing during normal request * execution will affect all threads, it's not safe. */ public class ApplicationConfiguration extends Configuration { // class variables ============================================================= // instance variables ========================================================== private CatalogConfiguration _catalogConfiguration; private DatabaseReferences _databaseReferences; private IdentityConfiguration _identityConfiguration; private InteractiveMap _interactiveMap = new InteractiveMap(); private MailConfiguration _mailConfiguration = new MailConfiguration(); private ThreadSchedulerConfiguration _threadSchedulerConfiguration; private DownloadConfiguration _downloadDataConfiguration; private MetadataAccessPolicy _metadataAccessPolicy; private String _version = ""; private HarvesterConfiguration _harvesterConfiguration = new HarvesterConfiguration(); private ProtocolFactories _protocolFactories = new ProtocolFactories(); // constructors ================================================================ /** Default constructor. */ public ApplicationConfiguration() { super(); setDatabaseReferences(new DatabaseReferences()); setIdentityConfiguration(new IdentityConfiguration()); setCatalogConfiguration(new CatalogConfiguration()); setMailConfiguration(new MailConfiguration()); setThreadSchedulerConfiguration(new ThreadSchedulerConfiguration()); setDownloadDataConfiguration(new DownloadConfiguration()); setMetadataAccessPolicy(new MetadataAccessPolicy()); } // properties ================================================================== /** * Gets the metadata access level configuration associated with this application. * @return the catalog configuration */ public MetadataAccessPolicy getMetadataAccessPolicy() { return _metadataAccessPolicy; } /** * Sets the metadata access level configuration associated with this application. * @param metadataAccessPolicy access policy */ public void setMetadataAccessPolicy( MetadataAccessPolicy metadataAccessPolicy) { this._metadataAccessPolicy = metadataAccessPolicy; } /** * Gets the metadata catalog configuration associated with this application. * @return the catalog configuration */ public CatalogConfiguration getCatalogConfiguration() { return _catalogConfiguration; } /** * Sets the metadata catalog configuration associated with this application. * @param configuration the catalog configuration */ private void setCatalogConfiguration(CatalogConfiguration configuration) { _catalogConfiguration = configuration; if (_catalogConfiguration == null) { _catalogConfiguration = new CatalogConfiguration(); } } /** * Gets the database references associated with this application. * @return the database references */ public DatabaseReferences getDatabaseReferences() { return _databaseReferences; } /** * Sets the database references associated with this application. * @param references the database references */ private void setDatabaseReferences(DatabaseReferences references) { _databaseReferences = references; if (_databaseReferences == null) { _databaseReferences = new DatabaseReferences(); } } /** * Gets the identity configuration associated with this application. * @return the identity configuration */ public IdentityConfiguration getIdentityConfiguration() { return _identityConfiguration; } /** * Sets the identity configuration associated with this application. * @param configuration the identity configuration */ private void setIdentityConfiguration(IdentityConfiguration configuration) { _identityConfiguration = configuration; if (_identityConfiguration == null) { _identityConfiguration = new IdentityConfiguration(); } } /** * Gets the interactive map configuration (for ArcGIS Server Javascript API). * @return the interactive map configuration */ public InteractiveMap getInteractiveMap() { return _interactiveMap; } /** * Gets the mail configuration associated with this application. * @return the mail configuration */ public MailConfiguration getMailConfiguration() { return _mailConfiguration; } /** * Sets the mail configuration associated with this application. * @param configuration the mail configuration */ private void setMailConfiguration(MailConfiguration configuration) { _mailConfiguration = configuration; if (_mailConfiguration == null) { _mailConfiguration = new MailConfiguration(); } } /** * Gets thread scheduler configuration. * @return thread scheduler configuration */ public ThreadSchedulerConfiguration getThreadSchedulerConfiguration() { return _threadSchedulerConfiguration; } /** * Sets thread scheduler configuration. * @param configuration thread scheduler configuration */ private void setThreadSchedulerConfiguration( ThreadSchedulerConfiguration configuration) { _threadSchedulerConfiguration = configuration; if (_threadSchedulerConfiguration == null) { _threadSchedulerConfiguration = new ThreadSchedulerConfiguration(); } } /** * Gets data download configuration. * @return data download configuration */ public DownloadConfiguration getDownloadDataConfiguration() { return _downloadDataConfiguration; } /** * Sets data download configuration. * @param downloadConfiguration data download configuration */ public void setDownloadDataConfiguration( DownloadConfiguration downloadConfiguration) { _downloadDataConfiguration = downloadConfiguration != null ? downloadConfiguration : new DownloadConfiguration(); } /** * Gets harvester configuration. * @return harvester configuration */ public HarvesterConfiguration getHarvesterConfiguration() { return this._harvesterConfiguration; } /** * Sets harvester configuration. * @param harvesterConfiguration harvester configuration */ public void setHarvesterConfiguration(HarvesterConfiguration harvesterConfiguration) { this._harvesterConfiguration = harvesterConfiguration != null ? harvesterConfiguration : new HarvesterConfiguration(); } /** * Gets protocol factories. * @return protocol factories */ public ProtocolFactories getProtocolFactories() { return _protocolFactories; } /** * Sets protocol factories. * @param protocolFactories protocol factories */ public void setProtocolFactories(ProtocolFactories protocolFactories) { this._protocolFactories = protocolFactories!=null? protocolFactories: new ProtocolFactories(); } /** * Gets the version. * @return the version */ public String getVersion() { return _version; } /** * Sets the version. * @param version the version */ protected void setVersion(String version) { _version = Val.chkStr(version); } // methods ===================================================================== /** * Instantiates a new Identity adapter. * @return the new identity adapter */ protected IdentityAdapter newIdentityAdapter() { IdentityAdapter identityAdapter = null; try { String adapterClassName = getIdentityConfiguration().getAdapterClassName(); if (adapterClassName.length() == 0) { throw new ConfigurationException( "The identity adapter class name was not properly configured."); } else { Class<?> clsAdapter = Class.forName(adapterClassName); Object objAdapter = clsAdapter.newInstance(); if (objAdapter instanceof IdentityAdapter) { identityAdapter = (IdentityAdapter) objAdapter; identityAdapter.setApplicationConfiguration(this); } else { throw new ConfigurationException( "The identity adapter class name is invalid: " + adapterClassName); } } } catch (Throwable t) { identityAdapter = new UnconfiguredIdentityAdapter(); identityAdapter.setApplicationConfiguration(this); LogUtil.getLogger().log(Level.SEVERE, "Unable to create a new IdenityAdapter.", t); } return identityAdapter; } /** * Returns a string representation of this object. * @return the string */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getName()).append(" (\n"); sb.append(" version=\"").append(getVersion()).append("\"\n"); sb.append(getDatabaseReferences()).append("\n"); sb.append(getMailConfiguration()).append("\n"); sb.append(getInteractiveMap()).append("\n"); sb.append(getCatalogConfiguration()).append("\n"); sb.append(getIdentityConfiguration()).append("\n"); sb.append(getThreadSchedulerConfiguration()).append("\n"); sb.append(getDownloadDataConfiguration()).append("\n"); sb.append(getMetadataAccessPolicy()).append("\n"); sb.append(getHarvesterConfiguration()).append("\n"); sb.append(getProtocolFactories()).append("\n"); sb.append(") ===== end ").append(getClass().getName()); return sb.toString(); } }
9237a9f39c716f6e900c1950af03057718100312
919
java
Java
src/main/java/com/greboreda/poker/hand/rank/royalflush/RoyalFlushCalculator.java
greboreda/poker
eb99a83ea272ba4c9afbdf39b89e9759e6f9d50c
[ "WTFPL" ]
null
null
null
src/main/java/com/greboreda/poker/hand/rank/royalflush/RoyalFlushCalculator.java
greboreda/poker
eb99a83ea272ba4c9afbdf39b89e9759e6f9d50c
[ "WTFPL" ]
null
null
null
src/main/java/com/greboreda/poker/hand/rank/royalflush/RoyalFlushCalculator.java
greboreda/poker
eb99a83ea272ba4c9afbdf39b89e9759e6f9d50c
[ "WTFPL" ]
null
null
null
26.257143
103
0.773667
998,152
package com.greboreda.poker.hand.rank.royalflush; import com.greboreda.poker.card.Value; import com.greboreda.poker.hand.Hand; import com.greboreda.poker.hand.rank.RankCalculator; import org.apache.commons.lang3.Validate; import java.util.EnumSet; import java.util.Optional; public class RoyalFlushCalculator implements RankCalculator<RoyalFlush> { public static final EnumSet<Value> mandatoryRoyalFlushValues = EnumSet.of( Value.ACE, Value.KING, Value.QUEEN, Value.JACK, Value.TEN ); @Override public Optional<RoyalFlush> calculateRank(Hand hand) { Validate.notNull(hand); final boolean containsMandatoryValues = hand.getCardsValues().containsAll(mandatoryRoyalFlushValues); final boolean allCardsHaveSameSuit = hand.getDistinctSuits().size() == 1; if (!containsMandatoryValues || !allCardsHaveSameSuit) { return Optional.empty(); } return Optional.of(new RoyalFlush()); } }
9237aa79c5f47ac2c91e42b543627a61198e6ad3
363
java
Java
web/src/main/java/edu/softserve/zoo/annotation/DocsParamDescription.java
skyfenko/Kv-014
d09755194a16d6dd1c9db57a475163ac93b66f9d
[ "MIT" ]
3
2016-05-24T11:13:40.000Z
2016-06-26T21:54:09.000Z
web/src/main/java/edu/softserve/zoo/annotation/DocsParamDescription.java
skyfenko/Kv-014
d09755194a16d6dd1c9db57a475163ac93b66f9d
[ "MIT" ]
55
2016-04-14T10:36:35.000Z
2016-07-05T11:53:02.000Z
web/src/main/java/edu/softserve/zoo/annotation/DocsParamDescription.java
skyfenko/Kv-014
d09755194a16d6dd1c9db57a475163ac93b66f9d
[ "MIT" ]
7
2016-06-01T22:30:49.000Z
2020-11-19T10:18:56.000Z
22.6875
44
0.796143
998,153
package edu.softserve.zoo.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * @author Taras Zubrei */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.PARAMETER) public @interface DocsParamDescription { String value(); }
9237aa8f1075853299d027294f43c3b8bea561f8
2,159
java
Java
src/main/java/com/orasi/utils/AlertHandler.java
taxibattman/Demo
dd35a8ea6dff6383751fa9649f35eab445a73956
[ "BSD-4-Clause" ]
null
null
null
src/main/java/com/orasi/utils/AlertHandler.java
taxibattman/Demo
dd35a8ea6dff6383751fa9649f35eab445a73956
[ "BSD-4-Clause" ]
null
null
null
src/main/java/com/orasi/utils/AlertHandler.java
taxibattman/Demo
dd35a8ea6dff6383751fa9649f35eab445a73956
[ "BSD-4-Clause" ]
null
null
null
32.712121
122
0.695229
998,154
package com.orasi.utils; import org.openqa.selenium.Alert; import org.openqa.selenium.WebDriver; import org.openqa.selenium.security.Credentials; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import com.orasi.exception.AutomationException; public class AlertHandler { public static boolean isAlertPresent(WebDriver driver, int timeout){ try{ WebDriverWait wait = new WebDriverWait(driver, timeout); wait.until(ExpectedConditions.alertIsPresent()); return true; } catch(Exception e){ return false; } } public static void handleAllAlerts(WebDriver driver, int timeout){ while (isAlertPresent(driver, timeout)){ alertHandler(driver); } } public static void handleAlert(WebDriver driver, int timeout){ if(isAlertPresent(driver, timeout)) alertHandler(driver); } public static void handleAlert(WebDriver driver, int timeout, String inputText){ if(isAlertPresent(driver, timeout)) alertHandler(driver, inputText); } public static void handleAlert(WebDriver driver, int timeout, Credentials user){ if(isAlertPresent(driver, timeout)) alertHandler(driver, user); } private static void alertHandler(WebDriver driver){ try { Alert alert = driver.switchTo().alert(); TestReporter.log("Closing alert popup with text [ <i>" + alert.getText() +" </i> ]<br />"); alert.accept(); } catch (Exception throwAway) {} } private static void alertHandler(WebDriver driver, String inputText){ try { Alert alert = driver.switchTo().alert(); TestReporter.log("Sending text [ <i>" + inputText +" </i> ] to Alert popup<br />"); alert.sendKeys(inputText); alertHandler(driver); } catch (Exception throwAway) {} } private static void alertHandler(WebDriver driver, Credentials user){ try { Alert alert = driver.switchTo().alert(); TestReporter.log("Closing alert popup with text [ <i>" + alert.getText() +" </i> ] with authentication user <br />"); alert.authenticateUsing(user); } catch (Exception throwAway) {} } }
9237ab6ef23c98982c9d21e7fd416baeb88b222c
135
java
Java
src/main/java/com/baidu/hive/schueuler/fuse/QueryOutputs.java
houzhizhen/hive-utils
29b200c0848bd95ff3cb1d14b0e897a36035c37e
[ "Apache-2.0" ]
null
null
null
src/main/java/com/baidu/hive/schueuler/fuse/QueryOutputs.java
houzhizhen/hive-utils
29b200c0848bd95ff3cb1d14b0e897a36035c37e
[ "Apache-2.0" ]
null
null
null
src/main/java/com/baidu/hive/schueuler/fuse/QueryOutputs.java
houzhizhen/hive-utils
29b200c0848bd95ff3cb1d14b0e897a36035c37e
[ "Apache-2.0" ]
null
null
null
15
39
0.762963
998,155
package com.baidu.hive.schueuler.fuse; import java.util.List; public class QueryOutputs { private List<QueryData> outputList; }
9237ab8f069e21f9e34972148169121aa6152877
782
java
Java
examples/appium/src/test/java/org/fluentlenium/example/appium/ios/IosUITestDemo.java
wenceslas/FluentLenium
4b64c91563a350f493f50bdfce3e2aca2fb8f9a6
[ "Apache-2.0" ]
577
2015-01-01T21:13:14.000Z
2022-03-25T12:30:56.000Z
examples/appium/src/test/java/org/fluentlenium/example/appium/ios/IosUITestDemo.java
wenceslas/FluentLenium
4b64c91563a350f493f50bdfce3e2aca2fb8f9a6
[ "Apache-2.0" ]
1,167
2015-01-20T01:19:12.000Z
2022-03-24T20:18:15.000Z
examples/appium/src/test/java/org/fluentlenium/example/appium/ios/IosUITestDemo.java
wenceslas/FluentLenium
4b64c91563a350f493f50bdfce3e2aca2fb8f9a6
[ "Apache-2.0" ]
205
2015-01-25T02:37:42.000Z
2022-02-20T12:12:02.000Z
25.225806
57
0.677749
998,156
package org.fluentlenium.example.appium.ios; import org.fluentlenium.core.annotation.Page; import org.fluentlenium.example.appium.ExampleFluentTest; import org.fluentlenium.example.appium.app.ios.HomePage; import org.junit.Test; public class IosUITestDemo extends ExampleFluentTest { @Page private HomePage homePage; @Test public void shouldCorrectlySwitchView() { homePage.clickAboutLink().verifyIfIsLoaded(); } @Test public void shouldCorrectlyAddNote() { String noteName = "Sample Note"; String noteDescription = "SampleNoteDescription"; homePage .clickAddButton() .addName(noteName, noteDescription) .clickAboutLink() .verifyIfIsLoaded(); } }
9237ad424e9d6679503a8dd02a2f8cb0549eb4fb
329
java
Java
pinpoint185demo/service-b/src/main/java/com/example/serviceb/ServiceBApplication.java
targerr/blog_demos
7a6e156802009c1773f74b34e04d0eed7f20f4cc
[ "Apache-2.0" ]
1,962
2017-05-11T12:59:45.000Z
2022-03-31T07:03:55.000Z
pinpoint185demo/service-b/src/main/java/com/example/serviceb/ServiceBApplication.java
targerr/blog_demos
7a6e156802009c1773f74b34e04d0eed7f20f4cc
[ "Apache-2.0" ]
22
2019-06-15T14:54:14.000Z
2022-03-31T19:51:18.000Z
pinpoint185demo/service-b/src/main/java/com/example/serviceb/ServiceBApplication.java
targerr/blog_demos
7a6e156802009c1773f74b34e04d0eed7f20f4cc
[ "Apache-2.0" ]
1,068
2017-07-05T02:04:46.000Z
2022-03-29T03:42:22.000Z
23.5
68
0.793313
998,157
package com.example.serviceb; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class ServiceBApplication { public static void main(String[] args) { SpringApplication.run(ServiceBApplication.class, args); } }